scirs2-vision 0.5.0

Computer vision module for SciRS2 (scirs2-vision)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
//! Feature descriptor matching algorithms
//!
//! Provides multiple matching strategies for both floating-point (SIFT-like)
//! and binary (ORB-like) descriptors:
//!
//! - **`BruteForce`** – exact O(n·m) exhaustive search
//! - **`FlannLike`** – approximate nearest-neighbour via a randomised
//!   kd-tree forest (float descriptors) or multi-probe LSH (binary descriptors)
//! - **`RatioTest`** – Lowe's ratio test: a match is retained only when the
//!   best-match distance is < `ratio × second-best-match distance`.
//!
//! All three methods return `(idx1, idx2, distance)` triples.

use crate::error::{Result, VisionError};
use crate::features::orb_like::{hamming_distance, OrbLikeDescriptor, DESC_WORDS};
use crate::features::sift_like::SIFTDescriptor;

// ─── Match method enum ────────────────────────────────────────────────────────

/// Strategy used to match feature descriptors.
#[derive(Debug, Clone)]
pub enum MatchMethod {
    /// Exhaustive brute-force matching (exact nearest neighbour).
    BruteForce,
    /// Approximate nearest-neighbour with a randomised forest / LSH index.
    FlannLike {
        /// Number of kd-trees (float) or hash tables (binary)
        num_trees: usize,
        /// Number of candidate checks per query
        checks: usize,
    },
    /// Lowe's ratio test: keep matches where `d_best / d_second < ratio`.
    RatioTest {
        /// Ratio threshold (typical value: 0.75)
        ratio: f64,
    },
}

impl Default for MatchMethod {
    fn default() -> Self {
        MatchMethod::RatioTest { ratio: 0.75 }
    }
}

// ─── Float descriptor matching (SIFT-like) ───────────────────────────────────

/// Match two sets of SIFT-like descriptors.
///
/// # Arguments
///
/// * `desc1` – Query descriptors
/// * `desc2` – Train descriptors
/// * `method` – Matching strategy
///
/// # Returns
///
/// Vector of `(idx1, idx2, distance)` triples sorted by distance ascending.
pub fn match_descriptors(
    desc1: &[SIFTDescriptor],
    desc2: &[SIFTDescriptor],
    method: &MatchMethod,
) -> Result<Vec<(usize, usize, f64)>> {
    if desc1.is_empty() || desc2.is_empty() {
        return Ok(Vec::new());
    }

    // Extract raw float vectors for matching
    let vecs1: Vec<&[f32]> = desc1.iter().map(|d| d.descriptor.as_slice()).collect();
    let vecs2: Vec<&[f32]> = desc2.iter().map(|d| d.descriptor.as_slice()).collect();

    let dim = vecs1[0].len();
    for v in vecs1.iter().chain(vecs2.iter()) {
        if v.len() != dim {
            return Err(VisionError::InvalidParameter(format!(
                "Descriptor dimension mismatch: expected {dim}, got {}",
                v.len()
            )));
        }
    }

    let matches = match method {
        MatchMethod::BruteForce => brute_force_float(&vecs1, &vecs2),
        MatchMethod::FlannLike { num_trees, checks } => {
            flann_like_float(&vecs1, &vecs2, *num_trees, *checks)
        }
        MatchMethod::RatioTest { ratio } => ratio_test_float(&vecs1, &vecs2, *ratio),
    };

    Ok(matches)
}

/// Exhaustive L2 nearest-neighbour.
fn brute_force_float(q: &[&[f32]], t: &[&[f32]]) -> Vec<(usize, usize, f64)> {
    let mut out = Vec::with_capacity(q.len());
    for (i, qi) in q.iter().enumerate() {
        let mut best_dist = f64::MAX;
        let mut best_j = 0usize;
        for (j, tj) in t.iter().enumerate() {
            let d = l2_distance_f32(qi, tj);
            if d < best_dist {
                best_dist = d;
                best_j = j;
            }
        }
        out.push((i, best_j, best_dist));
    }
    out.sort_unstable_by(|a, b| a.2.partial_cmp(&b.2).unwrap_or(std::cmp::Ordering::Equal));
    out
}

