Skip to content

DTime series · ts.changepoint

Change-point tests (level shifts)

Did the level of the series jump at some point — and if so, when, and by how much?

Single change-point tests for a shift in the mean — Pettitt's rank test, Buishand's range and U statistics, the standard normal homogeneity test (SNHT) and Lanzante's rank procedure — each returning the most probable change point, plus PELT for several shifts at once with a penalized Normal cost.

Verified in Python and R Python and R agree to 10 decimals Seeded Also called change point, changepoint, change-point detection…

A real result

Example “Battery guide”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Change-point testsRecorded · Python and R agreeRecorded 2026-11-17 · 29 values compared
R

Pettitt = 529.00, p < .001; Buishand range = 2.04, p = .002; Buishand U = 1.12, p = .003; SNHT = 19.27, p = .001; Lanzante = 161.00, p < .001

Pettitt K
529
p
0.0010
Change after observation
23

Effect size

  • Shift in mean (after − before) 1.109

Plots

x with the most probable change pointHow does the series move over time, and where is an estimated break?
View data
tx
10.5406
2−1.040
30.1992
4−0.0047
5−0.5666
6−2.396
7−0.5951
8−0.8601
90.2936
10−0.2738
11−0.1882
12−0.4904
130.0386
140.0542
15−2.247
161.667
170.9564
180.5776
19−0.4247
201.090
210.0913
220.2753
23−0.9320
241.946
250.5482
262.428
272.271
280.6181
291.225
302.326
310.0910
320.8064
330.4053
341.013
350.8824
361.885
371.333
38−0.1318
391.357
40−0.0249
41−0.3373
421.618
43−0.3442
441.187
450.0663
462.338
471.652
480.5575
491.779
501.426
51−0.1499
520.8338
530.1294
541.529
550.4552
560.8886
57−0.0964
580.1990
591.314
600.2009
Pettitt's U over time: xWhere does the series most likely change level, and is the change beyond chance?
View data
tx
10.5406
2−1.040
30.1992
4−0.0047
5−0.5666
6−2.396
7−0.5951
8−0.8601
90.2936
10−0.2738
11−0.1882
12−0.4904
130.0386
140.0542
15−2.247
161.667
170.9564
180.5776
19−0.4247
201.090
210.0913
220.2753
23−0.9320
241.946
250.5482
262.428
272.271
280.6181
291.225
302.326
310.0910
320.8064
330.4053
341.013
350.8824
361.885
371.333
38−0.1318
391.357
40−0.0249
41−0.3373
421.618
43−0.3442
441.187
450.0663
462.338
471.652
480.5575
491.779
501.426
51−0.1499
520.8338
530.1294
541.529
550.4552
560.8886
57−0.0964
580.1990
591.314
600.2009
Cumulative deviations from the mean: xDoes the running sum of deviations from the mean bend sharply — a shift in level?
View data
tx
10.5406
2−1.040
30.1992
4−0.0047
5−0.5666
6−2.396
7−0.5951
8−0.8601
90.2936
10−0.2738
11−0.1882
12−0.4904
130.0386
140.0542
15−2.247
161.667
170.9564
180.5776
19−0.4247
201.090
210.0913
220.2753
23−0.9320
241.946
250.5482
262.428
272.271
280.6181
291.225
302.326
310.0910
320.8064
330.4053
341.013
350.8824
361.885
371.333
38−0.1318
391.357
40−0.0249
41−0.3373
421.618
43−0.3442
441.187
450.0663
462.338
471.652
480.5575
491.779
501.426
51−0.1499
520.8338
530.1294
541.529
550.4552
560.8886
57−0.0964
580.1990
591.314
600.2009

Assumptions

  • Independent values — Lag-1 autocorrelation around the segment means is -0.12 (|ρ₁| ≤ 0.25).
  • Roughly normal values — Skewness of the values around the segment means is -0.16.

Change-point tests

TestStatisticpChange afterMean beforeMean afterAt α = .05
Pettitt529< .00123−0.18410.9250shift
Buishand range2.037.00223−0.18410.9250shift
Buishand U1.119.00323−0.18410.9250shift
SNHT19.266.00115−0.50240.8339shift
Lanzante161< .00123−0.18410.9250shift
  • Buishand and SNHT p-values from 999 simulated normal series (seed 42; identical in Python and R).
  • Lanzante's Wilcoxon p ignores that the split point was chosen from the data: with no shift it rejected about 37% of simulated series at the 5% level. Use the permutation p-value to judge.
  • A single-shift test also reacts to a gradual trend (the cumulative deviations rise and fall); check the series plot and a trend test before calling it a jump.
