Algorithm Search⌘K

Algorithmcore

CUSUM

Also called Page's CUSUM, cumulative sum control chart.

Page's online detector that sums log likelihood ratios, clips the sum at zero and alarms above a threshold. Lorden proved it asymptotically optimal, Moustakides exactly optimal.

Time
Θ(n) worst
Space
Θ(1) extra
Where
n = the number of observations read before the alarm or the end of the stream
Properties
deterministiconlineoptimal for lorden criterioniterative
Origin
E. S. Page, 1954

The CUSUM procedure watches a stream of observations for a change from a known density f0f_0 to a known density f1f_1. It adds the log likelihood ratio Zt=log⁡f1(xt)−log⁡f0(xt)Z_t = \log f_1(x_t) - \log f_0(x_t) of each new observation to a running sum, sets the sum back to 0 whenever it goes below 0, and raises an alarm when the sum reaches a threshold hh. The clipped sum equals the largest log likelihood ratio of "the change happened at time kk" over all possible kk, so the procedure is the online form of the maximum likelihood test for a change at an unknown time, and the time of the last reset estimates the change. It costs O(1)O(1) time and memory per observation. Page proposed it in 1954 for quality control. Lorden (1971) proved that it is asymptotically optimal for the worst-case detection delay at a given false alarm rate, and Moustakides (1986) proved that it is exactly optimal.

In plain words

A machine is supposed to fill bottles with one litre. Each bottle that comes out a bit light adds a little to a score; each bottle that comes out a bit heavy takes a little away. The score can never go below zero. While the machine is fine, light and heavy bottles balance, and the score keeps returning to zero. After the machine starts to underfill, the score climbs steadily. When it passes a line you chose, you stop the machine. A high line gives few false stops but a later alarm. A low line gives a quick alarm but more false stops. The last time the score was at zero is a good guess of when the problem started.

The problem

Observations x1,x2,…x_1, x_2, \ldots arrive one at a time. Before an unknown time ν\nu they are i.i.d. with density f0f_0; from time ν\nu on they are i.i.d. with density f1f_1, and ν=∞\nu = \infty means no change. Both densities are known. Find a stopping time TT, an alarm that may use only x1,…,xTx_1, \ldots, x_T, such that the false alarm run length E∞[T]E_\infty[T] is at least a given γ\gamma and the detection delay after a change is small. The usual measure of delay is Lorden's worst case

dˉ(T)=sup⁡ν≥1ess sup⁡Eν[(T−ν+1)+∣x1,…,xν−1].\bar d(T) = \sup_{\nu \ge 1}\operatorname{ess\,sup} E_\nu\bigl[(T - \nu + 1)^+ \mid x_1, \ldots, x_{\nu-1}\bigr].

See change-point detection for the other formulations.

The algorithm

  1. CUSUM(z_1, z_2, ..., h) ▷ z_t = log f_1(x_t) - log f_0(x_t), threshold h > 0
  2. 1S ← 0, k ← 1, t ← 0
  3. 2for each new z do
  4. 3t ← t + 1
  5. 4S ← S + z
  6. 5if S ≤ 0 then S ← 0, k ← t + 1 ▷ no evidence of a change up to now
  7. 6if S ≥ h then return (alarm at t, change estimate k)
  8. 7return no alarm

Line L4 adds the evidence of the new observation. Line L5 drops all evidence when the sum is not positive: a change before time t+1t + 1 is then no more likely than no change at all, so the best guess of the change moves to t+1t + 1. Line L6 sounds the alarm. The statistic StS_t after line L5 satisfies

St=max⁡(0,St−1+Zt)=max⁡1≤k≤t+1∑i=ktZi,S_t = \max(0, S_{t-1} + Z_t) = \max_{1 \le k \le t+1}\sum_{i=k}^{t} Z_i,

where the empty sum for k=t+1k = t + 1 is 0. The sum ∑i=ktZi\sum_{i=k}^t Z_i is the log likelihood ratio of "the change happened at time kk" against "no change by time tt". So StS_t is the generalized likelihood ratio statistic for a change, and kk is a maximizer.

