Skip to content

Planned looks and alpha spending

Compare Pocock, O'Brien–Fleming and Wang–Tsiatis boundaries, and see what each one costs in sample size.

Advanced ~12 min8 steps

What runs in CodeSplash

You will be able to

  • Explain how boundaries keep the overall false-positive rate at the planned level
  • Compare Pocock, O'Brien–Fleming and Wang–Tsiatis shapes
  • Read inflation as the cost of being allowed to stop early

Read first

01

A budget for false positives

Read

You have a fixed false-positive budget. Alpha spendingAlpha spendingA plan for how much of the false-positive budget each interim look may use. decides how much each planned look may use. Each look gets a zz boundary, set so that the chance of crossing at any look stays at α\alpha under no effect.

The boundary's shape is the design choice:

  • Pocock uses the same bar at every look.
  • O'Brien–Fleming starts very high and ends close to the usual value.
  • Wang–Tsiatis sits between them, set by a shape parameter Δ\Delta.
ck=C⋅(kK)Δ−1/2c_k = C \cdot \left(\frac{k}{K}\right)^{\Delta - 1/2}
02

Spend the budget

Explore

BExplorable · Spending alpha across looks

How can you look at the data early without inflating the error rate?

How often does peeking at 1.96 reject at these looks?

0.50
How sure?
2
0.0
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.

Switch between shapes and add looks. Which shape leaves the final bar closest to the usual 1.96?

03

Which final bar is higher?

Predict

Predict first

Three looks, two-sided at the 5% level. Which design asks for the stronger result at the last look?

Pocock has the higher final barO'Brien–Fleming has the higher final barThey end at the same place
Reveal

Pocock's bar is 2.29 at every look, and O'Brien–Fleming's final bar is 2.00. O'Brien–Fleming saved its budget for the end by spending almost nothing early.

04

Flexibility has a price

Read

To allow stopping early, you must plan for more users at most. That extra is the inflation.

DesignInflation
O'Brien–Fleming1.7%
Wang–Tsiatis (Δ\Delta = 1/4)5.4%
Pocock16.6%

Pocock costs the most in the worst case, but tends to stop soonest when the effect is large.

05

Read a live test

In the app
Sequential monitoring planRecorded · Python and R agreeRecorded 2026-11-09 · 29 values compared
R

3 looks, inflation 1.0174, final bound z = 2.004.

Information inflation
1.017
Expected size under H1 (fraction of fixed)
0.8562
Expected size under H0 (fraction of fixed)
1.012
Final efficacy z
2.004

Plots

Stopping boundariesAt each interim look, has the test statistic crossed the efficacy or futility boundary?
View data
BoundInformation fractionz
efficacy0.33333.471
efficacy0.3333−3.471
efficacy0.66672.454
efficacy0.6667−2.454
efficacy12.004
efficacy1−2.004
observed0.33331.100
observed0.66672.600

Boundaries by look

LookInformationEfficacy zNominal pα spent (cumulative)P(stop for efficacy | H0)P(stop for efficacy | H1)Observed zDecision
133.3%3.471< .0010.00050.00050.03291.100continue
266.7%2.454.0140.01430.01380.40952.600stop: efficacy
3100.0%2.004.0450.05000.03570.3576——
  • Bounds on the z scale of the treatment − control difference; information fractions are shares of the maximum information (≈ units).
  • Non-binding futility: the efficacy bounds assume the trial may continue past a futility bound, so stopping for futility never inflates α.
  • Always-valid p-values stay valid under continuous peeking; they are larger than fixed-horizon p-values.
The exact R script · R R version 4.5.1 (2025-06-13)
# Sequential monitoring — group-sequential boundaries and always-valid p-values
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method experiment.sequential 1.1.0 · spec 69f6b95ebd744285
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # error-spending bounds cs_exp_gs_* and cs_exp_msprt (twins of codesplash.experiment)

# %% Inputs
looks <- as.integer(3)
timing <- c() # information fractions (empty = equally spaced)
alpha <- 0.05
beta <- 1 - 0.8
two_sided <- "two-sided" == "two-sided"
spending <- "obf_classic" # obf | pocock | hsd | power | hp | pocock_classic | obf_classic | wt
param <- if (spending == "wt") 0.25 else -4 # Delta for Wang-Tsiatis
futility <- if (two_sided) "none" else "none"
fkind <- "hsd"
fparam <- -2
n_fixed <- NULL
observed <- as.numeric(unlist(c(1.1, 2.6)))
m_diff <- as.numeric(unlist(c()))
m_se <- as.numeric(unlist(c()))
m_tau <- NULL
warnings <- list()
if (spending == "power" && param <= 0) stop("The power family needs rho > 0.")
timing <- as.numeric(unlist(timing))
if (!length(timing)) {
  timing <- (seq_len(looks)) / looks
} else {
  timing <- sort(timing)[seq_len(min(length(timing), looks))]
  if (length(timing) < looks) stop(sprintf("Give %d information fractions (or none for equal spacing).", looks))
  timing[looks] <- 1
}
if (looks > 1 && any(diff(timing) <= 0)) stop("Information fractions must increase.")
if ("none" == "nonbinding" && two_sided) warnings <- c(warnings, "Futility bounds are only offered for one-sided designs; none were added.")

