Algorithm Search⌘K

Algorithmadvanced

PELT

Also called pruned exact linear time, PELT change-point algorithm.

Finds the change points that minimize a penalized cost exactly. It runs the optimal partitioning recursion and prunes start points that can never be optimal again.

Time
Θ(n²) worst
Space
Θ(n) extra
Where
n = the length of the series, with each segment cost computed in O(1)
Properties
deterministicexactofflineiterative
Origin
Rebecca Killick, Paul Fearnhead, Idris A. Eckley, 2012

PELT finds the exact minimizer of a penalized segmentation cost: the sum over segments of a cost C\mathcal C of each segment, plus a penalty β\beta for each change point. It runs the optimal partitioning recursion, a dynamic programme like the one for segmented least squares, F(t)=min⁡s<t[F(s)+C(xs+1..t)+β]F(t) = \min_{s < t}[F(s) + \mathcal C(x_{s+1..t}) + \beta], which costs Θ(n2)\Theta(n^2) segment costs, and adds one rule: a start point ss is removed for good when F(s)+C(xs+1..t)+K>F(t)F(s) + \mathcal C(x_{s+1..t}) + K > F(t). If the cost satisfies C(xa..s)+C(xs+1..b)+K≤C(xa..b)\mathcal C(x_{a..s}) + \mathcal C(x_{s+1..b}) + K \le \mathcal C(x_{a..b}), a removed point can never be the best last change again, so the result is still exactly optimal. The worst case stays quadratic, but when the number of changes grows in proportion to nn, the expected cost is linear (Killick, Fearnhead and Eckley 2012).

In plain words

You want to cut a series into pieces so that each piece is well described by a simple model, and each cut costs a fixed fee so that you do not cut everywhere. For each position, you work out the cheapest way to cut the series up to that position, by trying every place where the last piece could start. That is exact but slow, because the list of possible starts grows. The trick is that some starts are already so bad that no future data can make them the best choice. When a clear change has happened, all starts before it become hopeless, and you cross them off. Then the list stays short and the work stays close to one pass.

The problem

Given x1,…,xnx_1, \ldots, x_n, a segment cost C(xs+1..t)\mathcal C(x_{s+1..t}), written C(s,t)C(s, t), and a penalty β≥0\beta \ge 0, find change points 0<τ1<⋯<τm<n0 < \tau_1 < \cdots < \tau_m < n that minimize

∑j=0mC(τj,τj+1)+βm,τ0=0, τm+1=n.\sum_{j=0}^{m} C(\tau_j, \tau_{j+1}) + \beta m, \qquad \tau_0 = 0,\ \tau_{m+1} = n.

Here τj\tau_j is the last index of segment jj. A usual cost is the residual sum of squares for a change in mean, C(s,t)=∑i=s+1t(xi−xˉs+1..t)2C(s, t) = \sum_{i=s+1}^{t}(x_i - \bar x_{s+1..t})^2, which is twice the Gaussian negative log likelihood with unit variance up to a constant per point. Usual penalties are β=2log⁡n\beta = 2\log n, close to the BIC, and β=2\beta = 2 times the number of parameters added per change, the AIC. See change-point detection for the other formulations.

The algorithm

  1. PELT(n, C, β, K) ▷ C(s, t) is the cost of x_{s+1..t}; K satisfies the pruning condition
  2. 1F(0) ← -β; R ← {0}
  3. 2for t ← 1 to n do
  4. 3F(t) ← min over s in R of [F(s) + C(s, t) + β]
  5. 4last(t) ← the smallest s in R that attains the minimum
  6. 5R ← {s in R : F(s) + C(s, t) + K ≤ F(t)} ∪ {t}
  7. 6follow last from n back to 0 and return F(n) and the change points last(n), last(last(n)), ... that are positive

F(t)F(t) is the optimal penalized cost of x1,…,xtx_1, \ldots, x_t. The start value F(0)=−βF(0) = -\beta makes the first segment free of the penalty. Line L3 is the optimal partitioning recursion of Jackson et al. (2005), restricted to the set RR of candidate last change points. Line L5 is the pruning step. Without it, R={0,…,t−1}R = \{0, \ldots, t-1\} at time tt and the method is plain optimal partitioning. For the residual sum of squares, prefix sums of xix_i and xi2x_i^2 make each C(s,t)C(s, t) cost O(1)O(1).