For a shift in a normal mean from μ0\mu_0 to μ1\mu_1 with variance σ2\sigma^2, Zt=μ1−μ0σ2(xt−μ0+μ12)Z_t = \frac{\mu_1 - \mu_0}{\sigma^2}\bigl(x_t - \frac{\mu_0 + \mu_1}{2}\bigr). Quality control charts often drop the factor and use the reference value (μ0+μ1)/2(\mu_0 + \mu_1)/2 and a threshold on the scale of xx.

Example

In-control data are N(0,1)N(0, 1) and the planned shift is to N(1,1)N(1, 1), so Zt=xt−0.5Z_t = x_t - 0.5. With h=2h = 2:

tt 1 2 3 4 5 6
xtx_t 0.3 −0.6-0.6 0.2 1.4 0.9 1.6
ZtZ_t −0.2-0.2 −1.1-1.1 −0.3-0.3 0.9 0.4 1.1
StS_t 0 0 0 0.9 1.3 2.4
kk 2 3 4 4 4 4

The alarm sounds at t=6t = 6, and the change is estimated to have happened at k=4k = 4. Check: the sums ∑i=k6Zi\sum_{i=k}^6 Z_i for k=1,…,7k = 1, \ldots, 7 are 0.8, 1.0, 2.1, 2.4, 1.5, 1.1 and 0, and the largest is 2.4 at k=4k = 4.

The threshold sets the trade-off. A Monte Carlo simulation of the average run length to a false alarm, E∞[T]E_\infty[T], and of the average delay when the change is at the start, E1[T]E_1[T], gave these values:

hh 2 3 4 5
ehe^h, a proved lower bound for E∞[T]E_\infty[T] 7.39 20.1 54.6 148.4
E∞[T]E_\infty[T], simulated 37.3 121.7 330.0 913.7
E1[T]E_1[T], simulated 4.41 6.28 8.44 10.29
h/D(f1 ∥ f0)=2hh / D(f_1 \,\|\, f_0) = 2h 4 6 8 10

The false alarm run length grows like ehe^h, and the delay grows like hh divided by the Kullback-Leibler divergence D(f1 ∥ f0)=1/2D(f_1 \,\|\, f_0) = 1/2. So the delay grows only like the logarithm of the false alarm run length.

Correctness

The proof is in full below. In outline:

  1. The recursion is the maximum over change times. By induction on tt: max⁡(0,St−1+Zt)=max⁡(0,max⁡k≤t∑i=kt−1Zi+Zt)=max⁡k≤t+1∑i=ktZi\max(0, S_{t-1} + Z_t) = \max\bigl(0, \max_{k \le t}\sum_{i=k}^{t-1} Z_i + Z_t\bigr) = \max_{k \le t+1}\sum_{i=k}^t Z_i. The variable kk is the largest maximizer: it moves to t+1t + 1 exactly when every sum ending at tt is at most 0.
  2. False alarms. Let Rt=∑k=1t∏i=kteZiR_t = \sum_{k=1}^t \prod_{i=k}^t e^{Z_i}, the Shiryaev-Roberts statistic. Under no change, Rt−tR_t - t is a martingale, and at an alarm RT≥eST≥ehR_T \ge e^{S_T} \ge e^h. Optional stopping and Fatou's lemma give E∞[T]≥ehE_\infty[T] \ge e^h.
  3. Delay. If the statistic starts higher, it stays higher at every later time, so the worst case in Lorden's criterion is a change that meets S=0S = 0, and dˉ(T)=E1[T]\bar d(T) = E_1[T]. Since St≥∑i≤tZiS_t \ge \sum_{i \le t} Z_i, the alarm comes no later than the first time the plain sum reaches hh, and Wald's equation gives E1[T]≤(h+E[overshoot])/D(f1 ∥ f0)E_1[T] \le (h + E[\text{overshoot}])/D(f_1 \,\|\, f_0).
  4. Optimality. Lorden (1971) proved that every rule with E∞[T]≥γE_\infty[T] \ge \gamma has dˉ(T)≥(1+o(1))log⁡γ/D(f1 ∥ f0)\bar d(T) \ge (1 + o(1))\log\gamma / D(f_1 \,\|\, f_0) as γ→∞\gamma \to \infty. By facts 2 and 3, the CUSUM with h=log⁡γh = \log\gamma attains this. Moustakides (1986) proved that, with hh chosen so that E∞[T]=γE_\infty[T] = \gamma, the CUSUM minimizes dˉ\bar d exactly among all rules with E∞[T]≥γE_\infty[T] \ge \gamma. These two theorems are cited here, not proved.
