alice-edge 0.1.0

Embedded Model Generator - Don't send data, send the law
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
// SPDX-License-Identifier: MIT
//! Edge Pipeline Orchestrator
//!
//! Integrates capture → compress → classify → stream into a unified
//! processing loop running at 10Hz on Raspberry Pi 5.
//!
//! Author: Moroya Sakamoto

use std::time::{Duration, Instant};

use crate::asp_bridge::{AspEdgePacket, EdgeStreamEncoder};
use crate::depth_capture::{
    CameraConfig, DepthCameraDriver, DepthFrame, DolphinD5Driver, PointNormal,
};
use crate::object_classifier::{ObjectClass, SdfFeatures, TernaryClassifier, DEFAULT_NUM_CLASSES};
use crate::sdf_compress::{compress_point_cloud, CompressConfig, CompressStats, CompressedSdf};

/// Pipeline configuration
#[derive(Debug, Clone)]
pub struct PipelineConfig {
    /// Camera configuration
    pub camera: CameraConfig,
    /// SDF compression configuration
    pub compress: CompressConfig,
    /// Target frame rate (Hz)
    pub target_fps: f32,
    /// ASP keyframe interval (frames)
    pub keyframe_interval: u32,
    /// Number of classification categories
    pub num_classes: usize,
}

impl Default for PipelineConfig {
    fn default() -> Self {
        Self {
            camera: CameraConfig::default(),
            compress: CompressConfig::default(),
            target_fps: 10.0,
            keyframe_interval: 30,
            num_classes: DEFAULT_NUM_CLASSES,
        }
    }
}

/// Pipeline statistics for monitoring
#[derive(Debug, Clone, Default)]
pub struct PipelineStats {
    /// Total frames processed
    pub frames_processed: u64,
    /// Total keyframes sent
    pub keyframes_sent: u64,
    /// Total deltas sent
    pub deltas_sent: u64,
    /// Total frames skipped (no change)
    pub frames_skipped: u64,
    /// Average capture latency (ms)
    pub avg_capture_ms: f64,
    /// Average compress latency (ms)
    pub avg_compress_ms: f64,
    /// Average classify latency (ms)
    pub avg_classify_ms: f64,
    /// Average encode latency (ms)
    pub avg_encode_ms: f64,
    /// Average total pipeline latency (ms)
    pub avg_total_ms: f64,
    /// Total bytes transmitted
    pub total_bytes_sent: u64,
}

/// Callback for transmitting encoded packets
pub trait PacketSink: Send {
    fn send_keyframe(&mut self, scene_data: &[u8], frame_id: u64);
    fn send_delta(&mut self, delta_data: &[u8], frame_id: u64);
}

/// Edge processing pipeline
///
/// Orchestrates: capture → downsample → compress → classify → encode
pub struct EdgePipeline {
    config: PipelineConfig,
    driver: Box<dyn DepthCameraDriver>,
    classifier: TernaryClassifier,
    encoder: EdgeStreamEncoder,
    stats: PipelineStats,
    latency_sum_capture: f64,
    latency_sum_compress: f64,
    latency_sum_classify: f64,
    latency_sum_encode: f64,
    latency_sum_total: f64,
}

impl EdgePipeline {
    /// Create a new edge pipeline with Dolphin D5 Lite driver
    pub fn new(config: PipelineConfig) -> Self {
        let driver = Box::new(DolphinD5Driver::new(config.camera.clone()));
        let classifier = TernaryClassifier::new(config.num_classes);
        let encoder = EdgeStreamEncoder::new(config.keyframe_interval);

        Self {
            config,
            driver,
            classifier,
            encoder,
            stats: PipelineStats::default(),
            latency_sum_capture: 0.0,
            latency_sum_compress: 0.0,
            latency_sum_classify: 0.0,
            latency_sum_encode: 0.0,
            latency_sum_total: 0.0,
        }
    }

    /// Create pipeline with custom driver (for testing)
    pub fn with_driver(config: PipelineConfig, driver: Box<dyn DepthCameraDriver>) -> Self {
        let classifier = TernaryClassifier::new(config.num_classes);
        let encoder = EdgeStreamEncoder::new(config.keyframe_interval);

        Self {
            config,
            driver,
            classifier,
            encoder,
            stats: PipelineStats::default(),
            latency_sum_capture: 0.0,
            latency_sum_compress: 0.0,
            latency_sum_classify: 0.0,
            latency_sum_encode: 0.0,
            latency_sum_total: 0.0,
        }
    }

