Algorithm Search⌘K

Algorithmresearch

Mixture sequential probability ratio test

Also called mSPRT, always valid p-value.

An SPRT whose alternative is a mixture over effect sizes. Its likelihood ratio is a test martingale, so its test and its p-values stay valid at any stopping time.

Time
Θ(n) worst
Space
Θ(1) extra
Where
n = the number of observations read before the test stops or the stream ends
Properties
anytime validdeterministiconlineiterative
Origin
Herbert Robbins, Ramesh Johari, Pete Koomen, Leonid Pekelis, David Walsh, 1970

The mixture sequential probability ratio test (mSPRT) tests a point null hypothesis θ=θ0\theta = \theta_0 against the composite alternative θ≠θ0\theta \ne \theta_0 while the data arrive. Where the SPRT needs one alternative value, the mSPRT averages the likelihood ratio over a mixing distribution of alternatives that is fixed in advance. The mixture is a test martingale under the null, so by Ville's inequality the rule "reject when the mixture reaches 1/α1/\alpha" has type I error at most α\alpha for every way the analyst may look at the data and stop. The reciprocal of its running maximum is an always valid p-value, which online experiment platforms show to users who check their results every day.

In plain words

In an online experiment people look at the results every day and stop as soon as the effect looks significant. A normal test assumes that you look only once, at a size fixed in advance. Each extra look is a new chance for noise to look like an effect, so the false alarm rate grows well above the stated level. The mSPRT keeps a single running score that compares "there is some effect, of a size from a range fixed in advance" with "there is no effect". If there is truly no effect, the score is a fair game that cannot go below zero, so it seldom gets large. You may look after every new data point and stop when you like. The false alarm rate stays below the level you chose. The price is that a real effect needs somewhat more data to show.

The problem

Observations X1,X2,…X_1, X_2, \ldots are i.i.d. with density fθf_\theta from a parametric family. Test H0:θ=θ0H_0: \theta = \theta_0 against H1:θ≠θ0H_1: \theta \ne \theta_0, with a rule that may stop at any stopping time TT, chosen by the analyst while the data arrive, such that

Pθ0(the test rejects at or before T)≤αfor every stopping time T,P_{\theta_0}(\text{the test rejects at or before } T) \le \alpha \quad \text{for every stopping time } T,

and such that the test rejects eventually under every alternative. Also produce p-values pnp_n with Pθ0(pT≤u)≤uP_{\theta_0}(p_T \le u) \le u for every stopping time TT and every u∈[0,1]u \in [0, 1]. These are the always valid p-values of Johari, Koomen, Pekelis and Walsh.

Given a mixing distribution π\pi on the parameters, the mixture likelihood ratio is

Λn=∫∏i=1nfθ(Xi)fθ0(Xi) π(dθ).\Lambda_n = \int \prod_{i=1}^n \frac{f_\theta(X_i)}{f_{\theta_0}(X_i)}\,\pi(d\theta).

For normal data N(θ,σ2)N(\theta, \sigma^2) with σ\sigma known and π=N(θ0,τ2)\pi = N(\theta_0, \tau^2), with Sn=∑i≤n(Xi−θ0)S_n = \sum_{i \le n}(X_i - \theta_0), the integral has the closed form

Λn=σ2σ2+nτ2 exp⁡(τ2Sn22σ2(σ2+nτ2)).\Lambda_n = \sqrt{\frac{\sigma^2}{\sigma^2 + n\tau^2}}\,\exp\left(\frac{\tau^2 S_n^2}{2\sigma^2(\sigma^2 + n\tau^2)}\right).

The algorithm

  1. MSPRT(x_1, x_2, ..., θ_0, σ, τ, α) ▷ σ, τ > 0 and 0 < α < 1
  2. 1S ← 0, n ← 0, p ← 1
  3. 2for each new observation x do
  4. 3n ← n + 1, S ← S + (x - θ_0)
  5. 4Λ ← sqrt(σ² / (σ² + nτ²)) · exp(τ² S² / (2σ²(σ² + nτ²)))
  6. 5p ← min(p, 1 / Λ) ▷ always valid p-value p_n
  7. 6if Λ ≥ 1/α then return (reject H_0, n, p)
  8. 7return (no rejection, n, p)