Example

Take x=(1,0,1,5,6,5,6,1,0)x = (1, 0, 1, 5, 6, 5, 6, 1, 0), the residual sum of squares, β=4\beta = 4 and K=0K = 0:

tt 1 2 3 4 5 6 7 8 9
F(t)F(t) 0 1/2 2/3 14/3 31/6 16/3 17/3 29/3 61/6
last(t)(t) 0 0 0 3 3 3 3 7 7
∣R∣\lvert R \rvert at line L3 1 2 3 4 2 3 4 5 2

At t=4t = 4 the candidates are s=0,1,2,3s = 0, 1, 2, 3, and the values F(s)+C(s,4)F(s) + C(s, 4) are 43/443/4, 1414, 17/217/2 and 2/32/3. Only s=3s = 3 is at most F(4)=14/3F(4) = 14/3, so RR becomes {3,4}\{3, 4\}: the points before the first jump are gone for good. The same happens at t=8t = 8, where RR shrinks from {3,…,7}\{3, \ldots, 7\} to {7,8}\{7, 8\}. Back-tracking from t=9t = 9 gives last(9)=7(9) = 7 and last(7)=3(7) = 3, so the change points are {3,7}\{3, 7\} with segments (1,0,1)(1, 0, 1), (5,6,5,6)(5, 6, 5, 6) and (1,0)(1, 0), and F(9)=13/6+2⋅4=61/6F(9) = 13/6 + 2 \cdot 4 = 61/6.

The penalty picks the number of changes. The smallest residual sums of squares for m=0,1,2,3,4m = 0, 1, 2, 3, 4 change points are 500/9500/9, 71/271/2, 13/613/6, 5/35/3 and 4/34/3. Adding 4m4m gives about 55.56, 39.50, 10.17, 13.67 and 17.33, so m=2m = 2 wins.

Correctness

The proof is in full below. In outline:

  1. Optimal partitioning. Every segmentation of x1,…,xtx_1, \ldots, x_t has a last segment xs+1..tx_{s+1..t}, and the rest is a segmentation of x1,…,xsx_1, \ldots, x_s. So F(t)=min⁡0≤s<t[F(s)+C(s,t)+β]F(t) = \min_{0 \le s < t}[F(s) + C(s, t) + \beta], and back-tracking the minimizers gives an optimal segmentation.
  2. Pruning lemma. Suppose that C(a,s)+C(s,b)+K≤C(a,b)C(a, s) + C(s, b) + K \le C(a, b) for all a<s<ba < s < b. If F(s)+C(s,t)+K>F(t)F(s) + C(s, t) + K > F(t) at some t>st > s, then for every T>tT > t,
F(s)+C(s,T)≥F(s)+C(s,t)+K+C(t,T)>F(t)+C(t,T),F(s) + C(s, T) \ge F(s) + C(s, t) + K + C(t, T) > F(t) + C(t, T),

so ss is strictly worse than tt as the last change point before TT, and it is never a minimizer again. 3. Exactness. A minimizer of the full recursion is never pruned, so the minimum over RR equals the minimum over all s<ts < t, and the smallest minimizer is the same. PELT returns the same F(n)F(n) and the same change points as optimal partitioning.

For the residual sum of squares the condition holds with K=0K = 0, because cutting a segment can only lower its residual sum of squares. The same is true for any cost that is minus a maximized log likelihood. A smaller KK prunes less and stays exact; a larger KK breaks the condition and can remove the optimum.

Proof: The pruning rule of PELT never removes an optimal last change point, so PELT returns the exact optimal partitioningfull

Notation is that of the page. For 0≤s<t≤n0 \le s < t \le n, C(s,t)C(s, t) is the cost of the segment xs+1,…,xtx_{s+1}, \ldots, x_t. A segmentation of x1,…,xtx_1, \ldots, x_t is a set of change points 0<τ1<⋯<τm<t0 < \tau_1 < \cdots < \tau_m < t, and its penalized cost is ∑j=0mC(τj,τj+1)+βm\sum_{j=0}^{m}C(\tau_j, \tau_{j+1}) + \beta m with τ0=0\tau_0 = 0 and τm+1=t\tau_{m+1} = t. Let OPT(t)\mathrm{OPT}(t) be the smallest penalized cost over all segmentations of x1,…,xtx_1, \ldots, x_t, and OPT(0)=−β\mathrm{OPT}(0) = -\beta. We assume that there is a constant KK with