Python

Pettitt = 529.00, p < .001; Buishand range = 2.04, p = .002; Buishand U = 1.12, p = .003; SNHT = 19.27, p = .001; Lanzante = 161.00, p < .001

Pettitt K
529
p
0.0010
Change after observation
23

Effect size

  • Shift in mean (after − before) 1.109

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Independent values — Lag-1 autocorrelation around the segment means is -0.12 (|ρ₁| ≤ 0.25).
  • Roughly normal values — Skewness of the values around the segment means is -0.16.

Change-point tests

TestStatisticpChange afterMean beforeMean afterAt α = .05
Pettitt529< .00123−0.18410.9250shift
Buishand range2.037.00223−0.18410.9250shift
Buishand U1.119.00323−0.18410.9250shift
SNHT19.266.00115−0.50240.8339shift
Lanzante161< .00123−0.18410.9250shift
  • Buishand and SNHT p-values from 999 simulated normal series (seed 42; identical in Python and R).
  • Lanzante's Wilcoxon p ignores that the split point was chosen from the data: with no shift it rejected about 37% of simulated series at the 5% level. Use the permutation p-value to judge.
  • A single-shift test also reacts to a gradual trend (the cumulative deviations rise and fall); check the series plot and a trend test before calling it a jump.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Battery guides3_trend · time: t · value: x
  • Pettitt guides3_trend · time: t · value: x
  • Pettitt nile permutationml_nile · time: year · value: flow
  • Buishand range guides3_trend · time: t · value: x
  • Buishand u guides3_trend · time: t · value: x
  • Snht guides3_trend · time: t · value: x
  • Lanzante guides3_trend · time: t · value: x
  • Lanzante permutations3_shifts · time: week · value: noise

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • Time series (ARIMA, ETS) · DS & ML Decision Guide · Predict — forecast or classify outcomes

What you need

Seriesnumeric · 1 column
The values over time (one per period).
Timetemporal / numeric · 0–1 column
Orders the rows (omit to use the row order).

Choices you make

hypothesis

Testdefault battery

H₀: one level throughout (no shift in the mean).

  • Battery (Pettitt, Buishand R and U, SNHT, Lanzante)(default) — Each test weighs a shift differently; read where they agree on the location.
  • Pettitt (ranks) — Rank-based, so outliers and skew do not matter; best for a shift in the middle.
  • Buishand range — Range of cumulative deviations; assumes roughly normal values.
  • Buishand U — Squared cumulative deviations: sensitive to shifts anywhere, including near the ends.
  • Standard normal homogeneity (SNHT) — Alexandersson's test, most sensitive to shifts near the start or end of the record.
  • Lanzante (ranks + Wilcoxon) — Locates the shift with ranks, then compares the two segments with a Wilcoxon test.
  • PELT (several shifts) — Finds any number of mean shifts by minimizing a penalized cost (Killick et al. 2012).

options

p-values for Pettitt and Lanzantedefault monte_carlo

Classic approximate p-values, or permutation p-values for the whole procedure (slower, exact under H₀).

  • Classic (Pettitt's approximation; Lanzante's Wilcoxon p) — As published. Lanzante's p ignores that the split was chosen from the data: it rejects about 37% at the 5% level with no shift.
  • Permutation (the whole procedure)(default) — Shuffles the series and repeats the search for the maximum: honest p-values for any n.
Simulationsdefault 4999

Monte-Carlo replicates for Buishand and SNHT (normal null) and permutation p-values.

Penalty per changedefault bic

Cost of adding a change in PELT. Larger penalties find fewer changes.

  • BIC (2 log n)(default) — A mean and a location per change; the usual default.
  • Hannan–Quinn (4 log log n) — Lighter: finds more changes.
  • AIC (4) — Lightest: tends to over-segment long series.
  • Set a value — Uses the penalty you enter; pick it to tune how many changes are found, where larger values find fewer.
Penalty valuedefault 10

Penalty per change, when you set it yourself.

Shortest segmentdefault 5

No two changes closer than this many observations.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Independent values

    Serial correlation produces runs that look like shifts: the tests then find breaks too often.

  • Roughly normal values

    Buishand and SNHT assume normal values; Pettitt and Lanzante use ranks.

    • If violated → Use Pettitt's rank test — Pettitt's statistic uses only the ranks, so skewed or heavy-tailed values do not distort its p-value; the question (one shift in level) stays the same.

What it reports

