spatialrust_segmentation/
cluster.rs1use std::collections::{HashMap, VecDeque};
2
3#[cfg(feature = "segment-euclidean-gpu")]
4use spatialrust_core::DeviceKind;
5use spatialrust_core::{
6 ExecutionOutput, ExecutionPolicy, ExecutionReceipt, HasPositions3, PointCloud, SpatialError,
7 SpatialResult, TransferDirection,
8};
9use spatialrust_search::{KdTree, RadiusSearchIndex};
10
11use crate::cloud::with_labels;
12use crate::segmenter::PointCloudSegmenter;
13
14pub const DEFAULT_GPU_KDTREE_MIN_POINTS: usize = 50_000;
16
17pub const DEFAULT_GPU_MIN_POINTS_EUCLIDEAN: usize = 2_000;
19
20#[derive(Clone, Copy, Debug, PartialEq)]
22pub struct EuclideanClusterConfig {
23 pub cluster_tolerance: f32,
25 pub min_cluster_size: usize,
27 pub max_cluster_size: usize,
29 pub gpu_min_points: Option<usize>,
33}
34
35impl Default for EuclideanClusterConfig {
36 fn default() -> Self {
37 Self {
38 cluster_tolerance: 0.02,
39 min_cluster_size: 1,
40 max_cluster_size: usize::MAX,
41 gpu_min_points: Some(DEFAULT_GPU_MIN_POINTS_EUCLIDEAN),
42 }
43 }
44}
45
46impl EuclideanClusterConfig {
47 #[must_use]
49 pub const fn with_tolerance(cluster_tolerance: f32, min_cluster_size: usize) -> Self {
50 Self {
51 cluster_tolerance,
52 min_cluster_size,
53 max_cluster_size: usize::MAX,
54 gpu_min_points: Some(DEFAULT_GPU_MIN_POINTS_EUCLIDEAN),
55 }
56 }
57
58 #[must_use]
60 pub const fn without_gpu_min_points(mut self) -> Self {
61 self.gpu_min_points = None;
62 self
63 }
64
65 #[must_use]
67 pub const fn effective_gpu_min_points(&self) -> Option<usize> {
68 self.gpu_min_points
69 }
70}
71
72#[derive(Clone, Debug, PartialEq)]
74pub struct EuclideanClusterResult {
75 pub cloud: PointCloud,
77 pub cluster_count: usize,
79 pub cluster_sizes: Vec<usize>,
81}
82
83#[derive(Clone, Copy, Debug, PartialEq)]
85pub struct EuclideanClusterExtractor {
86 config: EuclideanClusterConfig,
87}
88
89impl EuclideanClusterExtractor {
90 #[must_use]
92 pub const fn new(config: EuclideanClusterConfig) -> Self {
93 Self { config }
94 }
95
96 #[must_use]
98 pub const fn config(&self) -> EuclideanClusterConfig {
99 self.config
100 }
101
102 pub fn extract(&self, input: &PointCloud) -> SpatialResult<EuclideanClusterResult> {
104 validate_cluster_config(self.config)?;
105 if input.is_empty() {
106 return Ok(EuclideanClusterResult {
107 cloud: input.clone(),
108 cluster_count: 0,
109 cluster_sizes: Vec::new(),
110 });
111 }
112 let roots = extract_cpu_roots(input, self.config)?;
113 finalize_euclidean_clusters(input, &roots, self.config)
114 }
115
116 pub fn extract_with_policy(
124 &self,
125 input: &PointCloud,
126 policy: ExecutionPolicy,
127 ) -> SpatialResult<EuclideanClusterResult> {
128 self.extract_with_policy_and_receipt(input, policy).map(ExecutionOutput::into_output)
129 }
130
131 pub fn extract_with_policy_and_receipt(
133 &self,
134 input: &PointCloud,
135 policy: ExecutionPolicy,
136 ) -> SpatialResult<ExecutionOutput<EuclideanClusterResult>> {
137 policy.validate()?;
138 let (output, resolved_policy, transfers) = self.extract_policy_output(input, policy)?;
139 let mut receipt = ExecutionReceipt::new(policy, resolved_policy);
140 receipt.record_stage("euclidean-clustering");
141 if let Some(transfers) = transfers {
142 receipt
143 .record_transfer(TransferDirection::HostToDevice, transfers.host_to_device_bytes());
144 receipt.record_transfer(
145 TransferDirection::DeviceToDevice,
146 transfers.device_to_device_bytes(),
147 );
148 receipt
149 .record_transfer(TransferDirection::DeviceToHost, transfers.device_to_host_bytes());
150 if !input.is_empty() {
151 if self.config.cluster_tolerance.is_finite() {
152 receipt.record_stage("gpu-sparse-grid");
153 }
154 receipt.record_stage("gpu-component-labeling");
155 }
156 }
157 Ok(ExecutionOutput::new(output, receipt))
158 }
159
160 fn extract_policy_output(
161 &self,
162 input: &PointCloud,
163 policy: ExecutionPolicy,
164 ) -> SpatialResult<(
165 EuclideanClusterResult,
166 ExecutionPolicy,
167 Option<spatialrust_core::TransferStats>,
168 )> {
169 #[cfg(feature = "segment-euclidean-gpu")]
170 {
171 let resolved = self.resolve_policy(input, policy)?;
172 if matches!(resolved, ExecutionPolicy::Gpu(DeviceKind::Wgpu)) {
173 if !self.gpu_grid_fits(input) {
174 if policy.allows_fallback() {
175 return Ok((self.extract(input)?, ExecutionPolicy::CpuSingle, None));
176 }
177 return Err(SpatialError::InvalidArgument(
178 "point cloud does not fit the GPU Euclidean clustering grid".to_owned(),
179 ));
180 }
181 let (output, transfers) =
182 crate::cluster_gpu::GpuEuclideanClusterExtractor::new(self.config)
183 .extract_with_receipt(input)?;
184 return Ok((output, resolved, Some(transfers)));
185 }
186 }
187
188 #[cfg(not(feature = "segment-euclidean-gpu"))]
189 if policy.requests_gpu() {
190 return Err(SpatialError::InvalidArgument(
191 "GPU Euclidean clustering requires the segment-euclidean-gpu feature".to_owned(),
192 ));
193 }
194
195 let resolved_policy = match policy {
196 ExecutionPolicy::Auto => ExecutionPolicy::CpuSingle,
197 other => other,
198 };
199 Ok((self.extract(input)?, resolved_policy, None))
200 }
201
202 #[cfg(feature = "segment-euclidean-gpu")]
203 fn gpu_grid_fits(&self, input: &PointCloud) -> bool {
204 let Ok((x, y, z)) = input.positions3() else {
205 return false;
206 };
207 spatialrust_search::uniform_grid_fits(x, y, z, self.config.cluster_tolerance)
208 }
209
210 #[cfg(feature = "segment-euclidean-gpu")]
211 fn should_use_gpu(&self, input: &PointCloud) -> bool {
212 self.config.effective_gpu_min_points().map_or(true, |min_points| input.len() >= min_points)
213 && spatialrust_gpu::WgpuRuntime::shared().is_ok()
214 }
215
216 #[cfg(feature = "segment-euclidean-gpu")]
217 fn resolve_policy(
218 &self,
219 input: &PointCloud,
220 policy: ExecutionPolicy,
221 ) -> SpatialResult<ExecutionPolicy> {
222 match policy {
223 ExecutionPolicy::Auto => {
224 if self.should_use_gpu(input) {
225 Ok(ExecutionPolicy::Gpu(DeviceKind::Wgpu))
226 } else {
227 Ok(ExecutionPolicy::CpuSingle)
228 }
229 }
230 ExecutionPolicy::Gpu(DeviceKind::Cpu) => Err(SpatialError::InvalidArgument(
231 "GPU execution policy cannot target the CPU device".to_owned(),
232 )),
233 ExecutionPolicy::Gpu(DeviceKind::Cuda) => Err(SpatialError::InvalidArgument(
234 "CUDA Euclidean clustering is not available".to_owned(),
235 )),
236 other => Ok(other),
237 }
238 }
239}
240
241impl PointCloudSegmenter for EuclideanClusterExtractor {
242 fn name(&self) -> &'static str {
243 "EuclideanClusterExtractor"
244 }
245}
246
247pub(crate) fn finalize_euclidean_clusters(
249 input: &PointCloud,
250 component_roots: &[u32],
251 config: EuclideanClusterConfig,
252) -> SpatialResult<EuclideanClusterResult> {
253 if component_roots.len() != input.len() {
254 return Err(SpatialError::InvalidArgument(
255 "component root labels must match point count".to_owned(),
256 ));
257 }
258
259 let mut sizes: HashMap<u32, usize> = HashMap::new();
260 for &root in component_roots {
261 *sizes.entry(root).or_insert(0) += 1;
262 }
263
264 let mut valid_roots: Vec<u32> = sizes
265 .iter()
266 .filter(|(_, &size)| size >= config.min_cluster_size && size <= config.max_cluster_size)
267 .map(|(&root, _)| root)
268 .collect();
269 valid_roots.sort_unstable();
270
271 let mut remap: HashMap<u32, i32> = HashMap::new();
272 for (cluster_id, root) in valid_roots.iter().enumerate() {
273 remap.insert(*root, cluster_id as i32);
274 }
275
276 let mut labels = vec![-1_i32; input.len()];
277 let mut cluster_sizes = Vec::with_capacity(valid_roots.len());
278 for root in &valid_roots {
279 cluster_sizes.push(sizes[root]);
280 for (index, &point_root) in component_roots.iter().enumerate() {
281 if point_root == *root {
282 labels[index] = remap[root];
283 }
284 }
285 }
286
287 Ok(EuclideanClusterResult {
288 cloud: with_labels(input, "label", labels)?,
289 cluster_count: cluster_sizes.len(),
290 cluster_sizes,
291 })
292}
293
294pub(crate) fn extract_cpu_roots(
295 input: &PointCloud,
296 config: EuclideanClusterConfig,
297) -> SpatialResult<Vec<u32>> {
298 let (x, y, z) = input.positions3()?;
299 let tree = KdTree::from_slices(x, y, z);
300 let len = input.len();
301 let mut processed = vec![false; len];
302 let mut roots = vec![0u32; len];
303
304 for seed in 0..len {
305 if processed[seed] {
306 continue;
307 }
308
309 let mut queue = VecDeque::from([seed]);
310 let mut cluster_indices = Vec::new();
311 processed[seed] = true;
312
313 while let Some(index) = queue.pop_front() {
314 cluster_indices.push(index);
315 let neighbors =
316 tree.radius_search(x[index], y[index], z[index], config.cluster_tolerance);
317 for neighbor in neighbors {
318 let candidate = neighbor.index;
319 if processed[candidate] {
320 continue;
321 }
322 processed[candidate] = true;
323 queue.push_back(candidate);
324 }
325 }
326
327 let root = *cluster_indices.iter().min().unwrap_or(&seed) as u32;
328 for index in cluster_indices {
329 roots[index] = root;
330 }
331 }
332
333 Ok(roots)
334}
335
336fn validate_cluster_config(config: EuclideanClusterConfig) -> SpatialResult<()> {
337 if config.cluster_tolerance < 0.0 {
338 return Err(SpatialError::InvalidArgument(
339 "cluster_tolerance must be non-negative".to_owned(),
340 ));
341 }
342 if config.min_cluster_size == 0 {
343 return Err(SpatialError::InvalidArgument(
344 "min_cluster_size must be greater than zero".to_owned(),
345 ));
346 }
347 if config.max_cluster_size < config.min_cluster_size {
348 return Err(SpatialError::InvalidArgument(
349 "max_cluster_size must be >= min_cluster_size".to_owned(),
350 ));
351 }
352 Ok(())
353}
354
355#[cfg(test)]
356mod tests {
357 use super::{EuclideanClusterConfig, EuclideanClusterExtractor};
358 use spatialrust_core::{DeviceKind, ExecutionPolicy, PointCloudBuilder, StandardSchemas};
359
360 fn three_clusters() -> spatialrust_core::PointCloud {
361 let mut builder = PointCloudBuilder::new(StandardSchemas::point_xyz());
362 for center in [(0.0, 0.0, 0.0), (10.0, 0.0, 0.0), (0.0, 10.0, 0.0)] {
363 for dx in 0..3 {
364 for dy in 0..3 {
365 builder
366 .push_point([center.0 + dx as f32, center.1 + dy as f32, center.2])
367 .unwrap();
368 }
369 }
370 }
371 builder.build().unwrap()
372 }
373
374 #[test]
375 fn finds_three_separated_clusters() {
376 let input = three_clusters();
377 let extractor = EuclideanClusterExtractor::new(EuclideanClusterConfig {
378 cluster_tolerance: 1.5,
379 min_cluster_size: 3,
380 max_cluster_size: usize::MAX,
381 ..Default::default()
382 });
383 let result = extractor.extract(&input).unwrap();
384 assert_eq!(result.cluster_count, 3);
385 assert!(result.cluster_sizes.iter().all(|&size| size == 9));
386 assert!(result.cloud.field("label").is_ok());
387 }
388
389 #[test]
390 fn rejects_clusters_smaller_than_minimum() {
391 let mut builder = PointCloudBuilder::new(StandardSchemas::point_xyz());
392 builder.push_point([0.0, 0.0, 0.0]).unwrap();
393 builder.push_point([0.1, 0.0, 0.0]).unwrap();
394 let input = builder.build().unwrap();
395
396 let extractor = EuclideanClusterExtractor::new(EuclideanClusterConfig {
397 cluster_tolerance: 0.5,
398 min_cluster_size: 3,
399 max_cluster_size: usize::MAX,
400 ..Default::default()
401 });
402 let result = extractor.extract(&input).unwrap();
403 assert_eq!(result.cluster_count, 0);
404 }
405
406 #[test]
407 fn rejects_unsupported_explicit_gpu_policy() {
408 let extractor = EuclideanClusterExtractor::new(EuclideanClusterConfig::default());
409 let error = extractor
410 .extract_with_policy(&three_clusters(), ExecutionPolicy::Gpu(DeviceKind::Cuda))
411 .unwrap_err();
412 assert!(matches!(error, spatialrust_core::SpatialError::InvalidArgument(_)));
413 }
414}