/// Approximate nearest-neighbour using a lightweight randomised kd-tree forest.
///
/// For each query, traversal with `checks` node evaluations is performed.
/// Falls back to brute-force for small descriptor sets.
fn flann_like_float(
    q: &[&[f32]],
    t: &[&[f32]],
    num_trees: usize,
    checks: usize,
) -> Vec<(usize, usize, f64)> {
    if t.len() < 16 {
        return brute_force_float(q, t);
    }

    // Build multiple randomised kd-trees
    let trees: Vec<KdNode> = (0..num_trees.max(1))
        .map(|seed| build_kdtree(t, seed as u64))
        .collect();

    let mut out = Vec::with_capacity(q.len());
    for (i, qi) in q.iter().enumerate() {
        let mut best_dist = f64::MAX;
        let mut best_j = 0usize;

        for tree in &trees {
            let (j, d) = search_kdtree(tree, qi, t, checks);
            if d < best_dist {
                best_dist = d;
                best_j = j;
            }
        }
        out.push((i, best_j, best_dist));
    }
    out.sort_unstable_by(|a, b| a.2.partial_cmp(&b.2).unwrap_or(std::cmp::Ordering::Equal));
    out
}

/// Lowe's ratio test: keep a match only if d1 / d2 < ratio.
fn ratio_test_float(q: &[&[f32]], t: &[&[f32]], ratio: f64) -> Vec<(usize, usize, f64)> {
    let mut out = Vec::new();
    for (i, qi) in q.iter().enumerate() {
        let mut first = (f64::MAX, 0usize);
        let mut second = f64::MAX;

        for (j, tj) in t.iter().enumerate() {
            let d = l2_distance_f32(qi, tj);
            if d < first.0 {
                second = first.0;
                first = (d, j);
            } else if d < second {
                second = d;
            }
        }

        if second > 0.0 && first.0 / second < ratio {
            out.push((i, first.1, first.0));
        }
    }
    out.sort_unstable_by(|a, b| a.2.partial_cmp(&b.2).unwrap_or(std::cmp::Ordering::Equal));
    out
}

// ─── Binary descriptor matching (ORB-like) ───────────────────────────────────

/// Match two sets of ORB-like binary descriptors using Hamming distance.
///
/// # Arguments
///
/// * `desc1` – Query descriptors
/// * `desc2` – Train descriptors
/// * `method` – Matching strategy
///
/// # Returns
///
/// Vector of `(idx1, idx2, distance)` where distance is the Hamming distance
/// (number of differing bits, 0–256).
pub fn match_binary_descriptors(
    desc1: &[OrbLikeDescriptor],
    desc2: &[OrbLikeDescriptor],
    method: &MatchMethod,
) -> Result<Vec<(usize, usize, f64)>> {
    if desc1.is_empty() || desc2.is_empty() {
        return Ok(Vec::new());
    }

    let refs1: Vec<&[u32; DESC_WORDS]> = desc1.iter().map(|d| &d.descriptor).collect();
    let refs2: Vec<&[u32; DESC_WORDS]> = desc2.iter().map(|d| &d.descriptor).collect();

    let matches = match method {
        MatchMethod::BruteForce => brute_force_binary(&refs1, &refs2),
        MatchMethod::FlannLike { checks, .. } => {
            // For binary: approximate via multi-table LSH
            lsh_binary(&refs1, &refs2, *checks)
        }
        MatchMethod::RatioTest { ratio } => ratio_test_binary(&refs1, &refs2, *ratio),
    };

    Ok(matches)
}

/// Exhaustive Hamming nearest-neighbour for binary descriptors.
fn brute_force_binary(
    q: &[&[u32; DESC_WORDS]],
    t: &[&[u32; DESC_WORDS]],
) -> Vec<(usize, usize, f64)> {
    let mut out = Vec::with_capacity(q.len());
    for (i, qi) in q.iter().enumerate() {
        let mut best = (u32::MAX, 0usize);
        for (j, tj) in t.iter().enumerate() {
            let d = hamming_distance(qi, tj);
            if d < best.0 {
                best = (d, j);
            }
        }
        out.push((i, best.1, best.0 as f64));
    }
    out.sort_unstable_by(|a, b| a.2.partial_cmp(&b.2).unwrap_or(std::cmp::Ordering::Equal));
    out
}