Proof: The CUSUM statistic is the maximum log likelihood ratio over change times, its false alarm run length is at least e^h, and its worst-case delay is E_1[T]full

Notation is that of the page. The scores are Zt=log⁡f1(xt)−log⁡f0(xt)Z_t = \log f_1(x_t) - \log f_0(x_t), the threshold is h>0h > 0, StS_t is the value of SS after line L5 at time tt, ktk_t is the value of kk at that point, and T=inf⁡{t:St≥h}T = \inf\{t : S_t \ge h\} is the alarm time. Write Λk,t=∑i=ktZi\Lambda_{k,t} = \sum_{i=k}^{t} Z_i, with Λt+1,t=0\Lambda_{t+1,t} = 0. Under PνP_\nu the observations x1,…,xν−1x_1, \ldots, x_{\nu-1} have density f0f_0 and xν,xν+1,…x_\nu, x_{\nu+1}, \ldots have density f1f_1, all independent; P∞P_\infty means no change. We assume that f0f_0 and f1f_1 have the same support, so that every ZtZ_t is finite, and that D=D(f1 ∥ f0)=E1[Z1]D = D(f_1 \,\|\, f_0) = E_1[Z_1] is finite and positive.

Lemma 1 (the recursion is the maximum over change times). For every t≥0t \ge 0,

St=max⁡1≤k≤t+1Λk,t,S_t = \max_{1 \le k \le t+1}\Lambda_{k,t},

and ktk_t is the largest kk in {1,…,t+1}\{1, \ldots, t+1\} at which the maximum is attained.

Proof. By induction on tt. For t=0t = 0, line L1 sets S0=0=Λ1,0S_0 = 0 = \Lambda_{1,0} and k0=1k_0 = 1, the only index. Let t≥1t \ge 1 and assume the claim for t−1t - 1. Lines L4 and L5 give St=max⁡(0,St−1+Zt)S_t = \max(0, S_{t-1} + Z_t). Since Λk,t=Λk,t−1+Zt\Lambda_{k,t} = \Lambda_{k,t-1} + Z_t for k≤tk \le t,

max⁡1≤k≤t+1Λk,t=max⁡(max⁡1≤k≤tΛk,t−1+Zt, Λt+1,t)=max⁡(St−1+Zt, 0)=St.\max_{1 \le k \le t+1}\Lambda_{k,t} = \max\Bigl(\max_{1 \le k \le t}\Lambda_{k,t-1} + Z_t,\ \Lambda_{t+1,t}\Bigr) = \max(S_{t-1} + Z_t,\ 0) = S_t.

For the index: if St−1+Zt≤0S_{t-1} + Z_t \le 0, then every Λk,t\Lambda_{k,t} with k≤tk \le t is at most 0, so k=t+1k = t + 1 attains the maximum and it is the largest index; line L5 sets kt=t+1k_t = t + 1. If St−1+Zt>0S_{t-1} + Z_t > 0, then k=t+1k = t + 1 does not attain the maximum, and Λk,t=Λk,t−1+Zt\Lambda_{k,t} = \Lambda_{k,t-1} + Z_t attains it for k≤tk \le t exactly when Λk,t−1\Lambda_{k,t-1} attains St−1S_{t-1}. By the induction hypothesis the largest such kk is kt−1k_{t-1}, and line L5 leaves kk unchanged. □\square