# Equivalent idiom: gsDesign::gsDesign(k = looks, test.type = if (two_sided) 2 else 1, alpha = alpha / 2, beta = beta, timing = timing, sfu = sfLDOF)
# %% Design
d <- cs_exp_gs_design(timing, alpha, beta, two_sided, spending, param, futility, fkind, fparam)
upper <- d$upper
lower <- d$lower

# %% Observed looks
decisions <- character(0)
for (k in seq_len(min(length(observed), looks))) {
  z <- observed[k]
  decisions[k] <- if ((if (two_sided) abs(z) else z) >= upper[k]) "stop: efficacy"
    else if (futility == "nonbinding" && z <= lower[k] && k < looks) "stop: futility (non-binding)"
    else if (k == looks) "final: not significant"
    else "continue"
}
if (length(observed) > looks) warnings <- c(warnings, sprintf("Only the first %d observed z values were used.", looks))

# %% Always-valid monitoring (mixture SPRT)
ms <- NULL
tau_used <- NULL
if (length(m_diff)) {
  if (length(m_se) != length(m_diff)) stop("Give one standard error per observed difference.")
  tau_used <- if (!is.null(m_tau) && m_tau > 0) m_tau else (stats::qnorm(1 - alpha / 2) + stats::qnorm(1 - beta)) * m_se[length(m_se)]
  ms <- cs_exp_msprt(m_diff, m_se^2, tau_used, alpha)
}

# %% Result
mult <- if (two_sided) 2 else 1
rows <- lapply(seq_len(looks), function(k) {
  row <- list(look = k, t = timing[k], upper = upper[k], lower = if (is.finite(lower[k])) lower[k] else NULL,
              nominal_p = (1 - stats::pnorm(upper[k])) * mult, spent = d$alpha_spent[k] * mult,
              cross_h0 = d$pu0[k] * mult, cross_h1 = d$pu1[k])
  if (!is.null(n_fixed)) row$n <- as.integer(ceiling(n_fixed * d$inflation * timing[k] - 1e-9))
  if (k <= length(decisions)) {
    row$z <- observed[k]
    row$decision <- decisions[k]
  }
  row
})
columns <- c(
  list(list(key = "look", label = "Look", type = "integer"), list(key = "t", label = "Information", type = "percent")),
  if (!is.null(n_fixed)) list(list(key = "n", label = "Units per arm", type = "integer")),
  list(list(key = "upper", label = "Efficacy z", type = "number")),
  if (futility == "nonbinding") list(list(key = "lower", label = "Futility z", type = "number")),
  list(list(key = "nominal_p", label = "Nominal p", type = "pvalue"), list(key = "spent", label = "α spent (cumulative)", type = "number"),
       list(key = "cross_h0", label = "P(stop for efficacy | H0)", type = "number"), list(key = "cross_h1", label = "P(stop for efficacy | H1)", type = "number")),
  if (length(decisions)) list(list(key = "z", label = "Observed z", type = "number"), list(key = "decision", label = "Decision", type = "string"))
)
tables <- list(list(key = "bounds", title = "Boundaries by look", columns = columns, rows = rows))
if (!is.null(ms)) {
  tables <- c(tables, list(list(
    key = "msprt", title = sprintf("Always-valid inference (mixture SPRT, τ = %.4g)", tau_used),
    columns = list(list(key = "look", label = "Look", type = "integer"), list(key = "diff", label = "Difference", type = "number"),
                   list(key = "p", label = "Always-valid p", type = "pvalue"), list(key = "low", label = "Lower", type = "number"),
                   list(key = "high", label = "Upper", type = "number")),
    rows = lapply(seq_along(ms$p), function(i) list(look = i, diff = m_diff[i], p = ms$p[i], low = ms$low[i], high = ms$high[i]))
  )))
}
bx <- bz <- numeric(0)
bl <- character(0)
for (k in seq_len(looks)) {
  bx <- c(bx, timing[k]); bz <- c(bz, upper[k]); bl <- c(bl, "efficacy")
  if (two_sided) { bx <- c(bx, timing[k]); bz <- c(bz, -upper[k]); bl <- c(bl, "efficacy") }
  if (futility == "nonbinding") { bx <- c(bx, timing[k]); bz <- c(bz, lower[k]); bl <- c(bl, "futility") }
}
for (k in seq_len(min(length(observed), looks))) { bx <- c(bx, timing[k]); bz <- c(bz, observed[k]); bl <- c(bl, "observed") }
values <- list(
  looks = looks, alpha = alpha, inflation = d$inflation, inflation_pct = d$inflation - 1, i_max = d$i_max,
  i_fix = d$i_fix, en0 = d$en0, en1 = d$en1, power_check = d$power, type1 = d$type1,
  upper_final = upper[looks], n_max = if (is.null(n_fixed)) NA else as.integer(ceiling(n_fixed * d$inflation - 1e-9)),
  decision_last = if (length(decisions)) decisions[length(decisions)] else NA, tau = if (is.null(tau_used)) NA else tau_used
)
for (k in seq_len(looks)) {
  values[[sprintf("upper[%d]", k)]] <- upper[k]
  values[[sprintf("lower[%d]", k)]] <- if (is.finite(lower[k])) lower[k] else NA
  values[[sprintf("spent[%d]", k)]] <- d$alpha_spent[k]
  values[[sprintf("cross_h0[%d]", k)]] <- d$pu0[k]
  values[[sprintf("cross_h1[%d]", k)]] <- d$pu1[k]
}
if (!is.null(ms)) for (i in seq_along(ms$p)) {
  values[[sprintf("msprt_p[%d]", i)]] <- ms$p[i]
  values[[sprintf("msprt_low[%d]", i)]] <- ms$low[i]
  values[[sprintf("msprt_high[%d]", i)]] <- ms$high[i]
}
cs_publish(list(
  method = "experiment.sequential",
  methodVersion = "1.1.0",
  title = "Sequential monitoring plan",
  engine = cs_engine_info("stats"),
  summary = sprintf("%d looks, inflation %.4f, final bound z = %.3f.", looks, d$inflation, upper[looks]),
  statistics = list(
    list(key = "inflation", label = "Information inflation", value = d$inflation),
    list(key = "en1", label = "Expected size under H1 (fraction of fixed)", value = d$en1),
    list(key = "en0", label = "Expected size under H0 (fraction of fixed)", value = d$en0),
    list(key = "upper_final", label = "Final efficacy z", value = upper[looks])
  ),
  tables = tables,
  warnings = warnings,
  notes = c("Bounds on the z scale of the treatment − control difference; information fractions are shares of the maximum information (≈ units).",
            "Non-binding futility: the efficacy bounds assume the trial may continue past a futility bound, so stopping for futility never inflates α.",
            "Always-valid p-values stay valid under continuous peeking; they are larger than fixed-horizon p-values."),
  charts = list(cs_chart(
    "boundaries", "sequential-boundary", "Stopping boundaries",
    list(information = cs_col("Information fraction", bx), z = cs_col("z", bz), bound = cs_col("Bound", bl))
  )),
  values = values
))
Python

