Skip to content

Design and planning of experiments

sequential_analysis.design

Design of sequential sampling plans: operating characteristics and optimal plans.

Executing a plan is a Sequential Procedure (PlanTest). Computing one is a design problem, solved here offline, before the experiment. Both functions work on the running sum S_n, which is sufficient for the one-parameter exponential families in sequential_analysis.procedures.

The sum is carried on a lattice. For Bernoulli and Poisson data the lattice is the integers and every result is exact up to floating point (the Poisson distribution leaves out terms below 1e-17). For normal data the observation is replaced by its discretisation on a lattice of step h (default sigma/16), and exponential data by the midpoints of cells of width h (default a eighth of the mean at theta*); the error of the operating characteristic is of order h^2, and exact is False in the results. Plans are executed on the real data, so their actual error rates can be checked by simulation, as the tests do.

operating_characteristic Probabilities of each decision, the distribution of the stopping time and its expectation (ASN), by forward recursion over the distribution of S_n.

kiefer_weiss_plan The plan with at most horizon observations that minimises the expected sample size at theta, subject to error probabilities alpha0 at theta0 and alpha1 at theta1 -- the modified Kiefer-Weiss problem (Lorden 1980). With theta at the least favourable point it is the Kiefer-Weiss test, which minimises the maximum expected sample size. Solved by backward induction on the Lagrangian

    E_theta*[N] + lambda0 P_theta0(reject H0) + lambda1 P_theta1(accept H0)

following Novikov, Novikov and Farkhshatov (2022, 2023).  The same
backward pass also yields the error probabilities, written as
expectations under theta* of the likelihood ratios, so adjusting the
multipliers to the targets costs one pass per trial.

Lattice dataclass

X takes the values (offset + i) * step + shift with probabilities weights[i].

After n observations S_n = k * step + n * shift for an integer k.

KieferWeissDesign dataclass

maximum_expected_n(grid=24)

max over theta in [theta0, theta1] of E_theta[N], and where it is attained.

lattice(family, theta, step=None)

The distribution of one observation on the lattice used by the design.

operating_characteristic(plan, family, theta, *, step=None)

Operating characteristic of plan for observations from family at theta.

maximum_expected_n(plan, family, lower, upper, *, step=None, grid=24)

The largest expected sample size of plan for theta between lower and upper, and its argmax.

A grid locates the maximum; golden-section search refines it between the neighbouring grid points.

kiefer_weiss_plan(theta0, theta1, alpha0, alpha1, horizon, *, family=None, theta_star=None, step=None, cache=None)

Optimal plan with at most horizon observations; see the module docstring.

family is Bernoulli (default), Poisson, Gaussian or Exponential. The returned plan never exceeds the horizon and has error probabilities at most alpha0 and alpha1 -- exactly for discrete data, on the lattice for normal data. Raises ValueError if no plan within the horizon can meet them.

theta_star is where the expected sample size is minimised. By default it is the first-order point of Lorden (1976). With theta_star="least-favourable" it solves the Kiefer-Weiss problem itself. By Lorden's characterisation the optimal test is the solution of the modified problem whose expected sample size is largest at theta* itself, the root of g(theta) = argmax_theta E_theta[N] - theta. For normal and exponential data that root is returned, found by the Illinois method from a bracket around the tabulated root (normal data) or over the whole interval; there the maximum of E[N] is too flat in theta* for comparisons between candidates to mean anything. For discrete data the attainable error rates move in steps and g need not have a root: the candidates of a bisection on g, the first-order point included, are compared, and the one with the smallest maximum expected sample size is returned; the gain over the first-order theta* is often a fraction of a percent.

Every plan computed is stored in the design cache and returned from it when the same question is asked again, after its error rates have been verified; cache selects the directory, or False turns the cache off (see sequential_analysis.cache). Saving and loading are reported on the logger "sequential_analysis.cache".

tabulated_least_favourable(alpha0, alpha1, rho)

lambda = (theta* - theta0) / (theta1 - theta0) of the least favourable theta* for normal data, from the table.