Line L3 keeps the centred sum, which is a sufficient statistic. Line L4 evaluates the closed-form mixture. Line L5 keeps pn=min⁡(1,1/max⁡k≤nΛk)p_n = \min(1, 1/\max_{k \le n}\Lambda_k), which never increases, so a p-value once shown can only go down. Line L6 rejects at the first time the mixture reaches 1/α1/\alpha; this is the same event as pn≤αp_n \le \alpha. There is no lower threshold: the test never accepts H0H_0, and if the analyst stops for another reason, line L7 reports that the test did not reject and gives the current p-value.

Example

Let θ0=0\theta_0 = 0, σ=τ=1\sigma = \tau = 1 and α=0.05\alpha = 0.05, so the threshold is Λ≥20\Lambda \ge 20. On the data 0.8,1.4,−0.2,1.1,0.9,1.6,0.3,1.20.8, 1.4, -0.2, 1.1, 0.9, 1.6, 0.3, 1.2:

nn 1 2 3 4 5 6 7 8
SnS_n 0.8 2.2 2.0 3.1 4.0 5.6 5.9 7.1
Λn\Lambda_n 0.830 1.294 0.824 1.169 1.549 3.550 3.114 5.485
always valid pnp_n 1 0.7731 0.7731 0.7731 0.6457 0.2817 0.2817 0.1823
fixed-nn z-test p-value 0.4237 0.1198 0.2482 0.1211 0.0736 0.0222 0.0257 0.0121

The mSPRT does not reject: its largest value is 5.485, far below 20. The two-sided z-test p-value 2Φˉ(∣Sn∣/n)2\bar\Phi(|S_n|/\sqrt n) falls below 0.05 at n=6n = 6, so an analyst who reruns the fixed-sample test after every observation would stop at n=6n = 6 and claim an effect. That p-value is valid only if n=6n = 6 was fixed in advance.

The difference matters under the null. In 2000 simulated streams of N(0,1)N(0, 1) data with a horizon of 500 observations (seed 5, as in the tests), the mSPRT with τ=1\tau = 1 rejected in 2.55% of the streams, while the z-test at level 0.05 repeated after every observation rejected at some time in 49.35% of them.

Correctness

The proofs are in full below; this is a summary.

  1. Closed form. With u=θ−θ0u = \theta - \theta_0, the product of normal likelihood ratios is exp⁡(uSn/σ2−nu2/(2σ2))\exp(uS_n/\sigma^2 - nu^2/(2\sigma^2)). Integrating it against the N(0,τ2)N(0, \tau^2) density of uu is a Gaussian integral and gives the formula of line L4.
  2. Test martingale. For each fixed θ\theta, the product Ln(θ)=∏i≤nfθ(Xi)/fθ0(Xi)L_n(\theta) = \prod_{i \le n} f_\theta(X_i)/f_{\theta_0}(X_i) is a nonnegative martingale with mean 1 under θ0\theta_0. By Tonelli's theorem, Eθ0[Λn∣Fn−1]=∫Eθ0[Ln(θ)∣Fn−1] π(dθ)=Λn−1E_{\theta_0}[\Lambda_n \mid \mathcal F_{n-1}] = \int E_{\theta_0}[L_n(\theta) \mid \mathcal F_{n-1}]\,\pi(d\theta) = \Lambda_{n-1}, so Λ\Lambda is a test martingale.
  3. Level at every stopping time. The test rejects at or before TT only if Λn≥1/α\Lambda_n \ge 1/\alpha for some nn. By Ville's inequality this has probability at most α\alpha under θ0\theta_0, whatever TT is, including T=∞T = \infty.
  4. Always valid p-values. For u∈(0,1]u \in (0, 1], {pT≤u}⊆{∃n:Λn≥1/u}\{p_T \le u\} \subseteq \{\exists n: \Lambda_n \ge 1/u\}, which has probability at most uu by Ville's inequality. So pTp_T is a valid p-value for every stopping time TT.
  5. Power one. If θ≠θ0\theta \ne \theta_0, then Sn/n→θ−θ0S_n/n \to \theta - \theta_0 almost surely, the exponent in line L4 grows like n(θ−θ0)2/(2σ2)n(\theta - \theta_0)^2/(2\sigma^2), and the prefactor shrinks only like n−1/2n^{-1/2}. So Λn→∞\Lambda_n \to \infty almost surely, and the test rejects in finite time with probability 1.
Proof: The mSPRT has level alpha at every stopping time and its p-values are always validfull

