//! Anytime-valid confidence sequence for a streaming mean, so the ladder can PEEK after every deal //! and stop the moment a paired difference is decisive -- without the optional-stopping inflation //! that quietly invalidates a fixed-n 95 % interval the instant you look at it early. //! //! # Why not a fixed-n CI, and why not a classic SPRT //! //! A fixed-n CI (`sim::paired`) is only valid at the ONE n it was computed for; stop as soon as it //! looks significant and the true type-I error balloons. Wald's SPRT fixes the peeking but assumes a //! KNOWN variance and a simple-vs-simple hypothesis -- neither holds for bb-per-deal. The modern, //! correct instrument is a time-uniform confidence sequence: an interval valid SIMULTANEOUSLY at //! every n, so you may watch it continuously and stop at any rule you like. //! //! # The boundary (derived, not recited) //! //! For increments `X_i - mu` with variance proxy `s2`, `M_n(lam) = exp(lam*S_n - lam^2*s2*n/2)` is a //! supermartingale with mean 1 (`S_n = sum(X_i - mu)`). Mix `lam ~ N(0, 1/(rho*s2))` and integrate: //! //! M_n = sqrt( rho/(n+rho) ) * exp( S_n^2 / (2*s2*(n+rho)) ). //! //! Ville's inequality gives `P(exists n: M_n >= 1/a) <= a`. Setting `M_n >= 1/a` and solving for S_n: //! //! |S_n| < sqrt( 2*s2*(n+rho) * [ ln(1/a) + 0.5*ln((n+rho)/rho) ] ) (each side; use a = alpha/2). //! //! Divide by n for the mean. `rho` sets where the boundary is tightest (near `rho` samples); pick it //! at the expected horizon. With a KNOWN sub-Gaussian `s2` the coverage is exact; we plug in the //! running sample variance, so the guarantee is asymptotic -- `tests` checks the real miscoverage //! under optional stopping stays at or below the nominal level. The rigorous fixed-sample-size-free //! upgrade for unknown variance is the self-normalised (Student) mixture; noted, not yet built. /// What a peek concludes. `Continue` = not yet separated from zero; the caller stops on /// `Better`/`Worse` or when it runs out of deals (then the result is simply unclear). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Decision { /// The whole confidence sequence lies above the threshold. Better, /// The whole confidence sequence lies below the threshold. Worse, /// Zero (or the threshold) is still inside: keep sampling. Continue, } /// A running normal-mixture confidence sequence over a stream of per-deal values. #[derive(Clone, Debug)] pub struct ConfSeq { n: u64, sum: f64, sumsq: f64, /// Ville error budget per side; the two-sided sequence holds at level `2*alpha_side`. alpha_side: f64, /// Mixture tightness: boundary is sharpest near `rho` samples. rho: f64, /// Variance floor, so an all-identical prefix cannot claim a zero-width interval. var_floor: f64, } impl ConfSeq { /// Two-sided level `alpha` (e.g. 0.05), boundary tuned to be sharpest near `horizon` samples. pub fn new(alpha: f64, horizon: u64) -> ConfSeq { ConfSeq { n: 0, sum: 0.0, sumsq: 0.0, alpha_side: (alpha / 2.0).clamp(1e-9, 0.5), rho: (horizon.max(1)) as f64, var_floor: 1e-9, } } pub fn push(&mut self, x: f64) { self.n += 1; self.sum += x; self.sumsq += x * x; } pub fn count(&self) -> u64 { self.n } pub fn mean(&self) -> f64 { if self.n == 0 { 0.0 } else { self.sum / self.n as f64 } } /// Unbiased sample variance, floored. fn var(&self) -> f64 { if self.n < 2 { return f64::INFINITY; } let n = self.n as f64; let m = self.sum / n; ((self.sumsq - n * m * m) / (n - 1.0)).max(self.var_floor) } /// Half-width of the time-uniform interval around the running mean (input units). Infinite until /// two samples exist. pub fn radius(&self) -> f64 { let s2 = self.var(); if !s2.is_finite() { return f64::INFINITY; } let n = self.n as f64; let nr = n + self.rho; let log_term = (1.0 / self.alpha_side).ln() + 0.5 * (nr / self.rho).ln(); (2.0 * s2 * nr * log_term).sqrt() / n } /// Time-uniform confidence interval for the true mean: holds simultaneously at every `n`. pub fn interval(&self) -> (f64, f64) { let (m, r) = (self.mean(), self.radius()); (m - r, m + r) } /// Decide against a threshold (0.0 for "is the difference positive?"). `Better` once the whole /// interval sits above `threshold`, `Worse` once wholly below, else `Continue`. pub fn decide(&self, threshold: f64) -> Decision { let (lo, hi) = self.interval(); if !lo.is_finite() { return Decision::Continue; } if lo > threshold { Decision::Better } else if hi < threshold { Decision::Worse } else { Decision::Continue } } } #[cfg(test)] mod tests { use super::*; struct Lcg(u64); impl Lcg { fn unif(&mut self) -> f64 { self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); ((self.0 >> 11) as f64 + 0.5) / (1u64 << 53) as f64 } fn normal(&mut self) -> f64 { (-2.0 * self.unif().ln()).sqrt() * (6.2831853071 * self.unif()).cos() } } /// The defining guarantee: under optional stopping the true mean escapes the sequence at MOST a /// 5 % fraction of runs, no matter how adversarially you peek. We peek after every sample and /// record the worst-ever excursion over a long horizon. #[test] fn time_uniform_coverage_under_peeking() { let (alpha, runs, horizon) = (0.05, 4000usize, 3000u64); let (mu, sigma) = (0.3, 10.0); // bb-per-deal-ish: tiny edge, huge spread let mut escaped = 0; for k in 0..runs { let mut r = Lcg(0xC0FFEE + k as u64); let mut cs = ConfSeq::new(alpha, horizon); let mut ever_out = false; for _ in 0..horizon { cs.push(mu + sigma * r.normal()); let (lo, hi) = cs.interval(); if lo.is_finite() && (mu < lo || mu > hi) { ever_out = true; break; } } escaped += ever_out as usize; } let rate = escaped as f64 / runs as f64; println!("peeking miscoverage {:.3} (nominal {:.3}) over {runs} runs x {horizon}", rate, alpha); // Time-uniform: the ALL-TIMES escape rate must not exceed the nominal per-interval level // (small plug-in slack allowed; the mixture is conservative, so it usually sits well under). assert!(rate <= alpha * 1.3, "miscoverage {rate:.3} over budget"); } /// Power: on a clear edge the sequence separates from zero, and far inside the horizon. #[test] fn stops_early_on_a_clear_edge() { let (alpha, horizon) = (0.05, 5000u64); let (mu, sigma) = (2.0, 8.0); let mut r = Lcg(7); let mut cs = ConfSeq::new(alpha, horizon); let mut stopped_at = None; for i in 1..=horizon { cs.push(mu + sigma * r.normal()); if cs.decide(0.0) == Decision::Better { stopped_at = Some(i); break; } } let n = stopped_at.expect("never separated from zero"); println!("separated from 0 after {n} deals (horizon {horizon})"); assert!(n < horizon, "no early stop"); } /// A true zero edge must NOT be declared better or worse just because we watched a long time. #[test] fn null_edge_rarely_fires() { let (alpha, runs, horizon) = (0.05, 2000usize, 2000u64); let mut fired = 0; for k in 0..runs { let mut r = Lcg(555 + k as u64); let mut cs = ConfSeq::new(alpha, horizon); let mut hit = false; for _ in 0..horizon { cs.push(7.0 * r.normal()); // mu = 0 exactly match cs.decide(0.0) { Decision::Better | Decision::Worse => { hit = true; break; } Decision::Continue => {} } } fired += hit as usize; } let rate = fired as f64 / runs as f64; println!("false-decision rate under the null {:.3} (nominal {:.3})", rate, alpha); assert!(rate <= alpha * 1.3, "fires too often under the null: {rate:.3}"); } /// Radius follows a sqrt(log n / n) envelope: it wiggles with the online variance estimate but /// shrinks decisively over the run. We check the envelope at checkpoints, not per-step monotony /// (the running s^2 ticks both ways, so a strict per-step drop is the wrong thing to demand). #[test] fn radius_follows_shrinking_envelope() { let mut r = Lcg(99); let mut cs = ConfSeq::new(0.05, 1000); let mut at: std::collections::BTreeMap = Default::default(); for i in 1..=4000u64 { cs.push(1.0 + 5.0 * r.normal()); if [100, 500, 2000, 4000].contains(&i) { at.insert(i, cs.radius()); } } println!("radius: {:?}", at.iter().map(|(n, r)| (n, (r * 1e3).round() / 1e3)).collect::>()); // Each checkpoint strictly tighter than the last: the envelope wins over the variance wiggle. assert!(at[&500] < at[&100], "500 vs 100"); assert!(at[&2000] < at[&500], "2000 vs 500"); assert!(at[&4000] < at[&2000], "4000 vs 2000"); // Shape: halving n near-doubles... the radius should fall by a clear factor over 40x data. assert!(at[&4000] < 0.6 * at[&100], "envelope barely moved"); } }