Did the level shift? Change-point tests
Find when a level shifted with Pettitt, Buishand, SNHT and Lanzante, date several shifts with PELT, and avoid mistaking autocorrelation or trend for a break.
What runs in CodeSplash
- STAT230Pettitt change point test Runs in CodeSplash
- STAT231Buishand range test Runs in CodeSplash
- STAT232Buishand U test Runs in CodeSplash
- STAT233Standard normal homogeneity test Runs in CodeSplash
- STAT234Lanzante change point test Runs in CodeSplash
- Change-point tests (level shifts) Verified in Python and R
You will be able to
- Say what a single change-point test asks and how it searches for a date
- Compare the rank-based and normal-theory tests, and why they can name different dates
- Use PELT with a penalty to date several shifts
Read first
The Nile in 1898
ReadThe Nile's annual flow seems to step down around the turn of the last century. You could pick the date from the plot, then test before against after. That's the problem: picking the most extreme date, then testing it as if it were chosen in advance, gives a p-value that's far too small.
A change-pointChange pointThe moment a series' level (mean) jumps — a relocated station, a new instrument, a policy taking effect. test accounts for the search. It asks: over all possible dates, is the largest before–after contrast surprising?
Predict the size of the search
PredictPredict first
A series has no shift at all. You run a t test at every possible split, and report the largest difference at the 0.05 level.
How often does that find a "significant" shift?
Reveal
Well above 5%. You've taken the best of many comparisons. Change-point tests have reference distributions, or simulations, built for the maximum.
Pettitt: ranks
ReadPettitt's testPettitt testA rank-based test for one shift in level — K is the largest gap between the ranks before and after a split. uses a Mann–Whitney count at each candidate date, and takes the largest in absolute value:
It uses ranks, so it isn't thrown by outliers or skew.
For the Nile, K = 1,617 with a permutation p of 0.001. The date is 1898, and the mean falls from 1,098 to 850.
Five tests, one battery
In the appPettitt = 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
View data
| t | x |
|---|---|
| 1 | 0.5406 |
| 2 | −1.040 |
| 3 | 0.1992 |
| 4 | −0.0047 |
| 5 | −0.5666 |
| 6 | −2.396 |
| 7 | −0.5951 |
| 8 | −0.8601 |
| 9 | 0.2936 |
| 10 | −0.2738 |
| 11 | −0.1882 |
| 12 | −0.4904 |
| 13 | 0.0386 |
| 14 | 0.0542 |
| 15 | −2.247 |
| 16 | 1.667 |
| 17 | 0.9564 |
| 18 | 0.5776 |
| 19 | −0.4247 |
| 20 | 1.090 |
| 21 | 0.0913 |
| 22 | 0.2753 |
| 23 | −0.9320 |
| 24 | 1.946 |
| 25 | 0.5482 |
| 26 | 2.428 |
| 27 | 2.271 |
| 28 | 0.6181 |
| 29 | 1.225 |
| 30 | 2.326 |
| 31 | 0.0910 |
| 32 | 0.8064 |
| 33 | 0.4053 |
| 34 | 1.013 |
| 35 | 0.8824 |
| 36 | 1.885 |
| 37 | 1.333 |
| 38 | −0.1318 |
| 39 | 1.357 |
| 40 | −0.0249 |
| 41 | −0.3373 |
| 42 | 1.618 |
| 43 | −0.3442 |
| 44 | 1.187 |
| 45 | 0.0663 |
| 46 | 2.338 |
| 47 | 1.652 |
| 48 | 0.5575 |
| 49 | 1.779 |
| 50 | 1.426 |
| 51 | −0.1499 |
| 52 | 0.8338 |
| 53 | 0.1294 |
| 54 | 1.529 |
| 55 | 0.4552 |
| 56 | 0.8886 |
| 57 | −0.0964 |
| 58 | 0.1990 |
| 59 | 1.314 |
| 60 | 0.2009 |
View data
| t | x |
|---|---|
| 1 | 0.5406 |
| 2 | −1.040 |
| 3 | 0.1992 |
| 4 | −0.0047 |
| 5 | −0.5666 |
| 6 | −2.396 |
| 7 | −0.5951 |
| 8 | −0.8601 |
| 9 | 0.2936 |
| 10 | −0.2738 |
| 11 | −0.1882 |
| 12 | −0.4904 |
| 13 | 0.0386 |
| 14 | 0.0542 |
| 15 | −2.247 |
| 16 | 1.667 |
| 17 | 0.9564 |
| 18 | 0.5776 |
| 19 | −0.4247 |
| 20 | 1.090 |
| 21 | 0.0913 |
| 22 | 0.2753 |
| 23 | −0.9320 |
| 24 | 1.946 |
| 25 | 0.5482 |
| 26 | 2.428 |
| 27 | 2.271 |
| 28 | 0.6181 |
| 29 | 1.225 |
| 30 | 2.326 |
| 31 | 0.0910 |
| 32 | 0.8064 |
| 33 | 0.4053 |
| 34 | 1.013 |
| 35 | 0.8824 |
| 36 | 1.885 |
| 37 | 1.333 |
| 38 | −0.1318 |
| 39 | 1.357 |
| 40 | −0.0249 |
| 41 | −0.3373 |
| 42 | 1.618 |
| 43 | −0.3442 |
| 44 | 1.187 |
| 45 | 0.0663 |
| 46 | 2.338 |
| 47 | 1.652 |
| 48 | 0.5575 |
| 49 | 1.779 |
| 50 | 1.426 |
| 51 | −0.1499 |
| 52 | 0.8338 |
| 53 | 0.1294 |
| 54 | 1.529 |
| 55 | 0.4552 |
| 56 | 0.8886 |
| 57 | −0.0964 |
| 58 | 0.1990 |
| 59 | 1.314 |
| 60 | 0.2009 |
View data
| t | x |
|---|---|
| 1 | 0.5406 |
| 2 | −1.040 |
| 3 | 0.1992 |
| 4 | −0.0047 |
| 5 | −0.5666 |
| 6 | −2.396 |
| 7 | −0.5951 |
| 8 | −0.8601 |
| 9 | 0.2936 |
| 10 | −0.2738 |
| 11 | −0.1882 |
| 12 | −0.4904 |
| 13 | 0.0386 |
| 14 | 0.0542 |
| 15 | −2.247 |
| 16 | 1.667 |
| 17 | 0.9564 |
| 18 | 0.5776 |
| 19 | −0.4247 |
| 20 | 1.090 |
| 21 | 0.0913 |
| 22 | 0.2753 |
| 23 | −0.9320 |
| 24 | 1.946 |
| 25 | 0.5482 |
| 26 | 2.428 |
| 27 | 2.271 |
| 28 | 0.6181 |
| 29 | 1.225 |
| 30 | 2.326 |
| 31 | 0.0910 |
| 32 | 0.8064 |
| 33 | 0.4053 |
| 34 | 1.013 |
| 35 | 0.8824 |
| 36 | 1.885 |
| 37 | 1.333 |
| 38 | −0.1318 |
| 39 | 1.357 |
| 40 | −0.0249 |
| 41 | −0.3373 |
| 42 | 1.618 |
| 43 | −0.3442 |
| 44 | 1.187 |
| 45 | 0.0663 |
| 46 | 2.338 |
| 47 | 1.652 |
| 48 | 0.5575 |
| 49 | 1.779 |
| 50 | 1.426 |
| 51 | −0.1499 |
| 52 | 0.8338 |
| 53 | 0.1294 |
| 54 | 1.529 |
| 55 | 0.4552 |
| 56 | 0.8886 |
| 57 | −0.0964 |
| 58 | 0.1990 |
| 59 | 1.314 |
| 60 | 0.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
| Test | Statistic | p | Change after | Mean before | Mean after | At α = .05 |
|---|---|---|---|---|---|---|
| Pettitt | 529 | < .001 | 23 | −0.1841 | 0.9250 | shift |
| Buishand range | 2.037 | .002 | 23 | −0.1841 | 0.9250 | shift |
| Buishand U | 1.119 | .003 | 23 | −0.1841 | 0.9250 | shift |
| SNHT | 19.266 | .001 | 15 | −0.5024 | 0.8339 | shift |
| Lanzante | 161 | < .001 | 23 | −0.1841 | 0.9250 | shift |
- 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.
The exact R script · R 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
))
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
| Test | Statistic | p | Change after | Mean before | Mean after | At α = .05 |
|---|---|---|---|---|---|---|
| Pettitt | 529 | < .001 | 23 | −0.1841 | 0.9250 | shift |
| Buishand range | 2.037 | .002 | 23 | −0.1841 | 0.9250 | shift |
| Buishand U | 1.119 | .003 | 23 | −0.1841 | 0.9250 | shift |
| SNHT | 19.266 | .001 | 15 | −0.5024 | 0.8339 | shift |
| Lanzante | 161 | < .001 | 23 | −0.1841 | 0.9250 | shift |
- 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.
The exact Python script · Python 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,
})
| Test | Based on | p | Date |
|---|---|---|---|
| Pettitt | Ranks | 0.0010 | 23 |
| Buishand range | Cumulative deviations | 0.002 | 23 |
| Buishand U | Cumulative deviations | 0.003 | 23 |
| SNHT | Standardized means | 0.001 | 15 |
| Lanzante | Ranks + Wilcoxon | 0.0000 | 23 |
All 5 tests reject, yet one names a different date. Which one? Open the plots on the card and see what might draw it there.
Why dates can differ
ReflectThe SNHTStandard normal homogeneity testAlexandersson's test for a shift in mean of standardized values; most sensitive to breaks near the start or end of a record. is known to favor dates near the ends of a series. Buishand's tests favor the middle, and Pettitt looks for shifts in the middle of the distribution.
These tests agree most often when a shift is sharp and large. Report the range of dates, not only the date you like.
Have you seen a metric "shift" in a chart? What would you want to know about what happened on that date, before you called it a change?
On noise
ReadOn simulated noise with 160 values, Lanzante's test with permutations gives 0.95. It names a date anyway, since a test always finds its best candidate: 2024-03-25.
A date on the card doesn't mean there's a shift there. Read the p-value first.
Several shifts: PELT
PredictPredict first
PELTPELTAn exact search for any number of change points that minimizes the fit cost plus a penalty per change. chooses segments to minimize the fit error plus a penalty per change. If you raise the penalty, what happens?
Reveal
Fewer segments. With BIC, a simulated series with 160 weeks has 2 changes, at 53 and 110. On the Nile, Hannan–Quinn finds 1. PELT gives a segmentation with no p-values. Its penalty is your choice, so check how the result moves.
Mimics
ReadA trend or strong positive autocorrelation can look like a level shift to all of these tests. Check on the card (0.16 for the Nile). If it's large, use Permutation with caution: shuffling assumes exchangeable values, and it breaks autocorrelation too.
Check your understanding
CheckpointCheck yourself
Why not run a t test at the date with the largest gap?
Show the answer
Answer: b
Change-point tests account for the search over dates. That's their whole purpose.
Check yourself
Pettitt gives p = 0.60 and names a date. What should you report?
Show the answer
Answer: b
A test always finds its best candidate. The date means something only if the evidence supports a shift.
Check yourself
You lower PELT's penalty and go from 2 to 6 segments. What's the right reaction?
Show the answer
Answer: b
The penalty sets the trade-off, and the data alone don't fix it. Subject knowledge has to help.
Do it in CodeSplash
In the appSet Series and Time. Test defaults to the battery, and PELT (several shifts) is separate. This is the Breaks step in the Series lab. The dates it finds can also set where a forecast's training window starts.
# pip install ruptures pyhomogeneity
import math
import pandas as pd
import pyhomogeneity as hg
import ruptures as rpt
y = pd.read_csv("nile.csv")["flow"].to_numpy()
print(hg.pettitt_test(y))
print(rpt.Pelt(model="l2").fit(y).predict(pen=2 * y.var() * math.log(len(y))))# install.packages(c("trend", "changepoint"))
y <- as.numeric(Nile)
trend::pettitt.test(y)
trend::snh.test(y)
changepoint::cpt.mean(y, method = "PELT")Recap
Recap- A change-point test accounts for the search across all dates.
- Pettitt and Lanzante use ranks. Buishand and SNHT use the values. They can name different dates.
- A test always names a date, so read the p-value first.
- PELT dates several shifts, with a penalty that's your responsibility.
- Trend and autocorrelation can mimic a shift.
Concepts in this lesson