Algorithm Search⌘K

Algorithmcore

Binary segmentation

Also called binary segmentation for change points, wild binary segmentation.

Cuts a series at its single best change point, then repeats on each part while the split statistic exceeds a threshold. Cost O(n(m+1)) for m changes, O(n²) in the worst case.

Time
Θ(n(m+1)) worst
Space
Θ(n) extra
Where
m = the number of change points found; n = the length of the series
Properties
deterministicnot exactofflinerecursive
Origin
A. J. Scott, M. Knott, L. Yu. Vostrikova, 1974

Binary segmentation finds several changes in the mean of a series by repeated single splits. It looks at the whole series, finds the one split point that best separates it into two parts with different means, and keeps the split if a test statistic exceeds a threshold ζ\zeta. Then it does the same on each part, and stops on a part when no split is strong enough. With prefix sums each split statistic costs O(1)O(1), so a part of length LL costs O(L)O(L) and the whole run costs O(n(m+1))O(n(m+1)) for mm change points: O(nlog⁡n)O(n \log n) when the splits are balanced and O(n2)O(n^2) in the worst case. It is a greedy method. It does not minimize a global cost, and it can miss short segments that the first split hides. Wild binary segmentation repairs this by also searching random sub-intervals.

In plain words

You have a long record of a measurement and you suspect its average level changed a few times. First you ask: if I could cut the record in exactly one place, where would the two parts differ most? If the difference there is clearly larger than noise, you make the cut. Then you treat each part as a new record and ask the same question. You stop cutting a part when no cut in it gives a clear difference. The method is fast and simple. Its weakness is that it judges each cut alone, so a short burst in the middle of a long flat record can look too small to cut at first, and then it is never found.

The problem

Given x1,…,xnx_1, \ldots, x_n, modelled as a piecewise constant mean plus noise of variance σ2\sigma^2, find the change points 0<τ1<⋯<τm<n0 < \tau_1 < \cdots < \tau_m < n, where τj\tau_j is the last index of segment jj. See change-point detection for the problem and the exact methods.

For a segment xs+1,…,xex_{s+1}, \ldots, x_e and a split s<b<es < b < e, the CUSUM contrast is

C(s,b,e)=(b−s)(e−b)e−s  ∣xˉs+1..b−xˉb+1..e∣,C(s, b, e) = \sqrt{\frac{(b - s)(e - b)}{e - s}}\;\bigl|\bar x_{s+1..b} - \bar x_{b+1..e}\bigr|,

where xˉi..j\bar x_{i..j} is the mean of xi,…,xjx_i, \ldots, x_j. Its square is the drop in the residual sum of squares when the segment is cut at bb. Under no change and Gaussian noise, C(s,b,e)/σC(s, b, e)/\sigma is the absolute value of a standard normal variable for each fixed bb.

The algorithm

  1. BINARY-SEGMENTATION(x_1, ..., x_n, ζ)
  2. 1P ← prefix sums of x; stack ← [(0, n)]; CP ← ∅
  3. 2while stack is not empty do
  4. 3pop (s, e); if e - s < 2 then continue ▷ the segment is x_{s+1..e}
  5. 4b ← the smallest maximizer of C(s, b, e) over s < b < e; c ← C(s, b, e)
  6. 5if c ≤ ζ then continue ▷ no change in this segment
  7. 6add b to CP; push (s, b) and (b, e)
  8. 7return CP in increasing order

Line L4 uses xˉi..j=(Pj−Pi−1)/(j−i+1)\bar x_{i..j} = (P_j - P_{i-1})/(j - i + 1), so each contrast costs O(1)O(1) and the scan costs O(e−s)O(e - s). The stack replaces the recursion; the order in which segments are processed does not change the result. Usual thresholds are ζ=Cσ2log⁡n\zeta = C\sigma\sqrt{2\log n} with a constant CC a little above 1, for example C=1.3C = 1.3 as in Fryzlewicz (2014), with σ\sigma estimated robustly from the differences xi+1−xix_{i+1} - x_i. An alternative is to grow the full tree with a very small ζ\zeta and choose the number of changes by a criterion such as the BIC.

Example

Take n=12n = 12, ζ=1.5\zeta = 1.5 and

