Skip to main content

visloc_localization/
map_merge.rs

1//! Merging maps of one place built in separate sessions.
2//!
3//! A map built by VIO-based SLAM lives in its session's gravity-aligned
4//! world, so two sessions' maps of the same place differ by a yaw about the
5//! vertical and a translation (four degrees of freedom), plus each session's
6//! own drift. [`register_map`] finds that transform from the two maps alone:
7//!
8//! 1. Every keyframe of the other map becomes a query: its landmark
9//!    observations are the keypoints and those landmarks' descriptors the
10//!    query descriptors. It is localized in the base map like a camera image
11//!    (Hamming matching against every base landmark, P3P RANSAC, at least
12//!    `min_inliers` inliers), which places the keyframe in the base map and
13//!    so implies one base-from-other transform.
14//! 2. The transform that most localized keyframes agree with wins (camera
15//!    centres within `agreement_m`, yaw within `agreement_yaw_deg`). It is
16//!    refitted to the agreeing keyframes (circular mean yaw, then the mean
17//!    translation of their camera centres) until that set settles. Fewer
18//!    than `min_keyframes` agreeing keyframes fail the registration, so one
19//!    wrong localization cannot place a map.
20//!
21//! A keyframe has fewer keypoints than a camera image (only those that
22//! became landmarks), so `min_inliers` defaults to 15 rather than the
23//! localizer's 30: the agreement of several keyframes, not each one's
24//! inlier count, is what rules out wrong poses. The fit uses the camera
25//! centres rather than the matched landmarks' 3D positions, which in the
26//! other map are only as good as its triangulation.
27//!
28//! [`merge_maps`] then moves the other map into the base frame and adds it:
29//! its keyframes and landmarks get new ids after the base map's, and each of
30//! its landmarks that lies within `fuse_radius_m` of a base landmark whose
31//! descriptor is within `fuse_max_hamming` bits is fused into that base
32//! landmark (one to one, closest descriptors first): its observations move
33//! over, and the base position and descriptor are kept. Without fusion, a
34//! place both sessions saw would hold two landmarks with nearly the same
35//! descriptor for each point, and the ratio test of matching would reject
36//! most matches there.
37
38use std::collections::HashMap;
39
40use nalgebra::{Point2, Vector3};
41use visloc_core::geometry::{Pose, SE3};
42use visloc_core::types::{
43    Camera, CameraId, Keyframe, Landmark, LandmarkDescriptorStore, LandmarkId, Observation,
44    VisualMap,
45};
46use visloc_vision::matching::HammingMatcher;
47use visloc_vision::pnp::{GaussNewtonPoseRefiner, P3PGrunert};
48use visloc_vision::ransac::PnPRansac;
49
50use crate::odom_correction::{wrap_angle, yaw_of, Offset};
51use crate::{
52    AllLandmarksSelector, BinaryLandmarkIndex, BinaryMatchGates, LocalizationConfig,
53    LocalizationPipeline,
54};
55
56/// Settings of [`register_map`] and [`merge_maps`].
57#[derive(Debug, Clone, PartialEq)]
58pub struct MapMergeConfig {
59    /// Hamming gates of keyframe-to-map matching.
60    pub gates: BinaryMatchGates,
61    /// Inliers a keyframe needs to count as localized in the base map.
62    pub min_inliers: usize,
63    pub ransac_iterations: usize,
64    pub reprojection_px: f64,
65    /// Localized keyframes that must agree on the transform.
66    pub min_keyframes: usize,
67    /// Position tolerance, in metres at the keyframes' camera centres, for
68    /// localized keyframes to agree with a transform.
69    pub agreement_m: f64,
70    /// Yaw tolerance, in degrees, for localized keyframes to agree with a
71    /// transform.
72    pub agreement_yaw_deg: f64,
73    /// A landmark of the other map fuses into a base landmark within this
74    /// distance (after the transform)...
75    pub fuse_radius_m: f64,
76    /// ...whose descriptor differs from its own by at most this many bits.
77    pub fuse_max_hamming: u32,
78    /// Threads localizing the other map's keyframes.
79    pub threads: usize,
80}
81
82impl Default for MapMergeConfig {
83    /// The match gates and PnP settings of `visloc_map_localize_node`; see
84    /// the module documentation for `min_inliers`.
85    fn default() -> Self {
86        Self {
87            gates: BinaryMatchGates {
88                max_distance: 70,
89                ratio: Some(0.8),
90            },
91            min_inliers: 15,
92            ransac_iterations: 1000,
93            reprojection_px: 3.0,
94            min_keyframes: 3,
95            agreement_m: 0.25,
96            agreement_yaw_deg: 2.0,
97            fuse_radius_m: 0.10,
98            fuse_max_hamming: 50,
99            threads: 1,
100        }
101    }
102}
103
104/// The transform found by [`register_map`] and how it was found.
105#[derive(Debug, Clone, PartialEq)]
106pub struct MapRegistration {
107    /// `p_base = base_from_other * p_other`: a yaw about z and a translation.
108    pub base_from_other: SE3,
109    /// Keyframes of the other map with a pose.
110    pub keyframes: usize,
111    /// Of those, keyframes localized in the base map.
112    pub localized_keyframes: usize,
113    /// Of those, keyframes agreeing with the transform.
114    pub agreeing_keyframes: usize,
115    /// Root mean square distance between the agreeing keyframes' camera
116    /// centres in the base map and where the transform puts them.
117    pub keyframe_rms_m: f64,
118}
119
120/// Result of [`merge_maps`].
121#[derive(Debug, Clone)]
122pub struct MergedMap {
123    pub map: VisualMap,
124    pub descriptors: LandmarkDescriptorStore,
125    /// Merged keyframe id of each keyframe of the other map.
126    pub keyframe_ids: HashMap<u64, u64>,
127    /// Merged landmark id of each landmark of the other map; a base
128    /// landmark's id when it was fused.
129    pub landmark_ids: HashMap<LandmarkId, LandmarkId>,
130    /// Landmarks of the other map fused into base landmarks.
131    pub fused_landmarks: usize,
132    /// Merged camera id of each camera of the other map: the same id when
133    /// the base map has that camera, a new one when it has another camera
134    /// under that id (another calibration of the rig).
135    pub camera_ids: HashMap<CameraId, CameraId>,
136}
137
138#[derive(Debug, Clone, PartialEq)]
139pub enum MapMergeError {
140    /// The base map has no landmark with a descriptor.
141    EmptyBaseMap,
142    /// Fewer than `needed` localized keyframes agree on a transform.
143    TooFewKeyframes {
144        localized: usize,
145        agreeing: usize,
146        needed: usize,
147    },
148    /// A camera of the other map is missing from the base map or differs
149    /// from it. No longer returned by [`merge_maps`], which adds such a
150    /// camera under a new id ([`MergedMap::camera_ids`]); kept for callers
151    /// that match on it.
152    CameraMismatch { camera_id: CameraId },
153}
154
155impl std::fmt::Display for MapMergeError {
156    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157        match self {
158            Self::EmptyBaseMap => write!(f, "the base map has no landmark descriptors"),
159            Self::TooFewKeyframes {
160                localized,
161                agreeing,
162                needed,
163            } => write!(
164                f,
165                "{localized} keyframes localized in the base map and at most {agreeing} agree \
166                 on a transform; {needed} needed"
167            ),
168            Self::CameraMismatch { camera_id } => write!(
169                f,
170                "camera {camera_id} differs between the maps (or is missing from the base map)"
171            ),
172        }
173    }
174}
175
176impl std::error::Error for MapMergeError {}
177
178/// One keyframe of the other map localized in the base map.
179#[derive(Debug, Clone)]
180struct KeyframeFix {
181    other_centre: Vector3<f64>,
182    base_centre: Vector3<f64>,
183    /// Yaw of the base-from-other rotation this keyframe implies.
184    yaw: f64,
185}
186
187impl KeyframeFix {
188    /// Distance from the base-map camera centre to where `offset` puts the
189    /// other map's.
190    fn residual(&self, offset: &Offset) -> f64 {
191        (offset.rotation() * self.other_centre + offset.translation - self.base_centre).norm()
192    }
193
194    fn agrees(&self, offset: &Offset, config: &MapMergeConfig) -> bool {
195        self.residual(offset) <= config.agreement_m
196            && wrap_angle(self.yaw - offset.yaw).abs() <= config.agreement_yaw_deg.to_radians()
197    }
198
199    /// The transform this keyframe alone implies.
200    fn offset(&self) -> Offset {
201        fit_keyframes(&[self])
202    }
203}
204
205/// Circular mean yaw, then the mean translation under that yaw.
206fn fit_keyframes(fixes: &[&KeyframeFix]) -> Offset {
207    let (sin, cos) = fixes.iter().fold((0.0, 0.0), |(sin, cos), fix| {
208        (sin + fix.yaw.sin(), cos + fix.yaw.cos())
209    });
210    let mut offset = Offset {
211        yaw: sin.atan2(cos),
212        translation: Vector3::zeros(),
213    };
214    let rotation = offset.rotation();
215    offset.translation = fixes
216        .iter()
217        .map(|fix| fix.base_centre - rotation * fix.other_centre)
218        .sum::<Vector3<f64>>()
219        / fixes.len() as f64;
220    offset
221}
222
223type Pipeline = LocalizationPipeline<HammingMatcher, AllLandmarksSelector, PnPRansac<P3PGrunert>>;
224
225fn pnp_pipeline(config: &MapMergeConfig) -> Pipeline {
226    let ransac = PnPRansac {
227        pose_estimator: P3PGrunert,
228        pose_refiner: Some(GaussNewtonPoseRefiner::default()),
229        iterations: config.ransac_iterations,
230        reprojection_threshold: config.reprojection_px,
231        seed: 7,
232        early_stop_min_iterations: 0,
233        early_stop_inlier_ratio: None,
234        confidence: Some(0.999),
235        inlier_refits: 0,
236    };
237    LocalizationPipeline::with_pose_estimator(
238        HammingMatcher {
239            max_distance: config.gates.max_distance,
240            ratio: config.gates.ratio,
241        },
242        AllLandmarksSelector,
243        ransac,
244        LocalizationConfig {
245            ratio: config.gates.ratio,
246            ransac_iterations: config.ransac_iterations,
247            reprojection_threshold: config.reprojection_px,
248            min_inliers: config.min_inliers,
249            ..LocalizationConfig::default()
250        },
251    )
252}
253
254/// Localizes one keyframe of `other` in the base map behind `index`.
255fn localize_keyframe(
256    keyframe: &Keyframe,
257    other: &VisualMap,
258    other_descriptors: &LandmarkDescriptorStore,
259    index: &BinaryLandmarkIndex,
260    pipeline: &Pipeline,
261    config: &MapMergeConfig,
262) -> Option<KeyframeFix> {
263    let pose = keyframe.frame.pose.as_ref()?;
264    let camera = other.cameras.get(&keyframe.frame.camera_id)?;
265    let mut keypoints = Vec::<Point2<f64>>::new();
266    let mut descriptors = Vec::<&[f32]>::new();
267    for observation in &keyframe.observations {
268        if let (true, Some(descriptor)) = (
269            other.landmarks.contains_key(&observation.landmark_id),
270            other_descriptors.get(observation.landmark_id),
271        ) {
272            keypoints.push(observation.xy);
273            descriptors.push(descriptor);
274        }
275    }
276    if keypoints.len() < config.min_inliers {
277        return None;
278    }
279    let correspondences =
280        index.match_all(&keypoints, &index.pack_query(&descriptors), config.gates, 1);
281    let result = pipeline.localize_correspondences(camera, correspondences);
282    let base_pose = result.pose.as_ref().filter(|_| result.success)?;
283    let base_from_other = base_pose
284        .camera_to_world()
285        .compose(&pose.world_to_camera)
286        .rotation;
287    Some(KeyframeFix {
288        other_centre: pose.camera_center_world().coords,
289        base_centre: base_pose.camera_center_world().coords,
290        yaw: yaw_of(&base_from_other),
291    })
292}
293
294/// Finds the transform taking `other` into `base`; see the module
295/// documentation.
296pub fn register_map(
297    base: &VisualMap,
298    base_descriptors: &LandmarkDescriptorStore,
299    other: &VisualMap,
300    other_descriptors: &LandmarkDescriptorStore,
301    config: &MapMergeConfig,
302) -> Result<MapRegistration, MapMergeError> {
303    let index = BinaryLandmarkIndex::new(base, base_descriptors);
304    if index.is_empty() {
305        return Err(MapMergeError::EmptyBaseMap);
306    }
307    let pipeline = pnp_pipeline(config);
308    let mut keyframes = other
309        .keyframes
310        .values()
311        .filter(|keyframe| keyframe.frame.pose.is_some())
312        .collect::<Vec<_>>();
313    keyframes.sort_by_key(|keyframe| keyframe.frame.id);
314
315    let localize = |keyframes: &[&Keyframe]| {
316        keyframes
317            .iter()
318            .map(|keyframe| {
319                localize_keyframe(
320                    keyframe,
321                    other,
322                    other_descriptors,
323                    &index,
324                    &pipeline,
325                    config,
326                )
327            })
328            .collect::<Vec<_>>()
329    };
330    let threads = config.threads.clamp(1, keyframes.len().max(1));
331    let fixes = if threads == 1 {
332        localize(&keyframes)
333    } else {
334        let chunk = keyframes.len().div_ceil(threads);
335        std::thread::scope(|scope| {
336            let handles = keyframes
337                .chunks(chunk)
338                .map(|chunk| {
339                    let localize = &localize;
340                    scope.spawn(move || localize(chunk))
341                })
342                .collect::<Vec<_>>();
343            handles
344                .into_iter()
345                .flat_map(|handle| handle.join().expect("registration thread panicked"))
346                .collect()
347        })
348    };
349    let fixes = fixes.into_iter().flatten().collect::<Vec<_>>();
350
351    // The transform most keyframes agree with, refitted to them until the
352    // agreeing set settles.
353    let agreeing = |offset: &Offset| {
354        fixes
355            .iter()
356            .filter(|fix| fix.agrees(offset, config))
357            .collect::<Vec<_>>()
358    };
359    let mut best = Vec::new();
360    for fix in &fixes {
361        let candidate = agreeing(&fix.offset());
362        if candidate.len() > best.len() {
363            best = candidate;
364        }
365    }
366    for _ in 0..5 {
367        if best.is_empty() {
368            break;
369        }
370        let refitted = agreeing(&fit_keyframes(&best));
371        let settled = refitted.len() == best.len();
372        best = refitted;
373        if settled {
374            break;
375        }
376    }
377    if best.len() < config.min_keyframes.max(1) {
378        return Err(MapMergeError::TooFewKeyframes {
379            localized: fixes.len(),
380            agreeing: best.len(),
381            needed: config.min_keyframes.max(1),
382        });
383    }
384    let offset = fit_keyframes(&best);
385    let keyframe_rms_m = (best
386        .iter()
387        .map(|fix| fix.residual(&offset).powi(2))
388        .sum::<f64>()
389        / best.len() as f64)
390        .sqrt();
391
392    Ok(MapRegistration {
393        base_from_other: offset.se3(),
394        keyframes: keyframes.len(),
395        localized_keyframes: fixes.len(),
396        agreeing_keyframes: best.len(),
397        keyframe_rms_m,
398    })
399}
400
401fn same_camera(lhs: &Camera, rhs: &Camera) -> bool {
402    lhs.model == rhs.model
403        && (lhs.width, lhs.height) == (rhs.width, rhs.height)
404        && lhs.params.len() == rhs.params.len()
405        && lhs
406            .params
407            .iter()
408            .zip(&rhs.params)
409            .all(|(a, b)| (a - b).abs() <= 1e-9 * a.abs().max(b.abs()).max(1.0))
410}
411
412/// Number of differing bits of two unpacked binary descriptors (`>= 0.5` is
413/// a set bit); `u32::MAX` when their lengths differ.
414fn bit_distance(lhs: &[f32], rhs: &[f32]) -> u32 {
415    if lhs.len() != rhs.len() {
416        return u32::MAX;
417    }
418    lhs.iter()
419        .zip(rhs)
420        .filter(|(a, b)| (**a >= 0.5) != (**b >= 0.5))
421        .count() as u32
422}
423
424/// For each landmark of `other` (positions already in the base frame), the
425/// base landmark it fuses into: one to one, smallest descriptor distance
426/// first, then smallest position distance.
427fn fusion_targets(
428    base: &VisualMap,
429    base_descriptors: &LandmarkDescriptorStore,
430    other_positions: &[(LandmarkId, Vector3<f64>, &[f32])],
431    config: &MapMergeConfig,
432) -> HashMap<LandmarkId, LandmarkId> {
433    let radius = config.fuse_radius_m;
434    if radius <= 0.0 {
435        return HashMap::new();
436    }
437    let cell = |position: &Vector3<f64>| {
438        (
439            (position.x / radius).floor() as i64,
440            (position.y / radius).floor() as i64,
441            (position.z / radius).floor() as i64,
442        )
443    };
444    let mut grid = HashMap::<(i64, i64, i64), Vec<(LandmarkId, Vector3<f64>, &[f32])>>::new();
445    for landmark in base.landmarks.values() {
446        if let Some(descriptor) = base_descriptors.get(landmark.id) {
447            grid.entry(cell(&landmark.position.coords))
448                .or_default()
449                .push((landmark.id, landmark.position.coords, descriptor));
450        }
451    }
452    let mut candidates = Vec::new();
453    for &(other_id, position, descriptor) in other_positions {
454        let (x, y, z) = cell(&position);
455        for dx in -1..=1 {
456            for dy in -1..=1 {
457                for dz in -1..=1 {
458                    for (base_id, base_position, base_descriptor) in
459                        grid.get(&(x + dx, y + dy, z + dz)).into_iter().flatten()
460                    {
461                        let distance = (base_position - position).norm();
462                        let bits = bit_distance(descriptor, base_descriptor);
463                        if distance <= radius && bits <= config.fuse_max_hamming {
464                            candidates.push((bits, distance, other_id, *base_id));
465                        }
466                    }
467                }
468            }
469        }
470    }
471    candidates.sort_by(|a, b| {
472        (a.0, a.1, a.2, a.3)
473            .partial_cmp(&(b.0, b.1, b.2, b.3))
474            .expect("finite distances")
475    });
476    let mut targets = HashMap::new();
477    let mut taken = std::collections::HashSet::new();
478    for (_, _, other_id, base_id) in candidates {
479        if !targets.contains_key(&other_id) && taken.insert(base_id) {
480            targets.insert(other_id, base_id);
481        }
482    }
483    targets
484}
485
486/// Adds `other`, moved by `base_from_other`, to `base`; see the module
487/// documentation. Observation confidences, landmark covariances and stereo
488/// observations of `other` are carried over.
489pub fn merge_maps(
490    base: &VisualMap,
491    base_descriptors: &LandmarkDescriptorStore,
492    other: &VisualMap,
493    other_descriptors: &LandmarkDescriptorStore,
494    base_from_other: &SE3,
495    config: &MapMergeConfig,
496) -> Result<MergedMap, MapMergeError> {
497    // Cameras: the base map's when they are the same; another calibration
498    // (another day's of the rig) is added under a new id.
499    let mut map = base.clone();
500    let mut other_camera_ids = other.cameras.keys().copied().collect::<Vec<_>>();
501    other_camera_ids.sort_unstable();
502    let mut camera_ids = HashMap::with_capacity(other_camera_ids.len());
503    for camera_id in other_camera_ids {
504        let camera = &other.cameras[&camera_id];
505        let merged_id = match map.cameras.get(&camera_id) {
506            Some(existing) if same_camera(existing, camera) => camera_id,
507            None => camera_id,
508            Some(_) => map
509                .cameras
510                .iter()
511                .find(|(_, existing)| same_camera(existing, camera))
512                .map(|(&id, _)| id)
513                .unwrap_or_else(|| map.cameras.keys().max().map_or(1, |id| id + 1)),
514        };
515        map.cameras.entry(merged_id).or_insert_with(|| {
516            let mut added = camera.clone();
517            added.id = merged_id;
518            added
519        });
520        camera_ids.insert(camera_id, merged_id);
521    }
522
523    let mut other_keyframe_ids = other.keyframes.keys().copied().collect::<Vec<_>>();
524    other_keyframe_ids.sort_unstable();
525    let first_keyframe = base.keyframes.keys().max().map_or(1, |id| id + 1);
526    let keyframe_ids = other_keyframe_ids
527        .iter()
528        .enumerate()
529        .map(|(index, &id)| (id, first_keyframe + index as u64))
530        .collect::<HashMap<_, _>>();
531
532    let mut other_landmarks = other.landmarks.values().collect::<Vec<_>>();
533    other_landmarks.sort_by_key(|landmark| landmark.id);
534    let moved = other_landmarks
535        .iter()
536        .filter_map(|landmark| {
537            Some((
538                landmark.id,
539                base_from_other.transform_point(&landmark.position).coords,
540                other_descriptors.get(landmark.id)?,
541            ))
542        })
543        .collect::<Vec<_>>();
544    let fused = fusion_targets(base, base_descriptors, &moved, config);
545    let mut next_landmark = base.landmarks.keys().max().map_or(1, |id| id + 1);
546    let mut landmark_ids = HashMap::with_capacity(other_landmarks.len());
547    for landmark in &other_landmarks {
548        let id = fused.get(&landmark.id).copied().unwrap_or_else(|| {
549            next_landmark += 1;
550            next_landmark - 1
551        });
552        landmark_ids.insert(landmark.id, id);
553    }
554
555    let remap = |observation: &Observation| {
556        Some(Observation {
557            frame_id: *keyframe_ids.get(&observation.frame_id)?,
558            landmark_id: *landmark_ids.get(&observation.landmark_id)?,
559            keypoint_index: observation.keypoint_index,
560            xy: observation.xy,
561        })
562    };
563    let rotation = base_from_other.rotation.to_rotation_matrix();
564    let mut descriptors = base_descriptors.clone();
565    for landmark in &other_landmarks {
566        let id = landmark_ids[&landmark.id];
567        let observations = landmark
568            .observations
569            .iter()
570            .filter_map(remap)
571            .collect::<Vec<_>>();
572        if fused.contains_key(&landmark.id) {
573            if let Some(target) = map.landmarks.get_mut(&id) {
574                target.observations.extend(observations);
575            }
576            continue;
577        }
578        let mut moved = Landmark::new(id, base_from_other.transform_point(&landmark.position));
579        moved.descriptor.clone_from(&landmark.descriptor);
580        moved.observations = observations;
581        map.landmarks.insert(id, moved);
582        if let Some(descriptor) = other_descriptors.get(landmark.id) {
583            descriptors.insert(id, descriptor.to_vec());
584        }
585        if let Some(covariance) = other.landmark_position_covariances.get(&landmark.id) {
586            map.landmark_position_covariances.insert(
587                id,
588                rotation.matrix() * covariance * rotation.matrix().transpose(),
589            );
590        }
591    }
592
593    let other_from_base = base_from_other.inverse();
594    for id in &other_keyframe_ids {
595        let keyframe = &other.keyframes[id];
596        let mut frame = keyframe.frame.clone();
597        frame.id = keyframe_ids[id];
598        frame.camera_id = camera_ids
599            .get(&frame.camera_id)
600            .copied()
601            .unwrap_or(frame.camera_id);
602        frame.pose = frame.pose.map(|pose| Pose {
603            world_to_camera: pose.world_to_camera.compose(&other_from_base),
604        });
605        let mut observations = Vec::with_capacity(keyframe.observations.len());
606        for observation in &keyframe.observations {
607            let Some(merged) = remap(observation) else {
608                continue;
609            };
610            if let Some(confidence) = other.observation_confidence(observation) {
611                map.set_observation_confidence(&merged, confidence);
612            }
613            observations.push(merged);
614        }
615        map.keyframes.insert(
616            frame.id,
617            Keyframe {
618                frame,
619                observations,
620            },
621        );
622    }
623    for stereo in &other.stereo_observations {
624        if let (Some(&frame_id), Some(&landmark_id)) = (
625            keyframe_ids.get(&stereo.frame_id),
626            landmark_ids.get(&stereo.landmark_id),
627        ) {
628            let mut stereo = stereo.clone();
629            stereo.frame_id = frame_id;
630            stereo.landmark_id = landmark_id;
631            stereo.right_camera_id = camera_ids
632                .get(&stereo.right_camera_id)
633                .copied()
634                .unwrap_or(stereo.right_camera_id);
635            map.stereo_observations.push(stereo);
636        }
637    }
638
639    Ok(MergedMap {
640        map,
641        descriptors,
642        keyframe_ids,
643        landmark_ids,
644        fused_landmarks: fused.len(),
645        camera_ids,
646    })
647}
648
649#[cfg(test)]
650mod tests {
651    use std::f64::consts::TAU;
652
653    use nalgebra::{Matrix3, Point3, Rotation3, UnitQuaternion};
654    use visloc_core::types::Frame;
655
656    use super::*;
657
658    struct Rng(u64);
659
660    impl Rng {
661        fn next(&mut self) -> u64 {
662            self.0 ^= self.0 << 13;
663            self.0 ^= self.0 >> 7;
664            self.0 ^= self.0 << 17;
665            self.0
666        }
667
668        fn unit(&mut self) -> f64 {
669            (self.next() % 1_000_000) as f64 / 1_000_000.0
670        }
671
672        fn bits(&mut self) -> Vec<f32> {
673            (0..256).map(|_| (self.next() & 1) as f32).collect()
674        }
675    }
676
677    fn flip(descriptor: &[f32], count: usize, rng: &mut Rng) -> Vec<f32> {
678        let mut flipped = descriptor.to_vec();
679        for _ in 0..count {
680            let bit = (rng.next() % 256) as usize;
681            flipped[bit] = 1.0 - flipped[bit];
682        }
683        flipped
684    }
685
686    const CAMERA_ID: CameraId = 1;
687
688    fn camera() -> Camera {
689        Camera::pinhole(CAMERA_ID, 640, 480, 400.0, 400.0, 320.0, 240.0)
690    }
691
692    /// World from camera of a level camera at `position` looking along
693    /// `heading` (yaw from +x).
694    fn level_camera(position: Vector3<f64>, heading: f64) -> SE3 {
695        let forward = Vector3::new(heading.cos(), heading.sin(), 0.0);
696        let right = Vector3::new(heading.sin(), -heading.cos(), 0.0);
697        let down = Vector3::new(0.0, 0.0, -1.0);
698        let rotation =
699            Rotation3::from_matrix_unchecked(Matrix3::from_columns(&[right, down, forward]));
700        SE3::new(UnitQuaternion::from_rotation_matrix(&rotation), position)
701    }
702
703    /// Points on the four walls of a 10 x 8 x 3 m room.
704    fn room(rng: &mut Rng, count: usize) -> Vec<Point3<f64>> {
705        (0..count)
706            .map(|index| {
707                let (u, v) = (rng.unit(), rng.unit());
708                match index % 4 {
709                    0 => Point3::new(u * 10.0, 0.0, v * 3.0),
710                    1 => Point3::new(u * 10.0, 8.0, v * 3.0),
711                    2 => Point3::new(0.0, u * 8.0, v * 3.0),
712                    _ => Point3::new(10.0, u * 8.0, v * 3.0),
713                }
714            })
715            .collect()
716    }
717
718    /// The map one session would build of `points` (world frame) from
719    /// `cameras` (world from camera), in its own frame `session_from_world`.
720    /// Point `i` is landmark `first_id + i`, jittered by up to `noise`
721    /// metres per axis, with descriptor `descriptors[i]`.
722    fn session_map(
723        points: &[Point3<f64>],
724        descriptors: &[Vec<f32>],
725        cameras: &[SE3],
726        session_from_world: &SE3,
727        first_id: LandmarkId,
728        noise: f64,
729        rng: &mut Rng,
730    ) -> (VisualMap, LandmarkDescriptorStore) {
731        let camera = camera();
732        let mut map = VisualMap::new();
733        map.cameras.insert(CAMERA_ID, camera.clone());
734        let mut store = LandmarkDescriptorStore::new();
735        for (index, world_from_camera) in cameras.iter().enumerate() {
736            let id = index as u64 + 1;
737            let mut frame = Frame::new(id, CAMERA_ID);
738            frame.pose = Some(Pose {
739                world_to_camera: session_from_world.compose(world_from_camera).inverse(),
740            });
741            map.keyframes.insert(
742                id,
743                Keyframe {
744                    frame,
745                    observations: Vec::new(),
746                },
747            );
748        }
749        for (index, point) in points.iter().enumerate() {
750            let landmark_id = first_id + index as u64;
751            let mut observations = Vec::new();
752            for (camera_index, world_from_camera) in cameras.iter().enumerate() {
753                let in_camera = world_from_camera.inverse().transform_point(point);
754                let Some(pixel) = camera.project(&in_camera).filter(|pixel| {
755                    in_camera.z > 0.5
756                        && pixel.x >= 0.0
757                        && pixel.x < 640.0
758                        && pixel.y >= 0.0
759                        && pixel.y < 480.0
760                }) else {
761                    continue;
762                };
763                let frame_id = camera_index as u64 + 1;
764                let keyframe = map.keyframes.get_mut(&frame_id).expect("keyframe");
765                let observation = Observation {
766                    frame_id,
767                    landmark_id,
768                    keypoint_index: keyframe.observations.len(),
769                    xy: pixel,
770                };
771                keyframe.observations.push(observation.clone());
772                observations.push(observation);
773            }
774            if observations.is_empty() {
775                continue;
776            }
777            let jitter =
778                Vector3::new(rng.unit() - 0.5, rng.unit() - 0.5, rng.unit() - 0.5) * (2.0 * noise);
779            let mut landmark = Landmark::new(
780                landmark_id,
781                session_from_world.transform_point(&(point + jitter)),
782            );
783            landmark.observations = observations;
784            map.landmarks.insert(landmark_id, landmark);
785            store.insert(landmark_id, descriptors[index].clone());
786        }
787        (map, store)
788    }
789
790    struct Sessions {
791        base: (VisualMap, LandmarkDescriptorStore),
792        other: (VisualMap, LandmarkDescriptorStore),
793        base_from_other: SE3,
794    }
795
796    /// Two sessions in one room, each in its own gravity-aligned frame. The
797    /// base session maps points 0..600 from x = 3.5 m, the other all 800
798    /// from x = 6.5 m with slightly different descriptors; points 600..800
799    /// are new to the other session.
800    fn sessions() -> Sessions {
801        let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
802        let points = room(&mut rng, 800);
803        let descriptors = (0..points.len()).map(|_| rng.bits()).collect::<Vec<_>>();
804        let other_descriptors = descriptors
805            .iter()
806            .map(|descriptor| flip(descriptor, (rng.next() % 12) as usize, &mut rng))
807            .collect::<Vec<_>>();
808        let around = |x: f64, phase: f64| {
809            (0..12)
810                .map(|k| level_camera(Vector3::new(x, 4.0, 1.5), phase + k as f64 * TAU / 12.0))
811                .collect::<Vec<_>>()
812        };
813        let base_from_other = SE3::new(
814            UnitQuaternion::from_axis_angle(&Vector3::z_axis(), 0.6),
815            Vector3::new(1.0, -2.0, 0.3),
816        );
817        Sessions {
818            base: session_map(
819                &points[..600],
820                &descriptors,
821                &around(3.5, 0.0),
822                &SE3::identity(),
823                0,
824                0.01,
825                &mut rng,
826            ),
827            other: session_map(
828                &points,
829                &other_descriptors,
830                &around(6.5, 0.1),
831                &base_from_other.inverse(),
832                100_000,
833                0.01,
834                &mut rng,
835            ),
836            base_from_other,
837        }
838    }
839
840    fn assert_se3_close(actual: &SE3, expected: &SE3, metres: f64, degrees: f64) {
841        let error = expected.inverse().compose(actual);
842        assert!(
843            error.translation.norm() < metres,
844            "translation off by {} m",
845            error.translation.norm()
846        );
847        assert!(
848            error.rotation.angle().to_degrees() < degrees,
849            "rotation off by {} deg",
850            error.rotation.angle().to_degrees()
851        );
852    }
853
854    #[test]
855    fn registration_recovers_the_transform_between_sessions() {
856        let s = sessions();
857        let registration = register_map(
858            &s.base.0,
859            &s.base.1,
860            &s.other.0,
861            &s.other.1,
862            &MapMergeConfig {
863                threads: 3,
864                ..MapMergeConfig::default()
865            },
866        )
867        .expect("registered");
868        assert_se3_close(
869            &registration.base_from_other,
870            &s.base_from_other,
871            0.005,
872            0.05,
873        );
874        assert_eq!(registration.keyframes, 12);
875        assert_eq!(
876            registration.agreeing_keyframes,
877            registration.localized_keyframes
878        );
879        assert!(registration.agreeing_keyframes >= 10, "{registration:?}");
880        assert!(registration.keyframe_rms_m < 0.02, "{registration:?}");
881
882        // The thread count does not change the result.
883        let serial = register_map(
884            &s.base.0,
885            &s.base.1,
886            &s.other.0,
887            &s.other.1,
888            &MapMergeConfig::default(),
889        )
890        .expect("registered");
891        assert_eq!(serial, registration);
892    }
893
894    #[test]
895    fn merging_fuses_shared_landmarks_and_adds_new_ones() {
896        let s = sessions();
897        let config = MapMergeConfig::default();
898        let merged = merge_maps(
899            &s.base.0,
900            &s.base.1,
901            &s.other.0,
902            &s.other.1,
903            &s.base_from_other,
904            &config,
905        )
906        .expect("merged");
907        let shared = s
908            .other
909            .0
910            .landmarks
911            .keys()
912            .filter(|id| s.base.0.landmarks.contains_key(&(*id - 100_000)))
913            .count();
914        assert!(shared > 500, "{shared}");
915        assert_eq!(merged.fused_landmarks, shared);
916        for (other_id, merged_id) in &merged.landmark_ids {
917            if s.base.0.landmarks.contains_key(&(other_id - 100_000)) {
918                assert_eq!(*merged_id, other_id - 100_000, "fused into its own point");
919            } else {
920                assert!(!s.base.0.landmarks.contains_key(merged_id));
921            }
922        }
923        assert_eq!(
924            merged.map.landmarks.len(),
925            s.base.0.landmarks.len() + s.other.0.landmarks.len() - shared
926        );
927        assert_eq!(merged.descriptors.len(), merged.map.landmarks.len());
928        assert_eq!(merged.map.keyframes.len(), 24);
929
930        // A fused landmark keeps the base position and gains the other
931        // session's observations, which point at moved keyframes.
932        let fused = &merged.map.landmarks[&5];
933        assert_eq!(fused.position, s.base.0.landmarks[&5].position);
934        let other_observations = fused
935            .observations
936            .iter()
937            .filter(|observation| observation.frame_id > 12)
938            .collect::<Vec<_>>();
939        assert_eq!(
940            other_observations.len(),
941            s.other.0.landmarks[&100_005].observations.len()
942        );
943        for observation in other_observations {
944            let keyframe = &merged.map.keyframes[&observation.frame_id];
945            assert!(keyframe.observations.contains(observation));
946            let pose = keyframe.frame.pose.as_ref().expect("pose");
947            let pixel = camera()
948                .project(&pose.transform_world_point(&fused.position))
949                .expect("in front");
950            assert!((pixel - observation.xy).norm() < 5.0);
951        }
952
953        // Keyframes of the other session land on their true poses.
954        let other_camera_one = level_camera(Vector3::new(6.5, 4.0, 1.5), 0.1);
955        let moved = merged.map.keyframes[&merged.keyframe_ids[&1]]
956            .frame
957            .pose
958            .as_ref()
959            .expect("pose")
960            .camera_to_world();
961        assert_se3_close(&moved, &other_camera_one, 1e-9, 1e-9);
962    }
963
964    #[test]
965    fn without_fusion_every_landmark_is_added() {
966        let s = sessions();
967        let merged = merge_maps(
968            &s.base.0,
969            &s.base.1,
970            &s.other.0,
971            &s.other.1,
972            &s.base_from_other,
973            &MapMergeConfig {
974                fuse_radius_m: 0.0,
975                ..MapMergeConfig::default()
976            },
977        )
978        .expect("merged");
979        assert_eq!(merged.fused_landmarks, 0);
980        assert_eq!(
981            merged.map.landmarks.len(),
982            s.base.0.landmarks.len() + s.other.0.landmarks.len()
983        );
984    }
985
986    #[test]
987    fn a_map_of_another_place_does_not_register() {
988        let s = sessions();
989        let mut rng = Rng(42);
990        let unrelated = s
991            .other
992            .0
993            .landmarks
994            .keys()
995            .map(|&id| (id, rng.bits()))
996            .collect::<Vec<_>>();
997        let mut store = LandmarkDescriptorStore::new();
998        for (id, descriptor) in unrelated {
999            store.insert(id, descriptor);
1000        }
1001        let error = register_map(
1002            &s.base.0,
1003            &s.base.1,
1004            &s.other.0,
1005            &store,
1006            &MapMergeConfig::default(),
1007        )
1008        .expect_err("nothing to register");
1009        assert!(matches!(
1010            error,
1011            MapMergeError::TooFewKeyframes { agreeing: 0, .. }
1012        ));
1013    }
1014
1015    #[test]
1016    fn another_calibration_is_added_under_a_new_camera_id() {
1017        let s = sessions();
1018        let mut other = s.other.0.clone();
1019        other.cameras.get_mut(&CAMERA_ID).expect("camera").params[0] += 1.0;
1020        let merged = merge_maps(
1021            &s.base.0,
1022            &s.base.1,
1023            &other,
1024            &s.other.1,
1025            &s.base_from_other,
1026            &MapMergeConfig::default(),
1027        )
1028        .expect("merged");
1029        let new_id = merged.camera_ids[&CAMERA_ID];
1030        assert_ne!(new_id, CAMERA_ID);
1031        assert_eq!(merged.map.cameras[&CAMERA_ID], s.base.0.cameras[&CAMERA_ID]);
1032        assert_eq!(
1033            merged.map.cameras[&new_id].params,
1034            other.cameras[&CAMERA_ID].params
1035        );
1036        assert_eq!(merged.map.cameras[&new_id].id, new_id);
1037        for (other_id, merged_id) in &merged.keyframe_ids {
1038            assert_eq!(other.keyframes[other_id].frame.camera_id, CAMERA_ID);
1039            assert_eq!(merged.map.keyframes[merged_id].frame.camera_id, new_id);
1040        }
1041        for keyframe in s.base.0.keyframes.values() {
1042            assert_eq!(
1043                merged.map.keyframes[&keyframe.frame.id].frame.camera_id,
1044                CAMERA_ID
1045            );
1046        }
1047    }
1048
1049    #[test]
1050    fn the_same_camera_keeps_its_id() {
1051        let s = sessions();
1052        let merged = merge_maps(
1053            &s.base.0,
1054            &s.base.1,
1055            &s.other.0,
1056            &s.other.1,
1057            &s.base_from_other,
1058            &MapMergeConfig::default(),
1059        )
1060        .expect("merged");
1061        assert_eq!(merged.camera_ids[&CAMERA_ID], CAMERA_ID);
1062        assert_eq!(merged.map.cameras.len(), 1);
1063    }
1064}