Notation is that of the page. X1,X2,…X_1, X_2, \ldots are i.i.d. with density fθf_\theta with respect to a measure ν\nu, Fn=σ(X1,…,Xn)\mathcal F_n = \sigma(X_1, \ldots, X_n) with F0\mathcal F_0 trivial, and π\pi is a probability measure on the parameters, fixed before the data. We assume that every fθf_\theta is positive wherever fθ0f_{\theta_0} is, and that (θ,x)↦fθ(x)(\theta, x) \mapsto f_\theta(x) is jointly measurable. Write

Ln(θ)=∏i=1nfθ(Xi)fθ0(Xi),Λn=∫Ln(θ) π(dθ),L0=Λ0=1.L_n(\theta) = \prod_{i=1}^n \frac{f_\theta(X_i)}{f_{\theta_0}(X_i)}, \qquad \Lambda_n = \int L_n(\theta)\,\pi(d\theta), \qquad L_0 = \Lambda_0 = 1.

All probabilities and expectations below are under Pθ0P_{\theta_0}, written PP and EE.

Lemma 1 (closed form for the normal model). If fθf_\theta is the N(θ,σ2)N(\theta, \sigma^2) density and π=N(θ0,τ2)\pi = N(\theta_0, \tau^2), then with Sn=∑i≤n(Xi−θ0)S_n = \sum_{i \le n}(X_i - \theta_0),

Λn=σ2σ2+nτ2 exp⁡(τ2Sn22σ2(σ2+nτ2)).\Lambda_n = \sqrt{\frac{\sigma^2}{\sigma^2 + n\tau^2}}\,\exp\left(\frac{\tau^2 S_n^2}{2\sigma^2(\sigma^2 + n\tau^2)}\right).

Proof. Let u=θ−θ0u = \theta - \theta_0. Expanding the squares in the normal densities,

log⁡Ln(θ)=∑i=1n(Xi−θ0)2−(Xi−θ0−u)22σ2=uSnσ2−nu22σ2.\log L_n(\theta) = \sum_{i=1}^n \frac{(X_i - \theta_0)^2 - (X_i - \theta_0 - u)^2}{2\sigma^2} = \frac{u S_n}{\sigma^2} - \frac{n u^2}{2\sigma^2}.

Let c=n/σ2+1/τ2=(σ2+nτ2)/(σ2τ2)c = n/\sigma^2 + 1/\tau^2 = (\sigma^2 + n\tau^2)/(\sigma^2\tau^2) and m=Sn/(σ2c)m = S_n/(\sigma^2 c). Then

Λn=∫12πτexp⁡(uSnσ2−cu22)du=12πτexp⁡(cm22)∫exp⁡(−c(u−m)22)du=1τcexp⁡(Sn22σ4c).\Lambda_n = \int \frac{1}{\sqrt{2\pi}\tau}\exp\left(\frac{u S_n}{\sigma^2} - \frac{c u^2}{2}\right)du = \frac{1}{\sqrt{2\pi}\tau}\exp\left(\frac{c m^2}{2}\right)\int \exp\left(-\frac{c(u - m)^2}{2}\right)du = \frac{1}{\tau\sqrt c}\exp\left(\frac{S_n^2}{2\sigma^4 c}\right).

Here τ2c=(σ2+nτ2)/σ2\tau^2 c = (\sigma^2 + n\tau^2)/\sigma^2, and Sn2/(2σ4c)=τ2Sn2/(2σ2(σ2+nτ2))S_n^2/(2\sigma^4 c) = \tau^2 S_n^2/(2\sigma^2(\sigma^2 + n\tau^2)). □\square

Lemma 2 (test martingale). (Λn)n≥0(\Lambda_n)_{n \ge 0} is a nonnegative martingale under PP with Λ0=1\Lambda_0 = 1.

Proof. Λn≥0\Lambda_n \ge 0 since it is an integral of a nonnegative function, and it is Fn\mathcal F_n-measurable by the joint measurability. For each θ\theta and n≥1n \ge 1, XnX_n is independent of Fn−1\mathcal F_{n-1} and

E[fθ(Xn)fθ0(Xn)]=∫{fθ0>0}fθ dν≤1,E\left[\frac{f_\theta(X_n)}{f_{\theta_0}(X_n)}\right] = \int_{\{f_{\theta_0} > 0\}} f_\theta\,d\nu \le 1,

