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        self.match_among_threaded(keypoints, query, gates, landmarks, 1)
437    }
438
439    /// [`Self::match_among`] on `threads` threads (keypoints split in
440    /// order, so the result is the same).
441    pub fn match_among_threaded(
442        &self,
443        keypoints: &[Point2<f64>],
444        query: &PackedDescriptors,
445        gates: BinaryMatchGates,
446        landmarks: &[usize],
447        threads: usize,
448    ) -> CorrespondenceSet {
449        let count = keypoints.len().min(query.len());
450        let match_range = |range: std::ops::Range<usize>| {
451            range
452                .filter_map(|query_index| {
453                    let bits = query.get(query_index)?;
454                    let candidates = landmarks.iter().flat_map(|&landmark| {
455                        self.landmark_rows(landmark)
456                            .map(move |train| (landmark, train))
457                    });
458                    let (distance, landmark, second) =
459                        self.search(bits, candidates).accept(gates)?;
460                    Some(descriptor_match(query_index, landmark, distance, second))
461                })
462                .collect::<Vec<_>>()
463        };
464        let threads = threads.clamp(1, count.max(1));
465        let matches = if threads == 1 {
466            match_range(0..count)
467        } else {
468            let chunk = count.div_ceil(threads);
469            std::thread::scope(|scope| {
470                let handles = (0..count)
471                    .step_by(chunk)
472                    .map(|start| {
473                        let match_range = &match_range;
474                        scope.spawn(move || match_range(start..(start + chunk).min(count)))
475                    })
476                    .collect::<Vec<_>>();
477                handles
478                    .into_iter()
479                    .flat_map(|handle| handle.join().expect("matcher thread panicked"))
480                    .collect()
481            })
482        };
483        self.correspondence_set(keypoints, matches, landmarks.len())
484    }
485
486    /// Indices (into this index) of the landmarks within `radius` of
487    /// `center`, in index order: the candidates of a radius search around a
488    /// pose prior, for [`Self::match_among`].
489    pub fn landmarks_within(&self, center: &Point3<f64>, radius: f64) -> Vec<usize> {
490        let r2 = radius * radius;
491        self.positions
492            .iter()
493            .enumerate()
494            .filter(|(_, p)| (*p - center).norm_squared() <= r2)
495            .map(|(i, _)| i)
496            .collect()
497    }
498
499    /// The nearest of `candidates` (landmark indices with their packed
500    /// descriptors, a landmark possibly more than once) to `bits`, with the
501    /// duplicate radius applied.
502    fn search<'a>(
503        &self,
504        bits: &[u64],
505        candidates: impl Iterator<Item = (usize, &'a [u64])>,
506    ) -> Nearest {
507        match self.duplicate_radius_m {
508            None => {
509                let mut nearest = Nearest::new();
510                for (landmark, train) in candidates {
511                    nearest.offer(hamming(bits, train), landmark);
512                }
513                nearest
514            }
515            Some(radius) => {
516                let mut nearest = NearestDistinct::new();
517                for (landmark, train) in candidates {
518                    nearest.offer(hamming(bits, train), landmark);
519                }
520                nearest.collapse(&self.positions, radius)
521            }
522        }
523    }
524
525    /// Index of landmark `id` in this index, if it has a descriptor.
526    pub fn landmark_index(&self, id: LandmarkId) -> Option<usize> {
527        self.landmark_ids.binary_search(&id).ok()
528    }
529
530    /// The packed descriptor of the landmark at `index`.
531    pub(crate) fn landmark_descriptor(&self, index: usize) -> Option<&[u64]> {
532        self.descriptors.get(index)
533    }
534
535    /// Projection-guided matching: each landmark is projected with
536    /// `pose_prior` and its descriptors (the nearest of them) compared only
537    /// with the keypoints
538    /// within `radius_px` of the projection (best and second best among
539    /// them, gated by `gates`); overlapping windows are then resolved
540    /// one-to-one, lowest distance first. The same correspondences as
541    /// [`ProjectionCorrespondenceBuilder::build_with_pose_prior`](crate::ProjectionCorrespondenceBuilder::build_with_pose_prior)
542    /// with a [`HammingMatcher`](visloc_vision::matching::HammingMatcher) of
543    /// the same gates, except that landmarks behind the camera (`z <= 0`)
544    /// are skipped before projecting.
545    pub fn match_projected(
546        &self,
547        camera: &Camera,
548        pose_prior: &Pose,
549        keypoints: &[Point2<f64>],
550        query: &PackedDescriptors,
551        radius_px: f64,
552        gates: BinaryMatchGates,
553    ) -> CorrespondenceSet {
554        let count = keypoints.len().min(query.len());
555        let grid = KeypointGrid::new(&keypoints[..count], radius_px);
556        let (width, height) = (f64::from(camera.width), f64::from(camera.height));
557        let radius_squared = radius_px * radius_px;
558        let mut candidate_count = 0;
559        let mut proposals = Vec::new();
560        for (landmark, position) in self.positions.iter().enumerate() {
561            if self.landmark_rows(landmark).next().is_none() {
562                continue;
563            }
564            let point_camera = pose_prior.transform_world_point(position);
565            if point_camera.z <= 0.0 {
566                continue;
567            }
568            let Some(projected) = camera.project(&point_camera) else {
569                continue;
570            };
571            if projected.x < 0.0
572                || projected.y < 0.0
573                || projected.x >= width
574                || projected.y >= height
575            {
576                continue;
577            }
578            candidate_count += 1;
579            // Window keypoints in ascending index order, as the builder's
580            // linear scan visits them.
581            let mut nearest = Nearest::new();
582            for keypoint in grid.within(keypoints, projected, radius_squared) {
583                if let Some(bits) = query.get(keypoint) {
584                    let distance = self
585                        .landmark_rows(landmark)
586                        .map(|train| hamming(train, bits))
587                        .min()
588                        .unwrap_or(u32::MAX);
589                    nearest.offer(distance, keypoint);
590                }
591            }
592            if let Some((distance, keypoint, second)) = nearest.accept(gates) {
593                proposals.push(descriptor_match(keypoint, landmark, distance, second));
594            }
595        }
596        // Landmark index order is landmark-id order, so this is the
597        // builder's (distance, landmark id, keypoint) order.
598        proposals.sort_by(|a, b| {
599            a.distance
600                .total_cmp(&b.distance)
601                .then_with(|| a.train_index.cmp(&b.train_index))
602                .then_with(|| a.query_index.cmp(&b.query_index))
603        });
604        let mut used_keypoints = HashSet::new();
605        let mut used_landmarks = HashSet::new();
606        proposals.retain(|m| {
607            used_keypoints.insert(m.query_index) && used_landmarks.insert(m.train_index)
608        });
609        self.correspondence_set(keypoints, proposals, candidate_count)
610    }
611
612    fn correspondence_set(
613        &self,
614        keypoints: &[Point2<f64>],
615        matches: Vec<DescriptorMatch>,
616        candidate_landmark_count: usize,
617    ) -> CorrespondenceSet {
618        CorrespondenceSet {
619            correspondences: matches
620                .iter()
621                .map(|m| Correspondence2D3D {
622                    point2d: keypoints[m.query_index],
623                    point3d: self.positions[m.train_index],
624                    confidence: None,
625                })
626                .collect(),
627            query_indices: matches.iter().map(|m| m.query_index).collect(),
628            landmark_ids: matches
629                .iter()
630                .map(|m| self.landmark_ids[m.train_index])
631                .collect(),
632            candidate_landmark_count,
633            match_count: matches.len(),
634            descriptor_matches: matches,
635        }
636    }
637}
638
639/// Keypoints bucketed into square cells of the search radius, so a window
640/// lookup visits only the 3x3 cells around the query point.
641struct KeypointGrid {
642    origin: Point2<f64>,
643    cell: f64,
644    columns: isize,
645    rows: isize,
646    /// Keypoint indices per cell, ascending.
647    cells: Vec<Vec<usize>>,
648}
649
650impl KeypointGrid {
651    fn new(keypoints: &[Point2<f64>], radius_px: f64) -> Self {
652        let finite = || {
653            keypoints
654                .iter()
655                .filter(|p| p.x.is_finite() && p.y.is_finite())
656        };
657        let fold = |init: f64, pick: fn(&Point2<f64>) -> f64, f: fn(f64, f64) -> f64| {
658            finite().map(pick).fold(init, f)
659        };
660        let origin = Point2::new(
661            fold(f64::INFINITY, |p| p.x, f64::min).min(0.0),
662            fold(f64::INFINITY, |p| p.y, f64::min).min(0.0),
663        );
664        let extent = Point2::new(
665            fold(0.0, |p| p.x, f64::max) - origin.x,
666            fold(0.0, |p| p.y, f64::max) - origin.y,
667        );
668        // Any cell at least the radius wide keeps every window inside 3x3
669        // cells; the cap only bounds the grid for far-flung coordinates.
670        let cell = radius_px.max(1.0).max(extent.x.max(extent.y) / 1024.0);
671        let columns = (extent.x / cell) as isize + 1;
672        let rows = (extent.y / cell) as isize + 1;
673        let mut grid = Self {
674            origin,
675            cell,
676            columns,
677            rows,
678            cells: vec![Vec::new(); (columns * rows) as usize],
679        };
680        for (index, keypoint) in keypoints.iter().enumerate() {
681            if keypoint.x.is_finite() && keypoint.y.is_finite() {
682                let (column, row) = grid.cell_of(keypoint);
683                grid.cells[(row * columns + column) as usize].push(index);
684            }
685        }
686        grid
687    }
688
689    /// The (possibly out-of-grid) cell of a point.
690    fn cell_of(&self, point: &Point2<f64>) -> (isize, isize) {
691        (
692            ((point.x - self.origin.x) / self.cell).floor() as isize,
693            ((point.y - self.origin.y) / self.cell).floor() as isize,
694        )
695    }
696
697    /// Indices of the keypoints within `sqrt(radius_squared)` of `center`,
698    /// ascending.
699    fn within(
700        &self,
701        keypoints: &[Point2<f64>],
702        center: Point2<f64>,
703        radius_squared: f64,
704    ) -> Vec<usize> {
705        let (column, row) = self.cell_of(&center);
706        let mut found = Vec::new();
707        for r in (row - 1).max(0)..=(row + 1).min(self.rows - 1) {
708            for c in (column - 1).max(0)..=(column + 1).min(self.columns - 1) {
709                for &index in &self.cells[(r * self.columns + c) as usize] {
710                    let d = keypoints[index] - center;
711                    if d.x * d.x + d.y * d.y <= radius_squared {
712                        found.push(index);
713                    }
714                }
715            }
716        }
717        found.sort_unstable();
718        found
719    }
720}
721
722#[cfg(test)]
723mod tests {
724    use nalgebra::{UnitQuaternion, Vector3};
725    use visloc_core::types::Landmark;
726    use visloc_vision::matching::HammingMatcher;
727
728    use super::*;
729    use crate::{CorrespondenceBuilder, ProjectionCorrespondenceBuilder};
730
731    struct Rng(u64);
732
733    impl Rng {
734        fn next(&mut self) -> u64 {
735            self.0 ^= self.0 << 13;
736            self.0 ^= self.0 >> 7;
737            self.0 ^= self.0 << 17;
738            self.0
739        }
740
741        fn unit(&mut self) -> f64 {
742            (self.next() % 1_000_000) as f64 / 1_000_000.0
743        }
744
745        fn bits(&mut self) -> Vec<f32> {
746            (0..256).map(|_| (self.next() & 1) as f32).collect()
747        }
748    }
749
750    fn flip(descriptor: &[f32], count: usize, rng: &mut Rng) -> Vec<f32> {
751        let mut flipped = descriptor.to_vec();
752        for _ in 0..count {
753            let bit = (rng.next() % 256) as usize;
754            flipped[bit] = 1.0 - flipped[bit];
755        }
756        flipped
757    }
758
759    struct Scene {
760        map: VisualMap,
761        store: LandmarkDescriptorStore,
762        camera: Camera,
763        prior: Pose,
764        keypoints: Vec<Point2<f64>>,
765        descriptors: Vec<Vec<f32>>,
766    }
767
768    /// Landmarks in front of and behind a camera; keypoints at the true
769    /// projections of most visible ones (descriptors a few bits off, some
770    /// landmarks sharing a descriptor so ratio tests bite) plus clutter. The
771    /// prior is off by a few pixels.
772    fn scene() -> Scene {
773        let mut rng = Rng(0x2545_f491_4f6c_dd1d);
774        let camera = Camera::pinhole(1, 640, 480, 400.0, 400.0, 320.0, 240.0);
775        let truth = Pose::identity();
776        let prior = Pose::from_world_to_camera(
777            UnitQuaternion::from_euler_angles(0.004, -0.003, 0.002),
778            Vector3::new(0.01, -0.02, 0.0),
779        );
780        let mut map = VisualMap::new();
781        let mut store = LandmarkDescriptorStore::new();
782        let mut keypoints = Vec::new();
783        let mut descriptors = Vec::new();
784        let mut shared = rng.bits();
785        for id in 0..400_u64 {
786            let position = Point3::new(
787                rng.unit() * 8.0 - 4.0,
788                rng.unit() * 6.0 - 3.0,
789                if id % 10 == 0 {
790                    -2.0
791                } else {
792                    1.5 + rng.unit() * 6.0
793                },
794            );
795            if id % 37 == 0 {
796                shared = rng.bits();
797            }
798            let descriptor = if id % 7 == 0 {
799                shared.clone()
800            } else {
801                rng.bits()
802            };
803            map.landmarks.insert(id, Landmark::new(id, position));
804            store.insert(id, descriptor.clone());
805            if let Some(pixel) = camera.project(&truth.transform_world_point(&position)) {
806                if position.z > 0.0 && id % 5 != 0 {
807                    keypoints.push(pixel + nalgebra::Vector2::new(rng.unit(), rng.unit()));
808                    descriptors.push(flip(&descriptor, (rng.next() % 30) as usize, &mut rng));
809                }
810            }
811        }
812        for _ in 0..150 {
813            keypoints.push(Point2::new(rng.unit() * 640.0, rng.unit() * 480.0));
814            descriptors.push(rng.bits());
815        }
816        // Interleave clutter with real keypoints.
817        let mut order = (0..keypoints.len()).collect::<Vec<_>>();
818        order.sort_by_key(|i| (i * 7919) % keypoints.len());
819        Scene {
820            map,
821            store,
822            camera,
823            prior,
824            keypoints: order.iter().map(|&i| keypoints[i]).collect(),
825            descriptors: order.iter().map(|&i| descriptors[i].clone()).collect(),
826        }
827    }
828
829    fn query(scene: &Scene) -> visloc_core::types::QueryImage {
830        visloc_core::types::QueryImage {
831            camera: scene.camera.clone(),
832            keypoints: scene.keypoints.clone(),
833            descriptors: scene.descriptors.clone(),
834        }
835    }
836
837    const GATES: BinaryMatchGates = BinaryMatchGates {
838        max_distance: 70,
839        ratio: Some(0.8),
840    };
841
842    fn hamming_matcher() -> HammingMatcher {
843        HammingMatcher {
844            max_distance: GATES.max_distance,
845            ratio: GATES.ratio,
846        }
847    }
848
849    #[test]
850    fn global_matching_equals_the_correspondence_builder() {
851        let scene = scene();
852        let index = BinaryLandmarkIndex::new(&scene.map, &scene.store);
853        assert_eq!(index.len(), 400);
854        let expected = CorrespondenceBuilder::new(hamming_matcher())
855            .build(&query(&scene), &scene.map, &scene.store)
856            .unwrap();
857        assert!(expected.match_count > 100, "{}", expected.match_count);
858        let packed = index.pack_query(&scene.descriptors);
859        for threads in [1, 3] {
860            let actual = index.match_all(&scene.keypoints, &packed, GATES, threads);
861            assert_eq!(actual, expected, "threads={threads}");
862        }
863    }
864
865    #[test]
866    fn projection_matching_equals_the_projection_builder() {
867        let scene = scene();
868        let index = BinaryLandmarkIndex::new(&scene.map, &scene.store);
869        let packed = index.pack_query(&scene.descriptors);
870        for radius in [4.0, 12.0, 40.0] {
871            let expected = ProjectionCorrespondenceBuilder::new(hamming_matcher())
872                .build_with_pose_prior(
873                    &query(&scene),
874                    &scene.map,
875                    &scene.store,
876                    &scene.prior,
877                    radius,
878                )
879                .unwrap();
880            let actual = index.match_projected(
881                &scene.camera,
882                &scene.prior,
883                &scene.keypoints,
884                &packed,
885                radius,
886                GATES,
887            );
888            assert!(
889                actual.match_count > 50,
890                "radius {radius}: {}",
891                actual.match_count
892            );
893            // The builder counts every map landmark as a candidate; the
894            // index counts those projecting into the image.
895            assert_eq!(expected.candidate_landmark_count, 400);
896            assert!(actual.candidate_landmark_count < 400);
897            assert_eq!(
898                CorrespondenceSet {
899                    candidate_landmark_count: 0,
900                    ..actual
901                },
902                CorrespondenceSet {
903                    candidate_landmark_count: 0,
904                    ..expected
905                },
906                "radius {radius}"
907            );
908        }
909    }
910
911    #[test]
912    fn mismatched_lengths_never_match() {
913        let mut scene = scene();
914        scene.descriptors[0] = vec![1.0; 8];
915        let index = BinaryLandmarkIndex::new(&scene.map, &scene.store);
916        let packed = index.pack_query(&scene.descriptors);
917        let all = index.match_all(&scene.keypoints, &packed, GATES, 1);
918        assert!(all.query_indices.iter().all(|&q| q != 0));
919        let empty = index.match_all(&[], &index.pack_query::<Vec<f32>>(&[]), GATES, 4);
920        assert_eq!(empty.match_count, 0);
921    }
922
923    #[test]
924    fn a_radius_below_the_landmark_spacing_changes_nothing() {
925        let scene = scene();
926        let index = BinaryLandmarkIndex::new(&scene.map, &scene.store);
927        let packed = index.pack_query(&scene.descriptors);
928        let plain = index.match_all(&scene.keypoints, &packed, GATES, 1);
929        let index = index.with_duplicate_radius(1e-9);
930        for threads in [1, 3] {
931            assert_eq!(
932                index.match_all(&scene.keypoints, &packed, GATES, threads),
933                plain
934            );
935        }
936    }
937
938    /// Landmark 0 has `copies` duplicates (within 2 cm, the same
939    /// descriptor); landmark 1, far away, has the same descriptor as landmark
940    /// 2. One keypoint observes each of 0, 1 and 3, its descriptor 8 bits
941    /// off.
942    fn duplicates(copies: usize) -> (BinaryLandmarkIndex, Vec<Point2<f64>>, PackedDescriptors) {
943        let mut rng = Rng(7);
944        let mut map = VisualMap::new();
945        let mut store = LandmarkDescriptorStore::new();
946        let point = |x: f64| Point3::new(x, 0.0, 3.0);
947        let original = rng.bits();
948        let twin = rng.bits();
949        let lone = rng.bits();
950        let mut add = |id: u64, position: Point3<f64>, descriptor: Vec<f32>| {
951            map.landmarks.insert(id, Landmark::new(id, position));
952            store.insert(id, descriptor);
953        };
954        add(0, point(0.0), original.clone());
955        add(1, point(5.0), twin.clone());
956        add(2, point(-5.0), twin.clone());
957        add(3, point(2.0), lone.clone());
958        for copy in 0..copies {
959            let jitter = 0.002 * copy as f64;
960            add(100 + copy as u64, point(jitter), original.clone());
961        }
962        let index = BinaryLandmarkIndex::new(&map, &store);
963        let query = [original, twin, lone]
964            .iter()
965            .map(|descriptor| flip(descriptor, 8, &mut rng))
966            .collect::<Vec<_>>();
967        let packed = index.pack_query(&query);
968        let keypoints = vec![Point2::new(10.0, 10.0); 3];
969        (index, keypoints, packed)
970    }
971
972    fn matched_queries(set: &CorrespondenceSet) -> Vec<usize> {
973        set.query_indices.clone()
974    }
975
976    #[test]
977    fn duplicates_of_a_point_pass_the_ratio_test_within_the_radius() {
978        let (index, keypoints, packed) = duplicates(1);
979        // The duplicate defeats the ratio test; the twin descriptors of two
980        // distinct points do too.
981        let plain = index.match_all(&keypoints, &packed, GATES, 1);
982        assert_eq!(matched_queries(&plain), [2]);
983        let index = index.with_duplicate_radius(0.05);
984        let tolerant = index.match_all(&keypoints, &packed, GATES, 1);
985        assert_eq!(matched_queries(&tolerant), [0, 2]);
986        assert_eq!(tolerant.landmark_ids, [0, 3]);
987    }
988
989    #[test]
990    fn a_crowd_of_duplicates_falls_back_to_a_lower_bound() {
991        // More duplicates than candidates kept: no distinct second-best is
992        // seen. The last kept distance, equal to the best, bounds it from
993        // below, and the ratio test rejects rather than guess.
994        let (index, keypoints, packed) = duplicates(DISTINCT_CANDIDATES + 2);
995        let index = index.with_duplicate_radius(0.05);
996        let tolerant = index.match_all(&keypoints, &packed, GATES, 1);
997        assert_eq!(matched_queries(&tolerant), [2]);
998    }
999
1000    /// `descriptor` with exactly the first `count` bits flipped.
1001    fn flip_first(descriptor: &[f32], count: usize) -> Vec<f32> {
1002        let mut flipped = descriptor.to_vec();
1003        for value in flipped.iter_mut().take(count) {
1004            *value = 1.0 - *value;
1005        }
1006        flipped
1007    }
1008
1009    #[test]
1010    fn extra_descriptors_match_their_landmark_and_never_compete_with_it() {
1011        let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
1012        let camera = Camera::pinhole(1, 640, 480, 400.0, 400.0, 320.0, 240.0);
1013        let mut map = VisualMap::new();
1014        let mut store = LandmarkDescriptorStore::new();
1015        // Landmark 1: main descriptor `a`, an extra `b` far from it (another
1016        // view), and an extra 2 bits from `a`. Landmark 2: `c`.
1017        let (a, b, c) = (rng.bits(), rng.bits(), rng.bits());
1018        let near_a = flip_first(&a, 2);
1019        for (id, position, descriptor) in [
1020            (1_u64, Point3::new(0.0, 0.0, 4.0), &a),
1021            (2, Point3::new(0.5, 0.0, 4.0), &c),
1022        ] {
1023            map.landmarks.insert(id, Landmark::new(id, position));
1024            store.insert(id, descriptor.clone());
1025        }
1026        let extra = vec![(1_u64, b.clone()), (1, near_a), (9, rng.bits())];
1027        let plain = BinaryLandmarkIndex::new(&map, &store);
1028        let index = plain.clone().with_extra_descriptors(&extra, 4);
1029        assert_eq!(index.extra_descriptor_count(), 2);
1030        assert_eq!(
1031            plain
1032                .clone()
1033                .with_extra_descriptors(&extra, 1)
1034                .extra_descriptor_count(),
1035            1
1036        );
1037
1038        // A keypoint seen from `b`'s view matches landmark 1 only with the
1039        // extras; one 1 bit from `a` is not rejected by `a`'s own neighbour.
1040        let keypoints = vec![Point2::new(320.0, 240.0), Point2::new(370.0, 240.0)];
1041        let descriptors = vec![flip_first(&b, 5), flip_first(&a, 1)];
1042        let query = index.pack_query(&descriptors);
1043        let ids = |set: &CorrespondenceSet| set.landmark_ids.clone();
1044        assert_eq!(
1045            ids(&plain.match_all(&keypoints[..1], &query, GATES, 1)),
1046            Vec::<u64>::new()
1047        );
1048        let matched = index.match_all(&keypoints, &query, GATES, 1);
1049        assert_eq!(ids(&matched), vec![1, 1]);
1050        assert_eq!(matched.descriptor_matches[0].distance, 5.0);
1051        assert_eq!(matched.descriptor_matches[1].distance, 1.0);
1052        // The second best is landmark 2, not landmark 1's other descriptors.
1053        let second = matched.descriptor_matches[1].second_best_distance.unwrap();
1054        assert!(second > 70.0, "{second}");
1055        assert_eq!(
1056            ids(&index.match_among(&keypoints, &query, GATES, &[0, 1])),
1057            vec![1, 1]
1058        );
1059
1060        // Around the projections, the nearest of a landmark's descriptors
1061        // counts: the first keypoint (at landmark 1) matches it through `b`.
1062        let pose = Pose::identity();
1063        let projected = index.match_projected(&camera, &pose, &keypoints, &query, 30.0, GATES);
1064        assert_eq!(ids(&projected), vec![1]);
1065        assert_eq!(projected.query_indices, vec![0]);
1066        assert!(plain
1067            .match_projected(
1068                &camera,
1069                &pose,
1070                &keypoints,
1071                &plain.pack_query(&descriptors),
1072                30.0,
1073                GATES
1074            )
1075            .landmark_ids
1076            .is_empty());
1077    }
1078}