Skip to main content

lib_jsl_statistics/
bootstrap.rs

1//! The nonparametric bootstrap: standard errors and confidence intervals by resampling.
2//!
3//! See the book entry [The bootstrap](https://jwkunz.github.io/lib_jsl/book/statistics/bootstrap.html).
4
5use lib_jsl_core::ErrorsJSL;
6use lib_jsl_random::uniform_generator::{UniformGenerator, UniformRNG};
7use lib_jsl_special_functions::{normal_cdf, normal_quantile};
8
9/// Bootstrap replicates of a statistic.
10#[derive(Debug, Clone)]
11#[non_exhaustive]
12pub struct BootstrapResult {
13    /// The statistic on the original sample.
14    pub estimate: f64,
15    /// The statistic on each resample.
16    pub replicates: Vec<f64>,
17    /// The standard deviation of the replicates.
18    pub standard_error: f64,
19    /// `mean(replicates) − estimate`.
20    pub bias: f64,
21}
22
23fn quantile_of_sorted(sorted: &[f64], p: f64) -> f64 {
24    let h = (sorted.len() - 1) as f64 * p.clamp(0.0, 1.0);
25    let (lo, frac) = (h.floor() as usize, h - h.floor());
26    if lo + 1 < sorted.len() { sorted[lo] + frac * (sorted[lo + 1] - sorted[lo]) } else { sorted[lo] }
27}
28
29// ANCHOR: bootstrap
30/// Resamples `data` with replacement `resamples` times and evaluates `statistic` on each.
31pub fn bootstrap<S: Fn(&[f64]) -> f64>(data: &[f64], statistic: S, resamples: usize, seed: u64) -> Result<BootstrapResult, ErrorsJSL> {
32    if data.len() < 2 || resamples < 2 {
33        return Err(ErrorsJSL::InvalidInputRange("Need at least two observations and two resamples."));
34    }
35    let n = data.len();
36    let mut rng = UniformRNG::from_seed(seed);
37    let mut sample = vec![0.0; n];
38    let replicates: Vec<f64> = (0..resamples)
39        .map(|_| {
40            for s in sample.iter_mut() {
41                *s = data[((rng.next_f64() * n as f64) as usize).min(n - 1)];
42            }
43            statistic(&sample)
44        })
45        .collect();
46    let estimate = statistic(data);
47    let m = replicates.iter().sum::<f64>() / resamples as f64;
48    let standard_error = (replicates.iter().map(|r| (r - m).powi(2)).sum::<f64>() / (resamples - 1) as f64).sqrt();
49    Ok(BootstrapResult { estimate, replicates, standard_error, bias: m - estimate })
50}
51// ANCHOR_END: bootstrap
52
53impl BootstrapResult {
54    fn sorted(&self) -> Vec<f64> {
55        let mut s = self.replicates.clone();
56        s.sort_by(f64::total_cmp);
57        s
58    }
59
60    /// The percentile interval: the `(1 ∓ confidence)/2` quantiles of the replicates.
61    pub fn percentile_interval(&self, confidence: f64) -> (f64, f64) {
62        let s = self.sorted();
63        let alpha = (1.0 - confidence) / 2.0;
64        (quantile_of_sorted(&s, alpha), quantile_of_sorted(&s, 1.0 - alpha))
65    }
66
67// ANCHOR: bca
68    /// The bias-corrected and accelerated (BCa) interval of Efron: the percentile levels are
69    /// shifted by the bias correction `z₀ = Φ⁻¹(#{θ* < θ̂}/B)` and the acceleration `a` from the
70    /// jackknife skewness of `statistic` on `data` (the same data and statistic as the
71    /// bootstrap). Second-order accurate, unlike the percentile interval.
72    pub fn bca_interval<S: Fn(&[f64]) -> f64>(&self, data: &[f64], statistic: S, confidence: f64) -> (f64, f64) {
73        let s = self.sorted();
74        let below = s.iter().filter(|&&r| r < self.estimate).count() as f64;
75        let z0 = normal_quantile((below / s.len() as f64).clamp(1e-10, 1.0 - 1e-10), 0.0, 1.0);
76        let n = data.len();
77        let jackknife: Vec<f64> = (0..n).map(|i| statistic(&[&data[..i], &data[i + 1..]].concat())).collect();
78        let jm = jackknife.iter().sum::<f64>() / n as f64;
79        let (num, den) = jackknife.iter().fold((0.0, 0.0), |(a, b), &t| (a + (jm - t).powi(3), b + (jm - t).powi(2)));
80        let acceleration = if den > 0.0 { num / (6.0 * den.powf(1.5)) } else { 0.0 };
81        let level = |z: f64| normal_cdf(z0 + (z0 + z) / (1.0 - acceleration * (z0 + z)), 0.0, 1.0);
82        let z = normal_quantile((1.0 + confidence) / 2.0, 0.0, 1.0);
83        (quantile_of_sorted(&s, level(-z)), quantile_of_sorted(&s, level(z)))
84    }
85// ANCHOR_END: bca
86}
87
88#[cfg(test)]
89mod tests {
90    use super::*;
91    use lib_jsl_random::distributions::exponential_distribution;
92
93    fn mean(x: &[f64]) -> f64 {
94        x.iter().sum::<f64>() / x.len() as f64
95    }
96
97    #[test]
98    fn standard_error_of_the_mean_matches_theory() {
99        let data: Vec<f64> = (0..100).map(|i| ((i * 37) % 100) as f64 / 10.0).collect();
100        let b = bootstrap(&data, mean, 4000, 1).unwrap();
101        let sd = (data.iter().map(|v| (v - mean(&data)).powi(2)).sum::<f64>() / data.len() as f64).sqrt();
102        assert!((b.standard_error / (sd / 10.0) - 1.0).abs() < 0.05, "{} vs {}", b.standard_error, sd / 10.0);
103        assert!(b.bias.abs() < 0.02 && b.estimate == mean(&data));
104        let (lo, hi) = b.percentile_interval(0.95);
105        assert!(lo < b.estimate && b.estimate < hi && ((hi - lo) / (2.0 * 1.96 * sd / 10.0) - 1.0).abs() < 0.1);
106        assert!(bootstrap(&[1.0], mean, 10, 0).is_err());
107    }
108
109    #[test]
110    fn bca_intervals_cover_a_skewed_mean_at_the_nominal_rate() {
111        // Means of exponential samples (true mean 1) are right-skewed; BCa shifts its interval
112        // up relative to the percentile one and covers close to the nominal 90%.
113        let mut rng = UniformRNG::from_seed(7);
114        let trials = 200;
115        let mut covered = 0;
116        let mut shifted_up = 0;
117        for t in 0..trials {
118            let data: Vec<f64> = (0..25).map(|_| exponential_distribution(&mut rng, 1.0)).collect();
119            let b = bootstrap(&data, mean, 1000, t as u64).unwrap();
120            let (lo, hi) = b.bca_interval(&data, mean, 0.9);
121            let (plo, phi) = b.percentile_interval(0.9);
122            covered += (lo <= 1.0 && 1.0 <= hi) as usize;
123            shifted_up += (lo + hi > plo + phi) as usize;
124        }
125        assert!((150..=195).contains(&covered), "coverage {covered}/{trials}");
126        assert!(shifted_up > trials * 3 / 4, "{shifted_up}");
127    }
128}