Skip to main content

spatialrust_filtering/
outlier.rs

1//! Neighborhood-based outlier removal filters.
2//!
3//! Both filters use a KD-tree over the input positions and drop points whose
4//! local neighborhood looks sparse, which removes scanner speckle and stray
5//! returns before downstream estimation (normals, registration, segmentation).
6
7use spatialrust_core::{
8    DType, FieldSemantic, HasPositions3, PointBuffer, PointBufferSet, PointCloud, PointField,
9    SpatialError, SpatialResult,
10};
11use spatialrust_search::{parallel_worker_count, KdTree};
12
13use crate::filter::PointCloudFilter;
14
15/// Configuration for [`StatisticalOutlierRemoval`].
16#[derive(Clone, Copy, Debug, PartialEq)]
17pub struct StatisticalOutlierConfig {
18    /// Number of nearest neighbors averaged per point.
19    pub k_neighbors: usize,
20    /// Standard-deviation multiplier; points whose mean neighbor distance
21    /// exceeds `global_mean + std_mul * global_std` are removed.
22    pub std_mul: f32,
23}
24
25impl Default for StatisticalOutlierConfig {
26    fn default() -> Self {
27        Self { k_neighbors: 16, std_mul: 1.0 }
28    }
29}
30
31impl StatisticalOutlierConfig {
32    /// Creates a config from the neighbor count and std multiplier.
33    #[must_use]
34    pub const fn new(k_neighbors: usize, std_mul: f32) -> Self {
35        Self { k_neighbors, std_mul }
36    }
37}
38
39/// Statistical Outlier Removal (SOR).
40///
41/// For each point the mean distance to its `k` nearest neighbors is computed.
42/// Assuming those means are roughly Gaussian, points whose mean distance is
43/// more than `std_mul` standard deviations above the global mean are dropped.
44#[derive(Clone, Copy, Debug, PartialEq)]
45pub struct StatisticalOutlierRemoval {
46    config: StatisticalOutlierConfig,
47}
48
49impl StatisticalOutlierRemoval {
50    /// Creates a filter from config.
51    #[must_use]
52    pub const fn new(config: StatisticalOutlierConfig) -> Self {
53        Self { config }
54    }
55
56    /// Returns the filter config.
57    #[must_use]
58    pub const fn config(&self) -> StatisticalOutlierConfig {
59        self.config
60    }
61
62    /// Computes the keep mask without materializing the filtered cloud.
63    pub fn keep_mask(&self, input: &PointCloud) -> SpatialResult<Vec<bool>> {
64        if self.config.k_neighbors == 0 {
65            return Err(SpatialError::InvalidArgument(
66                "k_neighbors must be greater than zero".to_owned(),
67            ));
68        }
69        if !self.config.std_mul.is_finite() || self.config.std_mul < 0.0 {
70            return Err(SpatialError::InvalidArgument(
71                "std_mul must be finite and nonnegative".to_owned(),
72            ));
73        }
74        let len = input.len();
75        if len == 0 {
76            return Ok(Vec::new());
77        }
78
79        let (x, y, z) = input.positions3()?;
80        if x.iter().chain(y).chain(z).any(|value| !value.is_finite()) {
81            return Err(SpatialError::InvalidArgument(
82                "outlier removal requires finite XYZ points".to_owned(),
83            ));
84        }
85        let tree = KdTree::from_slices(x, y, z);
86
87        // Mean distance to the k nearest neighbors (excluding the point itself).
88        let mut mean_dist = vec![0.0_f32; len];
89        fill_mean_neighbor_distances(
90            self.config.k_neighbors.min(len.saturating_sub(1)),
91            &tree,
92            x,
93            y,
94            z,
95            &mut mean_dist,
96        );
97
98        let n = len as f64;
99        let mean: f64 = mean_dist.iter().map(|&d| d as f64).sum::<f64>() / n;
100        let variance: f64 = mean_dist.iter().map(|&d| (d as f64 - mean).powi(2)).sum::<f64>() / n;
101        let std = variance.sqrt();
102        let threshold = mean + self.config.std_mul as f64 * std;
103
104        Ok(mean_dist.iter().map(|&d| d as f64 <= threshold).collect())
105    }
106}
107
108impl PointCloudFilter for StatisticalOutlierRemoval {
109    fn name(&self) -> &'static str {
110        "StatisticalOutlierRemoval"
111    }
112
113    fn filter(&self, input: &PointCloud) -> SpatialResult<PointCloud> {
114        let mask = self.keep_mask(input)?;
115        gather_mask(input, &mask)
116    }
117}
118
119fn fill_mean_neighbor_distances(
120    k_neighbors: usize,
121    tree: &KdTree,
122    x: &[f32],
123    y: &[f32],
124    z: &[f32],
125    mean_dist: &mut [f32],
126) {
127    let worker_count = parallel_worker_count(mean_dist.len());
128    if worker_count == 1 {
129        fill_mean_neighbor_distances_chunk(k_neighbors, tree, x, y, z, 0, mean_dist);
130        return;
131    }
132
133    let chunk_size = mean_dist.len().div_ceil(worker_count);
134    std::thread::scope(|scope| {
135        for (chunk_index, chunk) in mean_dist.chunks_mut(chunk_size).enumerate() {
136            let start = chunk_index * chunk_size;
137            scope.spawn(move || {
138                fill_mean_neighbor_distances_chunk(k_neighbors, tree, x, y, z, start, chunk);
139            });
140        }
141    });
142}
143
144fn fill_mean_neighbor_distances_chunk(
145    k_neighbors: usize,
146    tree: &KdTree,
147    x: &[f32],
148    y: &[f32],
149    z: &[f32],
150    start: usize,
151    mean_dist: &mut [f32],
152) {
153    let mut neighbors = Vec::with_capacity(k_neighbors.saturating_add(1));
154    for (offset, mean) in mean_dist.iter_mut().enumerate() {
155        let i = start + offset;
156        tree.nearest_k_unsorted_into(
157            x[i],
158            y[i],
159            z[i],
160            k_neighbors.saturating_add(1),
161            &mut neighbors,
162        );
163        let mut sum = 0.0_f32;
164        let mut count = 0_u32;
165        for neighbor in &neighbors {
166            if neighbor.index == i {
167                continue;
168            }
169            sum += neighbor.distance_squared.sqrt();
170            count += 1;
171        }
172        *mean = if count == 0 { 0.0 } else { sum / count as f32 };
173    }
174}
175
176/// Configuration for [`RadiusOutlierRemoval`].
177#[derive(Clone, Copy, Debug, PartialEq)]
178pub struct RadiusOutlierConfig {
179    /// Search radius (not squared) defining a point's neighborhood.
180    pub radius: f32,
181    /// Minimum neighbors (excluding the point itself) required to keep a point.
182    pub min_neighbors: usize,
183}
184
185impl Default for RadiusOutlierConfig {
186    fn default() -> Self {
187        Self { radius: 0.5, min_neighbors: 4 }
188    }
189}
190
191impl RadiusOutlierConfig {
192    /// Creates a config from the radius and minimum neighbor count.
193    #[must_use]
194    pub const fn new(radius: f32, min_neighbors: usize) -> Self {
195        Self { radius, min_neighbors }
196    }
197}
198
199/// Radius Outlier Removal (ROR).
200///
201/// Drops every point that has fewer than `min_neighbors` other points within
202/// `radius`. Unlike SOR this uses an absolute density threshold, so it is robust
203/// when outliers are clustered rather than isolated.
204#[derive(Clone, Copy, Debug, PartialEq)]
205pub struct RadiusOutlierRemoval {
206    config: RadiusOutlierConfig,
207}
208
209impl RadiusOutlierRemoval {
210    /// Creates a filter from config.
211    #[must_use]
212    pub const fn new(config: RadiusOutlierConfig) -> Self {
213        Self { config }
214    }
215
216    /// Returns the filter config.
217    #[must_use]
218    pub const fn config(&self) -> RadiusOutlierConfig {
219        self.config
220    }
221
222    /// Computes the keep mask without materializing the filtered cloud.
223    pub fn keep_mask(&self, input: &PointCloud) -> SpatialResult<Vec<bool>> {
224        let squared_radius = self.config.radius * self.config.radius;
225        if !self.config.radius.is_finite()
226            || self.config.radius <= 0.0
227            || !squared_radius.is_finite()
228            || squared_radius == 0.0
229        {
230            return Err(SpatialError::InvalidArgument(
231                "radius must be finite and positive with a finite nonzero square".to_owned(),
232            ));
233        }
234        let len = input.len();
235        if len == 0 {
236            return Ok(Vec::new());
237        }
238
239        let (x, y, z) = input.positions3()?;
240        if x.iter().chain(y).chain(z).any(|value| !value.is_finite()) {
241            return Err(SpatialError::InvalidArgument(
242                "outlier removal requires finite XYZ points".to_owned(),
243            ));
244        }
245        if self.config.min_neighbors >= len {
246            return Ok(vec![false; len]);
247        }
248
249        let tree = KdTree::from_slices(x, y, z);
250
251        // The query point itself is in the tree, so requiring `min_neighbors`
252        // *other* points within radius means reaching `min_neighbors + 1` total.
253        // `radius_reaches` early-exits at that threshold without allocating.
254        let target = self.config.min_neighbors + 1;
255        let mut keep = vec![false; len];
256        fill_radius_reaches_mask(&tree, x, y, z, self.config.radius, target, &mut keep);
257        Ok(keep)
258    }
259}
260
261impl PointCloudFilter for RadiusOutlierRemoval {
262    fn name(&self) -> &'static str {
263        "RadiusOutlierRemoval"
264    }
265
266    fn filter(&self, input: &PointCloud) -> SpatialResult<PointCloud> {
267        let mask = self.keep_mask(input)?;
268        gather_mask(input, &mask)
269    }
270}
271
272fn fill_radius_reaches_mask(
273    tree: &KdTree,
274    x: &[f32],
275    y: &[f32],
276    z: &[f32],
277    radius: f32,
278    target: usize,
279    keep: &mut [bool],
280) {
281    let worker_count = parallel_worker_count(keep.len());
282    if worker_count == 1 {
283        fill_radius_reaches_mask_chunk(tree, x, y, z, radius, target, 0, keep);
284        return;
285    }
286
287    let chunk_size = keep.len().div_ceil(worker_count);
288    std::thread::scope(|scope| {
289        for (chunk_index, chunk) in keep.chunks_mut(chunk_size).enumerate() {
290            let start = chunk_index * chunk_size;
291            scope.spawn(move || {
292                fill_radius_reaches_mask_chunk(tree, x, y, z, radius, target, start, chunk);
293            });
294        }
295    });
296}
297
298fn fill_radius_reaches_mask_chunk(
299    tree: &KdTree,
300    x: &[f32],
301    y: &[f32],
302    z: &[f32],
303    radius: f32,
304    target: usize,
305    start: usize,
306    keep: &mut [bool],
307) {
308    for (offset, keep_point) in keep.iter_mut().enumerate() {
309        let i = start + offset;
310        *keep_point = tree.radius_reaches(x[i], y[i], z[i], radius, target);
311    }
312}
313
314/// Builds a new cloud from the points where `mask` is true, preserving schema.
315fn gather_mask(input: &PointCloud, mask: &[bool]) -> SpatialResult<PointCloud> {
316    if let Some(output) = gather_xyz_mask(input, mask)? {
317        return Ok(output);
318    }
319
320    let indices: Vec<usize> =
321        mask.iter().enumerate().filter_map(|(i, &keep)| keep.then_some(i)).collect();
322
323    let mut buffers = PointBufferSet::new();
324    for field in input.schema().fields() {
325        let source = input.field(&field.name)?;
326        buffers.insert(field.name.clone(), gather_buffer(source, &indices));
327    }
328    PointCloud::try_from_parts(input.schema().clone(), buffers, input.metadata().clone())
329}
330
331fn gather_xyz_mask(input: &PointCloud, mask: &[bool]) -> SpatialResult<Option<PointCloud>> {
332    let schema = input.schema();
333    if schema.len() != 3 {
334        return Ok(None);
335    }
336
337    let Some(x_field) = xyz_f32_field(input, FieldSemantic::PositionX) else {
338        return Ok(None);
339    };
340    let Some(y_field) = xyz_f32_field(input, FieldSemantic::PositionY) else {
341        return Ok(None);
342    };
343    let Some(z_field) = xyz_f32_field(input, FieldSemantic::PositionZ) else {
344        return Ok(None);
345    };
346
347    let (x, y, z) = input.positions3()?;
348    let output_len = mask.iter().filter(|&&keep| keep).count();
349    let mut out_x = Vec::with_capacity(output_len);
350    let mut out_y = Vec::with_capacity(output_len);
351    let mut out_z = Vec::with_capacity(output_len);
352
353    for (index, &keep) in mask.iter().enumerate() {
354        if keep {
355            out_x.push(x[index]);
356            out_y.push(y[index]);
357            out_z.push(z[index]);
358        }
359    }
360
361    let mut buffers = PointBufferSet::new();
362    buffers.insert(x_field.name.clone(), PointBuffer::from_f32(out_x));
363    buffers.insert(y_field.name.clone(), PointBuffer::from_f32(out_y));
364    buffers.insert(z_field.name.clone(), PointBuffer::from_f32(out_z));
365    PointCloud::try_from_parts(schema.clone(), buffers, input.metadata().clone()).map(Some)
366}
367
368fn xyz_f32_field(input: &PointCloud, semantic: FieldSemantic) -> Option<&PointField> {
369    let field = input.schema().find_semantic(semantic)?;
370    (field.dtype == DType::F32 && field.components == 1).then_some(field)
371}
372
373fn gather_buffer(source: &PointBuffer, indices: &[usize]) -> PointBuffer {
374    match source {
375        PointBuffer::F32(v) => PointBuffer::from_f32(indices.iter().map(|&i| v[i]).collect()),
376        PointBuffer::F64(v) => PointBuffer::F64(indices.iter().map(|&i| v[i]).collect()),
377        PointBuffer::U8(v) => PointBuffer::U8(indices.iter().map(|&i| v[i]).collect()),
378        PointBuffer::U16(v) => PointBuffer::U16(indices.iter().map(|&i| v[i]).collect()),
379        PointBuffer::U32(v) => PointBuffer::U32(indices.iter().map(|&i| v[i]).collect()),
380        PointBuffer::I32(v) => PointBuffer::I32(indices.iter().map(|&i| v[i]).collect()),
381    }
382}
383
384#[cfg(test)]
385mod tests {
386    use super::*;
387    use spatialrust_core::{DType, FieldSemantic, PointField, PointSchema};
388
389    fn cloud_from_xyz(points: &[[f32; 3]]) -> PointCloud {
390        let schema = PointSchema::new()
391            .with_field(PointField::scalar("x", FieldSemantic::PositionX, DType::F32))
392            .with_field(PointField::scalar("y", FieldSemantic::PositionY, DType::F32))
393            .with_field(PointField::scalar("z", FieldSemantic::PositionZ, DType::F32));
394        let mut buffers = PointBufferSet::new();
395        buffers
396            .insert("x".to_owned(), PointBuffer::from_f32(points.iter().map(|p| p[0]).collect()));
397        buffers
398            .insert("y".to_owned(), PointBuffer::from_f32(points.iter().map(|p| p[1]).collect()));
399        buffers
400            .insert("z".to_owned(), PointBuffer::from_f32(points.iter().map(|p| p[2]).collect()));
401        PointCloud::try_from_parts(schema, buffers, Default::default()).unwrap()
402    }
403
404    /// A dense unit-spaced grid plus one far-away speckle point.
405    fn grid_with_outlier() -> (PointCloud, usize) {
406        let mut points = Vec::new();
407        for ix in 0..6 {
408            for iy in 0..6 {
409                points.push([ix as f32, iy as f32, 0.0]);
410            }
411        }
412        let outlier_index = points.len();
413        points.push([100.0, 100.0, 100.0]);
414        (cloud_from_xyz(&points), outlier_index)
415    }
416
417    #[test]
418    fn sor_removes_isolated_speckle() {
419        let (cloud, outlier) = grid_with_outlier();
420        let filter = StatisticalOutlierRemoval::new(StatisticalOutlierConfig::new(8, 1.0));
421        let mask = filter.keep_mask(&cloud).unwrap();
422        assert!(!mask[outlier], "the far speckle must be dropped");
423        // Every dense grid point should survive.
424        assert!(mask[..outlier].iter().all(|&k| k));
425        let out = filter.filter(&cloud).unwrap();
426        assert_eq!(out.len(), cloud.len() - 1);
427    }
428
429    #[test]
430    fn ror_removes_isolated_speckle() {
431        let (cloud, outlier) = grid_with_outlier();
432        let filter = RadiusOutlierRemoval::new(RadiusOutlierConfig::new(1.5, 2));
433        let mask = filter.keep_mask(&cloud).unwrap();
434        assert!(!mask[outlier], "the far speckle has no neighbors in radius");
435        assert!(mask[..outlier].iter().all(|&k| k));
436    }
437
438    #[test]
439    fn empty_cloud_is_passthrough() {
440        let cloud = cloud_from_xyz(&[]);
441        let sor = StatisticalOutlierRemoval::new(StatisticalOutlierConfig::default());
442        assert_eq!(sor.filter(&cloud).unwrap().len(), 0);
443        let ror = RadiusOutlierRemoval::new(RadiusOutlierConfig::default());
444        assert_eq!(ror.filter(&cloud).unwrap().len(), 0);
445    }
446
447    #[test]
448    fn invalid_params_error() {
449        let cloud = cloud_from_xyz(&[[0.0, 0.0, 0.0]]);
450        assert!(StatisticalOutlierRemoval::new(StatisticalOutlierConfig::new(0, 1.0))
451            .keep_mask(&cloud)
452            .is_err());
453        assert!(RadiusOutlierRemoval::new(RadiusOutlierConfig::new(0.0, 1))
454            .keep_mask(&cloud)
455            .is_err());
456    }
457
458    #[test]
459    fn invalid_floating_settings_do_not_silently_filter_points() {
460        let cloud = cloud_from_xyz(&[[0., 0., 0.], [1., 0., 0.]]);
461        for std_mul in [f32::NAN, f32::INFINITY, -1.] {
462            assert!(StatisticalOutlierRemoval::new(StatisticalOutlierConfig::new(1, std_mul))
463                .keep_mask(&cloud)
464                .is_err());
465        }
466        for radius in [f32::NAN, f32::INFINITY, f32::MAX, f32::MIN_POSITIVE] {
467            assert!(RadiusOutlierRemoval::new(RadiusOutlierConfig::new(radius, 1))
468                .keep_mask(&cloud)
469                .is_err());
470        }
471    }
472
473    #[test]
474    fn extreme_neighbor_counts_are_bounded_by_available_points() {
475        let cloud = cloud_from_xyz(&[[0., 0., 0.], [1., 0., 0.], [2., 0., 0.]]);
476        let huge = StatisticalOutlierRemoval::new(StatisticalOutlierConfig::new(usize::MAX, 1.))
477            .keep_mask(&cloud)
478            .unwrap();
479        let available = StatisticalOutlierRemoval::new(StatisticalOutlierConfig::new(2, 1.))
480            .keep_mask(&cloud)
481            .unwrap();
482        assert_eq!(huge, available);
483        assert_eq!(
484            RadiusOutlierRemoval::new(RadiusOutlierConfig::new(1., usize::MAX))
485                .keep_mask(&cloud)
486                .unwrap(),
487            vec![false; 3]
488        );
489    }
490
491    #[test]
492    fn nonfinite_positions_are_rejected_even_with_impossible_neighbor_counts() {
493        for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
494            let cloud = cloud_from_xyz(&[[0., value, 0.], [1., 0., 0.]]);
495            assert!(StatisticalOutlierRemoval::new(StatisticalOutlierConfig::default())
496                .keep_mask(&cloud)
497                .is_err());
498            for count in [1, usize::MAX] {
499                assert!(RadiusOutlierRemoval::new(RadiusOutlierConfig::new(1., count))
500                    .keep_mask(&cloud)
501                    .is_err());
502            }
503        }
504    }
505}