/// Approximate Hamming matching via a simple multi-probe approach:
/// for each query, randomly sub-sample `checks` train descriptors plus a
/// guided sweep of the top hash-bucket.
fn lsh_binary(
    q: &[&[u32; DESC_WORDS]],
    t: &[&[u32; DESC_WORDS]],
    checks: usize,
) -> Vec<(usize, usize, f64)> {
    if t.len() <= checks {
        return brute_force_binary(q, t);
    }

    // Build a simple random-projection table for approximate bucketing
    // Hash = XOR of selected descriptor words
    let bucket_count = (t.len() / 4).next_power_of_two().max(64);
    let mask = bucket_count - 1;

    // Assign train descriptors to buckets (based on first word XOR hash)
    let mut buckets: Vec<Vec<usize>> = vec![Vec::new(); bucket_count];
    for (j, tj) in t.iter().enumerate() {
        let hash = (tj[0] ^ tj[1].rotate_left(8) ^ tj[2].rotate_left(16)) as usize & mask;
        buckets[hash].push(j);
    }

    let mut out = Vec::with_capacity(q.len());
    for (i, qi) in q.iter().enumerate() {
        let query_hash = (qi[0] ^ qi[1].rotate_left(8) ^ qi[2].rotate_left(16)) as usize & mask;

        let mut candidates: Vec<usize> = buckets[query_hash].clone();
        // Also probe neighbouring buckets
        let nb1 = (query_hash + 1) & mask;
        let nb2 = (query_hash + bucket_count - 1) & mask;
        candidates.extend_from_slice(&buckets[nb1]);
        candidates.extend_from_slice(&buckets[nb2]);

        // Supplement with uniformly spaced samples if we have too few candidates
        if candidates.len() < checks {
            let step = t.len() / (checks - candidates.len()).max(1);
            for k in (0..t.len()).step_by(step.max(1)) {
                candidates.push(k);
            }
        }

        candidates.sort_unstable();
        candidates.dedup();

        let mut best = (u32::MAX, 0usize);
        for j in candidates {
            if j < t.len() {
                let d = hamming_distance(qi, t[j]);
                if d < best.0 {
                    best = (d, j);
                }
            }
        }

        out.push((i, best.1, best.0 as f64));
    }

    out.sort_unstable_by(|a, b| a.2.partial_cmp(&b.2).unwrap_or(std::cmp::Ordering::Equal));
    out
}

/// Lowe's ratio test for binary (Hamming) descriptors.
fn ratio_test_binary(
    q: &[&[u32; DESC_WORDS]],
    t: &[&[u32; DESC_WORDS]],
    ratio: f64,
) -> Vec<(usize, usize, f64)> {
    let mut out = Vec::new();
    for (i, qi) in q.iter().enumerate() {
        let mut first = (u32::MAX, 0usize);
        let mut second = u32::MAX;

        for (j, tj) in t.iter().enumerate() {
            let d = hamming_distance(qi, tj);
            if d < first.0 {
                second = first.0;
                first = (d, j);
            } else if d < second {
                second = d;
            }
        }

        if second > 0 {
            let r = first.0 as f64 / second as f64;
            if r < ratio {
                out.push((i, first.1, first.0 as f64));
            }
        }
    }
    out.sort_unstable_by(|a, b| a.2.partial_cmp(&b.2).unwrap_or(std::cmp::Ordering::Equal));
    out
}

// ─── Symmetric / cross-check filtering ───────────────────────────────────────

/// Filter a set of SIFT-like matches using symmetric (cross-check) validation.
///
/// Keeps only matches (i → j) where the reverse match (j → i) is also i.
/// This removes many spurious correspondences at the cost of slightly
/// fewer total matches.
pub fn symmetric_filter(
    desc1: &[SIFTDescriptor],
    desc2: &[SIFTDescriptor],
    method: &MatchMethod,
) -> Result<Vec<(usize, usize, f64)>> {
    let fwd = match_descriptors(desc1, desc2, method)?;
    let rev = match_descriptors(desc2, desc1, method)?;

    // Build reverse lookup: j → i
    let mut rev_map: std::collections::HashMap<usize, usize> =
        std::collections::HashMap::with_capacity(rev.len());
    for (j, i, _) in &rev {
        rev_map.insert(*j, *i);
    }

    let symmetric: Vec<(usize, usize, f64)> = fwd
        .into_iter()
        .filter(|(i, j, _)| rev_map.get(j).is_some_and(|&ri| ri == *i))
        .collect();

    Ok(symmetric)
}

// ─── kd-tree (float, randomised) ─────────────────────────────────────────────

/// Node in a randomised kd-tree.
enum KdNode {
    Leaf {
        indices: Vec<usize>,
    },
    Internal {
        axis: usize,
        split_val: f32,
        left: Box<KdNode>,
        right: Box<KdNode>,
    },
}

/// Build a randomised kd-tree over `vecs` (indexed by position).
fn build_kdtree(vecs: &[&[f32]], seed: u64) -> KdNode {
    let indices: Vec<usize> = (0..vecs.len()).collect();
    build_kdtree_rec(&indices, vecs, seed, 0)
}

