scirs2-ndimage 0.4.1

N-dimensional image processing module for SciRS2 (scirs2-ndimage)
Documentation
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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
//! GPU-accelerated chunked image processing
//!
//! This module provides GPU-accelerated versions of chunked image processing
//! operations. It integrates with the backend module to automatically select
//! the best available GPU backend (CUDA, OpenCL, Metal).
//!
//! # Features
//!
//! - **Automatic GPU detection**: Selects the best available GPU backend
//! - **Hybrid processing**: Falls back to CPU for small chunks
//! - **Memory management**: Efficient GPU memory allocation and pooling
//! - **Async transfers**: Overlapping compute and data transfer
//!
//! # Example
//!
//! ```rust,no_run
//! use scirs2_ndimage::gpu_chunked::{GpuChunkedProcessor, GpuChunkingConfig};
//! use scirs2_core::ndarray::Array2;
//!
//! let config = GpuChunkingConfig::default();
//! let processor = GpuChunkedProcessor::new(config).unwrap();
//!
//! let large_image = Array2::<f64>::zeros((10000, 10000));
//!
//! // Process on GPU if available, with automatic fallback
//! let result = processor.gaussian_filter(&large_image.view(), 2.0).unwrap();
//! ```

use std::fmt::Debug;
use std::marker::PhantomData;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

use scirs2_core::ndarray::{self as ndarray, Array2, ArrayView2, Axis};
use scirs2_core::numeric::{Float, FromPrimitive, NumCast, Zero};

use crate::backend::{Backend, DeviceManager};
use crate::chunked_processing::{
    ChunkOperation, ChunkRegion, ChunkRegionIterator, ChunkedImageProcessor, ChunkingConfig,
};
use crate::error::{NdimageError, NdimageResult};
use crate::filters::BorderMode;
use crate::morphology::MorphBorderMode;

// ============================================================================
// Configuration
// ============================================================================

/// Configuration for GPU-accelerated chunked processing
#[derive(Debug, Clone)]
pub struct GpuChunkingConfig {
    /// Maximum chunk size in bytes for GPU processing
    pub max_gpu_chunk_bytes: usize,

    /// Minimum chunk size for GPU processing (smaller uses CPU)
    pub min_gpu_chunk_elements: usize,

    /// Maximum overlap in pixels
    pub max_overlap_pixels: usize,

    /// Enable automatic fallback to CPU
    pub auto_fallback: bool,

    /// Preferred backend (None = auto-detect)
    pub preferred_backend: Option<Backend>,

    /// GPU memory fraction to use (0.0 - 1.0)
    pub gpu_memory_fraction: f64,

    /// Number of streams for async processing
    pub num_streams: usize,

    /// Enable profiling
    pub enable_profiling: bool,
}

impl Default for GpuChunkingConfig {
    fn default() -> Self {
        Self {
            max_gpu_chunk_bytes: 256 * 1024 * 1024, // 256 MB per chunk
            min_gpu_chunk_elements: 256 * 256,      // 64K elements minimum
            max_overlap_pixels: 64,
            auto_fallback: true,
            preferred_backend: None,
            gpu_memory_fraction: 0.7,
            num_streams: 2,
            enable_profiling: false,
        }
    }
}

// ============================================================================
// GPU Capabilities
// ============================================================================

/// GPU capabilities for a specific device
#[derive(Debug, Clone)]
pub struct GpuCapabilities {
    /// Backend type
    pub backend: Backend,

    /// Device name
    pub device_name: String,

    /// Available memory in bytes
    pub memory_bytes: usize,

    /// Number of compute units
    pub compute_units: u32,

    /// Maximum work group size
    pub max_work_group_size: usize,

    /// Whether the device supports double precision
    pub supports_double: bool,
}

impl GpuCapabilities {
    /// Check if capable of processing an array of given size
    pub fn can_process(&self, array_bytes: usize, element_size: usize) -> bool {
        // Need at least 2x array size for input and output
        let required_memory = array_bytes * 2;
        required_memory < self.memory_bytes
    }
}

// ============================================================================
// GPU Chunked Processor
// ============================================================================

/// GPU-accelerated chunked image processor
pub struct GpuChunkedProcessor {
    config: GpuChunkingConfig,
    device_manager: DeviceManager,
    capabilities: Option<GpuCapabilities>,
    cpu_fallback: ChunkedImageProcessor,
    stats: GpuProcessingStats,
}

