Skip to main content

spatialrust_features/
iss.rs

1//! Intrinsic Shape Signatures (ISS) keypoint detection.
2//!
3//! ISS picks a sparse set of geometrically salient points — corners and other
4//! spots with variation in all three directions — by thresholding the ratios of
5//! the eigenvalues of each point's neighborhood covariance, then keeping local
6//! maxima of the smallest eigenvalue. The keypoints are a natural front-end for
7//! descriptor-based global registration: far fewer points to describe and match.
8
9use spatialrust_core::{
10    HasPositions3, PointBuffer, PointBufferSet, PointCloud, SpatialError, SpatialResult,
11};
12use spatialrust_math::{symmetric_eigen3, Mat3};
13use spatialrust_search::{parallel_worker_count, KdTree, RadiusSearchIndex};
14
15/// Configuration for [`IssKeypointDetector`].
16#[derive(Clone, Copy, Debug, PartialEq)]
17pub struct IssKeypointConfig {
18    /// Radius of the neighborhood used to build each covariance matrix.
19    pub salient_radius: f32,
20    /// Radius for non-maximum suppression of the saliency (smallest eigenvalue).
21    pub non_max_radius: f32,
22    /// Upper bound on `lambda2 / lambda1` (rejects flat / planar points).
23    pub gamma_21: f32,
24    /// Upper bound on `lambda3 / lambda2` (rejects edge / linear points).
25    pub gamma_32: f32,
26    /// Minimum neighbors within `salient_radius` for a point to be considered.
27    pub min_neighbors: usize,
28}
29
30impl Default for IssKeypointConfig {
31    fn default() -> Self {
32        Self {
33            salient_radius: 0.2,
34            non_max_radius: 0.15,
35            gamma_21: 0.975,
36            gamma_32: 0.975,
37            min_neighbors: 5,
38        }
39    }
40}
41
42impl IssKeypointConfig {
43    /// Creates a config from the salient and non-max-suppression radii.
44    #[must_use]
45    pub fn with_radii(salient_radius: f32, non_max_radius: f32) -> Self {
46        Self { salient_radius, non_max_radius, ..Self::default() }
47    }
48}
49
50/// Result of ISS keypoint detection.
51#[derive(Clone, Debug, PartialEq)]
52pub struct IssKeypointResult {
53    /// Indices of the keypoints in the input cloud.
54    pub indices: Vec<usize>,
55    /// Sub-cloud containing only the keypoints (input schema preserved).
56    pub keypoints: PointCloud,
57}
58
59/// Explicit GPU ISS detection with complete input/flag/status payload receipts.
60#[cfg(feature = "feature-iss-gpu")]
61#[derive(Clone, Debug, PartialEq)]
62pub struct GpuIssKeypointResult {
63    /// Ordered original indices and gathered keypoint cloud.
64    pub result: IssKeypointResult,
65    /// Tree/query upload and selection/status download; uniform controls excluded.
66    pub transfers: spatialrust_core::TransferStats,
67}
68
69/// Intrinsic Shape Signatures keypoint detector.
70#[derive(Clone, Copy, Debug, PartialEq)]
71pub struct IssKeypointDetector {
72    config: IssKeypointConfig,
73}
74
75impl IssKeypointDetector {
76    /// Creates a detector from config.
77    #[must_use]
78    pub const fn new(config: IssKeypointConfig) -> Self {
79        Self { config }
80    }
81
82    /// Returns the detector config.
83    #[must_use]
84    pub const fn config(&self) -> IssKeypointConfig {
85        self.config
86    }
87
88    /// Detects keypoints and returns their indices and a keypoint sub-cloud.
89    ///
90    /// Shares one KD-tree across bounded scoped CPU workers. Saliency completes
91    /// before local-maximum selection reads it. Small/one-worker calls run on
92    /// the caller; neighborhood arithmetic, ties and point order are preserved.
93    pub fn detect(&self, input: &PointCloud) -> SpatialResult<IssKeypointResult> {
94        self.detect_with_workers(input, parallel_worker_count(input.len()))
95    }
96
97    /// Explicitly uploads input and computes radius graphs, covariance,
98    /// eigenvalue saliency and non-maximum suppression on the supplied GPU.
99    /// CPU tree construction, ordered flag compaction and attribute gathering
100    /// remain host operations; no automatic CPU fallback occurs.
101    /// Both capacities include self and must fit ALL radius matches. Overflow
102    /// rejects instead of silently using truncated rows. Positions/extents must
103    /// be finite, radii must have positive finite nonzero f32 squares, and gamma
104    /// values must be finite in [0,1]. These checks are stricter than CPU ISS.
105    /// GPU f32 covariance/eigen arithmetic can change selection near threshold
106    /// and NMS ties compared with the CPU's f64 arithmetic.
107    /// A nonzero evaluated local extent whose f32 square underflows the normal
108    /// range returns a numerical error; no approximate zero-variance fallback.
109    #[cfg(feature = "feature-iss-gpu")]
110    pub fn detect_with_gpu(
111        &self,
112        runtime: &spatialrust_gpu::WgpuRuntime,
113        input: &PointCloud,
114        salient_capacity: u32,
115        non_max_capacity: u32,
116    ) -> SpatialResult<GpuIssKeypointResult> {
117        let radii = [self.config.salient_radius, self.config.non_max_radius];
118        let gamma = [self.config.gamma_21, self.config.gamma_32];
119        if radii.iter().any(|&r| !r.is_finite() || r <= 0.0 || !(r * r).is_finite() || r * r == 0.0)
120            || gamma.iter().any(|g| !g.is_finite() || !(0.0..=1.0).contains(g))
121        {
122            return Err(SpatialError::InvalidArgument("GPU ISS requires positive finite nonzero radius squares and finite gamma values in [0,1]".to_owned()));
123        }
124        let (x, y, z) = input.positions3()?;
125        if x.iter().chain(y).chain(z).any(|v| !v.is_finite()) {
126            return Err(SpatialError::InvalidArgument("GPU ISS requires finite XYZ".to_owned()));
127        }
128        let tree = KdTree::from_slices(x, y, z);
129        let device_input = spatialrust_gpu::GpuIssInput::upload(runtime, &tree)?;
130        let neighborhoods = device_input.neighborhoods_resident(
131            runtime,
132            self.config.salient_radius,
133            self.config.non_max_radius,
134            salient_capacity,
135            non_max_capacity,
136        )?;
137        let output = device_input.keypoints_resident(
138            runtime,
139            &neighborhoods,
140            self.config.gamma_21,
141            self.config.gamma_32,
142            u32::try_from(self.config.min_neighbors).unwrap_or(u32::MAX),
143        )?;
144        let (indices, downloaded) = output.download(runtime)?;
145        let indices: Vec<_> = indices.into_iter().map(|i| i as usize).collect();
146        let keypoints = gather_indices(input, &indices)?;
147        let mut transfers = device_input.upload_transfers();
148        transfers.record(
149            spatialrust_core::TransferDirection::DeviceToHost,
150            downloaded.device_to_host_bytes(),
151        );
152        Ok(GpuIssKeypointResult { result: IssKeypointResult { indices, keypoints }, transfers })
153    }
154
155    fn detect_with_workers(
156        &self,
157        input: &PointCloud,
158        workers: usize,
159    ) -> SpatialResult<IssKeypointResult> {
160        if self.config.salient_radius <= 0.0 || self.config.non_max_radius <= 0.0 {
161            return Err(SpatialError::InvalidArgument("ISS radii must be positive".to_owned()));
162        }
163
164        let (x, y, z) = input.positions3()?;
165        let len = input.len();
166        let tree = KdTree::from_slices(x, y, z);
167        let workers = workers.max(1).min(len.max(1));
168
169        // Saliency = smallest eigenvalue (lambda3) where the eigenvalue-ratio
170        // tests pass; NaN marks a non-salient point.
171        let mut saliency = vec![f32::NAN; len];
172        fill_bands(&mut saliency, workers, |start, band| {
173            for (offset, value) in band.iter_mut().enumerate() {
174                let i = start + offset;
175                let neighbors = tree.radius_search(x[i], y[i], z[i], self.config.salient_radius);
176                if neighbors.len() < self.config.min_neighbors {
177                    continue;
178                }
179                let Some(eigenvalues) = neighborhood_eigenvalues(x, y, z, &neighbors) else {
180                    continue;
181                };
182                // Ascending order: l3 <= l2 <= l1.
183                let (l3, l2, l1) = (eigenvalues[0], eigenvalues[1], eigenvalues[2]);
184                if l1 <= 0.0 || l2 <= 0.0 {
185                    continue;
186                }
187                if (l2 / l1) < f64::from(self.config.gamma_21)
188                    && (l3 / l2) < f64::from(self.config.gamma_32)
189                {
190                    *value = l3 as f32;
191                }
192            }
193        });
194
195        // The completed saliency array is immutable throughout this phase.
196        // Equal maxima all survive, retaining the original >= tie behavior.
197        let is_keypoint = |i: usize| {
198            let s = saliency[i];
199            if s.is_nan() {
200                return false;
201            }
202            let neighbors = tree.radius_search(x[i], y[i], z[i], self.config.non_max_radius);
203            neighbors.iter().all(|n| {
204                let other = saliency[n.index];
205                n.index == i || other.is_nan() || s >= other
206            })
207        };
208        let mut indices = Vec::new();
209        if workers == 1 {
210            for i in 0..len {
211                if is_keypoint(i) {
212                    indices.push(i);
213                }
214            }
215        } else {
216            // One temporary byte per point avoids worker-local index vectors
217            // and a second result-sized index allocation during ordered joins.
218            let mut selected = vec![false; len];
219            fill_bands(&mut selected, workers, |start, band| {
220                for (offset, value) in band.iter_mut().enumerate() {
221                    *value = is_keypoint(start + offset);
222                }
223            });
224            for (i, selected) in selected.into_iter().enumerate() {
225                if selected {
226                    indices.push(i);
227                }
228            }
229        }
230
231        let keypoints = gather_indices(input, &indices)?;
232        Ok(IssKeypointResult { indices, keypoints })
233    }
234}
235
236/// Fills disjoint output bands, joining all workers before the next phase.
237fn fill_bands<T: Send, F: Fn(usize, &mut [T]) + Sync>(output: &mut [T], workers: usize, fill: F) {
238    if workers == 1 {
239        fill(0, output);
240        return;
241    }
242    let chunk_size = output.len().div_ceil(workers);
243    std::thread::scope(|scope| {
244        for (band, chunk) in output.chunks_mut(chunk_size).enumerate() {
245            let fill = &fill;
246            scope.spawn(move || fill(band * chunk_size, chunk));
247        }
248    });
249}
250
251#[cfg(all(test, not(target_arch = "wasm32")))]
252#[path = "../tests/fixtures/iss_serial.rs"]
253#[allow(dead_code)]
254mod previous;
255
256#[cfg(all(test, not(target_arch = "wasm32")))]
257#[path = "iss_parallel_tests.rs"]
258mod parallel_tests;
259
260#[cfg(all(test, not(target_arch = "wasm32")))]
261#[path = "iss_parallel_benchmark.rs"]
262mod parallel_benchmark;
263
264/// Eigenvalues (ascending) of the neighborhood covariance about its centroid.
265fn neighborhood_eigenvalues(
266    x: &[f32],
267    y: &[f32],
268    z: &[f32],
269    neighbors: &[spatialrust_search::Neighbor],
270) -> Option<[f64; 3]> {
271    let count = neighbors.len() as f64;
272    if count < 3.0 {
273        return None;
274    }
275    let (mut mx, mut my, mut mz) = (0.0_f64, 0.0_f64, 0.0_f64);
276    for n in neighbors {
277        mx += f64::from(x[n.index]);
278        my += f64::from(y[n.index]);
279        mz += f64::from(z[n.index]);
280    }
281    mx /= count;
282    my /= count;
283    mz /= count;
284
285    let (mut c00, mut c11, mut c22) = (0.0_f64, 0.0, 0.0);
286    let (mut c01, mut c02, mut c12) = (0.0_f64, 0.0, 0.0);
287    for n in neighbors {
288        let dx = f64::from(x[n.index]) - mx;
289        let dy = f64::from(y[n.index]) - my;
290        let dz = f64::from(z[n.index]) - mz;
291        c00 += dx * dx;
292        c11 += dy * dy;
293        c22 += dz * dz;
294        c01 += dx * dy;
295        c02 += dx * dz;
296        c12 += dy * dz;
297    }
298    let inv = 1.0 / count;
299    let covariance = Mat3::<f64>::from_rows(
300        [c00 * inv, c01 * inv, c02 * inv],
301        [c01 * inv, c11 * inv, c12 * inv],
302        [c02 * inv, c12 * inv, c22 * inv],
303    );
304    Some(symmetric_eigen3(covariance).eigenvalues)
305}
306
307/// Gathers the selected indices into a new cloud, preserving schema.
308fn gather_indices(input: &PointCloud, indices: &[usize]) -> SpatialResult<PointCloud> {
309    let mut buffers = PointBufferSet::new();
310    for field in input.schema().fields() {
311        let source = input.field(&field.name)?;
312        buffers.insert(field.name.clone(), gather_buffer(source, indices));
313    }
314    PointCloud::try_from_parts(input.schema().clone(), buffers, input.metadata().clone())
315}
316
317fn gather_buffer(source: &PointBuffer, indices: &[usize]) -> PointBuffer {
318    match source {
319        PointBuffer::F32(v) => PointBuffer::from_f32(indices.iter().map(|&i| v[i]).collect()),
320        PointBuffer::F64(v) => PointBuffer::F64(indices.iter().map(|&i| v[i]).collect()),
321        PointBuffer::U8(v) => PointBuffer::U8(indices.iter().map(|&i| v[i]).collect()),
322        PointBuffer::U16(v) => PointBuffer::U16(indices.iter().map(|&i| v[i]).collect()),
323        PointBuffer::U32(v) => PointBuffer::U32(indices.iter().map(|&i| v[i]).collect()),
324        PointBuffer::I32(v) => PointBuffer::I32(indices.iter().map(|&i| v[i]).collect()),
325    }
326}
327
328#[cfg(test)]
329mod tests {
330    use super::{IssKeypointConfig, IssKeypointDetector};
331    use spatialrust_core::{PointCloudBuilder, StandardSchemas};
332
333    /// A flat floor plus a sharp spike — the spike tip should be a keypoint and
334    /// the flat region should not.
335    fn floor_with_spike() -> spatialrust_core::PointCloud {
336        let mut builder = PointCloudBuilder::new(StandardSchemas::point_xyz());
337        for i in 0..30 {
338            for j in 0..30 {
339                builder.push_point([i as f32 * 0.05, j as f32 * 0.05, 0.0]).unwrap();
340            }
341        }
342        // A small dense cluster rising off the plane near its center.
343        for k in 0..40 {
344            let h = k as f32 * 0.02;
345            builder.push_point([0.75, 0.75, h]).unwrap();
346            builder.push_point([0.77, 0.75, h]).unwrap();
347            builder.push_point([0.75, 0.77, h]).unwrap();
348        }
349        builder.build().unwrap()
350    }
351
352    #[test]
353    fn finds_keypoints_on_salient_structure() {
354        let cloud = floor_with_spike();
355        let detector = IssKeypointDetector::new(IssKeypointConfig {
356            salient_radius: 0.12,
357            non_max_radius: 0.08,
358            gamma_21: 0.9,
359            gamma_32: 0.9,
360            min_neighbors: 5,
361        });
362        let result = detector.detect(&cloud).unwrap();
363        // Some keypoints found, far fewer than the input size.
364        assert!(!result.indices.is_empty());
365        assert!(result.indices.len() < cloud.len() / 4);
366        assert_eq!(result.keypoints.len(), result.indices.len());
367    }
368
369    #[test]
370    fn flat_plane_interior_is_not_salient() {
371        let n = 20;
372        let mut builder = PointCloudBuilder::new(StandardSchemas::point_xyz());
373        for i in 0..n {
374            for j in 0..n {
375                builder.push_point([i as f32 * 0.05, j as f32 * 0.05, 0.0]).unwrap();
376            }
377        }
378        let cloud = builder.build().unwrap();
379        let detector = IssKeypointDetector::new(IssKeypointConfig::with_radii(0.12, 0.08));
380        let result = detector.detect(&cloud).unwrap();
381        // ISS legitimately flags the plane's boundary (a real edge), but the
382        // isotropic interior (lambda1 ~ lambda2) must be rejected by gamma_21.
383        let center = (n / 2) * n + (n / 2);
384        assert!(!result.indices.contains(&center), "plane interior should not be salient");
385    }
386
387    #[test]
388    fn rejects_bad_radii() {
389        let cloud = floor_with_spike();
390        let detector = IssKeypointDetector::new(IssKeypointConfig::with_radii(0.0, 0.1));
391        assert!(detector.detect(&cloud).is_err());
392    }
393}