fn build_kdtree_rec(indices: &[usize], vecs: &[&[f32]], seed: u64, depth: usize) -> KdNode {
    const LEAF_SIZE: usize = 8;
    if indices.len() <= LEAF_SIZE {
        return KdNode::Leaf {
            indices: indices.to_vec(),
        };
    }

    let dim = vecs[0].len();
    // Randomised axis selection: pick the axis with highest variance among a
    // random subset of 5 dimensions.
    let axis = choose_split_axis(indices, vecs, seed, depth, dim);

    // Split at the median
    let mut vals: Vec<f32> = indices.iter().map(|&i| vecs[i][axis]).collect();
    vals.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
    let split_val = vals[vals.len() / 2];

    let left_idx: Vec<usize> = indices
        .iter()
        .copied()
        .filter(|&i| vecs[i][axis] < split_val)
        .collect();
    let right_idx: Vec<usize> = indices
        .iter()
        .copied()
        .filter(|&i| vecs[i][axis] >= split_val)
        .collect();

    // Guard against degenerate splits
    if left_idx.is_empty() || right_idx.is_empty() {
        return KdNode::Leaf {
            indices: indices.to_vec(),
        };
    }

    KdNode::Internal {
        axis,
        split_val,
        left: Box::new(build_kdtree_rec(&left_idx, vecs, seed, depth + 1)),
        right: Box::new(build_kdtree_rec(&right_idx, vecs, seed, depth + 1)),
    }
}

fn choose_split_axis(
    indices: &[usize],
    vecs: &[&[f32]],
    seed: u64,
    depth: usize,
    dim: usize,
) -> usize {
    // Sample up to 5 random dimensions and pick the one with highest variance
    let n_sample = 5usize.min(dim);
    let mut rng_state = seed.wrapping_add(depth as u64 * 6_364_136_223_846_793_005);

    let sample_n = indices.len().min(32);

    let mut best_axis = 0usize;
    let mut best_var = f64::NEG_INFINITY;

    for _ in 0..n_sample {
        rng_state = rng_state
            .wrapping_mul(6_364_136_223_846_793_005)
            .wrapping_add(1_442_695_040_888_963_407);
        let axis = (rng_state >> 33) as usize % dim;

        // Compute variance of this axis over a subset
        let step = indices.len() / sample_n + 1;
        let sampled: Vec<f64> = indices
            .iter()
            .step_by(step)
            .take(sample_n)
            .map(|&i| vecs[i][axis] as f64)
            .collect();

        let n = sampled.len() as f64;
        if n < 2.0 {
            continue;
        }
        let mean = sampled.iter().sum::<f64>() / n;
        let var = sampled.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / n;

        if var > best_var {
            best_var = var;
            best_axis = axis;
        }
    }

    best_axis
}

/// Approximate nearest-neighbour search in a kd-tree with `checks` leaf evaluations.
fn search_kdtree(root: &KdNode, query: &[f32], vecs: &[&[f32]], checks: usize) -> (usize, f64) {
    let mut best = (f64::MAX, 0usize);
    let mut evals = 0usize;
    search_kdtree_rec(root, query, vecs, &mut best, &mut evals, checks);
    (best.1, best.0)
}

fn search_kdtree_rec(
    node: &KdNode,
    query: &[f32],
    vecs: &[&[f32]],
    best: &mut (f64, usize),
    evals: &mut usize,
    max_evals: usize,
) {
    if *evals >= max_evals {
        return;
    }

    match node {
        KdNode::Leaf { indices } => {
            for &i in indices {
                *evals += 1;
                let d = l2_distance_f32(query, vecs[i]);
                if d < best.0 {
                    *best = (d, i);
                }
                if *evals >= max_evals {
                    return;
                }
            }
        }
        KdNode::Internal {
            axis,
            split_val,
            left,
            right,
        } => {
            let q_val = query[*axis];
            let (near, far) = if q_val < *split_val {
                (left.as_ref(), right.as_ref())
            } else {
                (right.as_ref(), left.as_ref())
            };

            search_kdtree_rec(near, query, vecs, best, evals, max_evals);

            // Backtrack to far side if potentially useful
            let plane_dist = (q_val - split_val).powi(2) as f64;
            if plane_dist < best.0 && *evals < max_evals {
                search_kdtree_rec(far, query, vecs, best, evals, max_evals);
            }
        }
    }
}

// ─── Distance helpers ─────────────────────────────────────────────────────────

/// Squared L2 distance between two float descriptor vectors.
fn l2_distance_f32(a: &[f32], b: &[f32]) -> f64 {
    a.iter()
        .zip(b.iter())
        .map(|(&x, &y)| {
            let d = x - y;
            (d * d) as f64
        })
        .sum::<f64>()
        .sqrt()
}