C(a,s)+C(s,b)+K≤C(a,b)for all 0≤a<s<b≤n.(P)C(a, s) + C(s, b) + K \le C(a, b) \quad \text{for all } 0 \le a < s < b \le n. \tag{P}

For s<Ts < T write VT(s)=OPT(s)+C(s,T)+βV_T(s) = \mathrm{OPT}(s) + C(s, T) + \beta.

Lemma 1 (optimal partitioning). For 1≤t≤n1 \le t \le n, OPT(t)=min⁡0≤s<tVt(s)\mathrm{OPT}(t) = \min_{0 \le s < t}V_t(s). If ss attains the minimum, then an optimal segmentation of x1,…,xsx_1, \ldots, x_s followed by the segment xs+1..tx_{s+1..t} is an optimal segmentation of x1,…,xtx_1, \ldots, x_t.

Proof. Group the segmentations of x1,…,xtx_1, \ldots, x_t by their last change point s=τms = \tau_m, with s=0s = 0 when there is none. For s≥1s \ge 1, the segmentations with last change point ss are exactly the segmentations of x1,…,xsx_1, \ldots, x_s followed by the segment xs+1..tx_{s+1..t}, and the penalized cost is the cost of the first part plus C(s,t)+βC(s, t) + \beta, since one change point is added. The smallest such cost is Vt(s)V_t(s). For s=0s = 0 the only segmentation is one segment, of cost C(0,t)=−β+C(0,t)+β=Vt(0)C(0, t) = -\beta + C(0, t) + \beta = V_t(0). Taking the minimum over ss gives the recursion, and the second claim follows from the same grouping. □\square

Lemma 2 (pruning). Let 0≤s<t<T≤n0 \le s < t < T \le n. If OPT(s)+C(s,t)+K>OPT(t)\mathrm{OPT}(s) + C(s, t) + K > \mathrm{OPT}(t), then VT(s)>VT(t)V_T(s) > V_T(t).

Proof. By (P) with a=sa = s, split point tt and b=Tb = T, C(s,T)≥C(s,t)+C(t,T)+KC(s, T) \ge C(s, t) + C(t, T) + K. Hence

VT(s)=OPT(s)+C(s,T)+β≥OPT(s)+C(s,t)+K+C(t,T)+β>OPT(t)+C(t,T)+β=VT(t).□V_T(s) = \mathrm{OPT}(s) + C(s, T) + \beta \ge \mathrm{OPT}(s) + C(s, t) + K + C(t, T) + \beta > \mathrm{OPT}(t) + C(t, T) + \beta = V_T(t). \quad\square