with equality because fθf_\theta is positive only where fθ0f_{\theta_0} is. Hence E[Ln(θ)∣Fn−1]=Ln−1(θ)E[L_n(\theta) \mid \mathcal F_{n-1}] = L_{n-1}(\theta). For a nonnegative jointly measurable integrand, Tonelli's theorem lets us exchange the conditional expectation and the integral over π\pi: for every bounded nonnegative Fn−1\mathcal F_{n-1}-measurable WW,

E[WΛn]=∫E[WLn(θ)] π(dθ)=∫E[WLn−1(θ)] π(dθ)=E[WΛn−1].E[W\Lambda_n] = \int E[W L_n(\theta)]\,\pi(d\theta) = \int E[W L_{n-1}(\theta)]\,\pi(d\theta) = E[W\Lambda_{n-1}].

With W=1W = 1 and induction, E[Λn]=1E[\Lambda_n] = 1, so Λn\Lambda_n is integrable, and the identity for all such WW is the statement E[Λn∣Fn−1]=Λn−1E[\Lambda_n \mid \mathcal F_{n-1}] = \Lambda_{n-1}. □\square

Theorem 1 (level at every stopping time). Let TT be any stopping time with respect to (Fn)(\mathcal F_n), possibly infinite. The probability that the mSPRT rejects H0H_0 at some n≤Tn \le T is at most α\alpha.

Proof. The test rejects at some n≤Tn \le T only if Λn≥1/α\Lambda_n \ge 1/\alpha for some n≥1n \ge 1. By Lemma 2 and Ville's inequality applied to the nonnegative martingale Λ\Lambda,

P(∃n≥1:Λn≥1/α)≤α E[Λ0]=α.□P(\exists n \ge 1: \Lambda_n \ge 1/\alpha) \le \alpha\,E[\Lambda_0] = \alpha. \qquad \square

Theorem 2 (always valid p-values). Let pn=min⁡(1,1/max⁡1≤k≤nΛk)p_n = \min(1, 1/\max_{1 \le k \le n}\Lambda_k) for n≥1n \ge 1, the value kept by line L5, and p∞=lim⁡npnp_\infty = \lim_n p_n, which exists because pnp_n never increases. For every stopping time TT, possibly infinite, and every u∈[0,1]u \in [0, 1],

P(pT≤u)≤u.P(p_T \le u) \le u.

Proof. For u=1u = 1 there is nothing to prove, and for u=0u = 0 the event {pT=0}\{p_T = 0\} is contained in {sup⁡nΛn=∞}\{\sup_n \Lambda_n = \infty\}, which has probability at most ε\varepsilon for every ε>0\varepsilon > 0 by Ville's inequality at level 1/ε1/\varepsilon. Let 0<u<10 < u < 1. If T<∞T < \infty and pT≤up_T \le u, then max⁡k≤TΛk≥1/u\max_{k \le T}\Lambda_k \ge 1/u. If T=∞T = \infty and p∞≤up_\infty \le u, then sup⁡kΛk≥1/u\sup_k \Lambda_k \ge 1/u. In both cases sup⁡kΛk≥1/u\sup_k \Lambda_k \ge 1/u, so by Ville's inequality the probability is at most uu. □\square

Lemma 3 (the procedure). After iteration nn of the loop of line L2, S=SnS = S_n, Λ=Λn\Lambda = \Lambda_n and p=pnp = p_n; the procedure rejects exactly at N=inf⁡{n:Λn≥1/α}N = \inf\{n : \Lambda_n \ge 1/\alpha\} if that is reached before the stream ends.

Proof. By induction on nn. Line L1 sets S=0S = 0, n=0n = 0 and p=1p = 1. Line L3 adds Xn−θ0X_n - \theta_0 to SS, line L4 evaluates the formula of Lemma 1, and line L5 sets p=min⁡(pn−1,1/Λn)p = \min(p_{n-1}, 1/\Lambda_n), which is pnp_n because p0=1p_0 = 1 makes the outer min⁡\min with 1 automatic. Line L6 returns at the first nn with Λn≥1/α\Lambda_n \ge 1/\alpha. □\square

Theorem 3 (power one, normal model). If the data are N(θ,σ2)N(\theta, \sigma^2) with θ≠θ0\theta \ne \theta_0, then Λn→∞\Lambda_n \to \infty almost surely, so the mSPRT rejects at a finite time with probability 1.

Proof. Let δ=θ−θ0\delta = \theta - \theta_0. By the strong law of large numbers Sn/n→δS_n/n \to \delta almost surely. Then