n_obs
How many independent units the analysis used; it sets precision and power.
stat
A single number that summarizes how far your data are from what H₀ predicts.
reject
A p-value below the chosen α; it says the data are hard to explain by chance alone, not that the effect matters.
location
The moment a series' level (mean) jumps — a relocated station, a new instrument, a policy taking effect.

Per group, level or term: p, test, test_label, location_label, mean_before, mean_after, shift, n_reject, reps, rho1, n_changes, penalty, sigma, change_<i>, segment_mean_<i>, <test>_stat, <test>_p, <test>_location, exact

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • Lanzante's classic Wilcoxon p ignores that the split was chosen from the data: with no shift it rejects 36.5% at the 5% level (n = 60, 400 series). The method defaults to permutation p-values for Pettitt and Lanzante, which hold near 5%; 'classic' reproduces trend::lanzante.test.
  • Same twin in both engines; Monte-Carlo and permutation p-values use the shared Wichmann–Hill stream, so they agree exactly.
  • Statistics and locations equal trend::pettitt.test / br.test / bu.test / snh.test / lanzante.test; Buishand's statistics use the sample sd (n − 1) as trend does (Buishand 1982 divides by n). trend simulates its own Monte-Carlo p-values (R's RNG), so those p-values differ slightly.
  • PELT uses a Normal mean-change cost scaled by a robust σ̂ = MAD(Δx)/√2 and penalties per change of 2 log n (BIC), 4 log log n or 4; changepoint::cpt.mean assumes σ = 1 unless the data are scaled.
Python

The exact script CodeSplash ran for example “Battery guide” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Change-point tests (level shifts)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.changepoint 1.0.2 · spec acf7553f2adb06ba
# Dataset: s3_trend (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import math

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import trend, ts

# %% Data
df = pd.read_parquet("tests/parity/fixtures/s3_trend.parquet", columns=["x", "t"])
n_input = len(df)
df = df.dropna(subset=["x", "t"])  # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["x", "t"])  # infinite values stop the run (registry/errors.yaml)

# %% Series
VALUE = "x"
TIME = "t"
TEMPORAL = False
TEST = "battery"
CALIBRATION = "classic"
REPS = 999
SEED = 42
PENALTY = "bic"
PEN_VALUE = 10
MIN_SIZE = 5
s = ts.ordered(df, VALUE, TIME, TEMPORAL)
d = s["df"].reset_index(drop=True)
keep = d[VALUE].notna()
if (~keep).sum():
    warnings.append(f"{int((~keep).sum())} rows with missing values were left out; the tests assume one value per evenly spaced time.")
d = d[keep].reset_index(drop=True)
x = d[VALUE].to_numpy(dtype=float)
labels = ts.time_labels(d[TIME].to_numpy(), TEMPORAL) if TIME else list(range(1, len(x) + 1))
n = len(x)
if s["dups"]:
    warnings.append(f"{s['dups']} repeated time values: the tests assume one observation per evenly spaced time.")
# Too short or constant series stop with a catalog message (registry/errors.yaml): the range and SNHT
# statistics divide by the standard deviation.
cs.check_rows(n, 10, "A change-point test")
check_not_constant(x, VALUE)
LABELS = {"pettitt": "Pettitt K", "buishand_range": "Buishand R/√n", "buishand_u": "Buishand U", "snht": "SNHT T₀", "lanzante": "Lanzante W"}
NAMES = {"pettitt": "Pettitt", "buishand_range": "Buishand range", "buishand_u": "Buishand U", "snht": "SNHT", "lanzante": "Lanzante"}


def run(t):
    if t == "pettitt":
        return trend.pettitt(x, "monte_carlo" if CALIBRATION == "monte_carlo" else "asymptotic", REPS, SEED)
    if t == "buishand_range":
        return trend.buishand_range(x, REPS, SEED)
    if t == "buishand_u":
        return trend.buishand_u(x, REPS, SEED)
    if t == "snht":
        return trend.snht(x, REPS, SEED)
    return trend.lanzante(x, CALIBRATION, REPS, SEED)


def seg_means(k):
    return float(x[:k].mean()), float(x[k:].mean())


