Skip to main content

adk_eval/experiments/
sequential.rs

1//! The normal-mixture sequential boundary: always-valid p-values and confidence sequences
2//! (spec 3.5 §7.12).
3
4use serde::{Deserialize, Serialize};
5
6use crate::error::{EvalError, Result};
7
8/// The always-valid boundary of a sequential test with a fixed error budget (spec 3.5 §7.12).
9///
10/// For an estimate with standard error `se` after `n` effective units, the boundary rejects
11/// "no difference" when `|z| = |estimate / se|` reaches [`critical_z(n)`](Self::critical_z),
12///
13/// ```text
14/// z*(n)² = (1 + ρ²n) / (ρ²n) · (2 ln(1/α) + ln(1 + ρ²n)),
15/// ```
16///
17/// the inversion of the normal-mixture likelihood ratio
18/// `Λ = (1 + ρ²n)^(−1/2) · exp(ρ²n·z² / (2(1 + ρ²n)))`. Under no difference Λ is a nonnegative
19/// martingale starting at 1, so by Ville's inequality it ever reaches `1/α` with probability at
20/// most α, however many looks are taken. `estimate ± z*(n)·se` is the matching confidence
21/// sequence: it covers the true difference at every look at once with probability at least
22/// `1 − α`.
23///
24/// ρ is fixed before the first look from the planned effective units `m`:
25/// `ρ² = (2 ln(1/α) + ln(1 + 2 ln(1/α))) / m`, which makes the boundary tightest near `m`.
26/// It changes power, never validity.
27///
28/// # Example
29///
30/// ```
31/// use adk_eval::experiments::SequentialBoundary;
32///
33/// // 10,000 planned units per arm are 5,000 effective units.
34/// let boundary = SequentialBoundary::new(0.05, 5_000.0).unwrap();
35/// // At the planned size the critical z is 3.04, against 1.96 for one fixed-sample look.
36/// assert!((boundary.critical_z(5_000.0) - 3.0352).abs() < 1e-4);
37/// // A z on the boundary has an always-valid p-value equal to α.
38/// let z = boundary.critical_z(1_200.0);
39/// assert!((boundary.p_value(z, 1_200.0) - 0.05).abs() < 1e-12);
40/// ```
41#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
42#[serde(rename_all = "camelCase")]
43pub struct SequentialBoundary {
44    alpha: f64,
45    mixing_rate: f64,
46}
47
48impl SequentialBoundary {
49    /// Creates the boundary for budget `alpha`, tightest at `planned_effective_units`.
50    ///
51    /// # Errors
52    ///
53    /// Returns [`EvalError::ConfigError`] when `alpha` is outside `(0, 1)` or the planned size
54    /// is not a positive finite number.
55    pub fn new(alpha: f64, planned_effective_units: f64) -> Result<Self> {
56        if !(alpha > 0.0 && alpha < 1.0) {
57            return Err(EvalError::ConfigError(format!(
58                "sequential boundary alpha = {alpha}; use a value in (0, 1)"
59            )));
60        }
61        if !(planned_effective_units.is_finite() && planned_effective_units > 0.0) {
62            return Err(EvalError::ConfigError(format!(
63                "sequential boundary planned size = {planned_effective_units}; use a positive \
64                 number of effective units"
65            )));
66        }
67        let c = 2.0 * (1.0 / alpha).ln();
68        Ok(Self { alpha, mixing_rate: (c + (1.0 + c).ln()) / planned_effective_units })
69    }
70
71    /// Returns the error budget α.
72    pub fn alpha(&self) -> f64 {
73        self.alpha
74    }
75
76    /// Returns ρ², the mixing rate per effective unit.
77    pub fn mixing_rate(&self) -> f64 {
78        self.mixing_rate
79    }
80
81    /// Returns the critical |z| after `effective_units`; infinite with no units.
82    pub fn critical_z(&self, effective_units: f64) -> f64 {
83        let x = self.mixing_rate * effective_units;
84        if x.is_nan() || x <= 0.0 {
85            return f64::INFINITY;
86        }
87        ((1.0 + x) / x * (2.0 * (1.0 / self.alpha).ln() + x.ln_1p())).sqrt()
88    }
89
90    /// Returns `min(1, 1/Λ)`, the always-valid p-value of `z` at this look alone.
91    ///
92    /// The p-value of a test is the running minimum of this value over its looks; it is at most
93    /// α exactly when `|z|` reaches [`critical_z`](Self::critical_z).
94    pub fn p_value(&self, z: f64, effective_units: f64) -> f64 {
95        let x = self.mixing_rate * effective_units;
96        if x.is_nan() || x <= 0.0 || !z.is_finite() {
97            return 1.0;
98        }
99        let log_inverse_lambda = 0.5 * x.ln_1p() - x * z * z / (2.0 * (1.0 + x));
100        log_inverse_lambda.exp().min(1.0)
101    }
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107
108    /// The Gaussian-mixture asymptotic confidence sequence of Waudby-Smith, Arbour, Sinha,
109    /// Kennedy and Ramdas (arXiv:2103.06476), written in their parameterisation: the half-width
110    /// for unit variance after `t` units, times √t.
111    fn waudby_smith(alpha: f64, rho2: f64, t: f64) -> f64 {
112        (2.0 * (t * rho2 + 1.0) / (t * t * rho2) * ((t * rho2 + 1.0).sqrt() / alpha).ln()).sqrt()
113            * t.sqrt()
114    }
115
116    #[test]
117    fn critical_z_matches_the_published_confidence_sequence() {
118        for (alpha, planned, n) in [
119            (0.05, 5_000.0, 5_000.0),
120            (0.05, 5_000.0, 100.0),
121            (0.05, 5_000.0, 50_000.0),
122            (0.1, 500.0, 250.0),
123            (0.01, 20_000.0, 1_000.0),
124        ] {
125            let boundary = SequentialBoundary::new(alpha, planned).unwrap();
126            let expected = waudby_smith(alpha, boundary.mixing_rate(), n);
127            assert!((boundary.critical_z(n) - expected).abs() < 1e-12, "{alpha} {planned} {n}");
128        }
129    }
130
131    // Reference values computed independently in Python.
132    #[test]
133    fn critical_z_matches_reference_values() {
134        let boundary = SequentialBoundary::new(0.05, 5_000.0).unwrap();
135        assert!((boundary.mixing_rate() - 0.001587230920347513).abs() < 1e-15);
136        assert!((boundary.critical_z(5_000.0) - 3.0352089903762534).abs() < 1e-12);
137        assert!((boundary.critical_z(100.0) - 6.69438861706604).abs() < 1e-12);
138        assert!((boundary.critical_z(50_000.0) - 3.241723145405438).abs() < 1e-12);
139    }
140
141    #[test]
142    fn the_boundary_is_tightest_near_the_planned_size() {
143        let boundary = SequentialBoundary::new(0.05, 5_000.0).unwrap();
144        let at_plan = boundary.critical_z(5_000.0);
145        for n in [500.0, 2_000.0, 20_000.0, 200_000.0] {
146            assert!(boundary.critical_z(n) > at_plan, "n = {n}");
147        }
148        assert!(at_plan > 1.959_963_984_540_054);
149    }
150
151    #[test]
152    fn no_units_means_no_evidence() {
153        let boundary = SequentialBoundary::new(0.05, 5_000.0).unwrap();
154        assert_eq!(boundary.critical_z(0.0), f64::INFINITY);
155        assert_eq!(boundary.p_value(10.0, 0.0), 1.0);
156        assert_eq!(boundary.p_value(0.0, 5_000.0), 1.0);
157    }
158
159    #[test]
160    fn invalid_settings_are_refused() {
161        assert!(SequentialBoundary::new(0.0, 10.0).is_err());
162        assert!(SequentialBoundary::new(1.0, 10.0).is_err());
163        assert!(SequentialBoundary::new(0.05, 0.0).is_err());
164        assert!(SequentialBoundary::new(0.05, f64::INFINITY).is_err());
165    }
166}