x=(0.1,−0.3,0.2,0.0,2.1,1.8,2.2,1.9,2.0,−0.1,0.2,0.1).x = (0.1, -0.3, 0.2, 0.0, 2.1, 1.8, 2.2, 1.9, 2.0, -0.1, 0.2, 0.1).

The contrasts on the whole series, C(0,b,12)C(0, b, 12), rounded to 3 decimals, are:

bb 1 2 3 4 5 6 7 8 9 10 11
C(0,b,12)C(0, b, 12) 0.783 1.472 1.700 2.082 1.259 0.693 0.088 0.735 1.567 1.084 0.783

The best split is b=4b = 4, and 2.082>1.52.082 > 1.5, so 4 is a change point. On the right part (4,12)(4, 12) the contrasts for b=5,…,11b = 5, \ldots, 11 are 0.882, 1.102, 1.661, 2.051, 2.647, 1.837 and 1.256, so 9 is a change point. The remaining parts have best contrasts 0.200 on (0,4)(0, 4) at b=2b = 2, 0.112 on (4,9)(4, 9) and 0.204 on (9,12)(9, 12), all below ζ\zeta. The result is {4,9}\{4, 9\}: means about 0, 2 and 0.

Note that the whole-series contrast at the true change 9 is only 1.567, because the two outer low parts pull the mean of the right side down. The method finds 9 only after the first cut has removed the left part.

Correctness

Binary segmentation is a heuristic: it does not compute an optimal segmentation, and what it returns is defined by the procedure itself. Two facts are proved in full below.

  1. The contrast is the gain of a cut. For every s<b<es < b < e, C(s,b,e)2=RSS(s,e)−RSS(s,b)−RSS(b,e)C(s, b, e)^2 = \mathrm{RSS}(s, e) - \mathrm{RSS}(s, b) - \mathrm{RSS}(b, e), where RSS(i,j)\mathrm{RSS}(i, j) is the residual sum of squares of xi+1,…,xjx_{i+1}, \ldots, x_j about their mean. So line L4 chooses the single cut that best fits a two-mean model to the segment by least squares.
  2. The stack version computes the recursive definition. Define BS(s,e)=∅\mathrm{BS}(s, e) = \emptyset if e−s<2e - s < 2 or if the best contrast is at most ζ\zeta, and otherwise BS(s,e)={b}∪BS(s,b)∪BS(b,e)\mathrm{BS}(s, e) = \{b\} \cup \mathrm{BS}(s, b) \cup \mathrm{BS}(b, e). Each push makes the segment strictly shorter, so the loop ends after at most 2n−12n - 1 pops, and it returns exactly BS(0,n)\mathrm{BS}(0, n).

Fryzlewicz (2014) gives conditions under which binary segmentation is consistent: the segments must not be too short compared to nn, and the jumps not too small. When these fail, as in the burst example under Variants, it can miss changes.

Proof: The squared CUSUM contrast is the gain in fit of a cut, and the stack procedure computes the recursive binary segmentationfull

Notation is that of the page. For 0≤i<j≤n0 \le i < j \le n, write xˉi,j\bar x_{i,j} for the mean of xi+1,…,xjx_{i+1}, \ldots, x_j and RSS(i,j)=∑l=i+1j(xl−xˉi,j)2\mathrm{RSS}(i, j) = \sum_{l=i+1}^{j}(x_l - \bar x_{i,j})^2, with RSS(i,i)=0\mathrm{RSS}(i, i) = 0.

Lemma 1 (the contrast is the gain of a cut). For s<b<es < b < e,

C(s,b,e)2=RSS(s,e)−RSS(s,b)−RSS(b,e).C(s, b, e)^2 = \mathrm{RSS}(s, e) - \mathrm{RSS}(s, b) - \mathrm{RSS}(b, e).

