Skip to content

[ENH] Implement PELTSegmenter for optimal time series changepoint detection - #3969

Open
shivamkumxr wants to merge 23 commits into
aeon-toolkit:mainfrom
shivamkumxr:feature/pelt-segmenter
Open

shivamkumxr wants to merge 23 commits into
aeon-toolkit:mainfrom
shivamkumxr:feature/pelt-segmenter

Conversation

@shivamkumxr

Copy link
Copy Markdown
Contributor

Reference Issues/PRs

Closes #3948

What does this implement/fix? Explain your changes.

Adds PELTSegmenter under aeon.segmentation based on Killick et al. (2012).

Summary of changes:

  • Implemented PELTSegmenter on top of BaseSegmenter.
  • Uses prefix sums to compute segment costs in $O(1)$ time with NumPy.
  • Added pruning step to discard candidate changepoints as the series is traversed.
  • Supported costs: L2 (mean shifts) and Gaussian log-likelihood (mean + variance shifts).
  • Penalty can be passed directly as a float or chosen via 'bic' / 'aic'.
  • Works on multivariate series by computing costs across channels.
  • Added tests in test_pelt.py and patched _yield_segmentation_checks.py to handle empty changepoint edge cases during generic estimator checks.

Does your contribution introduce a new dependency? If yes, which one?

No.

PR checklist

  • The PR title starts with [ENH].
  • Added PELTSegmenter to API documentation (docs/api_reference/segmentation.rst).
  • Added unit tests (test_pelt.py) and docstrings following numpydoc standards.
  • Verified compatibility with check_estimator(PELTSegmenter).

@aeon-actions-bot aeon-actions-bot Bot added enhancement New feature, improvement request or other non-bug code enhancement segmentation Segmentation package testing Testing related issue or pull request labels Oct 27, 2026
@aeon-actions-bot

Copy link
Copy Markdown
Contributor

Thank you for contributing to aeon

I have added the following labels to this PR based on the title: enhancement.
I have added the following labels to this PR based on the changes made: segmentation testing. Feel free to change these if they do not properly represent the PR.

The Checks tab will show the status of our automated tests. You can click on individual test runs in the tab or "Details" in the panel below to see more information if there is a failure.

If our pre-commit code quality check fails, please run pre-commit locally and push the fixes to your PR branch.

Don't hesitate to ask questions on the aeon Discord channel if you have any.

PR CI actions

These checkboxes will add labels to enable or disable CI functionality for this PR. This may not take effect immediately, and a new commit may be required to run the new configuration.

  • Run pre-commit checks for all files
  • Run mypy typecheck tests
  • Run all pytest tests and configurations
  • Run all notebook example tests
  • Run numba-disabled codecov tests
  • Disable numba cache loading
  • Regenerate expected results for testing
  • Push an empty commit to re-run CI checks

@baraline baraline left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a correctness review, only looked at testing side, some functions to move.

Comment thread aeon/segmentation/tests/test_pelt.py Resolved
@shivamkumxr
shivamkumxr requested a review from baraline November 12, 2026 13:16

@TonyBagnall TonyBagnall left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks for this, I am not that familiar with the algorithm and dont have the time to become so, so went for an AI review below. This is from gemini carbon, next one I will put claude on.

I did a full algorithmic, performance, and test review and found a few substantive issues that need addressing before this can be merged:

1. Premature pruning under min_size >= 2 breaks global optimality (aeon/segmentation/_pelt.py, lines 176-185)

The docstring states that PELTSegmenter guarantees the globally optimal solution under the chosen cost and penalty. However, at step t, line 180 immediately discards candidate tau whenever F[tau] + seg_costs[tau] > F[t].

In Killick et al. (2012, Theorem 3.1), pruning tau via F[t] relies on replacing a partition (..., tau, s) with (..., t, s) at future steps s > t. When min_size >= 2, (t, s] is only a valid segment once s >= t + min_size. For intermediate steps s in {t + 1, ..., t + min_size - 1}, t is inadmissible as a changepoint whereas tau is still admissible, so deleting tau immediately at t can prune the true global optimum.

Minimal counterexample (cost="l2", penalty=5.0, min_size=2, jump=1):

X = np.array([3.0, 9.0, 0.0, 2.0, 10.0])
PELTSegmenter(cost="l2", penalty=5.0, min_size=2).fit_predict(X)
# Returns array([2]) with penalised cost 18.0 + 56.0 + 5.0 = 79.0,
# whereas array([]) (no changepoint) has strictly lower cost 78.8!

