Skip to main content

lib_jsl_statistics/
kernel_density.rs

1//! Kernel density estimation with a Gaussian kernel.
2//!
3//! See the book entry [Kernel density estimation](https://jwkunz.github.io/lib_jsl/book/statistics/kernel-density.html).
4
5use crate::descriptive::{interquartile_range, standard_deviation};
6use lib_jsl_core::ErrorsJSL;
7use lib_jsl_random::distributions::gaussian_distribution_box_muller;
8use lib_jsl_random::uniform_generator::UniformGenerator;
9use lib_jsl_special_functions::normal_cdf;
10use std::f64::consts::PI;
11
12/// How to choose the kernel bandwidth.
13#[derive(Clone, Copy, Debug, PartialEq)]
14pub enum Bandwidth {
15    /// Scott's rule `σ n^{−1/5}` (SciPy's default factor).
16    Scott,
17    /// Silverman's rule of thumb `0.9 min(σ, IQR/1.34) n^{−1/5}`, robust to outliers and
18    /// heavy tails.
19    Silverman,
20    /// A given bandwidth.
21    Fixed(f64),
22}
23
24/// A Gaussian kernel density estimate `f̂(x) = (1/(n h)) Σ φ((x − xᵢ)/h)`.
25#[derive(Debug, Clone)]
26pub struct GaussianKde {
27    data: Vec<f64>,
28    bandwidth: f64,
29}
30
31impl GaussianKde {
32    // ANCHOR: kde_new
33    pub fn new(data: &[f64], bandwidth: Bandwidth) -> Result<Self, ErrorsJSL> {
34        if data.len() < 2 || data.iter().any(|v| !v.is_finite()) {
35            return Err(ErrorsJSL::InvalidInputRange("Need at least two finite observations."));
36        }
37        let n = data.len() as f64;
38        let h = match bandwidth {
39            Bandwidth::Scott => standard_deviation(data, 1)? * n.powf(-0.2),
40            Bandwidth::Silverman => {
41                let sigma = standard_deviation(data, 1)?;
42                let spread = interquartile_range(data)? / 1.34;
43                0.9 * if spread > 0.0 { sigma.min(spread) } else { sigma } * n.powf(-0.2)
44            }
45            Bandwidth::Fixed(h) => h,
46        };
47        if !(h > 0.0) {
48            return Err(ErrorsJSL::InvalidInputRange("The bandwidth must be positive (is the sample constant?)."));
49        }
50        Ok(GaussianKde { data: data.to_vec(), bandwidth: h })
51    }
52    // ANCHOR_END: kde_new
53
54    pub fn bandwidth(&self) -> f64 {
55        self.bandwidth
56    }
57
58    /// The estimated density at `x`.
59    pub fn pdf(&self, x: f64) -> f64 {
60        let h = self.bandwidth;
61        self.data.iter().map(|&xi| (-0.5 * ((x - xi) / h).powi(2)).exp()).sum::<f64>() / (self.data.len() as f64 * h * (2.0 * PI).sqrt())
62    }
63
64    /// The estimated cumulative distribution at `x`.
65    pub fn cdf(&self, x: f64) -> f64 {
66        self.data.iter().map(|&xi| normal_cdf(x, xi, self.bandwidth)).sum::<f64>() / self.data.len() as f64
67    }
68
69    /// Draws `count` samples from the estimate (a random observation plus kernel noise).
70    pub fn resample<U: UniformGenerator>(&self, count: usize, rng: &mut U) -> Vec<f64> {
71        (0..count)
72            .map(|_| {
73                let i = ((rng.next_f64() * self.data.len() as f64) as usize).min(self.data.len() - 1);
74                gaussian_distribution_box_muller(rng, self.data[i], self.bandwidth).0
75            })
76            .collect()
77    }
78}
79
80#[cfg(test)]
81mod tests {
82    use super::*;
83    use lib_jsl_random::uniform_generator::UniformRNG;
84    use lib_jsl_special_functions::normal_pdf;
85
86    fn normal_sample(n: usize, seed: u64) -> Vec<f64> {
87        let mut rng = UniformRNG::from_seed(seed);
88        (0..n).map(|_| gaussian_distribution_box_muller(&mut rng, 0.0, 1.0).0).collect()
89    }
90
91    #[test]
92    fn recovers_a_normal_density() {
93        let data = normal_sample(5000, 1);
94        let kde = GaussianKde::new(&data, Bandwidth::Scott).unwrap();
95        assert!((kde.bandwidth() - 5000f64.powf(-0.2)).abs() < 0.01);
96        for &x in &[-2.0, -1.0, 0.0, 0.5, 1.5] {
97            assert!((kde.pdf(x) - normal_pdf(x, 0.0, 1.0)).abs() < 0.02, "x={x}");
98        }
99        // The estimate is a density: it integrates to one, and its CDF runs from 0 to 1.
100        let h = 0.01;
101        let integral: f64 = (-800..800).map(|i| kde.pdf(i as f64 * h) * h).sum();
102        assert!((integral - 1.0).abs() < 1e-4);
103        assert!(kde.cdf(-10.0) < 1e-12 && (kde.cdf(10.0) - 1.0).abs() < 1e-12 && (kde.cdf(0.0) - 0.5).abs() < 0.03);
104    }
105
106    #[test]
107    fn silverman_resists_outliers_and_resampling_matches_moments() {
108        let mut data = normal_sample(500, 2);
109        data.extend([200.0, -150.0]);
110        let scott = GaussianKde::new(&data, Bandwidth::Scott).unwrap().bandwidth();
111        let silverman = GaussianKde::new(&data, Bandwidth::Silverman).unwrap().bandwidth();
112        assert!(silverman < scott / 5.0, "{silverman} vs {scott}");
113        let kde = GaussianKde::new(&normal_sample(2000, 3), Bandwidth::Fixed(0.3)).unwrap();
114        let draws = kde.resample(50_000, &mut UniformRNG::from_seed(4));
115        let mean = draws.iter().sum::<f64>() / draws.len() as f64;
116        let var = draws.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / draws.len() as f64;
117        // Resampled variance is the data variance plus h².
118        assert!(mean.abs() < 0.05 && (var - (1.0 + 0.09)).abs() < 0.1, "{mean} {var}");
119        assert!(GaussianKde::new(&[1.0, 1.0, 1.0], Bandwidth::Scott).is_err() && GaussianKde::new(&[1.0], Bandwidth::Fixed(1.0)).is_err());
120    }
121}