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.
- Solves
- Change-point detection
- Time
- Θ(n) worst
- Space
- Θ(1) extra
- Where
- n = the number of observations read before the alarm or the end of the stream
- Model
- Real RAM
- Properties
- deterministiconlineoptimal for lorden criterioniterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- E. S. Page, 1954
The CUSUM procedure watches a stream of observations for a change from a known density to a known density . It adds the log likelihood ratio 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 . The clipped sum equals the largest log likelihood ratio of "the change happened at time " over all possible , 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 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 arrive one at a time. Before an unknown time they are i.i.d. with density ; from time on they are i.i.d. with density , and means no change. Both densities are known. Find a stopping time , an alarm that may use only , such that the false alarm run length is at least a given and the detection delay after a change is small. The usual measure of delay is Lorden's worst case
See change-point detection for the other formulations.
The algorithm
CUSUM(z_1, z_2, ..., h) ▷ z_t = log f_1(x_t) - log f_0(x_t), threshold h > 0- 1
S ← 0, k ← 1, t ← 0 - 2
for each new z do - 3
t ← t + 1 - 4
S ← S + z - 5
if S ≤ 0 then S ← 0, k ← t + 1 ▷ no evidence of a change up to now - 6
if S ≥ h then return (alarm at t, change estimate k) - 7
return 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 is then no more likely than no change at all, so the best guess of the change moves to . Line L6 sounds the alarm. The statistic after line L5 satisfies
where the empty sum for is 0. The sum is the log likelihood ratio of "the change happened at time " against "no change by time ". So is the generalized likelihood ratio statistic for a change, and is a maximizer.
For a shift in a normal mean from to with variance , . Quality control charts often drop the factor and use the reference value and a threshold on the scale of .
Example
In-control data are and the planned shift is to , so . With :
| 1 | 2 | 3 | 4 | 5 | 6 | |
|---|---|---|---|---|---|---|
| 0.3 | 0.2 | 1.4 | 0.9 | 1.6 | ||
| 0.9 | 0.4 | 1.1 | ||||
| 0 | 0 | 0 | 0.9 | 1.3 | 2.4 | |
| 2 | 3 | 4 | 4 | 4 | 4 |
The alarm sounds at , and the change is estimated to have happened at . Check: the sums for are 0.8, 1.0, 2.1, 2.4, 1.5, 1.1 and 0, and the largest is 2.4 at .
The threshold sets the trade-off. A Monte Carlo simulation of the average run length to a false alarm, , and of the average delay when the change is at the start, , gave these values:
| 2 | 3 | 4 | 5 | |
|---|---|---|---|---|
| , a proved lower bound for | 7.39 | 20.1 | 54.6 | 148.4 |
| , simulated | 37.3 | 121.7 | 330.0 | 913.7 |
| , simulated | 4.41 | 6.28 | 8.44 | 10.29 |
| 4 | 6 | 8 | 10 |
The false alarm run length grows like , and the delay grows like divided by the Kullback-Leibler divergence . So the delay grows only like the logarithm of the false alarm run length.
Correctness
The proof is in full below. In outline:
- The recursion is the maximum over change times. By induction on : . The variable is the largest maximizer: it moves to exactly when every sum ending at is at most 0.
- False alarms. Let , the Shiryaev-Roberts statistic. Under no change, is a martingale, and at an alarm . Optional stopping and Fatou's lemma give .
- 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 , and . Since , the alarm comes no later than the first time the plain sum reaches , and Wald's equation gives .
- Optimality. Lorden (1971) proved that every rule with has as . By facts 2 and 3, the CUSUM with attains this. Moustakides (1986) proved that, with chosen so that , the CUSUM minimizes exactly among all rules with . 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 , the threshold is , is the value of after line L5 at time , is the value of at that point, and is the alarm time. Write , with . Under the observations have density and have density , all independent; means no change. We assume that and have the same support, so that every is finite, and that is finite and positive.
Lemma 1 (the recursion is the maximum over change times). For every ,
and is the largest in at which the maximum is attained.
Proof. By induction on . For , line L1 sets and , the only index. Let and assume the claim for . Lines L4 and L5 give . Since for ,
For the index: if , then every with is at most 0, so attains the maximum and it is the largest index; line L5 sets . If , then does not attain the maximum, and attains it for exactly when attains . By the induction hypothesis the largest such is , and line L5 leaves unchanged.
Corollary (what the procedure returns). Line L6 returns at the first with , which is , and the returned maximizes , the log likelihood ratio of a change at time against no change, given . If no score reaches , 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). .
Proof. If there is nothing to prove, so assume ; then almost surely. Define the Shiryaev-Roberts statistic and
Under , is independent of and . So , and is a martingale with . The stopped process is a martingale for each fixed , so . As , almost surely, and Fatou's lemma, which applies because , gives .
At the alarm, , so by Lemma 1 the maximum is attained at some , and . Hence .
Lemma 3 (monotone in the start). Run the recursion on the same scores from two start values . Then the two statistics satisfy for all , so the alarm from comes no later than the alarm from .
Proof. The map is nondecreasing for each . Induction on gives the inequality, and the first time also has .
Lemma 4 (worst-case delay). , where is Lorden's worst-case delay defined on the page.
Proof. Fix and the pre-change data . If , then . Otherwise the alarm has not sounded by time , and from time on the statistic follows the recursion from the start value , driven by scores that are i.i.d. under , with the same law as under . So is at most the alarm time of the recursion started at , and by Lemma 3 this is at most the alarm time of the recursion started at 0. Its conditional expectation is at most . Hence . The case gives equality, since then there are no pre-change data and the delay is itself.
Lemma 5 (bound on the delay). Let . Then , and
Proof. By Lemma 1, for every , so and . Under , is a random walk with i.i.d. increments of mean . Then : by the strong law of large numbers almost surely, and the standard renewal argument for a random walk with positive drift gives a finite mean. The time is a stopping time for , so Wald's equation gives . Write , where the second term is the overshoot, which is nonnegative.
Theorem. The procedure returns the first time at which the maximum log likelihood ratio over change times reaches , together with a maximizing change time. Its false alarm run length satisfies , and its worst-case delay satisfies . In particular, for a target run length , the choice gives and a worst-case delay of 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.
What is cited. Lorden (1971) proved that every stopping time with has as , 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 , one addition and two comparisons, so time for observations and extra space. Tracking the change estimate 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 against with lower threshold 0 and upper threshold , restarted at every acceptance of . This is Page's original description.
- Logarithmic delay. For a false alarm run length the delay is about , 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 . 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 with half the shift to detect, and the threshold is in units of . This is the same chart with scaled.
- Unknown post-change parameter. The generalized likelihood ratio procedure maximizes over the post-change parameter as well as over . It is not recursive and costs more per step, unless the window of 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 by the sum, . 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 . If the in-control variance is underestimated, false alarms come far sooner than planned.
- Dependent data. Autocorrelation in the in-control data makes drift up more often and shortens the false alarm run length. Fit a time series model and monitor its residuals instead.
- Reading as the run length. It is only a lower bound. In the example, is about 5 to 6 times . Compute the run length by simulation, by a Markov chain approximation, or from tables, and set 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.
# 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
- 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
- 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag ST2SET Edit this page History Report an error Markdown