3 looks, inflation 1.0174, final bound z = 2.004.

Information inflation
1.017
Expected size under H1 (fraction of fixed)
0.8562
Expected size under H0 (fraction of fixed)
1.012
Final efficacy z
2.004

To keep this page light, the plots are shown once, under the R tab.

Boundaries by look

LookInformationEfficacy zNominal pα spent (cumulative)P(stop for efficacy | H0)P(stop for efficacy | H1)Observed zDecision
133.3%3.471< .0010.00050.00050.03291.100continue
266.7%2.454.0140.01430.01380.40952.600stop: efficacy
3100.0%2.004.0450.05000.03570.3576——
  • Bounds on the z scale of the treatment − control difference; information fractions are shares of the maximum information (≈ units).
  • Non-binding futility: the efficacy bounds assume the trial may continue past a futility bound, so stopping for futility never inflates α.
  • Always-valid p-values stay valid under continuous peeking; they are larger than fixed-horizon p-values.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Sequential monitoring — group-sequential boundaries and always-valid p-values
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method experiment.sequential 1.1.0 · spec 69f6b95ebd744285
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import math

from scipy.special import ndtr, ndtri

import codesplash as cs
from codesplash.experiment import analyze as xa  # mixture SPRT (twin of R cs_exp_msprt)
from codesplash.experiment import sequential as gs  # error-spending bounds (twin of R cs_exp_gs_*)

# %% Inputs
looks = int(3)
timing = []  # information fractions (empty = equally spaced)
alpha = 0.05
beta = 1.0 - 0.8
two_sided = "two-sided" == "two-sided"
spending = "obf_classic"  # obf | pocock | hsd | power | hp | pocock_classic | obf_classic | wt
param = 0.25 if spending == "wt" else -4  # Δ for Wang–Tsiatis
futility = "none" if not two_sided else "none"
fkind = "hsd"
fparam = -2
n_fixed = None
observed = [1.1, 2.6]
m_diff = []
m_se = []
m_tau = None
warnings = []
if spending == "power" and param <= 0:
    raise ValueError("The power family needs ρ > 0.")
if not timing:
    timing = [(k + 1) / looks for k in range(looks)]
else:
    timing = sorted(float(t) for t in timing)[:looks]
    if len(timing) < looks:
        raise ValueError(f"Give {looks} information fractions (or none for equal spacing).")
    timing[-1] = 1.0
if any(b <= a for a, b in zip(timing, timing[1:])):
    raise ValueError("Information fractions must increase.")
if "none" == "nonbinding" and two_sided:
    warnings.append("Futility bounds are only offered for one-sided designs; none were added.")

# Equivalent idiom (R): gsDesign::gsDesign(k, test.type = 1 | 2 | 4, alpha, beta, timing, sfu = sfLDOF, sfl = sfHSD).
# %% Design
d = gs.design(timing, alpha, beta, two_sided, spending, param, futility, fkind, fparam)
upper, lower = d["upper"], d["lower"]

# %% Observed looks
decisions = []
for k, z in enumerate(observed[:looks]):
    if (abs(z) if two_sided else z) >= upper[k]:
        decisions.append("stop: efficacy")
    elif futility == "nonbinding" and z <= lower[k] and k < looks - 1:
        decisions.append("stop: futility (non-binding)")
    elif k == looks - 1:
        decisions.append("final: not significant")
    else:
        decisions.append("continue")
if len(observed) > looks:
    warnings.append(f"Only the first {looks} observed z values were used.")

# %% Always-valid monitoring (mixture SPRT)
m_p, m_lo, m_hi = [], [], []
tau_used = None
if m_diff:
    if len(m_se) != len(m_diff):
        raise ValueError("Give one standard error per observed difference.")
    tau_used = m_tau if m_tau else (float(ndtri(1.0 - alpha / 2.0)) + float(ndtri(1.0 - beta))) * m_se[-1]
    m_p, m_lo, m_hi = xa.msprt(m_diff, [s * s for s in m_se], tau_used, alpha)

