ifc_lite_diff/
mutual_nearest.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5use crate::geometry_compare::centre_distance;
6
7#[derive(Debug, Clone, Copy, PartialEq)]
8pub struct NearestPair { pub base: usize, pub head: usize, pub distance: f64 }
9
10fn unique_nearest(
11    from: &[[f64; 3]], to: &[[f64; 3]], retired_from: &[bool], retired_to: &[bool], margin: f64,
12) -> Vec<Option<usize>> {
13    from.iter().enumerate().map(|(i, point)| {
14        if retired_from[i] { return None; }
15        let mut best_index = None;
16        let mut best = f64::INFINITY;
17        let mut second = f64::INFINITY;
18        for (j, other) in to.iter().enumerate() {
19            if retired_to[j] { continue; }
20            let distance = centre_distance(*point, *other);
21            if distance < best {
22                second = best;
23                best = distance;
24                best_index = Some(j);
25            } else if distance < second { second = distance; }
26        }
27        if best < second && best * margin <= second { best_index } else { None }
28    }).collect()
29}
30
31/// A veto remains in the candidate pool. Exact ties abstain; every successful
32/// round retires at least one entity on each side, so termination is bounded.
33pub fn mutual_nearest_pairs(
34    base: &[[f64; 3]], head: &[[f64; 3]], max_distance: f64,
35    accept: impl Fn(usize, usize) -> bool, margin_ratio: f64,
36) -> Vec<NearestPair> {
37    let mut pairs = Vec::new();
38    let mut retired_base = vec![false; base.len()];
39    let mut retired_head = vec![false; head.len()];
40    loop {
41        let nearest_head = unique_nearest(base, head, &retired_base, &retired_head, margin_ratio);
42        let nearest_base = unique_nearest(head, base, &retired_head, &retired_base, margin_ratio);
43        let mut round = Vec::new();
44        for (b, point) in base.iter().enumerate() {
45            if retired_base[b] { continue; }
46            let Some(h) = nearest_head[b] else { continue };
47            if nearest_base[h] != Some(b) { continue; }
48            let distance = centre_distance(*point, head[h]);
49            // A comparison written this way also refuses NaN caps, like JS.
50            if distance.partial_cmp(&max_distance).is_none_or(|order| order.is_gt()) || !accept(b, h) { continue; }
51            round.push(NearestPair { base: b, head: h, distance });
52        }
53        if round.is_empty() { break; }
54        for pair in round {
55            retired_base[pair.base] = true;
56            retired_head[pair.head] = true;
57            pairs.push(pair);
58        }
59    }
60    pairs.sort_by_key(|pair| pair.base);
61    pairs
62}