Skip to main content

oxigdal_algorithms/raster/
focal.rs

1//! Focal (neighborhood) statistics operations
2//!
3//! This module provides focal/neighborhood operations that compute statistics
4//! over moving windows. These are essential for many spatial analysis tasks.
5//!
6//! # Supported Operations
7//!
8//! - **Focal Mean**: Average value in neighborhood
9//! - **Focal Median**: Median value in neighborhood
10//! - **Focal Range**: Max - Min in neighborhood
11//! - **Focal Variety**: Count of unique values
12//! - **Focal Min/Max**: Minimum/Maximum in neighborhood
13//! - **Focal Sum**: Sum of values in neighborhood
14//! - **Focal Standard Deviation**: Standard deviation in neighborhood
15//!
16//! # Window Shapes
17//!
18//! - **Rectangular**: Standard rectangular window
19//! - **Circular**: Circular window (pixels within radius)
20//! - **Custom**: User-defined kernel mask
21//!
22//! # Example
23//!
24//! ```ignore
25//! use oxigdal_algorithms::raster::focal::{focal_mean, WindowShape, BoundaryMode};
26//! use oxigdal_core::buffer::RasterBuffer;
27//! use oxigdal_core::types::RasterDataType;
28//! # use oxigdal_algorithms::error::Result;
29//!
30//! # fn main() -> Result<()> {
31//! let src = RasterBuffer::zeros(100, 100, RasterDataType::Float32);
32//! let window = WindowShape::rectangular(3, 3)?;
33//! let boundary = BoundaryMode::Reflect;
34//!
35//! let result = focal_mean(&src, &window, &boundary)?;
36//! # Ok(())
37//! # }
38//! ```
39
40use crate::error::{AlgorithmError, Result};
41use oxigdal_core::buffer::RasterBuffer;
42use oxigdal_core::types::RasterDataType;
43
44#[cfg(feature = "parallel")]
45use rayon::prelude::*;
46
47/// Window shape for focal operations
48#[derive(Debug, Clone, PartialEq)]
49pub enum WindowShape {
50    /// Rectangular window with given width and height (must be odd)
51    Rectangular { width: usize, height: usize },
52
53    /// Circular window with given radius
54    Circular { radius: f64 },
55
56    /// Custom window defined by a binary mask (1 = include, 0 = exclude)
57    Custom {
58        mask: Vec<bool>,
59        width: usize,
60        height: usize,
61    },
62}
63
64impl WindowShape {
65    /// Creates a rectangular window
66    ///
67    /// # Arguments
68    ///
69    /// * `width` - Window width (must be odd)
70    /// * `height` - Window height (must be odd)
71    ///
72    /// # Errors
73    ///
74    /// Returns an error if width or height is even or zero
75    pub fn rectangular(width: usize, height: usize) -> Result<Self> {
76        use oxigdal_core::OxiGdalError;
77
78        if width == 0 || height == 0 {
79            return Err(OxiGdalError::invalid_parameter_builder(
80                "window_size",
81                format!(
82                    "window dimensions must be greater than zero, got {}x{}",
83                    width, height
84                ),
85            )
86            .with_parameter("width", width.to_string())
87            .with_parameter("height", height.to_string())
88            .with_parameter("min", "1")
89            .with_operation("focal_operation")
90            .with_suggestion("Use positive window dimensions. Common values: 3, 5, 7, 9, 11")
91            .build()
92            .into());
93        }
94        if width.is_multiple_of(2) || height.is_multiple_of(2) {
95            let suggested_width = if width.is_multiple_of(2) {
96                width + 1
97            } else {
98                width
99            };
100            let suggested_height = if height.is_multiple_of(2) {
101                height + 1
102            } else {
103                height
104            };
105            return Err(OxiGdalError::invalid_parameter_builder(
106                "window_size",
107                format!("window dimensions must be odd, got {}x{}", width, height),
108            )
109            .with_parameter("width", width.to_string())
110            .with_parameter("height", height.to_string())
111            .with_operation("focal_operation")
112            .with_suggestion(format!(
113                "Use odd window dimensions for symmetric neighborhood. Try {}x{} instead",
114                suggested_width, suggested_height
115            ))
116            .build()
117            .into());
118        }
119        Ok(Self::Rectangular { width, height })
120    }
121
122    /// Creates a circular window
123    ///
124    /// # Arguments
125    ///
126    /// * `radius` - Window radius (must be positive)
127    ///
128    /// # Errors
129    ///
130    /// Returns an error if radius is not positive
131    pub fn circular(radius: f64) -> Result<Self> {
132        use oxigdal_core::OxiGdalError;
133
134        if radius <= 0.0 {
135            return Err(OxiGdalError::invalid_parameter_builder(
136                "radius",
137                format!("window radius must be positive, got {}", radius),
138            )
139            .with_parameter("value", radius.to_string())
140            .with_parameter("min", "0.0")
141            .with_operation("focal_operation")
142            .with_suggestion(
143                "Use positive radius value. Common values: 1.0, 1.5, 2.0, 3.0 (in pixels)",
144            )
145            .build()
146            .into());
147        }
148        Ok(Self::Circular { radius })
149    }
150
151    /// Creates a custom window from a binary mask
152    ///
153    /// # Arguments
154    ///
155    /// * `mask` - Binary mask (true = include pixel)
156    /// * `width` - Mask width
157    /// * `height` - Mask height
158    ///
159    /// # Errors
160    ///
161    /// Returns an error if dimensions don't match mask size or are even
162    pub fn custom(mask: Vec<bool>, width: usize, height: usize) -> Result<Self> {
163        use oxigdal_core::OxiGdalError;
164
165        if mask.len() != width * height {
166            let expected = width * height;
167            return Err(OxiGdalError::invalid_parameter_builder(
168                "mask",
169                format!(
170                    "mask size must match width * height, got {} but expected {}",
171                    mask.len(),
172                    expected
173                ),
174            )
175            .with_parameter("mask_length", mask.len().to_string())
176            .with_parameter("width", width.to_string())
177            .with_parameter("height", height.to_string())
178            .with_parameter("expected_length", expected.to_string())
179            .with_operation("focal_operation")
180            .with_suggestion(format!(
181                "Provide a mask with exactly {} elements ({}x{})",
182                expected, width, height
183            ))
184            .build()
185            .into());
186        }
187        if width.is_multiple_of(2) || height.is_multiple_of(2) {
188            let suggested_width = if width.is_multiple_of(2) {
189                width + 1
190            } else {
191                width
192            };
193            let suggested_height = if height.is_multiple_of(2) {
194                height + 1
195            } else {
196                height
197            };
198            return Err(OxiGdalError::invalid_parameter_builder(
199                "window_size",
200                format!("window dimensions must be odd, got {}x{}", width, height),
201            )
202            .with_parameter("width", width.to_string())
203            .with_parameter("height", height.to_string())
204            .with_operation("focal_operation")
205            .with_suggestion(format!(
206                "Use odd window dimensions for symmetric neighborhood. Try {}x{} instead",
207                suggested_width, suggested_height
208            ))
209            .build()
210            .into());
211        }
212        Ok(Self::Custom {
213            mask,
214            width,
215            height,
216        })
217    }
218
219    /// Gets the window dimensions
220    #[must_use]
221    pub fn dimensions(&self) -> (usize, usize) {
222        match self {
223            Self::Rectangular { width, height } => (*width, *height),
224            Self::Circular { radius } => {
225                let size = (radius.ceil() * 2.0 + 1.0) as usize;
226                (size, size)
227            }
228            Self::Custom { width, height, .. } => (*width, *height),
229        }
230    }
231
232    /// Checks if a pixel at given offset is included in the window
233    #[must_use]
234    pub fn includes(&self, dx: i64, dy: i64) -> bool {
235        match self {
236            Self::Rectangular { width, height } => {
237                let hw = (*width / 2) as i64;
238                let hh = (*height / 2) as i64;
239                dx.abs() <= hw && dy.abs() <= hh
240            }
241            Self::Circular { radius } => {
242                let dist = ((dx * dx + dy * dy) as f64).sqrt();
243                dist <= *radius
244            }
245            Self::Custom {
246                mask,
247                width,
248                height,
249            } => {
250                let hw = (*width / 2) as i64;
251                let hh = (*height / 2) as i64;
252                if dx.abs() > hw || dy.abs() > hh {
253                    return false;
254                }
255                let x = (dx + hw) as usize;
256                let y = (dy + hh) as usize;
257                mask[y * width + x]
258            }
259        }
260    }
261
262    /// Returns all offsets included in the window
263    #[must_use]
264    pub fn offsets(&self) -> Vec<(i64, i64)> {
265        let (width, height) = self.dimensions();
266        let hw = (width / 2) as i64;
267        let hh = (height / 2) as i64;
268
269        let mut result = Vec::new();
270        for dy in -hh..=hh {
271            for dx in -hw..=hw {
272                if self.includes(dx, dy) {
273                    result.push((dx, dy));
274                }
275            }
276        }
277        result
278    }
279
280    /// Returns the number of cells in the window
281    #[must_use]
282    pub fn cell_count(&self) -> usize {
283        self.offsets().len()
284    }
285}
286
287/// Boundary handling mode for focal operations
288#[derive(Debug, Clone, Copy, PartialEq, Eq)]
289pub enum BoundaryMode {
290    /// Ignore pixels outside boundary (smaller neighborhood at edges)
291    Ignore,
292
293    /// Use a constant value for pixels outside boundary
294    Constant(i64),
295
296    /// Reflect values at the boundary
297    Reflect,
298
299    /// Wrap around to opposite edge
300    Wrap,
301
302    /// Extend edge values
303    Edge,
304}
305
306/// Focal operation type
307#[derive(Debug, Clone, Copy, PartialEq, Eq)]
308pub enum FocalOperation {
309    /// Mean (average) value
310    Mean,
311
312    /// Median value
313    Median,
314
315    /// Range (max - min)
316    Range,
317
318    /// Variety (count of unique values)
319    Variety,
320
321    /// Minimum value
322    Min,
323
324    /// Maximum value
325    Max,
326
327    /// Sum of values
328    Sum,
329
330    /// Standard deviation
331    StdDev,
332
333    /// Majority (most common value)
334    Majority,
335}
336
337/// Computes focal mean over a raster
338///
339/// # Arguments
340///
341/// * `src` - Source raster buffer
342/// * `window` - Window shape
343/// * `boundary` - Boundary handling mode
344///
345/// # Errors
346///
347/// Returns an error if the operation fails
348pub fn focal_mean(
349    src: &RasterBuffer,
350    window: &WindowShape,
351    boundary: &BoundaryMode,
352) -> Result<RasterBuffer> {
353    focal_operation(src, window, boundary, FocalOperation::Mean)
354}
355
356/// Computes focal median over a raster
357///
358/// # Arguments
359///
360/// * `src` - Source raster buffer
361/// * `window` - Window shape
362/// * `boundary` - Boundary handling mode
363///
364/// # Errors
365///
366/// Returns an error if the operation fails
367pub fn focal_median(
368    src: &RasterBuffer,
369    window: &WindowShape,
370    boundary: &BoundaryMode,
371) -> Result<RasterBuffer> {
372    focal_operation(src, window, boundary, FocalOperation::Median)
373}
374
375/// Computes focal range (max - min) over a raster
376///
377/// # Arguments
378///
379/// * `src` - Source raster buffer
380/// * `window` - Window shape
381/// * `boundary` - Boundary handling mode
382///
383/// # Errors
384///
385/// Returns an error if the operation fails
386pub fn focal_range(
387    src: &RasterBuffer,
388    window: &WindowShape,
389    boundary: &BoundaryMode,
390) -> Result<RasterBuffer> {
391    focal_operation(src, window, boundary, FocalOperation::Range)
392}
393
394/// Computes focal variety (unique value count) over a raster
395///
396/// # Arguments
397///
398/// * `src` - Source raster buffer
399/// * `window` - Window shape
400/// * `boundary` - Boundary handling mode
401///
402/// # Errors
403///
404/// Returns an error if the operation fails
405pub fn focal_variety(
406    src: &RasterBuffer,
407    window: &WindowShape,
408    boundary: &BoundaryMode,
409) -> Result<RasterBuffer> {
410    focal_operation(src, window, boundary, FocalOperation::Variety)
411}
412
413/// Computes focal minimum over a raster
414///
415/// # Arguments
416///
417/// * `src` - Source raster buffer
418/// * `window` - Window shape
419/// * `boundary` - Boundary handling mode
420///
421/// # Errors
422///
423/// Returns an error if the operation fails
424pub fn focal_min(
425    src: &RasterBuffer,
426    window: &WindowShape,
427    boundary: &BoundaryMode,
428) -> Result<RasterBuffer> {
429    focal_operation(src, window, boundary, FocalOperation::Min)
430}
431
432/// Computes focal maximum over a raster
433///
434/// # Arguments
435///
436/// * `src` - Source raster buffer
437/// * `window` - Window shape
438/// * `boundary` - Boundary handling mode
439///
440/// # Errors
441///
442/// Returns an error if the operation fails
443pub fn focal_max(
444    src: &RasterBuffer,
445    window: &WindowShape,
446    boundary: &BoundaryMode,
447) -> Result<RasterBuffer> {
448    focal_operation(src, window, boundary, FocalOperation::Max)
449}
450
451/// Computes focal sum over a raster
452///
453/// # Arguments
454///
455/// * `src` - Source raster buffer
456/// * `window` - Window shape
457/// * `boundary` - Boundary handling mode
458///
459/// # Errors
460///
461/// Returns an error if the operation fails
462pub fn focal_sum(
463    src: &RasterBuffer,
464    window: &WindowShape,
465    boundary: &BoundaryMode,
466) -> Result<RasterBuffer> {
467    focal_operation(src, window, boundary, FocalOperation::Sum)
468}
469
470/// Computes focal standard deviation over a raster
471///
472/// # Arguments
473///
474/// * `src` - Source raster buffer
475/// * `window` - Window shape
476/// * `boundary` - Boundary handling mode
477///
478/// # Errors
479///
480/// Returns an error if the operation fails
481pub fn focal_stddev(
482    src: &RasterBuffer,
483    window: &WindowShape,
484    boundary: &BoundaryMode,
485) -> Result<RasterBuffer> {
486    focal_operation(src, window, boundary, FocalOperation::StdDev)
487}
488
489/// Computes focal majority (most common value) over a raster
490///
491/// # Arguments
492///
493/// * `src` - Source raster buffer
494/// * `window` - Window shape
495/// * `boundary` - Boundary handling mode
496///
497/// # Errors
498///
499/// Returns an error if the operation fails
500pub fn focal_majority(
501    src: &RasterBuffer,
502    window: &WindowShape,
503    boundary: &BoundaryMode,
504) -> Result<RasterBuffer> {
505    focal_operation(src, window, boundary, FocalOperation::Majority)
506}
507
508/// Generic focal operation
509fn focal_operation(
510    src: &RasterBuffer,
511    window: &WindowShape,
512    boundary: &BoundaryMode,
513    operation: FocalOperation,
514) -> Result<RasterBuffer> {
515    let width = src.width();
516    let height = src.height();
517    let mut dst = RasterBuffer::zeros(width, height, src.data_type());
518
519    let offsets = window.offsets();
520
521    #[cfg(feature = "parallel")]
522    {
523        let results: Result<Vec<_>> = (0..height)
524            .into_par_iter()
525            .map(|y| {
526                let mut row_data = Vec::with_capacity(width as usize);
527                for x in 0..width {
528                    let value = compute_focal_value(src, x, y, &offsets, boundary, operation)?;
529                    row_data.push(value);
530                }
531                Ok((y, row_data))
532            })
533            .collect();
534
535        for (y, row_data) in results? {
536            for (x, value) in row_data.into_iter().enumerate() {
537                dst.set_pixel(x as u64, y, value)
538                    .map_err(AlgorithmError::Core)?;
539            }
540        }
541    }
542
543    #[cfg(not(feature = "parallel"))]
544    {
545        for y in 0..height {
546            for x in 0..width {
547                let value = compute_focal_value(src, x, y, &offsets, boundary, operation)?;
548                dst.set_pixel(x, y, value).map_err(AlgorithmError::Core)?;
549            }
550        }
551    }
552
553    Ok(dst)
554}
555
556/// Computes the focal value for a single pixel
557fn compute_focal_value(
558    src: &RasterBuffer,
559    x: u64,
560    y: u64,
561    offsets: &[(i64, i64)],
562    boundary: &BoundaryMode,
563    operation: FocalOperation,
564) -> Result<f64> {
565    let width = src.width() as i64;
566    let height = src.height() as i64;
567    let x_i64 = x as i64;
568    let y_i64 = y as i64;
569
570    let mut values = Vec::with_capacity(offsets.len());
571
572    for &(dx, dy) in offsets {
573        let nx = x_i64 + dx;
574        let ny = y_i64 + dy;
575
576        let value = if nx >= 0 && nx < width && ny >= 0 && ny < height {
577            src.get_pixel(nx as u64, ny as u64)
578                .map_err(AlgorithmError::Core)?
579        } else {
580            match boundary {
581                BoundaryMode::Ignore => continue,
582                BoundaryMode::Constant(c) => *c as f64,
583                BoundaryMode::Reflect => {
584                    let rx = if nx < 0 {
585                        -nx - 1
586                    } else if nx >= width {
587                        2 * width - nx - 1
588                    } else {
589                        nx
590                    };
591                    let ry = if ny < 0 {
592                        -ny - 1
593                    } else if ny >= height {
594                        2 * height - ny - 1
595                    } else {
596                        ny
597                    };
598                    src.get_pixel(rx as u64, ry as u64)
599                        .map_err(AlgorithmError::Core)?
600                }
601                BoundaryMode::Wrap => {
602                    let wx = ((nx % width) + width) % width;
603                    let wy = ((ny % height) + height) % height;
604                    src.get_pixel(wx as u64, wy as u64)
605                        .map_err(AlgorithmError::Core)?
606                }
607                BoundaryMode::Edge => {
608                    let ex = nx.clamp(0, width - 1);
609                    let ey = ny.clamp(0, height - 1);
610                    src.get_pixel(ex as u64, ey as u64)
611                        .map_err(AlgorithmError::Core)?
612                }
613            }
614        };
615
616        values.push(value);
617    }
618
619    if values.is_empty() {
620        return Ok(0.0);
621    }
622
623    let result = match operation {
624        FocalOperation::Mean => {
625            let sum: f64 = values.iter().sum();
626            sum / values.len() as f64
627        }
628        FocalOperation::Median => {
629            values.sort_by(|a, b| a.partial_cmp(b).unwrap_or(core::cmp::Ordering::Equal));
630            let mid = values.len() / 2;
631            if values.len() % 2 == 0 {
632                (values[mid - 1] + values[mid]) / 2.0
633            } else {
634                values[mid]
635            }
636        }
637        FocalOperation::Range => {
638            // Compute min and max in a single pass using fold (panic-free)
639            // This is safe because values is guaranteed non-empty by check at line 590
640            let (min, max) = values.iter().copied().fold(
641                (f64::INFINITY, f64::NEG_INFINITY),
642                |(min_val, max_val), val| {
643                    let new_min = if val < min_val { val } else { min_val };
644                    let new_max = if val > max_val { val } else { max_val };
645                    (new_min, new_max)
646                },
647            );
648            max - min
649        }
650        FocalOperation::Variety => {
651            let mut unique = values.clone();
652            unique.sort_by(|a, b| a.partial_cmp(b).unwrap_or(core::cmp::Ordering::Equal));
653            unique.dedup_by(|a, b| (*a - *b).abs() < 1e-10);
654            unique.len() as f64
655        }
656        FocalOperation::Min => {
657            // Use fold to find minimum (panic-free)
658            // This is safe because values is guaranteed non-empty by check at line 590
659            values
660                .iter()
661                .copied()
662                .fold(f64::INFINITY, |acc, val| if val < acc { val } else { acc })
663        }
664        FocalOperation::Max => {
665            // Use fold to find maximum (panic-free)
666            // This is safe because values is guaranteed non-empty by check at line 590
667            values.iter().copied().fold(
668                f64::NEG_INFINITY,
669                |acc, val| if val > acc { val } else { acc },
670            )
671        }
672        FocalOperation::Sum => values.iter().sum(),
673        FocalOperation::StdDev => {
674            let mean = values.iter().sum::<f64>() / values.len() as f64;
675            let variance = values
676                .iter()
677                .map(|v| {
678                    let diff = v - mean;
679                    diff * diff
680                })
681                .sum::<f64>()
682                / values.len() as f64;
683            variance.sqrt()
684        }
685        FocalOperation::Majority => {
686            // Count occurrences (with tolerance for floating point)
687            let mut counts: Vec<(f64, usize)> = Vec::new();
688            for &val in &values {
689                if let Some(entry) = counts.iter_mut().find(|(v, _)| (v - val).abs() < 1e-10) {
690                    entry.1 += 1;
691                } else {
692                    counts.push((val, 1));
693                }
694            }
695            // Use fold to find value with maximum count (panic-free)
696            // This is safe because counts is guaranteed non-empty since values is non-empty (checked at line 590)
697            let (majority_val, _) =
698                counts
699                    .into_iter()
700                    .fold((0.0, 0), |(acc_val, acc_count), (val, count)| {
701                        if count > acc_count {
702                            (val, count)
703                        } else {
704                            (acc_val, acc_count)
705                        }
706                    });
707            majority_val
708        }
709    };
710
711    Ok(result)
712}
713
714/// Optimized focal mean for rectangular windows using separable filtering
715///
716/// This is much faster than the generic implementation for large rectangular windows.
717///
718/// # Arguments
719///
720/// * `src` - Source raster buffer
721/// * `width` - Window width (must be odd)
722/// * `height` - Window height (must be odd)
723///
724/// # Errors
725///
726/// Returns an error if the operation fails
727pub fn focal_mean_separable(
728    src: &RasterBuffer,
729    width: usize,
730    height: usize,
731) -> Result<RasterBuffer> {
732    if width.is_multiple_of(2) || height.is_multiple_of(2) {
733        return Err(AlgorithmError::InvalidParameter {
734            parameter: "window_size",
735            message: "Window dimensions must be odd".to_string(),
736        });
737    }
738
739    let img_width = src.width();
740    let img_height = src.height();
741
742    // Horizontal pass
743    let mut temp = RasterBuffer::zeros(img_width, img_height, RasterDataType::Float64);
744    let hw = (width / 2) as i64;
745
746    for y in 0..img_height {
747        for x in 0..img_width {
748            let mut sum = 0.0;
749            let mut count = 0;
750
751            for dx in -hw..=hw {
752                let nx = (x as i64 + dx).clamp(0, img_width as i64 - 1);
753                sum += src.get_pixel(nx as u64, y).map_err(AlgorithmError::Core)?;
754                count += 1;
755            }
756
757            temp.set_pixel(x, y, sum / count as f64)
758                .map_err(AlgorithmError::Core)?;
759        }
760    }
761
762    // Vertical pass
763    let mut dst = RasterBuffer::zeros(img_width, img_height, src.data_type());
764    let hh = (height / 2) as i64;
765
766    for y in 0..img_height {
767        for x in 0..img_width {
768            let mut sum = 0.0;
769            let mut count = 0;
770
771            for dy in -hh..=hh {
772                let ny = (y as i64 + dy).clamp(0, img_height as i64 - 1);
773                sum += temp.get_pixel(x, ny as u64).map_err(AlgorithmError::Core)?;
774                count += 1;
775            }
776
777            dst.set_pixel(x, y, sum / count as f64)
778                .map_err(AlgorithmError::Core)?;
779        }
780    }
781
782    Ok(dst)
783}
784
785/// Applies a custom kernel convolution
786///
787/// # Arguments
788///
789/// * `src` - Source raster buffer
790/// * `kernel` - Convolution kernel weights
791/// * `width` - Kernel width
792/// * `height` - Kernel height
793/// * `normalize` - Whether to normalize by kernel sum
794///
795/// # Errors
796///
797/// Returns an error if the operation fails
798pub fn focal_convolve(
799    src: &RasterBuffer,
800    kernel: &[f64],
801    width: usize,
802    height: usize,
803    normalize: bool,
804) -> Result<RasterBuffer> {
805    if kernel.len() != width * height {
806        return Err(AlgorithmError::InvalidParameter {
807            parameter: "kernel",
808            message: "Kernel size must match width * height".to_string(),
809        });
810    }
811
812    let img_width = src.width();
813    let img_height = src.height();
814    let mut dst = RasterBuffer::zeros(img_width, img_height, src.data_type());
815
816    let hw = (width / 2) as i64;
817    let hh = (height / 2) as i64;
818
819    let kernel_sum: f64 = if normalize {
820        let sum: f64 = kernel.iter().sum();
821        if sum.abs() < 1e-10 { 1.0 } else { sum }
822    } else {
823        1.0
824    };
825
826    for y in 0..img_height {
827        for x in 0..img_width {
828            let mut sum = 0.0;
829
830            for ky in 0..height {
831                for kx in 0..width {
832                    let dx = kx as i64 - hw;
833                    let dy = ky as i64 - hh;
834                    let nx = (x as i64 + dx).clamp(0, img_width as i64 - 1);
835                    let ny = (y as i64 + dy).clamp(0, img_height as i64 - 1);
836
837                    let pixel_val = src
838                        .get_pixel(nx as u64, ny as u64)
839                        .map_err(AlgorithmError::Core)?;
840                    sum += pixel_val * kernel[ky * width + kx];
841                }
842            }
843
844            dst.set_pixel(x, y, sum / kernel_sum)
845                .map_err(AlgorithmError::Core)?;
846        }
847    }
848
849    Ok(dst)
850}
851
852#[cfg(test)]
853mod tests {
854    use super::*;
855    use approx::assert_abs_diff_eq;
856
857    #[test]
858    fn test_window_shape_rectangular() {
859        let window = WindowShape::rectangular(3, 3)
860            .expect("3x3 rectangular window creation should succeed in test");
861        assert_eq!(window.dimensions(), (3, 3));
862        assert_eq!(window.cell_count(), 9);
863        assert!(window.includes(0, 0));
864        assert!(window.includes(1, 1));
865        assert!(!window.includes(2, 2));
866    }
867
868    #[test]
869    fn test_window_shape_circular() {
870        let window = WindowShape::circular(1.5)
871            .expect("circular window with radius 1.5 should succeed in test");
872        assert!(window.includes(0, 0));
873        assert!(window.includes(1, 0));
874        assert!(window.includes(0, 1));
875        assert!(!window.includes(2, 2));
876    }
877
878    #[test]
879    fn test_window_shape_custom() {
880        let mask = vec![false, true, false, true, true, true, false, true, false];
881        let window = WindowShape::custom(mask, 3, 3)
882            .expect("custom 3x3 window creation should succeed in test");
883        assert_eq!(window.cell_count(), 5);
884        assert!(window.includes(0, 0));
885        assert!(!window.includes(1, 1));
886    }
887
888    #[test]
889    fn test_focal_mean() {
890        let mut src = RasterBuffer::zeros(5, 5, RasterDataType::Float32);
891        // Set center to 5, rest to 0
892        src.set_pixel(2, 2, 5.0)
893            .expect("setting pixel (2,2) should succeed in test");
894
895        let window = WindowShape::rectangular(3, 3)
896            .expect("3x3 rectangular window creation should succeed in test");
897        let result = focal_mean(&src, &window, &BoundaryMode::Edge)
898            .expect("focal_mean operation should succeed in test");
899
900        // Center should be ~0.55 (5/9)
901        let center = result
902            .get_pixel(2, 2)
903            .expect("getting pixel (2,2) from result should succeed in test");
904        assert_abs_diff_eq!(center, 5.0 / 9.0, epsilon = 0.01);
905    }
906
907    #[test]
908    fn test_focal_median() {
909        let mut src = RasterBuffer::zeros(5, 5, RasterDataType::Float32);
910        src.set_pixel(2, 2, 9.0)
911            .expect("setting pixel (2,2) should succeed in test");
912
913        let window = WindowShape::rectangular(3, 3)
914            .expect("3x3 rectangular window creation should succeed in test");
915        let result = focal_median(&src, &window, &BoundaryMode::Edge)
916            .expect("focal_median operation should succeed in test");
917
918        // Median should be 0 (8 zeros, 1 nine)
919        let center = result
920            .get_pixel(2, 2)
921            .expect("getting pixel (2,2) from result should succeed in test");
922        assert_abs_diff_eq!(center, 0.0, epsilon = 0.01);
923    }
924
925    #[test]
926    fn test_focal_range() {
927        let mut src = RasterBuffer::zeros(5, 5, RasterDataType::Float32);
928        src.set_pixel(2, 2, 10.0)
929            .expect("setting pixel (2,2) should succeed in test");
930
931        let window = WindowShape::rectangular(3, 3)
932            .expect("3x3 rectangular window creation should succeed in test");
933        let result = focal_range(&src, &window, &BoundaryMode::Edge)
934            .expect("focal_range operation should succeed in test");
935
936        // Range should be 10
937        let center = result
938            .get_pixel(2, 2)
939            .expect("getting pixel (2,2) from result should succeed in test");
940        assert_abs_diff_eq!(center, 10.0, epsilon = 0.01);
941    }
942
943    #[test]
944    fn test_focal_variety() {
945        let mut src = RasterBuffer::zeros(5, 5, RasterDataType::Float32);
946        src.set_pixel(2, 2, 1.0)
947            .expect("setting pixel (2,2) should succeed in test");
948        src.set_pixel(2, 3, 2.0)
949            .expect("setting pixel (2,3) should succeed in test");
950
951        let window = WindowShape::rectangular(3, 3)
952            .expect("3x3 rectangular window creation should succeed in test");
953        let result = focal_variety(&src, &window, &BoundaryMode::Edge)
954            .expect("focal_variety operation should succeed in test");
955
956        // Should have 3 unique values (0, 1, 2)
957        let center = result
958            .get_pixel(2, 2)
959            .expect("getting pixel (2,2) from result should succeed in test");
960        assert_abs_diff_eq!(center, 3.0, epsilon = 0.01);
961    }
962
963    #[test]
964    fn test_focal_stddev() {
965        let mut src = RasterBuffer::zeros(5, 5, RasterDataType::Float32);
966        for y in 0..5 {
967            for x in 0..5 {
968                src.set_pixel(x, y, (x + y) as f64)
969                    .expect("setting pixel should succeed in test");
970            }
971        }
972
973        let window = WindowShape::rectangular(3, 3)
974            .expect("3x3 rectangular window creation should succeed in test");
975        let result = focal_stddev(&src, &window, &BoundaryMode::Edge)
976            .expect("focal_stddev operation should succeed in test");
977
978        // Should have non-zero standard deviation
979        let center = result
980            .get_pixel(2, 2)
981            .expect("getting pixel (2,2) from result should succeed in test");
982        assert!(center > 0.0);
983    }
984
985    #[test]
986    fn test_focal_mean_separable() {
987        let mut src = RasterBuffer::zeros(10, 10, RasterDataType::Float32);
988        for y in 0..10 {
989            for x in 0..10 {
990                src.set_pixel(x, y, (x + y) as f64)
991                    .expect("setting pixel should succeed in test");
992            }
993        }
994
995        let result = focal_mean_separable(&src, 3, 3)
996            .expect("focal_mean_separable operation should succeed in test");
997
998        // Compare with generic version
999        let window = WindowShape::rectangular(3, 3)
1000            .expect("3x3 rectangular window creation should succeed in test");
1001        let expected = focal_mean(&src, &window, &BoundaryMode::Edge)
1002            .expect("focal_mean operation should succeed in test");
1003
1004        for y in 1..9 {
1005            for x in 1..9 {
1006                let val = result
1007                    .get_pixel(x, y)
1008                    .expect("getting pixel from result should succeed in test");
1009                let exp = expected
1010                    .get_pixel(x, y)
1011                    .expect("getting pixel from expected should succeed in test");
1012                assert_abs_diff_eq!(val, exp, epsilon = 0.1);
1013            }
1014        }
1015    }
1016
1017    #[test]
1018    fn test_boundary_modes() {
1019        let src = RasterBuffer::zeros(3, 3, RasterDataType::Float32);
1020        let window = WindowShape::rectangular(3, 3)
1021            .expect("3x3 rectangular window creation should succeed in test");
1022
1023        // Test all boundary modes - they should not panic
1024        let _ = focal_mean(&src, &window, &BoundaryMode::Ignore);
1025        let _ = focal_mean(&src, &window, &BoundaryMode::Constant(0));
1026        let _ = focal_mean(&src, &window, &BoundaryMode::Reflect);
1027        let _ = focal_mean(&src, &window, &BoundaryMode::Wrap);
1028        let _ = focal_mean(&src, &window, &BoundaryMode::Edge);
1029    }
1030}