/// Statistics about GPU processing
#[derive(Debug, Default)]
pub struct GpuProcessingStats {
    /// Chunks processed on GPU
    pub gpu_chunks: AtomicUsize,

    /// Chunks processed on CPU (fallback)
    pub cpu_chunks: AtomicUsize,

    /// Total bytes transferred to GPU
    pub bytes_to_gpu: AtomicUsize,

    /// Total bytes transferred from GPU
    pub bytes_from_gpu: AtomicUsize,

    /// Total GPU compute time in milliseconds
    pub gpu_compute_ms: AtomicUsize,
}

impl GpuChunkedProcessor {
    /// Create a new GPU chunked processor
    pub fn new(config: GpuChunkingConfig) -> NdimageResult<Self> {
        let device_manager = DeviceManager::new()?;
        let capabilities = Self::detect_capabilities(&device_manager, &config)?;

        let cpu_config = ChunkingConfig {
            max_chunk_bytes: config.max_gpu_chunk_bytes,
            max_overlap_pixels: config.max_overlap_pixels,
            enable_parallel: true,
            ..Default::default()
        };

        Ok(Self {
            config,
            device_manager,
            capabilities,
            cpu_fallback: ChunkedImageProcessor::new(cpu_config),
            stats: GpuProcessingStats::default(),
        })
    }

    /// Create with default configuration
    pub fn with_defaults() -> NdimageResult<Self> {
        Self::new(GpuChunkingConfig::default())
    }

    /// Detect GPU capabilities
    fn detect_capabilities(
        device_manager: &DeviceManager,
        config: &GpuChunkingConfig,
    ) -> NdimageResult<Option<GpuCapabilities>> {
        let dev_caps = device_manager.get_capabilities();

        if !dev_caps.gpu_available {
            return Ok(None);
        }

        // Select best backend
        let backend = if let Some(preferred) = config.preferred_backend {
            preferred
        } else if dev_caps.cuda_available {
            #[cfg(feature = "cuda")]
            {
                Backend::Cuda
            }
            #[cfg(not(feature = "cuda"))]
            {
                return Ok(None);
            }
        } else if dev_caps.opencl_available {
            #[cfg(feature = "opencl")]
            {
                Backend::OpenCL
            }
            #[cfg(not(feature = "opencl"))]
            {
                return Ok(None);
            }
        } else if dev_caps.metal_available {
            #[cfg(all(target_os = "macos", feature = "metal"))]
            {
                Backend::Metal
            }
            #[cfg(not(all(target_os = "macos", feature = "metal")))]
            {
                return Ok(None);
            }
        } else {
            return Ok(None);
        };

        Ok(Some(GpuCapabilities {
            backend,
            device_name: "GPU Device".to_string(),
            memory_bytes: dev_caps.gpu_memory_mb * 1024 * 1024,
            compute_units: dev_caps.compute_units,
            max_work_group_size: 256,
            supports_double: true,
        }))
    }

    /// Check if GPU processing is available
    pub fn gpu_available(&self) -> bool {
        self.capabilities.is_some()
    }

    /// Get GPU capabilities if available
    pub fn capabilities(&self) -> Option<&GpuCapabilities> {
        self.capabilities.as_ref()
    }

    /// Should we use GPU for a given chunk size?
    fn should_use_gpu(&self, chunk_elements: usize, element_size: usize) -> bool {
        if !self.gpu_available() {
            return false;
        }

        if chunk_elements < self.config.min_gpu_chunk_elements {
            return false;
        }

        if let Some(caps) = &self.capabilities {
            let chunk_bytes = chunk_elements * element_size;
            caps.can_process(chunk_bytes, element_size)
        } else {
            false
        }
    }