Corollary (what the procedure returns). Line L6 returns at the first tt with St≥hS_t \ge h, which is TT, and the returned kk maximizes Λk,T\Lambda_{k,T}, the log likelihood ratio of a change at time kk against no change, given x1,…,xTx_1, \ldots, x_T. If no score reaches hh, line L7 is reached when the input ends. Each pass of the loop does a constant number of operations.

Lemma 2 (false alarm run length). E∞[T]≥ehE_\infty[T] \ge e^h.

Proof. If E∞[T]=∞E_\infty[T] = \infty there is nothing to prove, so assume E∞[T]<∞E_\infty[T] < \infty; then T<∞T < \infty almost surely. Define the Shiryaev-Roberts statistic R0=0R_0 = 0 and

Rt=∑k=1teΛk,t=(1+Rt−1)eZt.R_t = \sum_{k=1}^{t}e^{\Lambda_{k,t}} = (1 + R_{t-1})e^{Z_t}.

Under P∞P_\infty, ZtZ_t is independent of x1,…,xt−1x_1, \ldots, x_{t-1} and E∞[eZt]=∫f1=1E_\infty[e^{Z_t}] = \int f_1 = 1. So E∞[Rt∣x1,…,xt−1]=1+Rt−1E_\infty[R_t \mid x_1, \ldots, x_{t-1}] = 1 + R_{t-1}, and Mt=Rt−tM_t = R_t - t is a martingale with M0=0M_0 = 0. The stopped process MT∧nM_{T \wedge n} is a martingale for each fixed nn, so E∞[RT∧n]=E∞[T∧n]≤E∞[T]E_\infty[R_{T \wedge n}] = E_\infty[T \wedge n] \le E_\infty[T]. As n→∞n \to \infty, RT∧n→RTR_{T \wedge n} \to R_T almost surely, and Fatou's lemma, which applies because Rt≥0R_t \ge 0, gives E∞[RT]≤E∞[T]E_\infty[R_T] \le E_\infty[T].

At the alarm, ST≥h>0S_T \ge h > 0, so by Lemma 1 the maximum is attained at some k≤Tk \le T, and RT≥eΛk,T=eST≥ehR_T \ge e^{\Lambda_{k,T}} = e^{S_T} \ge e^h. Hence eh≤E∞[RT]≤E∞[T]e^h \le E_\infty[R_T] \le E_\infty[T]. □\square

Lemma 3 (monotone in the start). Run the recursion S′=max⁡(0,S′+Z)S' = \max(0, S' + Z) on the same scores from two start values 0≤a≤a′0 \le a \le a'. Then the two statistics satisfy St(a)≤St(a′)S_t(a) \le S_t(a') for all tt, so the alarm from a′a' comes no later than the alarm from aa.

