| Type: | Package |
| Title: | Dynamic Shrinkage Process and Change Point Detection |
| Version: | 1.8.0 |
| Description: | Provides efficient Markov chain Monte Carlo (MCMC) algorithms for dynamic shrinkage processes, which extend global-local shrinkage priors to the time series setting by allowing shrinkage to depend on its own past. These priors yield locally adaptive estimates, useful for time series and regression functions with irregular features. The package includes full MCMC implementations for trend filtering using dynamic shrinkage on signal differences, producing locally constant or linear fits with adaptive credible bands. Also included are models with static shrinkage and normal-inverse-Gamma priors for comparison. Additional tools cover dynamic regression with time-varying coefficients and B-spline models with shrinkage on basis differences, allowing for flexible curve-fitting with unequally spaced data. Some support for heteroscedastic errors, outlier detection, and change point estimation. Methods in this package are described in Kowal et al. (2019) <doi:10.1111/rssb.12325>, Wu et al. (2024) <doi:10.1080/07350015.2024.2362269>, Schafer and Matteson (2024) <doi:10.1080/00401706.2024.2407316>, and Cho and Matteson (2026) <doi:10.1080/07350015.2025.2602846>. |
| License: | GPL (≥ 3) |
| Depends: | R (≥ 4.1.0) |
| Imports: | coda, fda, graphics, grDevices, Matrix, MCMCpack, methods, msm, pgdraw, Rcpp, RcppZiggurat, spam, progress, stats, stochvol, BayesLogit, truncdist, mgcv, purrr, rlang, lifecycle, glue |
| Suggests: | ggplot2, testthat (≥ 3.0.0) |
| LinkingTo: | Rcpp, RcppArmadillo, RcppEigen |
| Encoding: | UTF-8 |
| RoxygenNote: | 7.3.3 |
| Config/testthat/edition: | 3 |
| URL: | https://github.com/schafert/dsp |
| BugReports: | https://github.com/schafert/dsp/issues |
| NeedsCompilation: | yes |
| Packaged: | 2026-11-25 21:23:38 UTC; torynschafer |
| Author: | Daniel R. Kowal [aut, cph],
Haoxuan Wu [aut],
Toryn Schafer |
| Maintainer: | Toryn Schafer <toryn27@gmail.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-11-25 22:40:09 UTC |
dsp: Dynamic shrinkage process and change point detection
Description
Provides efficient Markov chain Monte Carlo (MCMC) algorithms for dynamic shrinkage processes, which extend global-local shrinkage priors to the time series setting by allowing shrinkage to depend on its own past. These priors yield locally adaptive estimates, useful for time series and regression functions with irregular features. The package includes full MCMC implementations for trend filtering using dynamic shrinkage on signal differences, producing locally constant or linear fits with adaptive credible bands. Also included are models with static shrinkage and normal-inverse-Gamma priors for comparison. Additional tools cover dynamic regression with time-varying coefficients and B-spline models with shrinkage on basis differences, allowing for flexible curve-fitting with unequally spaced data. Some support for heteroscedastic errors, outlier detection, and change point estimation. Methods in this package are described in Kowal et al. (2019) doi:10.1111/rssb.12325, Wu et al. (2024) doi:10.1080/07350015.2024.2362269, Schafer and Matteson (2024) doi:10.1080/00401706.2024.2407316, and Cho and Matteson (2026) doi:10.1080/07350015.2025.2602846.
Author(s)
Maintainer: Toryn Schafer toryn27@gmail.com (ORCID)
Authors:
Daniel R. Kowal daniel.kowal@rice.edu [copyright holder]
Haoxuan Wu hw399@cornell.edu
Jason B. Cho bc454@cornell.edu
David S. Matteson matteson@cornell.edu
See Also
Useful links:
Adaptive Bayesian changepoint with outliers
Description
Run the MCMC sampler for ABCO with a penalty on first (D = 1), or second (D = 2) differences of the conditional expectation. The penalty utilizes the dynamic horseshoe prior on the evolution errors. Sampling is accomplished with a (parameter-expanded) Gibbs sampler, mostly relying on a dynamic linear model representation.
Usage
abco(
y,
D = 1,
useAnom = TRUE,
obsSV = "const",
nsave = 1000,
nburn = 1000,
nskip = 4,
mcmc_params = list("mu", "omega", "ypred", "evol_sigma_t2", "gamma", "zeta",
"obs_sigma_t2", "zeta_sigma_t2", "dhs_phi", "dhs_mean", "h_smooth"),
verbose = TRUE,
D_asv = 1,
evol_error_asv = "HS",
computeDIC = TRUE,
nugget_asv = TRUE
)
Arguments
y |
the |
D |
degree of differencing (D = 1, or D = 2) |
useAnom |
logical; if TRUE, include an anomaly component in the observation equation |
obsSV |
Options for modeling the error variance. It must be one of the following:
|
nsave |
number of MCMC iterations to record |
nburn |
number of MCMC iterations to discard (burnin) |
nskip |
number of MCMC iterations to skip between saving iterations, i.e., save every (nskip + 1)th draw |
mcmc_params |
named list of parameters for which we store the MCMC output; must be one or more of:
|
verbose |
logical; should R report extra information on progress? |
D_asv |
integer; degree of differencing (0, 1, or 2) for the ASV model. Only used when |
evol_error_asv |
character; evolution error distribution for the ASV model. Must be one of the five options used in |
computeDIC |
logical; if TRUE (default), compute the deviance information criterion |
nugget_asv |
logical; if |
Value
A named list of the nsave MCMC samples for the parameters named in mcmc_params
Coerce a fitted dsp model to an mcmc object
Description
Flattens the posterior draws stored in a dsp object into a single
matrix of class mcmc, so that the diagnostic and
plotting functions in coda can be applied to the fitted model.
Usage
## S3 method for class 'dsp'
as.mcmc(x, pars, ...)
Arguments
x |
an object of class |
pars |
character vector of parameter names to retain; defaults to all
parameters returned by |
... |
Further arguments to be passed to specific methods |
Details
Each element of x$mcmc_output is stored with the posterior draws in
the first dimension, so that a scalar parameter is a vector of length
nsave and a time-varying parameter is an nsave by T
matrix or an nsave by T by J array. Every element is
flattened column by column and the results are bound into one matrix with
nsave rows. Columns are named by indexing the original parameter,
dropping the leading draw index. Column "mu[3]" therefore holds the
draws of the mean function at time 3, and column "beta[3, 2]" holds
the draws of the second regression coefficient at time 3.
The deviance information criterion and the effective number of parameters
are posterior summaries rather than draws, and are dropped by the coercion.
They remain available through DIC().
The sampler saves every nskip + 1 iterations after burn-in, so the
returned object records a thinning interval of nskip + 1, a starting
iteration of nburn + nskip + 1 and a final iteration of
nburn + nsave * (nskip + 1).
Value
An object of class mcmc with nsave rows and one
column per scalar element of the retained parameters named by pars.
See Also
dsp, par_names(), summary.dsp(), coda::mcmc()
Examples
set.seed(200)
signal <- c(rep(0, 50), rep(10, 50))
y <- signal + rnorm(100)
model_spec <- dsp_spec(family = "gaussian", model = "smoothing", D = 1)
fit <- dsp_fit(y, model_spec = model_spec, nsave = 200, nburn = 200)
draws <- as.mcmc(fit, pars = c("dhs_phi", "dhs_mean"))
summary(draws)
coda::effectiveSize(draws)
Standardized maximum deviation of posterior draws
Description
Shared computation for credBands() and simBaS(): the pointwise posterior
mean and standard deviation, and for each draw the maximum over the domain
of the standardized absolute deviation from the mean.
Usage
band_stats(sampFuns)
Arguments
sampFuns |
|
Value
A list with components Efx and SDfx, vectors of
length m, Maxfx, a vector of length Nsims, and
varies, a logical vector of length m.
Note
Points with no posterior variation, such as fixed initial values,
have a standardized deviation of 0/0. They are excluded from the maximum,
so that they do not make every Maxfx undefined.
MCMC sampler for Bayesian trend filtering
Description
Run the MCMC for Bayesian trend filtering with a penalty on zeroth (D = 0), first (D = 1), or second (D = 2) differences of the conditional expectation. The penalty is determined by the prior on the evolution errors, which include:
the dynamic horseshoe prior ('DHS');
the horseshoe prior ('HS');
the Bayesian lasso ('BL');
the normal stochastic volatility model ('SV');
the normal-inverse-gamma prior ('NIG').
In each case, the evolution error is a scale mixture of Gaussians. Sampling is accomplished with a (parameter-expanded) Gibbs sampler, mostly relying on a dynamic linear model representation.
Usage
btf(
y,
evol_error = "DHS",
D = 2,
obsSV = "const",
nsave = 1000,
nburn = 1000,
nskip = 4,
mcmc_params = list("mu", "ypred", "evol_sigma_t2", "obs_sigma_t2", "dhs_phi",
"dhs_mean", "h_smooth"),
computeDIC = TRUE,
verbose = TRUE,
D_asv = 1,
evol_error_asv = "HS",
nugget_asv = TRUE
)
Arguments
y |
the |
evol_error |
the evolution error distribution; must be one of 'DHS' (dynamic horseshoe prior; the default), 'HS' (horseshoe prior), 'BL' (Bayesian lasso), or 'NIG' (normal-inverse-gamma prior) |
D |
degree of differencing (D = 0, D = 1, or D = 2) |
obsSV |
Options for modeling the error variance. It must be one of the following:
for the observation error variance |
nsave |
number of MCMC iterations to record |
nburn |
number of MCMC iterations to discard (burnin) |
nskip |
number of MCMC iterations to skip between saving iterations, i.e., save every (nskip + 1)th draw |
mcmc_params |
named list of parameters for which we store the MCMC output; must be one or more of:
|
computeDIC |
logical; if TRUE, compute the deviance information criterion |
verbose |
logical; should R report extra information on progress? |
D_asv |
integer; degree of differencing (0, 1, or 2) for the ASV model. Only used when |
evol_error_asv |
character; evolution error distribution for the ASV model. Must be one of the five options used in |
nugget_asv |
logical; if |
Value
A named list of the nsave MCMC samples for the parameters named in mcmc_params
Note
The data y may contain NAs, which will be treated with a simple imputation scheme
via an additional Gibbs sampling step. In general, rescaling y to have unit standard
deviation is recommended to avoid numerical issues.
MCMC sampler for Bayesian trend filtering: D = 0
Description
Run the MCMC for Bayesian trend filtering with a penalty on the conditional expectation. The penalty is determined by the prior on the evolution errors, which include:
the dynamic horseshoe prior ('DHS');
the horseshoe prior ('HS');
the Bayesian lasso ('BL');
the normal stochastic volatility model ('SV');
the normal-inverse-gamma prior ('NIG').
In each case, the evolution error is a scale mixture of Gaussians. Sampling is accomplished with a (parameter-expanded) Gibbs sampler, mostly relying on a dynamic linear model representation.
Usage
btf0(
y,
evol_error = "DHS",
obsSV = "const",
nsave = 1000,
nburn = 1000,
nskip = 4,
mcmc_params = list("mu", "ypred", "evol_sigma_t2", "obs_sigma_t2", "dhs_phi",
"dhs_mean", "h_smooth"),
computeDIC = TRUE,
verbose = TRUE,
D_asv = 1,
evol_error_asv = "HS",
nugget_asv = TRUE
)
Arguments
y |
the |
evol_error |
the evolution error distribution; must be one of 'DHS' (dynamic horseshoe prior), 'HS' (horseshoe prior), 'BL' (Bayesian lasso), or 'NIG' (normal-inverse-gamma prior) |
obsSV |
Options for modeling the error variance. It must be one of the following:
|
nsave |
number of MCMC iterations to record |
nburn |
number of MCMC iterations to discard (burnin) |
nskip |
number of MCMC iterations to skip between saving iterations, i.e., save every (nskip + 1)th draw |
mcmc_params |
named list of parameters for which we store the MCMC output; must be one or more of:
|
computeDIC |
logical; if TRUE, compute the deviance information criterion |
verbose |
logical; should R report extra information on progress? |
D_asv |
integer; degree of differencing (0, 1, or 2) for the ASV model. Only used when |
evol_error_asv |
character; evolution error distribution for the ASV model. Must be one of the five options used in |
nugget_asv |
logical; if |
Value
A named list of the nsave MCMC samples for the parameters named in mcmc_params
Note
The data y may contain NAs, which will be treated with a simple imputation scheme
via an additional Gibbs sampling step. In general, rescaling y to have unit standard
deviation is recommended to avoid numerical issues.
MCMC sampler for B-spline Bayesian trend filtering
Description
Run the MCMC for B-spline fitting with a Bayesian trend filtering model on the coefficients, i.e., a penalty on zeroth (D=0), first (D=1), or second (D=2) differences of the B-spline basis coefficients. The penalty is determined by the prior on the evolution errors, which include:
the dynamic horseshoe prior ('DHS');
the horseshoe prior ('HS');
the Bayesian lasso ('BL');
the normal stochastic volatility model ('SV');
the normal-inverse-gamma prior ('NIG').
In each case, the evolution error is a scale mixture of Gaussians. Sampling is accomplished with a (parameter-expanded) Gibbs sampler, mostly relying on a dynamic linear model representation.
Usage
btf_bspline(
y,
times = NULL,
num_knots = NULL,
evol_error = "DHS",
D = 2,
nsave = 1000,
nburn = 1000,
nskip = 4,
mcmc_params = list("mu", "ypred", "beta", "evol_sigma_t2", "obs_sigma_t2", "dhs_phi",
"dhs_mean"),
computeDIC = TRUE,
verbose = TRUE
)
Arguments
y |
the |
times |
the |
num_knots |
the number of knots; if NULL, use the default of |
evol_error |
the evolution error distribution; must be one of 'DHS' (dynamic horseshoe prior), 'HS' (horseshoe prior), 'BL' (Bayesian lasso), or 'NIG' (normal-inverse-gamma prior) |
D |
degree of differencing (D = 0, D = 1, or D = 2) |
nsave |
number of MCMC iterations to record |
nburn |
number of MCMC iterations to discard (burin-in) |
nskip |
number of MCMC iterations to skip between saving iterations, i.e., save every (nskip + 1)th draw |
mcmc_params |
named list of parameters for which we store the MCMC output; must be one or more of:
|
computeDIC |
logical; if TRUE, compute the deviance information criterion |
verbose |
logical; should R report extra information on progress? |
Value
A named list of the nsave MCMC samples for the parameters named in mcmc_params
Note
The data y may contain NAs, which will be treated with a simple imputation scheme
via an additional Gibbs sampling step. In general, rescaling y to have unit standard
deviation is recommended to avoid numerical issues.
The primary advantages of btf_bspline over btf are
Unequally-spaced points are handled automatically and
Computations are linear in the number of basis coefficients, which may be substantially fewer than the number of time points.
MCMC sampler for B-spline Bayesian trend filtering: D = 0
Description
Run the MCMC for B-spline fitting with a penalty the B-spline basis coefficients. The penalty is determined by the prior on the evolution errors, which include:
the dynamic horseshoe prior ('DHS');
the horseshoe prior ('HS');
the Bayesian lasso ('BL');
the normal stochastic volatility model ('SV');
the normal-inverse-gamma prior ('NIG').
In each case, the evolution error is a scale mixture of Gaussians. Sampling is accomplished with a (parameter-expanded) Gibbs sampler, mostly relying on a dynamic linear model representation.
Usage
btf_bspline0(
y,
times = NULL,
num_knots = NULL,
evol_error = "DHS",
nsave = 1000,
nburn = 1000,
nskip = 4,
mcmc_params = list("mu", "ypred", "beta", "evol_sigma_t2", "obs_sigma_t2", "dhs_phi",
"dhs_mean"),
computeDIC = TRUE,
verbose = TRUE
)
Arguments
y |
the |
times |
the |
num_knots |
the number of knots; if NULL, use the default of |
evol_error |
the evolution error distribution; must be one of 'DHS' (dynamic horseshoe prior), 'HS' (horseshoe prior), 'BL' (Bayesian lasso), or 'NIG' (normal-inverse-gamma prior) |
nsave |
number of MCMC iterations to record |
nburn |
number of MCMC iterations to discard (burin-in) |
nskip |
number of MCMC iterations to skip between saving iterations, i.e., save every (nskip + 1)th draw |
mcmc_params |
named list of parameters for which we store the MCMC output; must be one or more of:
|
computeDIC |
logical; if TRUE, compute the deviance information criterion |
verbose |
logical; should R report extra information on progress? |
Value
A named list of the nsave MCMC samples for the parameters named in mcmc_params
Note
The data y may contain NAs, which will be treated with a simple imputation scheme
via an additional Gibbs sampling step. In general, rescaling y to have unit standard
deviation is recommended to avoid numerical issues.
The primary advantages of btf_bspline over btf are
Unequally-spaced points are handled automatically and
Computations are linear in the number of basis coefficients, which may be substantially fewer than the number of time points.
MCMC sampler for Bayesian trend filtering with negative binomial observation model
Description
Run the MCMC for Bayesian trend filtering with a penalty on first (D = 1) or second (D = 2) differences of the log conditional expectation of a Negative Binomial distribution. The penalty is determined by the prior on the evolution errors, currently only the following options are available:
the dynamic horseshoe prior ('DHS');
the horseshoe prior ('HS');
In each case, the evolution error is a scale mixture of Gaussians. Sampling is accomplished with a (parameter-expanded) Gibbs sampler, mostly relying on a dynamic linear model representation.
Usage
btf_nb(
y,
evol_error = "DHS",
D = 2,
nsave = 1000,
nburn = 1000,
nskip = 4,
mcmc_params = list("mu", "ypred", "evol_sigma_t2", "r", "dhs_phi", "dhs_mean"),
r_init = NULL,
r_sample = TRUE,
step = 1,
evol0_sample = FALSE,
evol0_sd = 10,
sigma_e = 1/sqrt(Nt),
chol0 = NULL,
computeDIC = TRUE,
offset = 0,
verbose = TRUE
)
Arguments
y |
the length |
evol_error |
the evolution error distribution; must be one of 'DHS' (dynamic horseshoe prior; the default), 'HS' (horseshoe prior), 'BL' (Bayesian lasso), or 'NIG' (normal-inverse-gamma prior) |
D |
degree of differencing (D = 0, D = 1, or D = 2) |
nsave |
number of MCMC iterations to record |
nburn |
number of MCMC iterations to discard (burnin) |
nskip |
number of MCMC iterations to skip between saving iterations, i.e., save every (nskip + 1)th draw |
mcmc_params |
character list of parameters for which we store the MCMC output; must be one or more of:
Defaults to everything. |
r_init |
numeric; initial value of the overdispersion parameter, or
|
r_sample |
logical or character; controls whether and how the
overdispersion
|
step |
numeric (defaults to 1); step length of proposal distribution for
Metropolis-Hasting sampling of overdispersion parameter; ignored if r_sample is |
evol0_sample |
logical; if |
evol0_sd |
numeric; initial value (defaults to 10) or the fixed prior standard deviation
for the initial |
sigma_e |
numeric; scale value (defaults to |
chol0 |
logical; If anything except |
computeDIC |
logical; if TRUE, compute the deviance information criterion |
offset |
length |
verbose |
logical; If TRUE (the default), time remaining is printed to console |
Value
A named list with the following. One named element for each of the parameters specified in mcmc_params containing
the nsave posterior draws as a vector for scalar parameters and matrix for multivariate parameters.
An element named loglike containing a vector of the nsave evaluations of the log
likelihood of the data y with a Negative Binomial distribution defined by the current iteration conditional expectation + offset and overdispersion.
If computeDIC is TRUE, a named element for the computed value of DIC and effective parameters p_d for the data y
with a Negative Binomial distribution defined by the posterior mean of the conditional expectation + offset and posterior
mean overdispersion.
MCMC sampler for Bayesian trend filtering: regression
Description
Run the MCMC for Bayesian trend filtering regression with a penalty on first (D=1) or second (D=2) differences of each dynamic regression coefficient. The penalty is determined by the prior on the evolution errors, which include:
the dynamic horseshoe prior ('DHS');
the horseshoe prior ('HS');
the Bayesian lasso ('BL');
the normal stochastic volatility model ('SV');
the normal-inverse-gamma prior ('NIG').
In each case, the evolution error is a scale mixture of Gaussians. Sampling is accomplished with a (parameter-expanded) Gibbs sampler, mostly relying on a dynamic linear model representation.
Usage
btf_reg(
y,
X = NULL,
evol_error = "DHS",
D = 1,
obsSV = "const",
nsave = 1000,
nburn = 1000,
nskip = 4,
mcmc_params = list("mu", "ypred", "beta", "evol_sigma_t2", "obs_sigma_t2", "dhs_phi",
"dhs_mean", "h_smooth"),
use_backfitting = FALSE,
computeDIC = TRUE,
verbose = TRUE,
D_asv = 1,
evol_error_asv = "HS",
nugget_asv = TRUE
)
Arguments
y |
the |
X |
the |
evol_error |
the evolution error distribution; must be one of 'DHS' (dynamic horseshoe prior), 'HS' (horseshoe prior), 'BL' (Bayesian lasso), or 'NIG' (normal-inverse-gamma prior) |
D |
degree of differencing (D = 1 or D = 2) |
obsSV |
Options for modeling the error variance. It must be one of the following:
|
nsave |
number of MCMC iterations to record |
nburn |
number of MCMC iterations to discard (burin-in) |
nskip |
number of MCMC iterations to skip between saving iterations, i.e., save every (nskip + 1)th draw |
mcmc_params |
named list of parameters for which we store the MCMC output; must be one or more of:
|
use_backfitting |
logical; if TRUE, use backfitting to sample the predictors j=1,...,p (faster, but usually less MCMC efficient) |
computeDIC |
logical; if TRUE, compute the deviance information criterion |
verbose |
logical; should R report extra information on progress? |
D_asv |
integer; degree of differencing (0, 1, or 2) for the ASV model. Only used when |
evol_error_asv |
character; evolution error distribution for the ASV model. Must be one of the five options used in |
nugget_asv |
logical; if |
Value
A named list of the nsave MCMC samples for the parameters named in mcmc_params
Note
The data y may contain NAs, which will be treated with a simple imputation scheme
via an additional Gibbs sampling step. In general, rescaling y to have unit standard
deviation is recommended to avoid numerical issues.
Run the MCMC for sparse Bayesian trend filtering
Description
Sparse Bayesian trend filtering has two penalties: (1) a penalty on the first (D = 1) or second (D = 2) differences of the conditional expectation and (2) a penalty on the conditional expectation, i.e., shrinkage to zero.
Usage
btf_sparse(
y,
evol_error = "DHS",
zero_error = "DHS",
D = 2,
obsSV = "const",
nsave = 1000,
nburn = 1000,
nskip = 4,
mcmc_params = list("mu", "ypred", "evol_sigma_t2", "obs_sigma_t2", "zero_sigma_t2",
"dhs_phi", "dhs_mean", "dhs_phi_zero", "dhs_mean_zero", "h_smooth"),
computeDIC = TRUE,
verbose = TRUE,
D_asv = 1,
evol_error_asv = "HS",
nugget_asv = TRUE
)
Arguments
y |
the |
evol_error |
the evolution error distribution; must be one of 'DHS' (dynamic horseshoe prior), 'HS' (horseshoe prior), 'BL' (Bayesian lasso), or 'NIG' (normal-inverse-gamma prior) |
zero_error |
the shrinkage-to-zero distribution; must be one of 'DHS' (dynamic horseshoe prior), 'HS' (horseshoe prior), 'BL' (Bayesian lasso), or 'NIG' (normal-inverse-gamma prior) |
D |
degree of differencing (D = 1, or D = 2) |
obsSV |
Options for modeling the error variance. It must be one of the following:
|
nsave |
number of MCMC iterations to record |
nburn |
number of MCMC iterations to discard (burnin-in) |
nskip |
number of MCMC iterations to skip between saving iterations, i.e., save every (nskip + 1)th draw |
mcmc_params |
named list of parameters for which we store the MCMC output; must be one or more of:
|
computeDIC |
logical; if TRUE, compute the deviance information criterion |
verbose |
logical; should R report extra information on progress? |
D_asv |
integer; degree of differencing (0, 1, or 2) for the ASV model. Only used when |
evol_error_asv |
character; evolution error distribution for the ASV model. Must be one of the five options used in |
nugget_asv |
logical; if |
Details
Each penalty is determined by a prior, which include:
the dynamic horseshoe prior ('DHS');
the horseshoe prior ('HS');
the Bayesian lasso ('BL');
the normal stochastic volatility model ('SV');
the normal-inverse-gamma prior ('NIG').
In each case, the prior is a scale mixture of Gaussians. Sampling is accomplished with a (parameter-expanded) Gibbs sampler, mostly relying on a dynamic linear model representation.
Value
A named list of the nsave MCMC samples for the parameters named in mcmc_params
Note
The data y may contain NAs, which will be treated with a simple imputation scheme
via an additional Gibbs sampling step. In general, rescaling y to have unit standard
deviation is recommended to avoid numerical issues.
Compute the quadratic term in Bayesian trend filtering
Description
Compute the quadratic term arising in the full conditional distribution
of a Bayesian trend filtering model with D = 1 or D = 2.
This function exploits the known D-banded structure of Q
to compute the matrix directly, using objects in the Matrix package.
Usage
build_Q(obs_sigma_t2, evol_sigma_t2, D = 1)
Arguments
obs_sigma_t2 |
the |
evol_sigma_t2 |
the |
D |
the degree of differencing (one or two) |
Value
Banded T x T Matrix (object) Q
Compute X'X
Description
Build the Tp x Tp matrix XtX using the Matrix() package
Usage
build_XtX(X)
Arguments
X |
|
Value
Block diagonal Tp x Tp Matrix (object) where each p x p block is tcrossprod(matrix(X[t,]))
Note
X'X is a one-time computing cost. Special cases may have more efficient computing options, but the Matrix representation is important for efficient computations within the sampler.
Detect changepoints from a changepoint model
Description
Computes, for each time point, the posterior probability that the
increment of the mean exceeds the threshold of the changepoint model, and
reports the time points at which this probability is at least cp_thres.
Usage
changepoints(object, cp_thres = 0.5, times = NULL, all = FALSE)
Arguments
object |
object of class dsp from |
cp_thres |
(default 0.5) cutoff for the posterior probability of threshold exceedance needed to label a time point a changepoint. |
times |
optional vector of length |
all |
logical; if |
Details
The changepoint model of Wu et al. (2024) uses a thresholding mechanism with
a latent indicator variable. A time point t is a candidate
changepoint when the squared increment \omega_t^2 exceeds the
threshold \exp(\gamma). The posterior probability of this event is
estimated by the proportion of saved draws in which it occurs. Because
\omega is the Dth difference of \mu, no increment is defined
at the first D time points, and their probability is NA.
Value
A data frame with columns index (the position in the observed series),
time (only if times is supplied), and probability (the posterior
probability of threshold exceedance). If all = FALSE, it has one row per
detected changepoint, and zero rows if none is detected. If all = TRUE,
it has one row per time point and an additional logical column
changepoint.
See Also
plot.dsp(), which marks the detected changepoints, and
credible_bands(), which assesses the increments jointly.
Examples
set.seed(200)
signal = c(rep(0, 50), rep(10, 50))
noise = rep(1, 100)
noise_var = rep(1, 100)
for (k in 2:100){
noise_var[k] = exp(0.9*log(noise_var[k-1]) + rnorm(1, 0, 0.5))
noise[k] = rnorm(1, 0, sqrt(noise_var[k])) }
y = signal + noise
model_spec = dsp_spec(family = "gaussian", model = "changepoint",
D = 1, useAnom = TRUE)
mcmc_output = dsp_fit(y, model_spec = model_spec, nsave = 200, nburn = 200)
changepoints(mcmc_output)
changepoints(mcmc_output, cp_thres = 0.8,
times = seq(as.Date("2000-01-01"), by = "month", length.out = 100))
head(changepoints(mcmc_output, all = TRUE))
Stop unless an object is a fitted dsp model
Description
Stop unless an object is a fitted dsp model
Usage
check_dsp(object)
Arguments
object |
any R object |
Value
object, invisibly.
Extract posterior coefficient estimates
Description
Return posterior means of the regression or B-spline coefficients.
Usage
## S3 method for class 'dsp'
coef(object, ...)
Arguments
object |
a fitted |
... |
currently unused. |
Value
For regression, a matrix with one row per fitted time point and
one column per predictor, named by the column names of X, or x1,
x2, ... if X has none. For B-splines, a named vector of basis
coefficient estimates. Other model types do not have a separate
coefficient parameter; use fitted.dsp() for their mean process.
See Also
fitted.dsp(), credible_intervals()
Compute the DIC of the ASV model
Description
Computes the deviance information criterion and the effective number of parameters (Spiegelhalter et al. 2002).
Usage
computeDIC_ASV(y, beta, post_sigma2, post_loglike)
Arguments
y |
the |
beta |
the known mean of the process. 0 by default. |
post_sigma2 |
posterior samples of the variance, i.e. exp(h) |
post_loglike |
log likelihood based on the posterior sample. |
Value
a list containing DIC and p_d. Two options for estimating both DIC and p_d, which are both included.
Compute simultaneous credible bands
Description
Compute (1-alpha)\ (Journal of Computational and Graphical Statistics, 16(2), 265–288, doi:10.1198/106186007X208768).
Usage
credBands(sampFuns, alpha = 0.05)
Arguments
sampFuns |
|
alpha |
one minus the credibility level of the bands |
Value
m x 2 matrix of credible bands; the first column is the lower band, the second is the upper band
Note
The input needs not be curves: the simultaneous credible "bands" may be computed for vectors. The result is a joint credible band at credibility level 1 - alpha across all components of the vector. At a point with no posterior variation, both bands equal the constant value.
Simultaneous credible bands and band scores
Description
Computes simultaneous credible bands for a time-varying parameter, and the simultaneous band scores (SimBaS) that test, at each time point, whether the parameter is zero.
Usage
credible_bands(object, pars = "mu", level = 0.95, times = NULL, ...)
## S3 method for class 'dsp_bands'
print(x, digits = 2, max_periods = 10, ...)
Arguments
object |
an object of class |
pars |
character string naming one time-varying parameter; see
|
level |
the credibility level of the bands. Defaults to 0.95. |
times |
optional vector of length |
... |
currently not used |
x |
an object of class |
digits |
number of significant digits for the global Bayesian p-value |
max_periods |
the largest number of periods to list per band |
Details
The bands of Crainiceanu et al. (2007) have the form posterior mean plus or
minus a multiple of the pointwise posterior standard deviation. The
multiple is the level quantile, over the posterior draws, of the
largest standardized absolute deviation from the posterior mean across all
time points. The bands therefore contain the whole trajectory in a
proportion level of the posterior draws, whereas the pointwise
intervals from credible_intervals() are computed at each time point separately.
The SimBaS of Meyer et al. (2015) at time t is the smallest
\alpha for which the 1 - \alpha simultaneous band excludes zero
at t. A small value is evidence that the parameter is nonzero at
t, adjusted for testing all time points at once. The minimum over
time, min(bands[, "simBaS"], na.rm = TRUE), is the global Bayesian
p-value for the hypothesis that the parameter is zero at every time point.
The scores are informative only for a parameter for which zero is a value
of interest. Examples are the increments omega, where a small score
marks a time at which the mean function changes (for D = 1) or its
slope changes (for D = 2), and the regression coefficients
beta, where a small score marks a time at which the predictor has an
effect. For the mean function mu of a series far from zero, every
score is close to zero and carries no information. The changepoint model
stores omega by default. For omega, the test is distinct
from the changepoint rule of changepoints(), which compares the
increments with the threshold of the changepoint model.
Time points with no posterior variation, such as fixed initial values, are
excluded when the bands are calibrated. At those points both bands equal
the constant value and the score is NA.
Value
An object of class dsp_bands, a data frame with one row per time
point and columns time, mean, lower, upper and
simBaS. For a parameter with one band per predictor, such as the
regression coefficients beta, a column predictor follows
time, naming the predictor as in coef.dsp(): by the column names
of X, or x1, x2, ... if X has none. The time column is taken from times. The
increments omega have T - D entries, which are labelled with
the last T - D time points, so that each row refers to the time at
which the increment ends. The basis coefficients of a B-spline model,
beta and evol_sigma_t2, are labelled by a column
coefficient in place of time. The print method reports the global Bayesian
p-value and the periods in which the band excludes zero, by predictor.
Subsetting with [ returns a plain data frame.
References
Crainiceanu, C. M., Ruppert, D., Carroll, R. J., Joshi, A. and Goodner, B. (2007). Spatially adaptive Bayesian penalized splines with heteroscedastic errors. Journal of Computational and Graphical Statistics, 16(2), 265–288. doi:10.1198/106186007X208768
Meyer, M. J., Coull, B. A., Versace, F., Cinciripini, P. and Morris, J. S. (2015). Bayesian function-on-function regression for multilevel functional data. Biometrics, 71(3), 563–574. doi:10.1111/biom.12299
See Also
credible_intervals() for pointwise intervals, plot.dsp() with
include_joint_bands = TRUE to display the bands
Examples
set.seed(200)
y <- c(rep(0, 50), rep(10, 50)) + rnorm(100)
model_spec <- dsp_spec(family = "gaussian", model = "changepoint", D = 1)
fit <- dsp_fit(y, model_spec = model_spec, nsave = 200, nburn = 200)
# global Bayesian p-value and the periods in which the band excludes zero
bands <- credible_bands(fit, pars = "omega")
bands
# the pointwise values
head(as.data.frame(bands))
# time points at which the increment is nonzero at the joint 5% level
subset(bands, simBaS < 0.05)$time
Pointwise credible intervals
Description
Computes equal-tailed pointwise credible intervals for a stored parameter.
Usage
credible_intervals(object, pars = "mu", level = 0.95, times = NULL, ...)
Arguments
object |
an object of class |
pars |
character string naming one stored parameter; see
|
level |
the posterior probability covered by each interval. Defaults to 0.95. |
times |
optional vector of length |
... |
currently not used |
Details
Each interval runs from the (1 - level)/2 to the
(1 + level)/2 posterior quantile of the parameter at one time point,
so it covers that value with posterior probability level. The
intervals are computed at each time point separately. The simultaneous
bands of credible_bands() instead contain the whole trajectory with
posterior probability level, and are therefore wider.
Value
A data frame with columns mean, lower and upper, the
posterior mean and the interval limits. For a time-varying parameter there
is one row per time point, and a column time, taken from
times, comes first. For a parameter with one value per predictor and
time point, such as the regression coefficients beta, a column
predictor follows time, naming the predictor as in
coef.dsp(). The increments omega have
T - D entries, which are labelled with the last T - D time
points. The basis coefficients of a B-spline model, beta and
evol_sigma_t2, are labelled by a column coefficient, and a
scalar parameter gives a single row.
See Also
credible_bands() for simultaneous bands, fitted.dsp() for
other posterior quantiles, predict.dsp() for prediction intervals
Examples
set.seed(200)
y <- c(rep(0, 50), rep(10, 50)) + rnorm(100)
model_spec <- dsp_spec(family = "gaussian", model = "changepoint", D = 1)
fit <- dsp_fit(y, model_spec = model_spec, nsave = 200, nburn = 200)
# 95% pointwise intervals for the mean function
head(credible_intervals(fit))
# 80% intervals for the increments, labelled by date
dates <- seq(as.Date("2000-01-01"), by = "month", length.out = 100)
head(credible_intervals(fit, pars = "omega", level = 0.8, times = dates))
Extract the posterior mean deviance
Description
Return the posterior mean of the deviance, \bar{D} = -2 times the
average of the stored log-likelihood values.
Usage
## S3 method for class 'dsp'
deviance(object, ...)
Arguments
object |
a fitted |
... |
currently unused. |
Details
\bar{D} is the goodness-of-fit term of the deviance
information criterion: with the p_D estimator of the effective
number of parameters, DIC = \bar{D} + p_D. DIC() returns both
versions of the criterion.
Value
A numeric scalar.
See Also
Accessor functions for fitted dsp models
Description
Extract information from a fitted dsp object without referring to
its internal structure.
Usage
par_names(object)
## S3 method for class 'dsp'
fitted(object, pars = "mu", probs = c(0.025, 0.25, 0.5, 0.75, 0.975), ...)
DIC(object, ...)
## S3 method for class 'dsp'
DIC(object, ...)
get_spec(object)
## S3 method for class 'dsp'
nobs(object, ...)
Arguments
object |
an object of class |
pars |
character string naming one parameter; see |
probs |
numeric vector of probabilities for the posterior quantiles |
... |
currently not used |
Details
par_names() returns the names of the parameters with stored posterior
draws. These are the values accepted by the pars argument of
fitted(), credible_intervals(), credible_bands(), summary.dsp() and
as.mcmc.dsp(), and by the
type argument of plot.dsp().
fitted() returns pointwise posterior summaries of one parameter.
For the posterior draws themselves, use as.mcmc.dsp().
DIC() returns the deviance information criterion under the two
standard estimators of the effective number of parameters,
p_D (Spiegelhalter et al. 2002) and p_V (Gelman et al. 2014).
Lower values are preferred. We recommend p_D by default.
get_spec() returns the dsp_spec() object that the model was
fitted with.
nobs() returns the number of time points T in the fitted
series, including any missing observations, which the model imputes.
Value
par_names(): a character vector.
fitted(): for a time-varying parameter, a numeric matrix with one row
per time point (or index) and columns "mean" followed by one column
per element of probs, named as by stats::quantile(). A parameter
with a further dimension, such as the regression coefficients beta,
gives an array whose third dimension holds these summaries. A scalar
parameter gives a named vector.
DIC(): a data frame with one row per estimator and columns
estimator, DIC and p_eff, the effective number of
parameters.
get_spec(): an object of class dsp_spec.
nobs(): an integer.
References
Spiegelhalter, D. J., Best, N. G., Carlin, B. P. and van der Linde, A. (2002). Bayesian measures of model complexity and fit. Journal of the Royal Statistical Society: Series B, 64(4), 583–639.
Gelman, A., Carlin, J. B., Stern, H. S., Dunson, D. B., Vehtari, A. and Rubin, D. B. (2014). Bayesian Data Analysis, 3rd edition. CRC Press.
See Also
summary.dsp(), as.mcmc.dsp(), plot.dsp(), predict.dsp(),
changepoints()
Examples
set.seed(200)
y <- c(rep(0, 50), rep(10, 50)) + rnorm(100)
model_spec <- dsp_spec(family = "gaussian", model = "smoothing", D = 1)
fit <- dsp_fit(y, model_spec = model_spec, nsave = 200, nburn = 200)
par_names(fit)
head(fitted(fit))
DIC(fit)
get_spec(fit)
nobs(fit)
MCMC sampler for models with dynamic shrinkage processes
Description
Wrapper function for fitting models with Dynamic Shrinkage Processes (DSP), including:
Adaptive Bayesian Changepoint analysis and local Outlier (ABCO),
Bayesian Trend Filter for Gaussian Data
Time-varying Regression
Bayesian Trend Filter with B-spline for irregularly spaced or functional time-series.
Bayesian Smoothing for Count Data
Method for printing basic information about the MCMC sampling settings for the fitted model
Usage
dsp_fit(
y,
model_spec,
nsave = 1000,
nburn = 1000,
nskip = 4,
computeDIC = TRUE,
verbose = TRUE,
seed = NULL,
...
)
## S3 method for class 'dsp'
print(x, ...)
Arguments
y |
a numeric vector of the |
model_spec |
a list containing model specification generated from |
nsave |
integer scalar (default = 1000); number of MCMC iterations to record |
nburn |
integer scalar (default = 1000); number of MCMC iterations to discard (burn-in) |
nskip |
integer scalar (default = 4); number of MCMC iterations to skip between saving iterations, i.e., save every (nskip + 1)th draw |
computeDIC |
logical; if TRUE (default), compute the deviance information criterion |
verbose |
logical; should extra information on progress be printed to the console? Defaults to FALSE |
seed |
optional integer; if supplied, seeds the random number generator
for a reproducible fit. Equivalent to calling |
... |
currently not used |
x |
object of class dsp from |
Details
A brief summary of the settings used to fit the model including number of iterations, burn in, and thinning rates.
Value
dsp_fit returns an object of class "dsp".
An object of class "dsp" is defined as a list containing at least the following components:
mcmc_output |
a list of the |
y |
the original observations, including any missing values, retained for |
DIC |
Deviance Information Criterion |
mcpar |
named vector of supplied nsave, nburn, and nskip |
model_spec |
the object supplied for model_spec argument |
MCMC Output Parameters
Shared parameters across wrappers include:
-
mu: Conditional mean. -
ypred: Posterior predictive\tilde{y}_t. -
evol_sigma_t2: Variance of the state variable. ForD > 0, the firstDentries are the variances of the initial states. -
obs_sigma_t2: Observation variance\sigma^2_{\epsilon}(family = "gaussian"). One draw per iteration when the variance is constant in time (obsSV = "const", and always formodel = "bspline"), otherwise one per time point. -
dhs_phi,dhs_mean: DHS hyperparameter draws (evol_error = "DHS").
Model-specific parameters include:
-
changepoint(Gaussian):-
omega:D-th differenced posterior mean draws,\mu_t. -
zeta: anomaly component (whenuseAnom = TRUE), withTcolumns aligned withy. The anomaly is defined fort > Donly and is zero at the firstDtime points. -
zeta_sigma_t2: variance of the horseshoe+ prior on the anomaly (whenuseAnom = TRUE), zero at the firstDtime points. -
gamma: threshold parameter in the thresholded DHS log-volatility dynamics.
-
-
regression(Gaussian):-
beta: time-varying regression coefficient draws.
-
-
bspline(Gaussian):-
beta: B-spline basis coefficient draws.
-
-
smoothing(Negative Binomial):-
r: overdispersion parameter draws.
-
Note
The data y may contain NAs, which will be treated with a simple imputation scheme
via an additional Gibbs sampling step. In general, rescaling y to have unit standard
deviation is recommended to avoid numerical issues when family is "gaussian".
Examples
set.seed(200)
signal = c(rep(0, 50), rep(10, 50))
noise = rep(1, 100)
noise_var = rep(1, 100)
for (k in 2:100){
noise_var[k] = exp(0.9*log(noise_var[k-1]) + rnorm(1, 0, 0.5))
noise[k] = rnorm(1, 0, sqrt(noise_var[k])) }
y = signal + noise
model_spec = dsp_spec(family = "gaussian", model = "changepoint",
D = 1, useAnom = TRUE, obsSV = "SV")
mcmc_output = dsp_fit(y, model_spec = model_spec, nsave = 200, nburn = 200)
print(mcmc_output)
Model specification
Description
Method for creating dsp specification object prior to fitting.
Method for printing basic information about the model specification
Usage
dsp_spec(family, model, ...)
## S3 method for class 'dsp_spec'
print(x, ...)
Arguments
family |
A character string specifying the model family. Must be one of:
|
model |
A character string specifying the model type:
|
... |
currently not used |
x |
object of class dsp_spec from |
Value
A list containing the model specification.
Examples
model_spec <- dsp_spec(family = "gaussian",
model = "smoothing")
print(model_spec)
Effective sample sizes of the varying columns of a draws matrix
Description
Effective sample sizes of the varying columns of a draws matrix
Usage
ess_varying(b)
Arguments
b |
numeric matrix of posterior draws, one column per element |
Value
A numeric vector of length ncol(b), NA for a column
with no posterior variation, for which coda::effectiveSize() reports 0.
MCMC sampler for adaptive stochastic volatility (ASV) model
Description
The penalty is determined by the prior on the evolution errors, which include:
the dynamic horseshoe prior ('DHS');
the horseshoe prior ('HS');
the Bayesian lasso ('BL');
the normal-inverse-gamma prior ('NIG').
In each case, the evolution error is a scale mixture of Gaussians. Sampling is accomplished with a (parameter-expanded) Gibbs sampler, mostly relying on a dynamic linear model representation.
Usage
fit_ASV(
y,
beta = 0,
evol_error = "DHS",
D = 1,
nsave = 1000,
nburn = 1000,
nskip = 4,
mcmc_params = list("h", "logy2hat", "sigma2", "evol_sigma_t2", "dhs_phi", "dhs_mean"),
nugget = FALSE,
computeDIC = TRUE,
verbose = TRUE
)
Arguments
y |
the |
beta |
the mean of the observed process y. If not provided, they are assumed to be 0. |
evol_error |
the evolution error distribution; must be one of 'DHS' (dynamic horseshoe prior), 'HS' (horseshoe prior), 'BL' (Bayesian lasso), or 'NIG' (normal-inverse-gamma prior) |
D |
degree of differencing (D = 1, or D = 2) |
nsave |
number of MCMC iterations to record |
nburn |
number of MCMC iterations to discard (burin-in) |
nskip |
number of MCMC iterations to skip between saving iterations, i.e., save every (nskip + 1)th draw |
mcmc_params |
named list of parameters for which we store the MCMC output; must be one or more of:
|
nugget |
logical; if |
computeDIC |
logical; if TRUE, compute the deviance information criterion |
verbose |
logical; should R report extra information on progress? |
Value
A named list of the nsave MCMC samples for the parameters named in mcmc_params
Note
The data y may contain NAs, which will be treated with a simple imputation scheme
via an additional Gibbs sampling step. In general, rescaling y to have unit standard
deviation is recommended to avoid numerical issues.
Helper function for sampling parameters for ASV model
Description
Helper function for sampling parameters for ASV model
Usage
fit_paramsASV(data, sParams, evol_error, D)
Arguments
data |
the |
sParams |
list from the previous run of fit_paramsASV function or init_paramsASV function |
evol_error |
the evolution error distribution; must be one of 'DHS' (dynamic horseshoe prior), 'HS' (horseshoe prior), 'BL' (Bayesian lasso), or 'NIG' (normal-inverse-gamma prior) |
D |
degree of differencing (D = 1, or D = 2) |
Value
a list containing 4 sets of parameters
s_p_error_term: matrix containing mean and the variance from 10-componenet gaussian mixture (Omori et al. 2007)
s_mu: a vector containing the posterior sample of log variance h,
s_evolParams0: a list containing posterior samples of parameters associated with the variance of first D observation of the log variance term, h.
s_evolParams: a list containing posterior samples parameters associated with the variance of D to the last observations of the log variance temr , h.
Helper function for sampling parameters for ASV model with a nugget effect
Description
Helper function for sampling parameters for ASV model with a nugget effect
Usage
fit_paramsASV_n(data, sParams, evol_error, D)
Arguments
data |
the |
sParams |
list from the previous run of fit_paramsASV function or init_paramsASV function |
evol_error |
the evolution error distribution; must be one of 'DHS' (dynamic horseshoe prior), 'HS' (horseshoe prior), 'BL' (Bayesian lasso), or 'NIG' (normal-inverse-gamma prior) |
D |
degree of differencing (D = 1, or D = 2) |
Value
a list containing 4 sets of parameters
s_p_error_term: matrix containing mean and the variance from 10-componenet gaussian mixture (Omori et al. 2007)
s_mu: a vector containing the posterior sample of log variance h,
s_evolParams0: a list containing posterior samples of parameters associated with the variance of first D observation of the log variance term, h.
s_evolParams: a list containing posterior samples parameters associated with the variance of D to the last observations of the log variance temr , h.
Posterior predictive sampler on the transformed y (log(y^2))
Description
Posterior predictive sampler on the transformed y (log(y^2))
Usage
generate_ly2hat(h, p_error_term)
Arguments
h |
the log varaince term h |
p_error_term |
2 dimensional data frame containing mean and the variance from the 10 componenet Gaussian mixture in Omori et al 2007 paper. |
Value
a vector containing posterior predictive on log(y^2)
Compute the design matrix X for AR(p) model
Description
Compute the design matrix X for AR(p) model
Usage
getARpXmat(y, p = 1, include_intercept = FALSE)
Arguments
y |
(T x 1) vector of responses |
p |
order of AR(p) model |
include_intercept |
logical; if TRUE, first column of X is ones |
Compute non-zeros (signals)
Description
Estimate the location of non-zeros (signals) implied by horseshoe-type thresholding.
Usage
getNonZeros(post_evol_sigma_t2, post_obs_sigma_t2 = NULL)
Arguments
post_evol_sigma_t2 |
the |
post_obs_sigma_t2 |
the |
Details
Thresholding is based on kappa[t] > 1/2, where
kappa = 1/(1 + evol_sigma_t2/obs_sigma_t2), evol_sigma_t2 is the
evolution error variance, and obs_sigma_t2 is the observation error variance.
In particular, the decision rule is based on the posterior mean of kappa.
Value
A vector (or matrix) of indices identifying the signals according to the horsehoe-type thresholding rule.
Note
The thresholding rule depends on whether the prior variance for the state
variable mu (i.e., evol_sigma_t2) is scaled by the observation standard
deviation, obs_sigma_t2. Explicitly, if mu[t] ~ N(0, evol_sigma_t2[t])
then the correct thresholding rule is based on kappa = 1/(1 + evol_sigma_t2/obs_sigma_t2).
However, if mu[t] ~ N(0, evol_sigma_t2[t]*obs_sigma_t2[t])
then the correct thresholding rule is based on kappa = 1/(1 + evol_sigma_t2).
The latter case may be implemented by omitting the input for post_obs_sigma_t2
(or setting it to NULL).
Extract the posterior draws from a fitted dsp model
Description
Extract the posterior draws from a fitted dsp model
Usage
get_draws(object)
Arguments
object |
an object of class |
Value
The elements of object$mcmc_output that hold posterior draws,
with the draws in the first dimension.
Construct indexed column names for a flattened parameter
Description
Builds the column names used when a posterior array is flattened to a
matrix, in the column-major order produced by as.vector().
Usage
get_flatnames(name, dim = NULL, first_index = 1)
Arguments
name |
character, the name of the parameter |
dim |
integer vector of the parameter dimensions excluding the draws,
or |
first_index |
integer, the value the indices start from |
Value
A character vector of length prod(dim), or name itself
when dim is NULL or empty.
Index range in R notation
Description
Index range in R notation
Usage
index_range(from, to)
Arguments
from, to |
first and last index |
Value
"from" if the two are equal, otherwise "from:to".
Compute initial Cholesky decomposition for TVP regression
Description
Computes the Cholesky decomposition for the quadratic term in the (Gaussian) posterior of the TVP regression coefficients. The sparsity pattern will not change during the MCMC, so we can save computation time by computing this up front.
Usage
initCholReg_spam(obs_sigma_t2, evol_sigma_t2, XtX, D = 1)
Arguments
obs_sigma_t2 |
the |
evol_sigma_t2 |
the |
XtX |
the |
D |
the degree of differencing (one or two) |
Compute initial Cholesky decomposition for Bayesian trend filtering
Description
Computes the Cholesky decomposition for the quadratic term in the (Gaussian) posterior of the Bayesian Trend Filtering coefficients. The sparsity pattern will not change during the MCMC, so we can save computation time by computing this up front.
Usage
initChol_spam(nT, D = 1)
Arguments
nT |
number of time points |
D |
degree of differencing (D = 1 or D = 2) |
Initialize the evolution error variance parameters
Description
Compute initial values for evolution error variance parameters under the dynamic horseshoe prior
Usage
initDHS(omega)
Arguments
omega |
|
Value
List of relevant components: the T x p evolution error SD sigma_wt,
the T x p log-volatility ht, the p x 1 log-vol unconditional mean(s) dhs_mean,
the p x 1 log-vol AR(1) coefficient(s) dhs_phi,
the T x p log-vol innovation SD sigma_eta_t from the PG priors,
the p x 1 initial log-vol SD sigma_eta_0,
and the mean of log-vol means dhs_mean0 (relevant when p > 1)
Initialize the parameters for the initial state variance
Description
The initial state SDs are assumed to follow half-Cauchy priors, C+(0,A), where the SDs may be common or distinct among the states.
Usage
initEvol0(mu0, commonSD = TRUE)
Arguments
mu0 |
|
commonSD |
logical; if TRUE, use common SDs (otherwise distinct) |
Details
This function initializes the parameters for a PX-Gibbs sampler.
Value
List of relevant components:
the p x 1 evolution error SD sigma_w0,
the p x 1 parameter-expanded RV's px_sigma_w0,
and the corresponding global scale parameters
sigma_00 and px_sigma_00 (ignore if commonSD)
Initialize the evolution error variance parameters
Description
Compute initial values for evolution error variance parameters under the various options: dynamic horseshoe prior ('DHS'), horseshoe prior ('HS'), Bayesian lasso ('BL'), normal stochastic volatility ('SV'), or normal-inverse-gamma prior ('NIG').
Usage
initEvolParams(omega, evol_error = "DHS")
Arguments
omega |
|
evol_error |
the evolution error distribution; must be one of 'DHS' (dynamic horseshoe prior), 'HS' (horseshoe prior), or 'NIG' (normal-inverse-gamma prior) |
Value
List of relevant components: sigma_wt, the T x p matrix of evolution standard deviations,
and additional parameters associated with the DHS and HS priors.
Initialize the stochastic volatility parameters
Description
Compute initial values for normal stochastic volatility parameters. The model assumes an AR(1) for the log-volatility.
Usage
initSV(omega)
Arguments
omega |
|
Value
List of relevant components: sigma_wt, the T x p matrix of standard deviations,
and additional parameters (unconditional mean, AR(1) coefficient, and standard deviation).
Helper function for initializing parameters for ASV model
Description
Helper function for initializing parameters for ASV model
Usage
init_paramsASV(data, evol_error, D)
Arguments
data |
the |
evol_error |
the evolution error distribution; must be one of 'DHS' (dynamic horseshoe prior), 'HS' (horseshoe prior), 'BL' (Bayesian lasso), or 'NIG' (normal-inverse-gamma prior) |
D |
degree of differencing (D = 1, or D = 2) |
Value
a list containing 4 sets of parameters
s_p_error_term: matrix containing mean and the variance from 10-componenet gaussian mixture (Omori et al. 2007)
s_mu: a vector containing the posterior sample of log variance h,
s_evolParams0: a list containing posterior samples of parameters associated with the variance of first D observation of the log variance term, h.
s_evolParams: a list containing posterior samples parameters associated with the variance of D to the last observations of the log variance temr , h.
Helper function for initializing parameters for ASV model with a nugget effect
Description
Helper function for initializing parameters for ASV model with a nugget effect
Usage
init_paramsASV_n(data, evol_error, D)
Arguments
data |
the |
evol_error |
the evolution error distribution; must be one of 'DHS' (dynamic horseshoe prior), 'HS' (horseshoe prior), 'BL' (Bayesian lasso), or 'NIG' (normal-inverse-gamma prior) |
D |
degree of differencing (D = 1, or D = 2) |
Value
a list containing 4 sets of parameters
s_p_error_term: matrix containing mean and the variance from 10-componenet gaussian mixture (Omori et al. 2007)
s_mu: a vector containing the posterior sample of log variance h,
s_evolParams0: a list containing posterior samples of parameters associated with the variance of first D observation of the log variance term, h.
s_evolParams: a list containing posterior samples parameters associated with the variance of D to the last observations of the log variance temr , h.
Compute the inverse log-odds
Description
Compute the inverse log-odds
Usage
invlogit(x)
Arguments
x |
scalar or vector for which to compute the (componentwise) inverse log-odds |
Value
A scalar or vector of values in (0,1)
Dynamic shrinkage process (dsp) object
Description
Check whether an object is a fitted dsp model.
Usage
is.dsp(object)
Arguments
object |
any R object |
Details
A dsp object is a classified list created by dsp_fit.
It contains mcmc_output, a list of posterior draws whose matrix
elements are nsave by T and whose vector elements are of
length nsave; DIC, the deviance information criterion and
effective number of parameters; mcpar, the number of saved draws,
the burn-in and the thinning interval; and model_spec, the
dsp_spec object describing the fitted model.
The y component contains the original observations, including missing values.
The accessor functions par_names(), fitted.dsp(), DIC(),
get_spec() and nobs.dsp() extract these components without referring
to the structure of the object.
coef() returns the posterior means of the regression coefficients for
model = "regression" or the basis coefficients for model = "bspline".
residuals() subtracts the posterior mean of \mu_t from y_t.
credible_intervals() returns pointwise credible intervals for a stored
parameter, and credible_bands() simultaneous credible bands.
logLik() returns the posterior mean log-likelihood. Set
summary = "draws" to return the value at each saved iteration.
deviance() returns the posterior mean deviance, the goodness-of-fit
term of DIC().
predict() returns posterior predictive summaries, the same as
fitted(object, pars = "ypred"), for every model. For changepoint models, changepoints() returns the
detected changepoints and their posterior probabilities as a data frame.
Value
Logical, whether object inherits from class dsp.
See Also
dsp-accessors, as.mcmc.dsp(), summary.dsp()
Extract posterior log-likelihood values
Description
Return the posterior mean log-likelihood or the stored log-likelihood value at each saved MCMC iteration.
Usage
## S3 method for class 'dsp'
logLik(object, summary = c("mean", "draws"), ...)
Arguments
object |
a fitted |
summary |
either |
... |
currently unused. |
Details
The mean is the average of the stored log-likelihood values,
not the log-likelihood evaluated at posterior mean parameters or the
logarithm of the average likelihood. It is not a maximized
log-likelihood, and a shrinkage model has no fixed parameter count, so
the degrees of freedom are NA and AIC() and BIC() return NA.
Use DIC() for the model-comparison summaries provided by the package.
Value
For summary = "mean", an object of class logLik with
attributes nobs and df = NA. For summary = "draws", a numeric
vector with one value per saved iteration.
See Also
as.mcmc.dsp(), DIC(), deviance.dsp()
Compute the log-odds
Description
Compute the log-odds
Usage
logit(x)
Arguments
x |
scalar or vector in (0,1) for which to compute the (componentwise) log-odds |
Value
A scalar or vector of log-odds
Sample components from a discrete mixture of normals
Description
Sample Z from 1,2,...,k, with P(Z=i) proportional to q_iN(mu_i,sig2_i).
Usage
ncind(y, mu, sig, q)
Arguments
y |
vector of data |
mu |
vector of component means |
sig |
vector of component standard deviations |
q |
vector of component weights |
Value
Sample from {1,...,k}
Plot posterior summaries from a fitted dsp model
Description
Visualize posterior samples for a selected parameter from a fitted
dsp object. The parameter to plot is chosen with type, which must name
one of the parameters returned by par_names() and defaults to "mu".
Depending on the dimension of the selected posterior samples, the
function produces either a posterior density plot, a time-series plot
with credible intervals, or a multi-panel time-series plot.
Usage
## S3 method for class 'dsp'
plot(
x,
type = "mu",
true_values = NULL,
times = NULL,
y_obs = NULL,
include_joint_bands = FALSE,
alpha = 0.05,
xlab = NULL,
ylab = NULL,
main = NULL,
xlim = NULL,
ylim = NULL,
mar = NULL,
par_args = list(),
legend = TRUE,
legend_cex = 1,
legend_pt_cex = 2,
nr = NULL,
nc = NULL,
cp_thres = 0.5,
...
)
Arguments
x |
an object of class |
type |
character string giving the parameter name to visualize; must be one of the parameters returned by |
true_values |
optional ground-truth values to overlay on the plot. For scalar parameters, this should be a length-1 numeric value; for time-varying parameters, a |
times |
optional vector of observation points. If |
y_obs |
optional vector of observed data point of length T. Only for |
include_joint_bands |
logical; if |
alpha |
Specifies the posterior interval and band credibility level as |
xlab |
optional x-axis label. If |
ylab |
optional y-axis label. If |
main |
optional plot title. For multi-panel plots, this may be either a single title or a vector of titles of length equal to the number of panels. |
xlim |
optional x-axis limits passed to the plotting routine. |
ylim |
optional y-axis limits passed to the plotting routine. |
mar |
optional numeric vector of length 4 giving plot margins, passed to |
par_args |
optional named list of additional graphical parameters passed to |
legend |
logical; if |
legend_cex |
numeric scaling factor for legend text size. |
legend_pt_cex |
numeric scaling factor for legend symbol size. |
nr |
optional number of rows in the plotting layout for multi-panel ( |
nc |
optional number of columns in the plotting layout for multi-panel ( |
cp_thres |
(default 0.5) cutoff proportion for percentage of posterior samples exceeding the threshold needed to label a changepoint |
... |
additional graphical arguments passed to the main plotting call, such as |
Details
The plotting behavior depends on the dimension of the posterior samples stored in x$mcmc_output[[type]]:
-
1D (scalar parameter): A density-style summary is produced using a histogram with an overlaid kernel density estimate. The posterior mean and equal-tailed
(1-\alpha)100\%credible interval are marked, and the true value is added if supplied throughtrue_values. -
2D (time-varying parameter): A time-series plot is produced showing the posterior mean together with equal-tailed pointwise credible intervals. If
include_joint_bands = TRUEand the parameter is one ofzeta,omega,ypred, ormu, simultaneous credible bands are also displayed. Iftrue_valuesis provided, the ground truth is overlaid. -
3D (multi-parameter time-varying quantity): A multi-panel collection of time-series plots is produced, one panel for each slice of the third dimension. Each panel shows the posterior mean, pointwise credible intervals, optional joint bands when supported, and optional ground-truth values. The panel layout is controlled by
nrandnc; if omitted, a near-square layout is chosen automatically.
Axis labels, titles, plotting limits, margins, legend display, and additional graphical settings can be customized through xlab, ylab, main, xlim, ylim, mar, legend, legend_cex, legend_pt_cex, and par_args.
The x-axis values are taken from times. If times is not supplied, evenly spaced points on [0,1] are used. For "evol_sigma_t2", the first D entries, which are the variances of the initial states, are removed before plotting.
For fitted changepoint models, changepoint annotations may be added when supported by the plotted parameter and the corresponding latent components are present in the MCMC output.
Value
No return value, called for side effects
References
Crainiceanu, C. M., Ruppert, D., Carroll, R. J., Joshi, A., and Goodner, B. (2007). Spatially adaptive Bayesian penalized splines with heteroscedastic errors. Journal of Computational and Graphical Statistics, 16(2), 265–288. doi:10.1198/106186007X208768
Krivobokova, T., Kneib, T., and Claeskens, G. (2010). Simultaneous confidence bands for penalized spline estimators. Journal of the American Statistical Association, 105(490), 852–863. doi:10.1198/jasa.2010.tm09165
Examples
set.seed(200)
signal = c(rep(0, 50), rep(10, 50))
noise = rep(1, 100)
noise_var = rep(1, 100)
for (k in 2:100){
noise_var[k] = exp(0.9*log(noise_var[k-1]) + rnorm(1, 0, 0.5))
noise[k] = rnorm(1, 0, sqrt(noise_var[k])) }
y = signal + noise
model_spec = dsp_spec(family = "gaussian", model = "changepoint",
D = 1, useAnom = TRUE, obsSV = "SV")
mcmc_output = dsp_fit(y, model_spec = model_spec, nsave = 200, nburn = 200)
# Estimated posterior mean vs ground truth
plot(mcmc_output, type = "mu", true_values = signal)
# Estimated innovation variance vs ground truth for illustration only
plot(mcmc_output, type = "obs_sigma_t2", true_values = noise^2)
Posterior predictive summaries
Description
Posterior predictive summaries
Usage
## S3 method for class 'dsp'
predict(object, cp_thres = deprecated(), cp_prop = deprecated(), ...)
Arguments
object |
object of class dsp from |
cp_thres, cp_prop |
Deprecated. Changepoint
detection has moved to |
... |
|
Details
For every model, this method returns fitted(object, pars = "ypred", ...):
pointwise summaries of the posterior predictive distribution of a new
observation at each fitted time point. Its quantiles give prediction
intervals, which include the observation noise. For summaries of the
conditional mean \mu_t instead, use fitted(object, pars = "mu").
Missing values in y are drawn from the posterior predictive distribution
during fitting, so predict() imputes them. In particular, padding y
with NA at the end before fitting gives forecasts at those time points.
For regression, the covariates must be supplied in X for every time
point, including those with missing y; prediction at new covariate
values without refitting is not supported.
Changepoints of a changepoint model are returned by changepoints().
Value
A matrix with one row per time point of the fitted series, containing the posterior predictive mean and quantiles. The default quantiles are 2.5%, 25%, 50%, 75%, and 97.5%.
If the deprecated cp_thres or cp_prop is supplied for a changepoint
model, the return value of earlier versions: if cp_prop = FALSE, an
integer vector of the indices of detected changepoints; if
cp_prop = TRUE, a list with these indices in cp_t and, in cp_prop,
the posterior probabilities of threshold exceedance at all T time
points, with NA at the first D.
See Also
Examples
set.seed(200)
signal = c(rep(0, 50), rep(10, 50))
y = signal + rnorm(100)
# Withhold the last five observations to forecast them
y_f <- y
y_f[96:100] <- NA
spec_smooth <- dsp_spec(family = "gaussian", model = "smoothing", D = 1)
fit_smooth <- dsp_fit(y_f, spec_smooth, nsave = 200, nburn = 200)
tail(predict(fit_smooth, probs = c(0.025, 0.975)), 5)
# The conditional mean, without observation noise
tail(fitted(fit_smooth, pars = "mu", probs = c(0.025, 0.975)), 5)
Print a summary of a fitted dsp model
Description
Print a summary of a fitted dsp model
Usage
## S3 method for class 'summary.dsp'
print(x, digits = max(3L, getOption("digits") - 3L), ...)
Arguments
x |
object of class |
digits |
number of significant digits to print |
... |
currently not used |
Value
x, invisibly.
Objects exported from other packages
Description
These objects are imported from other packages. Follow the links below to see their documentation.
- coda
Extract response residuals
Description
Subtract the posterior mean of the stored mu process from the original
observations. For changepoint models, these residuals include any additive
anomaly component rather than subtracting it separately.
Usage
## S3 method for class 'dsp'
residuals(object, y = object$y, ...)
Arguments
object |
a fitted |
y |
original observations. Defaults to the observations retained by
|
... |
currently unused. |
Value
A vector of response residuals, with NA at originally missing
observations. No standardization by the observation variance is applied.
See Also
Sample the AR(1) coefficient(s)
Description
Compute one draw of the AR(1) coefficient in a model with Gaussian innovations and time-dependent innovation variances. In particular, we use the sampler for the log-volatility AR(1) process with the parameter-expanded Polya-Gamma sampler. The sampler also applies to a multivariate case with independent components.
Usage
sampleAR1(h_yc, h_phi, h_sigma_eta_t, prior_dhs_phi = NULL)
Arguments
h_yc |
the |
h_phi |
the |
h_sigma_eta_t |
the |
prior_dhs_phi |
the parameters of the prior for the log-volatility AR(1) coefficient |
Value
p x 1 vector of sampled AR(1) coefficient(s)
Note
For the standard AR(1) case, p = 1. However, the function applies more
generally for sampling p > 1 independent AR(1) processes (jointly).
Sampler for first or second order random walk (RW) Gaussian dynamic linear model (DLM)
Description
Compute one draw of the T x 1 state variable mu in a DLM using back-band substitution methods.
This model is equivalent to the Bayesian trend filtering (BTF) model, assuming appropriate
(shrinkage/sparsity) priors for the evolution errors.
Usage
sampleBTF(
y,
obs_sigma_t2,
evol_sigma_t2,
D = 1,
loc_obs = NULL,
chol0 = NULL,
prior_mean = NULL
)
Arguments
y |
the |
obs_sigma_t2 |
the |
evol_sigma_t2 |
the |
D |
the degree of differencing (one or two) |
loc_obs |
list of the row and column indices to fill in a band-sparse matrix |
chol0 |
(optional) the |
prior_mean |
optional (default is NULL); numeric |
Value
T x 1 vector of simulated states
Note
Missing entries (NAs) are not permitted in y. Imputation schemes are available.
Sampler for first or second order random walk (RW) Gaussian dynamic linear model (DLM)
Description
Compute one draw of the p x 1 B-spline basis coefficients beta in a DLM using
back-band substitution methods. The coefficients are penalized with a prior on the D = 0, D = 1, or
D = 2 differences. This model is equivalent to the Bayesian trend filtering (BTF) model
applied to p x 1 vector of equally-spaced B-spline coefficients, with the basis matrix
serving as a design matrix in the observation equation.
Usage
sampleBTF_bspline(
y,
X,
obs_sigma2,
evol_sigma_t2,
XtX_bands,
Xty = NULL,
D = 1
)
Arguments
y |
the |
X |
the |
obs_sigma2 |
the scalar observation error variance |
evol_sigma_t2 |
the |
XtX_bands |
list with 4 vectors consisting of the 4-bands of XtX = crossprod(X) (one-time cost) |
Xty |
the |
D |
the degree of differencing (zero, one, or two) |
Value
p x 1 vector of simulated basis coefficients beta
Note
Missing entries (NAs) are not permitted in y. Imputation schemes are available.
Sampler for first or second order random walk (RW) Gaussian dynamic linear model (DLM)
Description
Compute one draw of the T x p state variable beta in a DLM using back-band substitution methods.
This model is equivalent to the Bayesian trend filtering (BTF) model applied to p
dynamic regression coefficients corresponding to the design matrix X,
assuming appropriate (shrinkage/sparsity) priors for the evolution errors.
Usage
sampleBTF_reg(y, X, obs_sigma_t2, evol_sigma_t2, XtX, D = 1, chol0 = NULL)
Arguments
y |
the |
X |
the |
obs_sigma_t2 |
the |
evol_sigma_t2 |
the |
XtX |
the |
D |
the degree of differencing (one or two) |
chol0 |
(optional) the |
Value
T x p matrix of simulated dynamic regression coefficients beta
Note
Missing entries (NAs) are not permitted in y. Imputation schemes are available.
(Backfitting) sampler for first or second order random walk (RW) Gaussian dynamic linear model (DLM)
Description
Compute one draw of the T x p state variable beta in a DLM using back-band substitution methods.
This model is equivalent to the Bayesian trend filtering (BTF) model applied to p
dynamic regression coefficients corresponding to the design matrix X,
assuming appropriate (shrinkage/sparsity) priors for the evolution errors. The sampler
here uses a backfitting method that draws each predictor j=1,...,p conditional on the
other predictors (and coefficients), which leads to a faster O(Tp) algorithm.
However, the MCMC may be less efficient.
Usage
sampleBTF_reg_backfit(y, X, beta, obs_sigma_t2, evol_sigma_t2, D = 1)
Arguments
y |
the |
X |
the |
beta |
the |
obs_sigma_t2 |
the |
evol_sigma_t2 |
the |
D |
the degree of differencing (one or two) |
Value
T x p matrix of simulated dynamic regression coefficients beta
Note
Missing entries (NAs) are not permitted in y. Imputation schemes are available.
Sampler for first or second order random walk (RW) Gaussian dynamic linear model (DLM) with additional shrinkage to zero
Description
Compute one draw of the T x 1 state variable mu in a DLM using back-band substitution methods.
This model is equivalent to the Bayesian trend filtering (BTF) model, assuming appropriate
(shrinkage/sparsity) priors for the evolution errors, with an additional shrinkage-to-zero prior.
Usage
sampleBTF_sparse(
y,
obs_sigma_t2,
evol_sigma_t2,
zero_sigma_t2,
D = 1,
chol0 = NULL
)
Arguments
y |
the |
obs_sigma_t2 |
the |
evol_sigma_t2 |
the |
zero_sigma_t2 |
the |
D |
the degree of differencing (one or two) |
chol0 |
(optional) the |
Value
T x 1 vector of simulated states
Note
Missing entries (NAs) are not permitted in y. Imputation schemes are available.
Sample the dynamic shrinkage process parameters
Description
Compute one draw for each of the parameters in the dynamic shrinkage process
for the special case in which the shrinkage parameter kappa ~ Beta(alpha, beta)
with alpha = beta. The primary example is the dynamic horseshoe process with
alpha = beta = 1/2.
Usage
sampleDSP(
omega,
evolParams,
sigma_e = 1,
loc = NULL,
prior_dhs_phi = c(10, 2),
alphaPlusBeta = 1
)
Arguments
omega |
|
evolParams |
list of parameters to be updated (see Value below) |
sigma_e |
the observation error standard deviation; for (optional) scaling purposes |
loc |
list of the row and column indices to fill in a band-sparse matrix |
prior_dhs_phi |
the parameters of the prior for the log-volatility AR(1) coefficient |
alphaPlusBeta |
For the symmetric prior kappa ~ Beta(alpha, beta) with alpha=beta, specify the sum [alpha + beta] |
Value
List of relevant components:
the
T x pevolution error standard deviationssigma_wt,the
T x plog-volatilityht, thep x 1log-vol unconditional mean(s)dhs_mean,the
p x 1log-vol AR(1) coefficient(s)dhs_phi,the
T x plog-vol innovation standard deviationssigma_eta_tfrom the Polya-Gamma priors,the
p x 1initial log-vol SDsigma_eta_0,and the mean of log-vol means
dhs_mean0(relevant whenp > 1)
Note
The priors induced by prior_dhs_phi all imply a stationary (log-) volatility process.
Sample the parameters for the initial state variance
Description
The initial state SDs are assumed to follow half-Cauchy priors, C+(0,A), where the SDs may be common or distinct among the states.
Usage
sampleEvol0(mu0, evolParams0, commonSD = FALSE, A = 1)
Arguments
mu0 |
|
evolParams0 |
list of relevant components (see below) |
commonSD |
logical; if TRUE, use common SDs (otherwise distict) |
A |
prior scale parameter from the half-Cauchy prior, C+(0,A) |
Details
This function samples the parameters for a PX-Gibbs sampler.
Value
List of relevant components:
the p x 1 evolution error SD sigma_w0
and the p x 1 parameter-expanded RV's px_sigma_w0
Sample the evolution error variance parameters
Description
Compute one draw of evolution error variance parameters under the various options:
dynamic horseshoe prior ('DHS');
horseshoe prior ('HS');
normal-inverse-gamma prior ('NIG').
Usage
sampleEvolParams(
omega,
evolParams,
sigma_e = 1,
evol_error = "DHS",
loc = NULL
)
Arguments
omega |
|
evolParams |
list of parameters pertaining to each |
sigma_e |
the observation error standard deviation; for (optional) scaling purposes |
evol_error |
the evolution error distribution; must be one of 'DHS' (dynamic horseshoe prior), 'HS' (horseshoe prior), or 'NIG' (normal-inverse-gamma prior) |
loc |
list of the row and column indices to fill in a band-sparse matrix |
Value
List of relevant components in evolParams: sigma_wt, the T x p matrix of evolution standard deviations,
and additional parameters associated with the DHS and HS priors.
Note
The list evolParams is specific to each evol_error type,
but in each case contains the evolution error standard deviations sigma_wt.
To avoid scaling by the observation standard deviation sigma_e,
simply use sigma_e = 1 in the functional call.
Sample a Gaussian vector using the fast sampler of Bhattacharya et al.
Description
Sample from N(mu, Sigma) where Sigma = solve(crossprod(Phi) + solve(D)) and mu = Sigma*crossprod(Phi, alpha):
Usage
sampleFastGaussian(Phi, Ddiag, alpha)
Arguments
Phi |
|
Ddiag |
|
alpha |
|
Value
Draw from N(mu, Sigma), which is p x 1, and is computed in O(n^2*p)
Note
Assumes D is diagonal, but extensions are available
Sample the AR(1) unconditional means
Description
Compute one draw of the unconditional means in an AR(1) model with Gaussian innovations and time-dependent innovation variances. In particular, we use the sampler for the log-volatility AR(1) process with the parameter-expanded Polya-Gamma sampler. The sampler also applies to a multivariate case with independent components.
Usage
sampleLogVolMu(h, h_mu, h_phi, h_sigma_eta_t, h_sigma_eta_0, h_log_scale = 0)
Arguments
h |
the |
h_mu |
the |
h_phi |
the |
h_sigma_eta_t |
the |
h_sigma_eta_0 |
the standard deviations of initial log-vols |
h_log_scale |
prior mean from scale mixture of Gaussian (Polya-Gamma) prior, e.g. log(sigma_e^2) or dhs_mean0 |
Value
a list containing
the sampled mean(s)
dhs_meanandthe sampled precision(s)
dhs_mean_prec_jfrom the Polya-Gamma parameter expansion
Sample the mean of AR(1) unconditional means
Description
Compute one draw of the mean of unconditional means in an AR(1) model with Gaussian innovations and time-dependent innovation variances (for p > 1). More generally, the sampler applies to the "mean" parameter (on the log-scale) for a Polya-Gamma parameter expanded hierarchical model.
Usage
sampleLogVolMu0(h_mu, h_mu0, dhs_mean_prec_j, h_log_scale = 0)
Arguments
h_mu |
the |
h_mu0 |
the previous mean of unconditional means |
dhs_mean_prec_j |
the |
h_log_scale |
prior mean from scale mixture of Gaussian (Polya-Gamma) prior, e.g. log(sigma_e^2) |
Value
The sampled mean parameter dhs_mean0
Note
This sampler is particularly for p > 1 and the setting in which we want hierarchical
shrinkage effects, e.g. predictor- and time-dependent shrinkage, predictor-dependent shrinkage,
and global shrinkage, with a natural hierarchical ordering.
Sample the latent log-volatilities
Description
Compute one draw of the log-volatilities using a discrete mixture of Gaussians
approximation to the likelihood (see Omori, Chib, Shephard, and Nakajima, 2007)
where the log-vols are assumed to follow an AR(1) model with time-dependent
innovation variances. More generally, the code operates for p independent
AR(1) log-vol processes to produce an efficient joint sampler in O(Tp) time.
Usage
sampleLogVols(
h_y,
h_prev,
h_mu,
h_phi,
h_sigma_eta_t,
h_sigma_eta_0,
loc = NULL
)
Arguments
h_y |
the |
h_prev |
the |
h_mu |
the |
h_phi |
the |
h_sigma_eta_t |
the |
h_sigma_eta_0 |
the |
loc |
list of the row and column indices to fill in a band-sparse matrix |
Value
T x p matrix of simulated log-vols
Note
For Bayesian trend filtering, p = 1. More generally, the sampler allows for
p > 1 but assumes (contemporaneous) independence across the log-vols for j = 1,...,p.
Sampler for the stochastic volatility parameters
Description
Compute one draw of the normal stochastic volatility parameters. The model assumes an AR(1) for the log-volatility.
Usage
sampleSVparams(omega, svParams)
Arguments
omega |
|
svParams |
list of parameters to be updated |
Value
List of relevant components in svParams: sigma_wt, the T x p matrix of standard deviations,
and additional parameters associated with SV model.
Sampler for the stochastic volatility parameters using same functions as DHS prior
Description
Compute one draw of the normal stochastic volatility parameters. The model assumes an AR(1) for the log-volatility.
Usage
sampleSVparams0(omega, svParams)
Arguments
omega |
|
svParams |
list of parameters to be updated |
Value
List of relevant components in svParams: sigma_wt, the T x p matrix of standard deviations,
and additional parameters associated with SV model.
Sample components of the 10-component Gaussian mixture of Omori et al. (2007)
Description
Samples from the conditional posterior distribution of the log(\chi^2) distribution
by approximating it with the mixture Gaussian distribution described in Omori et al. 2007.
Usage
sample_j_wrap(Td, obs = NULL)
Arguments
Td |
length of the vector |
obs |
|
Value
Dataframe containing the posterior samples: mean and variance for the mixture component.
Note
When the obs is not not specified, the components are samples from the prior distribution.
Check inputs and call the C++ band-sparse Gaussian sampler
Description
Check inputs and call the C++ band-sparse Gaussian sampler
Usage
sample_mat_c(row_ind, col_ind, mat_val, mat_l, num_inp, linht, rd, D)
Arguments
row_ind |
list of the row indices to fill in the bandsparse matrix |
col_ind |
list of the columns indices to fill in the bandsparse matrix |
mat_val |
list of the values to fill in the bandsparse matrix |
mat_l |
dimension of the band-sparse matrix |
num_inp |
number of non-zero elements in the bandsparse matrix |
linht |
|
rd |
|
D |
the degree of differencing for changepoint |
Compute simultaneous band scores (SimBaS)
Description
Compute simultaneous band scores (SimBaS) from Meyer et al. (2015, Biometrics, 71(3), 563–574, doi:10.1111/biom.12299). SimBaS uses MC(MC) simulations of a function of interest to compute the minimum alpha such that the joint credible bands at the alpha level do not include zero. This quantity is computed for each grid point (or observation point) in the domain of the function.
Usage
simBaS(sampFuns)
Arguments
sampFuns |
|
Value
m x 1 vector of simBaS, NA at points with no posterior variation
Note
The input needs not be curves: the simBaS may be computed for vectors to achieve a multiplicity adjustment.
The minimum of the returned value, PsimBaS_t,
over the domain t is the Global Bayesian P-Value (GBPV) for testing
whether the function is zero everywhere.
Simulate noisy observations from a dynamic regression model
Description
Simulates data from a time series regression with dynamic regression coefficients.
The dynamic regression coefficients are simulated as a Gaussian random walk,
where jumps occur with a pre-specified probability sparsity.
The coefficients are initialized by a N(0,1) simulation.
Usage
simRegression(
nT = 200,
p = 20,
p_0 = 15,
sparsity = 0.05,
RSNR = 5,
ar1 = 0,
include_plot = FALSE
)
Arguments
nT |
number of time points |
p |
number of predictors (total) |
p_0 |
number of true zero regression terms |
sparsity |
the probability of a jump (i.e., a change in the dynamic regression coefficient) |
RSNR |
root-signal-to-noise ratio |
ar1 |
the AR(1) coefficient for the predictors X; default is zero for iid N(0,1) predictors |
include_plot |
logical; if TRUE, include a plot of the simulated data and the true curve |
Value
a list containing
the simulated function
ythe simulated predictors
Xthe simulated dynamic regression coefficients
beta_truethe true function
mu_truethe true observation standard deviation
sigma_true
Note
The root-signal-to-noise ratio is defined as RSNR = (sd of true function)/(sd of noise).
Simulate noisy observations from a dynamic regression model
Description
Simulates data from a time series regression with dynamic regression coefficients.
The dynamic regression coefficients are selected using the options from the
simUnivariate() function in the wmtsa package.
Usage
simRegression0(
signalNames = c("bumps", "blocks"),
nT = 200,
RSNR = 10,
p_0 = 5,
include_intercept = TRUE,
scale_all = TRUE,
include_plot = TRUE,
ar1 = 0
)
Arguments
signalNames |
vector of strings matching the "name" argument in the |
nT |
number of points |
RSNR |
root-signal-to-noise ratio |
p_0 |
number of true zero regression terms to include |
include_intercept |
logical; if TRUE, the first column of X is 1's |
scale_all |
logical; if TRUE, scale all regression coefficients to [0,1] |
include_plot |
logical; if TRUE, include a plot of the simulated data and the true curve |
ar1 |
the AR(1) coefficient for the predictors X; default is zero for iid N(0,1) predictors |
Value
a list containing
the simulated function
ythe simulated predictors
Xthe simulated dynamic regression coefficients
beta_truethe true function
mu_truethe true observation standard deviation
sigma_true
Note
The number of predictors is p = length(signalNames) + p_0.
The root-signal-to-noise ratio is defined as RSNR = (sd of true function)/(sd of noise).
Generate univariate signals of different types
Description
Using code from the archived wmtsa package
Usage
simUnivariate(name, n = 1024, snr = Inf)
Arguments
name |
character string of name of the test wavelet signal to be generated; one of "dirac", "kronecker", "heavisine", "bumps", "blocks", "doppler", "ramp", "cusp", "crease", "sing", "hisine", "losine", "linchirp", "twochirp", "quadchirp", "mishmash1", "mishmash2", "mishmash3", "levelshift", "jumpsine", "gauss", "patches", "linear", "quadratic", "cubic"; |
n |
length of the series; defaults to 1024 points; increasing n infills the time series |
snr |
desired signal-to-noise ratio; default |
Value
A numeric vector the same length as n.
Examples
nms <- c("blocks", "linchirp", "mishmash1", "bumps")
z <- lapply(nms, simUnivariate)
Compute the spectrum of an AR(p) model
Description
Compute the spectrum of an AR(p) model
Usage
spec_dsp(ar_coefs, sigma_e, n.freq = 500)
Arguments
ar_coefs |
(p x 1) vector of AR(p) coefficients |
sigma_e |
observation standard deviation |
n.freq |
number of frequencies at which to evaluate the spectrum |
Value
A (n.freq x 2) matrix where the first column is the frequencies and the second column is the spectrum evaluated at that frequency
Pointwise posterior summaries of one parameter
Description
Pointwise posterior summaries of one parameter
Usage
summarize_draws(samps, probs)
Arguments
samps |
posterior draws of one parameter, with the draws in the first dimension: a vector, a matrix or a three-dimensional array |
probs |
numeric vector of probabilities for the posterior quantiles |
Value
A named vector for a scalar parameter, a matrix with one row per index for a vector parameter, or an array whose third dimension holds the summaries for a matrix parameter.
Summarize a fitted dsp model
Description
Produces a compact summary of a fitted model: the model specification, the MCMC settings, the deviance information criterion and one line per parameter.
Usage
## S3 method for class 'dsp'
summary(object, pars, probs = c(0.025, 0.975), ess = FALSE, ...)
Arguments
object |
object of class dsp from |
pars |
parameter names to summarize; defaults to all parameters
returned by |
probs |
numeric vector of length two giving the probabilities of the posterior interval reported for scalar parameters. Defaults to c(0.025, 0.975) |
ess |
logical; if TRUE, also report the minimum and median pointwise effective sample size of each time-varying or vector parameter. Defaults to FALSE, because this requires one spectral estimate per time point and takes several seconds for long series. |
... |
currently not used |
Details
Scalar parameters are summarized by their posterior mean, standard
deviation, interval and effective sample size. A parameter indexed by time
(or by basis function, or by predictor) is summarized in one line by its
length and the range of its pointwise posterior means, and, if
ess = TRUE, the minimum and median of its pointwise effective sample
sizes. A regression coefficient array beta is reported one line per
predictor. The first D entries of evol_sigma_t2, the
variances of the initial states, are reported on their own line, labelled
by their indices, since they have a different prior from the remaining
evolution variances.
Effective sample sizes are computed by coda::effectiveSize(). Elements
with no posterior variation, such as the fixed initial values of the
evolution variances, are excluded from the minimum and median.
Pointwise posterior summaries of a time-varying parameter are returned by
fitted.dsp(), and the posterior draws by as.mcmc.dsp(), for which the
diagnostic functions in coda are available.
Value
An object of class summary.dsp, a list with components
- model_spec
the
dsp_spec()object of the fitted model- mcpar
the number of saved draws, the burn-in and
nskip- nobs
the number of time points
- DIC
the data frame returned by
DIC(), orNULLif the DIC was not computed- scalars
a matrix with one row per scalar parameter and columns
mean,sd, the two quantiles andess, orNULLif there are none- vectors
a data frame with one row per non-scalar parameter and columns
length,mean_minandmean_max, and, ifess = TRUE,ess_minandess_median; orNULLif there are none
See Also
fitted.dsp(), DIC(), as.mcmc.dsp()
Examples
set.seed(200)
signal = c(rep(0, 50), rep(10, 50))
noise = rep(1, 100)
noise_var = rep(1, 100)
for (k in 2:100){
noise_var[k] = exp(0.9*log(noise_var[k-1]) + rnorm(1, 0, 0.5))
noise[k] = rnorm(1, 0, sqrt(noise_var[k])) }
y = signal + noise
model_spec = dsp_spec(family = "gaussian", model = "changepoint",
D = 1, useAnom = TRUE, obsSV = "SV")
mcmc_output = dsp_fit(y, model_spec = model_spec, nsave = 200, nburn = 200)
summary(mcmc_output)
# pointwise summaries of the mean function
head(fitted(mcmc_output))
Initializer for location indices for filling in band-sparse matrix
Description
Create row and column indices for locations of symmetric band-sparse matrix. Starts with the locations of the diagonal, proceed with upper-diagonals, followed by lower-diagonals.
Usage
t_create_loc(len, D)
Arguments
len |
length of the diagonal of the band-sparse matrix |
D |
number of super-diagonals to include for the band-sparse |
Value
a list containing
the row indices
randthe column indices
c
Initialize the evolution error variance parameters
Description
Compute initial values for evolution error variance parameters under the dynamic horseshoe prior
Usage
t_initEvolParams_no(y, D, omega)
Arguments
y |
the |
D |
degree of differencing (D = 1, or D = 2) |
omega |
|
Value
List of relevant components: sigma_wt, the T vector of evolution standard deviations,
and additional parameters associated with the DHS priors.
Initialize the anomaly component parameters
Description
Compute initial values for the horseshoe+ prior (Bhadra et al. 2017) on the anomaly component, as in Wu et al. (2024).
Usage
t_initEvolZeta_ps(zeta)
Arguments
zeta |
|
Value
List of relevant components: sigma_wt, the T - D vector of standard deviations,
and the auxiliary variables of the inverse-gamma representation of the prior.
References
Bhadra, A., Datta, J., Polson, N. G., and Willard, B. (2017). The horseshoe+ estimator of ultra-sparse signals. Bayesian Analysis, 12(4), 1105–1131. doi:10.1214/16-BA1028
Wu, H., Schafer, T. L. J., and Matteson, D. S. (2024). Trend and variance adaptive Bayesian changepoint analysis and local outlier scoring. Journal of Business & Economic Statistics. doi:10.1080/07350015.2024.2362269
Initialize the stochastic volatility parameters
Description
Compute initial values for normal stochastic volatility parameters. The model assumes an AR(1) for the log-volatility.
Usage
t_initSV(omega)
Arguments
omega |
|
Value
List of relevant components: sigma_wt, the T vector of standard deviations,
and additional parameters (unconditional mean, AR(1) coefficient, and standard deviation).
Sample the TAR(1) coefficients
Description
Compute one draw of the TAR(1) coefficients in a model with Gaussian innovations and time-dependent innovation variances. In particular, we use the sampler for the log-volatility TAR(1) process with the parameter-expanded Polya-Gamma sampler. The sampler also applies to a multivariate case with independent components.
Usage
t_sampleAR1(h_yc, h_phi, h_phi2, h_sigma_eta_t, h_st, prior_dhs_phi = NULL)
Arguments
h_yc |
the |
h_phi |
the |
h_phi2 |
the |
h_sigma_eta_t |
the |
h_st |
the |
prior_dhs_phi |
the parameters of the prior for the log-volatility AR(1) coefficient |
Value
2 vector of sampled TAR(1) coefficient(s)
Sampler for first or second order random walk (RW) Gaussian dynamic linear model (DLM)
Description
Compute one draw of the T state variable mu in a DLM using back-band substitution methods.
This model is equivalent to the Bayesian trend filtering (BTF) model, assuming appropriate
(shrinkage/sparsity) priors for the evolution errors.
Usage
t_sampleBTF(y, obs_sigma_t2, evol_sigma_t2, D = 1, loc_obs)
Arguments
y |
the |
obs_sigma_t2 |
the |
evol_sigma_t2 |
the |
D |
the degree of differencing (one or two) |
loc_obs |
list of the row and column indices to fill in a band-sparse matrix |
Value
T x 1 vector of simulated states
Note
Missing entries (NAs) are not permitted in y. Imputation schemes are available.
Sample the thresholded dynamic shrinkage process parameters
Description
Compute one draw for each of the parameters in the thresholded dynamic shrinkage process
for the special case in which the shrinkage parameter kappa ~ Beta(alpha, beta)
with alpha = beta = 1/2.
Usage
t_sampleEvolParams(
omega,
evolParams,
D = 1,
sigma_e = 1,
lower_b,
upper_b,
loc,
prior_dhs_phi = c(20, 1),
alphaPlusBeta = 1
)
Arguments
omega |
|
evolParams |
list of parameters to be updated (see Value below) |
D |
the degree of differencing (one or two) |
sigma_e |
the observation error standard deviation; for (optional) scaling purposes |
lower_b |
the lower bound in the uniform prior of the threshold variable |
upper_b |
the upper bound in the uniform prior of the threshold variable |
loc |
list of the row and column indices to fill in a band-sparse matrix |
prior_dhs_phi |
the parameters of the prior for the log-volatility AR(1) coefficient |
alphaPlusBeta |
For the symmetric prior kappa ~ Beta(alpha, beta) with alpha=beta, specify the sum [alpha + beta] |
Value
List of relevant components:
the
Tevolution error standard deviationssigma_wt,the
Tlog-volatilityht,the
1log-vol unconditional mean(s)dhs_mean,the
1log-vol AR(1) coefficient(s)dhs_phi,the
1log-vol correction coefficient(s)dhs_phi2,the
Tlog-vol innovation standard deviationssigma_eta_tfrom the Polya-Gamma priors,the
1initial log-vol SDsigma_eta_0,the
1threshold parameter r
Note
The priors induced by prior_dhs_phi all imply a stationary (log-) volatility process.
Sampler for the anomaly component parameters
Description
Compute one draw of the parameters of the horseshoe+ prior on the anomaly
component, as in Wu et al. (2024). As in the code of that paper, the
additional local scale has a half-Cauchy prior with scale 4, so its
auxiliary variable eta_v has rate 1/16.
Usage
t_sampleEvolZeta_ps(omega, evolParams)
Arguments
omega |
|
evolParams |
list of parameters to be updated |
Value
List of relevant components in evolParams: sigma_wt,
the T - D vector of standard deviations, and the auxiliary variables of the inverse-gamma representation of the prior.
Sample the TAR(1) unconditional means
Description
Compute one draw of the unconditional means in an TAR(1) model with Gaussian innovations and time-dependent innovation variances. In particular, we use the sampler for the log-volatility TAR(1) process with the parameter-expanded Polya-Gamma sampler. The sampler also applies to a multivariate case with independent components.
Usage
t_sampleLogVolMu(
h,
h_mu,
h_phi,
h_phi2,
h_sigma_eta_t,
h_sigma_eta_0,
h_st,
h_log_scale = 0
)
Arguments
h |
the |
h_mu |
the |
h_phi |
the |
h_phi2 |
the |
h_sigma_eta_t |
the |
h_sigma_eta_0 |
the standard deviations of initial log-vols |
h_st |
the |
h_log_scale |
prior mean from scale mixture of Gaussian (Polya-Gamma) prior, e.g. log(sigma_e^2) or dhs_mean0 |
Value
the sampled mean(s) dhs_mean
Sample the latent log-volatilities
Description
Compute one draw of the log-volatilities using a discrete mixture of Gaussians
approximation to the likelihood (see Omori, Chib, Shephard, and Nakajima, 2007)
where the log-vols are assumed to follow an TAR(1) model with time-dependent
innovation variances. More generally, the code operates for p independent
TAR(1) log-vol processes to produce an efficient joint sampler in O(Tp) time.
Usage
t_sampleLogVols(
h_y,
h_prev,
h_mu,
h_phi,
h_phi2,
h_sigma_eta_t,
h_sigma_eta_0,
h_st,
loc
)
Arguments
h_y |
the |
h_prev |
the |
h_mu |
the |
h_phi |
the |
h_phi2 |
the |
h_sigma_eta_t |
the |
h_sigma_eta_0 |
the |
h_st |
the |
loc |
list of the row and column indices to fill in the band-sparse matrix in the sampler |
Value
T x p vector of simulated log-vols
Note
For Bayesian trend filtering, p = 1. More generally, the sampler allows for
p > 1 but assumes (contemporaneous) independence across the log-vols for j = 1,...,p.
Sample the threshold parameter
Description
Compute one draw of the threshold parameter in th TAR(1) model with Gaussian innovations and time-dependent innovation variances. The sampler utilizes metropolis hasting to draw from uniform prior.
Usage
t_sampleR_mh(
h_yc,
h_phi,
h_phi2,
h_sigma_eta_t,
h_sigma_eta_0,
h_st,
h_r,
lower_b,
upper_b,
omega,
D
)
Arguments
h_yc |
the |
h_phi |
the |
h_phi2 |
the |
h_sigma_eta_t |
the |
h_sigma_eta_0 |
the |
h_st |
the |
h_r |
|
lower_b |
the lower bound in the uniform prior of the threshold variable |
upper_b |
the upper bound in the uniform prior of the threshold variable |
omega |
|
D |
the degree of differencing (one or two) |
Value
the sampled threshold value r
Sampler for the stochastic volatility parameters
Description
Compute one draw of the normal stochastic volatility parameters. The model assumes an AR(1) for the log-volatility.
Usage
t_sampleSVparams(omega, svParams)
Arguments
omega |
|
svParams |
list of parameters to be updated |
Value
List of relevant components in svParams: sigma_wt, the T vector of standard deviations,
and additional parameters associated with SV model.
Univariate slice sampler from Neal (2008)
Description
Compute a draw from a univariate distribution using the code provided by Radford M. Neal. The documentation below is also reproduced from Neal (2008).
Usage
uni.slice(
x0,
g,
w = 1,
m = Inf,
lower = -Inf,
upper = +Inf,
gx0 = NULL,
max_iter = 1e+05
)
Arguments
x0 |
Initial point |
g |
Function returning the log of the probability density (plus constant) |
w |
Size of the steps for creating interval (default 1) |
m |
Limit on steps (default infinite) |
lower |
Lower bound on support of the distribution (default -Inf) |
upper |
Upper bound on support of the distribution (default +Inf) |
gx0 |
Value of g(x0), if known (default is not known) |
max_iter |
Maximum number of log-density evaluations allowed in each of the stepping-out and shrinkage phases (default 1e5). Exceeding it is an error. |
Value
The point sampled, with its log density attached as an attribute.
Note
The log density function may return -Inf for points outside the support of the distribution. If a lower and/or upper bound is specified for the support, the log density function will not be called outside such limits.
The log density at the initial point must be finite. If it is not, or if
max_iter is exceeded, the function stops with an error instead of
looping without end. These checks do not change the draws whenever the
sampler terminates normally.