# %% Result
rows = []
for k, t in enumerate(timing):
    row = {
        "look": k + 1, "t": t, "upper": upper[k],
        "lower": (lower[k] if math.isfinite(lower[k]) else None),
        "nominal_p": float(1.0 - ndtr(upper[k])) * (2.0 if two_sided else 1.0),
        "spent": d["alpha_spent"][k] * (2.0 if two_sided else 1.0),
        "cross_h0": d["pu0"][k] * (2.0 if two_sided else 1.0), "cross_h1": d["pu1"][k],
    }
    if n_fixed is not None:
        row["n"] = int(math.ceil(n_fixed * d["inflation"] * t - 1e-9))
    if k < len(decisions):
        row["z"] = observed[k]
        row["decision"] = decisions[k]
    rows.append(row)
columns = [
    {"key": "look", "label": "Look", "type": "integer"}, {"key": "t", "label": "Information", "type": "percent"},
    *([{"key": "n", "label": "Units per arm", "type": "integer"}] if n_fixed is not None else []),
    {"key": "upper", "label": "Efficacy z", "type": "number"},
    *([{"key": "lower", "label": "Futility z", "type": "number"}] if futility == "nonbinding" else []),
    {"key": "nominal_p", "label": "Nominal p", "type": "pvalue"}, {"key": "spent", "label": "α spent (cumulative)", "type": "number"},
    {"key": "cross_h0", "label": "P(stop for efficacy | H0)", "type": "number"}, {"key": "cross_h1", "label": "P(stop for efficacy | H1)", "type": "number"},
    *([{"key": "z", "label": "Observed z", "type": "number"}, {"key": "decision", "label": "Decision", "type": "string"}] if decisions else []),
]
tables = [{"key": "bounds", "title": "Boundaries by look", "columns": columns, "rows": rows}]
if m_p:
    tables.append({
        "key": "msprt", "title": f"Always-valid inference (mixture SPRT, τ = {tau_used:.4g})",
        "columns": [{"key": "look", "label": "Look", "type": "integer"}, {"key": "diff", "label": "Difference", "type": "number"},
                    {"key": "p", "label": "Always-valid p", "type": "pvalue"}, {"key": "low", "label": "Lower", "type": "number"},
                    {"key": "high", "label": "Upper", "type": "number"}],
        "rows": [{"look": i + 1, "diff": m_diff[i], "p": m_p[i], "low": m_lo[i], "high": m_hi[i]} for i in range(len(m_p))],
    })
bx, bz, bl = [], [], []
for k, t in enumerate(timing):
    bx.append(t); bz.append(upper[k]); bl.append("efficacy")
    if two_sided:
        bx.append(t); bz.append(-upper[k]); bl.append("efficacy")  # one level, both signs: drawn as upper + lower lines
    if futility == "nonbinding":
        bx.append(t); bz.append(lower[k]); bl.append("futility")
for k, z in enumerate(observed[:looks]):
    bx.append(timing[k]); bz.append(z); bl.append("observed")
values = {
    "looks": looks, "alpha": alpha, "inflation": d["inflation"], "inflation_pct": d["inflation"] - 1.0, "i_max": d["i_max"],
    "i_fix": d["i_fix"], "en0": d["en0"], "en1": d["en1"], "power_check": d["power"], "type1": d["type1"],
    "upper_final": upper[-1], "n_max": int(math.ceil(n_fixed * d["inflation"] - 1e-9)) if n_fixed is not None else None,
    "decision_last": decisions[-1] if decisions else None, "tau": tau_used,
}
for k in range(looks):
    values[f"upper[{k + 1}]"] = upper[k]
    values[f"lower[{k + 1}]"] = lower[k] if math.isfinite(lower[k]) else None
    values[f"spent[{k + 1}]"] = d["alpha_spent"][k]
    values[f"cross_h0[{k + 1}]"] = d["pu0"][k]
    values[f"cross_h1[{k + 1}]"] = d["pu1"][k]
for i in range(len(m_p)):
    values[f"msprt_p[{i + 1}]"] = m_p[i]
    values[f"msprt_low[{i + 1}]"] = m_lo[i]
    values[f"msprt_high[{i + 1}]"] = m_hi[i]
cs.publish({
    "method": "experiment.sequential",
    "methodVersion": "1.1.0",
    "title": "Sequential monitoring plan",
    "engine": cs.engine_info("scipy"),
    "summary": f"{looks} looks, inflation {d['inflation']:.4f}, final bound z = {upper[-1]:.3f}.",
    "statistics": [
        {"key": "inflation", "label": "Information inflation", "value": d["inflation"]},
        {"key": "en1", "label": "Expected size under H1 (fraction of fixed)", "value": d["en1"]},
        {"key": "en0", "label": "Expected size under H0 (fraction of fixed)", "value": d["en0"]},
        {"key": "upper_final", "label": "Final efficacy z", "value": upper[-1]},
    ],
    "tables": tables,
    "warnings": warnings,
    "notes": [
        "Bounds on the z scale of the treatment − control difference; information fractions are shares of the maximum information (≈ units).",
        "Non-binding futility: the efficacy bounds assume the trial may continue past a futility bound, so stopping for futility never inflates α.",
        "Always-valid p-values stay valid under continuous peeking; they are larger than fixed-horizon p-values.",
    ],
    "charts": [cs.chart(
        "boundaries", "sequential-boundary", "Stopping boundaries",
        {"information": cs.col("Information fraction", bx), "z": cs.col("z", bz), "bound": cs.col("Bound", bl)},
    )],
    "values": values,
})