Here tau = 0 is pruned at t = 4 (F[4] = 25.0 < -5.0 + 49.0 = 44.0), and then at t = 5, t = 4 cannot be used because 5 - 4 < min_size.

Suggested fix: When np.isfinite(F[t]) and F[tau] + seg_costs[tau] >= F[t], schedule tau to expire at t + min_size (e.g. expire[tau] = min(expire[tau], t + min_size)) rather than removing it before t can form a valid segment. Also avoid adding unreachable interior grid points 0 < t < min_size (where F[t] = np.inf) to candidates.


2. Scale sensitivity of "bic" / "aic" under cost="l2" and 1e-8 under cost="normal" (aeon/segmentation/_pelt.py, lines 254-285)

  • cost="l2" with "bic" / "aic": _cost_l2 computes unnormalised RSS $\sum (y_t - \bar{y})^2$, which scales by $\alpha^2$ if X is multiplied by $\alpha$, while _compute_penalty returns p * log(n_timepoints) ("bic") or 2 * p ("aic"), implicitly assuming unit noise variance $\sigma^2 = 1$. Because $-2 \log L = \text{RSS} / \sigma^2 + \text{const}$, rescaling make_example_mean_shift_series(random_state=42) gives:

    • 0.01 * series -> 0 changepoints
    • 1.0 * series -> 2 changepoints ([100, 200])
    • 10.0 * series -> 101 changepoints
    • 100.0 * series -> 131 changepoints

    For automatic "bic" / "aic" penalties under "l2", the penalty needs to account for noise variance (for example using a robust per-channel first-difference scale estimate such as MAD of $\Delta X_c / \sqrt{2}$, with a fallback when $\Delta X_c$ has zero median absolute deviation on noiseless step series). Also please check the parameter count p per additional changepoint against Killick et al. (2012, Section 2.1), where each changepoint adds the segment parameters plus 1 for the changepoint location (d + 1 / 2 * d + 1), and make sure the formula and docstring match your intended definition.

  • cost="normal": _cost_normal adds a fixed absolute 1e-8 inside np.log(var + 1e-8). On low-amplitude signals (e.g. 1e-5 * series, where var ~ 1e-10), 1e-8 dominates var and PELTSegmenter(cost="normal", penalty="bic", min_size=10) fails to detect any changepoints. Scaling epsilon relative to each channel's overall variance (falling back to 1e-8 only when a channel has zero variance) makes "normal" scale-invariant.


3. Performance: use Numba @njit for the inner DP loop (aeon/segmentation/_pelt.py, lines 149-186)

Running the dynamic programming loop in pure Python over set/dict containers and calling a Python staticmethod + NumPy slice reductions for every (t, tau) pair creates very high per-iteration overhead. In addition, line 180 uses <= (F[tau] + seg_costs[tau] <= F[t]), which keeps ties: on a constant series np.ones(n), 0.0 <= 0.0 holds for every tau > 0, so no candidate is ever pruned.

Locally, PELTSegmenter().fit_predict(np.ones(2500)) takes ~63 seconds (and stationary Gaussian n = 2500 takes ~10.5 seconds). numba is a core dependency in aeon; moving the DP loop into a @njit(cache=True) helper over flat float64/int64 arrays (with delayed >= tie-pruning) brings n = 2500 down to < 1 ms on constant input and ~6 ms on stationary Gaussian noise. Please also ensure tests pass with NUMBA_DISABLE_JIT=1 (pytest --nonumba) so the JIT body is covered.


4. Parameter and input validation edge cases (aeon/segmentation/_pelt.py, lines 130-140, 286-325)

  • In Python, isinstance(True, int) is True, whereas isinstance(np.int64(3), int) is False:
    • penalty=True, penalty=False, and jump=True silently pass validation instead of raising ValueError.
    • min_size=np.int64(3) and jump=np.int64(2) raise ValueError, which breaks NumPy integer values from hyperparameter grids. Please accept (int, np.integer) (or numbers.Integral) while explicitly rejecting bool.
  • penalty=np.nan and penalty=np.inf pass self.penalty < 0 (False) and silently return []; please check np.isfinite(self.penalty).
  • Input X containing np.inf or -np.inf passes BaseSeriesEstimator._check_X (which checks isnan), emits a RuntimeWarning in data - data.mean(...), and silently returns []; please raise a ValueError when non-finite values are present in X.