    /// Initialize the pipeline (connects to camera)
    pub fn init(&mut self) -> Result<(), crate::depth_capture::CaptureError> {
        self.driver.init()
    }

    /// Process a single frame through the pipeline
    ///
    /// Returns the encoded ASP packet and compression statistics.
    pub fn process_frame(
        &mut self,
    ) -> Result<(AspEdgePacket, CompressStats), crate::depth_capture::CaptureError> {
        let total_start = Instant::now();

        // Stage 1: Capture
        let capture_start = Instant::now();
        let frame = self.driver.capture_frame()?;
        let capture_ms = capture_start.elapsed().as_secs_f64() * 1000.0;

        // Downsample
        let mut points = frame.points;
        if !points.is_empty() {
            points = DolphinD5Driver::voxel_downsample(&points, self.config.camera.voxel_size);
            DolphinD5Driver::estimate_normals(&mut points, self.config.camera.normal_k);
        }

        // Convert to f32 array for compression
        let point_arrays: Vec<[f32; 3]> = points.iter().map(|p| [p.x, p.y, p.z]).collect();

        // Stage 2: Compress
        let compress_start = Instant::now();
        let (compressed, compress_stats) =
            compress_point_cloud(&point_arrays, &self.config.compress);
        let compress_ms = compress_start.elapsed().as_secs_f64() * 1000.0;

        // Stage 3: Classify
        let classify_start = Instant::now();
        let classifications = self.classify_compressed(&compressed, &point_arrays);
        let classify_ms = classify_start.elapsed().as_secs_f64() * 1000.0;

        // Stage 4: Encode to ASP
        let encode_start = Instant::now();
        let packet = self.encoder.encode_frame(&compressed, &classifications);
        let encode_ms = encode_start.elapsed().as_secs_f64() * 1000.0;

        let total_ms = total_start.elapsed().as_secs_f64() * 1000.0;

        // Update stats
        self.stats.frames_processed += 1;
        self.latency_sum_capture += capture_ms;
        self.latency_sum_compress += compress_ms;
        self.latency_sum_classify += classify_ms;
        self.latency_sum_encode += encode_ms;
        self.latency_sum_total += total_ms;

        let n = self.stats.frames_processed as f64;
        let inv_n = 1.0 / n;
        self.stats.avg_capture_ms = self.latency_sum_capture * inv_n;
        self.stats.avg_compress_ms = self.latency_sum_compress * inv_n;
        self.stats.avg_classify_ms = self.latency_sum_classify * inv_n;
        self.stats.avg_encode_ms = self.latency_sum_encode * inv_n;
        self.stats.avg_total_ms = self.latency_sum_total * inv_n;

        match &packet {
            AspEdgePacket::Keyframe { .. } => {
                self.stats.keyframes_sent += 1;
                self.stats.total_bytes_sent += compress_stats.output_bytes as u64;
            }
            AspEdgePacket::Delta { .. } => {
                self.stats.deltas_sent += 1;
                self.stats.total_bytes_sent += compress_stats.output_bytes as u64;
            }
            AspEdgePacket::Skip { .. } => {
                self.stats.frames_skipped += 1;
            }
        }

        Ok((packet, compress_stats))
    }

    /// Run the pipeline loop for a specified duration
    pub fn run_for(&mut self, duration: Duration) -> Vec<(AspEdgePacket, CompressStats)> {
        let frame_interval = Duration::from_secs_f64(1.0 / self.config.target_fps as f64);
        let start = Instant::now();
        let mut results = Vec::new();

        while start.elapsed() < duration {
            let frame_start = Instant::now();

            match self.process_frame() {
                Ok(result) => results.push(result),
                Err(_e) => {} // Skip failed frames
            }

            // Maintain target frame rate
            let frame_elapsed = frame_start.elapsed();
            if frame_elapsed < frame_interval {
                std::thread::sleep(frame_interval - frame_elapsed);
            }
        }

        results
    }

    /// Get current pipeline statistics
    #[must_use]
    pub fn stats(&self) -> &PipelineStats {
        &self.stats
    }

