Skip to main content

visloc_localization/
binary_index.rs

1//! Hamming matching against a map's binary landmark descriptors, packed once.
2//!
3//! [`CorrespondenceBuilder`](crate::CorrespondenceBuilder) and
4//! [`ProjectionCorrespondenceBuilder`](crate::ProjectionCorrespondenceBuilder)
5//! hand the map's descriptors to a generic [`Matcher`] as float vectors on
6//! every query, so a binary matcher re-packs (and the builders re-copy) the
7//! whole map per image. [`BinaryLandmarkIndex`] packs the landmark
8//! descriptors to 64-bit words once and produces the same correspondences as
9//! those builders with a [`HammingMatcher`], at a fraction of the cost:
10//! [`BinaryLandmarkIndex::match_all`] for the appearance-only search and
11//! [`BinaryLandmarkIndex::match_projected`] for a pose prior's projection
12//! windows, which only compares each projected landmark with the keypoints
13//! near it.
14//!
15//! A landmark can also carry extra descriptors, from the views of it whose
16//! descriptors differ most from its main one
17//! ([`BinaryLandmarkIndex::with_extra_descriptors`]): a keypoint matches the
18//! landmark at the nearest of them, and the ratio test compares it with the
19//! nearest other landmark.
20//!
21//! A map can hold several landmarks for one physical point: a SLAM map whose
22//! tracks broke and restarted, and more so a map merged from several
23//! sessions. Their descriptors are nearly equal, so the nearest /
24//! second-nearest ratio test rejects keypoints of that point.
25//! [`BinaryLandmarkIndex::with_duplicate_radius`] makes
26//! [`BinaryLandmarkIndex::match_all`] compare the best landmark with the
27//! best one farther than a radius from it instead.
28//!
29//! [`Matcher`]: visloc_vision::matching::Matcher
30//! [`HammingMatcher`]: visloc_vision::matching::HammingMatcher
31
32use std::collections::HashSet;
33
34use nalgebra::{Point2, Point3};
35use visloc_core::geometry::Pose;
36use visloc_core::types::{Camera, LandmarkDescriptorStore, LandmarkId, VisualMap};
37use visloc_vision::matching::DescriptorMatch;
38use visloc_vision::pnp::Correspondence2D3D;
39
40use crate::CorrespondenceSet;
41
42/// Acceptance gates of a Hamming match, as in
43/// [`HammingMatcher`](visloc_vision::matching::HammingMatcher).
44#[derive(Debug, Clone, Copy, PartialEq)]
45pub struct BinaryMatchGates {
46    /// Largest accepted Hamming distance.
47    pub max_distance: u32,
48    /// Accept only when `best < ratio * second_best`.
49    pub ratio: Option<f32>,
50}
51
52/// Binary descriptors stored one bit per value (`>= 0.5` is a set bit), as
53/// 64-bit words.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct PackedDescriptors {
56    dimension: usize,
57    words: usize,
58    bits: Vec<u64>,
59    /// Descriptors of another length than `dimension` never match.
60    valid: Vec<bool>,
61}
62
63impl PackedDescriptors {
64    /// Packs `descriptors`, which should all be `dimension` values long.
65    pub fn pack<D: AsRef<[f32]>>(descriptors: &[D], dimension: usize) -> Self {
66        let words = dimension.div_ceil(64);
67        let mut bits = vec![0_u64; words * descriptors.len()];
68        let mut valid = Vec::with_capacity(descriptors.len());
69        for (index, descriptor) in descriptors.iter().enumerate() {
70            let descriptor = descriptor.as_ref();
71            let ok = descriptor.len() == dimension;
72            valid.push(ok);
73            if !ok {
74                continue;
75            }
76            let packed = &mut bits[index * words..(index + 1) * words];
77            for (bit, value) in descriptor.iter().enumerate() {
78                if *value >= 0.5 {
79                    packed[bit / 64] |= 1 << (bit % 64);
80                }
81            }
82        }
83        Self {
84            dimension,
85            words,
86            bits,
87            valid,
88        }
89    }
90
91    pub const fn dimension(&self) -> usize {
92        self.dimension
93    }
94
95    pub fn len(&self) -> usize {
96        self.valid.len()
97    }
98
99    pub fn is_empty(&self) -> bool {
100        self.valid.is_empty()
101    }
102
103    pub(crate) fn get(&self, index: usize) -> Option<&[u64]> {
104        self.valid
105            .get(index)
106            .copied()
107            .unwrap_or(false)
108            .then(|| &self.bits[index * self.words..(index + 1) * self.words])
109    }
110
111    /// `(index, words)` of every valid descriptor.
112    fn iter(&self) -> impl Iterator<Item = (usize, &[u64])> {
113        self.bits
114            .chunks_exact(self.words.max(1))
115            .zip(&self.valid)
116            .enumerate()
117            .filter_map(|(index, (bits, valid))| valid.then_some((index, bits)))
118    }
119}
120
121fn hamming(a: &[u64], b: &[u64]) -> u32 {
122    // 256-bit descriptors (ORB) get a fixed-size kernel the compiler fully
123    // unrolls.
124    if let (Ok(a), Ok(b)) = (<&[u64; 4]>::try_from(a), <&[u64; 4]>::try_from(b)) {
125        return (a[0] ^ b[0]).count_ones()
126            + (a[1] ^ b[1]).count_ones()
127            + (a[2] ^ b[2]).count_ones()
128            + (a[3] ^ b[3]).count_ones();
129    }
130    a.iter().zip(b).map(|(a, b)| (a ^ b).count_ones()).sum()
131}
132
133/// Best and second-best distance of one search, with
134/// [`HammingMatcher`](visloc_vision::matching::HammingMatcher)'s tie rule
135/// (the first candidate at the lowest distance wins).
136#[derive(Clone, Copy)]
137struct Nearest {
138    best: (u32, usize),
139    second: u32,
140}
141
142impl Nearest {
143    const fn new() -> Self {
144        Self {
145            best: (u32::MAX, 0),
146            second: u32::MAX,
147        }
148    }
149
150    /// Offers a candidate; an index offered again (a landmark's other
151    /// descriptor) competes with itself only for the best distance, never as
152    /// the second best.
153    fn offer(&mut self, distance: u32, index: usize) {
154        if distance < self.best.0 {
155            if index != self.best.1 {
156                self.second = self.best.0;
157            }
158            self.best = (distance, index);
159        } else if distance < self.second && index != self.best.1 {
160            self.second = distance;
161        }
162    }
163
164    /// The accepted `(distance, index, second)`, if any.
165    fn accept(self, gates: BinaryMatchGates) -> Option<(u32, usize, Option<f32>)> {
166        let (distance, index) = self.best;
167        if distance > gates.max_distance {
168            return None;
169        }
170        let second = (self.second != u32::MAX).then_some(self.second as f32);
171        if let (Some(ratio), Some(second)) = (gates.ratio, second) {
172            if distance as f32 >= ratio * second {
173                return None;
174            }
175        }
176        Some((distance, index, second))
177    }
178}
179
180/// Candidates [`NearestDistinct`] keeps.
181const DISTINCT_CANDIDATES: usize = 8;
182
183/// The best distances of one search, for a ratio test whose second-best
184/// candidate must lie farther than a radius from the best one.
185#[derive(Clone, Copy)]
186struct NearestDistinct {
187    /// `(distance, index)`, ascending; ties keep the earlier candidate first.
188    candidates: [(u32, usize); DISTINCT_CANDIDATES],
189    len: usize,
190}
191
192impl NearestDistinct {
193    const fn new() -> Self {
194        Self {
195            candidates: [(u32::MAX, 0); DISTINCT_CANDIDATES],
196            len: 0,
197        }
198    }
199
200    fn offer(&mut self, distance: u32, index: usize) {
201        if self.len == DISTINCT_CANDIDATES && distance >= self.candidates[self.len - 1].0 {
202            return;
203        }
204        let at = self.candidates[..self.len].partition_point(|(kept, _)| *kept <= distance);
205        let end = self.len.min(DISTINCT_CANDIDATES - 1);
206        self.candidates.copy_within(at..end, at + 1);
207        self.candidates[at] = (distance, index);
208        self.len = (self.len + 1).min(DISTINCT_CANDIDATES);
209    }
210
211    /// The best candidate and, as the second-best distance, the nearest
212    /// candidate farther than `radius` from it. When every kept candidate is
213    /// within the radius, the last kept distance is a lower bound of that
214    /// second-best distance and stands in for it.
215    fn collapse(self, positions: &[Point3<f64>], radius: f64) -> Nearest {
216        if self.len == 0 {
217            return Nearest::new();
218        }
219        let (distance, index) = self.candidates[0];
220        let best = positions[index];
221        let second = self.candidates[1..self.len]
222            .iter()
223            .find(|(_, other)| (positions[*other] - best).norm() > radius)
224            .map(|(distance, _)| *distance)
225            .or_else(|| (self.len == DISTINCT_CANDIDATES).then(|| self.candidates[self.len - 1].0))
226            .unwrap_or(u32::MAX);
227        Nearest {
228            best: (distance, index),
229            second,
230        }
231    }
232}
233
234fn descriptor_match(
235    query_index: usize,
236    train_index: usize,
237    distance: u32,
238    second: Option<f32>,
239) -> DescriptorMatch {
240    DescriptorMatch {
241        query_index,
242        train_index,
243        distance: distance as f32,
244        second_best_distance: second,
245        ratio: second.map(|second| distance as f32 / second.max(1.0)),
246        confidence: None,
247    }
248}
249
250/// A map's landmarks with their binary descriptors packed for matching.
251#[derive(Debug, Clone)]
252pub struct BinaryLandmarkIndex {
253    landmark_ids: Vec<LandmarkId>,
254    positions: Vec<Point3<f64>>,
255    descriptors: PackedDescriptors,
256    /// Extra descriptors, grouped by landmark: those of the landmark at
257    /// index `i` are rows `extra_offsets[i]..extra_offsets[i + 1]`.
258    extra: PackedDescriptors,
259    extra_offsets: Vec<usize>,
260    /// The landmark index of each extra row.
261    extra_owner: Vec<usize>,
262    duplicate_radius_m: Option<f64>,
263}
264
265impl BinaryLandmarkIndex {
266    /// Indexes every landmark of `map` that has a descriptor in `store`, in
267    /// landmark-id order. Descriptors whose length differs from the first
268    /// one never match.
269    pub fn new(map: &VisualMap, store: &LandmarkDescriptorStore) -> Self {
270        let paired = store.ordered_landmark_descriptors(map);
271        let dimension = paired.first().map_or(0, |(_, descriptor)| descriptor.len());
272        let descriptors = paired
273            .iter()
274            .map(|(_, descriptor)| *descriptor)
275            .collect::<Vec<_>>();
276        Self {
277            landmark_ids: paired.iter().map(|(landmark, _)| landmark.id).collect(),
278            positions: paired
279                .iter()
280                .map(|(landmark, _)| landmark.position)
281                .collect(),
282            descriptors: PackedDescriptors::pack(&descriptors, dimension),
283            extra: PackedDescriptors::pack::<&[f32]>(&[], dimension),
284            extra_offsets: vec![0; paired.len() + 1],
285            extra_owner: Vec::new(),
286            duplicate_radius_m: None,
287        }
288    }
289
290    /// Adds extra descriptors, `(landmark id, descriptor)` rows with ids
291    /// repeated freely, at most `max_per_landmark` per landmark in the order
292    /// given; rows of landmarks not indexed are skipped. Replaces any extra
293    /// descriptors added before.
294    #[must_use]
295    pub fn with_extra_descriptors<D: AsRef<[f32]>>(
296        mut self,
297        rows: &[(LandmarkId, D)],
298        max_per_landmark: usize,
299    ) -> Self {
300        let mut grouped: Vec<Vec<&[f32]>> = vec![Vec::new(); self.len()];
301        for (id, descriptor) in rows {
302            if let Some(index) = self.landmark_index(*id) {
303                if grouped[index].len() < max_per_landmark {
304                    grouped[index].push(descriptor.as_ref());
305                }
306            }
307        }
308        let mut offsets = Vec::with_capacity(self.len() + 1);
309        let mut owner = Vec::new();
310        let mut flat = Vec::new();
311        offsets.push(0);
312        for (index, descriptors) in grouped.into_iter().enumerate() {
313            owner.extend(std::iter::repeat_n(index, descriptors.len()));
314            flat.extend(descriptors);
315            offsets.push(flat.len());
316        }
317        self.extra = PackedDescriptors::pack(&flat, self.dimension());
318        self.extra_offsets = offsets;
319        self.extra_owner = owner;
320        self
321    }
322
323    /// Number of extra descriptors indexed.
324    pub fn extra_descriptor_count(&self) -> usize {
325        self.extra.len()
326    }
327
328    /// Every descriptor row with its landmark index: the main ones, then
329    /// the extra ones.
330    fn rows(&self) -> impl Iterator<Item = (usize, &[u64])> {
331        self.descriptors.iter().chain(
332            self.extra
333                .iter()
334                .map(|(row, bits)| (self.extra_owner[row], bits)),
335        )
336    }
337
338    /// The descriptors of the landmark at `index`: its main one (if valid),
339    /// then its extra ones.
340    fn landmark_rows(&self, index: usize) -> impl Iterator<Item = &[u64]> {
341        let range = self.extra_offsets.get(index).copied().unwrap_or(0)
342            ..self.extra_offsets.get(index + 1).copied().unwrap_or(0);
343        self.descriptors
344            .get(index)
345            .into_iter()
346            .chain(range.filter_map(|row| self.extra.get(row)))
347    }
348
349    /// Makes the ratio test of [`Self::match_all`] treat landmarks within
350    /// `radius_m` of the best one as the same point: the second-best
351    /// distance is that of the best landmark farther away. See the module
352    /// documentation. `radius_m <= 0` turns it off.
353    #[must_use]
354    pub fn with_duplicate_radius(mut self, radius_m: f64) -> Self {
355        self.duplicate_radius_m = (radius_m > 0.0).then_some(radius_m);
356        self
357    }
358
359    pub fn len(&self) -> usize {
360        self.landmark_ids.len()
361    }
362
363    pub fn is_empty(&self) -> bool {
364        self.landmark_ids.is_empty()
365    }
366
367    /// Descriptor length of the indexed landmarks.
368    pub const fn dimension(&self) -> usize {
369        self.descriptors.dimension
370    }
371
372    /// Packs query descriptors for [`Self::match_all`] /
373    /// [`Self::match_projected`].
374    pub fn pack_query<D: AsRef<[f32]>>(&self, descriptors: &[D]) -> PackedDescriptors {
375        PackedDescriptors::pack(descriptors, self.dimension())
376    }
377
378    /// Appearance-only matching: every query descriptor against every
379    /// landmark, split over up to `threads` threads. Without a duplicate
380    /// radius, the same correspondences, in the same order, as
381    /// [`CorrespondenceBuilder`](crate::CorrespondenceBuilder) with a
382    /// [`HammingMatcher`](visloc_vision::matching::HammingMatcher) of the
383    /// same gates: one per accepted keypoint, several keypoints may share a
384    /// landmark.
385    pub fn match_all(
386        &self,
387        keypoints: &[Point2<f64>],
388        query: &PackedDescriptors,
389        gates: BinaryMatchGates,
390        threads: usize,
391    ) -> CorrespondenceSet {
392        let count = keypoints.len().min(query.len());
393        let match_range = |range: std::ops::Range<usize>| {
394            range
395                .filter_map(|query_index| {
396                    let bits = query.get(query_index)?;
397                    let nearest = self.search(bits, self.rows());
398                    let (distance, landmark, second) = nearest.accept(gates)?;
399                    Some(descriptor_match(query_index, landmark, distance, second))
400                })
401                .collect::<Vec<_>>()
402        };
403        let threads = threads.clamp(1, count.max(1));
404        let matches = if threads == 1 {
405            match_range(0..count)
406        } else {
407            let chunk = count.div_ceil(threads);
408            std::thread::scope(|scope| {
409                let handles = (0..count)
410                    .step_by(chunk)
411                    .map(|start| {
412                        let match_range = &match_range;
413                        scope.spawn(move || match_range(start..(start + chunk).min(count)))
414                    })
415                    .collect::<Vec<_>>();
416                handles
417                    .into_iter()
418                    .flat_map(|handle| handle.join().expect("matcher thread panicked"))
419                    .collect()
420            })
421        };
422        self.correspondence_set(keypoints, matches, self.len())
423    }
424
425    /// [`Self::match_all`] restricted to the landmarks at `landmarks`
426    /// (indices into this index, e.g. from
427    /// [`KeyframeRetrieval`](crate::KeyframeRetrieval)): each keypoint's
428    /// ratio test then weighs only those landmarks against each other.
429    pub fn match_among(
430        &self,
431        keypoints: &[Point2<f64>],
432        query: &PackedDescriptors,
433        gates: BinaryMatchGates,
434        landmarks: &[usize],
435    ) -> CorrespondenceSet {
436        let count = keypoints.len().min(query.len());
437        let matches = (0..count)
438            .filter_map(|query_index| {
439                let bits = query.get(query_index)?;
440                let candidates = landmarks.iter().flat_map(|&landmark| {
441                    self.landmark_rows(landmark)
442                        .map(move |train| (landmark, train))
443                });
444                let (distance, landmark, second) = self.search(bits, candidates).accept(gates)?;
445                Some(descriptor_match(query_index, landmark, distance, second))
446            })
447            .collect();
448        self.correspondence_set(keypoints, matches, landmarks.len())
449    }
450
451    /// The nearest of `candidates` (landmark indices with their packed
452    /// descriptors, a landmark possibly more than once) to `bits`, with the
453    /// duplicate radius applied.
454    fn search<'a>(
455        &self,
456        bits: &[u64],
457        candidates: impl Iterator<Item = (usize, &'a [u64])>,
458    ) -> Nearest {
459        match self.duplicate_radius_m {
460            None => {
461                let mut nearest = Nearest::new();
462                for (landmark, train) in candidates {
463                    nearest.offer(hamming(bits, train), landmark);
464                }
465                nearest
466            }
467            Some(radius) => {
468                let mut nearest = NearestDistinct::new();
469                for (landmark, train) in candidates {
470                    nearest.offer(hamming(bits, train), landmark);
471                }
472                nearest.collapse(&self.positions, radius)
473            }
474        }
475    }
476
477    /// Index of landmark `id` in this index, if it has a descriptor.
478    pub fn landmark_index(&self, id: LandmarkId) -> Option<usize> {
479        self.landmark_ids.binary_search(&id).ok()
480    }
481
482    /// The packed descriptor of the landmark at `index`.
483    pub(crate) fn landmark_descriptor(&self, index: usize) -> Option<&[u64]> {
484        self.descriptors.get(index)
485    }
486
487    /// Projection-guided matching: each landmark is projected with
488    /// `pose_prior` and its descriptors (the nearest of them) compared only
489    /// with the keypoints
490    /// within `radius_px` of the projection (best and second best among
491    /// them, gated by `gates`); overlapping windows are then resolved
492    /// one-to-one, lowest distance first. The same correspondences as
493    /// [`ProjectionCorrespondenceBuilder::build_with_pose_prior`](crate::ProjectionCorrespondenceBuilder::build_with_pose_prior)
494    /// with a [`HammingMatcher`](visloc_vision::matching::HammingMatcher) of
495    /// the same gates, except that landmarks behind the camera (`z <= 0`)
496    /// are skipped before projecting.
497    pub fn match_projected(
498        &self,
499        camera: &Camera,
500        pose_prior: &Pose,
501        keypoints: &[Point2<f64>],
502        query: &PackedDescriptors,
503        radius_px: f64,
504        gates: BinaryMatchGates,
505    ) -> CorrespondenceSet {
506        let count = keypoints.len().min(query.len());
507        let grid = KeypointGrid::new(&keypoints[..count], radius_px);
508        let (width, height) = (f64::from(camera.width), f64::from(camera.height));
509        let radius_squared = radius_px * radius_px;
510        let mut candidate_count = 0;
511        let mut proposals = Vec::new();
512        for (landmark, position) in self.positions.iter().enumerate() {
513            if self.landmark_rows(landmark).next().is_none() {
514                continue;
515            }
516            let point_camera = pose_prior.transform_world_point(position);
517            if point_camera.z <= 0.0 {
518                continue;
519            }
520            let Some(projected) = camera.project(&point_camera) else {
521                continue;
522            };
523            if projected.x < 0.0
524                || projected.y < 0.0
525                || projected.x >= width
526                || projected.y >= height
527            {
528                continue;
529            }
530            candidate_count += 1;
531            // Window keypoints in ascending index order, as the builder's
532            // linear scan visits them.
533            let mut nearest = Nearest::new();
534            for keypoint in grid.within(keypoints, projected, radius_squared) {
535                if let Some(bits) = query.get(keypoint) {
536                    let distance = self
537                        .landmark_rows(landmark)
538                        .map(|train| hamming(train, bits))
539                        .min()
540                        .unwrap_or(u32::MAX);
541                    nearest.offer(distance, keypoint);
542                }
543            }
544            if let Some((distance, keypoint, second)) = nearest.accept(gates) {
545                proposals.push(descriptor_match(keypoint, landmark, distance, second));
546            }
547        }
548        // Landmark index order is landmark-id order, so this is the
549        // builder's (distance, landmark id, keypoint) order.
550        proposals.sort_by(|a, b| {
551            a.distance
552                .total_cmp(&b.distance)
553                .then_with(|| a.train_index.cmp(&b.train_index))
554                .then_with(|| a.query_index.cmp(&b.query_index))
555        });
556        let mut used_keypoints = HashSet::new();
557        let mut used_landmarks = HashSet::new();
558        proposals.retain(|m| {
559            used_keypoints.insert(m.query_index) && used_landmarks.insert(m.train_index)
560        });
561        self.correspondence_set(keypoints, proposals, candidate_count)
562    }
563
564    fn correspondence_set(
565        &self,
566        keypoints: &[Point2<f64>],
567        matches: Vec<DescriptorMatch>,
568        candidate_landmark_count: usize,
569    ) -> CorrespondenceSet {
570        CorrespondenceSet {
571            correspondences: matches
572                .iter()
573                .map(|m| Correspondence2D3D {
574                    point2d: keypoints[m.query_index],
575                    point3d: self.positions[m.train_index],
576                    confidence: None,
577                })
578                .collect(),
579            query_indices: matches.iter().map(|m| m.query_index).collect(),
580            landmark_ids: matches
581                .iter()
582                .map(|m| self.landmark_ids[m.train_index])
583                .collect(),
584            candidate_landmark_count,
585            match_count: matches.len(),
586            descriptor_matches: matches,
587        }
588    }
589}
590
591/// Keypoints bucketed into square cells of the search radius, so a window
592/// lookup visits only the 3x3 cells around the query point.
593struct KeypointGrid {
594    origin: Point2<f64>,
595    cell: f64,
596    columns: isize,
597    rows: isize,
598    /// Keypoint indices per cell, ascending.
599    cells: Vec<Vec<usize>>,
600}
601
602impl KeypointGrid {
603    fn new(keypoints: &[Point2<f64>], radius_px: f64) -> Self {
604        let finite = || {
605            keypoints
606                .iter()
607                .filter(|p| p.x.is_finite() && p.y.is_finite())
608        };
609        let fold = |init: f64, pick: fn(&Point2<f64>) -> f64, f: fn(f64, f64) -> f64| {
610            finite().map(pick).fold(init, f)
611        };
612        let origin = Point2::new(
613            fold(f64::INFINITY, |p| p.x, f64::min).min(0.0),
614            fold(f64::INFINITY, |p| p.y, f64::min).min(0.0),
615        );
616        let extent = Point2::new(
617            fold(0.0, |p| p.x, f64::max) - origin.x,
618            fold(0.0, |p| p.y, f64::max) - origin.y,
619        );
620        // Any cell at least the radius wide keeps every window inside 3x3
621        // cells; the cap only bounds the grid for far-flung coordinates.
622        let cell = radius_px.max(1.0).max(extent.x.max(extent.y) / 1024.0);
623        let columns = (extent.x / cell) as isize + 1;
624        let rows = (extent.y / cell) as isize + 1;
625        let mut grid = Self {
626            origin,
627            cell,
628            columns,
629            rows,
630            cells: vec![Vec::new(); (columns * rows) as usize],
631        };
632        for (index, keypoint) in keypoints.iter().enumerate() {
633            if keypoint.x.is_finite() && keypoint.y.is_finite() {
634                let (column, row) = grid.cell_of(keypoint);
635                grid.cells[(row * columns + column) as usize].push(index);
636            }
637        }
638        grid
639    }
640
641    /// The (possibly out-of-grid) cell of a point.
642    fn cell_of(&self, point: &Point2<f64>) -> (isize, isize) {
643        (
644            ((point.x - self.origin.x) / self.cell).floor() as isize,
645            ((point.y - self.origin.y) / self.cell).floor() as isize,
646        )
647    }
648
649    /// Indices of the keypoints within `sqrt(radius_squared)` of `center`,
650    /// ascending.
651    fn within(
652        &self,
653        keypoints: &[Point2<f64>],
654        center: Point2<f64>,
655        radius_squared: f64,
656    ) -> Vec<usize> {
657        let (column, row) = self.cell_of(&center);
658        let mut found = Vec::new();
659        for r in (row - 1).max(0)..=(row + 1).min(self.rows - 1) {
660            for c in (column - 1).max(0)..=(column + 1).min(self.columns - 1) {
661                for &index in &self.cells[(r * self.columns + c) as usize] {
662                    let d = keypoints[index] - center;
663                    if d.x * d.x + d.y * d.y <= radius_squared {
664                        found.push(index);
665                    }
666                }
667            }
668        }
669        found.sort_unstable();
670        found
671    }
672}
673
674#[cfg(test)]
675mod tests {
676    use nalgebra::{UnitQuaternion, Vector3};
677    use visloc_core::types::Landmark;
678    use visloc_vision::matching::HammingMatcher;
679
680    use super::*;
681    use crate::{CorrespondenceBuilder, ProjectionCorrespondenceBuilder};
682
683    struct Rng(u64);
684
685    impl Rng {
686        fn next(&mut self) -> u64 {
687            self.0 ^= self.0 << 13;
688            self.0 ^= self.0 >> 7;
689            self.0 ^= self.0 << 17;
690            self.0
691        }
692
693        fn unit(&mut self) -> f64 {
694            (self.next() % 1_000_000) as f64 / 1_000_000.0
695        }
696
697        fn bits(&mut self) -> Vec<f32> {
698            (0..256).map(|_| (self.next() & 1) as f32).collect()
699        }
700    }
701
702    fn flip(descriptor: &[f32], count: usize, rng: &mut Rng) -> Vec<f32> {
703        let mut flipped = descriptor.to_vec();
704        for _ in 0..count {
705            let bit = (rng.next() % 256) as usize;
706            flipped[bit] = 1.0 - flipped[bit];
707        }
708        flipped
709    }
710
711    struct Scene {
712        map: VisualMap,
713        store: LandmarkDescriptorStore,
714        camera: Camera,
715        prior: Pose,
716        keypoints: Vec<Point2<f64>>,
717        descriptors: Vec<Vec<f32>>,
718    }
719
720    /// Landmarks in front of and behind a camera; keypoints at the true
721    /// projections of most visible ones (descriptors a few bits off, some
722    /// landmarks sharing a descriptor so ratio tests bite) plus clutter. The
723    /// prior is off by a few pixels.
724    fn scene() -> Scene {
725        let mut rng = Rng(0x2545_f491_4f6c_dd1d);
726        let camera = Camera::pinhole(1, 640, 480, 400.0, 400.0, 320.0, 240.0);
727        let truth = Pose::identity();
728        let prior = Pose::from_world_to_camera(
729            UnitQuaternion::from_euler_angles(0.004, -0.003, 0.002),
730            Vector3::new(0.01, -0.02, 0.0),
731        );
732        let mut map = VisualMap::new();
733        let mut store = LandmarkDescriptorStore::new();
734        let mut keypoints = Vec::new();
735        let mut descriptors = Vec::new();
736        let mut shared = rng.bits();
737        for id in 0..400_u64 {
738            let position = Point3::new(
739                rng.unit() * 8.0 - 4.0,
740                rng.unit() * 6.0 - 3.0,
741                if id % 10 == 0 {
742                    -2.0
743                } else {
744                    1.5 + rng.unit() * 6.0
745                },
746            );
747            if id % 37 == 0 {
748                shared = rng.bits();
749            }
750            let descriptor = if id % 7 == 0 {
751                shared.clone()
752            } else {
753                rng.bits()
754            };
755            map.landmarks.insert(id, Landmark::new(id, position));
756            store.insert(id, descriptor.clone());
757            if let Some(pixel) = camera.project(&truth.transform_world_point(&position)) {
758                if position.z > 0.0 && id % 5 != 0 {
759                    keypoints.push(pixel + nalgebra::Vector2::new(rng.unit(), rng.unit()));
760                    descriptors.push(flip(&descriptor, (rng.next() % 30) as usize, &mut rng));
761                }
762            }
763        }
764        for _ in 0..150 {
765            keypoints.push(Point2::new(rng.unit() * 640.0, rng.unit() * 480.0));
766            descriptors.push(rng.bits());
767        }
768        // Interleave clutter with real keypoints.
769        let mut order = (0..keypoints.len()).collect::<Vec<_>>();
770        order.sort_by_key(|i| (i * 7919) % keypoints.len());
771        Scene {
772            map,
773            store,
774            camera,
775            prior,
776            keypoints: order.iter().map(|&i| keypoints[i]).collect(),
777            descriptors: order.iter().map(|&i| descriptors[i].clone()).collect(),
778        }
779    }
780
781    fn query(scene: &Scene) -> visloc_core::types::QueryImage {
782        visloc_core::types::QueryImage {
783            camera: scene.camera.clone(),
784            keypoints: scene.keypoints.clone(),
785            descriptors: scene.descriptors.clone(),
786        }
787    }
788
789    const GATES: BinaryMatchGates = BinaryMatchGates {
790        max_distance: 70,
791        ratio: Some(0.8),
792    };
793
794    fn hamming_matcher() -> HammingMatcher {
795        HammingMatcher {
796            max_distance: GATES.max_distance,
797            ratio: GATES.ratio,
798        }
799    }
800
801    #[test]
802    fn global_matching_equals_the_correspondence_builder() {
803        let scene = scene();
804        let index = BinaryLandmarkIndex::new(&scene.map, &scene.store);
805        assert_eq!(index.len(), 400);
806        let expected = CorrespondenceBuilder::new(hamming_matcher())
807            .build(&query(&scene), &scene.map, &scene.store)
808            .unwrap();
809        assert!(expected.match_count > 100, "{}", expected.match_count);
810        let packed = index.pack_query(&scene.descriptors);
811        for threads in [1, 3] {
812            let actual = index.match_all(&scene.keypoints, &packed, GATES, threads);
813            assert_eq!(actual, expected, "threads={threads}");
814        }
815    }
816
817    #[test]
818    fn projection_matching_equals_the_projection_builder() {
819        let scene = scene();
820        let index = BinaryLandmarkIndex::new(&scene.map, &scene.store);
821        let packed = index.pack_query(&scene.descriptors);
822        for radius in [4.0, 12.0, 40.0] {
823            let expected = ProjectionCorrespondenceBuilder::new(hamming_matcher())
824                .build_with_pose_prior(
825                    &query(&scene),
826                    &scene.map,
827                    &scene.store,
828                    &scene.prior,
829                    radius,
830                )
831                .unwrap();
832            let actual = index.match_projected(
833                &scene.camera,
834                &scene.prior,
835                &scene.keypoints,
836                &packed,
837                radius,
838                GATES,
839            );
840            assert!(
841                actual.match_count > 50,
842                "radius {radius}: {}",
843                actual.match_count
844            );
845            // The builder counts every map landmark as a candidate; the
846            // index counts those projecting into the image.
847            assert_eq!(expected.candidate_landmark_count, 400);
848            assert!(actual.candidate_landmark_count < 400);
849            assert_eq!(
850                CorrespondenceSet {
851                    candidate_landmark_count: 0,
852                    ..actual
853                },
854                CorrespondenceSet {
855                    candidate_landmark_count: 0,
856                    ..expected
857                },
858                "radius {radius}"
859            );
860        }
861    }
862
863    #[test]
864    fn mismatched_lengths_never_match() {
865        let mut scene = scene();
866        scene.descriptors[0] = vec![1.0; 8];
867        let index = BinaryLandmarkIndex::new(&scene.map, &scene.store);
868        let packed = index.pack_query(&scene.descriptors);
869        let all = index.match_all(&scene.keypoints, &packed, GATES, 1);
870        assert!(all.query_indices.iter().all(|&q| q != 0));
871        let empty = index.match_all(&[], &index.pack_query::<Vec<f32>>(&[]), GATES, 4);
872        assert_eq!(empty.match_count, 0);
873    }
874
875    #[test]
876    fn a_radius_below_the_landmark_spacing_changes_nothing() {
877        let scene = scene();
878        let index = BinaryLandmarkIndex::new(&scene.map, &scene.store);
879        let packed = index.pack_query(&scene.descriptors);
880        let plain = index.match_all(&scene.keypoints, &packed, GATES, 1);
881        let index = index.with_duplicate_radius(1e-9);
882        for threads in [1, 3] {
883            assert_eq!(
884                index.match_all(&scene.keypoints, &packed, GATES, threads),
885                plain
886            );
887        }
888    }
889
890    /// Landmark 0 has `copies` duplicates (within 2 cm, the same
891    /// descriptor); landmark 1, far away, has the same descriptor as landmark
892    /// 2. One keypoint observes each of 0, 1 and 3, its descriptor 8 bits
893    /// off.
894    fn duplicates(copies: usize) -> (BinaryLandmarkIndex, Vec<Point2<f64>>, PackedDescriptors) {
895        let mut rng = Rng(7);
896        let mut map = VisualMap::new();
897        let mut store = LandmarkDescriptorStore::new();
898        let point = |x: f64| Point3::new(x, 0.0, 3.0);
899        let original = rng.bits();
900        let twin = rng.bits();
901        let lone = rng.bits();
902        let mut add = |id: u64, position: Point3<f64>, descriptor: Vec<f32>| {
903            map.landmarks.insert(id, Landmark::new(id, position));
904            store.insert(id, descriptor);
905        };
906        add(0, point(0.0), original.clone());
907        add(1, point(5.0), twin.clone());
908        add(2, point(-5.0), twin.clone());
909        add(3, point(2.0), lone.clone());
910        for copy in 0..copies {
911            let jitter = 0.002 * copy as f64;
912            add(100 + copy as u64, point(jitter), original.clone());
913        }
914        let index = BinaryLandmarkIndex::new(&map, &store);
915        let query = [original, twin, lone]
916            .iter()
917            .map(|descriptor| flip(descriptor, 8, &mut rng))
918            .collect::<Vec<_>>();
919        let packed = index.pack_query(&query);
920        let keypoints = vec![Point2::new(10.0, 10.0); 3];
921        (index, keypoints, packed)
922    }
923
924    fn matched_queries(set: &CorrespondenceSet) -> Vec<usize> {
925        set.query_indices.clone()
926    }
927
928    #[test]
929    fn duplicates_of_a_point_pass_the_ratio_test_within_the_radius() {
930        let (index, keypoints, packed) = duplicates(1);
931        // The duplicate defeats the ratio test; the twin descriptors of two
932        // distinct points do too.
933        let plain = index.match_all(&keypoints, &packed, GATES, 1);
934        assert_eq!(matched_queries(&plain), [2]);
935        let index = index.with_duplicate_radius(0.05);
936        let tolerant = index.match_all(&keypoints, &packed, GATES, 1);
937        assert_eq!(matched_queries(&tolerant), [0, 2]);
938        assert_eq!(tolerant.landmark_ids, [0, 3]);
939    }
940
941    #[test]
942    fn a_crowd_of_duplicates_falls_back_to_a_lower_bound() {
943        // More duplicates than candidates kept: no distinct second-best is
944        // seen. The last kept distance, equal to the best, bounds it from
945        // below, and the ratio test rejects rather than guess.
946        let (index, keypoints, packed) = duplicates(DISTINCT_CANDIDATES + 2);
947        let index = index.with_duplicate_radius(0.05);
948        let tolerant = index.match_all(&keypoints, &packed, GATES, 1);
949        assert_eq!(matched_queries(&tolerant), [2]);
950    }
951
952    /// `descriptor` with exactly the first `count` bits flipped.
953    fn flip_first(descriptor: &[f32], count: usize) -> Vec<f32> {
954        let mut flipped = descriptor.to_vec();
955        for value in flipped.iter_mut().take(count) {
956            *value = 1.0 - *value;
957        }
958        flipped
959    }
960
961    #[test]
962    fn extra_descriptors_match_their_landmark_and_never_compete_with_it() {
963        let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
964        let camera = Camera::pinhole(1, 640, 480, 400.0, 400.0, 320.0, 240.0);
965        let mut map = VisualMap::new();
966        let mut store = LandmarkDescriptorStore::new();
967        // Landmark 1: main descriptor `a`, an extra `b` far from it (another
968        // view), and an extra 2 bits from `a`. Landmark 2: `c`.
969        let (a, b, c) = (rng.bits(), rng.bits(), rng.bits());
970        let near_a = flip_first(&a, 2);
971        for (id, position, descriptor) in [
972            (1_u64, Point3::new(0.0, 0.0, 4.0), &a),
973            (2, Point3::new(0.5, 0.0, 4.0), &c),
974        ] {
975            map.landmarks.insert(id, Landmark::new(id, position));
976            store.insert(id, descriptor.clone());
977        }
978        let extra = vec![(1_u64, b.clone()), (1, near_a), (9, rng.bits())];
979        let plain = BinaryLandmarkIndex::new(&map, &store);
980        let index = plain.clone().with_extra_descriptors(&extra, 4);
981        assert_eq!(index.extra_descriptor_count(), 2);
982        assert_eq!(
983            plain
984                .clone()
985                .with_extra_descriptors(&extra, 1)
986                .extra_descriptor_count(),
987            1
988        );
989
990        // A keypoint seen from `b`'s view matches landmark 1 only with the
991        // extras; one 1 bit from `a` is not rejected by `a`'s own neighbour.
992        let keypoints = vec![Point2::new(320.0, 240.0), Point2::new(370.0, 240.0)];
993        let descriptors = vec![flip_first(&b, 5), flip_first(&a, 1)];
994        let query = index.pack_query(&descriptors);
995        let ids = |set: &CorrespondenceSet| set.landmark_ids.clone();
996        assert_eq!(
997            ids(&plain.match_all(&keypoints[..1], &query, GATES, 1)),
998            Vec::<u64>::new()
999        );
1000        let matched = index.match_all(&keypoints, &query, GATES, 1);
1001        assert_eq!(ids(&matched), vec![1, 1]);
1002        assert_eq!(matched.descriptor_matches[0].distance, 5.0);
1003        assert_eq!(matched.descriptor_matches[1].distance, 1.0);
1004        // The second best is landmark 2, not landmark 1's other descriptors.
1005        let second = matched.descriptor_matches[1].second_best_distance.unwrap();
1006        assert!(second > 70.0, "{second}");
1007        assert_eq!(
1008            ids(&index.match_among(&keypoints, &query, GATES, &[0, 1])),
1009            vec![1, 1]
1010        );
1011
1012        // Around the projections, the nearest of a landmark's descriptors
1013        // counts: the first keypoint (at landmark 1) matches it through `b`.
1014        let pose = Pose::identity();
1015        let projected = index.match_projected(&camera, &pose, &keypoints, &query, 30.0, GATES);
1016        assert_eq!(ids(&projected), vec![1]);
1017        assert_eq!(projected.query_indices, vec![0]);
1018        assert!(plain
1019            .match_projected(
1020                &camera,
1021                &pose,
1022                &keypoints,
1023                &plain.pack_query(&descriptors),
1024                30.0,
1025                GATES
1026            )
1027            .landmark_ids
1028            .is_empty());
1029    }
1030}