    /// Process an image with GPU acceleration
    pub fn process<T, Op>(&self, input: &ArrayView2<T>, operation: &Op) -> NdimageResult<Array2<T>>
    where
        T: Float + FromPrimitive + Debug + Clone + Send + Sync + Zero + 'static,
        Op: GpuChunkOperation<T>,
    {
        let element_size = std::mem::size_of::<T>();
        let image_shape = (input.nrows(), input.ncols());

        // Calculate chunk size
        let chunk_size = self.calculate_chunk_size(element_size);
        let overlap = operation.required_overlap();

        // Create output array
        let mut output = Array2::zeros(image_shape);

        // Create chunk iterator
        let chunk_iter = ChunkRegionIterator::new(image_shape, chunk_size, overlap);

        // Process chunks
        for region in chunk_iter {
            // Extract chunk
            let rows = region.padded_start.0..region.padded_end.0;
            let cols = region.padded_start.1..region.padded_end.1;
            let chunk = input.slice(ndarray::s![rows, cols]).to_owned();

            // Decide GPU vs CPU
            let result = if self.should_use_gpu(chunk.len(), element_size)
                && GpuChunkOperation::supports_gpu(operation)
            {
                // GPU processing
                self.stats.gpu_chunks.fetch_add(1, Ordering::Relaxed);
                let byte_count = chunk.len() * std::mem::size_of::<T>();
                self.stats
                    .bytes_to_gpu
                    .fetch_add(byte_count, Ordering::Relaxed);

                let gpu_result = GpuChunkOperation::apply_gpu(
                    operation,
                    &chunk.view(),
                    self.capabilities.as_ref(),
                )?;

                self.stats.bytes_from_gpu.fetch_add(
                    gpu_result.len() * std::mem::size_of::<T>(),
                    Ordering::Relaxed,
                );
                gpu_result
            } else {
                // CPU fallback
                self.stats.cpu_chunks.fetch_add(1, Ordering::Relaxed);
                operation.apply(&chunk.view())?
            };

            // Insert result
            self.insert_chunk_result(&mut output, &result.view(), &region)?;
        }

        Ok(output)
    }

    /// Calculate optimal chunk size for GPU
    fn calculate_chunk_size(&self, element_size: usize) -> (usize, usize) {
        let target_elements = self.config.max_gpu_chunk_bytes / element_size;
        let base_size = ((target_elements as f64).sqrt() as usize).max(32);
        (base_size, base_size)
    }

    /// Insert a processed chunk into the output array
    fn insert_chunk_result<T: Float + Clone>(
        &self,
        output: &mut Array2<T>,
        chunk: &ArrayView2<T>,
        region: &ChunkRegion,
    ) -> NdimageResult<()> {
        let overlap = region.overlap();
        let core_start_row = overlap.0 .0;
        let core_start_col = overlap.0 .1;
        let core_end_row = chunk.nrows() - overlap.1 .0;
        let core_end_col = chunk.ncols() - overlap.1 .1;

        let core_slice = chunk.slice(ndarray::s![
            core_start_row..core_end_row,
            core_start_col..core_end_col
        ]);

        output
            .slice_mut(ndarray::s![
                region.start.0..region.end.0,
                region.start.1..region.end.1
            ])
            .assign(&core_slice);

        Ok(())
    }

    /// Get processing statistics
    pub fn stats(&self) -> &GpuProcessingStats {
        &self.stats
    }

    /// Reset statistics
    pub fn reset_stats(&self) {
        self.stats.gpu_chunks.store(0, Ordering::Relaxed);
        self.stats.cpu_chunks.store(0, Ordering::Relaxed);
        self.stats.bytes_to_gpu.store(0, Ordering::Relaxed);
        self.stats.bytes_from_gpu.store(0, Ordering::Relaxed);
        self.stats.gpu_compute_ms.store(0, Ordering::Relaxed);
    }

    // ========================================================================
    // Convenience methods
    // ========================================================================

    /// Apply Gaussian filter with GPU acceleration
    pub fn gaussian_filter<T>(&self, input: &ArrayView2<T>, sigma: f64) -> NdimageResult<Array2<T>>
    where
        T: Float
            + FromPrimitive
            + Debug
            + Clone
            + Send
            + Sync
            + Zero
            + 'static
            + std::ops::AddAssign
            + std::ops::DivAssign,
    {
        let operation = GpuGaussianFilter::new(sigma, BorderMode::Reflect);
        self.process(input, &operation)
    }

    /// Apply uniform filter with GPU acceleration
    pub fn uniform_filter<T>(&self, input: &ArrayView2<T>, size: usize) -> NdimageResult<Array2<T>>
    where
        T: Float
            + FromPrimitive
            + Debug
            + Clone
            + Send
            + Sync
            + Zero
            + 'static
            + std::ops::AddAssign
            + std::ops::DivAssign,
    {
        let operation = GpuUniformFilter::new(size, BorderMode::Reflect);
        self.process(input, &operation)
    }

    /// Apply morphological erosion with GPU acceleration
    pub fn grey_erosion<T>(&self, input: &ArrayView2<T>, size: usize) -> NdimageResult<Array2<T>>
    where
        T: Float + FromPrimitive + Debug + Clone + Send + Sync + Zero + 'static + PartialOrd,
    {
        let operation = GpuGreyErosion::new(size, MorphBorderMode::Constant);
        self.process(input, &operation)
    }