// ─── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::features::sift_like::{Keypoint, SIFTDescriptor};

    fn make_sift_desc(id: usize, perturb: f32) -> SIFTDescriptor {
        let mut desc = vec![0.0f32; 128];
        desc[id % 128] = 1.0;
        // tiny perturbation so ratio test can differentiate
        desc[(id + 1) % 128] = perturb;
        // normalise
        let norm: f32 = desc.iter().map(|v| v * v).sum::<f32>().sqrt();
        for v in &mut desc {
            *v /= norm;
        }
        SIFTDescriptor {
            keypoint: Keypoint {
                x: id as f64,
                y: id as f64,
                scale: 1.0,
                orientation: 0.0,
                response: 1.0,
                octave: 0,
            },
            descriptor: desc,
        }
    }

    fn make_orb_desc(id: usize) -> OrbLikeDescriptor {
        let mut words = [0u32; DESC_WORDS];
        words[id % DESC_WORDS] = (id as u32).wrapping_mul(0x12345678);
        OrbLikeDescriptor {
            keypoint: crate::features::orb_like::OrbKeypoint {
                x: id as f64,
                y: id as f64,
                score: 1.0,
                orientation: 0.0,
                level: 0,
            },
            descriptor: words,
        }
    }

    #[test]
    fn test_brute_force_exact_match() {
        let descs: Vec<SIFTDescriptor> = (0..5).map(|i| make_sift_desc(i, 0.0)).collect();
        let matches = match_descriptors(&descs, &descs, &MatchMethod::BruteForce)
            .expect("match_descriptors should succeed");
        // Each descriptor should match itself (distance 0)
        for (i, j, d) in &matches {
            assert_eq!(i, j, "Self-match expected at index {i}");
            assert!(*d < 1e-6, "Self-match distance should be ~0, got {d}");
        }
    }

    #[test]
    fn test_ratio_test_returns_matches() {
        let q: Vec<SIFTDescriptor> = (0..4).map(|i| make_sift_desc(i, 0.01)).collect();
        let t: Vec<SIFTDescriptor> = (0..8).map(|i| make_sift_desc(i, 0.01)).collect();
        let m = match_descriptors(&q, &t, &MatchMethod::RatioTest { ratio: 0.9 })
            .expect("match_descriptors with ratio test should succeed");
        // Should return at least some matches
        assert!(!m.is_empty());
    }

    #[test]
    fn test_flann_like_consistent_with_brute_force_small() {
        // For a tiny set, FLANN should fall back to brute-force and give the same result
        let descs: Vec<SIFTDescriptor> = (0..5).map(|i| make_sift_desc(i, 0.0)).collect();
        let bf = match_descriptors(&descs, &descs, &MatchMethod::BruteForce)
            .expect("brute force match should succeed");
        let fl = match_descriptors(
            &descs,
            &descs,
            &MatchMethod::FlannLike {
                num_trees: 2,
                checks: 50,
            },
        )
        .expect("flann-like match should succeed");
        // Both should match each descriptor to itself
        assert_eq!(bf.len(), fl.len());
    }

    #[test]
    fn test_binary_brute_force() {
        let d: Vec<OrbLikeDescriptor> = (0..4).map(make_orb_desc).collect();
        let matches = match_binary_descriptors(&d, &d, &MatchMethod::BruteForce)
            .expect("match_binary_descriptors should succeed");
        for (i, j, dist) in &matches {
            assert_eq!(i, j, "Binary self-match expected");
            assert_eq!(*dist, 0.0, "Hamming self-distance should be 0");
        }
    }

    #[test]
    fn test_empty_match_set() {
        let empty: Vec<SIFTDescriptor> = Vec::new();
        let q: Vec<SIFTDescriptor> = (0..3).map(|i| make_sift_desc(i, 0.0)).collect();
        let m1 = match_descriptors(&empty, &q, &MatchMethod::BruteForce)
            .expect("match_descriptors should succeed with empty query");
        let m2 = match_descriptors(&q, &empty, &MatchMethod::BruteForce)
            .expect("match_descriptors should succeed with empty target");
        assert!(m1.is_empty());
        assert!(m2.is_empty());
    }

    #[test]
    fn test_symmetric_filter() {
        let descs: Vec<SIFTDescriptor> = (0..6).map(|i| make_sift_desc(i, 0.0)).collect();
        let sym = symmetric_filter(&descs, &descs, &MatchMethod::BruteForce)
            .expect("symmetric_filter should succeed");
        // All self-matches are symmetric
        for (i, j, d) in &sym {
            assert_eq!(i, j);
            assert!(*d < 1e-6);
        }
    }
}