# %% Tests
values = {"n_obs": n, "test": TEST}
rows = []
notes = []
segments = None
if TEST == "pelt":
    r = trend.pelt_mean(x, PENALTY, PEN_VALUE, MIN_SIZE)
    bounds = [0] + r["changes"] + [n]
    segments = np.concatenate([np.full(bounds[i + 1] - bounds[i], i + 1) for i in range(len(bounds) - 1)])
    values.update({"n_changes": r["n_changes"], "penalty": r["penalty"], "sigma": r["sigma"],
                   "stat": float(r["n_changes"]), "reject": int(r["n_changes"] > 0),
                   "location": r["changes"][0] if r["changes"] else 0})
    for i, c in enumerate(r["changes"], start=1):
        values[f"change_{i}"] = c
    for i, m in enumerate(r["means"], start=1):
        values[f"segment_mean_{i}"] = m
    for i in range(len(bounds) - 1):
        a, b = bounds[i], bounds[i + 1]
        rows.append({"segment": i + 1, "from": str(labels[a]), "to": str(labels[b - 1]), "n": b - a, "mean": r["means"][i],
                     "shift": None if i == 0 else r["means"][i] - r["means"][i - 1]})
    label = "PELT"
    summary = (f"PELT found {r['n_changes']} change{'s' if r['n_changes'] != 1 else ''} in the level of {VALUE} ({n} observations)"
               + (": after " + ", ".join(str(labels[c - 1]) for c in r["changes"]) + "." if r["changes"] else "."))
    notes.append(f"Penalty {r['penalty']:.3g} per change on a Normal cost scaled by a robust σ̂ = {r['sigma']:.4g} (MAD of differences / √2); shortest segment {MIN_SIZE}.")
else:
    tests = ["pettitt", "buishand_range", "buishand_u", "snht", "lanzante"] if TEST == "battery" else [TEST]
    res = {t: run(t) for t in tests}
    for t in tests:
        k = res[t]["location"]
        b, a = seg_means(k)
        rows.append({"test": NAMES[t], "statistic": res[t]["stat"], "p": res[t]["p"], "after": str(labels[k - 1]), "location": k,
                     "mean_before": b, "mean_after": a, "verdict": "shift" if res[t]["p"] < 0.05 else "no evidence"})
    main = res[tests[0]]
    k = main["location"]
    before, after = seg_means(k)
    values.update({"stat": main["stat"], "p": main["p"], "reject": int(main["p"] < 0.05), "location": k,
                   "location_label": str(labels[k - 1]), "mean_before": before, "mean_after": after, "shift": after - before})
    if TEST == "lanzante":
        values["exact"] = int(bool(main.get("exact")))
    if TEST == "battery":
        for t in tests:
            values[f"{t}_stat"] = res[t]["stat"]
            values[f"{t}_p"] = res[t]["p"]
            values[f"{t}_location"] = res[t]["location"]
        values["n_reject"] = sum(1 for t in tests if res[t]["p"] < 0.05)
        label = "Change-point battery"
        locs = sorted({res[t]["location"] for t in tests})
        summary = (f"{values['n_reject']} of {len(tests)} change-point tests reject at α = .05 for {VALUE}; "
                   + ("they agree on a shift after " + str(labels[locs[0] - 1]) if len(locs) == 1 else
                      "most probable change points: " + ", ".join(f"{NAMES[t]} after {labels[res[t]['location'] - 1]}" for t in tests))
                   + f" (mean {before:.4g} → {after:.4g} at Pettitt's point).")
    else:
        label = NAMES[TEST]
        summary = (f"{label} for {VALUE}: {main['stat']:.3f}, {cs.fmt_p(main['p'])} — "
                   + (f"a shift after {labels[k - 1]} (mean {before:.4g} → {after:.4g})." if main["p"] < 0.05 else "no evidence of a shift in level."))
    if any(t in tests for t in ("buishand_range", "buishand_u", "snht")):
        notes.append(f"Buishand and SNHT p-values from {REPS} simulated normal series (seed {SEED}; identical in Python and R).")
    if "lanzante" in tests and CALIBRATION != "monte_carlo":
        notes.append("Lanzante's Wilcoxon p ignores that the split point was chosen from the data: with no shift it rejected about 37% of simulated series at the 5% level. Use the permutation p-value to judge.")
    if CALIBRATION == "monte_carlo" and any(t in tests for t in ("pettitt", "lanzante")):
        notes.append(f"Pettitt / Lanzante p-values from {REPS} permutations of the series (seed {SEED}).")
values["test_label"] = label
if TEST != "pelt":
    values["reps"] = REPS

# %% Assumptions
k0 = values["location"] if values.get("location") else n // 2
resid = np.concatenate([x[:k0] - x[:k0].mean(), x[k0:] - x[k0:].mean()]) if 0 < k0 < n else x - x.mean()
if segments is not None:
    resid = x.copy()
    for g in np.unique(segments):
        resid[segments == g] -= x[segments == g].mean()
