Skip to main content

spatialrust_filtering/
mls.rs

1//! Moving Least Squares (MLS) surface smoothing.
2//!
3//! For each point a local reference plane is fit to its neighborhood, a bivariate
4//! polynomial height field is fit over that plane (weighted least squares), and
5//! the point is projected onto the polynomial surface. This removes scanner noise
6//! while preserving curvature far better than a plain average, and yields cleaner
7//! normals for downstream estimation.
8
9use spatialrust_core::{
10    FieldSemantic, HasPositions3, PointBuffer, PointBufferSet, PointCloud, SpatialError,
11    SpatialResult,
12};
13use spatialrust_math::{solve_linear_system, symmetric_eigen3, LeastSquaresResult, Mat3, Vec3};
14use spatialrust_search::{parallel_worker_count, KdTree, RadiusSearchIndex};
15
16use crate::filter::PointCloudFilter;
17
18/// Configuration for [`MlsSmoothing`].
19#[derive(Clone, Copy, Debug, PartialEq)]
20pub struct MlsConfig {
21    /// Neighborhood radius used to fit the local surface.
22    pub search_radius: f32,
23    /// Polynomial order of the fitted height field (1 = plane, 2 = quadratic).
24    pub polynomial_order: u8,
25    /// Minimum neighbors required to smooth a point (else it is left in place).
26    pub min_neighbors: usize,
27}
28
29impl Default for MlsConfig {
30    fn default() -> Self {
31        Self { search_radius: 0.1, polynomial_order: 2, min_neighbors: 6 }
32    }
33}
34
35impl MlsConfig {
36    /// Creates a config with the given search radius (quadratic fit).
37    #[must_use]
38    pub const fn with_radius(search_radius: f32) -> Self {
39        Self { search_radius, polynomial_order: 2, min_neighbors: 6 }
40    }
41}
42
43/// Explicit GPU MLS positions, device outcomes and payload receipt.
44#[cfg(feature = "filter-mls-gpu")]
45#[derive(Clone, Debug, PartialEq)]
46pub struct GpuMlsPositionResult {
47    /// Original-order explicitly downloaded GPU coordinates.
48    pub positions: Vec<Vec3<f32>>,
49    /// Per-point device outcomes aligned with positions.
50    pub modes: Vec<spatialrust_gpu::GpuMlsMode>,
51    /// Device fitting/fallback counts.
52    pub diagnostics: spatialrust_gpu::GpuMlsDiagnostics,
53    /// Tree/query upload and padded position/status download payload.
54    pub transfers: spatialrust_core::TransferStats,
55}
56
57/// Explicit GPU MLS filtered cloud, outcome counts and payload receipt.
58#[cfg(feature = "filter-mls-gpu")]
59#[derive(Clone, Debug, PartialEq)]
60pub struct GpuMlsFilterResult {
61    /// Smoothed cloud preserving schema, metadata and non-position fields.
62    pub cloud: PointCloud,
63    /// Per-point device outcomes aligned with cloud rows.
64    pub modes: Vec<spatialrust_gpu::GpuMlsMode>,
65    /// Device fitting/fallback counts.
66    pub diagnostics: spatialrust_gpu::GpuMlsDiagnostics,
67    /// Input upload and position/status download payload.
68    pub transfers: spatialrust_core::TransferStats,
69}
70
71/// Moving Least Squares smoothing filter.
72#[derive(Clone, Copy, Debug, PartialEq)]
73pub struct MlsSmoothing {
74    config: MlsConfig,
75}
76
77impl MlsSmoothing {
78    /// Creates a smoother from config.
79    #[must_use]
80    pub const fn new(config: MlsConfig) -> Self {
81        Self { config }
82    }
83
84    /// Returns the smoother config.
85    #[must_use]
86    pub const fn config(&self) -> MlsConfig {
87        self.config
88    }
89
90    /// Returns the smoothed XYZ positions, one per input point.
91    ///
92    /// Shares one KD-tree between bounded scoped CPU workers using the same
93    /// staging policy as neighborhood outlier filters. Small clouds and one
94    /// available worker retain serial execution. Point order, neighborhood
95    /// order and each fit's floating-point operation order are preserved.
96    pub fn smoothed_positions(&self, input: &PointCloud) -> SpatialResult<Vec<Vec3<f32>>> {
97        self.smoothed_positions_with_workers(input, parallel_worker_count(input.len()))
98    }
99
100    /// Explicitly uploads input, computes GPU radius neighborhoods, weighted
101    /// frames and order-0/1/2 polynomial fits, and downloads positions/status.
102    /// CPU tree construction remains; no automatic CPU fallback. Capacity includes
103    /// self and must fit all radius matches. GPU configuration requires finite
104    /// XYZ/extents and a positive finite nonzero f32 radius square, stricter than
105    /// CPU MLS. GPU normalized f32 math/rank tests can change coordinates and
106    /// fit/fallback decisions compared with CPU f64. Numerical underflow errors
107    /// propagate; insufficient support and singular fits use device fallbacks.
108    #[cfg(feature = "filter-mls-gpu")]
109    pub fn smoothed_positions_with_gpu(
110        &self,
111        runtime: &spatialrust_gpu::WgpuRuntime,
112        input: &PointCloud,
113        neighbor_capacity: u32,
114    ) -> SpatialResult<GpuMlsPositionResult> {
115        let radius = self.config.search_radius;
116        if !radius.is_finite()
117            || radius <= 0.0
118            || !(radius * radius).is_finite()
119            || radius * radius == 0.0
120            || self.config.polynomial_order > 2
121        {
122            return Err(SpatialError::InvalidArgument(
123                "GPU MLS requires a positive finite nonzero radius square and order 0..=2"
124                    .to_owned(),
125            ));
126        }
127        let (x, y, z) = input.positions3()?;
128        if x.iter().chain(y).chain(z).any(|v| !v.is_finite()) {
129            return Err(SpatialError::InvalidArgument("GPU MLS requires finite XYZ".to_owned()));
130        }
131        let tree = KdTree::from_slices(x, y, z);
132        let device_input = spatialrust_gpu::GpuMlsInput::upload(runtime, &tree)?;
133        let rows = device_input.neighborhoods_resident(runtime, radius, neighbor_capacity)?;
134        let output = device_input.smooth_resident(
135            runtime,
136            &rows,
137            self.config.polynomial_order,
138            u32::try_from(self.config.min_neighbors).unwrap_or(u32::MAX),
139        )?;
140        let readback = output.download(runtime)?;
141        let mut transfers = device_input.upload_transfers();
142        transfers.record(
143            spatialrust_core::TransferDirection::DeviceToHost,
144            readback.transfers.device_to_host_bytes(),
145        );
146        let positions =
147            readback.positions.into_iter().map(|p| Vec3::new(p[0], p[1], p[2])).collect();
148        Ok(GpuMlsPositionResult {
149            positions,
150            modes: readback.modes,
151            diagnostics: readback.diagnostics,
152            transfers,
153        })
154    }
155
156    /// Explicit GPU MLS filtering with CPU schema/attribute reconstruction. The
157    /// ordinary filter trait retains CPU execution. See the position API for
158    /// capacity, precision and numeric-error contracts; all payload is reported.
159    #[cfg(feature = "filter-mls-gpu")]
160    pub fn filter_with_gpu(
161        &self,
162        runtime: &spatialrust_gpu::WgpuRuntime,
163        input: &PointCloud,
164        neighbor_capacity: u32,
165    ) -> SpatialResult<GpuMlsFilterResult> {
166        let result = self.smoothed_positions_with_gpu(runtime, input, neighbor_capacity)?;
167        let cloud = build_output(input, &result.positions)?;
168        Ok(GpuMlsFilterResult {
169            cloud,
170            modes: result.modes,
171            diagnostics: result.diagnostics,
172            transfers: result.transfers,
173        })
174    }
175
176    fn smoothed_positions_with_workers(
177        &self,
178        input: &PointCloud,
179        workers: usize,
180    ) -> SpatialResult<Vec<Vec3<f32>>> {
181        if self.config.search_radius <= 0.0 || self.config.search_radius.is_nan() {
182            return Err(SpatialError::InvalidArgument("search_radius must be positive".to_owned()));
183        }
184        if self.config.polynomial_order > 2 {
185            return Err(SpatialError::InvalidArgument(
186                "polynomial_order must be 1 or 2".to_owned(),
187            ));
188        }
189
190        let (x, y, z) = input.positions3()?;
191        let len = input.len();
192        let tree = KdTree::from_slices(x, y, z);
193        // Gaussian weight scale: ~1/2 of the radius averages out noise while
194        // still down-weighting the far neighborhood to preserve curvature.
195        let h_sq = (self.config.search_radius / 2.0).powi(2).max(1e-12);
196
197        let smooth = |i| smooth_point(i, &tree, x, y, z, self.config, h_sq);
198        let workers = workers.max(1).min(len.max(1));
199        if workers == 1 {
200            let mut out = Vec::with_capacity(len);
201            for i in 0..len {
202                out.push(smooth(i));
203            }
204            return Ok(out);
205        }
206
207        let mut out = vec![Vec3::new(0.0, 0.0, 0.0); len];
208        let chunk_size = len.div_ceil(workers);
209        std::thread::scope(|scope| {
210            for (band, chunk) in out.chunks_mut(chunk_size).enumerate() {
211                let start = band * chunk_size;
212                let smooth = &smooth;
213                scope.spawn(move || {
214                    for (offset, position) in chunk.iter_mut().enumerate() {
215                        *position = smooth(start + offset);
216                    }
217                });
218            }
219        });
220        Ok(out)
221    }
222}
223
224fn smooth_point(
225    i: usize,
226    tree: &KdTree,
227    x: &[f32],
228    y: &[f32],
229    z: &[f32],
230    config: MlsConfig,
231    h_sq: f32,
232) -> Vec3<f32> {
233    let p = Vec3::new(x[i], y[i], z[i]);
234    let neighbors = tree.radius_search(p.x, p.y, p.z, config.search_radius);
235    if neighbors.len() < config.min_neighbors {
236        return p;
237    }
238    // Leave-one-out: exclude the query point itself so the surface is
239    // determined by its neighbors, which smooths the point's own noise.
240    let pts: Vec<Vec3<f32>> = neighbors
241        .iter()
242        .filter(|n| n.index != i)
243        .map(|n| Vec3::new(x[n.index], y[n.index], z[n.index]))
244        .collect();
245    project_point(p, &pts, config.polynomial_order, h_sq).unwrap_or(p)
246}
247
248impl PointCloudFilter for MlsSmoothing {
249    fn name(&self) -> &'static str {
250        "MlsSmoothing"
251    }
252
253    fn filter(&self, input: &PointCloud) -> SpatialResult<PointCloud> {
254        let smoothed = self.smoothed_positions(input)?;
255        build_output(input, &smoothed)
256    }
257}
258
259/// Fits a local frame + height polynomial and returns the projection of `p`.
260fn project_point(p: Vec3<f32>, neighbors: &[Vec3<f32>], order: u8, h_sq: f32) -> Option<Vec3<f32>> {
261    // Weighted centroid and covariance about the query point.
262    let mut sum_w = 0.0_f64;
263    let mut centroid = [0.0_f64; 3];
264    let mut weights = Vec::with_capacity(neighbors.len());
265    for q in neighbors {
266        let d_sq = (*q - p).length_squared();
267        let w = f64::from((-d_sq / h_sq).exp());
268        weights.push(w);
269        sum_w += w;
270        centroid[0] += w * f64::from(q.x);
271        centroid[1] += w * f64::from(q.y);
272        centroid[2] += w * f64::from(q.z);
273    }
274    if sum_w < 1e-12 {
275        return None;
276    }
277    let c = Vec3::new(
278        (centroid[0] / sum_w) as f32,
279        (centroid[1] / sum_w) as f32,
280        (centroid[2] / sum_w) as f32,
281    );
282
283    let mut cov = [[0.0_f64; 3]; 3];
284    for (q, &w) in neighbors.iter().zip(&weights) {
285        let d = *q - c;
286        let d = [f64::from(d.x), f64::from(d.y), f64::from(d.z)];
287        for r in 0..3 {
288            for col in 0..3 {
289                cov[r][col] += w * d[r] * d[col];
290            }
291        }
292    }
293    let covariance = Mat3::<f64>::from_rows(cov[0], cov[1], cov[2]);
294    let eigen = symmetric_eigen3(covariance);
295    // Smallest eigenvector (column 0) is the plane normal.
296    let normal = Vec3::new(
297        eigen.eigenvectors.m[0][0] as f32,
298        eigen.eigenvectors.m[1][0] as f32,
299        eigen.eigenvectors.m[2][0] as f32,
300    )
301    .normalize();
302
303    // In-plane orthonormal basis (u, w).
304    let helper =
305        if normal.x.abs() < 0.9 { Vec3::new(1.0, 0.0, 0.0) } else { Vec3::new(0.0, 1.0, 0.0) };
306    let u = normal.cross(helper).normalize();
307    let v = normal.cross(u);
308
309    // Query point's in-plane coordinates relative to the centroid.
310    let rel = p - c;
311    let qu = rel.dot(u);
312    let qv = rel.dot(v);
313
314    // Fit height(s, t) = sum coeff_k * basis_k(s, t) by weighted least squares.
315    let basis = |s: f32, t: f32| match order {
316        0 => vec![1.0_f64],
317        1 => vec![1.0, f64::from(s), f64::from(t)],
318        _ => vec![
319            1.0,
320            f64::from(s),
321            f64::from(t),
322            f64::from(s * s),
323            f64::from(s * t),
324            f64::from(t * t),
325        ],
326    };
327    let terms = basis(0.0, 0.0).len();
328    if neighbors.len() < terms {
329        // Not enough support for this order: fall back to the plane.
330        return Some(c + scale(u, qu) + scale(v, qv));
331    }
332
333    let mut ata = vec![vec![0.0_f64; terms]; terms];
334    let mut atb = vec![0.0_f64; terms];
335    for (q, &w) in neighbors.iter().zip(&weights) {
336        let d = *q - c;
337        let s = d.dot(u);
338        let t = d.dot(v);
339        let height = f64::from(d.dot(normal));
340        let row = basis(s, t);
341        for a in 0..terms {
342            atb[a] += w * row[a] * height;
343            for b in 0..terms {
344                ata[a][b] += w * row[a] * row[b];
345            }
346        }
347    }
348
349    let coeffs = match solve_linear_system(ata, atb) {
350        LeastSquaresResult::Solved(c) => c,
351        LeastSquaresResult::Singular => return Some(c + scale(u, qu) + scale(v, qv)),
352    };
353    let query_basis = basis(qu, qv);
354    let height: f64 = coeffs.iter().zip(&query_basis).map(|(c, b)| c * b).sum();
355
356    Some(c + scale(u, qu) + scale(v, qv) + scale(normal, height as f32))
357}
358
359fn scale(v: Vec3<f32>, s: f32) -> Vec3<f32> {
360    Vec3::new(v.x * s, v.y * s, v.z * s)
361}
362
363/// Rebuilds the cloud with smoothed positions, preserving every other field.
364fn build_output(input: &PointCloud, positions: &[Vec3<f32>]) -> SpatialResult<PointCloud> {
365    let schema = input.schema().clone();
366    let name_for = |sem| schema.find_semantic(sem).map(|f| f.name.clone());
367    let (xn, yn, zn) = (
368        name_for(FieldSemantic::PositionX),
369        name_for(FieldSemantic::PositionY),
370        name_for(FieldSemantic::PositionZ),
371    );
372
373    let mut buffers = PointBufferSet::new();
374    for field in schema.fields() {
375        let name = &field.name;
376        let buffer = if Some(name) == xn.as_ref() {
377            PointBuffer::from_f32(positions.iter().map(|p| p.x).collect())
378        } else if Some(name) == yn.as_ref() {
379            PointBuffer::from_f32(positions.iter().map(|p| p.y).collect())
380        } else if Some(name) == zn.as_ref() {
381            PointBuffer::from_f32(positions.iter().map(|p| p.z).collect())
382        } else {
383            clone_buffer(input.field(name)?)
384        };
385        buffers.insert(name.clone(), buffer);
386    }
387    PointCloud::try_from_parts(schema, buffers, input.metadata().clone())
388}
389
390fn clone_buffer(buffer: &PointBuffer) -> PointBuffer {
391    match buffer {
392        PointBuffer::F32(v) => PointBuffer::from_f32(v.clone()),
393        PointBuffer::F64(v) => PointBuffer::F64(v.clone()),
394        PointBuffer::U8(v) => PointBuffer::U8(v.clone()),
395        PointBuffer::U16(v) => PointBuffer::U16(v.clone()),
396        PointBuffer::U32(v) => PointBuffer::U32(v.clone()),
397        PointBuffer::I32(v) => PointBuffer::I32(v.clone()),
398    }
399}
400
401#[cfg(test)]
402#[allow(dead_code)]
403#[path = "../tests/fixtures/mls_serial.rs"]
404mod previous;
405
406#[cfg(test)]
407#[path = "mls_parallel_tests.rs"]
408mod parallel_tests;
409
410#[cfg(test)]
411#[path = "mls_parallel_benchmark.rs"]
412mod parallel_benchmark;
413
414#[cfg(test)]
415mod tests {
416    use super::*;
417    use spatialrust_core::{PointCloudBuilder, StandardSchemas};
418
419    /// A noisy plane: MLS should pull points back toward z = 0.
420    #[test]
421    fn flattens_noisy_plane() {
422        // Deterministic pseudo-noise so the test is stable.
423        let mut seed = 12345_u64;
424        let mut noise = || {
425            seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
426            // Top 32 bits mapped to a centered [-0.02, 0.02] perturbation.
427            let unit = (seed >> 32) as u32 as f32 / u32::MAX as f32;
428            (unit * 2.0 - 1.0) * 0.02
429        };
430
431        let mut builder = PointCloudBuilder::new(StandardSchemas::point_xyz());
432        let mut z_before = Vec::new();
433        for i in 0..25 {
434            for j in 0..25 {
435                let z = noise();
436                z_before.push(z);
437                builder.push_point([i as f32 * 0.05, j as f32 * 0.05, z]).unwrap();
438            }
439        }
440        let cloud = builder.build().unwrap();
441
442        // Order-1 (plane) fit is the right tool for a planar surface.
443        let smoother = MlsSmoothing::new(MlsConfig {
444            search_radius: 0.2,
445            polynomial_order: 1,
446            min_neighbors: 6,
447        });
448        let out = smoother.filter(&cloud).unwrap();
449        assert_eq!(out.len(), cloud.len());
450
451        let (_, _, z) = out.positions3().unwrap();
452        let interior = |k: usize| {
453            let (i, j) = (k / 25, k % 25);
454            (4..21).contains(&i) && (4..21).contains(&j)
455        };
456        // Compare the RMS deviation from the true plane (z = 0) before/after.
457        let rms = |get: &dyn Fn(usize) -> f32| {
458            let vals: Vec<f32> = (0..cloud.len()).filter(|&k| interior(k)).map(get).collect();
459            (vals.iter().map(|v| v * v).sum::<f32>() / vals.len() as f32).sqrt()
460        };
461        let before = rms(&|k| z_before[k]);
462        let after = rms(&|k| z[k]);
463        assert!(after < before * 0.6, "MLS did not flatten: rms {after} vs {before}");
464    }
465
466    #[test]
467    fn rejects_bad_params() {
468        let mut builder = PointCloudBuilder::new(StandardSchemas::point_xyz());
469        builder.push_point([0.0, 0.0, 0.0]).unwrap();
470        let cloud = builder.build().unwrap();
471        assert!(MlsSmoothing::new(MlsConfig::with_radius(0.0)).smoothed_positions(&cloud).is_err());
472        assert!(MlsSmoothing::new(MlsConfig {
473            search_radius: 0.1,
474            polynomial_order: 3,
475            min_neighbors: 6
476        })
477        .smoothed_positions(&cloud)
478        .is_err());
479    }
480}