Plotting runs, designs and plans¶
sequential_analysis.plotting draws the things a sequential analysis
produces: the evidence of a test as it accumulates, a confidence
sequence narrowing, the boundaries of a group sequential design, a
change detector's statistic, a filter's estimate, and the distribution
of stopping times from a plan.
It needs matplotlib, which is optional:
pip install "sequential-analysis[plot]"
Every function returns the matplotlib Axes it drew on. Pass ax= to
draw into a figure of your own; leave it out for a new figure. Nothing
is shown or saved for you: call plt.show(), or
ax.figure.savefig("run.png").
The outputs of a run can be given in any form the library produces them:
- a
Recorderattached to the run as a consumer; - a list of
OutputEvents; - a list of outputs;
- the (state, output) pairs returned by
trajectory.
The x axis is the procedure's own count: observations, units or events.
1. Evidence: the e-process of a test¶
An anytime-valid test rejects when its e-value reaches 1/α.
plot_e_process draws the e-value on a log scale, the threshold, and
the point where the test stopped. It finds the e-value field of any
test that has one (log_e_value, log_bf, log_wealth, ...); field=
names another.
from sequential_analysis import Recorder, Run, run_sync
from sequential_analysis.plotting import plot_e_process
from sequential_analysis.procedures import TMixtureSPRT
from sequential_analysis.sources import gaussian
evidence = Recorder()
test = Run(TMixtureSPRT(theta0=0.0, effect=0.5, alpha=0.05), consumers=[evidence])
run_sync(test, gaussian("x", mean=0.3, sd=1.0, seed=3, n=2000))
print(test.state.decision, "after", test.t, "observations")
ax = plot_e_process(evidence, alpha=0.05)

For MultipleTests it draws one line per metric, the e-BH thresholds,
and marks each metric where it is first rejected.
2. Estimation: a confidence sequence¶
A confidence sequence covers the true value at every time
simultaneously. plot_confidence_sequence draws it as a band, with the
estimate inside.
Here the same test is kept running after it rejects, to watch the interval narrow:
from sequential_analysis.plotting import plot_confidence_sequence
interval = Recorder()
test = Run(TMixtureSPRT(theta0=0.0, effect=0.5, alpha=0.05, stop_on_reject=False), consumers=[interval])
run_sync(test, gaussian("x", mean=0.3, sd=1.0, seed=3, n=1000))
last = interval.outputs[-1]
print(f"after {last.n} observations: mean {last.mean:.3f}, 95% confidence sequence [{last.lower:.3f}, {last.upper:.3f}]")
ax = plot_confidence_sequence(interval, truth=0.3)

The first bounds of a confidence sequence are infinite or very wide.
Infinite ones are left out. The y range is chosen so that the very wide
start does not flatten the rest; ax.set_ylim changes it.
3. A group sequential design¶
plot_group_sequential_design draws the efficacy and futility
boundaries of a design against the information fraction. observed=
adds the path of a trial. It takes Z values, or the outputs of a
GroupSequentialTest run.
from sequential_analysis.group_sequential import group_sequential_design
from sequential_analysis.plotting import plot_group_sequential_design
from sequential_analysis.procedures import GroupSequentialTest
design = group_sequential_design(0.025, [0.25, 0.5, 0.75, 1.0], spending="obrien-fleming",
futility="obrien-fleming", power=0.9)
n_max = design.max_sample_size(effect=0.3, sigma=1.0)
trial = Recorder()
run = Run(GroupSequentialTest.from_design(design, n_max, sigma=1.0), consumers=[trial])
run_sync(run, gaussian("x", mean=0.3, sd=1.0, seed=11))
print("stopped after", run.t, "of", n_max, "patients:", run.state.decision)
ax = plot_group_sequential_design(design, observed=trial)