rho = delta sqrt(H) / (z_alpha0 + z_alpha1), delta = |theta1 - theta0| / sigma: how much longer the horizon is than the shortest fixed-sample test. The value is the root of Lorden's characterisation (largest expected sample size at theta* itself), fitted to computed roots within about 3e-4 for alpha0, alpha1 in [0.005, 0.2] and rho in [1.5, 2.5]; it hardly depends on rho there, so larger rho use the value at 2.5. Below 1.5, where the horizon nearly binds, the value at 1.5 is returned and may be off by 0.015. None for error rates outside the table. The search for the least favourable theta* uses it only to bracket its root finding.

sequential_analysis.cache

Design cache: optimal plans are computed once and kept on disk.

Computing a Kiefer-Weiss plan takes from a second to hours; executing it takes microseconds per observation. kiefer_weiss_plan therefore stores every plan it computes and returns the stored one when it is asked the same question again.

Where cache= names a directory; otherwise the environment variable SEQUENTIAL_ANALYSIS_CACHE does; otherwise $XDG_CACHE_HOME/sequential-analysis, or ~/.cache/sequential-analysis. cache=False, or SEQUENTIAL_ANALYSIS_CACHE set to "off", turns the cache off. Deleting the directory, or clear_design_cache(), empties it.

What One JSON file per question. Its name is a hash of the question: every argument, the family, the library version and the version of the design algorithm, so a new version of either computes afresh. The file repeats the question in full, with the time the computation took.

Trust A stored plan is not taken on faith. On loading, its operating characteristic is recomputed (a forward pass, cheap next to the design) and must reproduce the stored one and meet the requested error rates within the horizon; otherwise the file is ignored and the plan computed again. An edited, truncated or foreign file can cost time, never the guarantee.

Messages Every save, load, ignored file and failed write is reported on the logger "sequential_analysis.cache" at WARNING level, so it is visible by default, with a structured incident record like the run's incidents. logging.getLogger("sequential_analysis.cache").setLevel(logging.ERROR) silences it. A cache that cannot be written never fails the design.

design_cache_dir(cache=None)

The cache directory selected by cache (see the module docstring), or None if the cache is off.

clear_design_cache(cache=None)

Delete the stored designs; returns how many files were removed.

read_entry(path, key)

The stored record for key, or None (missing, unreadable or for another question: reported).

write_entry(path, key, design, seconds, created_at)

Store atomically; a failure is reported and swallowed (the caller has its design anyway).

sequential_analysis.planning

Planning a sequential experiment: how long will it run, how often will it decide?

A sequential test has no fixed sample size; what is planned is its distribution. simulate runs any procedure on simulated data many times and reports how often it stopped within a budget (the power, or under no effect the false positive rate) and the distribution of the number of units it needed (median, 90th percentile, mean). Everything else in the library -- exact operating characteristics of plans (design), group sequential boundaries -- is computed without simulation; this module covers what has no closed form: the anytime-valid and nonparametric tests, change detectors and A/B tests with their real data shapes.

from sequential_analysis.planning import simulate, conversion_units
from sequential_analysis.procedures import TwoProportionTest

plan = simulate(TwoProportionTest, conversion_units(0.10, 0.12), runs=200, max_n=50_000)
plan.power, plan.median_n, plan.quantile(0.9)

The simulation draws from Python's random module seeded per run, so a plan is reproducible; Monte Carlo error is reported (power_interval, a Wilson interval).

Cost: runs x (units per run) x (cost of a step); a two-proportion plan of 200 runs up to 50,000 users takes seconds.

SimulationSummary dataclass

power property

Fraction of runs that stopped within max_n: the power, or the false positive rate under no effect.

power_interval property

Wilson score interval for power (Monte Carlo error).

mean_n_stopped property

Mean number of units among the runs that stopped (biased low when many did not).

quantile(q)

The q-quantile of the number of units over ALL runs, runs that did not stop counting as max_n + 1.

None when that quantile lies among the runs that did not stop: the budget is too small to say.

simulate(make, draw, *, runs=200, max_n=100000, seed=0, stop=_stopped, level=0.05)

Run make() on draw(rnd) inputs until stop(output) or max_n inputs, runs times.

draw receives the run's random generator and returns one statistical input (a dict). Each run uses random.Random(seed + run).

conversion_units(p_treatment, p_control, allocation=0.5, *, arms=(1, 0))

Users of a 0/1 metric: {"arm", "y"}, treatment with probability allocation.

metric_units(treatment, control, allocation=0.5, *, arms=(1, 0))

Users of any metric: {"arm", "y"}, with y drawn by treatment(rnd) or control(rnd).