hyprstream_calibration/
bootstrap.rs1use crate::error::MetricError;
11
12#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
14pub struct ConfidenceInterval {
15 pub level: f64,
17 pub low: f64,
19 pub high: f64,
21}
22
23#[derive(Debug, Clone)]
25pub struct SplitMix64 {
26 state: u64,
27}
28
29impl SplitMix64 {
30 #[must_use]
32 pub fn new(seed: u64) -> Self {
33 Self { state: seed }
34 }
35
36 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 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
54pub 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}