Skip to content

Decide after every observation

Follow Wald's likelihood ratio walk between two boundaries, then see MaxSPRT for monitoring events.

Advanced ~12 min8 steps

What runs in CodeSplash

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

01

A walk between two walls

Read

The 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:

Λn=∑i=1nlog⁡f1(xi)f0(xi)\Lambda_n = \sum_{i=1}^{n} \log \frac{f_1(x_i)}{f_0(x_i)}

Stop when it crosses a wall. With error rates α\alpha and β\beta, Wald's walls are about log⁡1−βα\log\frac{1-\beta}{\alpha} above and log⁡β1−α\log\frac{\beta}{1-\alpha} below.

Here the walls are at 2.77 and −1.56.

02

Walk it

Explore

BExplorable · 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?

500
How sure?
0.10
0.20
0.20
0.050
0.20
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

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.

03

How long does it take?

Predict

Predict 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?

About the same as a fixed testAbout two-thirds of a fixed testAbout a tenth of a fixed test
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 Λ\Lambda = 2.84.

04

See the result

In the app
Sequential probability ratio testRecorded · Python and R agreeRecorded 2026-11-09 · 40 values compared
R

Wald SPRT (bernoulli): bounds log A = 2.773, log B = -1.558; reject H0 after 20 observation(s).

Upper bound log A
2.773
Lower bound log B
−1.558
Expected sample size under H₁
23.169
Expected sample size under H₀
15.390
log Λ at the last observation used
2.842

Plots

Log-likelihood ratio walkAfter each observation (or event), has the evidence crossed the boundary for H₁ or for H₀?
View data
log ΛSeriesObservation
2.773reject H₀ (log A)0
2.773reject H₀ (log A)16
−1.558accept H₀ (log B)0
−1.558accept H₀ (log B)16
0observed log Λ0
0.3365observed log Λ1
0.6729observed log Λ2
0.1621observed log Λ3
0.4986observed log Λ4
0.8351observed log Λ5
1.172observed log Λ6
0.6607observed log Λ7
0.9972observed log Λ8
1.334observed log Λ9
1.670observed log Λ10
2.007observed log Λ11
1.496observed log Λ12
1.832observed log Λ13
2.169observed log Λ14
2.505observed log Λ15
2.842observed log Λ16
Probability of rejecting H₀How does power grow with sample size (or effect size), and where does it reach the target?
View data
P(reject H₀)True parameter
0.00020.3101
0.00030.3185
0.00040.3270
0.00060.3357
0.00070.3445
0.00100.3535
0.00130.3625
0.00170.3717
0.00220.3810
0.00280.3905
0.00370.4000
0.00490.4096
0.00640.4194
0.00830.4292
0.01090.4391
0.01410.4491
0.01830.4592
0.02370.4693
0.03050.4795
0.03920.4897
0.05000.5000
0.06350.5103
0.08000.5206
0.10020.5310
0.12430.5413
0.15280.5516
0.18590.5619
0.22350.5722
0.26540.5825
0.31110.5927
0.35980.6029
0.41050.6130
0.46210.6230
0.51340.6330
0.56350.6429
0.61130.6527
0.65620.6624
0.69770.6720
0.73550.6814
0.76960.6908
0.80000.7000
0.82690.7091
0.85050.7180
0.87120.7268
0.88920.7355
0.90480.7440
0.91820.7523
0.92990.7605
0.93990.7685
0.94850.7763
0.95580.7840
0.96220.7915
0.96760.7988
0.97230.8060
0.97630.8129
0.97970.8197
0.98260.8263
0.98510.8328
0.98730.8390
0.98910.8451

First 60 of 61 rows.