5. Data generation exports (aeon/testing/data_generation/_series.py, __init__.py)

Moving the synthetic shift generators into aeon.testing.data_generation makes sense, but right now this adds 6 public functions to aeon.testing.data_generation:

  • Please drop the 3 duplicate aliases (make_mean_shift_series, make_variance_shift_series, make_multivariate_series).
  • make_example_multivariate_series is too generic a name alongside make_example_2d_numpy_series given that it specifically generates a 2-segment mean shift. Consider consolidating all three into a single segmentation helper (e.g. make_example_segment_series supporting n_channels, mean/variance shifts, axis, and optionally returning the true changepoint indices), and match _series.py's random_state handling (np.random.RandomState or check_random_state) for consistency with the rest of the module.

6. Tests (aeon/segmentation/tests/test_pelt.py, aeon/testing/data_generation/tests/test_series.py)

  • Avoid magic numbers: test_pelt.py calls make_example_mean_shift_series(random_state=42) using hidden defaults and then hard-codes 100 and 200 in assertions; test_series.py similarly hard-codes 30, 20, and 3 instead of defining n_timepoints / n_channels variables once and reusing them. In test_series.py, please also assert that the generated segments actually exhibit the requested mean/variance shift rather than checking shape alone.
  • Prune / tighten redundant checks: test_pelt_get_params is already covered by check_estimator and can be removed; test_pelt_aic_penalty should verify exact equivalence against the manual AIC penalty formula rather than len(cps) >= 2; the invalid-parameter tests can be combined with @pytest.mark.parametrize.
  • Add exact-optimality & axis=0 tests: Please add a test comparing PELTSegmenter against an unpruned / brute-force partition search on small 1D and 2D series (covering both "l2" and "normal", min_size >= 2, jump >= 1, axis=0 and axis=1, and the [3.0, 9.0, 0.0, 2.0, 10.0] case above) to verify the global optimality guarantee directly.

@TonyBagnall

Copy link
Copy Markdown
Contributor

this should be fixed with #4029, merging to test

@shivamkumxr

Copy link
Copy Markdown
Contributor Author

Thanks @TonyBagnall and @baraline for the detailed reviews and feedback!

All requested changes and edge cases have been resolved, verified locally, and committed:


1. Pruning under min_size >= 2 & Global Optimality

  • Replaced immediate candidate deletion with delayed expiration tracking (expire[tau] = min(expire[tau], t + min_size)). Candidate $\tau$ is only dropped once $t \ge \text{expire}[\tau]$, ensuring valid predecessors remain available for future steps $s \in {t+1, \dots, t + \text{min_size} - 1}$ where $t$ cannot form an admissible segment.
  • Excluded interior grid points $0 &lt; t &lt; \text{min_size}$ from entering the candidate set.
  • Added test_pelt_pruning_counterexample for $X = [3.0, 9.0, 0.0, 2.0, 10.0]$ (which previously returned [2] instead of the global optimum []), and added test_pelt_against_brute_force comparing PELTSegmenter against an unpruned exact dynamic programming solver (_exact_partition_solver) across parameter grids (cost, min_size, jump, axis) over 20 random seeds.

2. Scale Sensitivity & Parameter Count (Killick et al. 2012, Sec 2.1)

  • cost="l2" with "bic" / "aic":
    • The channel noise variance is estimated via the MAD of first differences: $\hat{\sigma}^2_c = \left(\frac{1.4826 \cdot \text{MAD}(\Delta X_c)}{\sqrt{2}}\right)^2$, with a fallback floor (1e-8 * Var(X_c)) for noiseless step series.
    • Per Killick et al. (2012, Section 2.1), each changepoint introduces $p = 2$ parameters per channel (the changepoint location and the segment mean). The penalty is scaled by $\hat{\sigma}^2_c$: $\beta = 2 \sum_c \hat{\sigma}^2_c \log(n)$ for BIC, and $4 \sum_c \hat{\sigma}^2_c$ for AIC.
  • cost="normal":
    • Replaced the fixed $10^{-8}$ inside $\log(\text{var} + \epsilon)$ with an adaptive $\epsilon_c = 10^{-8} \cdot \mathrm{Var}(X_c)$ (falling back to $10^{-8}$ if $\mathrm{Var}(X_c) = 0$), guaranteeing scale invariance for low-amplitude signals.
  • Added test_pelt_scale_invariance testing scaling factors $0.01\times$, $1.0\times$, $100.0\times$, and $10^{-5}\times$.