log⁡Λn=τ2Sn22σ2(σ2+nτ2)−12log⁡(1+nτ2σ2)=n(τ2(Sn/n)22σ2(σ2/n+τ2)−log⁡(1+nτ2/σ2)2n),\log\Lambda_n = \frac{\tau^2 S_n^2}{2\sigma^2(\sigma^2 + n\tau^2)} - \frac12\log\left(1 + \frac{n\tau^2}{\sigma^2}\right) = n\left(\frac{\tau^2 (S_n/n)^2}{2\sigma^2(\sigma^2/n + \tau^2)} - \frac{\log(1 + n\tau^2/\sigma^2)}{2n}\right),

and the bracket tends to δ2/(2σ2)>0\delta^2/(2\sigma^2) > 0. So log⁡Λn→∞\log\Lambda_n \to \infty almost surely. □\square

Theorems 1 and 2 with Lemma 3 give the guarantees of the page: the procedure has type I error at most α\alpha whenever and however the analyst stops it, and the p-value it reports at that time is valid. ■\blacksquare

Complexity

Each observation costs one update of SS, one exponential and one square root, so the time is Θ(n)\Theta(n) for the nn observations read and the extra space is Θ(1)\Theta(1). Under an alternative with effect δ=θ−θ0\delta = \theta - \theta_0, setting Sn≈nδS_n \approx n\delta in line L4 shows that the test rejects at about the nn where

nδ22σ2≈log⁡1α+12log⁡nτ2σ2,\frac{n\delta^2}{2\sigma^2} \approx \log\frac1\alpha + \frac12\log\frac{n\tau^2}{\sigma^2},

so the expected sample size grows like 2σ2log⁡(1/α)/δ22\sigma^2\log(1/\alpha)/\delta^2 plus a term of order log⁡(1/δ)/δ2\log(1/\delta)/\delta^2. A one-sided SPRT that knows δ\delta needs about 2σ2log⁡(1/α)/δ22\sigma^2\log(1/\alpha)/\delta^2; the extra logarithm is the cost of not knowing δ\delta.

Properties

  • Anytime valid. The type I error bound holds for continuous monitoring, for stopping when the data look good, and for never stopping.
  • One threshold. The test never accepts H0H_0. A study that must end at a fixed horizon reports "no rejection" and the p-value at that point.
  • Monotone p-values. pnp_n never increases, so a result that was significant stays significant.
  • Conservative. Ville's inequality has slack because the mixture jumps over 1/α1/\alpha, and because a stream that stops early has no chance to cross later. The realized level is below α\alpha, 2.55% in the simulation above.
  • Inverts to a confidence sequence. The set of θ0\theta_0 that the mSPRT has not rejected by time nn is the normal mixture confidence sequence.

Variants and improvements

  • Other mixing distributions. Any π\pi fixed before the data works. A normal π\pi gives the closed form above; a one-sided mixture on θ>θ0\theta > \theta_0 gives a one-sided test with more power on that side. The mixing scale τ\tau chooses the effect sizes at which the test is fastest; Johari et al. (2022) discuss how to choose it from the effect sizes seen in earlier experiments.
  • Bernoulli data. For coin flips with null p0p_0 and a Beta(a,b)\mathrm{Beta}(a, b) mixture, the ratio is B(a+h,b+k)/(B(a,b) p0h(1−p0)k)B(a + h, b + k)/(B(a, b)\,p_0^h(1 - p_0)^k) after hh heads and kk tails. It is a Bayes factor and a test martingale for the same reason.
  • Two-sample A/B tests. With large samples, the difference of the arm means is close to normal with known variance, and the normal mSPRT is applied to it; this is the setting of Johari et al.
  • Multiple tests. Always valid p-values can be fed into Bonferroni or Benjamini-Hochberg procedures for many metrics at once; the multiple comparisons problem remains.
  • E-processes. For composite nulls, an infimum of test martingales over the null gives an e-process, which still gives anytime-valid tests (see test martingale).
  • Group sequential designs. When the number of looks is small and fixed in advance, a group sequential design with alpha spending gives more power than the mSPRT.

When to use it

Use the mSPRT when analysts will look at the results continuously, the stopping rule is not fixed, and the null is a point such as "no difference between the arms". It fits online A/B tests, monitoring dashboards and adaptive data collection. When the looks are few and planned, a group sequential design has more power. When there are only two simple hypotheses, the SPRT is faster.

