Skip to main content

flow_density/kde/
mod.rs

1//! Kernel Density Estimation (KDE) module
2//!
3//! Provides FFT-accelerated KDE with optional GPU support.
4
5mod fft;
6#[cfg(feature = "gpu")]
7mod gpu;
8mod kde2d;
9
10use crate::common::{interquartile_range, standard_deviation};
11use thiserror::Error;
12
13pub use fft::kde_fft;
14#[cfg(feature = "gpu")]
15pub use gpu::kde_fft_gpu;
16pub use kde2d::KernelDensity2D;
17
18/// Error type for KDE operations
19#[derive(Error, Debug)]
20pub enum KdeError {
21    #[error("Empty data for KDE")]
22    EmptyData,
23    #[error("Insufficient data: need at least {min} points, got {actual}")]
24    InsufficientData { min: usize, actual: usize },
25    #[error("Statistics error: {0}")]
26    StatsError(String),
27    #[error("FFT error: {0}")]
28    FftError(String),
29}
30
31pub type KdeResult<T> = Result<T, KdeError>;
32
33/// Kernel Density Estimation using Gaussian kernel with FFT acceleration
34///
35/// This is a simplified implementation of R's density() function
36/// with automatic bandwidth selection using Silverman's rule of thumb.
37/// Uses FFT-based convolution for O(n log n) performance instead of O(n*m).
38pub struct KernelDensity {
39    /// Grid points
40    pub x: Vec<f64>,
41    /// Density values
42    pub y: Vec<f64>,
43}
44
45impl KernelDensity {
46    /// Compute kernel density estimate using FFT-based convolution
47    ///
48    /// # Arguments
49    /// * `data` - Input data
50    /// * `adjust` - Bandwidth adjustment factor (default: 1.0)
51    /// * `n_points` - Number of grid points (default: 512)
52    pub fn estimate(data: &[f64], adjust: f64, n_points: usize) -> KdeResult<Self> {
53        if data.is_empty() {
54            return Err(KdeError::EmptyData);
55        }
56
57        // Remove NaN values
58        let clean_data: Vec<f64> = data.iter().filter(|x| x.is_finite()).copied().collect();
59
60        if clean_data.len() < 3 {
61            return Err(KdeError::InsufficientData {
62                min: 3,
63                actual: clean_data.len(),
64            });
65        }
66
67        // Calculate bandwidth using Silverman's rule of thumb
68        let n = clean_data.len() as f64;
69        let std_dev = standard_deviation(&clean_data).map_err(|e| KdeError::StatsError(e))?;
70        let iqr = interquartile_range(&clean_data).map_err(|e| KdeError::StatsError(e))?;
71
72        // Silverman's rule: bw = 0.9 * min(sd, IQR/1.34) * n^(-1/5)
73        let bw_factor = 0.9 * std_dev.min(iqr / 1.34) * n.powf(-0.2);
74        let bandwidth = bw_factor * adjust;
75
76        // Create grid
77        let data_min = clean_data.iter().cloned().fold(f64::INFINITY, f64::min);
78        let data_max = clean_data.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
79        let grid_min = data_min - 3.0 * bandwidth;
80        let grid_max = data_max + 3.0 * bandwidth;
81
82        let x: Vec<f64> = (0..n_points)
83            .map(|i| grid_min + (grid_max - grid_min) * (i as f64) / (n_points - 1) as f64)
84            .collect();
85
86        // Use FFT-based KDE for better performance
87        // Use GPU if available (batched operations provide speedup even for smaller datasets)
88        #[cfg(feature = "gpu")]
89        let y = if gpu::is_gpu_available() {
90            kde_fft_gpu(&clean_data, &x, bandwidth, n)?
91        } else {
92            kde_fft(&clean_data, &x, bandwidth, n)?
93        };
94
95        #[cfg(not(feature = "gpu"))]
96        let y = kde_fft(&clean_data, &x, bandwidth, n)?;
97
98        Ok(KernelDensity { x, y })
99    }
100
101    /// Find local maxima (peaks) in the density estimate
102    ///
103    /// # Arguments
104    /// * `peak_removal` - Minimum peak height as fraction of max density
105    ///
106    /// # Returns
107    /// Vector of x-coordinates where peaks occur
108    pub fn find_peaks(&self, peak_removal: f64) -> Vec<f64> {
109        if self.y.len() < 3 {
110            return Vec::new();
111        }
112
113        let max_y = self.y.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
114        let threshold = peak_removal * max_y;
115
116        let mut peaks = Vec::new();
117
118        for i in 1..self.y.len() - 1 {
119            // Check if this is a local maximum above threshold
120            if self.y[i] > self.y[i - 1] && self.y[i] > self.y[i + 1] && self.y[i] > threshold {
121                peaks.push(self.x[i]);
122            }
123        }
124
125        // If no peaks found, return the maximum point
126        if peaks.is_empty() {
127            if let Some((idx, _)) = self
128                .y
129                .iter()
130                .enumerate()
131                .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
132            {
133                peaks.push(self.x[idx]);
134            }
135        }
136
137        peaks
138    }
139
140    /// Get density value at a specific point using linear interpolation
141    ///
142    /// # Arguments
143    /// * `x` - The point at which to evaluate the density
144    ///
145    /// # Returns
146    /// The interpolated density value, or 0.0 if x is outside the grid range
147    pub fn density_at(&self, x: f64) -> f64 {
148        if self.x.is_empty() || self.y.is_empty() {
149            return 0.0;
150        }
151
152        // Handle out-of-bounds
153        if x <= self.x[0] {
154            return self.y[0];
155        }
156        if x >= self.x[self.x.len() - 1] {
157            return self.y[self.y.len() - 1];
158        }
159
160        // Find the two grid points to interpolate between
161        let mut left_idx = 0;
162        let mut right_idx = self.x.len() - 1;
163
164        // Binary search for the interval
165        while right_idx - left_idx > 1 {
166            let mid = (left_idx + right_idx) / 2;
167            if self.x[mid] <= x {
168                left_idx = mid;
169            } else {
170                right_idx = mid;
171            }
172        }
173
174        // Linear interpolation
175        let x0 = self.x[left_idx];
176        let x1 = self.x[right_idx];
177        let y0 = self.y[left_idx];
178        let y1 = self.y[right_idx];
179
180        if (x1 - x0).abs() < 1e-10 {
181            y0
182        } else {
183            y0 + (y1 - y0) * (x - x0) / (x1 - x0)
184        }
185    }
186}