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