Two looks are in, with z1=1.1z_1 = 1.1 and z2=2.6z_2 = 2.6. The second one clears its boundary, so the verdict is stop: efficacy.

Spending functions also handle looks that fall at uneven times. Only the information fraction at each look matters:

Sequential monitoring planRecorded · Python and R agreeRecorded 2026-11-09 · 29 values compared
R

3 looks, inflation 1.0426, final bound z = 2.049.

Information inflation
1.043
Expected size under H1 (fraction of fixed)
0.8365
Expected size under H0 (fraction of fixed)
1.033
Final efficacy z
2.049

Plots

Stopping boundariesAt each interim look, has the test statistic crossed the efficacy or futility boundary?
View data
BoundInformation fractionz
efficacy0.25002.802
efficacy0.2500−2.802
efficacy0.60002.444
efficacy0.6000−2.444
efficacy12.049
efficacy1−2.049
observed0.25001.200
observed0.60002.900

Boundaries by look

LookInformationUnits per armEfficacy zNominal pα spent (cumulative)P(stop for efficacy | H0)P(stop for efficacy | H1)Observed zDecision
125.0%1,3042.802.0050.00510.00510.08511.200continue
260.0%3,1282.444.0150.01820.01310.33472.900stop: efficacy
3100.0%5,2142.049.0400.05000.03180.3802——
  • Bounds on the z scale of the treatment − control difference; information fractions are shares of the maximum information (≈ units).
  • Non-binding futility: the efficacy bounds assume the trial may continue past a futility bound, so stopping for futility never inflates α.
  • Always-valid p-values stay valid under continuous peeking; they are larger than fixed-horizon p-values.
The exact R script · R R version 4.5.1 (2025-06-13)
# Sequential monitoring — group-sequential boundaries and always-valid p-values
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method experiment.sequential 1.1.0 · spec 2bacaeba644ff7e0
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # error-spending bounds cs_exp_gs_* and cs_exp_msprt (twins of codesplash.experiment)

# %% Inputs
looks <- as.integer(3)
timing <- c(0.25, 0.6, 1) # information fractions (empty = equally spaced)
alpha <- 0.05
beta <- 1 - 0.8
two_sided <- "two-sided" == "two-sided"
spending <- "hsd" # obf | pocock | hsd | power | hp | pocock_classic | obf_classic | wt
param <- if (spending == "wt") 0.25 else -2 # Delta for Wang-Tsiatis
futility <- if (two_sided) "none" else "none"
fkind <- "hsd"
fparam <- -2
n_fixed <- 5000
observed <- as.numeric(unlist(c(1.2, 2.9)))
m_diff <- as.numeric(unlist(c()))
m_se <- as.numeric(unlist(c()))
m_tau <- NULL
warnings <- list()
if (spending == "power" && param <= 0) stop("The power family needs rho > 0.")
timing <- as.numeric(unlist(timing))
if (!length(timing)) {
  timing <- (seq_len(looks)) / looks
} else {
  timing <- sort(timing)[seq_len(min(length(timing), looks))]
  if (length(timing) < looks) stop(sprintf("Give %d information fractions (or none for equal spacing).", looks))
  timing[looks] <- 1
}
if (looks > 1 && any(diff(timing) <= 0)) stop("Information fractions must increase.")
if ("none" == "nonbinding" && two_sided) warnings <- c(warnings, "Futility bounds are only offered for one-sided designs; none were added.")

# Equivalent idiom: gsDesign::gsDesign(k = looks, test.type = if (two_sided) 2 else 1, alpha = alpha / 2, beta = beta, timing = timing, sfu = sfLDOF)
# %% Design
d <- cs_exp_gs_design(timing, alpha, beta, two_sided, spending, param, futility, fkind, fparam)
upper <- d$upper
lower <- d$lower

# %% Observed looks
decisions <- character(0)
for (k in seq_len(min(length(observed), looks))) {
  z <- observed[k]
  decisions[k] <- if ((if (two_sided) abs(z) else z) >= upper[k]) "stop: efficacy"
    else if (futility == "nonbinding" && z <= lower[k] && k < looks) "stop: futility (non-binding)"
    else if (k == looks) "final: not significant"
    else "continue"
}
if (length(observed) > looks) warnings <- c(warnings, sprintf("Only the first %d observed z values were used.", looks))

# %% Always-valid monitoring (mixture SPRT)
ms <- NULL
tau_used <- NULL
if (length(m_diff)) {
  if (length(m_se) != length(m_diff)) stop("Give one standard error per observed difference.")
  tau_used <- if (!is.null(m_tau) && m_tau > 0) m_tau else (stats::qnorm(1 - alpha / 2) + stats::qnorm(1 - beta)) * m_se[length(m_se)]
  ms <- cs_exp_msprt(m_diff, m_se^2, tau_used, alpha)
}

