### Install Pre-commit Hooks Source: https://centre-borelli.github.io/ruptures-docs/contributing Activates pre-commit hooks to perform tasks like code formatting before each commit. ```bash pre-commit install ``` -------------------------------- ### Clone Repository and Install Development Version Source: https://centre-borelli.github.io/ruptures-docs/contributing Clones the ruptures GitHub repository and installs the package in editable mode with development dependencies. ```bash git clone https://github.com/deepcharles/ruptures cd ruptures ``` ```bash python -m pip install --editable .[dev] ``` -------------------------------- ### Install Stable Release with Pip Source: https://centre-borelli.github.io/ruptures-docs/install Use this command to install the latest stable version of the ruptures library via pip. ```bash python -m pip install ruptures ``` -------------------------------- ### Install Stable Release with Conda Source: https://centre-borelli.github.io/ruptures-docs/install Install the ruptures library from the conda-forge channel using conda. Ensure conda-forge is added as a channel first. ```bash conda install ruptures ``` -------------------------------- ### Use Custom Cost with Pelt Algorithm Source: https://centre-borelli.github.io/ruptures-docs/user-guide/costs/costcustom Integrate a custom cost function with Ruptures algorithms like Pelt. This example demonstrates data creation, cost function instantiation, change point detection, and visualization. ```python import numpy as np import matplotlib.pylab as plt import ruptures as rpt # creation of data a = np.random.exponential(scale=1, size=100) b = np.random.exponential(scale=2, size=200) signal, bkps = np.r_[a, b, a], [100, 300, 400] # cost algo = rpt.Pelt(custom_cost=MyCost()).fit(signal) my_bkps = algo.predict(pen=10) # display rpt.display(signal, bkps, my_bkps) plt.show() ``` -------------------------------- ### Pelt Changepoint Detection Source: https://centre-borelli.github.io/ruptures-docs/user-guide/detection/pelt Instantiate the Pelt algorithm with specified model, minimum segment size, and jump parameter, then fit it to the signal and predict changepoints using a given penalty value. This example demonstrates detecting changepoints in a piecewise constant signal. ```python import numpy as np import matplotlib.pylab as plt import ruptures as rpt # creation of data n, dim = 500, 3 n_bkps, sigma = 3, 1 signal, bkps = rpt.pw_constant(n, dim, n_bkps, noise_std=sigma) # change point detection model = "l1" # "l2", "rbf" algo = rpt.Pelt(model=model, min_size=3, jump=5).fit(signal) my_bkps = algo.predict(pen=3) # show results fig, ax_arr = rpt.display(signal, bkps, my_bkps, figsize=(10, 6)) plt.show() ``` -------------------------------- ### `__init__` Source: https://centre-borelli.github.io/ruptures-docs/code-reference/detection/window-reference Instantiate the Window detector with specified parameters. ```APIDOC ## `__init__(width=100, model='l2', custom_cost=None, min_size=2, jump=5, params=None)` ### Description Instantiate with window length. ### Parameters #### Parameters - **width** (`int`) - Optional - window length. Defaults to 100 samples. - **model** (`str`) - Optional - segment model, ["l1", "l2", "rbf"]. Not used if `custom_cost` is not None. Defaults to 'l2'. - **custom_cost** (`BaseCost`) - Optional - custom cost function. Defaults to None. - **min_size** (`int`) - Optional - minimum segment length. Defaults to 2. - **jump** (`int`) - Optional - subsample (one every _jump_ points). Defaults to 5. - **params** (`dict`) - Optional - a dictionary of parameters for the cost instance. Defaults to None. ``` -------------------------------- ### Import libraries and create a signal Source: https://centre-borelli.github.io/ruptures-docs/user-guide/detection/window Standard imports and signal generation for demonstrating change point detection. ```python import numpy as np import matplotlib.pylab as plt import ruptures as rpt # creation of data n, dim = 500, 3 # number of samples, dimension n_bkps, sigma = 3, 5 # number of change points, noise standart deviation signal, bkps = rpt.pw_constant(n, dim, n_bkps, noise_std=sigma) ``` -------------------------------- ### Initialize Dynp with Model and Parameters Source: https://centre-borelli.github.io/ruptures-docs/code-reference/detection/dynp-reference Instantiate the Dynp class using a predefined cost model and its associated parameters. The cost function will be created using the provided model name and parameters. ```python Dynp(model="l2", custom_cost=None, min_size=2, jump=5, params={"epsilon": 0.1}) ``` -------------------------------- ### seg(start, end, n_bkps) Source: https://centre-borelli.github.io/ruptures-docs/code-reference/detection/dynp-reference Recurrence to find the optimal partition of signal[start:end]. This method is intended to be memoized and then used. ```APIDOC ## seg(start, end, n_bkps) `cached` ### Description Recurrence to find the optimal partition of signal[start:end]. This method is to be memoized and then used. ### Parameters #### Path Parameters - **start** (int) - Required - start of the segment (inclusive) - **end** (int) - Required - end of the segment (exclusive) - **n_bkps** (int) - Required - number of breakpoints ### Returns - **dict**: {(start, end): cost value, ...} ``` -------------------------------- ### Import Libraries and Create Sample Data Source: https://centre-borelli.github.io/ruptures-docs/user-guide/costs/costcosine Imports necessary libraries and generates a piecewise constant signal with added noise for demonstration purposes. ```python import numpy as np import matplotlib.pylab as plt import ruptures as rpt # creation of data n, dim = 500, 3 # number of samples, dimension n_bkps, sigma = 3, 5 # number of change points, noise standart deviation signal, bkps = rpt.pw_constant(n, dim, n_bkps, noise_std=sigma) ``` -------------------------------- ### __init__ Source: https://centre-borelli.github.io/ruptures-docs/code-reference/detection/pelt-reference Initializes the Pelt instance with specified model, cost function, minimum segment size, and subsampling parameters. ```APIDOC ## __init__(model='l2', custom_cost=None, min_size=2, jump=5, params=None) ### Description Initialize a Pelt instance. ### Parameters #### Parameters - **model** (str) - Optional - segment model, ["l1", "l2", "rbf"]. Not used if 'custom_cost' is not None. Defaults to 'l2'. - **custom_cost** (BaseCost) - Optional - custom cost function. Defaults to None. - **min_size** (int) - Optional - minimum segment length. Defaults to 2. - **jump** (int) - Optional - subsample (one every _jump_ points). Defaults to 5. - **params** (dict) - Optional - a dictionary of parameters for the cost instance. Defaults to None. ``` -------------------------------- ### CostL2.error(start, end) Source: https://centre-borelli.github.io/ruptures-docs/code-reference/costs/costl2-reference Calculates the least squared deviation cost for a segment of the signal. The segment is defined by the start and end indices (exclusive of end). ```APIDOC ## CostL2.error(start, end) ### Description Return the approximation cost on the segment [start:end]. ### Method error ### Parameters #### Path Parameters - **start** (int) - Required - start of the segment - **end** (int) - Required - end of the segment ### Returns #### Success Response - **float** - segment cost ### Raises #### NotEnoughPoints - when the segment is too short (less than `min_size` samples). ``` -------------------------------- ### error(start, end) Source: https://centre-borelli.github.io/ruptures-docs/code-reference/costs/costclinear-reference Calculates the approximation cost on a given segment [start:end] using a piecewise linear model with continuity. Raises NotEnoughPoints if the segment is too short. ```APIDOC ## error(start, end) ### Description Return the approximation cost on the segment [start:end]. ### Parameters #### Path Parameters - `start` (int) - Required - start of the segment - `end` (int) - Required - end of the segment ### Returns - `float`: segment cost (float) ### Raises - `NotEnoughPoints`: when the segment is too short (less than `min_size` samples). ``` -------------------------------- ### Initialize and fit Window algorithm, predict change points Source: https://centre-borelli.github.io/ruptures-docs/user-guide/detection/window Initialize the `Window` algorithm with a specified model and width, fit it to the signal, and predict change points. Displays the results using `rpt.show.display`. ```python # change point detection model = "l2" # "l1", "rbf", "linear", "normal", "ar" algo = rpt.Window(width=40, model=model).fit(signal) my_bkps = algo.predict(n_bkps=3) # show results rpt.show.display(signal, bkps, my_bkps, figsize=(10, 6)) plt.show() ``` -------------------------------- ### __init__ Source: https://centre-borelli.github.io/ruptures-docs/code-reference/detection/binseg-reference Initializes the Binseg instance with specified parameters for segmentation. ```APIDOC ## __init__(model='l2', custom_cost=None, min_size=2, jump=5, params=None) ### Description Initialize a Binseg instance. ### Parameters #### Path Parameters - **model** (str) - Optional - segment model, ["l1", "l2", "rbf",...]. Not used if 'custom_cost' is not None. Defaults to 'l2'. - **custom_cost** (BaseCost) - Optional - custom cost function. Defaults to None. - **min_size** (int) - Optional - minimum segment length. Defaults to 2 samples. - **jump** (int) - Optional - subsample (one every _jump_ points). Defaults to 5 samples. - **params** (dict) - Optional - a dictionary of parameters for the cost instance. Defaults to None. ``` -------------------------------- ### Upgrade Pip Source: https://centre-borelli.github.io/ruptures-docs/contributing Ensures you have the latest version of pip for building and installation. ```python python -m pip install --upgrade pip ``` -------------------------------- ### error(start, end) Source: https://centre-borelli.github.io/ruptures-docs/code-reference/costs/costl1-reference Calculates the least absolute deviation cost for a specified segment of the signal. ```APIDOC ## error(start, end) ### Description Return the approximation cost on the segment [start:end]. ### Parameters #### Path Parameters - **start** (int) - Required - start of the segment - **end** (int) - Required - end of the segment ### Returns - `float` - segment cost ### Raises - `NotEnoughPoints` - when the segment is too short (less than `min_size` samples). ``` -------------------------------- ### Instantiate Change Point Detector with CostAR Source: https://centre-borelli.github.io/ruptures-docs/user-guide/costs/costautoregressive Demonstrates two equivalent ways to initialize a change point detection algorithm (Dynp) using the CostAR cost function. This allows integrating custom cost functions into standard algorithms. ```python c = rpt.costs.CostAR(order=10) algo = rpt.Dynp(custom_cost=c) # is equivalent to algo = rpt.Dynp(model="ar", params={"order": 10}) ``` -------------------------------- ### Upgrade to Latest Version with Pip Source: https://centre-borelli.github.io/ruptures-docs/install Upgrade your ruptures installation to the latest available version using pip. ```bash python -m pip install -U ruptures ``` -------------------------------- ### Dynp Initialization Source: https://centre-borelli.github.io/ruptures-docs/code-reference/detection/dynp-reference Initializes a Dynp instance with specified parameters for change point detection. ```APIDOC ## __init__(model='l2', custom_cost=None, min_size=2, jump=5, params=None) ### Description Creates a Dynp instance. ### Parameters #### Parameters - **model** (str) - Optional - segment model, ["l1", "l2", "rbf"]. Not used if 'custom_cost' is not None. Defaults to 'l2'. - **custom_cost** (BaseCost) - Optional - custom cost function. Defaults to None. - **min_size** (int) - Optional - minimum segment length. Defaults to 2. - **jump** (int) - Optional - subsample (one every _jump_ points). Defaults to 5. - **params** (dict) - Optional - a dictionary of parameters for the cost instance. Defaults to None. ``` -------------------------------- ### Show Current Package Version Source: https://centre-borelli.github.io/ruptures-docs/install Check the currently installed version of the ruptures package using pip. ```bash python -m pip show ruptures ``` -------------------------------- ### Initialize Change Point Detection Algorithm with CostNormal Source: https://centre-borelli.github.io/ruptures-docs/user-guide/costs/costnormal Demonstrates two equivalent ways to initialize a change point detection algorithm (Dynp) using the CostNormal class, either by passing an instance or by specifying the model name. ```python c = rpt.costs.CostNormal() algo = rpt.Dynp(custom_cost=c) # is equivalent to algo = rpt.Dynp(model="normal") ``` -------------------------------- ### single_bkp Source: https://centre-borelli.github.io/ruptures-docs/code-reference/detection/binseg-reference Returns the optimal breakpoint of a given segment [start:end], if one exists. This method is cached for performance. ```APIDOC ## single_bkp(start, end) ### Description Return the optimal breakpoint of [start:end] (if it exists). ### Parameters #### Path Parameters None #### Query Parameters - **start** (int) - The starting index of the segment. - **end** (int) - The ending index of the segment. #### Request Body None ### Request Example None ### Response #### Success Response (200) - **tuple** - A tuple containing the optimal breakpoint (int) and the associated gain (float). Returns (None, 0) if no breakpoint is found or if the cost is -inf. #### Response Example None ### Raises None explicitly documented for this cached method, but internal logic handles potential `ValueError` if `gain_list` is empty. ``` -------------------------------- ### Initialize Window Source: https://centre-borelli.github.io/ruptures-docs/code-reference/detection/window-reference Instantiate the Window class with specified parameters. The `width` parameter determines the window length, and `model` specifies the cost function. `custom_cost` can be used for user-defined cost functions. ```python def __init__( self, width=100, model="l2", custom_cost=None, min_size=2, jump=5, params=None, ): """Instanciate with window length. Args: width (int, optional): window length. Defaults to 100 samples. model (str, optional): segment model, ["l1", "l2", "rbf"]. Not used if `custom_cost` is not None. custom_cost (BaseCost, optional): custom cost function. Defaults to None. min_size (int, optional): minimum segment length. jump (int, optional): subsample (one every *jump* points). params (dict, optional): a dictionary of parameters for the cost instance.` """ self.min_size = min_size self.jump = jump self.width = 2 * (width // 2) self.n_samples = None self.signal = None self.inds = None if custom_cost is not None and isinstance(custom_cost, BaseCost): self.cost = custom_cost else: if params is None: self.cost = cost_factory(model=model) else: self.cost = cost_factory(model=model, **params) self.score = list() ``` -------------------------------- ### Initialize Binseg with Jump Parameter Source: https://centre-borelli.github.io/ruptures-docs/user-guide/detection/binseg Initialize the Binseg algorithm with a 'jump' parameter to speed up prediction. A higher jump value increases speed at the cost of potential precision. ```python algo = rpt.Binseg(model=model, jump=10).fit(signal) ``` -------------------------------- ### CostRank.error(start, end) Source: https://centre-borelli.github.io/ruptures-docs/code-reference/costs/costrank-reference Calculates the approximation cost for a given segment of the signal. Raises an error if the segment is too short. ```APIDOC ## error(start, end) ### Description Return the approximation cost on the segment [start:end]. ### Parameters #### Path Parameters - **start** (int) - Required - The starting index of the segment. - **end** (int) - Required - The ending index of the segment. ### Returns - **float** - The calculated cost for the segment. ### Raises - **NotEnoughPoints** - Raised when the segment length (end - start) is less than `min_size`. ``` -------------------------------- ### Initialize Pelt Instance Source: https://centre-borelli.github.io/ruptures-docs/code-reference/detection/pelt-reference Initializes the Pelt algorithm with specified cost model, minimum segment size, and subsampling rate. Use `custom_cost` for advanced cost function integration. ```python def __init__(self, model="l2", custom_cost=None, min_size=2, jump=5, params=None): """Initialize a Pelt instance. Args: model (str, optional): segment model, ["l1", "l2", "rbf"]. Not used if ``'custom_cost'`` is not None. custom_cost (BaseCost, optional): custom cost function. Defaults to None. min_size (int, optional): minimum segment length. jump (int, optional): subsample (one every *jump* points). params (dict, optional): a dictionary of parameters for the cost instance. """ if custom_cost is not None and isinstance(custom_cost, BaseCost): self.cost = custom_cost else: if params is None: self.cost = cost_factory(model=model) else: self.cost = cost_factory(model=model, **params) self.min_size = max(min_size, self.cost.min_size) self.jump = jump self.n_samples = None ``` -------------------------------- ### CostLinear Error Calculation Source: https://centre-borelli.github.io/ruptures-docs/code-reference/costs/costlinear-reference Calculates the approximation cost for a given segment [start:end] using least squares. Raises NotEnoughPoints if the segment is too short. ```python def error(self, start, end) -> float: """Return the approximation cost on the segment [start:end]. Args: start (int): start of the segment end (int): end of the segment Returns: segment cost Raises: NotEnoughPoints: when the segment is too short (less than `min_size` samples). """ if end - start < self.min_size: raise NotEnoughPoints y, X = self.signal[start:end], self.covar[start:end] _, residual, _, _ = lstsq(X, y, rcond=None) return residual.sum() ``` -------------------------------- ### CostRank.__init__() Source: https://centre-borelli.github.io/ruptures-docs/code-reference/costs/costrank-reference Initializes the CostRank object. Sets up internal variables for covariance, ranks, and minimum segment size. ```APIDOC ## __init__() ### Description Initialize the object. ### Attributes - `inv_cov`: (None) Placeholder for the inverse covariance matrix. - `ranks`: (None) Placeholder for the rank-transformed signal. - `min_size`: (int) Minimum segment size, defaults to 2. ``` -------------------------------- ### CostNormal Error Calculation Source: https://centre-borelli.github.io/ruptures-docs/code-reference/costs/costnormal-reference Calculates the cost for a given segment [start:end]. Raises `NotEnoughPoints` if the segment is shorter than `min_size`. Handles both univariate and multivariate signals. ```python def error(self, start, end) -> float: """Return the approximation cost on the segment [start:end]. Args: start (int): start of the segment end (int): end of the segment Returns: segment cost Raises: NotEnoughPoints: when the segment is too short (less than `min_size` samples). """ if end - start < self.min_size: raise NotEnoughPoints sub = self.signal[start:end] if self.signal.shape[1] > 1: cov = np.cov(sub.T) else: cov = np.array([[sub.var()]]) if self.add_small_diag: # adding small bias cov += 1e-6 * np.eye(self.n_dims) _, val = slogdet(cov) return val * (end - start) ``` -------------------------------- ### CostMl Error Calculation Source: https://centre-borelli.github.io/ruptures-docs/code-reference/costs/costml-reference Calculates the approximation cost for a given segment [start:end]. Raises NotEnoughPoints if the segment is shorter than min_size. Requires the signal to be fitted first. ```python def error(self, start, end): """Return the approximation cost on the segment [start:end]. Args: start (int): start of the segment end (int): end of the segment Returns: float: segment cost Raises: NotEnoughPoints: when the segment is too short (less than ``'min_size'`` samples). """ if end - start < self.min_size: raise NotEnoughPoints sub_gram = self.gram[start:end, start:end] val = np.diagonal(sub_gram).sum() val -= sub_gram.sum() / (end - start) return val ``` -------------------------------- ### Initialize Window algorithm with jump parameter for faster prediction Source: https://centre-borelli.github.io/ruptures-docs/user-guide/detection/window Initializes the `Window` algorithm with a `jump` parameter to increase prediction speed at the potential cost of precision. ```python algo = rpt.Window(model=model, jump=10).fit(signal) ``` -------------------------------- ### CostCosine Error Calculation Source: https://centre-borelli.github.io/ruptures-docs/code-reference/costs/costcosine-reference Calculates the approximation cost for a given segment [start:end]. Raises NotEnoughPoints if the segment is shorter than min_size. Requires the signal to be fitted first. ```python def error(self, start, end) -> float: """Return the approximation cost on the segment [start:end]. Args: start (int): start of the segment end (int): end of the segment Returns: segment cost Raises: NotEnoughPoints: when the segment is too short (less than `min_size` samples). """ if end - start < self.min_size: raise NotEnoughPoints sub_gram = self.gram[start:end, start:end] val = np.diagonal(sub_gram).sum() val -= sub_gram.sum() / (end - start) return val ``` -------------------------------- ### Create Signal and Imports Source: https://centre-borelli.github.io/ruptures-docs/user-guide/costs/costrank Imports necessary libraries and generates a piecewise constant signal with specified dimensions, change points, and noise level. ```python import numpy as np import matplotlib.pylab as plt import ruptures as rpt # creation of data n, dim = 500, 3 # number of samples, dimension n_bkps, sigma = 3, 5 # number of change points, noise standard deviation signal, bkps = rpt.pw_constant(n, dim, n_bkps, noise_std=sigma) ``` -------------------------------- ### CostAR Error Calculation Source: https://centre-borelli.github.io/ruptures-docs/code-reference/costs/costautoregressive-reference Calculates the approximation cost for a given segment [start:end] using least squares. Raises NotEnoughPoints if the segment is shorter than the minimum required size. ```python def error(self, start, end): """Return the approximation cost on the segment [start:end]. Args: start (int): start of the segment end (int): end of the segment Returns: float: segment cost Raises: NotEnoughPoints: when the segment is too short (less than ``'min_size'`` samples). """ if end - start < self.min_size: raise NotEnoughPoints y, X = self.signal[start:end], self.covar[start:end] _, residual, _, _ = lstsq(X, y, rcond=None) return residual.sum() ``` -------------------------------- ### Initialize Dynp with Custom Cost Source: https://centre-borelli.github.io/ruptures-docs/code-reference/detection/dynp-reference Instantiate the Dynp class, optionally providing a custom cost function. Ensure the custom cost is a valid BaseCost instance. ```python Dynp(model="l2", custom_cost=None, min_size=2, jump=5, params=None) ``` -------------------------------- ### CostCLinear Error Calculation Source: https://centre-borelli.github.io/ruptures-docs/code-reference/costs/costclinear-reference Calculates the approximation cost for a given segment [start:end] using a piecewise linear model with a continuity constraint. Raises NotEnoughPoints if the segment is too short. ```python def error(self, start, end) -> float: """Return the approximation cost on the segment [start:end]. Args: start (int): start of the segment end (int): end of the segment Returns: segment cost (float) Raises: NotEnoughPoints: when the segment is too short (less than `min_size` samples). """ if end - start < self.min_size: raise NotEnoughPoints if start == 0: start = 1 sub = self.signal[start:end] slope = (self.signal[end - 1] - self.signal[start - 1]) / (end - start) intercept = self.signal[start - 1] approx = slope.reshape(-1, 1) * np.arange( 1, end - start + 1 ) + intercept.reshape(-1, 1) return np.sum((sub - approx.transpose()) ** 2) ``` -------------------------------- ### Binseg Initialization Source: https://centre-borelli.github.io/ruptures-docs/code-reference/detection/binseg-reference Initializes the Binseg algorithm with specified parameters. ```APIDOC ## Binseg ### Description Binary segmentation algorithm. ### Parameters #### `__init__` - **model** (str, optional): segment model, ["l1", "l2", "rbf",...]. Not used if ``'custom_cost'`` is not None. Defaults to "l2". - **custom_cost** (BaseCost, optional): custom cost function. Defaults to None. - **min_size** (int, optional): minimum segment length. Defaults to 2 samples. - **jump** (int, optional): subsample (one every *jump* points). Defaults to 5 samples. - **params** (dict, optional): a dictionary of parameters for the cost instance. Defaults to None. ``` -------------------------------- ### Create Data with Piecewise Linear Trends Source: https://centre-borelli.github.io/ruptures-docs/user-guide/costs/costlinear Generates synthetic data with multiple linear trends and adds Gaussian noise. This setup is useful for testing change point detection algorithms. ```python import numpy as np import matplotlib.pylab as plt import ruptures as rpt # creation of data n, n_reg = 2000, 3 # number of samples, number of regressors (including intercept) n_bkps = 3 # number of change points # regressors tt = np.linspace(0, 10 * np.pi, n) X = np.vstack((np.sin(tt), np.sin(5 * tt), np.ones(n))).T # parameter vectors deltas, bkps = rpt.pw_constant(n, n_reg, n_bkps, noise_std=None, delta=(1, 3)) # observed signal y = np.sum(X * deltas, axis=1) y += np.random.normal(size=y.shape) # display signal rpt.show.display(y, bkps, figsize=(10, 6)) plt.show() ``` -------------------------------- ### Dynp Class Initialization Source: https://centre-borelli.github.io/ruptures-docs/code-reference/detection/dynp-reference Initializes the Dynp algorithm with specified parameters for cost function, minimum segment size, and sampling jump. ```APIDOC ## Dynp(model="l2", custom_cost=None, min_size=2, jump=5, params=None) ### Description Creates an instance of the dynamic programming change point detection algorithm. ### Parameters * **model** (str, optional): The segment model to use. Supported values are "l1", "l2", "rbf". This parameter is ignored if `custom_cost` is provided. Defaults to "l2". * **custom_cost** (BaseCost, optional): A custom cost function object. If provided, it overrides the `model` parameter. Defaults to None. * **min_size** (int, optional): The minimum length of a segment. This value is also constrained by the minimum size required by the cost function. Defaults to 2. * **jump** (int, optional): The subsampling interval. Only points at indices that are multiples of `jump` are considered as potential change points. Defaults to 5. * **params** (dict, optional): A dictionary of parameters to be passed to the cost function factory if a custom model is specified. Defaults to None. ``` -------------------------------- ### Initialize change point detection algorithm Source: https://centre-borelli.github.io/ruptures-docs/examples/music-segmentation Initialize the KernelCPD algorithm with a linear kernel and fit it to the transposed tempogram data. This prepares the algorithm for change point detection. ```python # Choose detection method algo = rpt.KernelCPD(kernel="linear").fit(tempogram.T) # Choose the number of changes (elbow heuristic) n_bkps_max = 20 # K_max # Start by computing the segmentation with most changes. ``` -------------------------------- ### Import necessary libraries and define utility functions Source: https://centre-borelli.github.io/ruptures-docs/examples/merging-cost-functions Imports `matplotlib`, `numpy`, and `ruptures`. Defines utility functions for min-max scaling and figure/axis creation. These are prerequisites for the cost function merging example. ```python import matplotlib.pyplot as plt import numpy as np import ruptures as rpt from ruptures.base import BaseCost WINDOW_SIZE = 200 def minmax_scale(array: np.ndarray) -> np.ndarray: """Scale each dimension to the [0, 1] range.""" return (array - np.min(array, axis=0)) / (np.max(array, axis=0) - np.min(array, axis=0) + 1e-8 ) def fig_ax(figsize=(10, 3)): return plt.subplots(figsize=figsize) ``` -------------------------------- ### Binseg Single Breakpoint Calculation Source: https://centre-borelli.github.io/ruptures-docs/code-reference/detection/binseg-reference Finds the optimal breakpoint within a given segment [start:end]. It considers segments of at least `min_size` and uses `jump` for subsampling. Returns the breakpoint and the associated gain. ```python @lru_cache(maxsize=None) def single_bkp(self, start, end): """Return the optimal breakpoint of [start:end] (if it exists).""" segment_cost = self.cost.error(start, end) if np.isinf(segment_cost) and segment_cost < 0: # if cost is -inf return None, 0 gain_list = list() for bkp in range(start, end, self.jump): if bkp - start >= self.min_size and end - bkp >= self.min_size: gain = ( segment_cost - self.cost.error(start, bkp) - self.cost.error(bkp, end) ) gain_list.append((gain, bkp)) try: gain, bkp = max(gain_list) except ValueError: # if empty sub_sampling return None, 0 return bkp, gain ``` -------------------------------- ### Initialize Window Detector Source: https://centre-borelli.github.io/ruptures-docs/code-reference/detection/window-reference Instantiate the Window detector with parameters like window width, model type, minimum segment size, and jump interval. Custom cost functions can also be provided. ```python class Window(BaseEstimator): """Window sliding method.""" def __init__( self, width=100, model="l2", custom_cost=None, min_size=2, jump=5, params=None, ): """Instanciate with window length. Args: width (int, optional): window length. Defaults to 100 samples. model (str, optional): segment model, ["l1", "l2", "rbf"]. Not used if `custom_cost` is not None. custom_cost (BaseCost, optional): custom cost function. Defaults to None. min_size (int, optional): minimum segment length. jump (int, optional): subsample (one every *jump* points). params (dict, optional): a dictionary of parameters for the cost instance.` """ self.min_size = min_size self.jump = jump self.width = 2 * (width // 2) self.n_samples = None self.signal = None self.inds = None if custom_cost is not None and isinstance(custom_cost, BaseCost): self.cost = custom_cost else: if params is None: self.cost = cost_factory(model=model) else: self.cost = cost_factory(model=model, **params) self.score = list() ``` -------------------------------- ### Find Single Optimal Breakpoint Source: https://centre-borelli.github.io/ruptures-docs/code-reference/detection/binseg-reference Finds the optimal breakpoint within a given segment [start:end]. Uses caching for performance. Returns `None` and 0 if the cost is negative infinity or if no valid breakpoint can be found. ```python @lru_cache(maxsize=None) def single_bkp(self, start, end): """Return the optimal breakpoint of [start:end] (if it exists).""" segment_cost = self.cost.error(start, end) if np.isinf(segment_cost) and segment_cost < 0: # if cost is -inf return None, 0 gain_list = list() for bkp in range(start, end, self.jump): if bkp - start >= self.min_size and end - bkp >= self.min_size: gain = ( segment_cost - self.cost.error(start, bkp) - self.cost.error(bkp, end) ) gain_list.append((gain, bkp)) try: gain, bkp = max(gain_list) except ValueError: # if empty sub_sampling return None, 0 return bkp, gain ``` -------------------------------- ### __init__() Source: https://centre-borelli.github.io/ruptures-docs/code-reference/costs/costl1-reference Initializes the CostL1 object. Sets the signal to None and minimum segment size to 2. ```APIDOC ## __init__() ### Description Initialize the object. ### Returns - `self`: The initialized CostL1 object. ``` -------------------------------- ### Initialize KernelCPD Source: https://centre-borelli.github.io/ruptures-docs/code-reference/detection/kernelcpd-reference Creates a KernelCPD instance with specified kernel, minimum segment size, and optional kernel parameters. Supports 'linear', 'rbf', and 'cosine' kernels. The 'jump' parameter is fixed at 1. ```python def __init__(self, kernel="linear", min_size=2, jump=1, params=None): r"""Creates a KernelCPD instance. Available kernels: - `linear`: $k(x,y) = x^T y$. - `rbf`: $k(x, y) = exp(\gamma \|x-y\|^2)$ where $\gamma>0$ (`gamma`) is a user-defined parameter. - `cosine`: $k(x,y)= (x^T y)/(\|x\||y\|)$. Args: kernel (str, optional): name of the kernel, ["linear", "rbf", "cosine"] min_size (int, optional): minimum segment length. jump (int, optional): not considered, set to 1. params (dict, optional): a dictionary of parameters for the kernel instance Raises: AssertionError: if the kernel is not implemented. """ self.kernel_name = kernel err_msg = "Kernel not found: {}.".format(self.kernel_name) assert self.kernel_name in ["linear", "rbf", "cosine"], err_msg self.model_name = "l2" if self.kernel_name == "linear" else self.kernel_name self.params = params # load the associated cost function if self.params is None: self.cost = cost_factory(model=self.model_name) else: self.cost = cost_factory(model=self.model_name, **self.params) self.min_size = max(min_size, self.cost.min_size) self.jump = 1 # set to 1 self.n_samples = None self.segmentations_dict = dict() # {n_bkps: bkps_list} ``` -------------------------------- ### Predict Optimal Breakpoints Source: https://centre-borelli.github.io/ruptures-docs/code-reference/detection/binseg-reference Call after fitting to get optimal breakpoints. The stopping rule depends on the provided parameter (`n_bkps`, `pen`, or `epsilon`). Raises `AssertionError` if no stopping parameter is set, or `BadSegmentationParameters` for impossible configurations. ```python def predict(self, n_bkps=None, pen=None, epsilon=None): """Return the optimal breakpoints. Must be called after the fit method. The breakpoints are associated with the signal passed to [`fit`][ruptures.detection.binseg.Binseg.fit]. The stopping rule depends on the parameter passed to the function. Args: n_bkps (int): number of breakpoints to find before stopping. pen (float): penalty value (>0) epsilon (float): reconstruction budget (>0) Raises: AssertionError: if none of `n_bkps`, `pen`, `epsilon` is set. BadSegmentationParameters: in case of impossible segmentation configuration Returns: list: sorted list of breakpoints """ msg = "Give a parameter." assert any(param is not None for param in (n_bkps, pen, epsilon)), msg # raise an exception in case of impossible segmentation configuration if not sanity_check( n_samples=self.cost.signal.shape[0], n_bkps=0 if n_bkps is None else n_bkps, jump=self.jump, min_size=self.min_size, ): raise BadSegmentationParameters partition = self._seg(n_bkps=n_bkps, pen=pen, epsilon=epsilon) bkps = sorted(e for s, e in partition.keys()) return bkps ``` -------------------------------- ### Adjust Margin for Precision and Recall Calculation Source: https://centre-borelli.github.io/ruptures-docs/user-guide/metrics/precisionrecall The `margin` parameter in the `precision_recall` function allows you to specify the tolerance for considering a detected change point as a true positive. This example shows how to use the default margin (10) and a custom margin (20). ```python p, r = precision_recall(bkps1, bkps2, margin=10) print((p, r)) ``` ```python p, r = precision_recall(bkps1, bkps2, margin=20) print((p, r)) ``` -------------------------------- ### BottomUp Initialization Source: https://centre-borelli.github.io/ruptures-docs/code-reference/detection/bottomup-reference Initializes the BottomUp instance with specified parameters for change point detection. ```APIDOC ## __init__(model='l2', custom_cost=None, min_size=2, jump=5, params=None) ### Description Initialize a BottomUp instance. ### Parameters #### Path Parameters - `model` (str) - Optional - segment model, ["l1", "l2", "rbf"]. Not used if 'custom_cost' is not None. Defaults to 'l2'. - `custom_cost` (BaseCost) - Optional - custom cost function. Defaults to None. - `min_size` (int) - Optional - minimum segment length. Defaults to 2 samples. - `jump` (int) - Optional - subsample (one every _jump_ points). Defaults to 5 samples. - `params` (dict) - Optional - a dictionary of parameters for the cost instance. Defaults to None. ``` -------------------------------- ### Initialize Dynp Detector Source: https://centre-borelli.github.io/ruptures-docs/code-reference/detection/dynp-reference Instantiate the Dynp detector. Use 'custom_cost' for user-defined cost functions or specify a 'model' like 'l1', 'l2', or 'rbf'. Adjust 'min_size' and 'jump' for segment constraints and subsampling. ```python def __init__(self, model="l2", custom_cost=None, min_size=2, jump=5, params=None): """Creates a Dynp instance. Args: model (str, optional): segment model, ["l1", "l2", "rbf"]. Not used if ``'custom_cost'`` is not None. custom_cost (BaseCost, optional): custom cost function. Defaults to None. min_size (int, optional): minimum segment length. jump (int, optional): subsample (one every *jump* points). params (dict, optional): a dictionary of parameters for the cost instance. """ if custom_cost is not None and isinstance(custom_cost, BaseCost): self.cost = custom_cost else: self.model_name = model if params is None: self.cost = cost_factory(model=model) else: self.cost = cost_factory(model=model, **params) self.min_size = max(min_size, self.cost.min_size) self.jump = jump self.n_samples = None ``` -------------------------------- ### Initialize and Fit Binseg Model Source: https://centre-borelli.github.io/ruptures-docs/user-guide/detection/binseg Initialize a Binseg instance with a specified cost function model and fit it to the signal. The cost function determines how change points are evaluated. ```python import numpy as np import matplotlib.pylab as plt import ruptures as rpt # creation of data n = 500 # number of samples dim = 1 # dimension of the signal (assuming univariate) n_bkps, sigma = 3, 5 # number of change points, noise standard deviation signal, bkps = rpt.pw_constant(n, dim, n_bkps, noise_std=sigma) # change point detection model = "l2" # "l1", "rbf", "linear", "normal", "ar",... algo = rpt.Binseg(model=model).fit(signal) my_bkps = algo.predict(n_bkps=3) # show results rpt.show.display(signal, bkps, my_bkps, figsize=(10, 6)) plt.show() ``` -------------------------------- ### Create Sample Signal and Display Source: https://centre-borelli.github.io/ruptures-docs/user-guide/costs/costautoregressive Generates a synthetic signal with piecewise linear trends and noise, then displays it along with the true change points. This is useful for testing change point detection algorithms. ```python from itertools import cycle import numpy as np import matplotlib.pylab as plt import ruptures as rpt # creation of data n = 2000 n_bkps, sigma = 4, 0.5 # number of change points, noise standart deviation bkps = [400, 1000, 1300, 1800, n] f1 = np.array([0.075, 0.1]) f2 = np.array([0.1, 0.125]) freqs = np.zeros((n, 2)) for sub, val in zip(np.split(freqs, bkps[:-1]), cycle([f1, f2])): sub += val tt = np.arange(n) signal = np.sum((np.sin(2 * np.pi * tt * f) for f in freqs.T)) signal += np.random.normal(scale=sigma, size=signal.shape) # display signal rpt.show.display(signal, bkps, figsize=(10, 6)) plt.show() ``` -------------------------------- ### Window Class Initialization Source: https://centre-borelli.github.io/ruptures-docs/code-reference/detection/window-reference Initializes the Window object with parameters for change point detection using a sliding window. Users can specify window width, cost model, minimum segment size, jump, and custom cost functions. ```APIDOC ## Window(width=100, model="l2", custom_cost=None, min_size=2, jump=5, params=None) ### Description Instantiate with window length. ### Parameters * **width** (int, optional): window length. Defaults to 100 samples. * **model** (str, optional): segment model, ["l1", "l2", "rbf"]. Not used if `custom_cost` is not None. * **custom_cost** (BaseCost, optional): custom cost function. Defaults to None. * **min_size** (int, optional): minimum segment length. * **jump** (int, optional): subsample (one every *jump* points). * **params** (dict, optional): a dictionary of parameters for the cost instance. ``` -------------------------------- ### Binseg Initialization Source: https://centre-borelli.github.io/ruptures-docs/code-reference/detection/binseg-reference Initializes the Binseg class with various cost functions and parameters. Use custom_cost for specific segmentation needs or model for standard cost functions like L1, L2, or RBF. ```python class Binseg(BaseEstimator): """Binary segmentation.""" def __init__(self, model="l2", custom_cost=None, min_size=2, jump=5, params=None): """Initialize a Binseg instance. Args: model (str, optional): segment model, ["l1", "l2", "rbf",...]. Not used if ``'custom_cost'`` is not None. custom_cost (BaseCost, optional): custom cost function. Defaults to None. min_size (int, optional): minimum segment length. Defaults to 2 samples. jump (int, optional): subsample (one every *jump* points). Defaults to 5 samples. params (dict, optional): a dictionary of parameters for the cost instance. """ if custom_cost is not None and isinstance(custom_cost, BaseCost): self.cost = custom_cost else: if params is None: self.cost = cost_factory(model=model) else: self.cost = cost_factory(model=model, **params) self.min_size = max(min_size, self.cost.min_size) self.jump = jump self.n_samples = None self.signal = None ``` -------------------------------- ### __init__() Source: https://centre-borelli.github.io/ruptures-docs/code-reference/costs/costclinear-reference Initializes the CostCLinear object, setting the signal to None and the minimum segment size to 3. ```APIDOC ## __init__() ### Description Initialize the object. ### Returns - `self`: The initialized CostCLinear object. ``` -------------------------------- ### Integrate CostRank into Change Point Detection Source: https://centre-borelli.github.io/ruptures-docs/user-guide/costs/costrank Demonstrates how to use the CostRank instance with a change point detection algorithm like Dynp, either by passing a custom cost instance or by specifying the model name. ```python c = rpt.costs.CostRank() algo = rpt.Dynp(custom_cost=c) # is equivalent to algo = rpt.Dynp(model="rank") ``` -------------------------------- ### Instantiate and Use CostMl for Sub-signal Cost Calculation Source: https://centre-borelli.github.io/ruptures-docs/user-guide/costs/costml Initializes a CostMl instance with an identity matrix as the metric and calculates the cost for a specific sub-signal. Requires the signal to be fitted first. ```python M = np.eye(dim) c = rpt.costs.CostMl(metric=M).fit(signal) print(c.error(50, 150)) ``` -------------------------------- ### Fit and Predict with Window Source: https://centre-borelli.github.io/ruptures-docs/code-reference/detection/window-reference A convenience method that first fits the signal and then predicts the change points. It simplifies the workflow by combining `fit` and `predict` calls. ```python def fit_predict(self, signal, n_bkps=None, pen=None, epsilon=None): """Helper method to call fit and predict once.""" self.fit(signal) return self.predict(n_bkps=n_bkps, pen=pen, epsilon=epsilon) ``` -------------------------------- ### PELT: Python vs. C Implementation (Linear Kernel) Source: https://centre-borelli.github.io/ruptures-docs/examples/kernel-cpd-performance-comparison Compares the execution time of pure Python Pelt and C-implemented KernelCPD for detecting an unknown number of change points using the PELT algorithm with a linear kernel and a specified penalty value. Both algorithms are fitted to the signal and then used to predict the change points. ```python algo_python = rpt.Pelt(model="l2", jump=1, min_size=2).fit( signal ) # written in pure python algo_c = rpt.KernelCPD(kernel="linear", min_size=2).fit( signal ) # written in C, same class as before penalty_value = 100 # beta for label, algo in zip( ("Python implementation", "C implementation"), (algo_python, algo_c) ): start_time = time.time() result = algo.predict(pen=penalty_value) print(f"{label}:\t{time.time() - start_time:.3f} s") ```