    fn classify_compressed(
        &self,
        compressed: &CompressedSdf,
        points: &[[f32; 3]],
    ) -> Vec<(u8, ObjectClass)> {
        match compressed {
            CompressedSdf::Primitives { primitives, .. } => {
                let bounds = compute_bounds_size(points);
                let point_len = points.len();
                primitives
                    .iter()
                    .enumerate()
                    .map(|(i, prim)| {
                        let features = SdfFeatures::from_primitive(
                            prim.kind as u8,
                            &prim.params,
                            bounds,
                            point_len,
                        );
                        let (class, _conf) = self.classifier.classify(&features);
                        (i as u8, class)
                    })
                    .collect()
            }
            CompressedSdf::SvoChunks {
                chunks,
                total_nodes,
            } => {
                chunks
                    .iter()
                    .map(|chunk| {
                        let bounds_size = [
                            chunk.bounds_max[0] - chunk.bounds_min[0],
                            chunk.bounds_max[1] - chunk.bounds_min[1],
                            chunk.bounds_max[2] - chunk.bounds_min[2],
                        ];
                        let features = SdfFeatures::from_svo_stats(
                            *total_nodes,
                            chunk.node_count,
                            6, // default depth
                            bounds_size,
                        );
                        let (class, _conf) = self.classifier.classify(&features);
                        (chunk.chunk_id as u8, class)
                    })
                    .collect()
            }
            CompressedSdf::Hybrid {
                primitives,
                svo_chunks,
                ..
            } => {
                let bounds = compute_bounds_size(points);
                let point_len = points.len();
                let mut results: Vec<(u8, ObjectClass)> = primitives
                    .iter()
                    .enumerate()
                    .map(|(i, prim)| {
                        let features = SdfFeatures::from_primitive(
                            prim.kind as u8,
                            &prim.params,
                            bounds,
                            point_len,
                        );
                        let (class, _) = self.classifier.classify(&features);
                        (i as u8, class)
                    })
                    .collect();

                for chunk in svo_chunks {
                    let bounds_size = [
                        chunk.bounds_max[0] - chunk.bounds_min[0],
                        chunk.bounds_max[1] - chunk.bounds_min[1],
                        chunk.bounds_max[2] - chunk.bounds_min[2],
                    ];
                    let features = SdfFeatures::from_svo_stats(
                        chunk.node_count,
                        chunk.node_count,
                        6,
                        bounds_size,
                    );
                    let (class, _) = self.classifier.classify(&features);
                    results.push((chunk.chunk_id as u8, class));
                }

                results
            }
        }
    }
}

/// Voxel grid downsampling — averages points within each voxel cell [E6]
///
/// More accurate than simple strided sampling. Groups points by voxel
/// coordinate and outputs centroid of each occupied voxel.
///
/// # Arguments
///
/// * `points` - Input point cloud (x, y, z)
/// * `voxel_size` - Edge length of each voxel cube (meters)
///
/// # Returns
///
/// Downsampled point cloud
#[must_use]
pub fn voxel_grid_downsample(points: &[[f32; 3]], voxel_size: f32) -> Vec<[f32; 3]> {
    if points.is_empty() || voxel_size <= 0.0 {
        return points.to_vec();
    }

    let inv_voxel = 1.0 / voxel_size;
    let mut voxel_map: std::collections::HashMap<(i32, i32, i32), (f64, f64, f64, u32)> =
        std::collections::HashMap::new();

    for p in points {
        let vx = (p[0] * inv_voxel).floor() as i32;
        let vy = (p[1] * inv_voxel).floor() as i32;
        let vz = (p[2] * inv_voxel).floor() as i32;

        let entry = voxel_map.entry((vx, vy, vz)).or_insert((0.0, 0.0, 0.0, 0));
        entry.0 += p[0] as f64;
        entry.1 += p[1] as f64;
        entry.2 += p[2] as f64;
        entry.3 += 1;
    }

    voxel_map
        .values()
        .map(|&(sx, sy, sz, count)| {
            let inv = 1.0 / count as f64;
            [(sx * inv) as f32, (sy * inv) as f32, (sz * inv) as f32]
        })
        .collect()
}