# %% Result
mult <- if (two_sided) 2 else 1
rows <- lapply(seq_len(looks), function(k) {
  row <- list(look = k, t = timing[k], upper = upper[k], lower = if (is.finite(lower[k])) lower[k] else NULL,
              nominal_p = (1 - stats::pnorm(upper[k])) * mult, spent = d$alpha_spent[k] * mult,
              cross_h0 = d$pu0[k] * mult, cross_h1 = d$pu1[k])
  if (!is.null(n_fixed)) row$n <- as.integer(ceiling(n_fixed * d$inflation * timing[k] - 1e-9))
  if (k <= length(decisions)) {
    row$z <- observed[k]
    row$decision <- decisions[k]
  }
  row
})
columns <- c(
  list(list(key = "look", label = "Look", type = "integer"), list(key = "t", label = "Information", type = "percent")),
  if (!is.null(n_fixed)) list(list(key = "n", label = "Units per arm", type = "integer")),
  list(list(key = "upper", label = "Efficacy z", type = "number")),
  if (futility == "nonbinding") list(list(key = "lower", label = "Futility z", type = "number")),
  list(list(key = "nominal_p", label = "Nominal p", type = "pvalue"), list(key = "spent", label = "α spent (cumulative)", type = "number"),
       list(key = "cross_h0", label = "P(stop for efficacy | H0)", type = "number"), list(key = "cross_h1", label = "P(stop for efficacy | H1)", type = "number")),
  if (length(decisions)) list(list(key = "z", label = "Observed z", type = "number"), list(key = "decision", label = "Decision", type = "string"))
)
tables <- list(list(key = "bounds", title = "Boundaries by look", columns = columns, rows = rows))
if (!is.null(ms)) {
  tables <- c(tables, list(list(
    key = "msprt", title = sprintf("Always-valid inference (mixture SPRT, τ = %.4g)", tau_used),
    columns = list(list(key = "look", label = "Look", type = "integer"), list(key = "diff", label = "Difference", type = "number"),
                   list(key = "p", label = "Always-valid p", type = "pvalue"), list(key = "low", label = "Lower", type = "number"),
                   list(key = "high", label = "Upper", type = "number")),
    rows = lapply(seq_along(ms$p), function(i) list(look = i, diff = m_diff[i], p = ms$p[i], low = ms$low[i], high = ms$high[i]))
  )))
}
bx <- bz <- numeric(0)
bl <- character(0)
for (k in seq_len(looks)) {
  bx <- c(bx, timing[k]); bz <- c(bz, upper[k]); bl <- c(bl, "efficacy")
  if (two_sided) { bx <- c(bx, timing[k]); bz <- c(bz, -upper[k]); bl <- c(bl, "efficacy") }
  if (futility == "nonbinding") { bx <- c(bx, timing[k]); bz <- c(bz, lower[k]); bl <- c(bl, "futility") }
}
for (k in seq_len(min(length(observed), looks))) { bx <- c(bx, timing[k]); bz <- c(bz, observed[k]); bl <- c(bl, "observed") }
values <- list(
  looks = looks, alpha = alpha, inflation = d$inflation, inflation_pct = d$inflation - 1, i_max = d$i_max,
  i_fix = d$i_fix, en0 = d$en0, en1 = d$en1, power_check = d$power, type1 = d$type1,
  upper_final = upper[looks], n_max = if (is.null(n_fixed)) NA else as.integer(ceiling(n_fixed * d$inflation - 1e-9)),
  decision_last = if (length(decisions)) decisions[length(decisions)] else NA, tau = if (is.null(tau_used)) NA else tau_used
)
for (k in seq_len(looks)) {
  values[[sprintf("upper[%d]", k)]] <- upper[k]
  values[[sprintf("lower[%d]", k)]] <- if (is.finite(lower[k])) lower[k] else NA
  values[[sprintf("spent[%d]", k)]] <- d$alpha_spent[k]
  values[[sprintf("cross_h0[%d]", k)]] <- d$pu0[k]
  values[[sprintf("cross_h1[%d]", k)]] <- d$pu1[k]
}
if (!is.null(ms)) for (i in seq_along(ms$p)) {
  values[[sprintf("msprt_p[%d]", i)]] <- ms$p[i]
  values[[sprintf("msprt_low[%d]", i)]] <- ms$low[i]
  values[[sprintf("msprt_high[%d]", i)]] <- ms$high[i]
}
cs_publish(list(
  method = "experiment.sequential",
  methodVersion = "1.1.0",
  title = "Sequential monitoring plan",
  engine = cs_engine_info("stats"),
  summary = sprintf("%d looks, inflation %.4f, final bound z = %.3f.", looks, d$inflation, upper[looks]),
  statistics = list(
    list(key = "inflation", label = "Information inflation", value = d$inflation),
    list(key = "en1", label = "Expected size under H1 (fraction of fixed)", value = d$en1),
    list(key = "en0", label = "Expected size under H0 (fraction of fixed)", value = d$en0),
    list(key = "upper_final", label = "Final efficacy z", value = upper[looks])
  ),
  tables = tables,
  warnings = warnings,
  notes = c("Bounds on the z scale of the treatment − control difference; information fractions are shares of the maximum information (≈ units).",
            "Non-binding futility: the efficacy bounds assume the trial may continue past a futility bound, so stopping for futility never inflates α.",
            "Always-valid p-values stay valid under continuous peeking; they are larger than fixed-horizon p-values."),
  charts = list(cs_chart(
    "boundaries", "sequential-boundary", "Stopping boundaries",
    list(information = cs_col("Information fraction", bx), z = cs_col("z", bz), bound = cs_col("Bound", bl))
  )),
  values = values
))
Python

3 looks, inflation 1.0426, final bound z = 2.049.