Proof. Let n1=b−sn_1 = b - s, n2=e−bn_2 = e - b, N=n1+n2N = n_1 + n_2, a=xˉs,ba = \bar x_{s,b}, c=xˉb,ec = \bar x_{b,e} and μ=xˉs,e=(n1a+n2c)/N\mu = \bar x_{s,e} = (n_1 a + n_2 c)/N. For any numbers y1,…,yky_1, \ldots, y_k with mean yˉ\bar y and any μ\mu, ∑(yl−μ)2=∑(yl−yˉ)2+k(yˉ−μ)2\sum(y_l - \mu)^2 = \sum(y_l - \bar y)^2 + k(\bar y - \mu)^2, because the cross term 2(yˉ−μ)∑(yl−yˉ)2(\bar y - \mu)\sum(y_l - \bar y) is 0. Apply this to the two parts and add:

RSS(s,e)=RSS(s,b)+RSS(b,e)+n1(a−μ)2+n2(c−μ)2.\mathrm{RSS}(s, e) = \mathrm{RSS}(s, b) + \mathrm{RSS}(b, e) + n_1(a - \mu)^2 + n_2(c - \mu)^2.

Now a−μ=n2(a−c)/Na - \mu = n_2(a - c)/N and c−μ=−n1(a−c)/Nc - \mu = -n_1(a - c)/N, so

n1(a−μ)2+n2(c−μ)2=n1n22+n2n12N2(a−c)2=n1n2N(a−c)2=C(s,b,e)2.□n_1(a - \mu)^2 + n_2(c - \mu)^2 = \frac{n_1 n_2^2 + n_2 n_1^2}{N^2}(a - c)^2 = \frac{n_1 n_2}{N}(a - c)^2 = C(s, b, e)^2. \quad\square

Corollary. Line L4 returns a cut bb that minimizes RSS(s,b)+RSS(b,e)\mathrm{RSS}(s, b) + \mathrm{RSS}(b, e) over s<b<es < b < e, that is, the least squares fit of a model with one change in the segment. The contrast is nonnegative, so maximizing CC and maximizing C2C^2 give the same bb.

Lemma 2 (prefix sums). With P0=0P_0 = 0 and Pj=x1+⋯+xjP_j = x_1 + \cdots + x_j, xˉi,j=(Pj−Pi)/(j−i)\bar x_{i,j} = (P_j - P_i)/(j - i). So each contrast costs O(1)O(1) after O(n)O(n) preprocessing, and line L4 costs O(e−s)O(e - s).

Proof. Pj−Pi=xi+1+⋯+xjP_j - P_i = x_{i+1} + \cdots + x_j. □\square

The recursive definition. For 0≤s<e≤n0 \le s < e \le n let β(s,e)\beta(s, e) be the smallest maximizer of C(s,⋅,e)C(s, \cdot, e) over s<b<es < b < e, and define

