Source code for tsseg.algorithms.autoplait.detector

"""
This module provides an aeon-compatible wrapper for the AutoPlait algorithm.
"""

import warnings

import numpy as np

from tsseg.algorithms._constructor import _deprecate_positional_args

from ..base import BaseSegmenter
from ..param_schema import (
    Closed,
    Interval,
    ParamDef,
)


def _regime_labels(regimes, n_samples):
    """One label per time point: the number of the regime of its segment.

    Parameters
    ----------
    regimes : list of list of tuple
        ``regimes[r]`` lists the ``(start, length)`` of the segments of regime
        ``r``.
    n_samples : int
        Length of the series.

    Returns
    -------
    np.ndarray
        Integer array of shape ``(n_samples,)``.

    Raises
    ------
    RuntimeError
        If the segments do not cover each time point exactly once.
    """
    labels = np.full(n_samples, -1, dtype=int)
    for regime, segments in enumerate(regimes):
        for start, length in segments:
            end = start + length
            if not 0 <= start < end <= n_samples:
                raise RuntimeError(
                    f"AutoPlait segment [{start}, {end - 1}] of regime {regime} lies "
                    f"outside a series of {n_samples} points."
                )
            if np.any(labels[start:end] != -1):
                raise RuntimeError(
                    f"AutoPlait segment [{start}, {end - 1}] of regime {regime} "
                    "overlaps another segment."
                )
            labels[start:end] = regime
    uncovered = np.flatnonzero(labels == -1)
    if uncovered.size:
        raise RuntimeError(
            f"AutoPlait segments leave {uncovered.size} time points without a "
            f"regime (first: {uncovered[0]})."
        )
    return labels


[docs] class AutoPlaitDetector(BaseSegmenter): """ AutoPlait state detection: regimes of hidden Markov models chosen by MDL. AutoPlait [1]_ describes the series as segments, each generated by one of a few *regimes*; a regime is a hidden Markov model with diagonal Gaussian emissions, and segments of the same regime share it. The number of regimes, the number of states of each HMM and the cut points are chosen by minimising the total description length (MDL) of the models and of the data. Starting from a single regime, AutoPlait tries to split each regime in two: seeds of length ``ceil(n / 10)`` initialise two HMMs, a cut point search (a Viterbi pass over the two models, with a switching probability per regime) assigns each part of the regime to one of them, and the two steps alternate. The split is kept when it shortens the description by more than 3 % of the cost of the regime. Parameters ---------- n_cps : int or None, default=None Deprecated and ignored. AutoPlait chooses the number of segments and regimes itself and has no guided mode, so this value has never changed the output. Passing it emits a ``FutureWarning`` at ``fit``; it will be removed in a future release. axis : int, default=0 Time axis: rows with ``0``, columns with ``1``. Attributes ---------- n_regimes_ : int Number of regimes of the last series segmented by ``predict``. cost_ : float Total description length, in bits, of that segmentation. Notes ----- The label of a time point is the number of the AutoPlait regime its segment belongs to: segments of the same regime share a label, and each change point is the first index of a segment. The algorithm is a Python translation, compiled with numba, of the C code of the authors [2]_ (version of June 18, 2014), random draws included: it returns the segmentation of the C binary built with GCC on Linux. Each channel is z-normalised in float32, as the C code reads its input. Unlike the binary, the translation has no limit on the number of channels, of regimes or of segments, and sets a constant channel to zero. The C code floors the log-density of an observation, summed over its channels, at :math:`\\log 10^{-6}`. With many channels the observations reach this floor under every model, which can no longer be told apart: on a 20-channel Gaussian series with a 3-sigma mean shift, AutoPlait finds a single regime. References ---------- .. [1] Y. Matsubara, Y. Sakurai, and C. Faloutsos, "AutoPlait: automatic mining of co-evolving time sequences," SIGMOD, 2014, doi: 10.1145/2588555.2588556. .. [2] Y. Matsubara, AutoPlait C code (version of June 18, 2014), https://www.dm.sanken.osaka-u.ac.jp/~yasuko/software.html. """ _tags = { "capability:univariate": True, "capability:multivariate": True, "fit_is_empty": False, "returns_dense": False, "detector_type": "state_detection", "capability:unsupervised": True, "capability:semi_supervised": False, "python_dependencies": ["numba"], } _parameter_schema = { "n_cps": ParamDef( constraint=Interval(int, 0, None, Closed.LEFT), description="Deprecated and ignored: AutoPlait has no guided mode.", nullable=True, ), } @_deprecate_positional_args( "n_cps", ) def __init__( self, *, n_cps=None, axis: int = 0, ): super().__init__(axis=axis) self.n_cps = n_cps def _fit(self, X, y=None): """Warn about the deprecated ``n_cps``; AutoPlait runs in ``predict``. Parameters ---------- X : np.ndarray The time series, of shape (n_timepoints, n_channels). y : None Not used: AutoPlait is unsupervised. Returns ------- self """ if self.n_cps is not None: warnings.warn( f"{type(self).__name__}: `n_cps` is deprecated and ignored. " "AutoPlait chooses the number of segments itself (it has no " "guided mode); `n_cps` will be removed in a future release.", FutureWarning, stacklevel=3, ) return self def _predict(self, X, y=None): """ Segment the time series and assign a regime label to each time point. Parameters ---------- X : np.ndarray The time series to segment, of shape (n_timepoints, n_channels). y : None Not used, for API compatibility. Returns ------- np.ndarray The regime label of each time point, of shape (n_timepoints,). """ from ._plait import autoplait ts = np.asarray(X) if ts.ndim == 1: ts = ts[:, np.newaxis] elif ts.ndim > 2: ts = ts.reshape(ts.shape[0], -1) result = autoplait(ts) self.n_regimes_ = len(result.regimes) self.cost_ = float(result.costT) regimes = [list(zip(s.st, s.ln)) for s in result.regimes] return _regime_labels(regimes, ts.shape[0])