Skip to main content

hyprstream_calibration/
bootstrap.rs

1//! Deterministic bootstrap confidence intervals for gate statistics.
2//!
3//! The gate protocol pins **percentile bootstrap CIs at 95% over 1000 resamples**
4//! ([`crate::protocol::GATE_BOOTSTRAP_RESAMPLES`], [`crate::protocol::GATE_CI_LEVEL`]).
5//! Resampling is seeded and deterministic — a gate report must be reproducible from its
6//! recorded seed, so this module carries its own small generator instead of depending on
7//! an RNG crate. `SplitMix64` is a fast counter-based generator, adequate for index
8//! resampling; it is not cryptographic and is never used for secrets.
9
10use crate::error::MetricError;
11
12/// A percentile bootstrap confidence interval.
13#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
14pub struct ConfidenceInterval {
15    /// Nominal coverage level (e.g. 0.95).
16    pub level: f64,
17    /// Lower percentile bound.
18    pub low: f64,
19    /// Upper percentile bound — gate comparisons that pin a bound condition on this.
20    pub high: f64,
21}
22
23/// SplitMix64 pseudo-random generator (deterministic, non-cryptographic).
24#[derive(Debug, Clone)]
25pub struct SplitMix64 {
26    state: u64,
27}
28
29impl SplitMix64 {
30    /// Seed the generator.
31    #[must_use]
32    pub fn new(seed: u64) -> Self {
33        Self { state: seed }
34    }
35
36    /// Next `u64` in the stream.
37    pub fn next_u64(&mut self) -> u64 {
38        self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15);
39        let mut z = self.state;
40        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
41        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
42        z ^ (z >> 31)
43    }
44
45    /// Uniform index in `0..n`.
46    pub fn below(&mut self, n: usize) -> usize {
47        debug_assert!(n > 0);
48        #[allow(clippy::cast_possible_truncation)]
49        let n64 = n as u64;
50        (self.next_u64() % n64) as usize
51    }
52}
53
54/// Percentile bootstrap CI for `statistic` over `values`.
55///
56/// Draws `resamples` resamples of size `values.len()` with replacement using
57/// `SplitMix64::new(seed)`, evaluates the statistic on each, and returns the observed
58/// statistic together with the `(1 − level)/2` and `1 − (1 − level)/2` percentiles of
59/// the resample distribution.
60///
61/// # Errors
62/// [`MetricError::EmptyInput`] on empty values; [`MetricError::InvalidLevel`] for a
63/// level outside `(0, 1)`; [`MetricError::InvalidBinCount`] if `resamples` is zero.
64pub fn bootstrap_ci(
65    values: &[f64],
66    statistic: impl Fn(&[f64]) -> f64,
67    resamples: usize,
68    level: f64,
69    seed: u64,
70) -> Result<(f64, ConfidenceInterval), MetricError> {
71    if values.is_empty() {
72        return Err(MetricError::EmptyInput("bootstrap"));
73    }
74    if !(0.0..1.0).contains(&level) {
75        return Err(MetricError::InvalidLevel { value: level });
76    }
77    if resamples == 0 {
78        return Err(MetricError::InvalidBinCount {
79            bins: resamples,
80            n: values.len(),
81        });
82    }
83    let observed = statistic(values);
84    let mut rng = SplitMix64::new(seed);
85    let mut dist = Vec::with_capacity(resamples);
86    let mut draw = Vec::with_capacity(values.len());
87    for _ in 0..resamples {
88        draw.clear();
89        for _ in 0..values.len() {
90            draw.push(values[rng.below(values.len())]);
91        }
92        dist.push(statistic(&draw));
93    }
94    dist.sort_by(f64::total_cmp);
95    let percentile = |q: f64| -> f64 {
96        #[allow(clippy::cast_precision_loss, clippy::cast_sign_loss)]
97        let idx = {
98            let pos = q * (dist.len() - 1) as f64;
99            pos.round().clamp(0.0, (dist.len() - 1) as f64) as usize
100        };
101        dist[idx]
102    };
103    let tail = (1.0 - level) / 2.0;
104    Ok((
105        observed,
106        ConfidenceInterval {
107            level,
108            low: percentile(tail),
109            high: percentile(1.0 - tail),
110        },
111    ))
112}