BS(s,e)={∅if e−s<2 or C(s,β(s,e),e)≤ζ,{β(s,e)}∪BS(s,β(s,e))∪BS(β(s,e),e)otherwise.\mathrm{BS}(s, e) = \begin{cases}\emptyset & \text{if } e - s < 2 \text{ or } C(s, \beta(s, e), e) \le \zeta,\\ \{\beta(s, e)\} \cup \mathrm{BS}(s, \beta(s, e)) \cup \mathrm{BS}(\beta(s, e), e) & \text{otherwise.}\end{cases}

The definition is well founded, because both segments on the right are strictly shorter than (s,e)(s, e).

Theorem. The procedure stops after at most 2n−12n - 1 pops and returns BS(0,n)\mathrm{BS}(0, n) in increasing order.

Proof. Consider the multiset S\mathcal S of segments on the stack together with the set CP. We claim that the following holds before each test of line L2:

BS(0,n)=CP  ∪⋃(s,e)∈SBS(s,e),\mathrm{BS}(0, n) = CP \;\cup \bigcup_{(s, e) \in \mathcal S}\mathrm{BS}(s, e),

and that the sets on the right are pairwise disjoint. Also the segments in S\mathcal S are pairwise disjoint, they lie in (0,n](0, n], and no element of CP lies strictly inside one of them.

Line L1 makes the claim true with S={(0,n)}\mathcal S = \{(0, n)\} and CP=∅CP = \emptyset. Suppose it holds and the loop pops (s,e)(s, e). If e−s<2e - s < 2, or if c≤ζc \le \zeta at line L5, then BS(s,e)=∅\mathrm{BS}(s, e) = \emptyset by definition and line L4 computed b=β(s,e)b = \beta(s, e), so removing (s,e)(s, e) keeps the identity. Otherwise line L6 adds b=β(s,e)b = \beta(s, e) to CP and pushes (s,b)(s, b) and (b,e)(b, e), which replaces BS(s,e)\mathrm{BS}(s, e) by {b}∪BS(s,b)∪BS(b,e)\{b\} \cup \mathrm{BS}(s, b) \cup \mathrm{BS}(b, e), which is the same set. The point bb lies strictly inside (s,e)(s, e), while BS(s,b)\mathrm{BS}(s, b) lies strictly inside (s,b)(s, b) and BS(b,e)\mathrm{BS}(b, e) strictly inside (b,e)(b, e), so disjointness is kept. The two new segments are disjoint and lie in the old one, so the segment facts are kept.

Termination: each split adds a new point of {1,…,n−1}\{1, \ldots, n-1\} to CP, and by disjointness no point is added twice, so there are at most n−1n - 1 splits. Every pop either splits or not, and every segment except (0,n)(0, n) is pushed by a split, so the number of pops is at most 1+2(n−1)=2n−11 + 2(n - 1) = 2n - 1. When the stack is empty the claim gives CP=BS(0,n)CP = \mathrm{BS}(0, n), and line L7 sorts it. ■\blacksquare

Running time. The pops form a binary tree rooted at (0,n)(0, n) in which the children of a split segment are its two parts. The segments at one depth are disjoint, so by Lemma 2 the work at one depth is O(n)O(n). A path from the root passes through split nodes only, except at its last node, so the depth is at most m+1m + 1 when mm change points are found, and the total time is O(n(m+1))O(n(m + 1)).

Complexity

The segments popped from the stack form a binary tree. Segments at the same depth are disjoint, so the scans of line L4 at one depth cost O(n)O(n) together. Each internal node of the tree is a change point, so the depth is at most m+1m + 1, and the total time is O(n(m+1))O(n(m + 1)). When the splits are balanced the depth is O(log⁡n)O(\log n) and the time is O(nlog⁡n)O(n \log n). When every split cuts off one point, the depth is n−1n - 1 and the time is Θ(n2)\Theta(n^2). This happens for xi=3ix_i = 3^i with ζ=0\zeta = 0: on every prefix x1,…,xex_1, \ldots, x_e the best cut is b=e−1b = e - 1. The extra space is O(n)O(n) for the prefix sums and the stack.

Properties

  • Greedy. Each cut is chosen without regard to later cuts, and a cut is never moved.
  • Nested results. Lowering ζ\zeta only adds change points, so a single run with a small threshold gives the whole sequence of nested segmentations.
  • Simple and fast. It needs only prefix sums and one scan per segment.
  • Not optimal. For a given number of changes, the segmentation can have a larger residual sum of squares than the best one found by dynamic programming in segmented least squares or PELT.
  • Weak on short segments. A short segment far from the ends of a long parent gives a small contrast, because the contrast compares long averages.

Variants and improvements

  • Wild binary segmentation (WBS). Fryzlewicz (2014) draws MM random intervals [sj,ej][s_j, e_j] once. On each segment, line L4 is replaced by a search over the segment itself and every drawn interval inside it, and the largest contrast decides the cut. When MM is large enough, with high probability some interval contains only one change with enough room on both sides, so short segments are found. The cost is O(Mn)O(Mn) per level of the tree. Example: let xx be 50 zeros, then 4 values equal to 3, then 50 zeros, so n=104n = 104 and ζ=1.32log⁡104=3.962\zeta = 1.3\sqrt{2\log 104} = 3.962. The best contrast on the whole series is 1.132 at b=50b = 50, below ζ\zeta, so binary segmentation finds nothing. WBS with 100 random intervals finds {50,54}\{50, 54\}, and so does PELT with penalty 2log⁡n2\log n.
  • Circular binary segmentation. Olshen et al. (2004) look for a pair of cuts at once, the best segment that differs from the rest of the circle. It finds a short middle segment in one step and is standard for DNA copy number data.
  • Other costs. The contrast can be replaced by any likelihood ratio for a single change, for example for a change in variance or in a Poisson rate.
  • Exact alternatives. PELT and optimal partitioning minimize the penalized cost exactly; their expected cost can be linear when changes are frequent.
  • Online detection. For data that arrive one at a time, use the CUSUM or Bayesian online changepoint detection.

When to use it

Use binary segmentation as a fast first pass on long series with a few well separated changes, or to produce the nested set of candidate segmentations for a model selection step. Use WBS or circular binary segmentation when short segments matter, and an exact penalized method when the best segmentation for a given cost is required.

Pitfalls

  • Masking. Two changes close together with opposite jumps can cancel in the whole-series contrast, so neither is found. WBS and exact methods are much less affected.
  • Threshold on the wrong scale. The threshold must scale with the noise level σ\sigma. Estimate σ\sigma robustly, for example from the median absolute difference of neighbours, because the plain standard deviation of the series includes the jumps.
  • Dependent noise. Positive autocorrelation makes contrasts larger under no change, so the method finds false changes. Inflate ζ\zeta or model the dependence.
  • Reading the order of the cuts as importance. The first cut is the strongest single cut of the whole series, not necessarily the largest jump.
  • Off-by-one in the output. Here a change point is the last index of a segment. Other software reports the first index of the new segment.

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.

binary_segmentation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/binary-segmentation/. The authors are listed in prov/PQ8R7K.jsonl.
"""Binary segmentation and wild binary segmentation for changes in the mean.

For the segment x_(s+1)..x_e and a split point b with s < b < e, the CUSUM
contrast is

    C(s, b, e) = sqrt((b - s)(e - b) / (e - s)) * |mean(x_(s+1..b)) - mean(x_(b+1..e))|.

C(s, b, e)^2 equals the drop in the residual sum of squares when the segment
is cut at b. Binary segmentation cuts at the best b when the contrast exceeds
a threshold zeta and recurses on both halves. With prefix sums each contrast
costs O(1), so one segment of length L costs O(L), each level of the
recursion tree costs O(n), and the whole run costs O(n (m + 1)) for m
change points found: O(n log n) for balanced splits and O(n^2) in the worst case.
"""

import math
import random
from collections.abc import Sequence


def prefix_sums(xs: Sequence[float]) -> list[float]:
    out = [0]
    for x in xs:
        out.append(out[-1] + x)
    return out


def contrast(p: Sequence[float], s: int, b: int, e: int) -> float:
    """C(s, b, e) from prefix sums p. Precondition: s < b < e. O(1)."""
    left = (p[b] - p[s]) / (b - s)
    right = (p[e] - p[b]) / (e - b)
    return math.sqrt((b - s) * (e - b) / (e - s)) * abs(left - right)


def contrast_squared(p: Sequence, s: int, b: int, e: int):
    """C(s, b, e)^2 in the arithmetic of p (exact for Fractions)."""
    left = (p[b] - p[s]) / (b - s)
    right = (p[e] - p[b]) / (e - b)
    return (b - s) * (e - b) * (left - right) ** 2 / (e - s)


def best_split(p: Sequence[float], s: int, e: int) -> tuple[int, float]:
    """The smallest b in (s, e) that maximizes C(s, b, e), and the maximum. O(e - s)."""
    best_b, best_c = s + 1, -1.0
    for b in range(s + 1, e):
        c = contrast(p, s, b, e)
        if c > best_c:
            best_b, best_c = b, c
    return best_b, best_c


def binary_segmentation(xs: Sequence[float], zeta: float) -> list[int]:
    """Change points (as last indices of segments, 1-based) found by binary segmentation."""
    p = prefix_sums(xs)  # @line L1
    stack = [(0, len(xs))]  # @line L1
    cps = []  # @line L1
    while stack:  # @line L2
        s, e = stack.pop()  # @line L3
        if e - s < 2:  # @line L3
            continue
        b, c = best_split(p, s, e)  # @line L4
        if c <= zeta:  # @line L5
            continue
        cps.append(b)  # @line L6
        stack.append((s, b))  # @line L6
        stack.append((b, e))  # @line L6
    return sorted(cps)  # @line L7


def random_intervals(n: int, m: int, rng: random.Random) -> list[tuple[int, int]]:
    """m random intervals (s, e) with 0 <= s < e - 1 < n, drawn uniformly over pairs."""
    out = []
    while len(out) < m:
        s, e = sorted(rng.sample(range(n + 1), 2))
        if e - s >= 2:
            out.append((s, e))
    return out


def wild_binary_segmentation(xs: Sequence[float], zeta: float, intervals: Sequence[tuple[int, int]]) -> list[int]:
    """Fryzlewicz's WBS: on each segment, search the full segment and every drawn interval inside it.

    Cost O(sum of interval lengths) per segment visited, so O(M n) per level
    for M intervals.
    """
    p = prefix_sums(xs)
    stack = [(0, len(xs))]
    cps = []
    while stack:
        s, e = stack.pop()
        if e - s < 2:
            continue
        cands = [(s, e)] + [(a, b) for a, b in intervals if s <= a and b <= e]
        best = (-1.0, 0)
        for a, b in cands:
            split, c = best_split(p, a, b)
            if c > best[0]:
                best = (c, split)
        c, split = best
        if c <= zeta:
            continue
        cps.append(split)
        stack.append((s, split))
        stack.append((split, e))
    return sorted(cps)


def default_threshold(n: int, sigma: float = 1.0, factor: float = 1.3) -> float:
    """zeta = factor * sigma * sqrt(2 log n), the form used by Fryzlewicz (2014) for WBS."""
    return factor * sigma * math.sqrt(2.0 * math.log(n))
test_binary_segmentation.py 126 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/binary-segmentation/. The authors are listed in prov/PQ8R7K.jsonl.
import math
import random
from fractions import Fraction

from binary_segmentation import (
    best_split,
    binary_segmentation,
    contrast,
    contrast_squared,
    default_threshold,
    prefix_sums,
    random_intervals,
    wild_binary_segmentation,
)

EXAMPLE = [0.1, -0.3, 0.2, 0.0, 2.1, 1.8, 2.2, 1.9, 2.0, -0.1, 0.2, 0.1]


def rss(xs):
    if not xs:
        return 0
    m = sum(xs) / len(xs)
    return sum((x - m) ** 2 for x in xs)


def naive_contrast(xs, s, b, e):
    left = xs[s:b]
    right = xs[b:e]
    d = sum(left) / len(left) - sum(right) / len(right)
    return math.sqrt(len(left) * len(right) / (e - s)) * abs(d)


def naive_binseg(xs, zeta, s=0, e=None):
    """Plain recursion with O(L) contrasts: the reference for the stack version."""
    if e is None:
        e = len(xs)
    if e - s < 2:
        return []
    vals = [(naive_contrast(xs, s, b, e), -b) for b in range(s + 1, e)]
    c, nb = max(vals)
    if c <= zeta:
        return []
    b = -nb
    return sorted(naive_binseg(xs, zeta, s, b) + [b] + naive_binseg(xs, zeta, b, e))


def test_worked_example():
    p = prefix_sums(EXAMPLE)
    b, c = best_split(p, 0, 12)
    assert b == 4 and abs(c - 2.082) < 1e-3
    b, c = best_split(p, 4, 12)
    assert b == 9 and abs(c - 2.647) < 1e-3
    assert binary_segmentation(EXAMPLE, 1.5) == [4, 9]


def test_edge_cases():
    assert binary_segmentation([], 1.0) == []
    assert binary_segmentation([5.0], 1.0) == []
    assert binary_segmentation([0.0, 10.0], 1.0) == [1]
    assert binary_segmentation([1.0] * 20, 0.0) == []


def test_contrast_squared_is_rss_drop_exact():
    rng = random.Random(1974)
    for _ in range(500):
        n = rng.randint(2, 15)
        xs = [Fraction(rng.randint(-9, 9), rng.randint(1, 3)) for _ in range(n)]
        p = prefix_sums(xs)
        s = rng.randint(0, n - 2)
        e = rng.randint(s + 2, n)
        b = rng.randint(s + 1, e - 1)
        assert contrast_squared(p, s, b, e) == rss(xs[s:e]) - rss(xs[s:b]) - rss(xs[b:e])


def test_matches_naive_recursion():
    rng = random.Random(1981)
    for _ in range(500):
        n = rng.randint(0, 25)
        mu = 0.0
        xs = []
        for _ in range(n):
            if rng.random() < 0.15:
                mu = rng.choice([-3.0, 0.0, 3.0])
            xs.append(mu + rng.gauss(0.0, 0.5))
        zeta = rng.uniform(0.5, 3.0)
        assert binary_segmentation(xs, zeta) == naive_binseg(xs, zeta)


def test_argmax_against_brute_force():
    rng = random.Random(6)
    for _ in range(500):
        n = rng.randint(2, 20)
        xs = [rng.gauss(0.0, 1.0) for _ in range(n)]
        p = prefix_sums(xs)
        b, c = best_split(p, 0, n)
        vals = [naive_contrast(xs, 0, k, n) for k in range(1, n)]
        assert abs(c - max(vals)) < 1e-9
        assert abs(contrast(p, 0, b, n) - max(vals)) < 1e-9


def test_misses_a_short_burst_that_wbs_finds():
    xs = [0.0] * 50 + [3.0] * 4 + [0.0] * 50
    zeta = default_threshold(len(xs))
    assert abs(zeta - 3.962) < 1e-3
    assert abs(best_split(prefix_sums(xs), 0, len(xs))[1] - 1.1323) < 1e-4
    assert binary_segmentation(xs, zeta) == []
    intervals = random_intervals(len(xs), 100, random.Random(1))
    assert wild_binary_segmentation(xs, zeta, intervals) == [50, 54]


def test_noisy_burst():
    rng = random.Random(2014)
    xs = [rng.gauss(0, 1) for _ in range(150)] + [rng.gauss(4, 1) for _ in range(6)] + [rng.gauss(0, 1) for _ in range(150)]
    zeta = default_threshold(len(xs))
    assert binary_segmentation(xs, zeta) == []
    found = wild_binary_segmentation(xs, zeta, random_intervals(len(xs), 300, random.Random(2)))
    assert any(abs(c - 150) <= 2 for c in found) and any(abs(c - 156) <= 2 for c in found)


def test_wbs_with_no_intervals_is_binary_segmentation():
    rng = random.Random(8)
    for _ in range(100):
        xs = [rng.choice([0.0, 2.0]) + rng.gauss(0, 0.3) for _ in range(rng.randint(0, 30))]
        assert wild_binary_segmentation(xs, 1.2, []) == binary_segmentation(xs, 1.2)

History

Scott and Knott (1974) proposed splitting a set of ordered group means into two groups by the largest between-group sum of squares, and then splitting each group again, which is binary segmentation applied to means. Vostrikova (1981, Soviet Mathematics Doklady 24) studied the method for change points in a multivariate process and proved its consistency. Olshen et al. (2004) introduced circular binary segmentation for DNA copy number arrays. Fryzlewicz (2014) introduced wild binary segmentation and analysed both methods.

References

  1. A. J. Scott and M. Knott, A cluster analysis method for grouping means in the analysis of variance, Biometrics 30(3) (1974), the method of splitting ordered group means into two groups by the largest between-group sum of squares, applied again to each group
  2. Piotr Fryzlewicz, Wild binary segmentation for multiple change-point detection, Annals of Statistics 42(6) (2014), the CUSUM statistic, the description and consistency conditions of binary segmentation, the wild binary segmentation algorithm, and the threshold of the form C sqrt(2 log n)
  3. Adam B. Olshen, E. S. Venkatraman, Robert Lucito and Michael Wigler, Circular binary segmentation for the analysis of array-based DNA copy number data, Biostatistics 5(4) (2004), the circular binary segmentation algorithm and its application to copy number data
  4. R. Killick, P. Fearnhead and I. A. Eckley, Optimal detection of changepoints with a linear computational cost, Journal of the American Statistical Association 107(500) (2012), the discussion of binary segmentation as an approximate search and its comparison with exact penalized segmentation
  5. Charles Truong, Laurent Oudre and Nicolas Vayatis, Selective review of offline change point detection methods, Signal Processing 167 (2020), the section on search methods, including binary segmentation and its variants

Where this leads

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