Lemma 3 (the invariant). For every tt, when line L3 runs: (a) F(s)=OPT(s)F(s) = \mathrm{OPT}(s) for every s<ts < t; (b) R⊆{0,…,t−1}R \subseteq \{0, \ldots, t - 1\} and t−1∈Rt - 1 \in R; (c) every s∈{0,…,t−1}∖Rs \in \{0, \ldots, t - 1\} \setminus R has Vt(s)>Vt(s′)V_t(s) > V_t(s') for some s′∈{0,…,t−1}s' \in \{0, \ldots, t-1\}.

Proof. By induction on tt. For t=1t = 1, line L1 gives F(0)=−β=OPT(0)F(0) = -\beta = \mathrm{OPT}(0) and R={0}R = \{0\}, and (c) is empty.

Assume the invariant at tt. We first show that line L3 sets F(t)=OPT(t)F(t) = \mathrm{OPT}(t). By (a), the values computed at line L3 are Vt(s)V_t(s) for s∈Rs \in R, so F(t)≥OPT(t)F(t) \ge \mathrm{OPT}(t) by Lemma 1. Let s∗s^* be a minimizer of VtV_t over {0,…,t−1}\{0, \ldots, t-1\}. By (c), s∗s^* is not outside RR, since a point outside RR is strictly beaten by some point and so is not a minimizer. So s∗∈Rs^* \in R and F(t)=Vt(s∗)=OPT(t)F(t) = V_t(s^*) = \mathrm{OPT}(t). This gives (a) at t+1t + 1.

Line L5 keeps tt, so (b) holds at t+1t + 1. For (c) at t+1t + 1, let s≤ts \le t with s∉Rs \notin R after line L5. Either ss was outside RR before step tt, or it was removed at line L5 of step tt. In the second case OPT(s)+C(s,t)+K>F(t)=OPT(t)\mathrm{OPT}(s) + C(s, t) + K > F(t) = \mathrm{OPT}(t), so Lemma 2 gives Vt+1(s)>Vt+1(t)V_{t+1}(s) > V_{t+1}(t). In the first case, ss was removed at line L5 of some step u<tu < t, and the same argument at that step gives OPT(s)+C(s,u)+K>OPT(u)\mathrm{OPT}(s) + C(s, u) + K > \mathrm{OPT}(u), so Lemma 2 with T=t+1>uT = t + 1 > u gives Vt+1(s)>Vt+1(u)V_{t+1}(s) > V_{t+1}(u). In both cases ss is strictly beaten. □\square

Theorem. If (P) holds, PELT returns F(n)=OPT(n)F(n) = \mathrm{OPT}(n) and an optimal segmentation. Moreover, at every tt the minimizers of VtV_t over RR are exactly the minimizers of VtV_t over {0,…,t−1}\{0, \ldots, t-1\}, so last(t)(t) is the smallest minimizer of the full recursion and PELT returns the same change points as optimal partitioning without pruning.

Proof. By Lemma 3, F(t)=OPT(t)F(t) = \mathrm{OPT}(t) for every tt. Every minimizer over the full set lies in RR, as shown in the proof of Lemma 3, and the minimum values over RR and over the full set agree, so the two sets of minimizers are equal. Then last(t)(t) attains the minimum in Lemma 1. Back-tracking at line L6 builds, from the end, a segmentation whose last segment is xlast(t)+1..tx_{\text{last}(t)+1..t} in front of an optimal segmentation of x1,…,xlast(t)x_1, \ldots, x_{\text{last}(t)}. By Lemma 1 and induction on tt, the result is optimal. The loop at line L6 stops because last(t)<t(t) < t. ■\blacksquare

The condition for the usual costs. If C(s,t)=min⁡θ∑i=s+1tℓ(xi,θ)C(s, t) = \min_\theta \sum_{i=s+1}^{t}\ell(x_i, \theta) for some loss ℓ\ell, for example the residual sum of squares or minus a maximized log likelihood, then (P) holds with K=0K = 0: using one parameter for both parts gives

C(a,b)=min⁡θ[∑i=a+1sℓ(xi,θ)+∑i=s+1bℓ(xi,θ)]≥C(a,s)+C(s,b).C(a, b) = \min_\theta\Bigl[\sum_{i=a+1}^{s}\ell(x_i, \theta) + \sum_{i=s+1}^{b}\ell(x_i, \theta)\Bigr] \ge C(a, s) + C(s, b).

If (P) holds for some KK, it holds for every smaller KK, and then line L5 removes fewer points, so the result stays exact.

Cost. Step tt evaluates ∣R∣≤t\lvert R \rvert \le t segment costs, so the total is at most n(n+1)/2n(n+1)/2. The expected linear cost under conditions on the data is a theorem of Killick, Fearnhead and Eckley (2012) and is not proved here.

Complexity

Each step tt costs O(∣R∣)O(\lvert R \rvert) segment costs. In the worst case nothing is pruned, ∣R∣=t\lvert R \rvert = t, and the total is Θ(n2)\Theta(n^2), the same as optimal partitioning. Series without changes come close to this case. Killick, Fearnhead and Eckley (2012) proved that the expected cost is O(n)O(n) when the number of changes grows linearly with nn and some further conditions hold; this is cited, not proved here. Measured average and largest sizes of RR per step, with β=2log⁡n\beta = 2\log n, Gaussian noise of variance 1, and one random generator with seed 3 (as in the tests), used for the rows in order, the series with changes before the series without:

nn changes every 100 points: mean ∣R∣\lvert R \rvert largest ∣R∣\lvert R \rvert total cost evaluations no change: mean ∣R∣\lvert R \rvert largest ∣R∣\lvert R \rvert total cost evaluations
1000 86.6 222 86617 319.3 703 319330
2000 82.8 206 165506 1000.5 2000 2001000
4000 91.5 317 365879 1751.9 3701 7007526
8000 90.1 340 720453 2940.7 5423 23525670

With a change every 100 points (a new mean drawn from {−2,−1,0,1,2}\{-2, -1, 0, 1, 2\}), the mean size of RR stays near 90 and the total grows in proportion to nn. Without changes the total grows by a factor between 3.4 and 6.3 each time nn doubles, much faster than nn; at n=2000n = 2000 nothing was pruned at all. The extra space is O(n)O(n) for FF, last and RR.

Properties

  • Exact. For a cost with the pruning property, the output is a global minimizer of the penalized cost, not an approximation.
  • Same tie rule as the full recursion. Pruned points are strictly worse, so the choice of the smallest minimizer is not changed.
  • Fast when changes are frequent. The cost is close to linear exactly in the case where binary segmentation is slowest.
  • Penalized, not constrained. It finds the best segmentation for a given β\beta, not for a given number of changes. For a fixed number of changes use the segment neighbourhood recursion of Auger and Lawrence (1989).
  • Any additive cost. Mean, variance, mean and variance, Poisson rate and regression costs all work when they satisfy the condition.

Variants and improvements

  • Optimal partitioning. The same recursion without line L5, Θ(n2)\Theta(n^2) always (Jackson et al. 2005).
  • Segment neighbourhood. A recursion over the number of segments that gives the best segmentation for every mm up to a bound, in O(mn2)O(m n^2) (Auger and Lawrence 1989). Segmented least squares is a close relative for line fits.
  • Functional pruning (FPOP). Maidstone et al. (2017) keep, for each candidate, the set of segment parameters for which it is still optimal, and drop it when that set is empty. This prunes more than PELT, also when there are few changes.
  • CROPS. Haynes, Eckley and Fearnhead (2017) find the optimal segmentations for all penalties in an interval [βmin⁡,βmax⁡][\beta_{\min}, \beta_{\max}] with a small number of PELT runs, which helps to choose β\beta.
  • Approximate search. Binary segmentation is faster when there are few changes but is not exact.
  • Online methods. For a stream, use the CUSUM or Bayesian online changepoint detection.

When to use it

Use PELT when the whole series is available, the segment cost is additive and has the pruning property, and the exact penalized optimum is wanted. If there are few changes in a very long series, PELT can be close to quadratic; use FPOP or binary segmentation then.

Pitfalls

  • Wrong KK. The constant KK must satisfy C(a,s)+C(s,b)+K≤C(a,b)C(a, s) + C(s, b) + K \le C(a, b) for every split. For the residual sum of squares K=0K = 0. A positive KK there can prune the optimal last change, and then the result is not optimal.
  • Penalty on the wrong scale. The residual sum of squares must be divided by the noise variance before β=2log⁡n\beta = 2\log n is meaningful. With the raw sum and a large variance, PELT finds many false changes.
  • Dependent or heavy-tailed noise. The Gaussian cost then finds too many changes. Use a robust cost, or estimate the dependence and inflate the penalty.
  • Expecting linear time always. Without changes nothing is pruned and the cost is quadratic, as the table shows.
  • Minimum segment length. Costs such as the variance cost are −∞-\infty on segments of length 1. Enforce a minimum length; the recursion and the pruning rule extend directly.

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.

pelt_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pelt-algorithm/. The authors are listed in prov/8P0SSC.jsonl.
"""PELT: pruned exact linear time search for multiple change points.

Minimize sum over segments of C(segment) + beta * (number of change points)
over all partitions of x_1..x_n into contiguous segments. The optimal
partitioning recursion is F(0) = -beta and
F(t) = min over 0 <= s < t of F(s) + C(s+1..t) + beta. PELT keeps only the
candidates s that can still be optimal: s is dropped at time t when
F(s) + C(s+1..t) + K > F(t). With a cost that satisfies
C(a..b) + K <= C(a..s) + C(s+1..b) for all a <= s < b, a dropped candidate is
never optimal later, so PELT returns the same optimum as the full O(n^2)
recursion. Worst case O(n^2) cost evaluations; the expected linear cost holds
only under conditions on the data (Killick, Fearnhead and Eckley 2012).
"""

from collections.abc import Callable, Sequence
from fractions import Fraction
from typing import TypeVar

Num = TypeVar("Num", float, Fraction)


def rss_cost(xs: Sequence[Num]) -> Callable[[int, int], Num]:
    """C(s+1..t) = sum of (x_i - segment mean)^2 for i in s+1..t, via prefix sums. O(1) per call.

    This is twice the Gaussian negative log likelihood with unit variance, up
    to a constant per point, and it satisfies the PELT condition with K = 0.
    """
    zero = xs[0] - xs[0] if xs else 0
    s1 = [zero]
    s2 = [zero]
    for x in xs:
        s1.append(s1[-1] + x)
        s2.append(s2[-1] + x * x)

    def cost(s: int, t: int) -> Num:
        tot = s1[t] - s1[s]
        return s2[t] - s2[s] - tot * tot / (t - s)

    return cost


def pelt(n: int, cost: Callable[[int, int], Num], beta: Num, k: Num = 0,
         sizes: list[int] | None = None) -> tuple[Num, list[int]]:
    """Optimal penalized partition of 1..n. Returns (F(n), sorted change points).

    cost(s, t) is the cost of the segment x_(s+1)..x_t. A change point tau
    means a new segment starts at tau + 1. Ties choose the smallest s. If
    sizes is a list, the candidate set size at each t is appended to it.
    """
    f = [-beta] + [None] * n  # @line L1
    last = [0] * (n + 1)  # @line L1
    cand = [0]  # @line L1
    for t in range(1, n + 1):  # @line L2
        vals = [(f[s] + cost(s, t) + beta, s) for s in cand]  # @line L3
        best, arg = min(vals)
        f[t] = best  # @line L3
        last[t] = arg  # @line L4
        if sizes is not None:
            sizes.append(len(cand))
        cand = [s for v, s in vals if v - beta + k <= best] + [t]  # @line L5
    cps = []
    t = n
    while t > 0:  # @line L6
        t = last[t]
        if t > 0:
            cps.append(t)
    return f[n], sorted(cps)  # @line L6


def optimal_partitioning(n: int, cost: Callable[[int, int], Num], beta: Num) -> tuple[Num, list[int]]:
    """The full O(n^2) recursion of Jackson et al. (2005), with the same tie rule."""
    f = [-beta] + [None] * n
    last = [0] * (n + 1)
    for t in range(1, n + 1):
        f[t], last[t] = min((f[s] + cost(s, t) + beta, s) for s in range(t))
    cps = []
    t = n
    while t > 0:
        t = last[t]
        if t > 0:
            cps.append(t)
    return f[n], sorted(cps)
test_pelt_algorithm.py 107 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pelt-algorithm/. The authors are listed in prov/8P0SSC.jsonl.
import itertools
import math
import random
from fractions import Fraction

from pelt_algorithm import optimal_partitioning, pelt, rss_cost


def l1_cost(xs):
    """Sum of |x_i - median| over the segment: another cost with the PELT property for K = 0."""
    def cost(s, t):
        seg = sorted(xs[s:t])
        med = seg[(len(seg) - 1) // 2]
        return sum(abs(x - med) for x in seg)
    return cost


def penalized(cost, n, beta, cps):
    bounds = [0] + list(cps) + [n]
    return sum(cost(a, b) for a, b in zip(bounds, bounds[1:])) + beta * len(cps)


def brute_force(n, cost, beta):
    best = None
    for m in range(n):
        for cps in itertools.combinations(range(1, n), m):
            v = penalized(cost, n, beta, cps)
            if best is None or v < best:
                best = v
    return best


def test_worked_example():
    xs = [Fraction(v) for v in [1, 0, 1, 5, 6, 5, 6, 1, 0]]
    sizes = []
    value, cps = pelt(len(xs), rss_cost(xs), Fraction(4), sizes=sizes)
    assert value == Fraction(61, 6)
    assert cps == [3, 7]
    assert sizes == [1, 2, 3, 4, 2, 3, 4, 5, 2]


def test_edge_cases():
    xs = [Fraction(3)]
    assert pelt(1, rss_cost(xs), Fraction(1)) == (Fraction(0), [])
    xs = [Fraction(v) for v in [0, 0, 10, 10]]
    assert pelt(4, rss_cost(xs), Fraction(1))[1] == [2]
    assert pelt(4, rss_cost(xs), Fraction(1000))[1] == []
    # A zero penalty and a constant series: one segment still wins on ties.
    assert pelt(5, rss_cost([Fraction(2)] * 5), Fraction(0))[1] == []


def test_equals_optimal_partitioning_exact():
    rng = random.Random(2012)
    for trial in range(500):
        n = rng.randint(1, 30)
        xs = [Fraction(rng.randint(-5, 5)) + (Fraction(rng.randint(0, 3)) * 3 if (i // 7) % 2 else 0)
              for i in range(n)]
        beta = Fraction(rng.randint(0, 40), rng.randint(1, 4))
        cost = rss_cost(xs) if trial % 2 else l1_cost(xs)
        assert pelt(n, cost, beta) == optimal_partitioning(n, cost, beta)


def test_equals_brute_force_over_all_partitions():
    rng = random.Random(1989)
    for trial in range(200):
        n = rng.randint(1, 10)
        xs = [Fraction(rng.randint(-4, 4)) for _ in range(n)]
        beta = Fraction(rng.randint(0, 20), rng.randint(1, 3))
        cost = rss_cost(xs) if trial % 2 else l1_cost(xs)
        value, cps = pelt(n, cost, beta)
        assert value == brute_force(n, cost, beta)
        assert penalized(cost, n, beta, cps) == value


def test_smaller_k_is_exact_and_too_large_k_is_not():
    rng = random.Random(5)
    broken = 0
    for _ in range(100):
        n = rng.randint(1, 20)
        xs = [Fraction(rng.randint(-3, 3)) for _ in range(n)]
        beta = Fraction(rng.randint(1, 10))
        ref = optimal_partitioning(n, rss_cost(xs), beta)
        # K = -2 prunes less than the valid K = 0, so the answer stays exact.
        assert pelt(n, rss_cost(xs), beta, k=Fraction(-2)) == ref
        # K = 2 violates C(a..s) + C(s+1..b) + K <= C(a..b) for the RSS cost; it may prune the optimum.
        value = pelt(n, rss_cost(xs), beta, k=Fraction(2))[0]
        assert value >= ref[0]
        broken += value > ref[0]
    assert broken > 0


def test_pruning_keeps_candidate_sets_small_with_regular_changes():
    rng = random.Random(3)
    n = 2000
    xs = []
    mu = 0
    for i in range(n):
        if i % 100 == 0:
            mu = rng.choice([-2, -1, 0, 1, 2])
        xs.append(rng.gauss(mu, 1.0))
    sizes = []
    value, cps = pelt(n, rss_cost(xs), 2 * math.log(n), sizes=sizes)
    assert sum(sizes) / n < 150
    ref = optimal_partitioning(300, rss_cost(xs[:300]), 2 * math.log(n))
    assert abs(pelt(300, rss_cost(xs[:300]), 2 * math.log(n))[0] - ref[0]) < 1e-9

History

Auger and Lawrence (1989) gave the segment neighbourhood dynamic programme for a fixed number of segments. Jackson et al. (2005) gave the optimal partitioning recursion for a penalized number of segments. Killick, Fearnhead and Eckley (2012) added the pruning step, proved that it keeps the exact optimum, and proved the expected linear cost under conditions on the data. Maidstone et al. (2017) compared inequality pruning with functional pruning, and Haynes, Eckley and Fearnhead (2017) gave CROPS for a range of penalties.

References

  1. 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 optimal partitioning recursion, the pruning condition on the cost with the constant K, the proof that pruning keeps the optimum, and the conditions for an expected linear cost
  2. Brad Jackson, Jeffrey D. Scargle and others, An algorithm for optimal partitioning of data on an interval, IEEE Signal Processing Letters 12(2) (2005), the optimal partitioning recursion over the position of the last change point
  3. I. E. Auger and C. E. Lawrence, Algorithms for the optimal identification of segment neighborhoods, Bulletin of Mathematical Biology 51(1) (1989), the segment neighbourhood recursion for a fixed number of segments
  4. Robert Maidstone, Toby Hocking, Guillem Rigaill and Paul Fearnhead, On optimal multiple changepoint algorithms for large data, Statistics and Computing 27(2) (2017), functional pruning (FPOP and pDPA) and its comparison with the inequality pruning of PELT
  5. Kaylea Haynes, Idris A. Eckley and Paul Fearnhead, Computationally efficient changepoint detection for a range of penalties, Journal of Computational and Graphical Statistics 26(1) (2017), the CROPS algorithm that finds the optimal segmentations for all penalties in an interval
  6. Charles Truong, Laurent Oudre and Nicolas Vayatis, Selective review of offline change point detection methods, Signal Processing 167 (2020), the sections on cost functions, penalties and exact search methods

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