BA/B tests · experiment.sprt
Sequential probability ratio tests — Wald SPRT, MaxSPRT and conditional MaxSPRT
Can I decide after every observation (or event) while keeping the planned error rates?
Wald's sequential probability ratio test for Bernoulli, normal, Poisson and exponential data or grouped looks at an estimated difference — boundaries, the log-likelihood-ratio walk and its first crossing, the operating characteristic and expected sample size (Wald's approximations plus exact truncated Monte Carlo on the shared random stream) — and the maximized SPRT for event surveillance: the exact critical value of the continuous Poisson MaxSPRT and of the conditional MaxSPRT when the baseline rate comes from historical data.
A real result
Example “Bernoulli guide”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Wald SPRT (bernoulli): bounds log A = 2.773, log B = -1.558; reject H0 after 20 observation(s).
- Upper bound log A
- 2.773
- Lower bound log B
- −1.558
- Expected sample size under H₁
- 23.169
- Expected sample size under H₀
- 15.390
- log Λ at the last observation used
- 2.842
Plots
View data
| log Λ | Series | Observation |
|---|---|---|
| 2.773 | reject H₀ (log A) | 0 |
| 2.773 | reject H₀ (log A) | 16 |
| −1.558 | accept H₀ (log B) | 0 |
| −1.558 | accept H₀ (log B) | 16 |
| 0 | observed log Λ | 0 |
| 0.3365 | observed log Λ | 1 |
| 0.6729 | observed log Λ | 2 |
| 0.1621 | observed log Λ | 3 |
| 0.4986 | observed log Λ | 4 |
| 0.8351 | observed log Λ | 5 |
| 1.172 | observed log Λ | 6 |
| 0.6607 | observed log Λ | 7 |
| 0.9972 | observed log Λ | 8 |
| 1.334 | observed log Λ | 9 |
| 1.670 | observed log Λ | 10 |
| 2.007 | observed log Λ | 11 |
| 1.496 | observed log Λ | 12 |
| 1.832 | observed log Λ | 13 |
| 2.169 | observed log Λ | 14 |
| 2.505 | observed log Λ | 15 |
| 2.842 | observed log Λ | 16 |
View data
| P(reject H₀) | True parameter |
|---|---|
| 0.0002 | 0.3101 |
| 0.0003 | 0.3185 |
| 0.0004 | 0.3270 |
| 0.0006 | 0.3357 |
| 0.0007 | 0.3445 |
| 0.0010 | 0.3535 |
| 0.0013 | 0.3625 |
| 0.0017 | 0.3717 |
| 0.0022 | 0.3810 |
| 0.0028 | 0.3905 |
| 0.0037 | 0.4000 |
| 0.0049 | 0.4096 |
| 0.0064 | 0.4194 |
| 0.0083 | 0.4292 |
| 0.0109 | 0.4391 |
| 0.0141 | 0.4491 |
| 0.0183 | 0.4592 |
| 0.0237 | 0.4693 |
| 0.0305 | 0.4795 |
| 0.0392 | 0.4897 |
| 0.0500 | 0.5000 |
| 0.0635 | 0.5103 |
| 0.0800 | 0.5206 |
| 0.1002 | 0.5310 |
| 0.1243 | 0.5413 |
| 0.1528 | 0.5516 |
| 0.1859 | 0.5619 |
| 0.2235 | 0.5722 |
| 0.2654 | 0.5825 |
| 0.3111 | 0.5927 |
| 0.3598 | 0.6029 |
| 0.4105 | 0.6130 |
| 0.4621 | 0.6230 |
| 0.5134 | 0.6330 |
| 0.5635 | 0.6429 |
| 0.6113 | 0.6527 |
| 0.6562 | 0.6624 |
| 0.6977 | 0.6720 |
| 0.7355 | 0.6814 |
| 0.7696 | 0.6908 |
| 0.8000 | 0.7000 |
| 0.8269 | 0.7091 |
| 0.8505 | 0.7180 |
| 0.8712 | 0.7268 |
| 0.8892 | 0.7355 |
| 0.9048 | 0.7440 |
| 0.9182 | 0.7523 |
| 0.9299 | 0.7605 |
| 0.9399 | 0.7685 |
| 0.9485 | 0.7763 |
| 0.9558 | 0.7840 |
| 0.9622 | 0.7915 |
| 0.9676 | 0.7988 |
| 0.9723 | 0.8060 |
| 0.9763 | 0.8129 |
| 0.9797 | 0.8197 |
| 0.9826 | 0.8263 |
| 0.9851 | 0.8328 |
| 0.9873 | 0.8390 |
| 0.9891 | 0.8451 |
First 60 of 61 rows.
Operating characteristic (Wald's approximation)
| True parameter | P(accept H₀) | P(reject H₀) | Expected sample size |
|---|---|---|---|
| 0.3101 | 0.9998 | 0.0002 | 6.277 |
| 0.3270 | 0.9996 | 0.0004 | 6.659 |
| 0.3445 | 0.9993 | 0.0007 | 7.103 |
| 0.3625 | 0.9987 | 0.0013 | 7.624 |
| 0.3810 | 0.9978 | 0.0022 | 8.239 |
| 0.4000 | 0.9963 | 0.0037 | 8.970 |
| 0.4194 | 0.9936 | 0.0064 | 9.843 |
| 0.4391 | 0.9891 | 0.0109 | 10.890 |
| 0.4592 | 0.9817 | 0.0183 | 12.145 |
| 0.4795 | 0.9695 | 0.0305 | 13.639 |
| 0.5000 | 0.9500 | 0.0500 | 15.390 |
| 0.5206 | 0.9200 | 0.0800 | 17.381 |
| 0.5413 | 0.8757 | 0.1243 | 19.538 |
| 0.5619 | 0.8141 | 0.1859 | 21.708 |
| 0.5825 | 0.7346 | 0.2654 | 23.659 |
| 0.6029 | 0.6402 | 0.3598 | 25.135 |
| 0.6230 | 0.5379 | 0.4621 | 25.941 |
| 0.6429 | 0.4365 | 0.5635 | 26.021 |
| 0.6624 | 0.3438 | 0.6562 | 25.465 |
| 0.6814 | 0.2645 | 0.7355 | 24.450 |
| 0.7000 | 0.2000 | 0.8000 | 23.169 |
| 0.7180 | 0.1495 | 0.8505 | 21.785 |
| 0.7355 | 0.1108 | 0.8892 | 20.407 |
| 0.7523 | 0.0818 | 0.9182 | 19.102 |
| 0.7685 | 0.0601 | 0.9399 | 17.903 |
| 0.7840 | 0.0442 | 0.9558 | 16.822 |
| 0.7988 | 0.0324 | 0.9676 | 15.857 |
| 0.8129 | 0.0237 | 0.9763 | 15.002 |
| 0.8263 | 0.0174 | 0.9826 | 14.248 |
| 0.8390 | 0.0127 | 0.9873 | 13.583 |
| 0.8510 | 0.0093 | 0.9907 | 12.997 |
Simulated truncated SPRT (400 tests per hypothesis, horizon 300, seed 42)
| True hypothesis | Parameter | P(reject H₀) | ± MC SE | Mean sample size | Median | 90th percentile | Reached the horizon |
|---|---|---|---|---|---|---|---|
| H₀ | 0.5000 | 0.0300 | 0.0085 | 18.302 | 14 | 38 | 0.0% |
| H₁ | 0.7000 | 0.8550 | 0.0176 | 26.977 | 21 | 49.300 | 0.0% |
- The walk crossed a boundary at observation 16; the 4 later value(s) were not used.
- Wald's boundaries are approximate: the walk overshoots them, so the realized error rates are usually a little below α and β (the simulation shows the actual rates).
- Analyze the decision at the first crossing only; this is not a fixed-sample test repeated after every observation.
Wald SPRT (bernoulli): bounds log A = 2.773, log B = -1.558; reject H0 after 20 observation(s).
- Upper bound log A
- 2.773
- Lower bound log B
- −1.558
- Expected sample size under H₁
- 23.169
- Expected sample size under H₀
- 15.390
- log Λ at the last observation used
- 2.842
To keep this page light, the plots are shown once, under the R tab.
Operating characteristic (Wald's approximation)
| True parameter | P(accept H₀) | P(reject H₀) | Expected sample size |
|---|---|---|---|
| 0.3101 | 0.9998 | 0.0002 | 6.277 |
| 0.3270 | 0.9996 | 0.0004 | 6.659 |
| 0.3445 | 0.9993 | 0.0007 | 7.103 |
| 0.3625 | 0.9987 | 0.0013 | 7.624 |
| 0.3810 | 0.9978 | 0.0022 | 8.239 |
| 0.4000 | 0.9963 | 0.0037 | 8.970 |
| 0.4194 | 0.9936 | 0.0064 | 9.843 |
| 0.4391 | 0.9891 | 0.0109 | 10.890 |
| 0.4592 | 0.9817 | 0.0183 | 12.145 |
| 0.4795 | 0.9695 | 0.0305 | 13.639 |
| 0.5000 | 0.9500 | 0.0500 | 15.390 |
| 0.5206 | 0.9200 | 0.0800 | 17.381 |
| 0.5413 | 0.8757 | 0.1243 | 19.538 |
| 0.5619 | 0.8141 | 0.1859 | 21.708 |
| 0.5825 | 0.7346 | 0.2654 | 23.659 |
| 0.6029 | 0.6402 | 0.3598 | 25.135 |
| 0.6230 | 0.5379 | 0.4621 | 25.941 |
| 0.6429 | 0.4365 | 0.5635 | 26.021 |
| 0.6624 | 0.3438 | 0.6562 | 25.465 |
| 0.6814 | 0.2645 | 0.7355 | 24.450 |
| 0.7000 | 0.2000 | 0.8000 | 23.169 |
| 0.7180 | 0.1495 | 0.8505 | 21.785 |
| 0.7355 | 0.1108 | 0.8892 | 20.407 |
| 0.7523 | 0.0818 | 0.9182 | 19.102 |
| 0.7685 | 0.0601 | 0.9399 | 17.903 |
| 0.7840 | 0.0442 | 0.9558 | 16.822 |
| 0.7988 | 0.0324 | 0.9676 | 15.857 |
| 0.8129 | 0.0237 | 0.9763 | 15.002 |
| 0.8263 | 0.0174 | 0.9826 | 14.248 |
| 0.8390 | 0.0127 | 0.9873 | 13.583 |
| 0.8510 | 0.0093 | 0.9907 | 12.997 |
Simulated truncated SPRT (400 tests per hypothesis, horizon 300, seed 42)
| True hypothesis | Parameter | P(reject H₀) | ± MC SE | Mean sample size | Median | 90th percentile | Reached the horizon |
|---|---|---|---|---|---|---|---|
| H₀ | 0.5000 | 0.0300 | 0.0085 | 18.302 | 14 | 38 | 0.0% |
| H₁ | 0.7000 | 0.8550 | 0.0176 | 26.977 | 21 | 49.300 | 0.0% |
- The walk crossed a boundary at observation 16; the 4 later value(s) were not used.
- Wald's boundaries are approximate: the walk overshoots them, so the realized error rates are usually a little below α and β (the simulation shows the actual rates).
- Analyze the decision at the first crossing only; this is not a fixed-sample test repeated after every observation.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Bernoulli guideNo data needed
- Normal truncatedNo data needed
- Poisson countsNo data needed
- Exponential timesNo data needed
- Difference looksNo data needed
- Maxsprt guideNo data needed
- Maxsprt design onlyNo data needed
- Bmaxsprt design onlyNo data needed
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Multiple comparisons · Statistics Guide · Additional considerations
- A/B testing (hypothesis testing) · DS & ML Decision Guide · Optimize / decide
Choices you make
hypothesis
- Testdefault sprt
Wald's SPRT tests two fixed values; MaxSPRT watches for any increase; conditional MaxSPRT uses a historical baseline.
- Wald SPRT (simple H₀ vs simple H₁)(default) — Two fully specified hypotheses; decide after each observation with Wald's boundaries A = (1 − β)/α and B = β/(1 − α).
- MaxSPRT (Poisson surveillance, unknown elevation) — Event counts against an expected baseline; the alternative is any elevated risk, maximized at each look (Kulldorff et al. 2011).
- Binomial MaxSPRT (matched or self-controlled events) — Each event falls in the exposed or the unexposed group; signals when too many are exposed for their share of person-time.
- Conditional MaxSPRT (baseline from historical data) — Like MaxSPRT, but the baseline rate is estimated from a historical count, whose uncertainty widens the boundary (Li & Kulldorff 2010).
- Datadefault bernoulli
What each observation is: yes/no, a measurement, a count, a waiting time, or grouped A/B looks.
- Yes/no outcomes (Bernoulli p₀ vs p₁)(default) — Each observation is 0 or 1; H₀ says the success rate is p₀, H₁ says p₁.
- Measurements with known σ (μ₀ vs μ₁) — Each observation is normal with standard deviation σ; H₀ mean μ₀, H₁ mean μ₁.
- Counts per unit (Poisson λ₀ vs λ₁) — Each observation is a count; H₀ rate λ₀ per observation, H₁ rate λ₁.
- Waiting times (exponential rate r₀ vs r₁) — Each observation is a time to event; H₀ rate r₀, H₁ rate r₁ (mean 1/r).
- Grouped looks at a difference (A/B) — At each look an estimated difference d with standard error s; H₀ Δ = 0, H₁ Δ = δ (a normal SPRT on the estimate).
- p₀ (success rate under H₀)default 0.5
The success rate if nothing changed (the null).
- p₁ (success rate under H₁)default 0.7
The success rate you want to detect; the test is tuned to tell p₀ from p₁.
- μ₀ (mean under H₀)default 0
The mean if nothing changed (the null).
- μ₁ (mean under H₁)default 0.5
The mean you want to detect.
- σ (known standard deviation)default 1
Known standard deviation of one observation (from history); estimated σ needs a t-based test instead.
- λ₀ (rate under H₀)default 1
Expected count per observation under the null.
- λ₁ (rate under H₁)default 1.5
Expected count per observation you want to detect.
- r₀ (event rate under H₀)default 1
Event rate (1 / mean waiting time) under the null.
- r₁ (event rate under H₁)default 2
Event rate you want to detect.
- δ (difference under H₁)default 0.01
The effect the test is designed to detect, in the units of the observed differences.
- Significance level (α)default 0.05
Probability of rejecting H₀ when it is true (for MaxSPRT: over the whole surveillance).
- Power (1 − β)default 0.8
Probability of rejecting H₀ when H₁ is true; sets the lower boundary log B.
- Surveillance length (expected events under H₀, T)default 10
Surveillance ends when the expected count reaches T.
- Minimum events before a signal (M)default 1
No signal before this many events, to avoid alarms from one or two early cases.
- Surveillance length (events in all, N)default 50
Surveillance ends when this many events have happened, exposed and unexposed together.
- Unexposed per exposed person-time (z)default 1
1 for 1:1 matching; under H₀ each event is in the exposed group with probability 1/(1 + z).
- Relative risk to plan fordefault 2
The exact power and expected events are computed at this relative risk; it does not change the critical value.
- Historical events (c)default 20
Events in the historical comparison data that set the baseline rate.
- Stop surveillance at this many current events (K)default 20
Surveillance ends at this many events in the current data.
options
- Truncate after this many observationsdefault —
At the truncation point Wald's rule decides H₁ when log Λ ≥ 0, H₀ otherwise.
- Observations so far (in order)default
The walk stops at the first boundary crossing; later values are ignored.
- Observed differences at each lookdefault
Treatment − control estimate at each look, cumulative (the latest analysis of all data so far).
- Standard errors of those differencesdefault
Standard error of each look's difference.
- Cumulative events in all at each lookdefault
Total events, exposed and unexposed, up to each look.
- Cumulative exposed events at each lookdefault
Events in the exposed group up to each look, one per entry above.
- Cumulative events at each lookdefault
Total events observed up to each look (cumulative).
- Cumulative expected events under H₀ at each lookdefault
Events expected by each look if the baseline rate holds (cumulative).
- Historical exposure (V, person-time)default —
Needed to evaluate observed looks (current exposure is divided by V).
- Cumulative current events at each lookdefault
Total current events up to each look (cumulative).
- Cumulative current exposure at each look (P)default
Total current person-time up to each look, in the same units as V.
statistics
- Monte Carlo replicates for the exact OC and ASNdefault 2000
Truncated SPRTs simulated under H₀ and H₁ on the shared stream (0 = Wald's approximations only).
- Simulation horizon (observations)default 1000
Each simulated test stops at this many observations if no boundary was crossed (the truncation, when set, is used instead).
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Hypotheses fixed before monitoringNot checked from data: state why it holds
Boundaries are valid only for the H₀, H₁ (or surveillance length) and α chosen before the first look.
Observations independent given the parameterNot checked from data: state why it holds
Each observation (or event) adds an independent likelihood-ratio term; clustered or autocorrelated data break the error rates.
Only the first crossing countsNot checked from data: state why it holds
Analyze the decision at the first boundary crossing; continuing after a crossing and re-testing is not an SPRT.
What it reports
- variant
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- alpha_target
- Adds up the log-likelihood ratio of H₁ to H₀ after every observation and stops as soon as it crosses an upper or lower boundary.
- decision
- Adds up the log-likelihood ratio of H₁ to H₀ after every observation and stops as soon as it crosses an upper or lower boundary.
Per group, level or term: alpha_exact, asn_h0, asn_h1, cv, fixed_n, hist_events, k_max, llr_last, llr_stop, log_a, log_b, min_events, n_looks, n_observed, n_stop, n_total, power, power_target, rr_target, t_max, z
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-9). Python uses numpy, scipy, codesplash; R uses stats, codesplashr.
Default traps between the two languages
- Critical values come from Brent root finding (brentq ↔ uniroot, tol 1e-13) of the same exact recursions; the walk and Monte Carlo draws are identical (shared Wichmann–Hill stream, constants from the C library's log).
- Continuous Poisson MaxSPRT reproduces Sequential::CV.Poisson (e.g. 3.064248 for SampleSize = 10, M = 3, α = 0.05).
- Binomial MaxSPRT reports the smallest log-likelihood ratio that signals, with a signal at LLR ≥ CV. Sequential::CV.Binomial reports the largest that does not (3.13949 against 3.36911 for N = 25, z = 1), with a signal at LLR > CV: the same states signal, and the exact α and Performance.Binomial's power and event counts agree (tests/crosscheck/w1ex1_sequential.R).
- Conditional MaxSPRT assumes the historical data were collected until c events (fixed-count sampling, as the guide's pitfall warns): its α is exact under that design (Monte Carlo check 0.0496 ± 0.0003 at the guide example's CV 3.0530). Sequential::CV.CondPoisson(Inference = "exact", StopType = "Cases", K = 20, cc = 20, M = 2) returns 3.149, whose type I error is ≈ 0.046 under fixed-count sampling and ≈ 0.034 under fixed-exposure sampling. Test 291 is graded P2 against Sequential for this reason; tests/crosscheck/w3lb1_meta_lab.R rechecks both critical values by simulation.
The exact script CodeSplash ran for example “Bernoulli guide” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Sequential probability ratio tests — Wald SPRT, MaxSPRT and conditional MaxSPRT
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method experiment.sprt 1.1.0 · spec 804131c54c11a37c
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import codesplash as cs
from codesplash.experiment import sprt as sp # SPRT / MaxSPRT / conditional MaxSPRT (twin of R cs_exp_sprt_*)
# %% Inputs
variant = "sprt" # sprt | maxsprt | bmaxsprt | cmaxsprt
alpha = 0.05
seed = 42 # shared Wichmann–Hill stream: R simulates the same tests
warnings = []
tables, charts = [], []
values = {"variant": variant, "alpha_target": alpha}
if variant == "sprt":
# %% Wald SPRT
family = "bernoulli"
beta = 1.0 - 0.8
params = {
"p0": 0.5, "p1": 0.7, "mu0": 0, "mu1": 0.5,
"sigma": 1, "lam0": 1, "lam1": 1.5,
"rate0": 1, "rate1": 2, "delta": 0.01,
}
n_max = None
log_a, log_b = sp.wald_bounds(alpha, beta)
# Equivalent idiom (R): SPRT::SPRT() — or the cumulative sum of log f1/f0 against these bounds.
if family == "difference":
diffs = []
ses = []
w = sp.levels_walk(sp.difference_path(diffs, ses, params["delta"]), log_a, log_b)
n_obs = len(diffs)
unit = "look"
else:
obs = [1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1]
w = sp.walk(sp.increments(family, obs, params), log_a, log_b, n_max)
n_obs = len(obs)
unit = "observation"
if w["n_stop"] is not None and w["n_stop"] < n_obs:
warnings.append(f"The walk crossed a boundary at {unit} {w['n_stop']}; the {n_obs - w['n_stop']} later value(s) were not used.")
values.update({
"family": family, "power_target": 1.0 - beta, "log_a": log_a, "log_b": log_b, "bound_a": math.exp(log_a),
"bound_b": math.exp(log_b), "n_observed": n_obs, "n_stop": w["n_stop"], "llr_stop": w["llr_stop"],
"decision": w["decision"] if n_obs else "no data yet", "oc_h0": None, "oc_h1": None, "asn_h0": None,
"asn_h1": None, "fixed_n": None,
})
for i, v in enumerate(w["llr"]):
values[f"llr[{i + 1}]"] = v
if family != "difference":
# %% Operating characteristic and expected sample size (Wald's approximations)
ends = sp.oc_asn(family, params, log_a, log_b, [1.0, -1.0]) # h = 1 → θ₀, h = −1 → θ₁
h0 = next(r for r in ends if r["h"] == 1.0)
h1 = next(r for r in ends if r["h"] == -1.0)
values.update({"oc_h0": h0["oc"], "oc_h1": h1["oc"], "asn_h0": h0["asn"], "asn_h1": h1["asn"],
"fixed_n": sp.fixed_n(family, params, alpha, beta)})
curve = sp.oc_asn(family, params, log_a, log_b)
tables.append({
"key": "oc", "title": "Operating characteristic (Wald's approximation)",
"columns": [{"key": "theta", "label": "True parameter", "type": "number"},
{"key": "oc", "label": "P(accept H₀)", "type": "number"},
{"key": "power", "label": "P(reject H₀)", "type": "number"},
{"key": "asn", "label": "Expected sample size", "type": "number"}],
"rows": [{k: r[k] for k in ("theta", "oc", "power", "asn")} for r in curve[::2]],
})
charts.append(cs.chart("oc", "power-curve", "Probability of rejecting H₀",
{"x": cs.col("True parameter", [r["theta"] for r in curve]),
"power": cs.col("P(reject H₀)", [r["power"] for r in curve])},
controls={"target": 1.0 - beta}))
reps = int(400)
if reps > 0:
# %% Exact truncated OC and ASN by simulation
horizon = int(n_max) if n_max is not None else int(300)
t0, t1 = sp.theta_pair(family, params)
sims = [("H₀", t0, sp.simulate(family, params, t0, log_a, log_b, horizon, reps, seed)),
("H₁", t1, sp.simulate(family, params, t1, log_a, log_b, horizon, reps, seed + 1))]
for tag, (label, theta, r) in zip(("h0", "h1"), sims):
values[f"mc_reject_{tag}"] = r["reject"]
values[f"mc_asn_{tag}"] = r["asn"]
values[f"mc_truncated_{tag}"] = r["truncated"]
values["mc_reps"] = reps
tables.append({
"key": "mc", "title": f"Simulated truncated SPRT ({reps} tests per hypothesis, horizon {horizon}, seed {seed})",
"columns": [{"key": "hypothesis", "label": "True hypothesis", "type": "string"},
{"key": "theta", "label": "Parameter", "type": "number"},
{"key": "reject", "label": "P(reject H₀)", "type": "number"},
{"key": "reject_se", "label": "± MC SE", "type": "number"},
{"key": "asn", "label": "Mean sample size", "type": "number"},
{"key": "n_median", "label": "Median", "type": "number"},
{"key": "n_p90", "label": "90th percentile", "type": "number"},
{"key": "truncated", "label": "Reached the horizon", "type": "percent"}],
"rows": [{"hypothesis": lab, "theta": th, **{k: r[k] for k in ("reject", "reject_se", "asn", "n_median", "n_p90", "truncated")}} for lab, th, r in sims],
})
if any(r["truncated"] > 0.01 for _, _, r in sims):
warnings.append("More than 1% of simulated tests reached the horizon without a decision; raise the horizon or set a truncation rule.")
# %% Walk chart
xs = [0] + [i + 1 for i in range(len(w["llr"]))]
end = max(xs[-1], 1)
px = [0, end, 0, end] + xs
py = [log_a, log_a, log_b, log_b] + [0.0] + list(w["llr"])
ps = ["reject H₀ (log A)"] * 2 + ["accept H₀ (log B)"] * 2 + ["observed log Λ"] * len(xs)
charts.insert(0, cs.chart("walk", "sprt-path", "Log-likelihood ratio walk",
{"x": cs.col(unit.capitalize(), px), "llr": cs.col("log Λ", py), "series": cs.col("Series", ps)}))
summary = (f"Wald SPRT ({family}): bounds log A = {log_a:.3f}, log B = {log_b:.3f}; "
+ (f"{values['decision']} after {n_obs} {unit}(s)." if n_obs else "no observations yet."))
statistics = [
{"key": "log_a", "label": "Upper bound log A", "value": log_a},
{"key": "log_b", "label": "Lower bound log B", "value": log_b},
*([{"key": "asn_h1", "label": "Expected sample size under H₁", "value": values["asn_h1"]},
{"key": "asn_h0", "label": "Expected sample size under H₀", "value": values["asn_h0"]}] if values["asn_h1"] is not None else []),
*([{"key": "llr_stop", "label": "log Λ at the last observation used", "value": w["llr_stop"]}] if n_obs else []),
]
notes = [
"Wald's boundaries are approximate: the walk overshoots them, so the realized error rates are usually a little below α and β (the simulation shows the actual rates).",
"Analyze the decision at the first crossing only; this is not a fixed-sample test repeated after every observation.",
]
elif variant == "maxsprt":
# %% Poisson MaxSPRT (continuous surveillance)
t_max = 10
m_min = int(1)
# Equivalent idiom (R): Sequential::CV.Poisson(SampleSize = t_max, M = m_min, alpha = alpha)
cv = sp.maxsprt_cv(alpha, t_max, m_min)
thr = sp.maxsprt_thresholds(cv, t_max, m_min)
events = []
expected = []
if len(events) != len(expected):
raise ValueError("Give one expected count per observed event count.")
looks, decision, signal_at = [], "no data yet", None
for i, (c, mu) in enumerate(zip(events, expected)):
llr = sp.maxsprt_llr(float(c), float(mu))
if llr >= cv and c >= m_min:
dec, signal_at = "signal: reject H0", i + 1
elif mu >= t_max:
dec = "end: no signal"
else:
dec = "continue"
looks.append({"look": i + 1, "events": c, "expected": mu, "llr": llr, "decision": dec})
decision = dec
if signal_at or mu >= t_max:
break
if len(looks) < len(events):
warnings.append(f"Surveillance ended at look {len(looks)}; later looks were not used.")
values.update({"cv": cv, "alpha_exact": sp.maxsprt_alpha(cv, t_max, m_min), "t_max": t_max, "min_events": m_min,
"n_thresholds": len(thr), "n_looks": len(looks), "llr_last": looks[-1]["llr"] if looks else None,
"decision": decision, "signal_look": signal_at})
for r in looks:
values[f"llr[{r['look']}]"] = r["llr"]
tables.append({
"key": "thresholds", "title": "Signal thresholds: the k-th event signals if it arrives before this expected count",
"columns": [{"key": "k", "label": "Events", "type": "integer"}, {"key": "a", "label": "Latest expected count", "type": "number"}],
"rows": [{"k": k, "a": a} for a, k in thr],
})
if looks:
tables.append({"key": "looks", "title": "Observed looks", "rows": looks,
"columns": [{"key": "look", "label": "Look", "type": "integer"}, {"key": "events", "label": "Events", "type": "integer"},
{"key": "expected", "label": "Expected under H₀", "type": "number"}, {"key": "llr", "label": "log LR", "type": "number"},
{"key": "decision", "label": "Decision", "type": "string"}]})
px = [0.0, t_max] + [0.0] + [r["expected"] for r in looks]
py = [cv, cv] + [0.0] + [r["llr"] for r in looks]
ps = ["critical value"] * 2 + ["observed log LR"] * (len(looks) + 1)
charts.append(cs.chart("walk", "sprt-path", "Maximized log-likelihood ratio",
{"x": cs.col("Expected events under H₀", px), "llr": cs.col("log LR", py), "series": cs.col("Series", ps)}))
summary = f"Poisson MaxSPRT to T = {t_max:g} expected events (M = {m_min}): critical value {cv:.4f}" + (f"; {decision}." if looks else ".")
statistics = [{"key": "cv", "label": "Critical value", "value": cv}, {"key": "alpha_exact", "label": "Exact type I error", "value": values["alpha_exact"]}]
notes = ["Signal at the first look whose log-likelihood ratio reaches the critical value; the critical value controls α over continuous monitoring to T, not at a single look."]
elif variant == "bmaxsprt":
# %% Binomial MaxSPRT (matched or self-controlled events)
n_total = int(50)
z = 1
m_min = int(1)
rr = 2
# Equivalent idiom (R): Sequential::CV.Binomial(N = n_total, alpha = alpha, M = m_min, z = z); Performance.Binomial(...) for power
cv = sp.bmaxsprt_cv(alpha, n_total, m_min, z)
null_run = sp.bmaxsprt_run(cv, n_total, m_min, z)
alt_run = sp.bmaxsprt_run(cv, n_total, m_min, z, rr)
thr = sp.bmaxsprt_thresholds(cv, n_total, m_min, z)
totals = []
exposed = []
if len(totals) != len(exposed):
raise ValueError("Give one exposed-event count per total-event count.")
looks, decision, signal_at = [], "no data yet", None
for i, (n, c) in enumerate(zip(totals, exposed)):
if c > n or (i and (n < totals[i - 1] or c < exposed[i - 1])):
raise ValueError("Event counts are cumulative: they never fall, and exposed events cannot exceed the total.")
llr = sp.bmaxsprt_llr(float(c), float(n), z)
if llr >= cv - 1e-9 and c >= m_min:
dec, signal_at = "signal: reject H0", i + 1
elif n >= n_total:
dec = "end: no signal"
else:
dec = "continue"
looks.append({"look": i + 1, "total": n, "exposed": c, "share": c / n if n > 0 else None, "llr": llr, "decision": dec})
decision = dec
if signal_at or n >= n_total:
break
if len(looks) < len(totals):
warnings.append(f"Surveillance ended at look {len(looks)}; later looks were not used.")
values.update({"cv": cv, "alpha_exact": null_run["reject"], "n_total": n_total, "z": z, "null_share": 1.0 / (1.0 + z), "min_events": m_min,
"rr_target": rr, "power": alt_run["reject"], "events_if_signal": alt_run["events_if_signal"], "events_expected": alt_run["events"],
"events_expected_h0": null_run["events"], "n_looks": len(looks), "llr_last": looks[-1]["llr"] if looks else None,
"decision": decision, "signal_look": signal_at})
for r in looks:
values[f"llr[{r['look']}]"] = r["llr"]
step = max(1, math.ceil(len(thr) / 200))
tables.append({
"key": "thresholds", "title": "Signal thresholds: after n events in all, this many in the exposed group signal",
"columns": [{"key": "n", "label": "Events in all", "type": "integer"}, {"key": "c", "label": "Exposed events", "type": "integer"}],
"rows": [{"n": n, "c": c} for n, c in thr[::step]],
})
tables.append({
"key": "power", "title": "Exact operating characteristics",
"columns": [{"key": "scenario", "label": "If the true relative risk is", "type": "string"}, {"key": "reject", "label": "P(signal)", "type": "number"},
{"key": "at_signal", "label": "Mean events at a signal", "type": "number"}, {"key": "events", "label": "Mean events at stopping", "type": "number"}],
"rows": [{"scenario": "1 (H₀)", "reject": null_run["reject"], "at_signal": null_run["events_if_signal"], "events": null_run["events"]},
{"scenario": f"{rr:g}", "reject": alt_run["reject"], "at_signal": alt_run["events_if_signal"], "events": alt_run["events"]}],
})
if looks:
tables.append({"key": "looks", "title": "Observed looks", "rows": looks,
"columns": [{"key": "look", "label": "Look", "type": "integer"}, {"key": "total", "label": "Events in all", "type": "integer"},
{"key": "exposed", "label": "Exposed events", "type": "integer"}, {"key": "share", "label": "Exposed share", "type": "number"},
{"key": "llr", "label": "log LR", "type": "number"}, {"key": "decision", "label": "Decision", "type": "string"}]})
px = [0.0, float(n_total)] + [0.0] + [float(r["total"]) for r in looks]
py = [cv, cv] + [0.0] + [r["llr"] for r in looks]
ps = ["critical value"] * 2 + ["observed log LR"] * (len(looks) + 1)
charts.append(cs.chart("walk", "sprt-path", "Maximized log-likelihood ratio (binomial)",
{"x": cs.col("Events in all", px), "llr": cs.col("log LR", py), "series": cs.col("Series", ps)}))
summary = f"Binomial MaxSPRT to N = {n_total} events (z = {z:g}, M = {m_min}): critical value {cv:.4f}, exact α {null_run['reject']:.4f}" + (f"; {decision}." if looks else ".")
statistics = [{"key": "cv", "label": "Critical value", "value": cv}, {"key": "alpha_exact", "label": "Exact type I error", "value": null_run["reject"]},
{"key": "power", "label": f"Power at relative risk {rr:g}", "value": alt_run["reject"]}]
notes = ["With discrete events only some error rates are attainable: the critical value is the smallest log-likelihood ratio that keeps the exact α at or below the target, so the exact α can be lower than you asked for.",
"Under H₀ each event falls in the exposed group with probability 1/(1 + z), where z is the unexposed person-time per exposed person-time."]
else:
# %% Conditional Poisson MaxSPRT
c_hist = float(20)
k_max = int(20)
m_min = int(1)
v_hist = None
# Equivalent idiom (R): Sequential::CV.CondPoisson(Inference = "exact", StopType = "Cases", K = k_max, cc = c_hist, M = m_min, alpha = alpha)
cv = sp.cmaxsprt_cv(alpha, c_hist, k_max, m_min)
thr = sp.cmaxsprt_thresholds(cv, c_hist, k_max, m_min)
cases = []
exposure = []
if len(cases) != len(exposure):
raise ValueError("Give one exposure per observed case count.")
if cases and v_hist is None:
raise ValueError("Set the historical exposure V to evaluate observed looks.")
looks, decision, signal_at = [], "no data yet", None
for i, (x, pt) in enumerate(zip(cases, exposure)):
u = float(pt) / float(v_hist)
llr = sp.cmaxsprt_llr(c_hist, float(x), u)
if llr >= cv and x >= m_min:
dec, signal_at = "signal: reject H0", i + 1
elif x >= k_max:
dec = "end: no signal"
else:
dec = "continue"
looks.append({"look": i + 1, "cases": x, "exposure": pt, "ratio": u, "llr": llr, "decision": dec})
decision = dec
if signal_at or x >= k_max:
break
if len(looks) < len(cases):
warnings.append(f"Surveillance ended at look {len(looks)}; later looks were not used.")
values.update({"cv": cv, "alpha_exact": sp.cmaxsprt_alpha(cv, c_hist, k_max, m_min), "hist_events": int(c_hist),
"k_max": k_max, "min_events": m_min, "n_looks": len(looks), "llr_last": looks[-1]["llr"] if looks else None,
"decision": decision, "signal_look": signal_at})
for r in looks:
values[f"llr[{r['look']}]"] = r["llr"]
tables.append({
"key": "thresholds", "title": "Signal thresholds: the x-th current event signals if the exposure ratio P/V is at most",
"columns": [{"key": "x", "label": "Current events", "type": "integer"}, {"key": "u", "label": "Largest P / V", "type": "number"},
*([{"key": "p", "label": "Largest current exposure P", "type": "number"}] if v_hist is not None else [])],
"rows": [{"x": x, "u": u, **({"p": u * v_hist} if v_hist is not None else {})} for u, x in thr],
})
if looks:
tables.append({"key": "looks", "title": "Observed looks", "rows": looks,
"columns": [{"key": "look", "label": "Look", "type": "integer"}, {"key": "cases", "label": "Current events", "type": "integer"},
{"key": "exposure", "label": "Current exposure", "type": "number"}, {"key": "ratio", "label": "P / V", "type": "number"},
{"key": "llr", "label": "log LR", "type": "number"}, {"key": "decision", "label": "Decision", "type": "string"}]})
end = max([u for u, _ in thr] + [r["ratio"] for r in looks])
px = [0.0, end] + [0.0] + [r["ratio"] for r in looks]
py = [cv, cv] + [0.0] + [r["llr"] for r in looks]
ps = ["critical value"] * 2 + ["observed log LR"] * (len(looks) + 1)
charts.append(cs.chart("walk", "sprt-path", "Conditional maximized log-likelihood ratio",
{"x": cs.col("Current / historical exposure (P / V)", px), "llr": cs.col("log LR", py), "series": cs.col("Series", ps)}))
summary = f"Conditional MaxSPRT (c = {int(c_hist)}, K = {k_max}, M = {m_min}): critical value {cv:.4f}" + (f"; {decision}." if looks else ".")
statistics = [{"key": "cv", "label": "Critical value", "value": cv}, {"key": "alpha_exact", "label": "Exact type I error", "value": values["alpha_exact"]}]
notes = ["The historical data are taken as collected until c events (fixed-count sampling); the baseline's uncertainty is part of the critical value."]
# %% Result
cs.publish({
"method": "experiment.sprt",
"methodVersion": "1.1.0",
"title": {"sprt": "Sequential probability ratio test", "maxsprt": "MaxSPRT surveillance", "bmaxsprt": "Binomial MaxSPRT surveillance", "cmaxsprt": "Conditional MaxSPRT surveillance"}[variant],
"engine": cs.engine_info("scipy"),
"summary": summary,
"statistics": statistics,
"tables": tables,
"warnings": warnings,
"notes": notes,
"charts": charts,
"values": values,
})
The exact script CodeSplash ran for example “Bernoulli guide” · R version 4.5.1 (2025-06-13)
# Sequential probability ratio tests — Wald SPRT, MaxSPRT and conditional MaxSPRT
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method experiment.sprt 1.1.0 · spec 804131c54c11a37c
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # SPRT / MaxSPRT / binomial and conditional MaxSPRT: cs_exp_sprt_*, cs_exp_maxsprt_*, cs_exp_bmaxsprt_*, cs_exp_cmaxsprt_*
# %% Inputs
variant <- "sprt" # sprt | maxsprt | bmaxsprt | cmaxsprt
alpha <- 0.05
seed <- 42 # shared Wichmann-Hill stream: Python simulates the same tests
warnings <- list()
tables <- list()
charts <- list()
values <- list(variant = variant, alpha_target = alpha)
nz <- function(x) if (is.null(x) || (length(x) == 1 && is.na(x))) NA else x
if (variant == "sprt") {
# %% Wald SPRT
family <- "bernoulli"
beta <- 1 - 0.8
params <- list(p0 = 0.5, p1 = 0.7, mu0 = 0, mu1 = 0.5,
sigma = 1, lam0 = 1, lam1 = 1.5,
rate0 = 1, rate1 = 2, delta = 0.01)
n_max <- NULL
b <- cs_exp_sprt_bounds(alpha, beta)
log_a <- b[1]
log_b <- b[2]
if (family == "difference") {
diffs <- as.numeric(unlist(c()))
ses <- as.numeric(unlist(c()))
w <- cs_exp_sprt_levels(cs_exp_sprt_difference(diffs, ses, params$delta), log_a, log_b)
n_obs <- length(diffs)
unit <- "look"
} else {
obs <- as.numeric(unlist(c(1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1)))
w <- cs_exp_sprt_walk(cs_exp_sprt_increments(family, obs, params), log_a, log_b, n_max)
n_obs <- length(obs)
unit <- "observation"
}
if (!is.na(w$n_stop) && w$n_stop < n_obs) warnings <- c(warnings, sprintf("The walk crossed a boundary at %s %d; the %d later value(s) were not used.", unit, w$n_stop, n_obs - w$n_stop))
values <- c(values, list(
family = family, power_target = 1 - beta, log_a = log_a, log_b = log_b, bound_a = exp(log_a), bound_b = exp(log_b),
n_observed = n_obs, n_stop = nz(w$n_stop), llr_stop = w$llr_stop, decision = if (n_obs > 0) w$decision else "no data yet",
oc_h0 = NA, oc_h1 = NA, asn_h0 = NA, asn_h1 = NA, fixed_n = NA
))
for (i in seq_along(w$llr)) values[[sprintf("llr[%d]", i)]] <- w$llr[i]
if (family != "difference") {
# %% Operating characteristic and expected sample size (Wald's approximations)
ends <- cs_exp_sprt_oc(family, params, log_a, log_b, c(1, -1))
h0 <- ends[ends$h == 1, ]
h1 <- ends[ends$h == -1, ]
values$oc_h0 <- h0$oc
values$oc_h1 <- h1$oc
values$asn_h0 <- h0$asn
values$asn_h1 <- h1$asn
values$fixed_n <- cs_exp_sprt_fixed_n(family, params, alpha, beta)
curve <- cs_exp_sprt_oc(family, params, log_a, log_b)
every <- curve[seq(1, nrow(curve), by = 2), , drop = FALSE]
tables <- c(tables, list(list(
key = "oc", title = "Operating characteristic (Wald's approximation)",
columns = list(list(key = "theta", label = "True parameter", type = "number"), list(key = "oc", label = "P(accept H₀)", type = "number"),
list(key = "power", label = "P(reject H₀)", type = "number"), list(key = "asn", label = "Expected sample size", type = "number")),
rows = lapply(seq_len(nrow(every)), function(i) list(theta = every$theta[i], oc = every$oc[i], power = every$power[i], asn = every$asn[i]))
)))
charts <- c(charts, list(cs_chart("oc", "power-curve", "Probability of rejecting H₀",
list(x = cs_col("True parameter", curve$theta), power = cs_col("P(reject H₀)", curve$power)),
controls = list(target = 1 - beta))))
reps <- as.integer(400)
if (reps > 0) {
# %% Exact truncated OC and ASN by simulation
horizon <- if (!is.null(n_max)) as.integer(n_max) else as.integer(300)
th <- switch(family, bernoulli = c(params$p0, params$p1), normal = c(params$mu0, params$mu1),
poisson = c(params$lam0, params$lam1), exponential = c(params$rate0, params$rate1))
sims <- list(
list(label = "H₀", theta = th[1], r = cs_exp_sprt_simulate(family, params, th[1], log_a, log_b, horizon, reps, seed)),
list(label = "H₁", theta = th[2], r = cs_exp_sprt_simulate(family, params, th[2], log_a, log_b, horizon, reps, seed + 1))
)
for (j in 1:2) {
tag <- c("h0", "h1")[j]
values[[paste0("mc_reject_", tag)]] <- sims[[j]]$r$reject
values[[paste0("mc_asn_", tag)]] <- sims[[j]]$r$asn
values[[paste0("mc_truncated_", tag)]] <- sims[[j]]$r$truncated
}
values$mc_reps <- reps
tables <- c(tables, list(list(
key = "mc", title = sprintf("Simulated truncated SPRT (%d tests per hypothesis, horizon %d, seed %d)", reps, horizon, seed),
columns = list(list(key = "hypothesis", label = "True hypothesis", type = "string"), list(key = "theta", label = "Parameter", type = "number"),
list(key = "reject", label = "P(reject H₀)", type = "number"), list(key = "reject_se", label = "± MC SE", type = "number"),
list(key = "asn", label = "Mean sample size", type = "number"), list(key = "n_median", label = "Median", type = "number"),
list(key = "n_p90", label = "90th percentile", type = "number"), list(key = "truncated", label = "Reached the horizon", type = "percent")),
rows = lapply(sims, function(s) c(list(hypothesis = s$label, theta = s$theta), s$r[c("reject", "reject_se", "asn", "n_median", "n_p90", "truncated")]))
)))
if (any(vapply(sims, function(s) s$r$truncated > 0.01, logical(1)))) warnings <- c(warnings, "More than 1% of simulated tests reached the horizon without a decision; raise the horizon or set a truncation rule.")
}
}
# %% Walk chart
xs <- c(0, seq_along(w$llr))
end <- max(xs[length(xs)], 1)
charts <- c(list(cs_chart("walk", "sprt-path", "Log-likelihood ratio walk", list(
x = cs_col(paste0(toupper(substr(unit, 1, 1)), substring(unit, 2)), c(0, end, 0, end, xs)),
llr = cs_col("log Λ", c(log_a, log_a, log_b, log_b, 0, w$llr)),
series = cs_col("Series", c(rep("reject H₀ (log A)", 2), rep("accept H₀ (log B)", 2), rep("observed log Λ", length(xs))))
))), charts)
summary <- sprintf("Wald SPRT (%s): bounds log A = %.3f, log B = %.3f; %s", family, log_a, log_b,
if (n_obs > 0) sprintf("%s after %d %s(s).", values$decision, n_obs, unit) else "no observations yet.")
statistics <- c(
list(list(key = "log_a", label = "Upper bound log A", value = log_a), list(key = "log_b", label = "Lower bound log B", value = log_b)),
if (!is.na(values$asn_h1)) list(list(key = "asn_h1", label = "Expected sample size under H₁", value = values$asn_h1),
list(key = "asn_h0", label = "Expected sample size under H₀", value = values$asn_h0)),
if (n_obs > 0) list(list(key = "llr_stop", label = "log Λ at the last observation used", value = w$llr_stop))
)
notes <- c("Wald's boundaries are approximate: the walk overshoots them, so the realized error rates are usually a little below α and β (the simulation shows the actual rates).",
"Analyze the decision at the first crossing only; this is not a fixed-sample test repeated after every observation.")
} else if (variant == "maxsprt") {
# %% Poisson MaxSPRT (continuous surveillance)
t_max <- 10
m_min <- as.integer(1)
cv <- cs_exp_maxsprt_cv(alpha, t_max, m_min)
thr <- cs_exp_maxsprt_thresholds(cv, t_max, m_min)
thr <- thr[order(thr$a, thr$k, method = "radix"), , drop = FALSE]
events <- as.numeric(unlist(c()))
expected <- as.numeric(unlist(c()))
if (length(events) != length(expected)) stop("Give one expected count per observed event count.")
looks <- list()
decision <- "no data yet"
signal_at <- NA
for (i in seq_along(events)) {
llr <- cs_exp_maxsprt_llr(events[i], expected[i])
dec <- if (llr >= cv && events[i] >= m_min) { signal_at <- i; "signal: reject H0" } else if (expected[i] >= t_max) "end: no signal" else "continue"
looks[[i]] <- list(look = i, events = events[i], expected = expected[i], llr = llr, decision = dec)
decision <- dec
if (!is.na(signal_at) || expected[i] >= t_max) break
}
if (length(looks) < length(events)) warnings <- c(warnings, sprintf("Surveillance ended at look %d; later looks were not used.", length(looks)))
values <- c(values, list(cv = cv, alpha_exact = cs_exp_maxsprt_alpha(cv, t_max, m_min), t_max = t_max, min_events = m_min,
n_thresholds = nrow(thr), n_looks = length(looks), llr_last = if (length(looks)) looks[[length(looks)]]$llr else NA,
decision = decision, signal_look = signal_at))
for (r in looks) values[[sprintf("llr[%d]", r$look)]] <- r$llr
tables <- c(tables, list(list(
key = "thresholds", title = "Signal thresholds: the k-th event signals if it arrives before this expected count",
columns = list(list(key = "k", label = "Events", type = "integer"), list(key = "a", label = "Latest expected count", type = "number")),
rows = lapply(seq_len(nrow(thr)), function(i) list(k = thr$k[i], a = thr$a[i]))
)))
if (length(looks)) tables <- c(tables, list(list(
key = "looks", title = "Observed looks", rows = looks,
columns = list(list(key = "look", label = "Look", type = "integer"), list(key = "events", label = "Events", type = "integer"),
list(key = "expected", label = "Expected under H₀", type = "number"), list(key = "llr", label = "log LR", type = "number"),
list(key = "decision", label = "Decision", type = "string"))
)))
lx <- vapply(looks, function(r) r$expected, numeric(1))
ly <- vapply(looks, function(r) r$llr, numeric(1))
charts <- c(charts, list(cs_chart("walk", "sprt-path", "Maximized log-likelihood ratio", list(
x = cs_col("Expected events under H₀", c(0, t_max, 0, lx)), llr = cs_col("log LR", c(cv, cv, 0, ly)),
series = cs_col("Series", c(rep("critical value", 2), rep("observed log LR", length(looks) + 1)))
))))
summary <- paste0(sprintf("Poisson MaxSPRT to T = %s expected events (M = %d): critical value %.4f", format(t_max), m_min, cv),
if (length(looks)) sprintf("; %s.", decision) else ".")
statistics <- list(list(key = "cv", label = "Critical value", value = cv), list(key = "alpha_exact", label = "Exact type I error", value = values$alpha_exact))
notes <- c("Signal at the first look whose log-likelihood ratio reaches the critical value; the critical value controls α over continuous monitoring to T, not at a single look.")
} else if (variant == "bmaxsprt") {
# %% Binomial MaxSPRT (matched or self-controlled events)
n_total <- as.integer(50)
z <- 1
m_min <- as.integer(1)
rr <- 2
cv <- cs_exp_bmaxsprt_cv(alpha, n_total, m_min, z)
null_run <- cs_exp_bmaxsprt_run(cv, n_total, m_min, z)
alt_run <- cs_exp_bmaxsprt_run(cv, n_total, m_min, z, rr)
thr <- cs_exp_bmaxsprt_thresholds(cv, n_total, m_min, z)
totals <- as.numeric(unlist(c()))
exposed <- as.numeric(unlist(c()))
if (length(totals) != length(exposed)) stop("Give one exposed-event count per total-event count.")
looks <- list()
decision <- "no data yet"
signal_at <- NA
for (i in seq_along(totals)) {
n <- totals[i]
c <- exposed[i]
if (c > n || (i > 1 && (n < totals[i - 1] || c < exposed[i - 1]))) stop("Event counts are cumulative: they never fall, and exposed events cannot exceed the total.")
llr <- cs_exp_bmaxsprt_llr(c, n, z)
dec <- if (llr >= cv - 1e-9 && c >= m_min) { signal_at <- i; "signal: reject H0" } else if (n >= n_total) "end: no signal" else "continue"
looks[[i]] <- list(look = i, total = n, exposed = c, share = if (n > 0) c / n else NA, llr = llr, decision = dec)
decision <- dec
if (!is.na(signal_at) || n >= n_total) break
}
if (length(looks) < length(totals)) warnings <- c(warnings, sprintf("Surveillance ended at look %d; later looks were not used.", length(looks)))
values <- c(values, list(cv = cv, alpha_exact = null_run$reject, n_total = n_total, z = z, null_share = 1 / (1 + z), min_events = m_min,
rr_target = rr, power = alt_run$reject, events_if_signal = alt_run$events_if_signal, events_expected = alt_run$events,
events_expected_h0 = null_run$events, n_looks = length(looks), llr_last = if (length(looks)) looks[[length(looks)]]$llr else NA,
decision = decision, signal_look = signal_at))
for (r in looks) values[[sprintf("llr[%d]", r$look)]] <- r$llr
step <- max(1L, as.integer(ceiling(length(thr) / 200)))
tables <- c(tables, list(list(
key = "thresholds", title = "Signal thresholds: after n events in all, this many in the exposed group signal",
columns = list(list(key = "n", label = "Events in all", type = "integer"), list(key = "c", label = "Exposed events", type = "integer")),
rows = lapply(thr[seq.int(1L, length(thr), by = step)], function(r) list(n = r[[1]], c = r[[2]]))
), list(
key = "power", title = "Exact operating characteristics",
columns = list(list(key = "scenario", label = "If the true relative risk is", type = "string"), list(key = "reject", label = "P(signal)", type = "number"),
list(key = "at_signal", label = "Mean events at a signal", type = "number"), list(key = "events", label = "Mean events at stopping", type = "number")),
rows = list(list(scenario = "1 (H₀)", reject = null_run$reject, at_signal = null_run$events_if_signal, events = null_run$events),
list(scenario = format(rr), reject = alt_run$reject, at_signal = alt_run$events_if_signal, events = alt_run$events))
)))
if (length(looks)) tables <- c(tables, list(list(
key = "looks", title = "Observed looks", rows = looks,
columns = list(list(key = "look", label = "Look", type = "integer"), list(key = "total", label = "Events in all", type = "integer"),
list(key = "exposed", label = "Exposed events", type = "integer"), list(key = "share", label = "Exposed share", type = "number"),
list(key = "llr", label = "log LR", type = "number"), list(key = "decision", label = "Decision", type = "string"))
)))
lx <- vapply(looks, function(r) r$total, numeric(1))
ly <- vapply(looks, function(r) r$llr, numeric(1))
charts <- c(charts, list(cs_chart("walk", "sprt-path", "Maximized log-likelihood ratio (binomial)", list(
x = cs_col("Events in all", c(0, n_total, 0, lx)), llr = cs_col("log LR", c(cv, cv, 0, ly)),
series = cs_col("Series", c(rep("critical value", 2), rep("observed log LR", length(looks) + 1)))
))))
summary <- paste0(sprintf("Binomial MaxSPRT to N = %d events (z = %s, M = %d): critical value %.4f, exact α %.4f", n_total, format(z), m_min, cv, null_run$reject),
if (length(looks)) sprintf("; %s.", decision) else ".")
statistics <- list(list(key = "cv", label = "Critical value", value = cv), list(key = "alpha_exact", label = "Exact type I error", value = null_run$reject),
list(key = "power", label = sprintf("Power at relative risk %s", format(rr)), value = alt_run$reject))
notes <- c("With discrete events only some error rates are attainable: the critical value is the smallest log-likelihood ratio that keeps the exact α at or below the target, so the exact α can be lower than you asked for.",
"Under H₀ each event falls in the exposed group with probability 1/(1 + z), where z is the unexposed person-time per exposed person-time.")
} else {
# %% Conditional Poisson MaxSPRT
c_hist <- as.numeric(20)
k_max <- as.integer(20)
m_min <- as.integer(1)
v_hist <- NULL
cv <- cs_exp_cmaxsprt_cv(alpha, c_hist, k_max, m_min)
thr <- cs_exp_cmaxsprt_thresholds(cv, c_hist, k_max, m_min)
cases <- as.numeric(unlist(c()))
exposure <- as.numeric(unlist(c()))
if (length(cases) != length(exposure)) stop("Give one exposure per observed case count.")
if (length(cases) && is.null(v_hist)) stop("Set the historical exposure V to evaluate observed looks.")
looks <- list()
decision <- "no data yet"
signal_at <- NA
for (i in seq_along(cases)) {
u <- exposure[i] / v_hist
llr <- cs_exp_cmaxsprt_llr(c_hist, cases[i], u)
dec <- if (llr >= cv && cases[i] >= m_min) { signal_at <- i; "signal: reject H0" } else if (cases[i] >= k_max) "end: no signal" else "continue"
looks[[i]] <- list(look = i, cases = cases[i], exposure = exposure[i], ratio = u, llr = llr, decision = dec)
decision <- dec
if (!is.na(signal_at) || cases[i] >= k_max) break
}
if (length(looks) < length(cases)) warnings <- c(warnings, sprintf("Surveillance ended at look %d; later looks were not used.", length(looks)))
values <- c(values, list(cv = cv, alpha_exact = cs_exp_cmaxsprt_alpha(cv, c_hist, k_max, m_min), hist_events = as.integer(c_hist),
k_max = k_max, min_events = m_min, n_looks = length(looks), llr_last = if (length(looks)) looks[[length(looks)]]$llr else NA,
decision = decision, signal_look = signal_at))
for (r in looks) values[[sprintf("llr[%d]", r$look)]] <- r$llr
tables <- c(tables, list(list(
key = "thresholds", title = "Signal thresholds: the x-th current event signals if the exposure ratio P/V is at most",
columns = c(list(list(key = "x", label = "Current events", type = "integer"), list(key = "u", label = "Largest P / V", type = "number")),
if (!is.null(v_hist)) list(list(key = "p", label = "Largest current exposure P", type = "number"))),
rows = lapply(seq_len(nrow(thr)), function(i) c(list(x = thr$x[i], u = thr$u[i]), if (!is.null(v_hist)) list(p = thr$u[i] * v_hist)))
)))
if (length(looks)) tables <- c(tables, list(list(
key = "looks", title = "Observed looks", rows = looks,
columns = list(list(key = "look", label = "Look", type = "integer"), list(key = "cases", label = "Current events", type = "integer"),
list(key = "exposure", label = "Current exposure", type = "number"), list(key = "ratio", label = "P / V", type = "number"),
list(key = "llr", label = "log LR", type = "number"), list(key = "decision", label = "Decision", type = "string"))
)))
lx <- vapply(looks, function(r) r$ratio, numeric(1))
ly <- vapply(looks, function(r) r$llr, numeric(1))
end <- max(c(thr$u, lx))
charts <- c(charts, list(cs_chart("walk", "sprt-path", "Conditional maximized log-likelihood ratio", list(
x = cs_col("Current / historical exposure (P / V)", c(0, end, 0, lx)), llr = cs_col("log LR", c(cv, cv, 0, ly)),
series = cs_col("Series", c(rep("critical value", 2), rep("observed log LR", length(looks) + 1)))
))))
summary <- paste0(sprintf("Conditional MaxSPRT (c = %d, K = %d, M = %d): critical value %.4f", as.integer(c_hist), k_max, m_min, cv),
if (length(looks)) sprintf("; %s.", decision) else ".")
statistics <- list(list(key = "cv", label = "Critical value", value = cv), list(key = "alpha_exact", label = "Exact type I error", value = values$alpha_exact))
notes <- c("The historical data are taken as collected until c events (fixed-count sampling); the baseline's uncertainty is part of the critical value.")
}
# %% Result
cs_publish(list(
method = "experiment.sprt",
methodVersion = "1.1.0",
title = switch(variant, sprt = "Sequential probability ratio test", maxsprt = "MaxSPRT surveillance", bmaxsprt = "Binomial MaxSPRT surveillance", cmaxsprt = "Conditional MaxSPRT surveillance"),
engine = cs_engine_info("stats"),
summary = summary,
statistics = statistics,
tables = tables,
warnings = warnings,
notes = notes,
charts = charts,
values = values
))
Sources
- Wald, A. (1945). Sequential tests of statistical hypotheses. Annals of Mathematical Statistics, 16, 117–186.
- Wald, A. (1947). Sequential Analysis. Wiley.
- Kulldorff, M., Davis, R. L., Kolczak, M., Lewis, E., Lieu, T., & Platt, R. (2011). A maximized sequential probability ratio test for drug and vaccine safety surveillance. Sequential Analysis, 30, 58–78.
- Li, L., & Kulldorff, M. (2010). A conditional maximized sequential probability ratio test for pharmacovigilance. Statistics in Medicine, 29, 284–295.
- Silva, I. R., & Kulldorff, M. (2024). Sequential: Exact Sequential Analysis for Poisson and Binomial Data. R package.
From the CodeSplash method registry · experiment.sprt v1.1.0.