scale="score" draws the score B = Z√t instead. scale="p" draws the
nominal p-value of each boundary, on a log scale.
4. Change detection¶
plot_detection draws the statistic of a change detector, its
threshold and the alarm. It works for:
- CUSUM, on its own scale;
- Shiryaev–Roberts and the e-detectors, on a log scale, with the
threshold you gave the procedure (
threshold=Aorarl); BayesianChangePoint, as the probability of a recent change.
An e-detector also estimates where the change began, which is drawn at
the alarm. change_point= marks the true change when it is known, as in
a simulation.
The data are the response times of the monitoring tutorial: the mean rises from 0.2 s to 0.3 s after request 400.
import random
from sequential_analysis.plotting import plot_detection
from sequential_analysis.procedures import MeanEDetector
from sequential_analysis.sources import from_values
rnd = random.Random(4)
latency = ([min(1.0, rnd.gammavariate(2.0, 0.1)) for _ in range(400)]
+ [min(1.0, rnd.gammavariate(2.0, 0.15)) for _ in range(400)])
detection = Recorder()
detector = Run(MeanEDetector(m=0.2, lo=0.0, hi=1.0, arl=1000, direction="increase", statistic="cusum"),
consumers=[detection])
run_sync(detector, from_values("x", latency))
print("alarm at request", detector.t, "-- change estimated at", detection.outputs[-1].change_estimate)
ax = plot_detection(detection, threshold=1000, change_point=400)

5. A filter, and the smoother afterwards¶
plot_filter draws a filter's mean with a band of ±2 standard
deviations. observations= and truth= add the data and the true
state. smoothed= adds the Rauch–Tung–Striebel smoother's estimates
over the same inputs. For a vector state, component= picks the
coordinate.
The level below drifts upwards from step 150; a local-linear-trend Kalman filter follows it as the readings arrive:
from sequential_analysis.plotting import plot_filter
from sequential_analysis.procedures import KalmanFilter
from sequential_analysis.smoothing import kalman_smoother
rnd = random.Random(5)
level = [0.5 * (1 + (t > 150) * (t - 150) / 100) for t in range(300)]
readings = [v + rnd.gauss(0.0, 0.1) for v in level]
model = KalmanFilter.local_linear_trend(level_noise=1e-5, slope_noise=1e-6, observation_noise=0.01)
filtered = Recorder()
run_sync(Run(model, consumers=[filtered]), from_values("y", readings))
smoothed = kalman_smoother(model, [{"y": y} for y in readings])
print(f"level at the end: filtered {filtered.outputs[-1].mean[0]:.3f}, true {level[-1]:.3f}")
ax = plot_filter(filtered, observations=readings, truth=level, smoothed=smoothed)

The smoothed line uses the readings that came later, too. It finds the start of the drift that the filter could see only afterwards.
6. How long will it run? Stopping times of a plan¶
planning.simulate runs a procedure many times on simulated data.
plot_stopping_times draws the share of runs stopped by each sample
size. The curve ends at the power, since runs that never stopped do not
count. kind="hist" draws a histogram of the stopping times instead.
from sequential_analysis.planning import simulate
from sequential_analysis.plotting import plot_stopping_times
plan = simulate(lambda: TMixtureSPRT(theta0=0.0, effect=0.5, alpha=0.05),
lambda rnd: {"x": rnd.gauss(0.2, 1.0)}, runs=300, max_n=300)
print(f"power within 300 observations: {plan.power:.2f}, median {plan.median_n:.0f}")
ax = plot_stopping_times(plan)

A plain list of stopping times works as well.
Several plots in one figure¶
With ax=, the plots go wherever you like, and are styled further with
matplotlib as usual:
import matplotlib.pyplot as plt
fig, (left, right) = plt.subplots(1, 2, figsize=(10, 3.6), sharex=True)
plot_e_process(interval, alpha=0.05, ax=left)
plot_confidence_sequence(interval, truth=0.3, ax=right)
left.set_title("evidence against mean 0")
right.set_title("95% confidence sequence for the mean")
fig.tight_layout()
print("panels:", [ax.get_title() for ax in fig.axes])

