Skip to main content

spatialrust_metrics/
distance.rs

1//! Chamfer and Hausdorff distances between two point clouds.
2
3use spatialrust_core::{
4    HasPositions3, PointCloud, SpatialError, SpatialResult, DEFAULT_SPATIAL_TENSOR_CHUNK_SIZE,
5};
6use spatialrust_search::{parallel_worker_count, KdTree, NearestNeighborIndex};
7
8/// A bundle of directed and symmetric cloud-to-cloud distance statistics.
9///
10/// "Directed" means nearest-neighbor distances from one cloud to the other; the
11/// metrics are not symmetric on their own, so both directions are reported.
12#[derive(Clone, Copy, Debug, PartialEq)]
13pub struct CloudDistances {
14    /// Mean squared NN distance from `a` to `b`.
15    pub mean_sq_a_to_b: f64,
16    /// Mean squared NN distance from `b` to `a`.
17    pub mean_sq_b_to_a: f64,
18    /// Largest NN distance from `a` to `b` (directed Hausdorff).
19    pub max_a_to_b: f64,
20    /// Largest NN distance from `b` to `a` (directed Hausdorff).
21    pub max_b_to_a: f64,
22}
23
24impl CloudDistances {
25    /// Symmetric Chamfer distance: the sum of the two mean squared NN distances.
26    #[must_use]
27    pub fn chamfer(&self) -> f64 {
28        self.mean_sq_a_to_b + self.mean_sq_b_to_a
29    }
30
31    /// Symmetric Hausdorff distance: the larger of the two directed maxima.
32    #[must_use]
33    pub fn hausdorff(&self) -> f64 {
34        self.max_a_to_b.max(self.max_b_to_a)
35    }
36}
37
38/// Computes directed NN distance statistics between `a` and `b` in both
39/// directions with a single KD-tree per side.
40///
41/// Large query sides share their target tree across bounded scoped CPU workers.
42/// A reusable window holds at most one default point chunk per worker. Distance
43/// accumulation retains input order; small/one-worker sides remain serial.
44pub fn cloud_distances(a: &PointCloud, b: &PointCloud) -> SpatialResult<CloudDistances> {
45    cloud_distances_with_workers(
46        a,
47        b,
48        parallel_worker_count(a.len()),
49        parallel_worker_count(b.len()),
50    )
51}
52
53fn cloud_distances_with_workers(
54    a: &PointCloud,
55    b: &PointCloud,
56    workers_a: usize,
57    workers_b: usize,
58) -> SpatialResult<CloudDistances> {
59    if a.is_empty() || b.is_empty() {
60        return Err(SpatialError::InvalidArgument("both clouds must be non-empty".to_owned()));
61    }
62    let (ax, ay, az) = a.positions3()?;
63    let (bx, by, bz) = b.positions3()?;
64
65    let tree_b = KdTree::from_slices(bx, by, bz);
66    let tree_a = KdTree::from_slices(ax, ay, az);
67
68    let (mean_sq_a_to_b, max_a_to_b) = directed(ax, ay, az, &tree_b, workers_a);
69    let (mean_sq_b_to_a, max_b_to_a) = directed(bx, by, bz, &tree_a, workers_b);
70
71    Ok(CloudDistances { mean_sq_a_to_b, mean_sq_b_to_a, max_a_to_b, max_b_to_a })
72}
73
74/// Mean squared and max NN distance from each query point to `target`.
75fn directed(x: &[f32], y: &[f32], z: &[f32], target: &KdTree, workers: usize) -> (f64, f64) {
76    let workers = workers.max(1).min(x.len().max(1));
77    if workers == 1 {
78        return directed_serial(x, y, z, target);
79    }
80    // Preserve Some(NaN) versus None, including the original sum/max behavior.
81    // Reuse a worker-bounded window instead of staging every query's result.
82    let window_size = x.len().min(workers.saturating_mul(DEFAULT_SPATIAL_TENSOR_CHUNK_SIZE));
83    let mut nearest = vec![None; window_size];
84    let mut sum_sq = 0.0_f64;
85    let mut max = 0.0_f64;
86    for start in (0..x.len()).step_by(window_size) {
87        let count = window_size.min(x.len() - start);
88        let active_workers = workers.min(count);
89        let fill = |offset: usize, band: &mut [Option<f32>]| {
90            // nearest_one uses this same one-neighbor traversal. Reuse its
91            // output buffer; nearest_k_into resets the query accumulator.
92            let mut neighbor = Vec::new();
93            for (i, distance) in band.iter_mut().enumerate() {
94                let i = start + offset + i;
95                target.nearest_k_into(x[i], y[i], z[i], 1, &mut neighbor);
96                *distance = neighbor.first().map(|n| n.distance_squared);
97            }
98        };
99        if active_workers == 1 {
100            fill(0, &mut nearest[..count]);
101        } else {
102            let chunk_size = count.div_ceil(active_workers);
103            std::thread::scope(|scope| {
104                for (band, chunk) in nearest[..count].chunks_mut(chunk_size).enumerate() {
105                    let fill = &fill;
106                    scope.spawn(move || fill(band * chunk_size, chunk));
107                }
108            });
109        }
110        // Never combine worker-local sums: f64 addition is order-sensitive.
111        for distance in nearest[..count].iter().flatten() {
112            let d_sq = f64::from(*distance);
113            sum_sq += d_sq;
114            let d = d_sq.sqrt();
115            if d > max {
116                max = d;
117            }
118        }
119    }
120    (sum_sq / x.len() as f64, max)
121}
122
123fn directed_serial(x: &[f32], y: &[f32], z: &[f32], target: &KdTree) -> (f64, f64) {
124    let mut sum_sq = 0.0_f64;
125    let mut max = 0.0_f64;
126    for i in 0..x.len() {
127        if let Some(neighbor) = target.nearest_one(x[i], y[i], z[i]) {
128            let d_sq = f64::from(neighbor.distance_squared);
129            sum_sq += d_sq;
130            let d = d_sq.sqrt();
131            if d > max {
132                max = d;
133            }
134        }
135    }
136    (sum_sq / x.len() as f64, max)
137}
138
139/// Symmetric Chamfer distance between two clouds (sum of mean squared NN
140/// distances in both directions). Lower is better; zero for identical clouds.
141pub fn chamfer_distance(a: &PointCloud, b: &PointCloud) -> SpatialResult<f64> {
142    Ok(cloud_distances(a, b)?.chamfer())
143}
144
145/// Symmetric Hausdorff distance between two clouds (the largest NN distance in
146/// either direction). Captures the worst-case discrepancy.
147pub fn hausdorff_distance(a: &PointCloud, b: &PointCloud) -> SpatialResult<f64> {
148    Ok(cloud_distances(a, b)?.hausdorff())
149}
150
151#[cfg(all(test, not(target_arch = "wasm32")))]
152#[path = "../tests/fixtures/distance_serial.rs"]
153#[allow(dead_code)]
154mod previous;
155
156#[cfg(all(test, not(target_arch = "wasm32")))]
157#[path = "distance_parallel_tests.rs"]
158mod parallel_tests;
159
160#[cfg(all(test, not(target_arch = "wasm32")))]
161#[path = "distance_parallel_benchmark.rs"]
162mod parallel_benchmark;
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167    use spatialrust_core::{PointCloudBuilder, StandardSchemas};
168
169    fn cloud(points: &[[f32; 3]]) -> PointCloud {
170        let mut builder = PointCloudBuilder::new(StandardSchemas::point_xyz());
171        for p in points {
172            builder.push_point(*p).unwrap();
173        }
174        builder.build().unwrap()
175    }
176
177    #[test]
178    fn identical_clouds_have_zero_distance() {
179        let c = cloud(&[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]);
180        assert!(chamfer_distance(&c, &c).unwrap() < 1e-9);
181        assert!(hausdorff_distance(&c, &c).unwrap() < 1e-9);
182    }
183
184    #[test]
185    fn translation_shows_up_in_distances() {
186        let a = cloud(&[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0]]);
187        let b = cloud(&[[0.0, 0.5, 0.0], [1.0, 0.5, 0.0], [2.0, 0.5, 0.0]]);
188        // Every point's nearest neighbor is exactly 0.5 away.
189        let chamfer = chamfer_distance(&a, &b).unwrap();
190        assert!((chamfer - (0.25 + 0.25)).abs() < 1e-6);
191        let hausdorff = hausdorff_distance(&a, &b).unwrap();
192        assert!((hausdorff - 0.5).abs() < 1e-6);
193    }
194
195    #[test]
196    fn hausdorff_catches_a_single_outlier() {
197        let a = cloud(&[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]]);
198        let b = cloud(&[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [10.0, 0.0, 0.0]]);
199        // The lone far point in b is 9.0 from its nearest neighbor in a.
200        assert!((hausdorff_distance(&a, &b).unwrap() - 9.0).abs() < 1e-6);
201    }
202}