Pitfalls

  • Choosing the mixture after seeing the data. The guarantee needs π\pi fixed in advance. Tuning τ\tau on the same data voids it.
  • Unknown variance. The closed form assumes σ\sigma known. Plugging in an estimate is an approximation that is accurate only for large nn.
  • Dependent data. Daily or weekly cycles in traffic break the i.i.d. assumption, and with it the martingale property.
  • Reading pnp_n as a fixed-sample p-value. It is larger than the fixed-sample p-value at the same nn, as the example shows; that is the price of validity at all times.
  • Effect estimates at the stopping time. The sample mean when the test stops is biased away from zero. Report a confidence sequence instead.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

msprt_core.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mixture-sequential-probability-ratio-test/. The authors are listed in prov/7K0XX7.jsonl.
"""The mixture sequential probability ratio test (mSPRT) for a normal mean.

Data x_1, x_2, ... are i.i.d. N(theta, sigma^2) with sigma known. H0 is
theta = theta0. The likelihood ratio of N(theta, sigma^2) to N(theta0,
sigma^2) is mixed over theta ~ N(theta0, tau^2), which gives the closed form

    Lambda_n = sqrt(sigma^2 / (sigma^2 + n tau^2))
               * exp(tau^2 S_n^2 / (2 sigma^2 (sigma^2 + n tau^2))),

with S_n = sum (x_i - theta0). Lambda_n is a nonnegative martingale with mean 1
under H0, so rejecting at the first n with Lambda_n >= 1/alpha has level alpha
at every stopping time (Ville's inequality). The always valid p-value is
p_n = min(1, 1 / max_(k <= n) Lambda_k). Cost O(1) time and memory per item.
"""

import math
from collections.abc import Iterable
from fractions import Fraction


def msprt_ratio(n: int, s: float, sigma: float, tau: float) -> float:
    """Lambda_n from n and the centred sum s = sum (x_i - theta0)."""
    v = sigma * sigma + n * tau * tau
    return math.sqrt(sigma * sigma / v) * math.exp(tau * tau * s * s / (2.0 * sigma * sigma * v))


def msprt(stream: Iterable[float], theta0: float, sigma: float, tau: float,
          alpha: float) -> tuple[bool, int, float]:
    """Run the normal mSPRT. Returns (rejected, n, always valid p-value at stop).

    Precondition: sigma > 0, tau > 0, 0 < alpha < 1. The test stops at the
    first n with Lambda_n >= 1/alpha, or at the end of the stream.
    """
    if sigma <= 0 or tau <= 0 or not 0.0 < alpha < 1.0:
        raise ValueError("need sigma > 0, tau > 0, 0 < alpha < 1")
    s = 0.0  # @line L1
    n = 0  # @line L1
    p = 1.0  # @line L1
    for x in stream:  # @line L2
        n += 1  # @line L3
        s += x - theta0  # @line L3
        lam = msprt_ratio(n, s, sigma, tau)  # @line L4
        p = min(p, 1.0 / lam)  # @line L5
        if lam >= 1.0 / alpha:  # @line L6
            return True, n, p  # @line L6
    return False, n, p  # @line L7


def always_valid_p_values(xs: Iterable[float], theta0: float, sigma: float, tau: float) -> list[float]:
    """The sequence p_1, p_2, ... with p_n = min(1, 1 / max_(k <= n) Lambda_k)."""
    out = []
    s = 0.0
    p = 1.0
    for n, x in enumerate(xs, 1):
        s += x - theta0
        p = min(p, 1.0 / msprt_ratio(n, s, sigma, tau))
        out.append(p)
    return out


def _beta_fn(a: int, b: int) -> Fraction:
    return Fraction(math.factorial(a - 1) * math.factorial(b - 1), math.factorial(a + b - 1))


def beta_bernoulli_ratio(heads: int, tails: int, a: int, b: int, p0: Fraction) -> Fraction:
    """Exact mixture ratio for coin flips: Beta(a, b) mixture over p against the point p0.

    Lambda = B(a + heads, b + tails) / B(a, b) / (p0^heads (1 - p0)^tails).
    Precondition: a, b positive integers, 0 < p0 < 1.
    """
    return _beta_fn(a + heads, b + tails) / _beta_fn(a, b) / (p0 ** heads * (1 - p0) ** tails)
