Decide after every observation
Follow Wald's likelihood ratio walk between two boundaries, then see MaxSPRT for monitoring events.
What runs in CodeSplash
- STAT289Wald sequential probability ratio test Runs in CodeSplash
- STAT290Maximized sequential probability ratio test Runs in CodeSplash
- STAT291Conditional MaxSPRT Runs in CodeSplash
- Sequential probability ratio tests — Wald SPRT, MaxSPRT and conditional MaxSPRT Verified in Python and R
You will be able to
- Track the log-likelihood ratio toward Wald's boundaries
- Explain why the SPRT usually stops sooner than a fixed test
- Use MaxSPRT when you can't name one alternative in advance
Read first
A walk between two walls
ReadThe SPRTSequential probability ratio test (SPRT)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. compares two specific hypotheses after every observation. Keep a running log-likelihood ratio:
Stop when it crosses a wall. With error rates and , Wald's walls are about above and below.
Here the walls are at 2.77 and −1.56.
Walk it
ExploreBExplorable · The sequential probability ratio test
What if you could stop as soon as the evidence is clear?
How many observations does the test use on average?
Commit your prediction above to see the result
Make your prediction to see the result.
Set a true effect and watch paths reach a wall. Then set the truth halfway between the two hypotheses, and see why that's the slowest case.
How long does it take?
PredictPredict first
A fixed test for these same hypotheses and error rates needs about 36 observations. On average, how many would the SPRT need if the alternative is true?
Reveal
23.2 on Wald's approximation, against a fixed 36.5. In this data the walk crossed the upper wall at observation 16, with = 2.84.
See the result
In the appWald 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.
The exact R script · R 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
))
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.
The exact Python script · Python 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 simulated rejection rate under the null was 3.0%, against a planned 5.0%. Wald's walls are slightly conservative because the walk overshoots them.
When you can't name an alternative
ReadPlain SPRT needs one specific alternative. In safety monitoring you may only know the baseline rate of an event. Any excess matters.
MaxSPRTMaximized SPRT (MaxSPRT)An SPRT for event surveillance where the alternative is any elevated rate, maximized over the elevation at each look. tests against the best-fitting elevated rate at each look, and uses an exact critical value:
Poisson MaxSPRT to T = 10 expected events (M = 3): critical value 3.0642; signal: reject H0.
- Critical value
- 3.064
- Exact type I error
- 0.0500
Plots
View data
| log LR | Series | Expected events under H₀ |
|---|---|---|
| 3.064 | critical value | 0 |
| 3.064 | critical value | 10 |
| 0 | observed log LR | 0 |
| 0 | observed log LR | 1.200 |
| 0.2164 | observed log LR | 2 |
| 1.062 | observed log LR | 3.100 |
| 4.128 | observed log LR | 4 |
Signal thresholds: the k-th event signals if it arrives before this expected count
| Events | Latest expected count |
|---|---|
| 3 | 0.4639 |
| 4 | 0.8449 |
| 5 | 1.290 |
| 6 | 1.783 |
| 7 | 2.313 |
| 8 | 2.874 |
| 9 | 3.460 |
| 10 | 4.067 |
| 11 | 4.692 |
| 12 | 5.334 |
| 13 | 5.989 |
| 14 | 6.657 |
| 15 | 7.337 |
| 16 | 8.026 |
| 17 | 8.725 |
| 18 | 9.433 |
| 19 | 10 |
Observed looks
| Look | Events | Expected under H₀ | log LR | Decision |
|---|---|---|---|---|
| 1 | 1 | 1.200 | 0 | continue |
| 2 | 3 | 2 | 0.2164 | continue |
| 3 | 6 | 3.100 | 1.062 | continue |
| 4 | 11 | 4 | 4.128 | signal: reject H0 |
- Surveillance ended at look 4; later looks were not used.
- 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.
The exact R script · R 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 98ebe1bf1c646231
# 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 <- "maxsprt" # 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()))
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(2000)
if (reps > 0) {
# %% Exact truncated OC and ASN by simulation
horizon <- if (!is.null(n_max)) as.integer(n_max) else as.integer(1000)
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(3)
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(1, 3, 6, 11, 12)))
expected <- as.numeric(unlist(c(1.2, 2, 3.1, 4, 5)))
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(3)
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(3)
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
))
Poisson MaxSPRT to T = 10 expected events (M = 3): critical value 3.0642; signal: reject H0.
- Critical value
- 3.064
- Exact type I error
- 0.0500
To keep this page light, the plots are shown once, under the R tab.
Signal thresholds: the k-th event signals if it arrives before this expected count
| Events | Latest expected count |
|---|---|
| 3 | 0.4639 |
| 4 | 0.8449 |
| 5 | 1.290 |
| 6 | 1.783 |
| 7 | 2.313 |
| 8 | 2.874 |
| 9 | 3.460 |
| 10 | 4.067 |
| 11 | 4.692 |
| 12 | 5.334 |
| 13 | 5.989 |
| 14 | 6.657 |
| 15 | 7.337 |
| 16 | 8.026 |
| 17 | 8.725 |
| 18 | 9.433 |
| 19 | 10 |
Observed looks
| Look | Events | Expected under H₀ | log LR | Decision |
|---|---|---|---|---|
| 1 | 1 | 1.200 | 0 | continue |
| 2 | 3 | 2 | 0.2164 | continue |
| 3 | 6 | 3.100 | 1.062 | continue |
| 4 | 11 | 4 | 4.128 | signal: reject H0 |
- Surveillance ended at look 4; later looks were not used.
- 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.
The exact Python script · Python 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 98ebe1bf1c646231
# 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 = "maxsprt" # 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 = []
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(2000)
if reps > 0:
# %% Exact truncated OC and ASN by simulation
horizon = int(n_max) if n_max is not None else int(1000)
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(3)
# 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 = [1, 3, 6, 11, 12]
expected = [1.2, 2, 3.1, 4, 5]
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(3)
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(3)
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 critical value is 3.06. The statistic reached 4.13 at look 4: signal: reject H0.
Conditional MaxSPRT handles a baseline rate that is itself estimated from limited history, so that uncertainty raises the bar a little:
Conditional MaxSPRT (c = 20, K = 20, M = 2): critical value 3.0530; signal: reject H0.
- Critical value
- 3.053
- Exact type I error
- 0.0500
Plots
View data
| log LR | Series | Current / historical exposure (P / V) |
|---|---|---|
| 3.053 | critical value | 0 |
| 3.053 | critical value | 0.4532 |
| 0 | observed log LR | 0 |
| 0.4414 | observed log LR | 0.0800 |
| 2.065 | observed log LR | 0.1600 |
| 4.259 | observed log LR | 0.2400 |
Signal thresholds: the x-th current event signals if the exposure ratio P/V is at most
| Current events | Largest P / V | Largest current exposure P |
|---|---|---|
| 2 | 0.0083 | 8.345 |
| 3 | 0.0219 | 21.928 |
| 4 | 0.0394 | 39.361 |
| 5 | 0.0593 | 59.347 |
| 6 | 0.0811 | 81.131 |
| 7 | 0.1042 | 104.24 |
| 8 | 0.1284 | 128.36 |
| 9 | 0.1533 | 153.28 |
| 10 | 0.1788 | 178.84 |
| 11 | 0.2049 | 204.93 |
| 12 | 0.2314 | 231.44 |
| 13 | 0.2583 | 258.32 |
| 14 | 0.2855 | 285.52 |
| 15 | 0.3130 | 312.98 |
| 16 | 0.3407 | 340.67 |
| 17 | 0.3686 | 368.56 |
| 18 | 0.3966 | 396.63 |
| 19 | 0.4249 | 424.85 |
| 20 | 0.4532 | 453.21 |
Observed looks
| Look | Current events | Current exposure | P / V | log LR | Decision |
|---|---|---|---|---|---|
| 1 | 3 | 80 | 0.0800 | 0.4414 | continue |
| 2 | 8 | 160 | 0.1600 | 2.065 | continue |
| 3 | 14 | 240 | 0.2400 | 4.259 | signal: reject H0 |
- Surveillance ended at look 3; later looks were not used.
- The historical data are taken as collected until c events (fixed-count sampling); the baseline's uncertainty is part of the critical value.
The exact R script · R 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 3431567bc5d245d9
# 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 <- "cmaxsprt" # 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()))
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(2000)
if (reps > 0) {
# %% Exact truncated OC and ASN by simulation
horizon <- if (!is.null(n_max)) as.integer(n_max) else as.integer(1000)
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(2)
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(2)
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(2)
v_hist <- 1000
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(3, 8, 14, 15)))
exposure <- as.numeric(unlist(c(80, 160, 240, 260)))
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
))
Conditional MaxSPRT (c = 20, K = 20, M = 2): critical value 3.0530; signal: reject H0.
- Critical value
- 3.053
- Exact type I error
- 0.0500
To keep this page light, the plots are shown once, under the R tab.
Signal thresholds: the x-th current event signals if the exposure ratio P/V is at most
| Current events | Largest P / V | Largest current exposure P |
|---|---|---|
| 2 | 0.0083 | 8.345 |
| 3 | 0.0219 | 21.928 |
| 4 | 0.0394 | 39.361 |
| 5 | 0.0593 | 59.347 |
| 6 | 0.0811 | 81.131 |
| 7 | 0.1042 | 104.24 |
| 8 | 0.1284 | 128.36 |
| 9 | 0.1533 | 153.28 |
| 10 | 0.1788 | 178.84 |
| 11 | 0.2049 | 204.93 |
| 12 | 0.2314 | 231.44 |
| 13 | 0.2583 | 258.32 |
| 14 | 0.2855 | 285.52 |
| 15 | 0.3130 | 312.98 |
| 16 | 0.3407 | 340.67 |
| 17 | 0.3686 | 368.56 |
| 18 | 0.3966 | 396.63 |
| 19 | 0.4249 | 424.85 |
| 20 | 0.4532 | 453.21 |
Observed looks
| Look | Current events | Current exposure | P / V | log LR | Decision |
|---|---|---|---|---|---|
| 1 | 3 | 80 | 0.0800 | 0.4414 | continue |
| 2 | 8 | 160 | 0.1600 | 2.065 | continue |
| 3 | 14 | 240 | 0.2400 | 4.259 | signal: reject H0 |
- Surveillance ended at look 3; later looks were not used.
- The historical data are taken as collected until c events (fixed-count sampling); the baseline's uncertainty is part of the critical value.
The exact Python script · Python 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 3431567bc5d245d9
# 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 = "cmaxsprt" # 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 = []
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(2000)
if reps > 0:
# %% Exact truncated OC and ASN by simulation
horizon = int(n_max) if n_max is not None else int(1000)
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(2)
# 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(2)
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(2)
v_hist = 1000
# 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 = [3, 8, 14, 15]
exposure = [80, 160, 240, 260]
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,
})
Check your understanding
CheckpointCheck yourself
What must you specify for a plain SPRT?
Show the answer
Answer: a
The likelihood ratio needs both hypotheses. MaxSPRT relaxes this by leaving the alternative open.
Check yourself
When is an SPRT slowest?
Show the answer
Answer: c
Between the hypotheses, the evidence favors neither, so the walk drifts without heading to a wall. That's why many plans add a maximum sample size.
Check yourself
You're monitoring adverse events against a known expected count. Which plan fits?
Show the answer
Answer: b
MaxSPRT was built for this kind of surveillance: signal as soon as the excess is significant, at any size.
Set it up
In the appIn Studios, open Experiments and start from Test that stops as soon as the evidence is clear. The Design step offers Wald SPRT and MaxSPRT as stopping plans, and the Monitor step tracks each look against the plan.
Method guide · experiment.sprtSequential probability ratio tests — Wald SPRT, MaxSPRT and conditional MaxSPRTCan I decide after every observation (or event) while keeping the planned error rates?Recap
Recap- The SPRT adds up evidence after every observation and stops at a wall.
- It usually needs fewer observations, but is slowest when the truth lies between the hypotheses.
- MaxSPRT leaves the alternative open, for monitoring events against a baseline.
Concepts in this lesson