Information inflation
1.043
Expected size under H1 (fraction of fixed)
0.8365
Expected size under H0 (fraction of fixed)
1.033
Final efficacy z
2.049

To keep this page light, the plots are shown once, under the R tab.

Boundaries by look

LookInformationUnits per armEfficacy zNominal pα spent (cumulative)P(stop for efficacy | H0)P(stop for efficacy | H1)Observed zDecision
125.0%1,3042.802.0050.00510.00510.08511.200continue
260.0%3,1282.444.0150.01820.01310.33472.900stop: efficacy
3100.0%5,2142.049.0400.05000.03180.3802——
  • Bounds on the z scale of the treatment − control difference; information fractions are shares of the maximum information (≈ units).
  • Non-binding futility: the efficacy bounds assume the trial may continue past a futility bound, so stopping for futility never inflates α.
  • Always-valid p-values stay valid under continuous peeking; they are larger than fixed-horizon p-values.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Sequential monitoring — group-sequential boundaries and always-valid p-values
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method experiment.sequential 1.1.0 · spec 2bacaeba644ff7e0
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import math

from scipy.special import ndtr, ndtri

import codesplash as cs
from codesplash.experiment import analyze as xa  # mixture SPRT (twin of R cs_exp_msprt)
from codesplash.experiment import sequential as gs  # error-spending bounds (twin of R cs_exp_gs_*)

# %% Inputs
looks = int(3)
timing = [0.25, 0.6, 1]  # information fractions (empty = equally spaced)
alpha = 0.05
beta = 1.0 - 0.8
two_sided = "two-sided" == "two-sided"
spending = "hsd"  # obf | pocock | hsd | power | hp | pocock_classic | obf_classic | wt
param = 0.25 if spending == "wt" else -2  # Δ for Wang–Tsiatis
futility = "none" if not two_sided else "none"
fkind = "hsd"
fparam = -2
n_fixed = 5000
observed = [1.2, 2.9]
m_diff = []
m_se = []
m_tau = None
warnings = []
if spending == "power" and param <= 0:
    raise ValueError("The power family needs ρ > 0.")
if not timing:
    timing = [(k + 1) / looks for k in range(looks)]
else:
    timing = sorted(float(t) for t in timing)[:looks]
    if len(timing) < looks:
        raise ValueError(f"Give {looks} information fractions (or none for equal spacing).")
    timing[-1] = 1.0
if any(b <= a for a, b in zip(timing, timing[1:])):
    raise ValueError("Information fractions must increase.")
if "none" == "nonbinding" and two_sided:
    warnings.append("Futility bounds are only offered for one-sided designs; none were added.")

# Equivalent idiom (R): gsDesign::gsDesign(k, test.type = 1 | 2 | 4, alpha, beta, timing, sfu = sfLDOF, sfl = sfHSD).
# %% Design
d = gs.design(timing, alpha, beta, two_sided, spending, param, futility, fkind, fparam)
upper, lower = d["upper"], d["lower"]

# %% Observed looks
decisions = []
for k, z in enumerate(observed[:looks]):
    if (abs(z) if two_sided else z) >= upper[k]:
        decisions.append("stop: efficacy")
    elif futility == "nonbinding" and z <= lower[k] and k < looks - 1:
        decisions.append("stop: futility (non-binding)")
    elif k == looks - 1:
        decisions.append("final: not significant")
    else:
        decisions.append("continue")
if len(observed) > looks:
    warnings.append(f"Only the first {looks} observed z values were used.")

# %% Always-valid monitoring (mixture SPRT)
m_p, m_lo, m_hi = [], [], []
tau_used = None
if m_diff:
    if len(m_se) != len(m_diff):
        raise ValueError("Give one standard error per observed difference.")
    tau_used = m_tau if m_tau else (float(ndtri(1.0 - alpha / 2.0)) + float(ndtri(1.0 - beta))) * m_se[-1]
    m_p, m_lo, m_hi = xa.msprt(m_diff, [s * s for s in m_se], tau_used, alpha)

# %% Result
rows = []
for k, t in enumerate(timing):
    row = {
        "look": k + 1, "t": t, "upper": upper[k],
        "lower": (lower[k] if math.isfinite(lower[k]) else None),
        "nominal_p": float(1.0 - ndtr(upper[k])) * (2.0 if two_sided else 1.0),
        "spent": d["alpha_spent"][k] * (2.0 if two_sided else 1.0),
        "cross_h0": d["pu0"][k] * (2.0 if two_sided else 1.0), "cross_h1": d["pu1"][k],
    }
    if n_fixed is not None:
        row["n"] = int(math.ceil(n_fixed * d["inflation"] * t - 1e-9))
    if k < len(decisions):
        row["z"] = observed[k]
        row["decision"] = decisions[k]
    rows.append(row)