The pictures on this page are made by running its code:
python tools/make_plots.py.
Reference¶
Plots of runs, designs and plans, with matplotlib.
pip install "sequential-analysis[plot]"
Every function draws on a matplotlib Axes and returns it: pass ax= to
draw into a figure of your own, or leave it out for a new figure. None
of them calls plt.show() or saves anything; that is up to the caller
(ax.figure.savefig("run.png")).
plot_e_process evidence against H0 (e-value, log scale), 1/alpha and the stop plot_confidence_sequence the confidence sequence as a band, with the estimate plot_group_sequential_design efficacy and futility boundaries, and an observed path plot_detection a change detector's statistic, its threshold and the alarm plot_filter a filter's mean with a +-2 sd band (and a smoother's) plot_stopping_times the distribution of stopping times from planning.simulate
The outputs of a run are accepted in any of the forms the library
produces them: a Recorder, a list of OutputEvents, a list of
outputs, or the (state, output) pairs of trajectory.
matplotlib is an optional dependency, imported only when a function is called: importing this module works without it.
plot_e_process(outputs, *, alpha=None, field=None, ax=None)
¶
The e-value of a test against the number of observations, on a log scale.
The e-value is exp of the output's log e-value field, found
automatically (log_e_value, log_lambda, log_bf, log_evidence,
log_wealth) or named by field. With alpha the rejection threshold
1/alpha is drawn; the first output with a decision is marked.
For MultipleTests every test's e-value is drawn (or only the test
named by field), with the e-BH thresholds K/alpha (the first
rejection) and 1/alpha (all K), and each test marked where e-BH first
rejects it.
The y axis is log10 of the e-value (ticks labelled 1, 10, 100, ...), so that runs of any length stay readable without overflow.
plot_confidence_sequence(outputs, *, estimate=None, truth=None, ax=None)
¶
The confidence sequence (lower, upper) as a band against the number of observations.
estimate: None finds the estimate field (estimate, mean, rate_ratio,
hazard_ratio_estimate, difference, or the one coefficient of an
AnytimeLinearModel's estimates), a str names it, False leaves the line
out. truth draws the true value as a reference line.
A bound that is None or infinite (an unbounded start) leaves a gap; the band is drawn where both bounds are finite. The y range leaves out the first, very wide part of the band when that would flatten the rest.
plot_group_sequential_design(design, *, observed=None, scale='z', ax=None)
¶
Efficacy (and futility) boundaries of a group sequential design against information fraction.
design is a GroupSequentialDesign. scale: "z" the standardised
statistic Z_k (the default), "score" B_k = Z_k sqrt(t_k), "p" the
nominal p-value 1 - Phi(Z_k) (two-sided: 2 (1 - Phi(|Z_k|))), on a log
scale. Infinite boundaries (no alpha spent at an analysis) are left out.
observed adds the path of a trial: a sequence of Z values for the
first analyses, or the outputs of a GroupSequentialTest run (any of
the forms plot_e_process takes), from which the analyses are taken
and the decision, if any, is marked. (With an estimated variance the
run's statistic is a t statistic, drawn against the Z boundaries.)
The regions where the trial stops are shaded.
plot_detection(outputs, *, threshold=None, change_point=None, field=None, ax=None)
¶
A change detector's statistic against the number of observations, with the threshold and the alarm.
CUSUM: W_n and its threshold h on a linear scale. Shiryaev-Roberts
(log_statistic) and the e-detectors (statistic with change_estimate):
R_n or M_t on a log scale, with threshold the A or arl given to
the procedure. BayesianChangePoint: the probability of a change within
the alarm window, against alarm_probability. field names another
statistic, drawn on a linear scale.
The first alarm is marked; an e-detector's estimate of where the
change began is drawn at it, and change_point (the true change, when
known) as a reference line.
plot_filter(outputs, *, observations=None, truth=None, component=0, smoothed=None, ax=None)
¶
A filter's mean with a band of +-2 standard deviations, against the number of observations.
Works for the Kalman filters (KalmanFilter, RobustKalmanFilter,
LocalLevelKalman) and the particle filters; for a vector state,
component picks the coordinate. observations are drawn as dots,
truth (a number or one value per step) as a reference line, and
smoothed -- a KalmanSmoothing from smoothing.kalman_smoother over
the same inputs -- as a second line and band.
The y range leaves out the first, very wide part of a band that starts from a vague prior.
plot_stopping_times(summary_or_samples, *, kind='ecdf', ax=None)
¶
The distribution of the stopping time, from planning.simulate or a list of stopping times.
kind="ecdf" (the default): the fraction of ALL runs stopped by n, a step function that ends at the power (runs that did not stop within max_n never count), with the median marked. kind="hist": a histogram of the stopping times of the runs that stopped.