lib_jsl_statistics/
kernel_density.rs1use 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#[derive(Clone, Copy, Debug, PartialEq)]
14pub enum Bandwidth {
15 Scott,
17 Silverman,
20 Fixed(f64),
22}
23
24#[derive(Debug, Clone)]
26pub struct GaussianKde {
27 data: Vec<f64>,
28 bandwidth: f64,
29}
30
31impl GaussianKde {
32 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 pub fn bandwidth(&self) -> f64 {
55 self.bandwidth
56 }
57
58 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 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 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 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 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}