columns = [
    {"key": "look", "label": "Look", "type": "integer"}, {"key": "t", "label": "Information", "type": "percent"},
    *([{"key": "n", "label": "Units per arm", "type": "integer"}] if n_fixed is not None else []),
    {"key": "upper", "label": "Efficacy z", "type": "number"},
    *([{"key": "lower", "label": "Futility z", "type": "number"}] if futility == "nonbinding" else []),
    {"key": "nominal_p", "label": "Nominal p", "type": "pvalue"}, {"key": "spent", "label": "α spent (cumulative)", "type": "number"},
    {"key": "cross_h0", "label": "P(stop for efficacy | H0)", "type": "number"}, {"key": "cross_h1", "label": "P(stop for efficacy | H1)", "type": "number"},
    *([{"key": "z", "label": "Observed z", "type": "number"}, {"key": "decision", "label": "Decision", "type": "string"}] if decisions else []),
]
tables = [{"key": "bounds", "title": "Boundaries by look", "columns": columns, "rows": rows}]
if m_p:
    tables.append({
        "key": "msprt", "title": f"Always-valid inference (mixture SPRT, τ = {tau_used:.4g})",
        "columns": [{"key": "look", "label": "Look", "type": "integer"}, {"key": "diff", "label": "Difference", "type": "number"},
                    {"key": "p", "label": "Always-valid p", "type": "pvalue"}, {"key": "low", "label": "Lower", "type": "number"},
                    {"key": "high", "label": "Upper", "type": "number"}],
        "rows": [{"look": i + 1, "diff": m_diff[i], "p": m_p[i], "low": m_lo[i], "high": m_hi[i]} for i in range(len(m_p))],
    })
bx, bz, bl = [], [], []
for k, t in enumerate(timing):
    bx.append(t); bz.append(upper[k]); bl.append("efficacy")
    if two_sided:
        bx.append(t); bz.append(-upper[k]); bl.append("efficacy")  # one level, both signs: drawn as upper + lower lines
    if futility == "nonbinding":
        bx.append(t); bz.append(lower[k]); bl.append("futility")
for k, z in enumerate(observed[:looks]):
    bx.append(timing[k]); bz.append(z); bl.append("observed")
values = {
    "looks": looks, "alpha": alpha, "inflation": d["inflation"], "inflation_pct": d["inflation"] - 1.0, "i_max": d["i_max"],
    "i_fix": d["i_fix"], "en0": d["en0"], "en1": d["en1"], "power_check": d["power"], "type1": d["type1"],
    "upper_final": upper[-1], "n_max": int(math.ceil(n_fixed * d["inflation"] - 1e-9)) if n_fixed is not None else None,
    "decision_last": decisions[-1] if decisions else None, "tau": tau_used,
}
for k in range(looks):
    values[f"upper[{k + 1}]"] = upper[k]
    values[f"lower[{k + 1}]"] = lower[k] if math.isfinite(lower[k]) else None
    values[f"spent[{k + 1}]"] = d["alpha_spent"][k]
    values[f"cross_h0[{k + 1}]"] = d["pu0"][k]
    values[f"cross_h1[{k + 1}]"] = d["pu1"][k]
for i in range(len(m_p)):
    values[f"msprt_p[{i + 1}]"] = m_p[i]
    values[f"msprt_low[{i + 1}]"] = m_lo[i]
    values[f"msprt_high[{i + 1}]"] = m_hi[i]
cs.publish({
    "method": "experiment.sequential",
    "methodVersion": "1.1.0",
    "title": "Sequential monitoring plan",
    "engine": cs.engine_info("scipy"),
    "summary": f"{looks} looks, inflation {d['inflation']:.4f}, final bound z = {upper[-1]:.3f}.",
    "statistics": [
        {"key": "inflation", "label": "Information inflation", "value": d["inflation"]},
        {"key": "en1", "label": "Expected size under H1 (fraction of fixed)", "value": d["en1"]},
        {"key": "en0", "label": "Expected size under H0 (fraction of fixed)", "value": d["en0"]},
        {"key": "upper_final", "label": "Final efficacy z", "value": upper[-1]},
    ],
    "tables": tables,
    "warnings": warnings,
    "notes": [
        "Bounds on the z scale of the treatment − control difference; information fractions are shares of the maximum information (≈ units).",
        "Non-binding futility: the efficacy bounds assume the trial may continue past a futility bound, so stopping for futility never inflates α.",
        "Always-valid p-values stay valid under continuous peeking; they are larger than fixed-horizon p-values.",
    ],
    "charts": [cs.chart(
        "boundaries", "sequential-boundary", "Stopping boundaries",
        {"information": cs.col("Information fraction", bx), "z": cs.col("z", bz), "bound": cs.col("Bound", bl)},
    )],
    "values": values,
})
06

Check your understanding

Checkpoint

Check yourself

You want to stop early only for a dramatic result, and keep the final analysis close to a standard one. Which fits?

Show the answer

Answer: a

O'Brien–Fleming spends very little early, so only a dramatic result stops the test, and its final bar is close to the usual value.

Check yourself

The table above gives Pocock's inflation as a percentage. Written as a multiplier on the information a fixed test would need, what is it? Give two decimals.

Show the answer

Answer: 1.16638706406468

An inflation of about 17% means a multiplier of about 1.17 on the fixed-test information.

Check yourself

Halfway through, the result looks close, so you add an unplanned look. What's wrong with that?

Show the answer

Answer: b

Spending functions handle uneven timing, but not looks whose timing depends on what the results show.

07

Set it up

In the app

In Studios, open Experiments and start from Test with interim looks. The Design step lets you choose the boundary family and the number of looks, and the Monitor step compares each look with its boundary.

Method guide · experiment.sequentialSequential monitoring — group-sequential boundaries and always-valid p-valuesWhen may an A/B test stop early, and what do the interim looks say so far?
08

Recap

Recap
  • Boundaries keep the overall false-positive rate at α\alpha across planned looks.
  • O'Brien–Fleming saves its budget for the end; Pocock spends it evenly.
  • Inflation is the price of being allowed to stop early.

Concepts in this lesson