Proof. The map s↦max⁡(0,s+z)s \mapsto \max(0, s + z) is nondecreasing for each zz. Induction on tt gives the inequality, and the first time St(a)≥hS_t(a) \ge h also has St(a′)≥hS_t(a') \ge h. □\square

Lemma 4 (worst-case delay). dˉ(T)=E1[T]\bar d(T) = E_1[T], where dˉ\bar d is Lorden's worst-case delay defined on the page.

Proof. Fix ν≥1\nu \ge 1 and the pre-change data x1,…,xν−1x_1, \ldots, x_{\nu-1}. If T≤ν−1T \le \nu - 1, then (T−ν+1)+=0(T - \nu + 1)^+ = 0. Otherwise the alarm has not sounded by time ν−1\nu - 1, and from time ν\nu on the statistic follows the recursion from the start value a=Sν−1≥0a = S_{\nu-1} \ge 0, driven by scores that are i.i.d. under f1f_1, with the same law as Z1,Z2,…Z_1, Z_2, \ldots under P1P_1. So (T−ν+1)+(T - \nu + 1)^+ is at most the alarm time of the recursion started at aa, and by Lemma 3 this is at most the alarm time T(0)T^{(0)} of the recursion started at 0. Its conditional expectation is at most E1[T(0)]=E1[T]E_1[T^{(0)}] = E_1[T]. Hence dˉ(T)≤E1[T]\bar d(T) \le E_1[T]. The case ν=1\nu = 1 gives equality, since then there are no pre-change data and the delay is TT itself. □\square

Lemma 5 (bound on the delay). Let τ=inf⁡{t:Λ1,t≥h}\tau = \inf\{t : \Lambda_{1,t} \ge h\}. Then T≤τT \le \tau, and

E1[T]≤E1[τ]=h+E1[Λ1,τ−h]D.E_1[T] \le E_1[\tau] = \frac{h + E_1[\Lambda_{1,\tau} - h]}{D}.

Proof. By Lemma 1, St≥Λ1,tS_t \ge \Lambda_{1,t} for every tt, so Sτ≥hS_\tau \ge h and T≤τT \le \tau. Under P1P_1, Λ1,t\Lambda_{1,t} is a random walk with i.i.d. increments of mean D>0D > 0. Then E1[τ]<∞E_1[\tau] < \infty: by the strong law of large numbers τ<∞\tau < \infty almost surely, and the standard renewal argument for a random walk with positive drift gives a finite mean. The time τ\tau is a stopping time for x1,x2,…x_1, x_2, \ldots, so Wald's equation gives E1[Λ1,τ]=D E1[τ]E_1[\Lambda_{1,\tau}] = D\,E_1[\tau]. Write Λ1,τ=h+(Λ1,τ−h)\Lambda_{1,\tau} = h + (\Lambda_{1,\tau} - h), where the second term is the overshoot, which is nonnegative. □\square

Theorem. The procedure returns the first time TT at which the maximum log likelihood ratio over change times reaches hh, together with a maximizing change time. Its false alarm run length satisfies E∞[T]≥ehE_\infty[T] \ge e^h, and its worst-case delay satisfies dˉ(T)=E1[T]≤(h+E1[overshoot])/D\bar d(T) = E_1[T] \le (h + E_1[\text{overshoot}])/D. In particular, for a target run length γ\gamma, the choice h=log⁡γh = \log\gamma gives E∞[T]≥γE_\infty[T] \ge \gamma and a worst-case delay of (log⁡γ)/D(\log\gamma)/D plus a term that stays bounded when the overshoot has a bounded mean.

Proof. The first sentence is the Corollary. The bounds are Lemmas 2, 4 and 5. ■\blacksquare

What is cited. Lorden (1971) proved that every stopping time with E∞[T]≥γE_\infty[T] \ge \gamma has dˉ(T)≥(1+o(1))(log⁡γ)/D\bar d(T) \ge (1 + o(1))(\log\gamma)/D as γ→∞\gamma \to \infty, so the Theorem shows that the CUSUM is first-order optimal. Moustakides (1986) proved exact optimality. Neither result is proved here.

Complexity

Each observation costs one evaluation of ZtZ_t, one addition and two comparisons, so Θ(n)\Theta(n) time for nn observations and Θ(1)\Theta(1) extra space. Tracking the change estimate kk costs nothing extra. The two-sided chart runs two CUSUMs, one for an increase and one for a decrease, and doubles the constant.

Properties

  • Online and constant memory. The statistic is a function of the previous statistic and the new observation only.
  • Repeated SPRT. The CUSUM is a sequence of SPRTs of f0f_0 against f1f_1 with lower threshold 0 and upper threshold hh, restarted at every acceptance of f0f_0. This is Page's original description.
  • Logarithmic delay. For a false alarm run length γ\gamma the delay is about log⁡γ/D(f1 ∥ f0)\log\gamma / D(f_1 \,\|\, f_0), the best possible to first order.
  • Built-in change estimate. The time of the last reset is the maximum likelihood estimate of the change time given the alarm.
  • Tuned to one alternative. The procedure is optimal for the planned f1f_1. For a smaller shift the delay grows, and for a larger one it is not as short as a chart tuned to that shift.

Variants and improvements

  • Two-sided CUSUM. Run one chart for an increase and one for a decrease, and alarm when either crosses.
  • Tabular CUSUM with a reference value. In quality control the increment is xt−μ0−Kx_t - \mu_0 - K with KK half the shift to detect, and the threshold HH is in units of xx. This is the same chart with ZtZ_t scaled.
  • Unknown post-change parameter. The generalized likelihood ratio procedure maximizes over the post-change parameter as well as over kk. It is not recursive and costs more per step, unless the window of kk is limited. A mixture over the post-change parameter gives a statistic in the spirit of the mixture SPRT.
  • Shiryaev-Roberts procedure. Replace the maximum over kk by the sum, Rt=(1+Rt−1)eZtR_t = (1 + R_{t-1})e^{Z_t}. It is optimal in a Bayesian limit and nearly optimal for Pollak's criterion (Pollak 1985).
  • Bayesian detection. With a prior on the change time, and possibly several changes, Bayesian online changepoint detection computes the posterior of the time since the last change.
  • Smoothing charts. The EWMA chart, based on an exponential moving average, weighs recent data more. It detects small shifts about as fast but has no likelihood interpretation.
  • Offline segmentation. When the whole series is available and there may be many changes, use PELT or binary segmentation.

When to use it

Use the CUSUM when observations arrive online, the in-control law is known or well estimated, and there is a specific change worth detecting, such as a planned shift in the mean of a process. It is the standard tool for statistical process control of small persistent shifts, and it is used in signal detection and in surveillance of health outcomes. Use the Bayesian detector when there are many changes and unknown parameters, and an offline method when the whole series is available.

Pitfalls

  • Wrong pre-change model. The false alarm run length depends strongly on f0f_0. If the in-control variance is underestimated, false alarms come far sooner than planned.
  • Dependent data. Autocorrelation in the in-control data makes StS_t drift up more often and shortens the false alarm run length. Fit a time series model and monitor its residuals instead.
  • Reading ehe^h as the run length. It is only a lower bound. In the example, E∞[T]E_\infty[T] is about 5 to 6 times ehe^h. Compute the run length by simulation, by a Markov chain approximation, or from tables, and set hh from it.
  • Not resetting after an alarm. After an alarm and a repair the chart should restart at 0; otherwise the old evidence triggers a second alarm at once.
  • Estimated parameters treated as known. A chart built from a short phase I sample has a random false alarm run length, often much shorter than the nominal one.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

cusum.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cusum/. The authors are listed in prov/ST2SET.jsonl.
"""Page's CUSUM procedure for online change detection.

Before the change the observations have density f0, after it f1. With the
log likelihood ratio increments Z_t = log f1(x_t) - log f0(x_t), the CUSUM
statistic is S_0 = 0, S_t = max(0, S_(t-1) + Z_t). It equals the largest log
likelihood ratio of "the change happened at time k" over k = 1, ..., t + 1
(k = t + 1 means no change yet). An alarm sounds at the first t with S_t >= h.

Cost O(1) time and O(1) memory per observation.
"""

import math
from collections.abc import Callable, Iterable


def cusum_scores(zs: Iterable[float], h: float) -> tuple[int | None, int | None, list[float]]:
    """Run CUSUM on given increments. Returns (alarm time, change estimate, statistics).

    The alarm time is the first t (1-based) with S_t >= h, or None. The change
    estimate is the first index of the maximizing segment, that is the time of
    the last reset plus 1. Precondition: h > 0.
    """
    if h <= 0:
        raise ValueError("h must be positive")
    s = 0  # @line L1
    k = 1  # @line L1
    t = 0  # @line L1
    path = []
    for z in zs:  # @line L2
        t += 1  # @line L3
        s = s + z  # @line L4
        if s <= 0:  # @line L5
            s = 0  # @line L5
            k = t + 1  # @line L5
        path.append(s)
        if s >= h:  # @line L6
            return t, k, path  # @line L6
    return None, None, path  # @line L7


def cusum(stream: Iterable[float], log_f0: Callable[[float], float], log_f1: Callable[[float], float],
          h: float) -> tuple[int | None, int | None]:
    """CUSUM on raw observations with known pre-change and post-change log densities."""
    t, k, _ = cusum_scores((log_f1(x) - log_f0(x) for x in stream), h)
    return t, k


def gaussian_mean_shift_scores(xs: Iterable[float], mu0: float, mu1: float, sigma: float) -> list[float]:
    """Z_t for N(mu0, sigma^2) -> N(mu1, sigma^2): (mu1 - mu0) / sigma^2 * (x - (mu0 + mu1) / 2)."""
    d = (mu1 - mu0) / (sigma * sigma)
    m = 0.5 * (mu0 + mu1)
    return [d * (x - m) for x in xs]


def brute_force_statistic(zs: list[float], t: int) -> tuple[float, int]:
    """max over k in 1..t+1 of sum_(i=k)^t z_i, with the largest maximizing k (O(t^2))."""
    best, arg = 0, t + 1
    for k in range(t, 0, -1):
        total = sum(zs[k - 1:t])
        if total > best:
            best, arg = total, k
    return best, arg


def two_sided_gaussian(xs: Iterable[float], mu0: float, delta: float, sigma: float,
                       h: float) -> int | None:
    """Two CUSUMs, for a shift up by delta and down by delta. Returns the first alarm time."""
    up = down = 0.0
    for t, x in enumerate(xs, 1):
        u = (x - mu0) / sigma
        up = max(0.0, up + delta * u - 0.5 * delta * delta)
        down = max(0.0, down - delta * u - 0.5 * delta * delta)
        if up >= h or down >= h:
            return t
    return None


def gaussian_log_density(mu: float, sigma: float) -> Callable[[float], float]:
    c = -math.log(sigma * math.sqrt(2.0 * math.pi))
    return lambda x: c - 0.5 * ((x - mu) / sigma) ** 2
test_cusum.py 105 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cusum/. The authors are listed in prov/ST2SET.jsonl.
import math
import random
from fractions import Fraction

import pytest

from cusum import (
    brute_force_statistic,
    cusum,
    cusum_scores,
    gaussian_log_density,
    gaussian_mean_shift_scores,
    two_sided_gaussian,
)

EXAMPLE = [0.3, -0.6, 0.2, 1.4, 0.9, 1.6]


def test_worked_example():
    zs = gaussian_mean_shift_scores(EXAMPLE, 0.0, 1.0, 1.0)
    t, k, path = cusum_scores(zs, 2.0)
    assert (t, k) == (6, 4)
    assert all(abs(a - b) < 1e-12 for a, b in zip(path, [0, 0, 0, 0.9, 1.3, 2.4]))
    assert cusum(EXAMPLE, gaussian_log_density(0.0, 1.0), gaussian_log_density(1.0, 1.0), 2.0) == (6, 4)


def test_no_alarm_and_empty():
    assert cusum_scores([], 1.0) == (None, None, [])
    t, k, path = cusum_scores([-1, -2, 0, 1], 5)
    assert (t, k) == (None, None) and path == [0, 0, 0, 1]
    with pytest.raises(ValueError):
        cusum_scores([1.0], 0.0)


def test_recursion_equals_maximum_over_change_times_exact():
    rng = random.Random(1954)
    for _ in range(600):
        n = rng.randint(1, 25)
        zs = [Fraction(rng.randint(-6, 6), rng.randint(1, 4)) for _ in range(n)]
        _, _, path = cusum_scores(zs, Fraction(10 ** 9))
        s, k = 0, 1
        for t in range(1, n + 1):
            best, arg = brute_force_statistic(zs, t)
            assert path[t - 1] == best
            s = s + zs[t - 1]
            if s <= 0:
                s, k = 0, t + 1
            assert k == arg


def test_alarm_and_estimate_against_brute_force():
    rng = random.Random(42)
    for _ in range(500):
        n = rng.randint(1, 30)
        zs = [rng.randint(-3, 3) for _ in range(n)]
        h = rng.randint(1, 8)
        t, k, _ = cusum_scores(zs, h)
        want_t = next((u for u in range(1, n + 1) if brute_force_statistic(zs, u)[0] >= h), None)
        assert t == want_t
        if t is not None:
            assert k == brute_force_statistic(zs, t)[1]


def test_false_alarm_rate_above_lorden_bound():
    # Lorden: E_infinity[T] >= e^h for the one-sided CUSUM with the true log likelihood ratio.
    rng = random.Random(9)
    for h in (2.0, 3.0):
        reps = 1500
        total = 0
        for _ in range(reps):
            s, t = 0.0, 0
            while s < h:
                t += 1
                s = max(0.0, s + rng.gauss(0.0, 1.0) - 0.5)
            total += t
        assert total / reps > math.exp(h)


def test_detection_delay_grows_like_h_over_kl():
    rng = random.Random(10)
    delays = []
    for h in (4.0, 8.0):
        reps = 1000
        total = 0
        for _ in range(reps):
            s, t = 0.0, 0
            while s < h:
                t += 1
                s = max(0.0, s + rng.gauss(1.0, 1.0) - 0.5)
            total += t
        delays.append(total / reps)
        # The KL divergence is 1/2, so the delay is h / (1/2) plus a bounded overshoot term.
        assert 2 * h < delays[-1] < 2 * h + 3
    assert delays[1] > delays[0]


def test_two_sided_detects_both_directions():
    rng = random.Random(4)
    up = [rng.gauss(0, 1) for _ in range(50)] + [rng.gauss(2, 1) for _ in range(50)]
    down = [rng.gauss(0, 1) for _ in range(50)] + [rng.gauss(-2, 1) for _ in range(50)]
    for xs in (up, down):
        t = two_sided_gaussian(xs, 0.0, 2.0, 1.0, 5.0)
        assert t is not None and 50 < t <= 60

History

Page (1954) introduced the cumulative sum scheme for continuous inspection of a production process and described it as a sequence of Wald's sequential tests. Lorden (1971) defined the worst-case delay criterion, proved a lower bound for all procedures, and showed that the CUSUM attains it asymptotically as the false alarm run length grows. Moustakides (1986) proved that the CUSUM is exactly optimal for Lorden's criterion. Pollak (1985) studied the Shiryaev-Roberts procedure under a related criterion. Siegmund (1985) gives approximations for the run lengths.

References

  1. E. S. Page, Continuous inspection schemes, Biometrika 41(1/2) (1954), the cumulative sum scheme, its form as a sequence of sequential probability ratio tests, and its average run length
  2. G. Lorden, Procedures for reacting to a change in distribution, Annals of Mathematical Statistics 42(6) (1971), the worst-case delay criterion, the asymptotic lower bound on the delay, and the asymptotic optimality of the CUSUM
  3. George V. Moustakides, Optimal stopping times for detecting changes in distributions, Annals of Statistics 14(4) (1986), the proof that the CUSUM minimizes Lorden's worst-case delay among all rules with the same false alarm run length
  4. David Siegmund, Sequential Analysis, Tests and Confidence Intervals, Springer, 1985, Chapter II (cusum tests as repeated sequential probability ratio tests) and the approximations for the average run length
  5. Moshe Pollak, Optimal detection of a change in distribution, Annals of Statistics 13(1) (1985), the Shiryaev-Roberts statistic and the conditional average delay criterion
  6. Alexander Tartakovsky, Igor Nikiforov and Michèle Basseville, Sequential Analysis, Hypothesis Testing and Changepoint Detection, CRC Press, 2014, the chapters on quickest change detection, the CUSUM and the Shiryaev-Roberts procedures

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example