#[inline(always)]
fn compute_bounds_size(points: &[[f32; 3]]) -> [f32; 3] {
    if points.is_empty() {
        return [1.0, 1.0, 1.0];
    }
    let mut min = [f32::MAX; 3];
    let mut max = [f32::MIN; 3];
    for p in points {
        min[0] = min[0].min(p[0]);
        min[1] = min[1].min(p[1]);
        min[2] = min[2].min(p[2]);
        max[0] = max[0].max(p[0]);
        max[1] = max[1].max(p[1]);
        max[2] = max[2].max(p[2]);
    }
    [
        (max[0] - min[0]).max(0.001),
        (max[1] - min[1]).max(0.001),
        (max[2] - min[2]).max(0.001),
    ]
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Mock depth camera for testing
    struct MockCamera {
        frame_counter: u32,
    }

    impl DepthCameraDriver for MockCamera {
        fn init(&mut self) -> Result<(), crate::depth_capture::CaptureError> {
            Ok(())
        }

        fn capture_frame(&mut self) -> Result<DepthFrame, crate::depth_capture::CaptureError> {
            self.frame_counter += 1;
            Ok(DepthFrame {
                points: vec![
                    PointNormal {
                        x: 0.0,
                        y: 0.0,
                        z: 1.0,
                        ..Default::default()
                    },
                    PointNormal {
                        x: 0.1,
                        y: 0.0,
                        z: 1.0,
                        ..Default::default()
                    },
                    PointNormal {
                        x: 0.0,
                        y: 0.1,
                        z: 1.0,
                        ..Default::default()
                    },
                ],
                timestamp_ms: self.frame_counter as u64 * 100,
                frame_id: self.frame_counter,
            })
        }

        fn is_connected(&self) -> bool {
            true
        }
        fn info(&self) -> String {
            "MockCamera".to_string()
        }
    }

    #[test]
    fn test_pipeline_creation() {
        let config = PipelineConfig::default();
        let mock = Box::new(MockCamera { frame_counter: 0 });
        let pipeline = EdgePipeline::with_driver(config, mock);
        assert_eq!(pipeline.stats().frames_processed, 0);
    }

    #[test]
    fn test_pipeline_process_frame() {
        let config = PipelineConfig::default();
        let mock = Box::new(MockCamera { frame_counter: 0 });
        let mut pipeline = EdgePipeline::with_driver(config, mock);
        pipeline.init().unwrap();

        let (packet, _) = pipeline.process_frame().unwrap();
        assert!(matches!(packet, AspEdgePacket::Keyframe { .. }));
        assert_eq!(pipeline.stats().frames_processed, 1);
    }

    #[test]
    fn test_pipeline_stats_update() {
        let config = PipelineConfig::default();
        let mock = Box::new(MockCamera { frame_counter: 0 });
        let mut pipeline = EdgePipeline::with_driver(config, mock);
        pipeline.init().unwrap();

        for _ in 0..5 {
            let _ = pipeline.process_frame();
        }

        let stats = pipeline.stats();
        assert_eq!(stats.frames_processed, 5);
        assert!(stats.avg_total_ms >= 0.0);
    }

    // ── E6: ボクセルダウンサンプル テスト ──────────────────────────

    #[test]
    fn test_voxel_grid_downsample_basic() {
        // 同じボクセル内の3点 → 1点に集約
        let points = vec![[0.01, 0.01, 0.01], [0.02, 0.02, 0.02], [0.03, 0.03, 0.03]];
        let result = voxel_grid_downsample(&points, 0.1);
        assert_eq!(result.len(), 1);
        // 平均: (0.01+0.02+0.03)/3 = 0.02
        assert!((result[0][0] - 0.02).abs() < 0.001);
    }

    #[test]
    fn test_voxel_grid_downsample_separate() {
        // 離れた2点 → 2点のまま
        let points = vec![[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]];
        let result = voxel_grid_downsample(&points, 0.1);
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn test_voxel_grid_downsample_empty() {
        let result = voxel_grid_downsample(&[], 0.1);
        assert!(result.is_empty());
    }

    #[test]
    fn test_voxel_grid_downsample_zero_size() {
        let points = vec![[0.0, 0.0, 0.0]];
        let result = voxel_grid_downsample(&points, 0.0);
        assert_eq!(result.len(), 1);
    }

    #[test]
    fn test_pipeline_multi_frame_keyframe_delta() {
        let config = PipelineConfig {
            keyframe_interval: 3,
            ..PipelineConfig::default()
        };
        let mock = Box::new(MockCamera { frame_counter: 0 });
        let mut pipeline = EdgePipeline::with_driver(config, mock);
        pipeline.init().unwrap();

        // Frame 1: keyframe
        let (p1, _) = pipeline.process_frame().unwrap();
        assert!(matches!(p1, AspEdgePacket::Keyframe { .. }));

        // Frame 2: delta or skip (data changes each frame)
        let (p2, _) = pipeline.process_frame().unwrap();
        assert!(matches!(
            p2,
            AspEdgePacket::Delta { .. } | AspEdgePacket::Skip { .. }
        ));

        // Frame 3: keyframe (interval=3)
        let (p3, _) = pipeline.process_frame().unwrap();
        assert!(matches!(p3, AspEdgePacket::Keyframe { .. }));
    }

    #[test]
    fn test_pipeline_latency_stats_accumulate() {
        let config = PipelineConfig::default();
        let mock = Box::new(MockCamera { frame_counter: 0 });
        let mut pipeline = EdgePipeline::with_driver(config, mock);
        pipeline.init().unwrap();

        for _ in 0..10 {
            let _ = pipeline.process_frame();
        }

        let stats = pipeline.stats();
        assert_eq!(stats.frames_processed, 10);
        assert!(stats.avg_capture_ms >= 0.0);
        assert!(stats.avg_compress_ms >= 0.0);
        assert!(stats.avg_classify_ms >= 0.0);
        assert!(stats.avg_encode_ms >= 0.0);
        assert!(stats.avg_total_ms >= stats.avg_capture_ms);
        // keyframes + deltas + skips = total frames
        assert_eq!(
            stats.keyframes_sent + stats.deltas_sent + stats.frames_skipped,
            stats.frames_processed
        );
    }

    #[test]
    fn test_pipeline_bytes_sent_tracking() {
        let config = PipelineConfig::default();
        let mock = Box::new(MockCamera { frame_counter: 0 });
        let mut pipeline = EdgePipeline::with_driver(config, mock);
        pipeline.init().unwrap();

        let _ = pipeline.process_frame().unwrap();
        // 最初のフレームは keyframe なのでバイト送信がある
        assert!(pipeline.stats().total_bytes_sent > 0);
    }

    /// 空のフレームを返すモックカメラ
    struct EmptyCamera;
    impl DepthCameraDriver for EmptyCamera {
        fn init(&mut self) -> Result<(), crate::depth_capture::CaptureError> {
            Ok(())
        }
        fn capture_frame(&mut self) -> Result<DepthFrame, crate::depth_capture::CaptureError> {
            Ok(DepthFrame {
                points: vec![],
                timestamp_ms: 0,
                frame_id: 0,
            })
        }
        fn is_connected(&self) -> bool {
            true
        }
        fn info(&self) -> String {
            "EmptyCamera".to_string()
        }
    }

    #[test]
    fn test_pipeline_empty_frame() {
        let config = PipelineConfig::default();
        let mock = Box::new(EmptyCamera);
        let mut pipeline = EdgePipeline::with_driver(config, mock);
        pipeline.init().unwrap();

        let (packet, compress_stats) = pipeline.process_frame().unwrap();
        assert!(matches!(packet, AspEdgePacket::Keyframe { .. }));
        assert_eq!(compress_stats.input_points, 0);
    }

    #[test]
    fn test_classify_compressed_primitives() {
        use crate::sdf_compress::{PrimitiveKind, SerializedPrimitive};
        let config = PipelineConfig::default();
        let mock = Box::new(MockCamera { frame_counter: 0 });
        let pipeline = EdgePipeline::with_driver(config, mock);

        let compressed = CompressedSdf::Primitives {
            primitives: vec![SerializedPrimitive {
                kind: PrimitiveKind::Sphere,
                params: [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0],
                mse: 0.001,
            }],
            asdf_data: vec![1, 2, 3],
        };
        let points = vec![[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]];
        let result = pipeline.classify_compressed(&compressed, &points);
        assert_eq!(result.len(), 1);
    }

    #[test]
    fn test_classify_compressed_svo_chunks() {
        use crate::sdf_compress::SvoChunkData;
        let config = PipelineConfig::default();
        let mock = Box::new(MockCamera { frame_counter: 0 });
        let pipeline = EdgePipeline::with_driver(config, mock);

        let compressed = CompressedSdf::SvoChunks {
            chunks: vec![
                SvoChunkData {
                    chunk_id: 0,
                    data: vec![1, 2, 3, 4],
                    node_count: 10,
                    bounds_min: [-1.0, -1.0, -1.0],
                    bounds_max: [1.0, 1.0, 1.0],
                },
                SvoChunkData {
                    chunk_id: 1,
                    data: vec![5, 6, 7, 8],
                    node_count: 5,
                    bounds_min: [0.0, 0.0, 0.0],
                    bounds_max: [2.0, 2.0, 2.0],
                },
            ],
            total_nodes: 15,
        };
        let points = vec![[0.0, 0.0, 0.0]];
        let result = pipeline.classify_compressed(&compressed, &points);
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].0, 0);
        assert_eq!(result[1].0, 1);
    }

    #[test]
    fn test_compute_bounds_size_empty() {
        let bounds = compute_bounds_size(&[]);
        assert_eq!(bounds, [1.0, 1.0, 1.0]);
    }

    #[test]
    fn test_voxel_grid_negative_size() {
        let points = vec![[0.0, 0.0, 0.0]];
        let result = voxel_grid_downsample(&points, -1.0);
        assert_eq!(result.len(), 1);
    }
}