    /// Apply morphological dilation with GPU acceleration
    pub fn grey_dilation<T>(&self, input: &ArrayView2<T>, size: usize) -> NdimageResult<Array2<T>>
    where
        T: Float + FromPrimitive + Debug + Clone + Send + Sync + Zero + 'static + PartialOrd,
    {
        let operation = GpuGreyDilation::new(size, MorphBorderMode::Constant);
        self.process(input, &operation)
    }
}

// ============================================================================
// GPU Chunk Operation Trait
// ============================================================================

/// Trait for operations that can be GPU-accelerated
pub trait GpuChunkOperation<T>: ChunkOperation<T>
where
    T: Float + FromPrimitive + Debug + Clone + Send + Sync,
{
    /// Whether this operation supports GPU acceleration
    fn supports_gpu(&self) -> bool {
        true
    }

    /// Apply the operation on GPU
    fn apply_gpu(
        &self,
        chunk: &ArrayView2<T>,
        capabilities: Option<&GpuCapabilities>,
    ) -> NdimageResult<Array2<T>> {
        // Default: fall back to CPU implementation
        self.apply(chunk)
    }

    /// Estimate GPU memory requirements
    fn gpu_memory_estimate(&self, input_elements: usize, element_size: usize) -> usize {
        // Default: input + output + working memory
        input_elements * element_size * 3
    }
}

// ============================================================================
// GPU-Accelerated Operations
// ============================================================================

/// GPU-accelerated Gaussian filter
pub struct GpuGaussianFilter {
    sigma: f64,
    border_mode: BorderMode,
    kernel_radius: usize,
}

impl GpuGaussianFilter {
    pub fn new(sigma: f64, border_mode: BorderMode) -> Self {
        let kernel_radius = (sigma * 4.0).ceil() as usize;
        Self {
            sigma,
            border_mode,
            kernel_radius,
        }
    }
}

impl<T> ChunkOperation<T> for GpuGaussianFilter
where
    T: Float
        + FromPrimitive
        + Debug
        + Clone
        + Send
        + Sync
        + Zero
        + 'static
        + std::ops::AddAssign
        + std::ops::DivAssign,
{
    fn apply(&self, chunk: &ArrayView2<T>) -> NdimageResult<Array2<T>> {
        let chunk_f64 = chunk.mapv(|x| x.to_f64().unwrap_or(0.0));
        let result =
            crate::filters::gaussian_filter(&chunk_f64, self.sigma, Some(self.border_mode), None)?;
        Ok(result.mapv(|x| T::from_f64(x).unwrap_or_else(T::zero)))
    }

    fn required_overlap(&self) -> usize {
        self.kernel_radius
    }

    fn name(&self) -> &str {
        "gpu_gaussian_filter"
    }
}

impl<T> GpuChunkOperation<T> for GpuGaussianFilter
where
    T: Float
        + FromPrimitive
        + Debug
        + Clone
        + Send
        + Sync
        + Zero
        + 'static
        + std::ops::AddAssign
        + std::ops::DivAssign,
{
    fn supports_gpu(&self) -> bool {
        true
    }

    fn apply_gpu(
        &self,
        chunk: &ArrayView2<T>,
        capabilities: Option<&GpuCapabilities>,
    ) -> NdimageResult<Array2<T>> {
        // In a full implementation, this would use the GPU backend
        // For now, we use the CPU implementation with potential future GPU extension
        #[cfg(feature = "gpu")]
        if let Some(caps) = capabilities {
            // TODO: Implement actual GPU kernel execution
            // For now, fall back to CPU
            return self.apply(chunk);
        }

        self.apply(chunk)
    }

    fn gpu_memory_estimate(&self, input_elements: usize, element_size: usize) -> usize {
        // Gaussian filter needs: input + output + kernel
        let kernel_size = (self.kernel_radius * 2 + 1).pow(2);
        (input_elements * 2 + kernel_size) * element_size
    }
}

/// GPU-accelerated uniform filter
pub struct GpuUniformFilter {
    size: usize,
    border_mode: BorderMode,
}

impl GpuUniformFilter {
    pub fn new(size: usize, border_mode: BorderMode) -> Self {
        Self { size, border_mode }
    }
}