rho1 = float((resid[1:] @ resid[:-1]) / (resid @ resid))
values["rho1"] = rho1
crit = 1.959963984540054 / math.sqrt(n)
if abs(rho1) <= crit:
    ind = ("pass", f"Lag-1 autocorrelation around the segment means is {rho1:.2f} (|ρ₁| ≤ {crit:.2f}).")
else:
    ind = ("warn", f"Lag-1 autocorrelation around the segment means is {rho1:.2f} (> {crit:.2f}): persistent noise creates runs that look like shifts.")
sk = float(((resid - resid.mean()) ** 3).mean() / ((resid - resid.mean()) ** 2).mean() ** 1.5)
normal_ok = abs(sk) < 1.0
assumptions = [{"key": "independence", "label": "Independent values", "status": ind[0], "detail": ind[1]},
               {"key": "normality", "label": "Roughly normal values",
                "status": "pass" if normal_ok or TEST in ("pettitt", "lanzante") else "warn",
                "detail": f"Skewness of the values around the segment means is {sk:.2f}"
                + ("." if normal_ok else " — Buishand and SNHT assume normal values; Pettitt and Lanzante use ranks.")}]

# %% Charts
kind = "temporal" if TEMPORAL else "numeric"
xcol = cs.col(TIME or "index", labels, kind=kind)
charts = []
if TEST == "pelt":
    charts.append(cs.chart("segments", "segment-means", f"{VALUE} with segment means", {"x": xcol, "y": cs.col(VALUE, x),
                                                                                         "segment": cs.col("segment", [str(int(g)) for g in segments], kind="categorical")}))
else:
    charts.append(cs.chart("series", "series-line", f"{VALUE} with the most probable change point", {"x": xcol, "y": cs.col(VALUE, x)},
                           controls={"marker": values["location"]}))
    if TEST in ("battery", "pettitt", "lanzante"):
        charts.append(cs.chart("pettitt", "pettitt-u", f"Pettitt's U over time: {VALUE}", {"x": xcol, "y": cs.col(VALUE, x)}))
    if TEST in ("battery", "buishand_range", "buishand_u", "snht"):
        charts.append(cs.chart("cusum", "buishand-cusum", f"Cumulative deviations from the mean: {VALUE}", {"x": xcol, "y": cs.col(VALUE, x)}))
