Skip to main content

lib_jsl_geometry/algorithms/
hausdorff.rs

1//! The Hausdorff distance between point sets (SciPy's `scipy.spatial.distance.directed_hausdorff`).
2//!
3//! See the book entry [Rotation fitting, Procrustes analysis and Hausdorff distance](https://jwkunz.github.io/lib_jsl/book/geometry/alignment.html#the-hausdorff-distance).
4
5use lib_jsl_core::ErrorsJSL;
6
7/// The result of [`directed_hausdorff`]: the distance and the pair of points that realise it.
8#[derive(Clone, Copy, Debug, PartialEq)]
9#[non_exhaustive]
10pub struct DirectedHausdorff {
11    pub distance: f64,
12    /// The point of `u` farthest from `v`.
13    pub index_u: usize,
14    /// Its nearest point in `v`.
15    pub index_v: usize,
16}
17
18// ANCHOR: directed_hausdorff
19/// The directed Hausdorff distance `h(u, v) = max_{a ∈ u} min_{b ∈ v} ‖a − b‖` between point sets
20/// in any dimension (SciPy's `directed_hausdorff`), by Taha and Hanbury's early-break algorithm:
21/// the inner search over `v` stops as soon as some point is closer than the largest minimum found
22/// so far, since that `a` can no longer raise the maximum. SciPy shuffles the points first (with
23/// a fixed seed) to make early breaks likely; the library keeps the given order, which gives the
24/// same distance and, without ties, the same pair.
25pub fn directed_hausdorff(u: &[Vec<f64>], v: &[Vec<f64>]) -> Result<DirectedHausdorff, ErrorsJSL> {
26    let d = u.first().map_or(0, |p| p.len());
27    if u.is_empty() || v.is_empty() || d == 0 || u.iter().chain(v).any(|p| p.len() != d) {
28        return Err(ErrorsJSL::InvalidInputRange("directed_hausdorff: need non-empty point sets of one dimension"));
29    }
30    let (mut cmax, mut iu, mut iv) = (0.0f64, 0usize, 0usize);
31    for (i, a) in u.iter().enumerate() {
32        let (mut cmin, mut jmin, mut broke) = (f64::INFINITY, 0usize, false);
33        for (j, b) in v.iter().enumerate() {
34            let dist: f64 = a.iter().zip(b).map(|(x, y)| (x - y) * (x - y)).sum();
35            if dist < cmax {
36                broke = true;
37                break;
38            }
39            if dist < cmin {
40                cmin = dist;
41                jmin = j;
42            }
43        }
44        if !broke && cmin != f64::INFINITY && cmin > cmax {
45            cmax = cmin;
46            iu = i;
47            iv = jmin;
48        }
49    }
50    Ok(DirectedHausdorff { distance: cmax.sqrt(), index_u: iu, index_v: iv })
51}
52// ANCHOR_END: directed_hausdorff
53
54/// The (symmetric) Hausdorff distance `max(h(u, v), h(v, u))`.
55pub fn hausdorff_distance(u: &[Vec<f64>], v: &[Vec<f64>]) -> Result<f64, ErrorsJSL> {
56    Ok(directed_hausdorff(u, v)?.distance.max(directed_hausdorff(v, u)?.distance))
57}
58
59#[cfg(test)]
60mod tests {
61    use super::*;
62
63    #[test]
64    fn matches_the_definition() {
65        let u: Vec<Vec<f64>> = (0..30).map(|i| vec![(i as f64 * 0.37).sin(), (i as f64 * 0.91).cos(), i as f64 * 0.05]).collect();
66        let v: Vec<Vec<f64>> = (0..25).map(|i| vec![(i as f64 * 0.53).cos(), (i as f64 * 0.29).sin(), 0.7]).collect();
67        let r = directed_hausdorff(&u, &v).unwrap();
68        let dist = |a: &[f64], b: &[f64]| a.iter().zip(b).map(|(x, y)| (x - y) * (x - y)).sum::<f64>().sqrt();
69        let brute = u.iter().map(|a| v.iter().map(|b| dist(a, b)).fold(f64::INFINITY, f64::min)).fold(0.0, f64::max);
70        assert!((r.distance - brute).abs() < 1e-15);
71        assert!((dist(&u[r.index_u], &v[r.index_v]) - brute).abs() < 1e-15);
72        assert!(hausdorff_distance(&u, &v).unwrap() >= brute);
73    }
74}