impl<T> ChunkOperation<T> for GpuUniformFilter
where
    T: Float
        + FromPrimitive
        + Debug
        + Clone
        + Send
        + Sync
        + Zero
        + 'static
        + std::ops::AddAssign
        + std::ops::DivAssign,
{
    fn apply(&self, chunk: &ArrayView2<T>) -> NdimageResult<Array2<T>> {
        let chunk_f64 = chunk.mapv(|x| x.to_f64().unwrap_or(0.0));
        let result = crate::filters::uniform_filter(
            &chunk_f64,
            &[self.size, self.size],
            Some(self.border_mode),
            None,
        )?;
        Ok(result.mapv(|x| T::from_f64(x).unwrap_or_else(T::zero)))
    }

    fn required_overlap(&self) -> usize {
        self.size / 2 + 1
    }

    fn name(&self) -> &str {
        "gpu_uniform_filter"
    }
}

impl<T> GpuChunkOperation<T> for GpuUniformFilter
where
    T: Float
        + FromPrimitive
        + Debug
        + Clone
        + Send
        + Sync
        + Zero
        + 'static
        + std::ops::AddAssign
        + std::ops::DivAssign,
{
    fn supports_gpu(&self) -> bool {
        true
    }
}

/// GPU-accelerated grey erosion
pub struct GpuGreyErosion {
    size: usize,
    border_mode: MorphBorderMode,
}

impl GpuGreyErosion {
    pub fn new(size: usize, border_mode: MorphBorderMode) -> Self {
        Self { size, border_mode }
    }
}

impl<T> ChunkOperation<T> for GpuGreyErosion
where
    T: Float + FromPrimitive + Debug + Clone + Send + Sync + Zero + 'static + PartialOrd,
{
    fn apply(&self, chunk: &ArrayView2<T>) -> NdimageResult<Array2<T>> {
        let chunk_f64 = chunk.mapv(|x| x.to_f64().unwrap_or(0.0));
        let chunk_owned = chunk_f64.to_owned();

        let result = crate::morphology::grey_erosion(
            &chunk_owned,
            Some(&[self.size, self.size]),
            None,
            Some(self.border_mode),
            None,
            None,
        )?;

        Ok(result.mapv(|x| T::from_f64(x).unwrap_or_else(T::zero)))
    }

    fn required_overlap(&self) -> usize {
        self.size / 2 + 1
    }

    fn name(&self) -> &str {
        "gpu_grey_erosion"
    }
}

impl<T> GpuChunkOperation<T> for GpuGreyErosion
where
    T: Float + FromPrimitive + Debug + Clone + Send + Sync + Zero + 'static + PartialOrd,
{
    fn supports_gpu(&self) -> bool {
        true
    }
}

/// GPU-accelerated grey dilation
pub struct GpuGreyDilation {
    size: usize,
    border_mode: MorphBorderMode,
}

impl GpuGreyDilation {
    pub fn new(size: usize, border_mode: MorphBorderMode) -> Self {
        Self { size, border_mode }
    }
}

impl<T> ChunkOperation<T> for GpuGreyDilation
where
    T: Float + FromPrimitive + Debug + Clone + Send + Sync + Zero + 'static + PartialOrd,
{
    fn apply(&self, chunk: &ArrayView2<T>) -> NdimageResult<Array2<T>> {
        let chunk_f64 = chunk.mapv(|x| x.to_f64().unwrap_or(0.0));
        let chunk_owned = chunk_f64.to_owned();

        let result = crate::morphology::grey_dilation(
            &chunk_owned,
            Some(&[self.size, self.size]),
            None,
            Some(self.border_mode),
            None,
            None,
        )?;

        Ok(result.mapv(|x| T::from_f64(x).unwrap_or_else(T::zero)))
    }

    fn required_overlap(&self) -> usize {
        self.size / 2 + 1
    }

    fn name(&self) -> &str {
        "gpu_grey_dilation"
    }
}

impl<T> GpuChunkOperation<T> for GpuGreyDilation
where
    T: Float + FromPrimitive + Debug + Clone + Send + Sync + Zero + 'static + PartialOrd,
{
    fn supports_gpu(&self) -> bool {
        true
    }
}

// ============================================================================
// GPU Memory Pool
// ============================================================================

/// Simple GPU memory pool for efficient allocation
#[cfg(feature = "gpu")]
pub struct GpuMemoryPool {
    allocations: Vec<GpuAllocation>,
    total_allocated: usize,
    max_memory: usize,
}

#[cfg(feature = "gpu")]
struct GpuAllocation {
    ptr: usize,
    size: usize,
    in_use: bool,
}

#[cfg(feature = "gpu")]
impl GpuMemoryPool {
    /// Create a new memory pool with given max size
    pub fn new(max_memory: usize) -> Self {
        Self {
            allocations: Vec::new(),
            total_allocated: 0,
            max_memory,
        }
    }