columns = ([{"key": "segment", "label": "Segment", "type": "integer"}, {"key": "from", "label": "From", "type": "string"},
            {"key": "to", "label": "To", "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
            {"key": "mean", "label": "Mean", "type": "number"}, {"key": "shift", "label": "Change", "type": "number"}] if TEST == "pelt" else
           [{"key": "test", "label": "Test", "type": "string"}, {"key": "statistic", "label": "Statistic", "type": "number"},
            {"key": "p", "label": "p", "type": "pvalue"}, {"key": "after", "label": "Change after", "type": "string"},
            {"key": "mean_before", "label": "Mean before", "type": "number"}, {"key": "mean_after", "label": "Mean after", "type": "number"},
            {"key": "verdict", "label": "At α = .05", "type": "string"}])
notes.append("A single-shift test also reacts to a gradual trend (the cumulative deviations rise and fall); check the series plot and a trend test before calling it a jump.")
statistics = ([{"key": "n_changes", "label": "Changes", "value": values["n_changes"]}] if TEST == "pelt" else
              [{"key": "stat", "label": LABELS[TEST if TEST != "battery" else "pettitt"], "value": values["stat"]},
               {"key": "p", "label": "p", "value": values["p"]}, {"key": "location", "label": "Change after observation", "value": values["location"]}])
cs.publish({
    "method": "ts.changepoint",
    "methodVersion": "1.0.2",
    "title": "Change-point tests",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": "" if TEST in ("pelt",) else "; ".join(f"{r['test']} = {r['statistic']:.2f}, {cs.fmt_p(r['p'])}" for r in rows),
    "statistics": statistics,
    "tables": [{"key": "segments" if TEST == "pelt" else "tests", "title": "Segments" if TEST == "pelt" else "Change-point tests", "columns": columns, "rows": rows}],
    "effectSizes": [] if TEST == "pelt" else [{"key": "shift", "label": "Shift in mean (after − before)", "value": values["shift"],
                                                "method": "Difference of the segment means at the most probable change point"}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": notes,
    "charts": charts,
    "values": values,
})
R

The exact script CodeSplash ran for example “Battery guide” · R version 4.5.1 (2025-06-13)

# Change-point tests (level shifts)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.changepoint 1.0.2 · spec acf7553f2adb06ba
# Dataset: s3_trend (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s3_trend.parquet", col_select = c("x", "t")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("x", "t")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("x", "t"))  # infinite values stop the run (registry/errors.yaml)

# %% Series
VALUE <- "x"
TIME <- "t"
TEMPORAL <- FALSE
TEST <- "battery"
CALIBRATION <- "classic"
REPS <- 999
SEED <- 42
PENALTY <- "bic"
PEN_VALUE <- 10
MIN_SIZE <- 5
s <- cs_ts_ordered(df, VALUE, TIME, TEMPORAL)
d <- s$df
keep <- !is.na(d[[VALUE]])
if (sum(!keep) > 0) warnings <- c(warnings, sprintf("%d rows with missing values were left out; the tests assume one value per evenly spaced time.", sum(!keep)))
d <- d[keep, , drop = FALSE]
x <- as.numeric(d[[VALUE]])
labels <- if (!is.null(TIME)) cs_ts_time_labels(d[[TIME]], TEMPORAL) else seq_along(x)
n <- length(x)
if (s$dups > 0) warnings <- c(warnings, sprintf("%d repeated time values: the tests assume one observation per evenly spaced time.", s$dups))
# Too short or constant series stop with a catalog message (registry/errors.yaml): the range and SNHT
# statistics divide by the standard deviation.
cs_check_rows(n, 10, "A change-point test")
cs_check_not_constant(x, VALUE)
LABELS <- list(pettitt = "Pettitt K", buishand_range = "Buishand R/√n", buishand_u = "Buishand U", snht = "SNHT T₀", lanzante = "Lanzante W")
NAMES <- list(pettitt = "Pettitt", buishand_range = "Buishand range", buishand_u = "Buishand U", snht = "SNHT", lanzante = "Lanzante")
lab <- function(i) as.character(labels[[i]])
fmt4 <- function(v) formatC(v, digits = 4, format = "g")
run_test <- function(t) switch(t,
  pettitt = cs_tr_pettitt(x, if (CALIBRATION == "monte_carlo") "monte_carlo" else "asymptotic", REPS, SEED),
  buishand_range = cs_tr_buishand_range(x, REPS, SEED),
  buishand_u = cs_tr_buishand_u(x, REPS, SEED),
  snht = cs_tr_snht(x, REPS, SEED),
  cs_tr_lanzante(x, CALIBRATION, REPS, SEED))
seg_means <- function(k) c(mean(x[1:k]), mean(x[(k + 1):n]))

# %% Tests
values <- list(n_obs = n, test = TEST)
rows <- list()
notes <- list()
segments <- NULL
if (TEST == "pelt") {
  r <- cs_tr_pelt_mean(x, PENALTY, PEN_VALUE, MIN_SIZE)
  bounds <- c(0, r$changes, n)
  segments <- unlist(lapply(seq_len(length(bounds) - 1), function(i) rep(i, bounds[i + 1] - bounds[i])))
  values <- c(values, list(n_changes = r$n_changes, penalty = r$penalty, sigma = r$sigma, stat = as.numeric(r$n_changes),
                           reject = as.integer(r$n_changes > 0), location = if (length(r$changes)) r$changes[1] else 0))
  for (i in seq_along(r$changes)) values[[paste0("change_", i)]] <- r$changes[i]
  for (i in seq_along(r$means)) values[[paste0("segment_mean_", i)]] <- r$means[i]
  for (i in seq_len(length(bounds) - 1)) {
    a <- bounds[i]
    b <- bounds[i + 1]
    rows[[i]] <- list(segment = i, from = lab(a + 1), to = lab(b), n = b - a, mean = r$means[i], shift = if (i == 1) NULL else r$means[i] - r$means[i - 1])
  }
  label <- "PELT"
  summary <- paste0(sprintf("PELT found %d change%s in the level of %s (%d observations)", r$n_changes, if (r$n_changes != 1) "s" else "", VALUE, n),
                    if (length(r$changes)) paste0(": after ", paste(vapply(r$changes, lab, ""), collapse = ", "), ".") else ".")
  notes <- c(notes, sprintf("Penalty %s per change on a Normal cost scaled by a robust σ̂ = %s (MAD of differences / √2); shortest segment %d.",
                            formatC(r$penalty, digits = 3, format = "g"), fmt4(r$sigma), MIN_SIZE))
} else {
  tests <- if (TEST == "battery") c("pettitt", "buishand_range", "buishand_u", "snht", "lanzante") else TEST
  res <- lapply(stats::setNames(tests, tests), run_test)
  for (t in tests) {
    k <- res[[t]]$location
    m <- seg_means(k)
    rows[[length(rows) + 1]] <- list(test = NAMES[[t]], statistic = res[[t]]$stat, p = res[[t]]$p, after = lab(k), location = k,
                                     mean_before = m[1], mean_after = m[2], verdict = if (res[[t]]$p < 0.05) "shift" else "no evidence")
  }
  main <- res[[tests[1]]]
  k <- main$location
  m <- seg_means(k)
  values <- c(values, list(stat = main$stat, p = main$p, reject = as.integer(main$p < 0.05), location = k, location_label = lab(k),
                           mean_before = m[1], mean_after = m[2], shift = m[2] - m[1]))
  if (TEST == "lanzante") values$exact <- as.integer(isTRUE(main$exact))
  if (TEST == "battery") {
    for (t in tests) {
      values[[paste0(t, "_stat")]] <- res[[t]]$stat
      values[[paste0(t, "_p")]] <- res[[t]]$p
      values[[paste0(t, "_location")]] <- res[[t]]$location
    }
    values$n_reject <- sum(vapply(tests, function(t) res[[t]]$p < 0.05, logical(1)))
    label <- "Change-point battery"
    locs <- sort(unique(vapply(tests, function(t) res[[t]]$location, numeric(1))))
    summary <- paste0(sprintf("%d of %d change-point tests reject at α = .05 for %s; ", values$n_reject, length(tests), VALUE),
                      if (length(locs) == 1) paste0("they agree on a shift after ", lab(locs[1]))
                      else paste0("most probable change points: ", paste(vapply(tests, function(t) sprintf("%s after %s", NAMES[[t]], lab(res[[t]]$location)), ""), collapse = ", ")),
                      sprintf(" (mean %s → %s at Pettitt's point).", fmt4(m[1]), fmt4(m[2])))
  } else {
    label <- NAMES[[TEST]]
    summary <- paste0(sprintf("%s for %s: %.3f, %s — ", label, VALUE, main$stat, cs_fmt_p(main$p)),
                      if (main$p < 0.05) sprintf("a shift after %s (mean %s → %s).", lab(k), fmt4(m[1]), fmt4(m[2])) else "no evidence of a shift in level.")
  }
  if (any(tests %in% c("buishand_range", "buishand_u", "snht")))
    notes <- c(notes, sprintf("Buishand and SNHT p-values from %d simulated normal series (seed %d; identical in Python and R).", REPS, SEED))
  if ("lanzante" %in% tests && CALIBRATION != "monte_carlo")
    notes <- c(notes, "Lanzante's Wilcoxon p ignores that the split point was chosen from the data: with no shift it rejected about 37% of simulated series at the 5% level. Use the permutation p-value to judge.")
  if (CALIBRATION == "monte_carlo" && any(tests %in% c("pettitt", "lanzante")))
    notes <- c(notes, sprintf("Pettitt / Lanzante p-values from %d permutations of the series (seed %d).", REPS, SEED))
}
values$test_label <- label
if (TEST != "pelt") values$reps <- REPS

# %% Assumptions
k0 <- if (!is.null(values$location) && values$location > 0) values$location else n %/% 2
resid <- if (k0 > 0 && k0 < n) c(x[1:k0] - mean(x[1:k0]), x[(k0 + 1):n] - mean(x[(k0 + 1):n])) else x - mean(x)
if (!is.null(segments)) {
  resid <- x
  for (g in unique(segments)) resid[segments == g] <- x[segments == g] - mean(x[segments == g])
}
rho1 <- sum(resid[-1] * resid[-n]) / sum(resid * resid)
values$rho1 <- rho1
crit <- 1.959963984540054 / sqrt(n)
ind <- if (abs(rho1) <= crit) c("pass", sprintf("Lag-1 autocorrelation around the segment means is %.2f (|ρ₁| ≤ %.2f).", rho1, crit)) else
  c("warn", sprintf("Lag-1 autocorrelation around the segment means is %.2f (> %.2f): persistent noise creates runs that look like shifts.", rho1, crit))
rc <- resid - mean(resid)
sk <- mean(rc^3) / mean(rc^2)^1.5
normal_ok <- abs(sk) < 1
assumptions <- list(list(key = "independence", label = "Independent values", status = ind[1], detail = ind[2]),
                    list(key = "normality", label = "Roughly normal values", status = if (normal_ok || TEST %in% c("pettitt", "lanzante")) "pass" else "warn",
                         detail = paste0(sprintf("Skewness of the values around the segment means is %.2f", sk),
                                         if (normal_ok) "." else " — Buishand and SNHT assume normal values; Pettitt and Lanzante use ranks.")))

# %% Charts
kind <- if (TEMPORAL) "temporal" else "numeric"
xcol <- cs_col(if (is.null(TIME)) "index" else TIME, labels, kind = kind)
charts <- list()
if (TEST == "pelt") {
  charts[[1]] <- cs_chart("segments", "segment-means", sprintf("%s with segment means", VALUE),
                          list(x = xcol, y = cs_col(VALUE, x), segment = cs_col("segment", as.character(segments), kind = "categorical")))
} else {
  charts[[1]] <- cs_chart("series", "series-line", sprintf("%s with the most probable change point", VALUE), list(x = xcol, y = cs_col(VALUE, x)),
                          controls = list(marker = values$location))
  if (TEST %in% c("battery", "pettitt", "lanzante"))
    charts[[length(charts) + 1]] <- cs_chart("pettitt", "pettitt-u", sprintf("Pettitt's U over time: %s", VALUE), list(x = xcol, y = cs_col(VALUE, x)))
  if (TEST %in% c("battery", "buishand_range", "buishand_u", "snht"))
    charts[[length(charts) + 1]] <- cs_chart("cusum", "buishand-cusum", sprintf("Cumulative deviations from the mean: %s", VALUE), list(x = xcol, y = cs_col(VALUE, x)))
}
columns <- if (TEST == "pelt") list(list(key = "segment", label = "Segment", type = "integer"), list(key = "from", label = "From", type = "string"),
                                    list(key = "to", label = "To", type = "string"), list(key = "n", label = "n", type = "integer"),
                                    list(key = "mean", label = "Mean", type = "number"), list(key = "shift", label = "Change", type = "number")) else
  list(list(key = "test", label = "Test", type = "string"), list(key = "statistic", label = "Statistic", type = "number"),
       list(key = "p", label = "p", type = "pvalue"), list(key = "after", label = "Change after", type = "string"),
       list(key = "mean_before", label = "Mean before", type = "number"), list(key = "mean_after", label = "Mean after", type = "number"),
       list(key = "verdict", label = "At α = .05", type = "string"))
notes <- c(notes, "A single-shift test also reacts to a gradual trend (the cumulative deviations rise and fall); check the series plot and a trend test before calling it a jump.")
statistics <- if (TEST == "pelt") list(list(key = "n_changes", label = "Changes", value = values$n_changes)) else
  list(list(key = "stat", label = LABELS[[if (TEST == "battery") "pettitt" else TEST]], value = values$stat), list(key = "p", label = "p", value = values$p),
       list(key = "location", label = "Change after observation", value = values$location))
cs_publish(list(
  method = "ts.changepoint",
  methodVersion = "1.0.2",
  title = "Change-point tests",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = if (TEST == "pelt") "" else paste(vapply(rows, function(r) sprintf("%s = %.2f, %s", r$test, r$statistic, cs_fmt_p(r$p)), ""), collapse = "; "),
  statistics = statistics,
  tables = list(list(key = if (TEST == "pelt") "segments" else "tests", title = if (TEST == "pelt") "Segments" else "Change-point tests", columns = columns, rows = rows)),
  effectSizes = if (TEST == "pelt") list() else list(list(key = "shift", label = "Shift in mean (after − before)", value = values$shift,
                                                         method = "Difference of the segment means at the most probable change point")),
  assumptions = assumptions,
  warnings = warnings,
  notes = notes,
  charts = charts,
  values = values
))

Sources

  • Pettitt, A. N. (1979). A non-parametric approach to the change-point problem. Applied Statistics, 28, 126–135.
  • Buishand, T. A. (1982). Some methods for testing the homogeneity of rainfall records. J. Hydrology, 58, 11–27.
  • Buishand, T. A. (1984). Tests for detecting a shift in the mean of hydrological time series. J. Hydrology, 73, 51–69.
  • Alexandersson, H. (1986). A homogeneity test applied to precipitation data. J. Climatology, 6, 661–675.
  • Lanzante, J. R. (1996). Resistant, robust and non-parametric techniques for the analysis of climate data. Int. J. Climatology, 16, 1197–1226.
  • Killick, R., Fearnhead, P., & Eckley, I. A. (2012). Optimal detection of changepoints with a linear computational cost. JASA, 107, 1590–1598.

From the CodeSplash method registry · ts.changepoint v1.0.2.