Operating characteristic (Wald's approximation)

True parameterP(accept H₀)P(reject H₀)Expected sample size
0.31010.99980.00026.277
0.32700.99960.00046.659
0.34450.99930.00077.103
0.36250.99870.00137.624
0.38100.99780.00228.239
0.40000.99630.00378.970
0.41940.99360.00649.843
0.43910.98910.010910.890
0.45920.98170.018312.145
0.47950.96950.030513.639
0.50000.95000.050015.390
0.52060.92000.080017.381
0.54130.87570.124319.538
0.56190.81410.185921.708
0.58250.73460.265423.659
0.60290.64020.359825.135
0.62300.53790.462125.941
0.64290.43650.563526.021
0.66240.34380.656225.465
0.68140.26450.735524.450
0.70000.20000.800023.169
0.71800.14950.850521.785
0.73550.11080.889220.407
0.75230.08180.918219.102
0.76850.06010.939917.903
0.78400.04420.955816.822
0.79880.03240.967615.857
0.81290.02370.976315.002
0.82630.01740.982614.248
0.83900.01270.987313.583
0.85100.00930.990712.997

Simulated truncated SPRT (400 tests per hypothesis, horizon 300, seed 42)

True hypothesisParameterP(reject H₀)± MC SEMean sample sizeMedian90th percentileReached the horizon
H₀0.50000.03000.008518.30214380.0%
H₁0.70000.85500.017626.9772149.3000.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
))
Python

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 parameterP(accept H₀)P(reject H₀)Expected sample size
0.31010.99980.00026.277
0.32700.99960.00046.659
0.34450.99930.00077.103
0.36250.99870.00137.624
0.38100.99780.00228.239
0.40000.99630.00378.970
0.41940.99360.00649.843
0.43910.98910.010910.890
0.45920.98170.018312.145
0.47950.96950.030513.639
0.50000.95000.050015.390
0.52060.92000.080017.381
0.54130.87570.124319.538
0.56190.81410.185921.708
0.58250.73460.265423.659
0.60290.64020.359825.135
0.62300.53790.462125.941
0.64290.43650.563526.021
0.66240.34380.656225.465
0.68140.26450.735524.450
0.70000.20000.800023.169
0.71800.14950.850521.785
0.73550.11080.889220.407
0.75230.08180.918219.102
0.76850.06010.939917.903
0.78400.04420.955816.822
0.79880.03240.967615.857
0.81290.02370.976315.002
0.82630.01740.982614.248
0.83900.01270.987313.583
0.85100.00930.990712.997

Simulated truncated SPRT (400 tests per hypothesis, horizon 300, seed 42)

True hypothesisParameterP(reject H₀)± MC SEMean sample sizeMedian90th percentileReached the horizon
H₀0.50000.03000.008518.30214380.0%
H₁0.70000.85500.017626.9772149.3000.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.

05

When you can't name an alternative

Read

Plain 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:

MaxSPRT surveillanceRecorded · Python and R agreeRecorded 2026-11-09 · 15 values compared
R

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

Maximized log-likelihood ratioAfter each observation (or event), has the evidence crossed the boundary for H₁ or for H₀?
View data
log LRSeriesExpected events under H₀
3.064critical value0
3.064critical value10
0observed log LR0
0observed log LR1.200
0.2164observed log LR2
1.062observed log LR3.100
4.128observed log LR4

Signal thresholds: the k-th event signals if it arrives before this expected count

EventsLatest expected count
30.4639
40.8449
51.290
61.783
72.313
82.874
93.460
104.067
114.692
125.334
135.989
146.657
157.337
168.026
178.725
189.433
1910

Observed looks

LookEventsExpected under H₀log LRDecision
111.2000continue
2320.2164continue
363.1001.062continue
41144.128signal: 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
))
Python

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

EventsLatest expected count
30.4639
40.8449
51.290
61.783
72.313
82.874
93.460
104.067
114.692
125.334
135.989
146.657
157.337
168.026
178.725
189.433
1910

Observed looks

LookEventsExpected under H₀log LRDecision
111.2000continue
2320.2164continue
363.1001.062continue
41144.128signal: 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 surveillanceRecorded · Python and R agreeRecorded 2026-11-09 · 14 values compared
R

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

Conditional maximized log-likelihood ratioAfter each observation (or event), has the evidence crossed the boundary for H₁ or for H₀?
View data
log LRSeriesCurrent / historical exposure (P / V)
3.053critical value0
3.053critical value0.4532
0observed log LR0
0.4414observed log LR0.0800
2.065observed log LR0.1600
4.259observed log LR0.2400

Signal thresholds: the x-th current event signals if the exposure ratio P/V is at most

Current eventsLargest P / VLargest current exposure P
20.00838.345
30.021921.928
40.039439.361
50.059359.347
60.081181.131
70.1042104.24
80.1284128.36
90.1533153.28
100.1788178.84
110.2049204.93
120.2314231.44
130.2583258.32
140.2855285.52
150.3130312.98
160.3407340.67
170.3686368.56
180.3966396.63
190.4249424.85
200.4532453.21

Observed looks

LookCurrent eventsCurrent exposureP / Vlog LRDecision
13800.08000.4414continue
281600.16002.065continue
3142400.24004.259signal: 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
))
Python

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 eventsLargest P / VLargest current exposure P
20.00838.345
30.021921.928
40.039439.361
50.059359.347
60.081181.131
70.1042104.24
80.1284128.36
90.1533153.28
100.1788178.84
110.2049204.93
120.2314231.44
130.2583258.32
140.2855285.52
150.3130312.98
160.3407340.67
170.3686368.56
180.3966396.63
190.4249424.85
200.4532453.21

Observed looks

LookCurrent eventsCurrent exposureP / Vlog LRDecision
13800.08000.4414continue
281600.16002.065continue
3142400.24004.259signal: 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,
})
06

Check your understanding

Checkpoint

Check 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.

07

Set it up

In the app

In 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?
08

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