Source code for pyts.utils._utils

"""Code for utility tools."""

# Author: Johann Faouzi <johann.faouzi@gmail.com>
# License: BSD-3-Clause

from typing import Any, cast

import numpy as np
import numpy.typing as npt
from numba import njit
from numpy.lib.stride_tricks import as_strided
from sklearn.utils import check_array


def _word_vectorizer_params() -> dict[str, Any]:
    """Keyword arguments for the vectorizers that count the words of pyts.

    Words are separated by single spaces and use any alphabet, but
    scikit-learn's defaults lowercase the text (merging symbols that only
    differ by case, such as ``'a'`` and ``'A'``) and only keep tokens of at
    least two word characters (dropping one-symbol words and symbols such as
    ``'+'`` or ``'-'``). Every whitespace-separated word is kept as is instead.
    """
    return {'lowercase': False, 'token_pattern': r'\S+'}


[docs] def segmentation( ts_size: int, window_size: int, overlapping: bool = False, n_segments: int | None = None, ) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.int64], int]: """Compute the indices for Piecewise Agrgegate Approximation. Parameters ---------- ts_size : int The size of the time series. window_size : int The size of the window. overlapping : bool (default = False) If True, overlapping windows may be used. If False, non-overlapping are used. n_segments : int or None (default = None) The number of windows. If None, the number is automatically computed using ``window_size``. Returns ------- start : array The lower bound for each window. end : array The upper bound for each window. size : int The size of ``start``. Examples -------- >>> from pyts.utils import segmentation >>> start, end, size = segmentation(ts_size=12, window_size=3) >>> print(start) [0 3 6 9] >>> print(end) [ 3 6 9 12] >>> size 4 """ if not isinstance(ts_size, (int, np.integer)): raise TypeError("'ts_size' must be an integer.") if not ts_size >= 2: raise ValueError( f"'ts_size' must be an integer greater than or equal to 2 (got {ts_size})." ) if not isinstance(window_size, (int, np.integer)): raise TypeError("'window_size' must be an integer.") if not window_size >= 1: raise ValueError( "'window_size' must be an integer greater than or " f"equal to 1 (got {window_size})." ) if not window_size <= ts_size: raise ValueError( "'window_size' must be lower than or equal to " f"'ts_size' ({window_size} > {ts_size})." ) if not (n_segments is None or isinstance(n_segments, (int, np.integer))): raise TypeError("'n_segments' must be None or an integer.") if isinstance(n_segments, (int, np.integer)): # A single segment (the whole series) is valid: it is what PAA, # GramianAngularField and the bag-of-words estimators need for an # output or word size of 1. if not n_segments >= 1: raise ValueError( "If 'n_segments' is an integer, it must be greater than or " f"equal to 1 (got {n_segments})." ) if not n_segments <= ts_size: raise ValueError( "If 'n_segments' is an integer, it must be lower than or " f"equal to 'ts_size' ({n_segments} > {ts_size})." ) if n_segments is None: quotient, remainder = divmod(ts_size, window_size) n_segments = quotient if remainder == 0 else quotient + 1 if not overlapping: bounds = np.linspace(0, ts_size, n_segments + 1).astype('int64') start = bounds[:-1] end = bounds[1:] size = start.size return start, end, size else: n_overlapping = (n_segments * window_size) - ts_size n_overlaps = n_segments - 1 overlaps = np.linspace(0, n_overlapping, n_overlaps + 1).astype('int64') bounds = np.arange(0, (n_segments + 1) * window_size, window_size) start = bounds[:-1] - overlaps end = bounds[1:] - overlaps size = start.size return start, end, size
# Deliberately left without an explicit signature (unlike the other # ``@njit`` functions in this package): the public ``windowed_view`` calls # ``check_array(X, dtype=None)``, so it preserves whatever numeric dtype # the caller passes (its own doctest exercises it with an integer array), # and numpy's default integer width itself varies by platform. An eager # signature would either narrow this to a single dtype (breaking that # documented flexibility) or require guessing every dtype ever passed; # lazy compilation is the correct choice here. @njit() def _windowed_view( X: npt.NDArray[Any], n_samples: int, n_timestamps: int, window_size: int, window_step: int, ) -> npt.NDArray[Any]: overlap = window_size - window_step shape_new = ( n_samples, (n_timestamps - overlap) // window_step, window_size // 1, ) s0, s1 = X.strides strides_new = (s0, window_step * s1, s1) return as_strided(X, shape=shape_new, strides=strides_new)
[docs] def windowed_view( X: npt.ArrayLike, window_size: int, window_step: int = 1 ) -> npt.NDArray[Any]: """Return a windowed view of a 2D array. Parameters ---------- X : array-like, shape = (n_samples, n_timestamps) Input data. window_size : int The size of the window. It must be between 1 and ``n_timestamps``. window_step : int (default = 1) The step of the sliding window Returns ------- X_new : array, shape = (n_samples, n_windows, window_size) Windowed view of the input data. ``n_windows`` is computed as ``(n_timestamps - window_size + window_step) // window_step``. Examples -------- >>> import numpy as np >>> from pyts.utils import windowed_view >>> windowed_view(np.arange(6).reshape(1, -1), window_size=2) array([[[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]]]) """ X = cast(npt.NDArray[Any], check_array(X, dtype=None)) n_samples, n_timestamps = X.shape if not isinstance(window_size, (int, np.integer)): raise TypeError("'window_size' must be an integer.") if not 1 <= window_size <= n_timestamps: raise ValueError("'window_size' must be an integer between 1 and n_timestamps.") if not isinstance(window_step, (int, np.integer)): raise TypeError("'window_step' must be an integer.") if not 1 <= window_step <= n_timestamps: raise ValueError("'window_step' must be an integer between 1 and n_timestamps.") return _windowed_view(X, n_samples, n_timestamps, window_size, window_step)