3. Numba Acceleration (@njit(cache=True))

  • Moved the inner DP loop, segment costs (_cost_l2_numba, _cost_normal_numba), in-place candidate compaction, and backtracking into @njit(cache=True) helper functions operating on flat float64 / int64 1D and 2D arrays.
  • Benchmarks ($n = 2500$ timepoints):
    • Constant series np.ones(2500): 0.64 ms (down from ~63 s)
    • Gaussian noise $n = 2500$ (L2 cost): 4.27 ms (down from ~10.5 s)
    • Gaussian noise $n = 2500$ (Normal cost): 5.69 ms
  • All tests pass both with JIT enabled and with NUMBA_DISABLE_JIT=1 (pytest --nonumba).

4. Input & Parameter Validation

  • Explicitly rejects bool for penalty, min_size, and jump.
  • Accepts standard Python int as well as np.integer types (np.int32, np.int64) for min_size and jump.
  • Enforces finite penalty via np.isfinite (rejects nan, inf, -inf).
  • Raises ValueError if input $X$ contains inf or -inf.
  • Added unified parameterized test test_pelt_validation_errors and test_pelt_accepts_integer_types.

5. Consolidated Data Generator (make_example_segment_series)

  • Removed duplicate aliases (make_mean_shift_series, make_variance_shift_series, make_multivariate_series).
  • Consolidated synthetic segment generation into a single function in aeon.testing.data_generation: make_example_segment_series. Supports n_channels, shift_type ("mean" or "variance"), axis, return_changepoints, and check_random_state-style seed handling.

6. Test Suite Cleanup

  • Eliminated magic numbers in tests; dynamic properties and true_cps are checked directly.
  • Added tests in test_series.py asserting that generated segments exhibit the intended empirical mean and variance shifts.
  • Removed redundant test_pelt_get_params (covered by check_estimator).
  • test_pelt_aic_penalty and test_pelt_bic_vs_manual_penalty now assert exact parity against the manual mathematical formulas.
  • Verified that check_estimator(PELTSegmenter) passes all 26 generic estimator contract checks.

All automated CI checks are green. Ready for your review!

@TonyBagnall TonyBagnall left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the substantial revision.

One remaining question concerns the BIC/AIC parameter counts. The implementation uses p=2d for both L2 and Gaussian costs, where d is the number of channels. However, changepoint locations are shared across channels. I would expect d+1 parameters for L2 and 2d+1 for Gaussian if counting the changepoint location as a parameter, as discussed in my original review.

Could you check this against the reference and either correct the formulas or explain the alternative convention being used? Please include a multivariate test of the resulting penalty calculation.

Otherwise this looks close to approval.

@shivamkumxr

Copy link
Copy Markdown
Contributor Author

Thanks @TonyBagnall, you're right, and thanks for pointing me back to the reference. The changepoint location is shared across channels, so it should count once, not once per channel. Following Killick et al. (2012, Sec 2.1), I've switched to p = d + 1 for L2 and p = 2d + 1 for the Gaussian cost.

For L2 the penalty stays in RSS units, so it is (sum_c sigma2_c + mean_c sigma2_c) * log(n) for BIC and 2 * (sum_c sigma2_c + mean_c sigma2_c) for AIC. The location term has no single channel to belong to, so I weight it by the mean of the per-channel noise variances. That is my own convention rather than something from the paper, so please say if you would prefer a different one. The Gaussian penalty is already in log-likelihood units, so it is just (2d + 1) * log(n) for BIC and 2 * (2d + 1) for AIC.

The docstring now states this convention. I also added test_pelt_penalty_multivariate_param_count (d in 2, 3, 5, using tiled channels), an exact-formula test at d=3, and a test for the data=None fallback.

All tests pass locally, with and without Numba (NUMBA_DISABLE_JIT=1), and check_estimator and pre-commit are clean. Happy to adjust anything else. Thanks again for the careful review!

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature, improvement request or other non-bug code enhancement segmentation Segmentation package testing Testing related issue or pull request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[ENH] Implement native PELT (Pruned Exact Linear Time) segmentation estimator

3 participants