| Title: | Comprehensive Regime Change Detection in Time Series |
|---|---|
| Description: | A unified framework for detecting regime changes (changepoints) in time series data. Implements both frequentist methods including Cumulative Sum (CUSUM, Page (1954) <doi:10.1093/biomet/41.1-2.100>), Pruned Exact Linear Time (PELT, Killick, Fearnhead, and Eckley (2012) <doi:10.1080/01621459.2012.737745>), Binary Segmentation, and Wild Binary Segmentation, as well as Bayesian methods such as Bayesian Online Changepoint Detection (BOCPD, Adams and MacKay (2007) <doi:10.48550/arXiv.0710.3742> and Shiryaev-Roberts. Supports offline analysis for retrospective detection and online monitoring for real-time surveillance. Provides rigorous uncertainty quantification through confidence intervals and posterior distributions. Handles univariate and multivariate series with detection of changes in mean, variance, trend, and distributional properties. |
| Authors: | José Mauricio Gómez Julián [aut, cre]
|
| Maintainer: | José Mauricio Gómez Julián <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.1.1 |
| Built: | 2026-10-06 09:09:49 UTC |
| Source: | https://github.com/IsadoreNabi/RegimeChange |
A unified framework for detecting regime changes (changepoints) in time series data. Implements both frequentist methods including Cumulative Sum (CUSUM, Page (1954) doi:10.1093/biomet/41.1-2.100), Pruned Exact Linear Time (PELT, Killick, Fearnhead, and Eckley (2012) doi:10.1080/01621459.2012.737745), Binary Segmentation, and Wild Binary Segmentation, as well as Bayesian methods such as Bayesian Online Changepoint Detection (BOCPD, Adams and MacKay (2007) https://arxiv.org/abs/0710.3742) and Shiryaev-Roberts. Supports offline analysis for retrospective detection and online monitoring for real-time surveillance. Provides rigorous uncertainty quantification through confidence intervals and posterior distributions. Handles univariate and multivariate series with detection of changes in mean, variance, trend, and distributional properties.
Maintainer: José Mauricio Gómez Julián [email protected] (ORCID)
Useful links:
Report bugs at https://github.com/IsadoreNabi/RegimeChange/issues
Rand Index corrected for chance agreement.
adjusted_rand_index(detected, true_cp, n)adjusted_rand_index(detected, true_cp, n)
detected |
Vector of detected changepoint locations |
true_cp |
Vector of true changepoint locations |
n |
Total number of observations |
Adjusted Rand Index (can be negative, 1 is perfect)
Detects changepoints by identifying regions where reconstruction error is anomalously high, indicating the model (trained on normal patterns) fails to reconstruct the data.
autoencoder_detect( data, window_size = 50, latent_dim = 10, hidden_dims = c(32, 16), epochs = 100, batch_size = 32, threshold = NULL, contamination = 0.1, variational = FALSE, verbose = FALSE )autoencoder_detect( data, window_size = 50, latent_dim = 10, hidden_dims = c(32, 16), epochs = 100, batch_size = 32, threshold = NULL, contamination = 0.1, variational = FALSE, verbose = FALSE )
data |
Numeric vector of time series data |
window_size |
Size of sliding window (default: 50) |
latent_dim |
Dimension of latent space (default: 10) |
|
Hidden layer dimensions (default: c(32, 16)) |
|
epochs |
Training epochs (default: 100) |
batch_size |
Batch size (default: 32) |
threshold |
Threshold for anomaly detection. NULL for automatic selection using 3-sigma rule. |
contamination |
Expected proportion of anomalies for threshold selection (default: 0.1) |
variational |
Use Variational Autoencoder (default: FALSE) |
verbose |
Show training progress (default: FALSE) |
List with:
changepoints |
Detected changepoint locations |
reconstruction_error |
Per-window reconstruction error |
threshold |
Threshold used for detection |
model |
Trained Keras model |
## Not run: data <- c(rnorm(100), rnorm(100, mean = 3), rnorm(100)) result <- autoencoder_detect(data, window_size = 30) plot(result$reconstruction_error, type = "l") abline(v = result$changepoints, col = "red") ## End(Not run)## Not run: data <- c(rnorm(100), rnorm(100, mean = 3), rnorm(100)) result <- autoencoder_detect(data, window_size = 30) plot(result$reconstruction_error, type = "l") abline(v = result$changepoints, col = "red") ## End(Not run)
Compare execution time between Julia and R implementations.
benchmark_backends(data, method = "pelt", n_reps = 10, ...)benchmark_backends(data, method = "pelt", n_reps = 10, ...)
data |
Test data. |
method |
Method to benchmark. |
n_reps |
Number of repetitions. |
... |
Additional arguments for the method. |
Data frame with timing results (invisibly).
data <- c(rnorm(500), rnorm(500, 3)) benchmark_backends(data, method = "pelt", penalty = log(1000))data <- c(rnorm(500), rnorm(500, 3)) benchmark_backends(data, method = "pelt", penalty = log(1000))
Recursive binary segmentation for changepoint detection. Greedy algorithm that recursively splits at the best changepoint.
binary_segmentation( data, type = "both", penalty = "BIC", min_segment = 2, n_changepoints = "multiple", threshold = NULL, ... )binary_segmentation( data, type = "both", penalty = "BIC", min_segment = 2, n_changepoints = "multiple", threshold = NULL, ... )
data |
Numeric vector or matrix |
type |
Type of change to detect |
penalty |
Penalty for adding changepoints |
min_segment |
Minimum segment length |
n_changepoints |
Maximum number of changepoints to detect |
threshold |
Significance threshold |
... |
Additional arguments |
List with changepoints
data <- c(rnorm(100), rnorm(100, mean = 2)) result <- binary_segmentation(data)data <- c(rnorm(100), rnorm(100, mean = 2)) result <- binary_segmentation(data)
Implements the BOCPD algorithm of Adams and MacKay (2007). Maintains a posterior distribution over the run length (time since last changepoint) and updates it online as new observations arrive.
bocpd( data, type = "both", prior = NULL, hazard = NULL, threshold = 0.3, truncate_run_length = NULL, ... )bocpd( data, type = "both", prior = NULL, hazard = NULL, threshold = 0.3, truncate_run_length = NULL, ... )
data |
Numeric vector or matrix |
type |
Type of change to detect (currently supports "both") |
prior |
Prior specification (from normal_gamma(), normal_known_var(), etc.) |
hazard |
Hazard prior (from geometric_hazard(), etc.) or numeric hazard rate |
threshold |
Probability threshold for declaring a changepoint |
truncate_run_length |
Maximum run length to track (for efficiency) |
... |
Additional arguments |
List containing:
changepoints: Detected changepoint locations
posterior: Matrix of run length posteriors over time
prob_change: Probability of changepoint at each time
map_run_length: Maximum a posteriori run length at each time
Adams, R. P. and MacKay, D. J. C. (2007). Bayesian Online Changepoint Detection. arXiv:0710.3742
data <- c(rnorm(100, mean = 0), rnorm(100, mean = 3)) result <- bocpd(data) result <- bocpd(data, prior = normal_gamma(mu0 = 0, kappa0 = 1, alpha0 = 1, beta0 = 1)) result <- bocpd(data, hazard = 0.01)data <- c(rnorm(100, mean = 0), rnorm(100, mean = 3)) result <- bocpd(data) result <- bocpd(data, prior = normal_gamma(mu0 = 0, kappa0 = 1, alpha0 = 1, beta0 = 1)) result <- bocpd(data, hazard = 0.01)
Runs multiple detection methods on the same data and compares results.
compare_methods( data, methods = c("pelt", "binseg", "wbs", "bocpd"), true_changepoints = NULL, tolerance = 5, ... )compare_methods( data, methods = c("pelt", "binseg", "wbs", "bocpd"), true_changepoints = NULL, tolerance = 5, ... )
data |
Numeric vector or matrix |
methods |
Character vector of method names |
true_changepoints |
Vector of true changepoints (for evaluation) |
tolerance |
Tolerance for evaluation metrics |
... |
Additional arguments passed to detect_regimes |
Object of class "regime_comparison"
true_cp <- c(50, 100) data <- c(rnorm(50), rnorm(50, mean = 2), rnorm(50)) comparison <- compare_methods( data, methods = c("pelt", "binseg"), true_changepoints = true_cp )true_cp <- c(50, 100) data <- c(rnorm(50), rnorm(50, mean = 2), rnorm(50)) comparison <- compare_methods( data, methods = c("pelt", "binseg"), true_changepoints = true_cp )
Constant Hazard Prior (Alias for Geometric)
constant_hazard(lambda = 0.01)constant_hazard(lambda = 0.01)
lambda |
Hazard rate (probability of changepoint at each step). Should be between 0 and 1. Smaller values expect fewer changepoints. |
An object of class "hazard_prior"
Measures how well detected segments cover true segments using IoU.
covering_metric(detected, true_cp, n)covering_metric(detected, true_cp, n)
detected |
Vector of detected changepoint locations |
true_cp |
Vector of true changepoint locations |
n |
Total number of observations |
Covering metric (0 to 1)
Uses self-supervised contrastive learning to detect changepoints by identifying where the learned representations change significantly.
cpc_detect( data, window_size = 64, encoding_dim = 32, n_negative = 10, prediction_steps = 5, epochs = 100, threshold = NULL, verbose = FALSE )cpc_detect( data, window_size = 64, encoding_dim = 32, n_negative = 10, prediction_steps = 5, epochs = 100, threshold = NULL, verbose = FALSE )
data |
Numeric vector |
window_size |
Window size (default: 64) |
encoding_dim |
Encoding dimension (default: 32) |
n_negative |
Number of negative samples (default: 10) |
prediction_steps |
Future steps to predict (default: 5) |
epochs |
Training epochs (default: 100) |
threshold |
Detection threshold for representation distance |
verbose |
Show progress |
List with changepoints and learned encodings
Oord, A. v. d., Li, Y., and Vinyals, O. (2018). Representation Learning with Contrastive Predictive Coding
Efficiently computes optimal segmentations for a range of penalty values, useful for model selection.
crops_detect( data, penalty_range = c(0.1, 100), method = "pelt", min_segment = 2 )crops_detect( data, penalty_range = c(0.1, 100), method = "pelt", min_segment = 2 )
data |
Numeric vector |
penalty_range |
Vector of length 2: c(min_penalty, max_penalty) |
method |
Segmentation method ("pelt" or "fpop") |
min_segment |
Minimum segment length |
List with:
penalties |
Penalty values tested |
n_changepoints |
Number of changepoints for each penalty |
changepoints |
List of changepoint vectors |
costs |
Optimal costs |
Haynes, K., Eckley, I. A., and Fearnhead, P. (2017). Computationally efficient changepoint detection for a range of penalties. Journal of Computational and Graphical Statistics, 26(1), 134-143.
Detects changepoints using the Cumulative Sum (CUSUM) statistic. Foundational method for detecting changes in mean.
cusum( data, type = "mean", threshold = 4, mode = "offline", mu0 = NULL, sigma = NULL, ... )cusum( data, type = "mean", threshold = 4, mode = "offline", mu0 = NULL, sigma = NULL, ... )
data |
Numeric vector |
type |
Type of change ("mean", "variance", "both") |
threshold |
Detection threshold (alarm when statistic exceeds this) |
mode |
"offline" for retrospective or "online" for sequential |
mu0 |
Target mean under null hypothesis (for online mode) |
sigma |
Known standard deviation (if NULL, estimated from data) |
... |
Additional arguments |
List with changepoints and statistics
data <- c(rnorm(50), rnorm(50, mean = 2)) result <- cusum(data)data <- c(rnorm(50), rnorm(50, mean = 2)) result <- cusum(data)
Pruned Exact Linear Time (PELT) algorithm for optimal changepoint detection with enhancements for autocorrelated data and numerical stability.
detect_pelt( data, type = "both", penalty = "MBIC", min_segment = 2, robust = FALSE, correct_ar = FALSE, merge_close = NULL, ... )detect_pelt( data, type = "both", penalty = "MBIC", min_segment = 2, robust = FALSE, correct_ar = FALSE, merge_close = NULL, ... )
data |
Numeric vector or matrix. For matrices, rows are observations. |
type |
Type of change to detect: |
penalty |
Penalty type ( |
min_segment |
Minimum segment length (default: 2). |
robust |
Logical or character. FALSE for standard, TRUE for moderate robustness, or one of "mild", "moderate", "aggressive", "auto" for specific levels. |
correct_ar |
Logical. Apply pre-whitening for autocorrelated data. Default: FALSE. |
merge_close |
Integer or NULL. Merge changepoints within this distance. Default: NULL. |
... |
Additional arguments (currently unused). |
This implementation includes enhancements over standard PELT:
Pre-whitening for autocorrelated data: When correct_ar = TRUE,
the function estimates the AR(1) coefficient and transforms the data via
before applying PELT.
Configurable robustness: The robust parameter accepts:
FALSE: Standard MLE-based estimation
TRUE or "moderate": 10\
"mild": 5\
"aggressive": 15\
"auto": Automatically select based on data characteristics
A list with components:
Integer vector of detected changepoint locations
Number of changepoints detected
Final cost value
Estimated AR(1) coefficient (if correct_ar = TRUE)
Logical indicating if pre-whitening was applied
Logical indicating if robust estimation was used
Character indicating robustness level used
Reserved for future use
Killick, R., Fearnhead, P., and Eckley, I. A. (2012). Optimal detection of changepoints with a linear computational cost. JASA, 107(500), 1590-1598.
data <- c(rnorm(100, 0), rnorm(100, 3)) result <- detect_pelt(data, type = "mean") data_contaminated <- c(rnorm(100, 0), rnorm(100, 3)) data_contaminated[sample(200, 10)] <- rnorm(10, 0, 10) result_robust <- detect_pelt(data_contaminated, robust = TRUE) result_auto <- detect_pelt(data_contaminated, robust = "auto")data <- c(rnorm(100, 0), rnorm(100, 3)) result <- detect_pelt(data, type = "mean") data_contaminated <- c(rnorm(100, 0), rnorm(100, 3)) data_contaminated[sample(200, 10)] <- rnorm(10, 0, 10) result_robust <- detect_pelt(data_contaminated, robust = TRUE) result_auto <- detect_pelt(data_contaminated, robust = "auto")
Main function for detecting regime changes (changepoints) in time series data. Supports multiple detection methods, both frequentist and Bayesian, and can operate in offline (retrospective) or online (sequential) modes.
detect_regimes( data, method = c("pelt", "bocpd", "cusum", "binseg", "wbs", "shiryaev", "ensemble"), type = c("both", "mean", "variance", "trend", "distribution"), mode = c("offline", "online"), n_changepoints = "multiple", penalty = "BIC", min_segment = 2, prior = NULL, hazard = NULL, threshold = NULL, uncertainty = TRUE, bootstrap_reps = 200, ... )detect_regimes( data, method = c("pelt", "bocpd", "cusum", "binseg", "wbs", "shiryaev", "ensemble"), type = c("both", "mean", "variance", "trend", "distribution"), mode = c("offline", "online"), n_changepoints = "multiple", penalty = "BIC", min_segment = 2, prior = NULL, hazard = NULL, threshold = NULL, uncertainty = TRUE, bootstrap_reps = 200, ... )
data |
Numeric vector, time series (ts object), or matrix for multivariate data. For matrices, rows are observations and columns are variables. |
method |
Detection method. One of:
|
type |
Type of change to detect:
|
mode |
Operation mode:
|
n_changepoints |
Expected number of changepoints:
|
penalty |
Penalty for model complexity (offline methods):
|
min_segment |
Minimum segment length (number of observations) |
prior |
Prior specification for Bayesian methods (from prior functions) |
hazard |
Hazard prior for changepoint occurrence (Bayesian methods) |
threshold |
Detection threshold (for online/CUSUM methods) |
uncertainty |
Logical; if TRUE, compute confidence intervals |
bootstrap_reps |
Number of bootstrap replicates for uncertainty (if uncertainty = TRUE) |
... |
Additional arguments passed to specific methods |
An object of class "regime_result" containing:
changepoints: Vector of detected changepoint locations
n_changepoints: Number of changepoints detected
segments: List of segment information (start, end, parameters)
confidence_intervals: Confidence intervals for changepoint locations
existence_probability: Probability that each changepoint exists
posterior: Posterior distribution (Bayesian methods)
information_criterion: BIC/AIC values
method: Method used
call: The function call
set.seed(123) data <- c(rnorm(100, mean = 0), rnorm(100, mean = 3)) result <- detect_regimes(data) print(result) plot(result) result <- detect_regimes(data, method = "bocpd", prior = normal_gamma()) result <- detect_regimes(data, method = "cusum", mode = "online", threshold = 5)set.seed(123) data <- c(rnorm(100, mean = 0), rnorm(100, mean = 3)) result <- detect_regimes(data) print(result) plot(result) result <- detect_regimes(data, method = "bocpd", prior = normal_gamma()) result <- detect_regimes(data, method = "cusum", mode = "online", threshold = 5)
A simulated time series representing an economic indicator with regime changes corresponding to expansion, recession, recovery, and stable growth periods.
economic_cycleseconomic_cycles
A time series object of length 500 with attributes:
Vector of true changepoint locations: c(120, 250, 380)
Description of the dataset
Names of the regimes: Expansion, Recession, Recovery, Stable Growth
The data simulates monthly economic data from 2000-2041 with four distinct regimes:
Regime 1 (1-120): Expansion - positive trend, low volatility
Regime 2 (121-250): Recession - negative trend, high volatility
Regime 3 (251-380): Recovery - positive trend, medium volatility
Regime 4 (381-500): Stable Growth - low trend, low volatility
Simulated data for package examples
data(economic_cycles) result <- detect_regimes(economic_cycles, method = "pelt") plot(result) # Compare with true changepoints true_cps <- attr(economic_cycles, "true_changepoints") evaluate(result, true_changepoints = true_cps)data(economic_cycles) result <- detect_regimes(economic_cycles, method = "pelt") plot(result) # Compare with true changepoints true_cps <- attr(economic_cycles, "true_changepoints") evaluate(result, true_changepoints = true_cps)
Nonparametric changepoint detection using energy statistics. Can detect changes in any aspect of the distribution.
edivisive_detect(data, min_segment = 5, alpha = 0.05, n_perm = 199)edivisive_detect(data, min_segment = 5, alpha = 0.05, n_perm = 199)
data |
Numeric vector or matrix |
min_segment |
Minimum segment length |
alpha |
Significance level for permutation tests |
n_perm |
Number of permutations |
List with changepoints and test statistics
Matteson, D. S., and James, N. A. (2014). A nonparametric approach for multiple change point analysis of multivariate data. Journal of the American Statistical Association, 109(505), 334-345.
Combines multiple deep learning methods for robust detection.
ensemble_dl_detect( data, methods = c("autoencoder", "tcn", "transformer"), min_agreement = 2, ... )ensemble_dl_detect( data, methods = c("autoencoder", "tcn", "transformer"), min_agreement = 2, ... )
data |
Numeric vector |
methods |
Vector of methods to use (default: all) |
min_agreement |
Minimum number of methods that must agree |
... |
Additional arguments passed to individual methods |
List with consensus changepoints and individual results
Comprehensive evaluation of detection results against known ground truth. Computes multiple metrics for localization, segmentation, and detection.
evaluate(result, true_changepoints, n = NULL, tolerance = 5)evaluate(result, true_changepoints, n = NULL, tolerance = 5)
result |
A regime_result object or vector of changepoint locations |
true_changepoints |
Vector of true changepoint locations |
n |
Total number of observations (required if result is a vector) |
tolerance |
Tolerance window for matching changepoints (for F1 score) |
A list of class "regime_evaluation" containing all metrics
true_cp <- c(50, 100) data <- c(rnorm(50), rnorm(50, mean = 2), rnorm(50)) result <- detect_regimes(data) evaluation <- evaluate(result, true_cp) print(evaluation)true_cp <- c(50, 100) data <- c(rnorm(50), rnorm(50, mean = 2), rnorm(50)) result <- detect_regimes(data) evaluation <- evaluate(result, true_cp) print(evaluation)
Functions for evaluating changepoint detection results against ground truth. Includes metrics for localization accuracy, segmentation quality, and detection performance.
Harmonic mean of precision and recall.
f1_score(detected, true_cp, tolerance = 5)f1_score(detected, true_cp, tolerance = 5)
detected |
Vector of detected changepoint locations |
true_cp |
Vector of true changepoint locations |
tolerance |
Maximum distance for a match |
F1 score (0 to 1)
f1_score(c(48, 102, 150), c(50, 100), tolerance = 5)f1_score(c(48, 102, 150), c(50, 100), tolerance = 5)
More efficient than PELT for certain data types by maintaining piecewise quadratic cost functions instead of just minimum values. Achieves O(n) complexity in practice.
fpop_detect(data, penalty = "bic", min_segment = 2, cost_type = "mean")fpop_detect(data, penalty = "bic", min_segment = 2, cost_type = "mean")
data |
Numeric vector of observations |
penalty |
Penalty for adding a changepoint. Can be:
|
min_segment |
Minimum segment length (default: 2) |
cost_type |
Type of cost function:
|
List with:
changepoints |
Vector of changepoint locations |
cost |
Final optimal cost |
n_candidates |
Average candidates per time point (efficiency metric) |
Maidstone, R., Hocking, T., Rigaill, G., and Fearnhead, P. (2017). On optimal multiple changepoint algorithms for large data. Statistics and Computing, 27(2), 519-533.
data <- c(rnorm(100, 0), rnorm(100, 3), rnorm(100, 1)) result <- fpop_detect(data, penalty = "bic") print(result$changepoints)data <- c(rnorm(100, 0), rnorm(100, 3), rnorm(100, 1)) result <- fpop_detect(data, penalty = "bic") print(result$changepoints)
Creates a geometric (constant hazard) prior for the changepoint process. This implies that the probability of a changepoint at each time step is constant and independent.
geometric_hazard(lambda = 0.01)geometric_hazard(lambda = 0.01)
lambda |
Hazard rate (probability of changepoint at each step). Should be between 0 and 1. Smaller values expect fewer changepoints. |
Under a geometric hazard, the expected run length (time between changepoints) is 1/lambda. For example, lambda = 0.01 expects a changepoint every 100 observations on average.
An object of class "hazard_prior"
hazard <- geometric_hazard(lambda = 0.01) hazard <- geometric_hazard(lambda = 0.1)hazard <- geometric_hazard(lambda = 0.01) hazard <- geometric_hazard(lambda = 0.1)
Computes the Hausdorff distance between detected and true changepoints. The Hausdorff distance is the maximum distance from a point in one set to the nearest point in the other set.
hausdorff_distance(detected, true_cp)hausdorff_distance(detected, true_cp)
detected |
Vector of detected changepoint locations |
true_cp |
Vector of true changepoint locations |
Hausdorff distance (non-negative number)
hausdorff_distance(c(48, 102), c(50, 100))hausdorff_distance(c(48, 102), c(50, 100))
A simulated time series from a manufacturing process with abrupt changes representing process shifts and equipment states.
industrial_sensorindustrial_sensor
A time series object of length 600 with attributes:
Vector of true changepoint locations: c(150, 300, 450)
Description of the dataset
Names of the regimes: Normal, Drift, Malfunction, Corrected
The data simulates per-minute sensor measurements with four distinct regimes:
Regime 1 (1-150): Normal operation - mean=50, sd=2
Regime 2 (151-300): Process drift - mean=55, sd=2.5
Regime 3 (301-450): Equipment malfunction - mean=45, sd=5
Regime 4 (451-600): Corrected operation - mean=50, sd=1.5
The data includes autocorrelation typical of industrial processes.
Simulated data for package examples
data(industrial_sensor) result <- detect_regimes(industrial_sensor, method = "bocpd") plot(result, type = "segments")data(industrial_sensor) result <- detect_regimes(industrial_sensor, method = "bocpd") plot(result, type = "segments")
Explicitly initialize the Julia backend for improved performance. This loads the RegimeChangeJulia module and makes Julia functions available.
init_julia(force = FALSE, num_threads = NULL)init_julia(force = FALSE, num_threads = NULL)
force |
Logical. Force reinitialization even if already initialized. Default is FALSE. |
num_threads |
Integer or NULL. Number of Julia threads to use. Default is NULL (auto-detect). |
Logical indicating success (invisibly).
## Not run: init_julia() julia_available() result <- detect_regimes(data, method = "pelt") ## End(Not run)## Not run: init_julia() julia_available() result <- detect_regimes(data, method = "pelt") ## End(Not run)
Creates an Inverse-Gamma prior for detecting changes in variance with known mean.
inverse_gamma_var(alpha0 = 1, beta0 = 1, known_mean = 0)inverse_gamma_var(alpha0 = 1, beta0 = 1, known_mean = 0)
alpha0 |
Shape parameter |
beta0 |
Scale parameter |
known_mean |
Known mean of the observations |
An object of class "regime_prior"
Check if Julia Backend is Available
julia_available()julia_available()
Logical indicating if Julia is available and initialized.
Get Julia Backend Status
julia_status()julia_status()
List with Julia status information.
Detects changepoints using Maximum Mean Discrepancy (MMD) in a Reproducing Kernel Hilbert Space. This nonparametric approach can detect changes in any aspect of the distribution.
kernel_cpd_detect( data, penalty = "bic", kernel = "rbf", bandwidth = 0, min_segment = 5 )kernel_cpd_detect( data, penalty = "bic", kernel = "rbf", bandwidth = 0, min_segment = 5 )
data |
Numeric vector or matrix (rows = observations) |
penalty |
Penalty for changepoints (default: "bic") |
kernel |
Kernel function to use:
|
bandwidth |
Kernel bandwidth (0 = automatic median heuristic) |
min_segment |
Minimum segment length |
List with changepoints and kernel statistics
Arlot, S., Celisse, A., and Harchaoui, Z. (2019). A kernel multiple change-point algorithm via model selection. Journal of Machine Learning Research, 20(162), 1-56.
Computes mean absolute error between matched changepoints. Unmatched changepoints are ignored.
mean_absolute_error(detected, true_cp)mean_absolute_error(detected, true_cp)
detected |
Vector of detected changepoint locations |
true_cp |
Vector of true changepoint locations |
Mean absolute error
Creates a negative binomial hazard prior, which allows for more flexibility in the distribution of run lengths.
negbin_hazard(r = 1, p = 0.01)negbin_hazard(r = 1, p = 0.01)
r |
Number of successes (shape parameter) |
p |
Probability of success |
An object of class "hazard_prior"
Creates a Normal-Gamma prior specification for data with unknown mean and variance. This is conjugate for normal observations.
normal_gamma(mu0 = 0, kappa0 = 1, alpha0 = 1, beta0 = 1)normal_gamma(mu0 = 0, kappa0 = 1, alpha0 = 1, beta0 = 1)
mu0 |
Prior mean for the mean parameter |
kappa0 |
Prior pseudo-observations for the mean (strength of prior) |
alpha0 |
Shape parameter for the precision (inverse variance) |
beta0 |
Rate parameter for the precision |
The Normal-Gamma prior places a joint distribution on (mu, tau) where tau = 1/sigma^2:
tau ~ Gamma(alpha0, beta0) mu | tau ~ Normal(mu0, 1/(kappa0 * tau))
The prior mean of mu is mu0, and the prior mean of sigma^2 is beta0/(alpha0-1) for alpha0 > 1.
An object of class "regime_prior"
prior <- normal_gamma() prior <- normal_gamma(mu0 = 0, kappa0 = 10, alpha0 = 3, beta0 = 2)prior <- normal_gamma() prior <- normal_gamma(mu0 = 0, kappa0 = 10, alpha0 = 3, beta0 = 2)
Creates a Normal prior specification for data with unknown mean but known variance.
normal_known_var(mu0 = 0, sigma0 = 1, known_var = 1)normal_known_var(mu0 = 0, sigma0 = 1, known_var = 1)
mu0 |
Prior mean |
sigma0 |
Prior standard deviation for the mean |
known_var |
Known variance of the observations |
An object of class "regime_prior"
prior <- normal_known_var(mu0 = 0, sigma0 = 1, known_var = 1)prior <- normal_known_var(mu0 = 0, sigma0 = 1, known_var = 1)
Creates a Normal-Wishart prior for multivariate normal data with unknown mean vector and covariance matrix.
normal_wishart(mu0, kappa0 = 1, nu0 = NULL, Psi0 = NULL)normal_wishart(mu0, kappa0 = 1, nu0 = NULL, Psi0 = NULL)
mu0 |
Prior mean vector (d-dimensional) |
kappa0 |
Prior pseudo-observations for the mean |
nu0 |
Degrees of freedom for the Wishart (must be >= d) |
Psi0 |
Scale matrix for the Wishart (d x d positive definite) |
An object of class "regime_prior"
prior <- normal_wishart( mu0 = c(0, 0), kappa0 = 1, nu0 = 3, Psi0 = diag(2) )prior <- normal_wishart( mu0 = c(0, 0), kappa0 = 1, nu0 = 3, Psi0 = diag(2) )
Detects changepoints by finding the narrowest intervals that contain significant changes, providing excellent localization.
not_detect( data, threshold = NULL, min_segment = 5, contrast_type = "pcwsConst" )not_detect( data, threshold = NULL, min_segment = 5, contrast_type = "pcwsConst" )
data |
Numeric vector |
threshold |
Detection threshold (NULL for automatic) |
min_segment |
Minimum segment length |
contrast_type |
Type of contrast function |
List with changepoints and interval information
Baranowski, R., Chen, Y., and Fryzlewicz, P. (2019). Narrowest-over- threshold detection of multiple change points and change-point-like features. Journal of the Royal Statistical Society Series B, 81(3), 649-672.
Wrapper for detect_pelt for compatibility.
pelt( data, type = "both", penalty = "MBIC", min_segment = 2, robust = FALSE, correct_ar = FALSE, merge_close = NULL, ... )pelt( data, type = "both", penalty = "MBIC", min_segment = 2, robust = FALSE, correct_ar = FALSE, merge_close = NULL, ... )
data |
Numeric vector or matrix. For matrices, rows are observations. |
type |
Type of change to detect: |
penalty |
Penalty type ( |
min_segment |
Minimum segment length (default: 2). |
robust |
Logical or character. FALSE for standard, TRUE for moderate robustness, or one of "mild", "moderate", "aggressive", "auto" for specific levels. |
correct_ar |
Logical. Apply pre-whitening for autocorrelated data. Default: FALSE. |
merge_close |
Integer or NULL. Merge changepoints within this distance. Default: NULL. |
... |
Additional arguments (currently unused). |
List with changepoints and diagnostics
Creates a faceted plot comparing results from different methods.
plot_compare(..., names = NULL)plot_compare(..., names = NULL)
... |
Multiple regime_result objects |
names |
Names for each result |
A ggplot object
Creates an interactive version of the changepoint plot using plotly.
plot_interactive(result, ...)plot_interactive(result, ...)
result |
A regime_result object |
... |
Additional arguments |
A plotly object
Creates a comprehensive multi-panel visualization of detection results.
plot_summary(result, ...)plot_summary(result, ...)
result |
A regime_result object |
... |
Additional arguments |
A combined ggplot object
Create visualizations of changepoint detection results.
## S3 method for class 'regime_result' plot( x, type = c("data", "segments", "posterior", "diagnostic", "runlength"), show_ci = TRUE, show_segments = TRUE, title = NULL, ... )## S3 method for class 'regime_result' plot( x, type = c("data", "segments", "posterior", "diagnostic", "runlength"), show_ci = TRUE, show_segments = TRUE, title = NULL, ... )
x |
A regime_result object |
type |
Type of plot:
|
show_ci |
Show confidence intervals if available |
show_segments |
Color segments differently |
title |
Plot title |
... |
Additional arguments passed to ggplot |
A ggplot2 object
data <- c(rnorm(100), rnorm(100, mean = 2)) result <- detect_regimes(data) plot(result) plot(result, type = "segments")data <- c(rnorm(100), rnorm(100, mean = 2)) result <- detect_regimes(data) plot(result) plot(result, type = "segments")
Creates a Gamma prior specification for Poisson-distributed count data.
poisson_gamma(alpha0 = 1, beta0 = 1)poisson_gamma(alpha0 = 1, beta0 = 1)
alpha0 |
Shape parameter for the rate |
beta0 |
Rate parameter |
An object of class "regime_prior"
prior <- poisson_gamma(alpha0 = 1, beta0 = 1)prior <- poisson_gamma(alpha0 = 1, beta0 = 1)
Proportion of detected changepoints that are within tolerance of a true one.
precision_score(detected, true_cp, tolerance = 5)precision_score(detected, true_cp, tolerance = 5)
detected |
Vector of detected changepoint locations |
true_cp |
Vector of true changepoint locations |
tolerance |
Maximum distance for a match |
Precision (0 to 1)
Measures agreement between detected and true segmentations. Based on pairwise comparisons of whether points are in the same segment.
rand_index(detected, true_cp, n)rand_index(detected, true_cp, n)
detected |
Vector of detected changepoint locations |
true_cp |
Vector of true changepoint locations |
n |
Total number of observations |
Rand Index (0 to 1)
Proportion of true changepoints that are matched by a detection.
recall_score(detected, true_cp, tolerance = 5)recall_score(detected, true_cp, tolerance = 5)
detected |
Vector of detected changepoint locations |
true_cp |
Vector of true changepoint locations |
tolerance |
Maximum distance for a match |
Recall (0 to 1)
Creates a detector object for online (sequential) changepoint detection. The detector maintains state and can be updated incrementally as new observations arrive.
regime_detector( method = c("bocpd", "cusum", "shiryaev"), prior = NULL, hazard = NULL, threshold = NULL, ... )regime_detector( method = c("bocpd", "cusum", "shiryaev"), prior = NULL, hazard = NULL, threshold = NULL, ... )
method |
Detection method: "bocpd", "cusum", or "shiryaev" |
prior |
Prior specification for Bayesian methods |
hazard |
Hazard prior for changepoint occurrence |
threshold |
Detection threshold (probability or statistic value) |
... |
Additional method-specific parameters |
An object of class "regime_detector"
detector <- regime_detector(method = "bocpd", prior = normal_gamma(), threshold = 0.5) for (x in rnorm(100)) { detector <- update(detector, x) if (detector$last_result$alarm) { message("Change detected at observation ", detector$last_result$t) detector <- reset(detector) } }detector <- regime_detector(method = "bocpd", prior = normal_gamma(), threshold = 0.5) for (x in rnorm(100)) { detector <- update(detector, x) if (detector$last_result$alarm) { message("Change detected at observation ", detector$last_result$t) detector <- reset(detector) } }
Reset a detector to its initial state
reset(object, ...) ## S3 method for class 'regime_detector' reset(object, ...)reset(object, ...) ## S3 method for class 'regime_detector' reset(object, ...)
object |
A detector object (e.g., from BOCPD or Shiryaev-Roberts) |
... |
Additional arguments |
The reset detector object
reset(regime_detector): Reset method for regime_detector
RMSE for Changepoints
rmse_changepoints(detected, true_cp)rmse_changepoints(detected, true_cp)
detected |
Vector of detected changepoint locations |
true_cp |
Vector of true changepoint locations |
Root mean squared error
Implements the Shiryaev-Roberts procedure, which is asymptotically optimal for detecting changes with minimal detection delay.
shiryaev_roberts( data, type = "mean", prior = NULL, hazard = NULL, threshold = 100, mu0 = NULL, mu1 = NULL, sigma = NULL, ... )shiryaev_roberts( data, type = "mean", prior = NULL, hazard = NULL, threshold = 100, mu0 = NULL, mu1 = NULL, sigma = NULL, ... )
data |
Numeric vector |
type |
Type of change to detect |
prior |
Prior specification |
hazard |
Hazard prior |
threshold |
Detection threshold |
mu0 |
Pre-change mean (if known) |
mu1 |
Post-change mean (if known) |
sigma |
Known standard deviation (if applicable) |
... |
Additional arguments |
List with changepoints and statistics
Shiryaev, A. N. (1963). On Optimum Methods in Quickest Detection Problems. Theory of Probability and Its Applications.
data <- c(rnorm(100), rnorm(100, mean = 1)) result <- shiryaev_roberts(data)data <- c(rnorm(100), rnorm(100, mean = 1)) result <- shiryaev_roberts(data)
A collection of simulated datasets with known changepoints for benchmarking changepoint detection methods.
simulated_changepointssimulated_changepoints
A list with multiple scenarios:
Single mean change from 0 to 3
Single variance change from 1 to 9
Three mean changes
Gradual trend change (challenging)
Small mean change of 0.5 SD (challenging)
Three closely spaced changepoints (challenging)
Mean change with t-distributed noise
Bivariate mean and covariance change
Each scenario contains:
data: The time series data
true_changepoints: Vector of true changepoint locations
type: Type of change (mean, variance, etc.)
description: Description of the scenario
Simulated data for package benchmarking
data(simulated_changepoints) # Run benchmark on single mean scenario scenario <- simulated_changepoints$single_mean result <- detect_regimes(scenario$data, method = "pelt") evaluate(result, true_changepoints = scenario$true_changepoints) # Compare multiple methods comparison <- compare_methods( data = scenario$data, methods = c("pelt", "bocpd", "binseg"), true_changepoints = scenario$true_changepoints ) print(comparison)data(simulated_changepoints) # Run benchmark on single mean scenario scenario <- simulated_changepoints$single_mean result <- detect_regimes(scenario$data, method = "pelt") evaluate(result, true_changepoints = scenario$true_changepoints) # Compare multiple methods comparison <- compare_methods( data = scenario$data, methods = c("pelt", "bocpd", "binseg"), true_changepoints = scenario$true_changepoints ) print(comparison)
Detects changepoints in high-dimensional data using random sparse projections to reduce dimensionality while preserving changepoint structure.
sparse_projection_cpd( data, n_projections = 10, penalty = "bic", min_segment = 5, sparsity = 0.3 )sparse_projection_cpd( data, n_projections = 10, penalty = "bic", min_segment = 5, sparsity = 0.3 )
data |
Matrix with rows = observations, columns = dimensions |
n_projections |
Number of random projections (default: 10) |
penalty |
Penalty for changepoints |
min_segment |
Minimum segment length |
sparsity |
Sparsity level for projections (fraction of non-zeros) |
List with changepoints and projection information
Wang, D. and Bhattacharjee, M. (2021). High-dimensional changepoint estimation via sparse projection. arXiv preprint.
Uses Temporal Convolutional Networks with dilated causal convolutions for sequence-to-sequence changepoint prediction.
tcn_detect( data, true_changepoints = NULL, window_size = 64, n_filters = 64, kernel_size = 3, dilations = c(1, 2, 4, 8, 16), dropout = 0.2, epochs = 50, threshold = 0.5, verbose = FALSE )tcn_detect( data, true_changepoints = NULL, window_size = 64, n_filters = 64, kernel_size = 3, dilations = c(1, 2, 4, 8, 16), dropout = 0.2, epochs = 50, threshold = 0.5, verbose = FALSE )
data |
Numeric vector of time series data |
true_changepoints |
Optional vector of known changepoints for supervised training. If NULL, uses unsupervised approach. |
window_size |
Size of input window (default: 64) |
n_filters |
Number of convolutional filters (default: 64) |
kernel_size |
Kernel size for convolutions (default: 3) |
dilations |
Dilation rates (default: c(1, 2, 4, 8, 16)) |
dropout |
Dropout rate (default: 0.2) |
epochs |
Training epochs (default: 50) |
threshold |
Detection threshold (default: 0.5) |
verbose |
Show training progress (default: FALSE) |
List with changepoints, probabilities, and model
Bai, S., Kolter, J. Z., and Koltun, V. (2018). An Empirical Evaluation of Generic Convolutional and Recurrent Networks for Sequence Modeling
Implements a transformer architecture inspired by TCDformer for time series changepoint detection using self-attention mechanisms.
transformer_detect( data, true_changepoints = NULL, window_size = 128, d_model = 64, n_heads = 4, n_layers = 2, d_ff = 256, dropout = 0.1, epochs = 50, threshold = 0.5, verbose = FALSE )transformer_detect( data, true_changepoints = NULL, window_size = 128, d_model = 64, n_heads = 4, n_layers = 2, d_ff = 256, dropout = 0.1, epochs = 50, threshold = 0.5, verbose = FALSE )
data |
Numeric vector of time series data |
true_changepoints |
Optional vector of known changepoints |
window_size |
Input window size (default: 128) |
d_model |
Model dimension (default: 64) |
n_heads |
Number of attention heads (default: 4) |
n_layers |
Number of transformer layers (default: 2) |
d_ff |
Feed-forward dimension (default: 256) |
dropout |
Dropout rate (default: 0.1) |
epochs |
Training epochs (default: 50) |
threshold |
Detection threshold (default: 0.5) |
verbose |
Show progress (default: FALSE) |
List with changepoints, attention weights, and model
Wu, H., et al. (2023). TimesNet: Temporal 2D-Variation Modeling
Zhou, H., et al. (2021). Informer: Efficient Transformer for Long Sequence Time-Series Forecasting
Update Online Detector with New Observation
## S3 method for class 'regime_detector' update(object, x, ...)## S3 method for class 'regime_detector' update(object, x, ...)
object |
A regime_detector object |
x |
New observation (scalar or vector for multivariate) |
... |
Additional arguments |
The updated regime_detector object with results in $last_result
A simulated well-log porosity dataset with abrupt lithology changes typical of geological formations.
well_logwell_log
A numeric vector of length 1000 with attributes:
Vector of true changepoint locations: c(200, 350, 500, 700, 850)
Description of the dataset
Names of lithology units
The data simulates porosity measurements from a well log with six distinct lithological units:
Unit 1 (1-200): Sandstone - porosity ~15%
Unit 2 (201-350): Shale - porosity ~8%
Unit 3 (351-500): Limestone - porosity ~20%
Unit 4 (501-700): Sandstone - porosity ~12%
Unit 5 (701-850): Dense Shale - porosity ~5%
Unit 6 (851-1000): Sandstone - porosity ~18%
Simulated data based on typical well-log characteristics
data(well_log) result <- detect_regimes(well_log, method = "pelt", min_segment = 50) plot(result, type = "segments") # Compare with true lithology boundaries true_cps <- attr(well_log, "true_changepoints") evaluate(result, true_changepoints = true_cps)data(well_log) result <- detect_regimes(well_log, method = "pelt", min_segment = 50) plot(result, type = "segments") # Compare with true lithology boundaries true_cps <- attr(well_log, "true_changepoints") evaluate(result, true_changepoints = true_cps)
Detects multiple changepoints using the Wild Binary Segmentation algorithm. Uses random intervals to improve detection in long time series.
wild_binary_segmentation( data, type = "both", penalty = "BIC", min_segment = 2, n_changepoints = "multiple", M = 5000, threshold = NULL, ... )wild_binary_segmentation( data, type = "both", penalty = "BIC", min_segment = 2, n_changepoints = "multiple", M = 5000, threshold = NULL, ... )
data |
Numeric vector or matrix of time series data |
type |
Type of change to detect: "mean", "variance", or "both" |
penalty |
Penalty for model complexity: "BIC", "AIC", "MBIC", or numeric |
min_segment |
Minimum segment length |
n_changepoints |
Expected number of changepoints: "single", "multiple", or integer |
M |
Number of random intervals to draw |
threshold |
Detection threshold for CUSUM statistic. If NULL, automatically determined |
... |
Additional arguments |
A list with:
changepoints |
Vector of detected changepoint locations |
n_changepoints |
Number of changepoints detected |
information_criterion |
BIC value for the segmentation |
Fryzlewicz, P. (2014). Wild Binary Segmentation for multiple change-point detection. Annals of Statistics, 42(6), 2243-2281.
data <- c(rnorm(100), rnorm(100, mean = 2), rnorm(100)) result <- wild_binary_segmentation(data)data <- c(rnorm(100), rnorm(100, mean = 2), rnorm(100)) result <- wild_binary_segmentation(data)