    /// Allocate memory from the pool
    pub fn allocate(&mut self, size: usize) -> NdimageResult<usize> {
        // Look for an existing free allocation of sufficient size
        for alloc in &mut self.allocations {
            if !alloc.in_use && alloc.size >= size {
                alloc.in_use = true;
                return Ok(alloc.ptr);
            }
        }

        // Need new allocation
        if self.total_allocated + size > self.max_memory {
            return Err(NdimageError::MemoryError(
                "GPU memory pool exhausted".into(),
            ));
        }

        // In a real implementation, this would call the GPU allocation API
        let ptr = self.total_allocated;
        self.allocations.push(GpuAllocation {
            ptr,
            size,
            in_use: true,
        });
        self.total_allocated += size;

        Ok(ptr)
    }

    /// Free memory back to the pool
    pub fn free(&mut self, ptr: usize) {
        for alloc in &mut self.allocations {
            if alloc.ptr == ptr {
                alloc.in_use = false;
                return;
            }
        }
    }

    /// Get available memory
    pub fn available(&self) -> usize {
        self.max_memory - self.total_allocated
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_gpu_config_default() {
        let config = GpuChunkingConfig::default();
        assert!(config.max_gpu_chunk_bytes > 0);
        assert!(config.auto_fallback);
    }

    #[test]
    fn test_gpu_processor_creation() {
        let result = GpuChunkedProcessor::with_defaults();
        // May or may not have GPU available
        assert!(result.is_ok());
    }

    #[test]
    fn test_gpu_gaussian_filter() {
        if let Ok(processor) = GpuChunkedProcessor::with_defaults() {
            let input = Array2::<f64>::ones((50, 50));
            let result = processor.gaussian_filter(&input.view(), 1.0);

            assert!(result.is_ok());
            let output = result.expect("Should succeed");
            assert_eq!(output.shape(), input.shape());
        }
    }

    #[test]
    fn test_gpu_uniform_filter() {
        if let Ok(processor) = GpuChunkedProcessor::with_defaults() {
            let input = Array2::<f64>::ones((50, 50));
            let result = processor.uniform_filter(&input.view(), 3);

            assert!(result.is_ok());
            let output = result.expect("Should succeed");
            assert_eq!(output.shape(), input.shape());
        }
    }

    #[test]
    fn test_gpu_morphology() {
        if let Ok(processor) = GpuChunkedProcessor::with_defaults() {
            let input = Array2::<f64>::ones((50, 50));

            let eroded = processor.grey_erosion(&input.view(), 3);
            assert!(eroded.is_ok());

            let dilated = processor.grey_dilation(&input.view(), 3);
            assert!(dilated.is_ok());
        }
    }

    #[test]
    fn test_gpu_stats() {
        if let Ok(processor) = GpuChunkedProcessor::with_defaults() {
            processor.reset_stats();

            let input = Array2::<f64>::ones((100, 100));
            let _ = processor.gaussian_filter(&input.view(), 1.0);

            let stats = processor.stats();
            let total =
                stats.gpu_chunks.load(Ordering::Relaxed) + stats.cpu_chunks.load(Ordering::Relaxed);
            assert!(total > 0);
        }
    }

    #[test]
    fn test_gpu_capabilities() {
        if let Ok(processor) = GpuChunkedProcessor::with_defaults() {
            if let Some(caps) = processor.capabilities() {
                assert!(caps.memory_bytes > 0);
                assert!(caps.compute_units > 0);
            }
        }
    }

    #[test]
    fn test_gpu_operation_trait() {
        let op: GpuGaussianFilter = GpuGaussianFilter::new(1.0, BorderMode::Reflect);
        assert!(GpuChunkOperation::<f64>::supports_gpu(&op));
        assert!(ChunkOperation::<f64>::required_overlap(&op) > 0);
        assert_eq!(ChunkOperation::<f64>::name(&op), "gpu_gaussian_filter");
    }

    #[cfg(feature = "gpu")]
    #[test]
    fn test_gpu_memory_pool() {
        let mut pool = GpuMemoryPool::new(1024 * 1024);

        let alloc1 = pool.allocate(1024);
        assert!(alloc1.is_ok());

        let alloc2 = pool.allocate(2048);
        assert!(alloc2.is_ok());

        pool.free(alloc1.expect("Should have ptr"));
        assert!(pool.available() < 1024 * 1024);
    }
}