mixture_sequential_probability_ratio_test.py 8 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mixture-sequential-probability-ratio-test/. The authors are listed in prov/7K0XX7.jsonl.
"""Entry point named after the slug. The code lives in msprt_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""

from msprt_core import always_valid_p_values, beta_bernoulli_ratio, msprt, msprt_ratio

__all__ = ["always_valid_p_values", "beta_bernoulli_ratio", "msprt", "msprt_ratio"]
test_mixture_sequential_probability_ratio_test.py 140 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mixture-sequential-probability-ratio-test/. The authors are listed in prov/7K0XX7.jsonl.
import itertools
import math
import random
from fractions import Fraction

import pytest

from mixture_sequential_probability_ratio_test import (
    always_valid_p_values,
    beta_bernoulli_ratio,
    msprt,
    msprt_ratio,
)

EXAMPLE = [0.8, 1.4, -0.2, 1.1, 0.9, 1.6, 0.3, 1.2]


def mixture_by_quadrature(xs: list[float], theta0: float, sigma: float, tau: float, m: int = 4000) -> float:
    """Integral over theta of prod f_theta(x_i) / f_theta0(x_i) times the N(theta0, tau^2) density."""
    lo, hi = theta0 - 12 * tau, theta0 + 12 * tau
    h = (hi - lo) / m
    acc = 0.0
    for i in range(m + 1):
        t = lo + i * h
        w = 1.0 if i in (0, m) else (4.0 if i % 2 else 2.0)
        log_lr = sum(((x - theta0) ** 2 - (x - t) ** 2) / (2 * sigma * sigma) for x in xs)
        prior = math.exp(-0.5 * ((t - theta0) / tau) ** 2) / (tau * math.sqrt(2 * math.pi))
        acc += w * math.exp(log_lr) * prior
    return acc * h / 3.0


def test_worked_example():
    p = always_valid_p_values(EXAMPLE, 0.0, 1.0, 1.0)
    want = [1.0, 0.7731, 0.7731, 0.7731, 0.6457, 0.2817, 0.2817, 0.1823]
    assert all(abs(a - b) < 1e-4 for a, b in zip(p, want))
    assert msprt(EXAMPLE, 0.0, 1.0, 1.0, 0.05) == (False, 8, p[-1])
    assert abs(msprt_ratio(6, 5.6, 1.0, 1.0) - 3.550) < 1e-3


def test_p_values_never_increase_and_reject_matches():
    rng = random.Random(3)
    xs = [rng.gauss(0.6, 1.0) for _ in range(200)]
    p = always_valid_p_values(xs, 0.0, 1.0, 0.5)
    assert all(a >= b for a, b in zip(p, p[1:]))
    rejected, n, pn = msprt(xs, 0.0, 1.0, 0.5, 0.05)
    first = next(i for i, v in enumerate(p, 1) if v <= 0.05)
    assert rejected and n == first and pn == p[n - 1]


def test_closed_form_matches_quadrature():
    rng = random.Random(8)
    for _ in range(20):
        sigma = rng.uniform(0.5, 2.0)
        tau = rng.uniform(0.2, 2.0)
        theta0 = rng.uniform(-1.0, 1.0)
        xs = [rng.gauss(theta0 + rng.uniform(-1, 1), sigma) for _ in range(rng.randint(1, 12))]
        s = sum(x - theta0 for x in xs)
        want = mixture_by_quadrature(xs, theta0, sigma, tau)
        assert abs(msprt_ratio(len(xs), s, sigma, tau) - want) < 1e-8 * max(1.0, want)


def test_beta_bernoulli_martingale_mean_one_exact():
    for a, b in ((1, 1), (2, 3), (5, 1)):
        for p0 in (Fraction(1, 2), Fraction(1, 3), Fraction(7, 10)):
            for n in range(0, 11):
                mean = sum(p0 ** sum(s) * (1 - p0) ** (n - sum(s)) * beta_bernoulli_ratio(sum(s), n - sum(s), a, b, p0)
                           for s in itertools.product((0, 1), repeat=n))
                assert mean == 1


def test_beta_bernoulli_stopped_mean_at_most_one_exact():
    # Stop when Lambda >= 1/alpha or after 12 flips: E0[Lambda_T] = 1 exactly for a bounded stopping time.
    p0, alpha = Fraction(1, 2), Fraction(1, 10)
    alive = {(0, 0): Fraction(1)}
    stopped = Fraction(0)
    reject = Fraction(0)
    for n in range(1, 13):
        nxt: dict[tuple[int, int], Fraction] = {}
        for (h, t), m in alive.items():
            for h2, t2, q in ((h + 1, t, p0), (h, t + 1, 1 - p0)):
                lam = beta_bernoulli_ratio(h2, t2, 1, 1, p0)
                if lam >= 1 / alpha or n == 12:
                    stopped += m * q * lam
                    reject += m * q * (lam >= 1 / alpha)
                else:
                    nxt[(h2, t2)] = nxt.get((h2, t2), Fraction(0)) + m * q
        alive = nxt
    assert stopped == 1
    assert reject <= alpha


def test_optional_stopping_size_against_naive_z_test():
    rng = random.Random(5)
    reps, horizon, alpha = 2000, 500, 0.05
    msprt_rej = naive_rej = 0
    for _ in range(reps):
        s = 0.0
        hit_m = hit_z = False
        for n in range(1, horizon + 1):
            s += rng.gauss(0.0, 1.0)
            hit_m = hit_m or msprt_ratio(n, s, 1.0, 1.0) >= 1 / alpha
            hit_z = hit_z or abs(s) / math.sqrt(n) >= 1.959964
            if hit_m and hit_z:
                break
        msprt_rej += hit_m
        naive_rej += hit_z
    se = math.sqrt(alpha * (1 - alpha) / reps)
    assert msprt_rej / reps < alpha
    assert naive_rej / reps > alpha + 10 * se


def test_power_one():
    rng = random.Random(12)
    for _ in range(50):
        xs = (rng.gauss(0.3, 1.0) for _ in range(5000))
        assert msprt(xs, 0.0, 1.0, 1.0, 0.05)[0]


def test_random_streams_against_direct_formula():
    rng = random.Random(77)
    for _ in range(500):
        sigma, tau = rng.uniform(0.3, 3), rng.uniform(0.1, 3)
        theta0 = rng.uniform(-2, 2)
        xs = [rng.gauss(theta0 + rng.uniform(-1, 1), sigma) for _ in range(rng.randint(1, 15))]
        p = 1.0
        for n in range(1, len(xs) + 1):
            mean = sum(xs[:n]) / n
            v = sigma ** 2 + n * tau ** 2
            lam = math.sqrt(sigma ** 2 / v) * math.exp(n * n * tau ** 2 * (mean - theta0) ** 2 / (2 * sigma ** 2 * v))
            p = min(p, 1 / lam)
        assert abs(always_valid_p_values(xs, theta0, sigma, tau)[-1] - p) < 1e-9 * max(1.0, p)


def test_bad_input():
    with pytest.raises(ValueError):
        msprt([1.0], 0.0, 0.0, 1.0, 0.05)
    with pytest.raises(ValueError):
        msprt([1.0], 0.0, 1.0, 1.0, 1.5)

History

Robbins (1970) introduced the method of mixtures: average the likelihood ratio over a distribution of alternatives and apply the maximal inequality for nonnegative martingales to bound the probability of ever crossing a boundary. He used it to build tests of power one and confidence sequences. Johari, Koomen, Pekelis and Walsh (2017, 2022) named the test the mSPRT, defined always valid p-values and confidence intervals, and deployed them in a commercial A/B testing platform. Ramdas, Grünwald, Vovk and Shafer (2023) place it within the theory of test martingales and e-values.

References

  1. Herbert Robbins, Statistical methods related to the law of the iterated logarithm, Annals of Mathematical Statistics 41(5) (1970), pages 1397 to 1409, the method of mixtures, which mixes the likelihood ratio over a prior on the alternative and bounds the crossing probability of the mixture
  2. Ramesh Johari, Pete Koomen, Leonid Pekelis and David Walsh, Peeking at A/B tests, why it matters, and what to do about it, Proceedings of KDD 2017, pages 1517 to 1525, the mSPRT with a normal mixing distribution and the always valid p-values used in an online experimentation platform
  3. Ramesh Johari, Pete Koomen, Leonid Pekelis and David Walsh, Always valid inference, continuous monitoring of A/B tests, Operations Research 70(3) (2022), pages 1806 to 1821, the definition of always valid p-values and confidence intervals, their construction from the mSPRT, and the choice of the mixing distribution
  4. Aaditya Ramdas, Peter Grünwald, Vladimir Vovk and Glenn Shafer, Game-theoretic statistics and safe anytime-valid inference, Statistical Science 38(4) (2023), pages 576 to 601, mixture likelihood ratios as test martingales and the resulting anytime-valid p-values

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example