1use spatialrust_core::{
4 HasPositions3, PointCloud, SpatialError, SpatialResult, DEFAULT_SPATIAL_TENSOR_CHUNK_SIZE,
5};
6use spatialrust_search::{parallel_worker_count, KdTree, NearestNeighborIndex};
7
8#[derive(Clone, Copy, Debug, PartialEq)]
13pub struct CloudDistances {
14 pub mean_sq_a_to_b: f64,
16 pub mean_sq_b_to_a: f64,
18 pub max_a_to_b: f64,
20 pub max_b_to_a: f64,
22}
23
24impl CloudDistances {
25 #[must_use]
27 pub fn chamfer(&self) -> f64 {
28 self.mean_sq_a_to_b + self.mean_sq_b_to_a
29 }
30
31 #[must_use]
33 pub fn hausdorff(&self) -> f64 {
34 self.max_a_to_b.max(self.max_b_to_a)
35 }
36}
37
38pub 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
74fn 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 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 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 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
139pub fn chamfer_distance(a: &PointCloud, b: &PointCloud) -> SpatialResult<f64> {
142 Ok(cloud_distances(a, b)?.chamfer())
143}
144
145pub 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 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 assert!((hausdorff_distance(&a, &b).unwrap() - 9.0).abs() < 1e-6);
201 }
202}