### Setup development environment Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Commands to clone the repository, create a virtual environment, install with development dependencies, and set up pre-commit hooks. ```bash # Clone repository git clone https://github.com/hildensia/bayesian_changepoint_detection.git cd bayesian_changepoint_detection # Install with development dependencies uv venv && source .venv/bin/activate uv pip install -e ".[dev]" # ...or, without uv: python -m venv .venv && source .venv/bin/activate && pip install -e ".[dev]" # Install pre-commit hooks (ruff lint + format on staged files) pre-commit install ``` -------------------------------- ### Install and run tests Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/AGENTS.md Install the package with development dependencies and run the test suite. Tests must pass without a GPU. ```bash pip install -e ".[dev]" ``` ```bash pytest ``` -------------------------------- ### Clone, setup virtual environment, install dev dependencies, and run tests Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/CONTRIBUTING.md Sets up a local development environment for the library. Creates a virtual environment, installs the package with the 'dev' extra (which includes numpy and scipy for the test suite), and runs the full test suite with pytest. ```bash git clone https://github.com/hildensia/bayesian_changepoint_detection.git cd bayesian_changepoint_detection python -m venv .venv && source .venv/bin/activate # or: uv venv && source .venv/bin/activate pip install -e ".[dev]" # or: uv pip install -e ".[dev]" pytest ``` -------------------------------- ### Install with uv Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Alternative installation using the uv package manager. ```bash uv add bayesian-changepoint ``` -------------------------------- ### Install with pip Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Install the bayesian-changepoint distribution using pip. Requires Python 3.9 or higher and PyTorch 2.0 or higher (installed automatically). ```bash pip install bayesian-changepoint ``` -------------------------------- ### Install pre-commit hooks and run linter/formatter Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/CONTRIBUTING.md Installs pre-commit hooks once and runs the same lint and format checks that CI performs. Requires the 'dev' extra which includes ruff. ```bash pre-commit install # once; hooks come from .pre-commit-config.yaml ruff check . && ruff format . # what CI checks (ruff is in the dev extra) ``` -------------------------------- ### Preview and build the documentation site with mkdocs Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/CONTRIBUTING.md Install the documentation dependencies and preview the site locally with live reload. Use `mkdocs build --strict` to match CI, where warnings fail the build. ```bash pip install -e ".[docs]" ``` ```bash mkdocs serve # http://127.0.0.1:8000, rebuilds on save ``` ```bash mkdocs build --strict # what CI runs; warnings fail the build ``` -------------------------------- ### Check library version Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/SECURITY.md Use this command to retrieve the installed version of the bayesian_changepoint_detection library, which is required when reporting a vulnerability. ```bash python -c "import bayesian_changepoint_detection as b; print(b.__version__)" ``` -------------------------------- ### Replace old package names Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Uninstall the old distribution names `bayescd` and `bayesian-changepoint-detection` before installing the new one. Both are frozen and do not receive updates. ```bash pip uninstall bayescd bayesian-changepoint-detection pip install bayesian-changepoint ``` -------------------------------- ### viterbi_changepoints(data, hazard, likelihood) Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Computes the single most probable run-length path and its segment starts using the Viterbi algorithm. Returns the path and changepoint indices. ```APIDOC ## viterbi_changepoints(data, hazard, likelihood) ### Description Computes the single most probable run-length path and its segment starts using the Viterbi algorithm. Returns the path and changepoint indices. ### Parameters - **data** (tensor) - Required - Input data, shape `[T]` or `[T, d]`. - **hazard** (callable) - Required - Hazard function. - **likelihood** (object) - Required - Likelihood model. ### Returns - **path** (tensor) - Most probable run-length path. - **changepoints** (tensor) - Indices where new segments start. ``` -------------------------------- ### segment_statistics(data, starts) Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Computes per-segment mean and standard deviation, change in mean, and z-score at each changepoint. Useful for summarizing detected segments. ```APIDOC ## segment_statistics(data, starts) ### Description Computes per-segment mean and standard deviation, change in mean, and z-score at each changepoint. Useful for summarizing detected segments. ### Parameters - **data** (tensor) - Required - Input data, shape `[T]` or `[T, d]`. - **starts** (tensor) - Required - Indices where segments start. ### Returns - **statistics** (dict) - Per-segment mean, std, change in mean, and z-score. ``` -------------------------------- ### Streaming detection with OnlineChangepointDetector Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Processes a stream of unknown length one observation at a time, keeping only the current run-length posterior. Use max_run_length to bound memory and time per observation. The changepoint_probability method gives the probability of a segment starting lag observations ago. ```python from bayesian_changepoint_detection import OnlineChangepointDetector detector = OnlineChangepointDetector( hazard, StudentT(alpha=0.1, beta=0.01, kappa=1, mu=0), max_run_length=500 ) starts = [] for x in data: # any iterable: a socket, a file, a generator detector.update(x) # P(a segment started 10 observations ago), as changepoint_probabilities if detector.t > 10 and detector.changepoint_probability(lag=10) > 0.5: starts.append(detector.t - 10) print(starts) # [50, 100] ``` -------------------------------- ### Import libraries and setup for Bayesian changepoint detection Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/examples/Example_Code.ipynb Imports matplotlib, numpy, and the data generation function, then enables inline plotting and autoreload for the notebook. ```python import matplotlib.pyplot as plt import numpy as np from bayesian_changepoint_detection.generate_data import generate_normal_time_series %matplotlib inline %load_ext autoreload %autoreload 2 ``` -------------------------------- ### Multivariate changepoint detection with MultivariateT Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Pass a [T, d] tensor with one row per observation and a multivariate likelihood. All detectors validate input: data must be [T] or [T, d], non-empty, real, finite, and match the likelihood's dims; a transposed [d, T] tensor is rejected with a hint. The example creates three segments of 50 observations each and prints the detected changepoints. ```python from bayesian_changepoint_detection import MultivariateT dims = 3 mv_data = torch.cat([ torch.randn(50, dims) + torch.tensor([0.0, 0.0, 0.0]), torch.randn(50, dims) + torch.tensor([2.0, -1.0, 1.0]), torch.randn(50, dims) + torch.tensor([0.0, 0.0, 0.0]), ]) R, _ = online_changepoint_detection(mv_data, hazard, MultivariateT(dims=dims)) print(get_map_changepoints(R, min_separation=10)) # tensor([ 48, 100]) ``` -------------------------------- ### Default CPU usage with online and offline changepoint detection Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/docs/devices.md Runs both detectors with default device (CPU) on a synthetic 200-point series. The online detector uses StudentT likelihood and constant_hazard; the offline detector uses OfflineStudentT and const_prior. Prints segment starts and device of R. ```python from functools import partial import torch from bayesian_changepoint_detection import ( const_prior, constant_hazard, get_map_changepoints, offline_changepoint_detection, online_changepoint_detection, ) from bayesian_changepoint_detection.offline_likelihoods import StudentT as OfflineStudentT from bayesian_changepoint_detection.online_likelihoods import StudentT torch.manual_seed(0) data = torch.cat([torch.randn(100), torch.randn(100) + 3]) R, map_run_lengths = online_changepoint_detection( data, partial(constant_hazard, 100), StudentT() ) print("online, segment starts:", get_map_changepoints(R)) print("R lives on", R.device) Q, P, changepoint_log_probs = offline_changepoint_detection( data, partial(const_prior, p=1 / 201), OfflineStudentT() ) changepoint_probs = torch.exp(changepoint_log_probs).sum(0) print("offline, P(change) > 0.5 at:", torch.where(changepoint_probs > 0.5)[0] + 1) ``` -------------------------------- ### Segment statistics with segment_statistics Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Summarizes segments between changepoints: mean, standard deviation, and for each changepoint the change in mean and a Welch z-score. The z-score overstates significance because changepoints were found in the same data; treat as a rough guide. Offline positions are the last index of the old segment: pass positions + 1. ```python from bayesian_changepoint_detection import segment_statistics stats = segment_statistics(data, get_map_changepoints(R, min_separation=10)) print(stats.means.tolist()) # about [0.096, 3.173, -0.165] print(stats.mean_changes.tolist()) # about [3.078, -3.339]: up, then down ``` -------------------------------- ### changepoint_probabilities(R, lag) Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Computes the probability that a new segment started at each time point, judged `lag` observations later. Useful for precise changepoint localization. ```APIDOC ## changepoint_probabilities(R, lag) ### Description Computes the probability that a new segment started at each time point, judged `lag` observations later. Useful for precise changepoint localization. ### Parameters - **R** (tensor) - Required - Run-length posterior from `online_changepoint_detection`. - **lag** (int) - Required - Number of observations to wait before judging. ### Returns - **probabilities** (tensor) - Probability of a new segment starting at each time point. ``` -------------------------------- ### Generate multivariate data and load modules Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/examples/Multivariate_Example.ipynb Imports matplotlib and the bayesian_changepoint_detection data generation module, then generates a multivariate time series with changepoints using gd.generate_xuan_motivating_example(200, 500). The partition and data arrays are used in subsequent examples. ```python import matplotlib.pyplot as plt import bayesian_changepoint_detection.generate_data as gd %matplotlib inline %load_ext autoreload %autoreload 2 partition, data = gd.generate_xuan_motivating_example(200, 500) ``` -------------------------------- ### get_map_changepoints(R, min_separation=1) Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Extracts the indices where the MAP run-length path starts a new segment. Optionally enforces a minimum separation between changepoints. ```APIDOC ## get_map_changepoints(R, min_separation=1) ### Description Extracts the indices where the MAP run-length path starts a new segment. Optionally enforces a minimum separation between changepoints. ### Parameters - **R** (tensor) - Required - Run-length posterior from `online_changepoint_detection`. - **min_separation** (int) - Optional - Minimum number of observations between changepoints (default: 1). ### Returns - **changepoints** (tensor) - Indices where a new segment starts. ``` -------------------------------- ### Build sdist and wheel Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Commands to build the distribution packages and check the metadata with twine. ```bash # Build sdist and wheel python -m build # Check the metadata PyPI will see twine check --strict dist/* ``` -------------------------------- ### Lint and format with ruff Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Commands to run ruff linting and formatting on the codebase. ```bash # Lint with ruff ruff check . # Format code ruff format . ``` -------------------------------- ### Project architecture tree Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Shows the file layout of the bayesian_changepoint_detection package, including the main modules and their purposes. ```text bayesian_changepoint_detection/ ├── __init__.py # Public API and __version__ (from package metadata) ├── bayesian_models.py # The two detectors, viterbi_changepoints, and the R helpers ├── streaming.py # OnlineChangepointDetector: the online recursion one observation at a time ├── segments.py # segment_statistics: mean, spread and direction of each change ├── online_likelihoods.py # Online StudentT and MultivariateT: per-run-length predictive densities ├── offline_likelihoods.py # Offline StudentT, MultivariateT, IndependentFeatures, FullCovariance: segment marginals ├── priors.py # const_prior, geometric_prior, negative_binomial_prior (segment-length priors) ├── hazard_functions.py # constant_hazard, negative_binomial_hazard ├── device.py # get_device, get_device_info, to_tensor, ensure_tensor └── generate_data.py # Synthetic series with known changepoints, for tests and examples ``` -------------------------------- ### Run a subset of tests with pytest Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/CONTRIBUTING.md Shows various ways to run a subset of the test suite: a single test file, tests by name with -k, skipping slow tests, running only GPU or math tests, and running with coverage. The -m gpu tests skip when no GPU is present. ```bash pytest tests/test_online_detection.py # one file pytest -k "multivariate and not slow" # by name pytest -m "not slow" # skip tests marked slow pytest -m gpu # only the GPU tests (they skip without one) pytest -m math # only the tests that check the mathematics pytest --cov=bayesian_changepoint_detection # with coverage (needs pytest-cov, in the dev extra) ``` -------------------------------- ### Run tests with pytest Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Commands to run the full test suite, math-only tests, behavior-only tests, coverage, and a single test file. Tests are marked with 'math' or 'behavior'. ```bash # Run all tests (about 15 s on a CPU) pytest # Only the tests that check the mathematics against independent references pytest -m math # Only the tests that pin current behavior (contracts, edge cases, devices, goldens) pytest -m behavior # With coverage pytest --cov=bayesian_changepoint_detection --cov-report=term-missing # One file pytest tests/test_online_detection.py -v ``` -------------------------------- ### get_device, get_device_info, to_tensor Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Device helpers for managing computation devices (CPU, CUDA, MPS). `get_device` returns the current device, `get_device_info` provides details, and `to_tensor` converts input to a tensor on the specified device. ```APIDOC ## get_device, get_device_info, to_tensor ### Description Device helpers for managing computation devices (CPU, CUDA, MPS). `get_device` returns the current device, `get_device_info` provides details, and `to_tensor` converts input to a tensor on the specified device. ### Parameters - **device** (str) - Optional - Device name (e.g., "cpu", "cuda", "mps", "auto"). ### Returns - **device** (torch.device) - Device object. - **info** (dict) - Device information. - **tensor** (torch.Tensor) - Converted tensor. ``` -------------------------------- ### Import bayesian_changepoint_detection Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md The import name is `bayesian_changepoint_detection`, regardless of the distribution name. ```python import bayesian_changepoint_detection ``` -------------------------------- ### Type checking with mypy Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Command to run mypy type checking on the package. This is advisory and not enforced in CI. ```bash # Type checking (configured, advisory: not enforced in CI) mypy bayesian_changepoint_detection ``` -------------------------------- ### get_device and get_device_info usage Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/docs/devices.md Shows how to query and select a device. get_device(None) returns the CPU, get_device("auto") picks the first available of CUDA, MPS, CPU, and an explicit choice is returned unchanged. ```python from bayesian_changepoint_detection import get_device, get_device_info print(get_device_info()) # cuda_available, mps_available, devices, ... print(get_device()) # cpu: the default print(get_device("auto")) # the best available device on this machine print(get_device("cpu")) # an explicit choice is returned unchanged ``` -------------------------------- ### offline_changepoint_detection(data, prior, likelihood) Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Runs the offline Bayesian changepoint detection algorithm. Returns log evidence, segment log likelihoods, and log probability of changepoints. ```APIDOC ## offline_changepoint_detection(data, prior, likelihood) ### Description Runs the offline Bayesian changepoint detection algorithm. Returns log evidence, segment log likelihoods, and log probability of changepoints. ### Parameters - **data** (tensor) - Required - Input data, shape `[T]` or `[T, d]`. - **prior** (callable) - Required - Prior on segment length. - **likelihood** (object) - Required - Likelihood model. ### Returns - **Q** (tensor) - Log evidence. - **P** (tensor) - Segment log likelihoods. - **Pcp** (tensor) - Log probability of the j-th changepoint at t. ``` -------------------------------- ### online_changepoint_detection(data, hazard, likelihood) Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Runs the online Bayesian changepoint detection algorithm on a sequence of observations. Returns the run-length posterior and the MAP run length after each point. ```APIDOC ## online_changepoint_detection(data, hazard, likelihood) ### Description Runs the online Bayesian changepoint detection algorithm on a sequence of observations. Returns the run-length posterior and the MAP run length after each point. ### Parameters - **data** (tensor) - Required - Input data, shape `[T]` or `[T, d]`. - **hazard** (callable) - Required - Hazard function for changepoint probability. - **likelihood** (object) - Required - Likelihood model (e.g., `MultivariateT`). ### Returns - **R** (tensor) - Run-length posterior, shape `[T+1, T+1]`. - **MAP run length** (tensor) - MAP run length after each point. ``` -------------------------------- ### Benchmark online changepoint detection Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/examples/Example_Code.ipynb Times the online changepoint detection algorithm with a StudentT likelihood using parameters (10, .03, 1, 0). Shows performance comparison with the offline version. ```python %timeit R, maxes = online_changepoint_detection(data, hazard_function, online_ll.StudentT(10, .03, 1, 0)) ``` -------------------------------- ### Online detection with online_changepoint_detection Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Processes a series point by point, returning the run-length posterior matrix R and MAP run lengths. Use get_map_changepoints to extract changepoint indices and changepoint_probabilities for per-position probabilities. Requires a hazard function and a likelihood object. ```python from functools import partial import torch from bayesian_changepoint_detection import ( StudentT, changepoint_probabilities, constant_hazard, get_map_changepoints, online_changepoint_detection, ) torch.manual_seed(42) data = torch.cat([ torch.randn(50) + 0, # first segment: mean 0 torch.randn(50) + 3, # second segment: mean 3 torch.randn(50) + 0, # third segment: mean 0 ]) hazard = partial(constant_hazard, 250) # prior: one change every ~250 points likelihood = StudentT(alpha=0.1, beta=0.01, kappa=1, mu=0) # unknown mean and variance R, map_run_lengths = online_changepoint_detection(data, hazard, likelihood) # Index of the first point of each new segment on the MAP run-length path. # min_separation merges starts closer than that many points when the # posterior hesitates between neighbors. print(get_map_changepoints(R, min_separation=10)) # tensor([ 50, 100]) # Or a probability per position, judged `lag` observations later. probs = changepoint_probabilities(R, lag=10) # probs[t] refers to data index t print(torch.where(probs[1:] > 0.5)[0] + 1) # tensor([ 50, 100]) ``` -------------------------------- ### Benchmark offline changepoint detection Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/examples/Example_Code.ipynb Times the offline changepoint detection algorithm using the StudentT likelihood. Shows performance comparison with the online version. ```python %timeit Q, P, Pcp = offline_changepoint_detection(data, prior_function, offline_ll.StudentT()) ``` -------------------------------- ### Plot the generated time series Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/examples/Example_Code.ipynb Creates a 16x12 figure and plots the generated data to visualize the series. ```python fig, ax = plt.subplots(figsize=[16, 12]) ax.plot(data) ``` -------------------------------- ### Opting into CUDA with fallback to CPU Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/docs/devices.md Selects CUDA if available, otherwise falls back to CPU. The likelihood is created with the device, and the online detector uses it. Results are moved back to the CPU with .cpu(). ```python device = "cuda" if torch.cuda.is_available() else "cpu" likelihood = StudentT(device=device) R, map_run_lengths = online_changepoint_detection(data, partial(constant_hazard, 100), likelihood) print("R lives on", R.device) # same device as the likelihood # Results move back to the CPU like any tensor. starts = get_map_changepoints(R).cpu() print(starts) ``` -------------------------------- ### Plot online changepoint detection results Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/examples/Example_Code.ipynb Plots the data, the negative log probability density matrix (grey-scale), and the probability of a changepoint after waiting Nw samples. Uses a sparsity of 5 for faster display. ```python import matplotlib.cm as cm epsilon = 1e-7 fig, ax = plt.subplots(3, figsize=[18, 16], sharex=True) ax[0].plot(data) sparsity = 5 # only plot every fifth data for faster display density_matrix = -(R[0:-1:sparsity, 0:-1:sparsity] + epsilon).log() ax[1].pcolor( np.array(range(0, len(R[:, 0]), sparsity)), np.array(range(0, len(R[:, 0]), sparsity)), density_matrix, cmap=cm.Greys, vmin=0, vmax=density_matrix.max(), shading="auto", ) Nw = 10 ax[2].plot(R[Nw, Nw:-1]) ``` -------------------------------- ### Run online changepoint detection Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/examples/Example_Code.ipynb Runs the online changepoint detection algorithm on the data with the defined hazard function and a StudentT likelihood. Returns R (probability distribution over sequence lengths) and maxes (MAP estimates). ```python import bayesian_changepoint_detection.online_likelihoods as online_ll from bayesian_changepoint_detection.bayesian_models import online_changepoint_detection R, maxes = online_changepoint_detection( data, hazard_function, online_ll.StudentT(alpha=0.1, beta=0.01, kappa=1, mu=0) ) ``` -------------------------------- ### Time the online detector on CPU and CUDA Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/docs/devices.md Times the online changepoint detector on a given device, discarding the first warm-up run and synchronizing CUDA before reading the clock. Build a fresh likelihood object per run because it accumulates state. Returns the minimum time over repeats after warm-up. ```python import time def time_online(data, device, repeats=3): hazard = partial(constant_hazard, 250) times = [] for _ in range(repeats + 1): likelihood = StudentT(device=device) # single-use: one per run if torch.cuda.is_available(): torch.cuda.synchronize() start = time.perf_counter() online_changepoint_detection(data, hazard, likelihood, device=device) if torch.cuda.is_available(): torch.cuda.synchronize() times.append(time.perf_counter() - start) return min(times[1:]) # drop the warm-up run torch.manual_seed(0) series = torch.cat([torch.randn(150), torch.randn(150) + 3]) print(f"cpu: {time_online(series, 'cpu'):.3f} s") if torch.cuda.is_available(): print(f"cuda: {time_online(series, 'cuda'):.3f} s") ``` -------------------------------- ### online_likelihoods.StudentT, online_likelihoods.MultivariateT Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Online conjugate models (Normal-Gamma, Normal-Wishart) for Student-T and multivariate Student-T likelihoods. Used with online detectors. ```APIDOC ## online_likelihoods.StudentT, online_likelihoods.MultivariateT ### Description Online conjugate models (Normal-Gamma, Normal-Wishart) for Student-T and multivariate Student-T likelihoods. Used with online detectors. ### Parameters - **dims** (int) - Required for MultivariateT - Dimensionality of data. ### Returns - **likelihood** (object) - Likelihood instance. ``` -------------------------------- ### Run offline changepoint detection with StudentT likelihood Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/examples/Example_Code.ipynb Calls offline_changepoint_detection with the data, prior function, and StudentT likelihood model, returning Q, P, and Pcp. ```python import bayesian_changepoint_detection.offline_likelihoods as offline_ll from bayesian_changepoint_detection.bayesian_models import offline_changepoint_detection Q, P, Pcp = offline_changepoint_detection( data, prior_function, offline_ll.StudentT() ) ``` -------------------------------- ### Plot changepoint probabilities Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/examples/Example_Code.ipynb Plots the original data and the summed probabilities of changepoints over time, showing the detection results. ```python fig, ax = plt.subplots(2, figsize=[18, 16], sharex=True) ax[0].plot(data[:]) ax[1].plot(Pcp.exp().sum(0)) ``` -------------------------------- ### OnlineChangepointDetector(hazard, likelihood, max_run_length=None) Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Streaming detector that processes observations one at a time. Provides methods to update, query the run-length posterior, MAP run length, and changepoint probability. ```APIDOC ## OnlineChangepointDetector(hazard, likelihood, max_run_length=None) ### Description Streaming detector that processes observations one at a time. Provides methods to update, query the run-length posterior, MAP run length, and changepoint probability. ### Constructor Parameters - **hazard** (callable) - Required - Hazard function. - **likelihood** (object) - Required - Likelihood model. - **max_run_length** (int) - Optional - Maximum run length to consider. ### Methods - **update(x)** - Process a new observation. - **run_length_posterior** - Current run-length posterior. - **map_run_length** - Current MAP run length. - **changepoint_probability(lag)** - Probability of a changepoint `lag` observations ago. ``` -------------------------------- ### Estimate memory usage for online and offline detectors Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/docs/devices.md Calculates memory footprint for online and offline detectors at series lengths 1,000, 10,000, and 50,000. Online uses a (T+1)x(T+1) float32 matrix; offline uses T x T and (T-1)x(T-1) float64 tables. Outputs sizes in GB. ```python for T in (1_000, 10_000, 50_000): online_bytes = 4 * (T + 1) ** 2 offline_bytes = 8 * T**2 + 8 * (T - 1) ** 2 print(f"T={T:>6}: online R {online_bytes / 1e9:6.2f} GB, offline tables {offline_bytes / 1e9:6.2f} GB") ``` -------------------------------- ### Plot full covariance model results Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/examples/Multivariate_Example.ipynb Creates a two-panel figure: the top shows raw data with original changepoints, the bottom plots the changepoint probability from Pcp_full.exp().sum(0) for the full covariance model. The legend labels the model as 'Full Covariance Model'. ```python fig, ax = plt.subplots(2, figsize=[18, 8]) for p in changes: ax[0].plot([p, p], [float(data.min()), float(data.max())], "r") for d in range(2): ax[0].plot(data[:, d]) plt.legend(["Raw data with Original Changepoints"]) ax[1].plot(Pcp_full.exp().sum(0)) plt.legend(["Full Covariance Model"]) plt.show() ``` -------------------------------- ### Time independent features model with %timeit Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/examples/Multivariate_Example.ipynb Uses the %timeit magic to benchmark the offline_changepoint_detection call with IndependentFeaturesLikelihood and the same constant prior. This measures execution time for the independent features model. ```python %timeit Q_ifm, P_ifm, Pcp_ifm = offline_changepoint_detection(data, partial(const_prior, p=1/(len(data)+1)), IndependentFeaturesLikelihood()) ``` -------------------------------- ### const_prior, geometric_prior, negative_binomial_prior Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Log priors on segment length for the offline detector. Each returns the log prior probability for a given segment length. ```APIDOC ## const_prior, geometric_prior, negative_binomial_prior ### Description Log priors on segment length for the offline detector. Each returns the log prior probability for a given segment length. ### Parameters - **r** (int) - Required - Segment length. ### Returns - **log_prior** (float) - Log prior probability. ``` -------------------------------- ### Offline detection with offline_changepoint_detection Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Sees the whole series and returns posterior probabilities that a segment ends at each position. Usually sharper than online detection; use for retrospective analysis. Note the different index convention: offline reports the last point of the old segment, online the first of the new. ```python from bayesian_changepoint_detection import const_prior, offline_changepoint_detection from bayesian_changepoint_detection.offline_likelihoods import StudentT as OfflineStudentT prior = partial(const_prior, p=1 / (len(data) + 1)) # flat prior on segment length Q, P, changepoint_log_probs = offline_changepoint_detection(data, prior, OfflineStudentT()) changepoint_probs = torch.exp(changepoint_log_probs).sum(0) # P(a segment ends at t) print(torch.where(changepoint_probs > 0.5)[0]) # tensor([49, 99]) ``` -------------------------------- ### Generate normal time series data Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/examples/Example_Code.ipynb Generates a synthetic time series with 7 changepoints, 50 segments, and 200 observations per segment using generate_normal_time_series. ```python partition, data = generate_normal_time_series(7, 50, 200) ``` -------------------------------- ### constant_hazard(lam, r) Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Hazard function returning `1/lam` for every run length. Used for online detection with constant hazard. ```APIDOC ## constant_hazard(lam, r) ### Description Hazard function returning `1/lam` for every run length. Used for online detection with constant hazard. ### Parameters - **lam** (float) - Required - Mean segment length. - **r** (int) - Required - Run length. ### Returns - **hazard** (float) - Hazard value `1/lam`. ``` -------------------------------- ### negative_binomial_hazard(k, p, r) Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Hazard function for negative binomial segment lengths with mean `k/p`. Online counterpart of `negative_binomial_prior`. ```APIDOC ## negative_binomial_hazard(k, p, r) ### Description Hazard function for negative binomial segment lengths with mean `k/p`. Online counterpart of `negative_binomial_prior`. ### Parameters - **k** (float) - Required - Number of successes. - **p** (float) - Required - Success probability. - **r** (int) - Required - Run length. ### Returns - **hazard** (float) - Hazard value. ``` -------------------------------- ### Detect changepoints with full covariance model Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/examples/Multivariate_Example.ipynb Runs offline changepoint detection using FullCovarianceLikelihood, which accounts for changes in correlation. The source warns this model takes a while to run. Returns Q_full, P_full, and Pcp_full. ```python from bayesian_changepoint_detection.offline_likelihoods import FullCovarianceLikelihood Q_full, P_full, Pcp_full = offline_changepoint_detection( data, partial(const_prior, p=1 / (len(data) + 1)), FullCovarianceLikelihood(), ) ``` -------------------------------- ### online_likelihoods.Poisson, offline_likelihoods.Poisson Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Count data likelihoods: Gamma-Poisson for online, negative-binomial predictive for offline. Used for count data. ```APIDOC ## online_likelihoods.Poisson, offline_likelihoods.Poisson ### Description Count data likelihoods: Gamma-Poisson for online, negative-binomial predictive for offline. Used for count data. ### Returns - **likelihood** (object) - Likelihood instance. ``` -------------------------------- ### Plot raw data with changepoint lines Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/examples/Multivariate_Example.ipynb Computes cumulative changepoint positions from the partition and plots vertical red lines at each changepoint, overlaying the two data dimensions. This visualizes the ground truth changepoints for comparison with detection results. ```python import numpy as np changes = partition.cumsum(0) fig, ax = plt.subplots(figsize=[16, 4]) for p in changes: ax.plot([p, p], [float(data.min()), float(data.max())], "r") for d in range(2): ax.plot(data[:, d]) ``` -------------------------------- ### Plot independent factor model results Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/examples/Multivariate_Example.ipynb Creates a two-panel figure: the top shows raw data with original changepoints, the bottom plots the changepoint probability from Pcp_ifm.exp().sum(0) for the independent factor model. The legend labels the model as 'Independent Factor Model'. ```python fig, ax = plt.subplots(2, figsize=[18, 8]) for p in changes: ax[0].plot([p, p], [float(data.min()), float(data.max())], "r") for d in range(2): ax[0].plot(data[:, d]) plt.legend(["Raw data with Original Changepoints"]) ax[1].plot(Pcp_ifm.exp().sum(0)) plt.legend(["Independent Factor Model"]) plt.show() ``` -------------------------------- ### Define prior function for offline changepoint detection Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/examples/Example_Code.ipynb Creates a constant prior function using const_prior with p = 1/(len(data)+1), assuming a uniform prior over sequence lengths. ```python from functools import partial from bayesian_changepoint_detection.priors import const_prior prior_function = partial(const_prior, p=1 / (len(data) + 1)) ``` -------------------------------- ### Define hazard function with constant_hazard Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/examples/Example_Code.ipynb Creates a hazard function using partial with a constant hazard rate of 250. This is used for online changepoint detection. ```python from bayesian_changepoint_detection.hazard_functions import constant_hazard hazard_function = partial(constant_hazard, 250) ``` -------------------------------- ### Detect changepoints with independent features model Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/examples/Multivariate_Example.ipynb Runs offline changepoint detection using IndependentFeaturesLikelihood and a constant prior with p=1/(len(data)+1). Returns Q_ifm, P_ifm, and Pcp_ifm; the latter is used to plot the changepoint probability. ```python from functools import partial from bayesian_changepoint_detection.bayesian_models import offline_changepoint_detection from bayesian_changepoint_detection.offline_likelihoods import ( IndependentFeaturesLikelihood, ) from bayesian_changepoint_detection.priors import const_prior Q_ifm, P_ifm, Pcp_ifm = offline_changepoint_detection( data, partial(const_prior, p=1 / (len(data) + 1)), IndependentFeaturesLikelihood(), ) ``` -------------------------------- ### compute_run_length_posterior(data, hazard, likelihood) Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Computes only the run-length posterior `R` for code that only needs the posterior. Useful for custom downstream analysis. ```APIDOC ## compute_run_length_posterior(data, hazard, likelihood) ### Description Computes only the run-length posterior `R` for code that only needs the posterior. Useful for custom downstream analysis. ### Parameters - **data** (tensor) - Required - Input data, shape `[T]` or `[T, d]`. - **hazard** (callable) - Required - Hazard function. - **likelihood** (object) - Required - Likelihood model. ### Returns - **R** (tensor) - Run-length posterior, shape `[T+1, T+1]`. ``` -------------------------------- ### offline_likelihoods.StudentT, MultivariateT, IndependentFeaturesLikelihood, FullCovarianceLikelihood Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Offline segment marginal likelihoods for various models. Used with the offline detector. ```APIDOC ## offline_likelihoods.StudentT, MultivariateT, IndependentFeaturesLikelihood, FullCovarianceLikelihood ### Description Offline segment marginal likelihoods for various models. Used with the offline detector. ### Parameters - **dims** (int) - Required for MultivariateT - Dimensionality of data. ### Returns - **likelihood** (object) - Likelihood instance. ``` -------------------------------- ### online_likelihoods.NormalKnownVariance, offline_likelihoods.NormalKnownVariance Source: https://github.com/hildensia/bayesian_changepoint_detection/blob/master/README.md Mean changes with known noise variance: Normal-Normal for online, Normal predictive for offline. Used for mean shift detection. ```APIDOC ## online_likelihoods.NormalKnownVariance, offline_likelihoods.NormalKnownVariance ### Description Mean changes with known noise variance: Normal-Normal for online, Normal predictive for offline. Used for mean shift detection. ### Parameters - **variance** (float) - Required - Known noise variance. ### Returns - **likelihood** (object) - Likelihood instance. ```