| Title: | Variational and Monte Carlo Inference for Bayesian State-Space Models of Count Data |
|---|---|
| Description: | Bayesian inference for a general class of state-space models for count data, providing a unified interface to variational Bayes and Markov chain Monte Carlo. Models are assembled from modular components for the observation distribution, link function, gain function, lag distribution, system equation, and system error, and support Poisson and negative binomial observations together with seasonality terms. The model class and the hybrid variational approximation are described in Tang and Prado (2026) <doi:10.1016/j.csda.2026.108368>. |
| Authors: | Meini Tang [aut, cre] (ORCID: <https://orcid.org/0000-0001-5338-8772>), Raquel Prado [aut] (ORCID: <https://orcid.org/0000-0001-6709-7191>) |
| Maintainer: | Meini Tang <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.1.0 |
| Built: | 2026-10-28 19:30:38 UTC |
| Source: | https://github.com/cran/dgtf |
dgtf_sim objectWraps externally-generated simulated data (e.g. from another
simulator, or a hand-built study) into a dgtf_sim so that the
print() and plot() methods work on it.
as_dgtf_sim(x, model, ...)as_dgtf_sim(x, model, ...)
x |
A list with at least an element |
model |
A |
... |
Unused. |
An object of class dgtf_sim.
as_dgtf_sim() does not check that psi and the parameters in
model match a forward simulation of y. Nothing in the package
reads them automatically, but if you pass them as the truth in a
model check (e.g.
plot(fit, what = "Rt", truth = log1p(exp(sim$psi))), or the
Rt argument of posterior_predict()), use only values that
actually came from a forward simulation under the same model.
Arbitrary numbers produce meaningless comparisons.
# An external simulation is any code that draws from the generative # process described by `mod`. Here dgtf_simulate_model() stands in for # an external simulator, and only `y` and `psi` are kept. mod <- dgtf_hawkes(seasonality = seas_period(1, init = 2)) draw <- dgtf_simulate_model(mod, ntime = 50, seed = 1) raw <- list(y = as.numeric(draw$y), psi = as.numeric(draw$psi)) sim <- as_dgtf_sim(raw, model = mod) plot(sim, what = "Rt")# An external simulation is any code that draws from the generative # process described by `mod`. Here dgtf_simulate_model() stands in for # an external simulator, and only `y` and `psi` are kept. mod <- dgtf_hawkes(seasonality = seas_period(1, init = 2)) draw <- dgtf_simulate_model(mod, ntime = 50, seed = 1) raw <- list(y = as.numeric(draw$y), psi = as.numeric(draw$psi)) sim <- as_dgtf_sim(raw, model = mod) plot(sim, what = "Rt")
Daily counts of newly reported COVID-19 cases in Santa Cruz County, California from July 1, 2020 through December 1, 2021.
covid_scz_2020covid_scz_2020
A numeric vector of length 518.
California Department of Public Health, https://data.chhs.ca.gov/dataset/covid-19-time-series-metrics-by-county-and-state.
The user-facing entry point for inference on a DGTF model. The
function wraps the C++ inference engines and returns an S3
dgtf_fit object supporting the standard methods (print,
summary, coef, predict, and others).
dgtf( y, model, prior = dgtf_prior(), method = c("hva", "mcmc", "vb"), control = NULL, seed = NULL, verbose = FALSE )dgtf( y, model, prior = dgtf_prior(), method = c("hva", "mcmc", "vb"), control = NULL, seed = NULL, verbose = FALSE )
y |
Numeric vector of observed counts (or, in future versions, a matrix for multivariate observations). |
model |
A |
prior |
A |
method |
|
control |
A method-specific control object. When |
seed |
Optional integer seed. |
verbose |
If |
An object of class dgtf_fit.
"hva" (or its synonym "vb"): the hybrid variational
approximation, which combines sequential Monte Carlo smoothing with
variational updates. It is the faster of the two methods and is well
suited to exploratory analysis and model screening. Tuned through
vb_control().
"mcmc": a blocked sampler that updates the latent state
disturbances by Metropolis–Hastings and the static parameters by
Hamiltonian Monte Carlo. It targets the exact posterior and is the
reference method for uncertainty quantification, at a higher
computational cost. Tuned through mcmc_control().
Anything supplied a prior in prior is treated as unknown and
inferred. Anything left out of prior is treated as fixed at the
value supplied to dgtf_model().
mod <- dgtf_hawkes(seasonality = seas_period(1, init = 2)) sim <- dgtf_simulate_model(mod, ntime = 100, seed = 1) prior <- dgtf_prior(W = inv_gamma(1, 1), rho = inv_gamma(1, 1)) # Small tuning values keep the example fast. Use the vb_control() # defaults, or larger values, in real analyses. ctrl <- vb_control(iter = 50, n_sample = 100, n_particle = 100) fit <- dgtf(sim$y, mod, prior, method = "hva", control = ctrl, seed = 1) fit summary(fit) # MCMC targets the exact posterior but is much slower than HVA. fit_mcmc <- dgtf(sim$y, mod, prior, method = "mcmc", control = mcmc_control(iter = 200, warmup = 200), seed = 1) summary(fit_mcmc)mod <- dgtf_hawkes(seasonality = seas_period(1, init = 2)) sim <- dgtf_simulate_model(mod, ntime = 100, seed = 1) prior <- dgtf_prior(W = inv_gamma(1, 1), rho = inv_gamma(1, 1)) # Small tuning values keep the example fast. Use the vb_control() # defaults, or larger values, in real analyses. ctrl <- vb_control(iter = 50, n_sample = 100, n_particle = 100) fit <- dgtf(sim$y, mod, prior, method = "hva", control = ctrl, seed = 1) fit summary(fit) # MCMC targets the exact posterior but is much slower than HVA. fit_mcmc <- dgtf(sim$y, mod, prior, method = "mcmc", control = mcmc_control(iter = 200, warmup = 200), seed = 1) summary(fit_mcmc)
Compares an arbitrary named list of dgtf_fit, dgtf_ppc,
or dgtf_forecast objects on a common set of metrics. The list
must be homogeneous: all fits, all PPCs, or all forecasts.
dgtf_compare(fits, ...)dgtf_compare(fits, ...)
fits |
Named list of objects of homogeneous class. |
... |
For fit lists, the optional arguments |
For fit lists, the columns are the in-sample posterior predictive
scoring metrics computed via posterior_predict(), the static
parameter count, the HVA log marginal likelihood proxy (NA for MCMC),
and the runtime breakdown.
For PPC lists, the columns are the in-sample scoring metrics on the
observed counts and, when the PPC carries a reference
trajectory, the corresponding recovery metrics.
For forecast lists, the columns are the forecast horizon, the number
of forecast draws, and the out-of-sample scoring metrics
(coverage, chi, crps) when held-out truth was
supplied to dgtf_forecast_fit().
A data frame of class dgtf_comparison, one row per
input element. The columns depend on the input class.
Long-form table stacking per-parameter posterior summaries for every
fit in fits, with an added model column. One row per
(parameter, fit) pair. Use this for the detailed cross-fit view of
static parameter estimation.
dgtf_compare_params(fits, truth = NULL, level = 0.95)dgtf_compare_params(fits, truth = NULL, level = 0.95)
fits |
Named list of |
truth |
Optional named numeric vector or named list of true
static parameter values (same convention as
|
level |
Credible interval level for the |
When truth is supplied, the table additionally reports recovery
metrics (bias, mae, rmse, crps, coverage) from
param_recovery(). When truth is NULL, only the posterior
summaries (mean, median, sd, q_lo, q_hi) are reported,
giving a side-by-side view of the marginal posteriors without
assuming a known data generating process.
For a compact summary across fits, use dgtf_compare(), supplying
truth when the recovery columns are wanted.
A data frame of class dgtf_param_comparison with columns
parameter, model, mean, median, sd, q_lo, q_hi,
and, when truth is supplied, truth, bias, mae, rmse,
crps, coverage. Rows are ordered by parameter, then by the
input order of fits.
Overlays posterior bands, forecasts, simulated truth, or parameter summaries from a named list of fitted DGTF-related objects.
dgtf_compare_plot( fits, what = "Rt", level = 0.95, time = NULL, palette = NULL, alpha = 0.5, legend.position = "right", legend.name = "Method", legend.nrow = NULL, xlab = "Time", ylab = NULL, main = NULL, theme = ggplot2::theme_minimal(), hline = NULL, ... )dgtf_compare_plot( fits, what = "Rt", level = 0.95, time = NULL, palette = NULL, alpha = 0.5, legend.position = "right", legend.name = "Method", legend.nrow = NULL, xlab = "Time", ylab = NULL, main = NULL, theme = ggplot2::theme_minimal(), hline = NULL, ... )
fits |
Named list of objects accepted by the plotting backend. |
what |
Quantity to plot, such as |
level |
Credible interval level. |
time |
Optional time index. |
palette |
Optional named color vector. |
alpha |
Ribbon transparency. |
legend.position, legend.name, legend.nrow
|
Legend controls passed to ggplot2. |
xlab, ylab, main
|
Axis labels and title. |
theme |
ggplot2 theme. |
hline |
Optional horizontal reference line. |
... |
Additional arguments for static parameter plots. |
A ggplot object.
Constructs a distributed lag model where the lag weights follow a
negative binomial distribution parameterized by (number of
successes) and (failure probability).
dgtf_distributed_lag( r = 4L, kappa = 0.5, sys = c("nbinom", "shift"), obs = "nbinom", gain = "softplus", W = 0.01, seasonality = seas_none() )dgtf_distributed_lag( r = 4L, kappa = 0.5, sys = c("nbinom", "shift"), obs = "nbinom", gain = "softplus", W = 0.01, seasonality = seas_none() )
r |
Integer. Number of successes in the negative binomial lag
distribution. Default 4. Under |
kappa |
Numeric. Failure probability in (0, 1). Default 0.5. Can be inferred under either system form. |
sys |
Either |
obs |
Character or |
gain |
Character or |
W |
Numeric. Innovation variance. Default 0.01. |
seasonality |
A |
By default the model uses the exact iterative Solow form
(sys = "nbinom"), which represents the full untruncated NB
lag distribution through an -dimensional latent state and
the recursion in sys_nbinom(). Pass
sys = "shift" for the truncated sliding window form, where
the lag tail is dropped at the truncation length implied by the
lag component's residual_prob budget. The two forms are
mathematically equivalent in the limit of zero truncation budget.
When the lag distribution is geometric and the model
reduces to the Koyck model (see dgtf_koyck).
A dgtf_model object.
m <- dgtf_distributed_lag(r = 4, kappa = 0.5) # DL(2) with weekly seasonality m <- dgtf_distributed_lag(r = 2, seasonality = seas_weekly()) # Truncated sliding window form m <- dgtf_distributed_lag(r = 4, kappa = 0.5, sys = "shift")m <- dgtf_distributed_lag(r = 4, kappa = 0.5) # DL(2) with weekly seasonality m <- dgtf_distributed_lag(r = 2, seasonality = seas_weekly()) # Truncated sliding window form m <- dgtf_distributed_lag(r = 4, kappa = 0.5, sys = "shift")
-step-ahead posterior predictive forecasts, optionally
scored against held-out future observations.
dgtf_forecast_fit( object, h = 1L, nrep = 100L, ypred_true = NULL, only_last = FALSE, return_samples = FALSE, verbose = FALSE, ... )dgtf_forecast_fit( object, h = 1L, nrep = 100L, ypred_true = NULL, only_last = FALSE, return_samples = FALSE, verbose = FALSE, ... )
object |
A |
h |
Forecast horizon (positive integer). |
nrep |
Number of replicate draws per posterior sample. The
total number of forecast draws is |
ypred_true |
Optional numeric vector of held-out future
observations, of length at least |
only_last |
If |
return_samples |
If |
verbose |
If |
... |
Unused. |
An object of class dgtf_forecast (a list) with the
following elements.
quantiles, a numeric matrix with columns lower, median, and
upper at the 95% level. It has h rows by default, or one row
when only_last = TRUE.
level, the credible interval level, currently fixed at 0.95.
horizon, the requested forecast horizon h.
only_last, the flag described above, and nsample, the total
number of forecast draws.
samples, a matrix of posterior predictive draws, present only
when return_samples = TRUE.
ypred_true, the supplied vector of held-out observations, when
one was given.
coverage, chi, and crps, the scoring metrics, present only
when ypred_true is supplied.
mod <- dgtf_hawkes(seasonality = seas_period(1, init = 2)) sim <- dgtf_simulate_model(mod, ntime = 100, seed = 1) prior <- dgtf_prior(W = inv_gamma(1, 1), rho = inv_gamma(1, 1)) # Small tuning values keep the example fast. Use the vb_control() # defaults, or larger values, in real analyses. ctrl <- vb_control(iter = 50, n_sample = 100, n_particle = 100) y <- as.numeric(sim$y) fit <- dgtf(y[1:81], mod, prior, method = "hva", control = ctrl, seed = 1) fc <- dgtf_forecast_fit(fit, h = 20, nrep = 20, ypred_true = y[82:101]) fc summary(fc)mod <- dgtf_hawkes(seasonality = seas_period(1, init = 2)) sim <- dgtf_simulate_model(mod, ntime = 100, seed = 1) prior <- dgtf_prior(W = inv_gamma(1, 1), rho = inv_gamma(1, 1)) # Small tuning values keep the example fast. Use the vb_control() # defaults, or larger values, in real analyses. ctrl <- vb_control(iter = 50, n_sample = 100, n_particle = 100) y <- as.numeric(sim$y) fit <- dgtf(y[1:81], mod, prior, method = "hva", control = ctrl, seed = 1) fc <- dgtf_forecast_fit(fit, h = 20, nrep = 20, ypred_true = y[82:101]) fc summary(fc)
Constructs a discretized Hawkes model (branching process with immigration). The conditional intensity is
where is the gain function, is the
discretized serial interval (lognormal), and follows a
random walk.
dgtf_hawkes( obs = "nbinom", gain = "softplus", meanlog = 1.386, sigma2 = 0.32, W = 0.01, seasonality = seas_none() )dgtf_hawkes( obs = "nbinom", gain = "softplus", meanlog = 1.386, sigma2 = 0.32, W = 0.01, seasonality = seas_none() )
obs |
Character or |
gain |
Character or |
meanlog |
Numeric. Log-scale mean |
sigma2 |
Numeric. Log-scale variance |
W |
Numeric. Innovation variance. Default 0.01. |
seasonality |
A |
The discounted variant (M1 in the CSDA paper) is obtained by fitting
this same model with use_discount = TRUE in the inference
control, not through a separate constructor.
A dgtf_model object.
# Default Hawkes (zero baseline, softplus gain, lognormal lag) m <- dgtf_hawkes() # With nonzero baseline m <- dgtf_hawkes(seasonality = seas_period(1, init = 5)) # COVID-19 application with weekly seasonality m <- dgtf_hawkes(meanlog = 1.386, sigma2 = 0.32, seasonality = seas_weekly(init = rep(1, 7)))# Default Hawkes (zero baseline, softplus gain, lognormal lag) m <- dgtf_hawkes() # With nonzero baseline m <- dgtf_hawkes(seasonality = seas_period(1, init = 5)) # COVID-19 application with weekly seasonality m <- dgtf_hawkes(meanlog = 1.386, sigma2 = 0.32, seasonality = seas_weekly(init = rep(1, 7)))
Equivalent to dgtf_distributed_lag(r = 1, kappa = kappa).
The geometric lag weights produce the well-known Koyck recursion
,
which is exactly the iterative Solow form at . The
default sys = "nbinom" represents this directly via a
two-dimensional state ; pass
sys = "shift" for the truncated sliding equivalent.
dgtf_koyck( kappa = 0.5, sys = c("nbinom", "shift"), obs = "nbinom", gain = "softplus", W = 0.01, seasonality = seas_none() )dgtf_koyck( kappa = 0.5, sys = c("nbinom", "shift"), obs = "nbinom", gain = "softplus", W = 0.01, seasonality = seas_none() )
kappa |
Numeric. Memory parameter in (0, 1). Default 0.5. |
sys, obs, gain, W, seasonality
|
See |
A dgtf_model object.
m <- dgtf_koyck(kappa = 0.7)m <- dgtf_koyck(kappa = 0.7)
Assembles the components of a dynamic generalized transfer function
(DGTF) model. The returned object carries all structural choices and
all fixed parameter values, and is the object on which dgtf() and
dgtf_simulate_model() operate.
dgtf_model( obs, link, sys, gain = gain_identity(), lag = lag_uniform(window = 1L), err = err_gaussian(W = 0.01), intercept = 0, seasonality = NULL, obs_init = c(0, 30), zi = FALSE )dgtf_model( obs, link, sys, gain = gain_identity(), lag = lag_uniform(window = 1L), err = err_gaussian(W = 0.01), intercept = 0, seasonality = NULL, obs_init = c(0, 30), zi = FALSE )
obs |
Observation distribution. See |
link |
Link function. See |
sys |
System equation. See |
gain |
Gain function. See |
lag |
Lag distribution. See |
err |
System error distribution. See |
intercept |
Numeric scalar baseline. Used only when
|
seasonality |
A |
obs_init |
Numeric vector of initial observation distribution
parameters. The first element is currently unused. The second is the
negative binomial dispersion |
zi |
Logical; whether the observation model is zero-inflated. |
Components may be supplied either as full constructor objects
(obs_nbinom(), lag_lognormal(...), and so on) or as the
corresponding string shortcuts ("nbinom", "lognorm"). The
constructor form is the more general of the two, since it also
carries the component parameter values.
Anything supplied as a numeric value, such as intercept = 0 or
err = err_gaussian(W = 0.01), is treated as fixed. To infer it,
supply a prior in dgtf_prior().
An object of class dgtf_model.
The seasonality block already encodes the level of the series, so
intercept and a non-trivial seasonality are mutually exclusive:
dgtf_model(intercept = a) (with seasonality left NULL) is
equivalent to dgtf_model(seasonality = seas_period(1, init = a)),
since the intercept is the single seasonal effect under period 1.
dgtf_model(seasonality = seas_weekly(init = c(...))) includes the
level inside the seasonal pattern; do not also set intercept.
Setting both produces a warning and the intercept is ignored.
# Period-1 model: intercept = 5 dgtf_model(obs_poisson(), link_identity(), sys_identity(), intercept = 5) # Period-2 deterministic seasonality with explicit pattern dgtf_model(obs_poisson(), link_identity(), sys_identity(), seasonality = seas_period(period = 2, init = c(1, 2))) # Discretized Hawkes with weekly seasonality dgtf_model( obs_nbinom(), link_identity(), sys_shift(), gain = gain_softplus(), lag = lag_lognormal(), seasonality = seas_weekly(init = c(0.9, 1.0, 1.1, 1.0, 0.9, 0.8, 1.3)) )# Period-1 model: intercept = 5 dgtf_model(obs_poisson(), link_identity(), sys_identity(), intercept = 5) # Period-2 deterministic seasonality with explicit pattern dgtf_model(obs_poisson(), link_identity(), sys_identity(), seasonality = seas_period(period = 2, init = c(1, 2))) # Discretized Hawkes with weekly seasonality dgtf_model( obs_nbinom(), link_identity(), sys_shift(), gain = gain_softplus(), lag = lag_lognormal(), seasonality = seas_weekly(init = c(0.9, 1.0, 1.1, 1.0, 0.9, 0.8, 1.3)) )
Constructs a negative binomial AR(p) model. The intensity is
where each follows an independent random walk.
dgtf_nb_ar(p = 3L, gain = "softplus", W = 0.01, seasonality = seas_none())dgtf_nb_ar(p = 3L, gain = "softplus", W = 0.01, seasonality = seas_none())
p |
Integer. Autoregressive order. Default 3. |
gain |
Character or |
W |
Numeric. Scalar innovation variance (applied as
|
seasonality |
A |
The C++ engine uses sys_eq = "identity" () and
lag_dist = "uniform" (). With
full_rank = TRUE, all p states receive independent noise.
A dgtf_model object.
m <- dgtf_nb_ar(p = 3, seasonality = seas_weekly())m <- dgtf_nb_ar(p = 3, seasonality = seas_weekly())
Same structure as dgtf_nb_ar but with Poisson
observations. Denoted M4 in Tang and Prado (2026).
dgtf_poisson_ar(p = 5L, gain = "softplus", W = 0.01, seasonality = seas_none())dgtf_poisson_ar(p = 5L, gain = "softplus", W = 0.01, seasonality = seas_none())
p |
Integer. Autoregressive order. Default 5. |
gain, W, seasonality
|
See |
A dgtf_model object.
m <- dgtf_poisson_ar(p = 5)m <- dgtf_poisson_ar(p = 5)
Collects per-parameter prior specifications. Anything passed here is
treated as an unknown to be inferred; anything left out is treated as
fixed at the value supplied to dgtf_model().
dgtf_prior( intercept = NULL, seasonality = NULL, W = NULL, rho = NULL, lag = NULL, ... )dgtf_prior( intercept = NULL, seasonality = NULL, W = NULL, rho = NULL, lag = NULL, ... )
intercept |
Prior on the baseline |
seasonality |
Prior on the seasonality effect. |
W |
Prior on the system error variance. |
rho |
Prior on the negative binomial dispersion. |
lag |
A named list of priors on the lag distribution parameters,
with elements |
... |
Additional named priors on other model parameters (reserved for future extensions; currently passed through unchanged). |
An object of class dgtf_prior.
dgtf_prior( seasonality = normal(1, 1), W = inv_gamma(1, 1), rho = inv_gamma(1, 1), lag = list(par1 = normal(0, 1), par2 = inv_gamma(1, 1)) )dgtf_prior( seasonality = normal(1, 1), W = inv_gamma(1, 1), rho = inv_gamma(1, 1), lag = list(par1 = normal(0, 1), par2 = inv_gamma(1, 1)) )
Draws an observation series and the corresponding latent trajectories
from a dgtf_model().
dgtf_simulate_model(model, ntime, seed = NULL, y0 = 0, z = NULL)dgtf_simulate_model(model, ntime, seed = NULL, y0 = 0, z = NULL)
model |
A |
ntime |
Length of the simulated series. |
seed |
Optional RNG seed. |
y0 |
Initial observation (default 0). |
z |
Optional binary mask of length |
An object of class dgtf_sim (a list) with components
y, lambda, psi, Rt, Theta, ft, nlag, plus the
originating model and the gain function name gain. Rt is the
reproduction number , where is the
model's gain function. It is omitted for autoregressive models
(sys_identity()), whose psi is not on the scale.
When the model is zero-inflated, prob and z are also present.
mod <- dgtf_hawkes(seasonality = seas_period(1, init = 2)) sim <- dgtf_simulate_model(mod, ntime = 200, seed = 1) print(sim) plot(sim) plot(sim, what = "Rt")mod <- dgtf_hawkes(seasonality = seas_period(1, init = 2)) sim <- dgtf_simulate_model(mod, ntime = 200, seed = 1) print(sim) plot(sim) plot(sim, what = "Rt")
err_gaussian(W, full_rank, w0): Gaussian system error with variance W
(scalar or matrix). full_rank = TRUE allows correlated state errors.
err_constant(): degenerate (zero) system error.
err_gaussian(W = 0.01, full_rank = FALSE, w0 = 0) err_constant()err_gaussian(W = 0.01, full_rank = FALSE, w0 = 0) err_constant()
W |
Variance (scalar or square matrix). |
full_rank |
If |
w0 |
Initial value of the latent random walk, i.e. the state at time 0. |
A dgtf_err component object.
Transforms of the latent state, giving the reproduction number
. Inside the transfer function the gain is applied
to each that enters it, i.e. to every lagged state in the
sliding-window form, not only the most recent one.
gain_ramp() is not differentiable, so code paths that need the
derivative of the gain stop with an error for it.
gain_identity() gain_softplus() gain_ramp() gain_exponential() gain_logistic()gain_identity() gain_softplus() gain_ramp() gain_exponential() gain_logistic()
A dgtf_gain component object.
The discretized probability mass function that weights past observations in a sliding window transfer function.
lag_lognormal( meanlog = 1.386, sigma2 = NULL, sdlog = NULL, residual_prob = 0.005, window = NULL ) lag_nbinom(r = 1, kappa = 0.5, residual_prob = 0.005, window = NULL) lag_uniform(window = 1L)lag_lognormal( meanlog = 1.386, sigma2 = NULL, sdlog = NULL, residual_prob = 0.005, window = NULL ) lag_nbinom(r = 1, kappa = 0.5, residual_prob = 0.005, window = NULL) lag_uniform(window = 1L)
meanlog |
Numeric. Log-normal mean parameter |
sigma2 |
Numeric. Log-normal variance parameter
|
sdlog |
Numeric. Log-normal standard deviation parameter on the
log scale. If supplied, it is squared before passing settings to the
C++ engine. Do not supply both |
residual_prob |
Numeric in |
window |
Integer. For |
r, kappa
|
Negative binomial hyperparameters. |
lag_lognormal(meanlog, sigma2, sdlog, residual_prob)Discretized
log-normal distribution. Note: sigma2 is the
variance on the log scale, i.e. where
. This matches the C++ engine
and the CSDA paper. The sdlog argument is also accepted and
converted internally to sigma2 = sdlog^2.
lag_nbinom(r, kappa, residual_prob)Discretized
negative binomial (Solow form), with r successes and
kappa failure probability. Reduces to geometric when
r = 1.
lag_uniform(window)Discrete uniform over the window (used for AR models where each lag gets its own time-varying coefficient).
A dgtf_lag component object.
Maps the conditional mean to a linear predictor.
link_identity() link_exponential() link_logistic()link_identity() link_exponential() link_logistic()
A dgtf_link component object.
Constructors for the observational level of a dgtf_model().
Counts: obs_poisson(), obs_nbinom() (mean/dispersion form),
obs_nbinom_p() (number of successes and probability form).
Continuous: obs_normal().
obs_poisson() obs_nbinom() obs_nbinom_p() obs_normal()obs_poisson() obs_nbinom() obs_nbinom_p() obs_normal()
A dgtf_obs component object.
Lightweight constructors for the prior distributions accepted by dgtf().
Each returns an object of class dgtf_prior_dist carrying the
distribution name (as the C++ engine recognizes it) and a numeric vector
of hyperparameters.
normal(mean = 0, sd = 1) inv_gamma(shape = 1, scale = 1) dist_gamma(shape = 1, rate = 1) dist_beta(alpha = 1, beta = 1) uniform(lower = 0, upper = 1) half_normal(sd = 1) half_cauchy(scale = 1) half_t(df = 3, scale = 1)normal(mean = 0, sd = 1) inv_gamma(shape = 1, scale = 1) dist_gamma(shape = 1, rate = 1) dist_beta(alpha = 1, beta = 1) uniform(lower = 0, upper = 1) half_normal(sd = 1) half_cauchy(scale = 1) half_t(df = 3, scale = 1)
mean, sd, shape, scale, rate, alpha, beta, lower, upper, df
|
Hyperparameters. |
Supported distributions and their (par1, par2) interpretations:
normal(mean, sd)
inv_gamma(shape, scale)
dist_gamma(shape, rate) (renamed to avoid masking base::gamma)
dist_beta(alpha, beta) (renamed to avoid masking base::beta)
uniform(lower, upper)
half_normal(sd) (the second hyperparameter slot is unused)
half_cauchy(scale)
half_t(df, scale)
An object of class dgtf_prior_dist.
normal(0, 1) inv_gamma(2, 1)normal(0, 1) inv_gamma(2, 1)
Specify the period, seasonal effects, and whether seasonality enters via the latent state vector or as a fixed deterministic offset.
seas_none() seas_weekly(init = rep(0, 7L), in_state = FALSE) seas_period(period, init = rep(0, period), in_state = FALSE)seas_none() seas_weekly(init = rep(0, 7L), in_state = FALSE) seas_period(period, init = rep(0, period), in_state = FALSE)
init |
Seasonal-effect values. Scalar (recycled), or a vector of
length |
in_state |
If |
period |
Integer seasonal period. |
seas_none(): no seasonality (period 1, init 0). The model has
no intercept either; supply one via dgtf_model(intercept = ...).
seas_weekly(init, in_state): weekly seasonality (period 7).
seas_period(period, init, in_state): arbitrary period.
init is the seasonal-effect vector. A scalar is recycled to length
period. A vector of length period is accepted as-is;
only the first period elements form the seasonal pattern, and the
extras are ignored.
Note that when seasonality has period the seasonal effects
already encode the level of the series; there is no separate
"intercept". dgtf_model() will warn if both intercept and a
non-trivial seasonality are set.
A dgtf_seasonality object.
seas_none() seas_weekly(init = c(0.9, 1.0, 1.1, 1.0, 0.9, 0.8, 1.3)) seas_period(period = 2, init = c(1, 2))seas_none() seas_weekly(init = c(0.9, 1.0, 1.1, 1.0, 0.9, 0.8, 1.3)) seas_period(period = 2, init = c(1, 2))
Determines the form of the latent state evolution .
sys_identity() sys_shift() sys_nbinom(kappa = 0.5)sys_identity() sys_shift() sys_nbinom(kappa = 0.5)
kappa |
Decay parameter for the nonlinear |
sys_identity(): , no state evolution (e.g. Poisson AR).
sys_shift(): shift matrix for windowed Hawkes and distributed lag
models.
sys_nbinom(): nonlinear evolution for the Solow distributed lag
model, where kappa is the geometric or negative binomial decay
parameter.
A dgtf_sys component object.
Thin wrapper around EpiEstim::estimate_R() and
EpiEstim::wallinga_teunis() that returns posterior R_t bands
in a format dgtf_compare_plot() consumes. The return value is a
length(y) x 3 numeric matrix with columns lower, median, and
upper, padded with leading NAs so that row i corresponds to time
i in the input series. This follows the same convention as
dgtf_fit$fit$psi.
epiestim_baseline( y, mean_si, sd_si, method = c("parametric_si", "uncertain_si", "wallinga_teunis"), window = 7L, level = 0.95, align = c("center", "right"), mean_sd_si = 1.8, sd_sd_si = 1.4, ... )epiestim_baseline( y, mean_si, sd_si, method = c("parametric_si", "uncertain_si", "wallinga_teunis"), window = 7L, level = 0.95, align = c("center", "right"), mean_sd_si = 1.8, sd_sd_si = 1.4, ... )
y |
Numeric vector of incident counts (the same vector you
pass to |
mean_si, sd_si
|
Serial interval mean and standard
deviation in the same time units as |
method |
One of three options.
|
window |
Sliding window width in time units (default 7). Smaller windows give noisier, more responsive estimates. |
level |
Credible interval level (default 0.95). EpiEstim
natively reports the 0.025 and 0.975 quantiles. For any other level
the bounds are derived from a normal approximation to the posterior,
|
align |
Alignment of the EpiEstim window summary in the returned
matrix. Use |
mean_sd_si, sd_sd_si
|
Prior standard deviations on the SI
mean and SI sd respectively. Used only by
|
... |
Additional arguments forwarded to
|
The wrapper exists so that a renewal equation baseline can be placed
next to dgtf_fit objects in the comparison plot.
fit_hva <- dgtf(y, mod, prior, method = "hva")
fit_mcmc <- dgtf(y, mod, prior, method = "mcmc")
epi <- epiestim_baseline(y, mean_si = 4.7, sd_si = 2.9)
dgtf_compare_plot(
list(HVA = fit_hva, MCMC = fit_mcmc, EpiEstim = epi),
what = "Rt")
An object of class "epiestim_baseline", a
length(y) x 3 numeric matrix with columns lower, median, and
upper. The first window rows are NA, because no estimate is
available yet. The method, the level, and the serial interval
parameters are stored as attributes.
Computes the effective sample size of a
1-D vector of posterior draws from FFT-based autocorrelations
. The sum adds consecutive pairs
and stops at the first negative pair, a
variant of Geyer's initial positive sequence, and the lag-
autocovariance is divided by . Values can therefore differ
slightly from coda::effectiveSize() or posterior::ess_basic().
Non-finite entries are dropped.
ess(x)ess(x)
x |
A numeric vector of posterior draws (a single chain). |
A scalar no larger than the number of finite draws, and at least 1 when there are two or more.
set.seed(1); ess(rnorm(2000)) x <- as.numeric(stats::arima.sim(list(ar = 0.9), 2000)); ess(x)set.seed(1); ess(rnorm(2000)) x <- as.numeric(stats::arima.sim(list(ar = 0.9), 2000)); ess(x)
Returns a matrix of posterior draws of psi (one column per draw), or, for autoregressive HVA fits, a 3-D array of Theta draws (state dimension x length(y) x draws). See Value.
extract_state_draws(object, what = c("psi", "Theta"))extract_state_draws(object, what = c("psi", "Theta"))
object |
A |
what |
One of |
For what = "psi", a numeric matrix of posterior draws of
the latent state , with one row per time point (that is,
per element of the fitted series) and one column per posterior draw.
For autoregressive models fitted by HVA, the rows instead hold the
lag coefficients at the final time point. For what = "Theta", a
numeric 3-D array of draws of the full state vector, with dimensions
state dimension x time points x posterior draws; it is stored only
for autoregressive models fitted by HVA. An error is raised when the
requested component is not stored for the fit.
fitted() returns the posterior mean of the expected count
, residuals() compares it with the observed series, and
predict() returns fitted values or forecasts, optionally with
intervals. In-sample results are aligned with object$y; the first
element is NA because the initial value of the series is not
modelled.
## S3 method for class 'dgtf_fit' fitted(object, type = c("response", "intensity"), ...) ## S3 method for class 'dgtf_fit' residuals(object, type = c("response", "pearson"), ...) ## S3 method for class 'dgtf_fit' predict( object, horizon = 0L, type = c("response", "intensity"), interval = c("none", "credible", "prediction"), level = 0.95, nrep = 100L, ... )## S3 method for class 'dgtf_fit' fitted(object, type = c("response", "intensity"), ...) ## S3 method for class 'dgtf_fit' residuals(object, type = c("response", "pearson"), ...) ## S3 method for class 'dgtf_fit' predict( object, horizon = 0L, type = c("response", "intensity"), interval = c("none", "credible", "prediction"), level = 0.95, nrep = 100L, ... )
object |
A |
type |
For |
... |
For |
horizon |
Number of steps ahead. |
interval |
|
level |
Interval level. Forecasts ( |
nrep |
Number of posterior predictive replicates per posterior draw, used for prediction intervals and forecasts. |
The posterior predictive variance used by Pearson residuals
is the posterior mean of the per-draw variance of plus the
posterior variance of the per-draw mean. Zero-inflated models and
Gaussian observations are not yet supported.
fitted() and residuals() return a numeric vector of the
same length as object$y. See predict() below for its return
value.
predict() returns a numeric vector when
interval = "none", and otherwise a matrix with columns fit,
lwr, and upr. In sample, it has one entry or row per element of
object$y. For forecasts, it has horizon entries or rows, and
fit is the median of the forecast draws.
posterior_predict(), dgtf_forecast_fit()
Tuning parameters for the disturbance sampler, selected in dgtf()
with method = "mcmc".
mcmc_control(iter = 2000L, warmup = 1000L, thin = 1L, verbose = FALSE, ...)mcmc_control(iter = 2000L, warmup = 1000L, thin = 1L, verbose = FALSE, ...)
iter |
Number of retained post-warmup MCMC iterations. |
warmup |
Number of burn-in iterations, which are discarded. |
thin |
Thinning interval. |
verbose |
If |
... |
Forwarded to the C++ engine. The HMC tuning options
|
A dgtf_mcmc_control object.
Compares per-parameter posterior summaries (mean, sd, credible interval) to user-supplied true values. Useful for simulation studies and SBC-style aggregation across replicates.
param_recovery(object, truth, level = 0.95, digits = 3)param_recovery(object, truth, level = 0.95, digits = 3)
object |
A |
truth |
Named numeric vector or named list of true static
parameter values. Scalar parameters use the bare name,
such as |
level |
Credible interval level for the |
digits |
Number of digits to round the numeric columns to
for display (default |
A data.frame of class param_recovery with one row per
matched parameter and columns parameter, truth, mean,
median, sd, q_lo, q_hi, bias (mean - truth), mae,
rmse, crps, and the logical coverage, which records whether
the truth lies in [q_lo, q_hi].
The default print method suppresses the coverage column and
instead appends an unnamed column whose value is "*" when the
truth lies inside the credible interval, with the convention
explained in a footer (cf. print.summary.lm).
Returns NULL if there are no posterior draws or no name
matches.
mod <- dgtf_hawkes(seasonality = seas_period(1, init = 2)) sim <- dgtf_simulate_model(mod, ntime = 100, seed = 1) prior <- dgtf_prior(W = inv_gamma(1, 1), rho = inv_gamma(1, 1)) # Small tuning values keep the example fast. Use the vb_control() # defaults, or larger values, in real analyses. ctrl <- vb_control(iter = 50, n_sample = 100, n_particle = 100) fit <- dgtf(sim$y, mod, prior, method = "hva", control = ctrl, seed = 1) param_recovery(fit, truth = list(W = mod$err$params$var[1], rho = mod$obs_init[2]))mod <- dgtf_hawkes(seasonality = seas_period(1, init = 2)) sim <- dgtf_simulate_model(mod, ntime = 100, seed = 1) prior <- dgtf_prior(W = inv_gamma(1, 1), rho = inv_gamma(1, 1)) # Small tuning values keep the example fast. Use the vb_control() # defaults, or larger values, in real analyses. ctrl <- vb_control(iter = 50, n_sample = 100, n_particle = 100) fit <- dgtf(sim$y, mod, prior, method = "hva", control = ctrl, seed = 1) param_recovery(fit, truth = list(W = mod$err$params$var[1], rho = mod$obs_init[2]))
Compares the per-lag weights of one or more dgtf_fit objects on a
single grouped bar chart. The plot shows how the different DGTF model
families distribute the influence of past observations across lags.
plot_dgtf_lag( fits, window = NULL, xlim = NULL, normalize = c("pmf", "raw", "branching"), summary = c("median", "mean"), alpha = 0.5, palette = NULL, xlab = "Lag", ylab = NULL, main = NULL, theme = ggplot2::theme_minimal(), ... )plot_dgtf_lag( fits, window = NULL, xlim = NULL, normalize = c("pmf", "raw", "branching"), summary = c("median", "mean"), alpha = 0.5, palette = NULL, xlab = "Lag", ylab = NULL, main = NULL, theme = ggplot2::theme_minimal(), ... )
fits |
Either a |
window |
Maximum lag to display. |
xlim |
Largest lag to show in the plot, which truncates the
display only. Defaults to |
normalize |
One of three options.
|
summary |
Posterior summary applied to each model's parameter or
coefficient draws before the weights are computed. Either
|
alpha |
Bar transparency (default 0.5). |
palette |
Optional named character vector of fill colors.
Same convention as |
xlab, ylab, main
|
Axis and title labels. The default
|
theme |
A ggplot2 theme. |
... |
Unused. |
The three families define their lag weights differently, and the plot places all three on a common scale.
Hawkes (sys = shift, lag = lognormal) uses the discretized
lognormal PMF evaluated at the posterior medians of meanlog and
sigma2, through dlognorm0().
Distributed lag and Koyck (sys = nbinom or shift,
lag = nbinom) use the discretized negative binomial PMF
evaluated at the posterior medians of kappa and r, through
dnbinom0(). The two system forms share the same lag
weights and differ only in the underlying state-space
representation.
AR (sys = identity, lag = uniform) uses the autoregressive
coefficient h(theta_l) after the gain transform, summarized
across time and posterior samples for each lag l. These
coefficients are not probabilities. See normalize for how they
are placed on a comparable scale.
A ggplot object.
mod <- dgtf_hawkes(seasonality = seas_period(1, init = 2)) y <- as.numeric(dgtf_simulate_model(mod, ntime = 100, seed = 1)$y) prior <- dgtf_prior(W = inv_gamma(1, 1)) # Small tuning values keep the example fast. Use the vb_control() # defaults, or larger values, in real analyses. ctrl <- vb_control(iter = 50, n_sample = 100, n_particle = 100) fit_hawkes <- dgtf(y, mod, prior, control = ctrl, seed = 1) plot_dgtf_lag(fit_hawkes) base <- seas_period(1, init = 2) fit_dl <- dgtf(y, dgtf_distributed_lag(r = 3, seasonality = base), prior, control = ctrl, seed = 1) fit_ar <- dgtf(y, dgtf_nb_ar(p = 3, seasonality = base), prior, control = ctrl, seed = 1) plot_dgtf_lag(list( Hawkes = fit_hawkes, DL3 = fit_dl, "AR(3)" = fit_ar )) # Raw magnitudes. The AR branching weights are larger than the # unit-mass PMFs of the shift system. plot_dgtf_lag(list(Hawkes = fit_hawkes, "AR(3)" = fit_ar), normalize = "raw" )mod <- dgtf_hawkes(seasonality = seas_period(1, init = 2)) y <- as.numeric(dgtf_simulate_model(mod, ntime = 100, seed = 1)$y) prior <- dgtf_prior(W = inv_gamma(1, 1)) # Small tuning values keep the example fast. Use the vb_control() # defaults, or larger values, in real analyses. ctrl <- vb_control(iter = 50, n_sample = 100, n_particle = 100) fit_hawkes <- dgtf(y, mod, prior, control = ctrl, seed = 1) plot_dgtf_lag(fit_hawkes) base <- seas_period(1, init = 2) fit_dl <- dgtf(y, dgtf_distributed_lag(r = 3, seasonality = base), prior, control = ctrl, seed = 1) fit_ar <- dgtf(y, dgtf_nb_ar(p = 3, seasonality = base), prior, control = ctrl, seed = 1) plot_dgtf_lag(list( Hawkes = fit_hawkes, DL3 = fit_dl, "AR(3)" = fit_ar )) # Raw magnitudes. The AR branching weights are larger than the # unit-mass PMFs of the shift system. plot_dgtf_lag(list(Hawkes = fit_hawkes, "AR(3)" = fit_ar), normalize = "raw" )
Plots the posterior predictive band for y over the in-sample
window and, optionally, the forecast band for y over the
out-of-sample window taken from a dgtf_forecast, with the two
distinguished by color. Truth values for either segment are overlaid
as a single dashed black line spanning both windows.
plot_dgtf_y( x, forecast = NULL, truth_in = NULL, truth_out = NULL, show_truth = TRUE, time_in = NULL, time_out = NULL, level = 0.95, nrep = 100L, in_color = "#0072B2", out_color = "#D55E00", in_name = "In-sample", out_name = "Forecast", alpha = 0.4, xlab = "Time", ylab = expression(y[t]), main = NULL, theme = ggplot2::theme_minimal(), ... )plot_dgtf_y( x, forecast = NULL, truth_in = NULL, truth_out = NULL, show_truth = TRUE, time_in = NULL, time_out = NULL, level = 0.95, nrep = 100L, in_color = "#0072B2", out_color = "#D55E00", in_name = "In-sample", out_name = "Forecast", alpha = 0.4, xlab = "Time", ylab = expression(y[t]), main = NULL, theme = ggplot2::theme_minimal(), ... )
x |
Either a |
forecast |
Optional |
truth_in |
Optional numeric vector of length |
truth_out |
Optional numeric vector of length
|
show_truth |
If |
time_in, time_out
|
Optional numeric vectors giving the x-axis
values for the two segments, such as real dates coerced to
numeric. They default to |
level |
Credible interval level used when the in-sample PPC
has to be computed on the fly (i.e. |
nrep |
Posterior predictive replicate count for the on-the-fly PPC. |
in_color, out_color
|
Hex colors for the two bands. Default to Okabe–Ito blue and vermillion, so that the two are easy to tell apart. |
in_name, out_name
|
Legend labels for the two bands. |
alpha |
Ribbon transparency (default 0.4). |
xlab, ylab, main
|
Axis and title labels. |
theme |
A ggplot2 theme. |
... |
Unused. |
The in-sample band can come from either of two sources.
A dgtf_fit, whose attr(., "ppc") is reused when present and
otherwise computed by posterior_predict() on the fly. The
observed y is used as the in-sample truth by default.
A dgtf_ppc, which is used directly. There is no automatic
in-sample truth in this case, because the PPC object does not
carry y. Supply one through truth_in when it is wanted.
A ggplot object.
mod <- dgtf_hawkes(seasonality = seas_period(1, init = 2)) sim <- dgtf_simulate_model(mod, ntime = 100, seed = 1) prior <- dgtf_prior(W = inv_gamma(1, 1), rho = inv_gamma(1, 1)) # Small tuning values keep the example fast. Use the vb_control() # defaults, or larger values, in real analyses. ctrl <- vb_control(iter = 50, n_sample = 100, n_particle = 100) y <- as.numeric(sim$y) fit <- dgtf(y[1:81], mod, prior, method = "hva", control = ctrl, seed = 1) fc <- dgtf_forecast_fit(fit, h = 20, nrep = 20, ypred_true = y[82:101]) # In-sample band + forecast band + dashed truth across the gap. plot_dgtf_y(fit, fc) # In-sample only (forecast = NULL); equivalent to a yhat PPC plot # with the observed series overlaid. plot_dgtf_y(fit, nrep = 10) # Real dates on the x-axis. date_seq <- seq(as.Date("2020-07-01"), by = "day", length.out = 101) plot_dgtf_y(fit, fc, time_in = as.numeric(date_seq[1:81]), time_out = as.numeric(date_seq[82:101]), xlab = "Date" )mod <- dgtf_hawkes(seasonality = seas_period(1, init = 2)) sim <- dgtf_simulate_model(mod, ntime = 100, seed = 1) prior <- dgtf_prior(W = inv_gamma(1, 1), rho = inv_gamma(1, 1)) # Small tuning values keep the example fast. Use the vb_control() # defaults, or larger values, in real analyses. ctrl <- vb_control(iter = 50, n_sample = 100, n_particle = 100) y <- as.numeric(sim$y) fit <- dgtf(y[1:81], mod, prior, method = "hva", control = ctrl, seed = 1) fc <- dgtf_forecast_fit(fit, h = 20, nrep = 20, ypred_true = y[82:101]) # In-sample band + forecast band + dashed truth across the gap. plot_dgtf_y(fit, fc) # In-sample only (forecast = NULL); equivalent to a yhat PPC plot # with the observed series overlaid. plot_dgtf_y(fit, nrep = 10) # Real dates on the x-axis. date_seq <- seq(as.Date("2020-07-01"), by = "day", length.out = 101) plot_dgtf_y(fit, fc, time_in = as.numeric(date_seq[1:81]), time_out = as.numeric(date_seq[82:101]), xlab = "Date" )
Side-by-side equivalent of plot_dgtf_y() for an arbitrary number
of model variants. For each method the function draws an in-sample
posterior predictive band, taken from the fit's PPC either cached or
computed on the fly. When a forecast is supplied, it also draws a
forecast band continuing the time axis past the train/test
boundary.
plot_dgtf_y_compare( fits, forecasts = NULL, truth_in = NULL, truth_out = NULL, show_truth = TRUE, time_in = NULL, time_out = NULL, level = 0.95, nrep = 100L, palette = NULL, alpha = 0.4, split_line = TRUE, xlab = "Time", ylab = expression(y[t]), main = NULL, theme = ggplot2::theme_minimal(), ... )plot_dgtf_y_compare( fits, forecasts = NULL, truth_in = NULL, truth_out = NULL, show_truth = TRUE, time_in = NULL, time_out = NULL, level = 0.95, nrep = 100L, palette = NULL, alpha = 0.4, split_line = TRUE, xlab = "Time", ylab = expression(y[t]), main = NULL, theme = ggplot2::theme_minimal(), ... )
fits |
Named list. Each entry is a |
forecasts |
Named list of |
truth_in |
Optional numeric vector for the in-sample truth.
|
truth_out |
Optional numeric vector for the out-of-sample
truth. |
show_truth |
|
time_in, time_out
|
Optional numeric vectors giving the x-axis
values for the two segments. They default to |
level, nrep
|
Forwarded to |
palette |
Optional named character vector of colors. |
alpha |
Ribbon transparency (default 0.4). |
split_line |
If |
xlab, ylab, main
|
Axis and title labels. |
theme |
A ggplot2 theme. |
... |
Unused. |
Each method gets a single color applied to both its in-sample band and its forecast band; segments are visually distinguished by a vertical dotted line at the train/test split rather than by a second color channel. This keeps the legend readable across many methods.
A ggplot object.
Time series plot of the forecast quantile band, drawn as a median line with a ribbon, with an optional truth overlay as a dashed black line. This follows the convention of the other dgtf time series plotting methods.
## S3 method for class 'dgtf_forecast' plot( x, truth = NULL, time = NULL, color = NULL, alpha = 0.5, xlab = NULL, ylab = NULL, main = NULL, theme = ggplot2::theme_minimal(), ... )## S3 method for class 'dgtf_forecast' plot( x, truth = NULL, time = NULL, color = NULL, alpha = 0.5, xlab = NULL, ylab = NULL, main = NULL, theme = ggplot2::theme_minimal(), ... )
x |
A |
truth |
Optional numeric vector of true future values to
overlay (same length convention as |
time |
Optional numeric vector of length |
color |
Optional color for the forecast band (line + ribbon). Defaults to black for a single-method forecast plot. |
alpha |
Ribbon transparency (default 0.5). |
xlab, ylab, main
|
Axis and title labels. |
theme |
A ggplot2 theme. |
... |
Unused. |
Single-step forecasts, obtained by setting only_last = TRUE in the
original dgtf_forecast_fit() call, are rendered as a point with
an interval rather than as a line with a ribbon, since a single pair
of horizon and value is all there is to show. The truth, when
present, is drawn as a black cross at the same time step.
A ggplot object.
Visualises the observed series y or the reproduction number
R_t = h(psi_t) from a dgtf_simulate_model() result.
## S3 method for class 'dgtf_sim' plot(x, what = c("y", "Rt"), split = NULL, ...)## S3 method for class 'dgtf_sim' plot(x, what = c("y", "Rt"), split = NULL, ...)
x |
A |
what |
One of |
split |
Optional numeric scalar or vector of time indices at
which to draw a vertical dotted line. Useful for marking a
train/test boundary in simulation studies. Default |
... |
Unused. |
A ggplot object.
Generates posterior predictive samples for an in-sample series under the fitted model. Use this for posterior predictive checks and goodness of fit assessment.
posterior_predict(object, ...) ## S3 method for class 'dgtf_fit' posterior_predict( object, nrep = 100L, Rt = NULL, level = 0.95, verbose = FALSE, ... )posterior_predict(object, ...) ## S3 method for class 'dgtf_fit' posterior_predict( object, nrep = 100L, Rt = NULL, level = 0.95, verbose = FALSE, ... )
object |
A |
... |
Unused. |
nrep |
Number of replicate draws per posterior sample. The
total number of posterior predictive draws is |
Rt |
Optional reference |
level |
Credible interval level used when reporting coverage,
interval width, and the interval score (default |
verbose |
If |
An object of class dgtf_ppc (a list). These elements are
always present.
chi, the averaged chi-square discrepancy of y.
Rt, an (ntime + 1) x 3 matrix of R_t posterior quantiles at
(alpha/2, 0.5, 1 - alpha/2) with alpha = 1 - level.
width_Rt, the mean width of the R_t credible bands.
level, the credible interval level used.
fitted_mean and fitted_var, vectors of length ntime + 1 with
the posterior mean and the posterior predictive variance of
, and fitted_qt, an (ntime + 1) x 3 matrix of
posterior quantiles of the expected count .
lambda_mean and lambda_qt, the same summaries for the
intensity .
The first entry of each of these is a placeholder for the initial
value of the series. fitted.dgtf_fit() and its companions
replace it with NA.
Further elements are added when nrep > 0.
crps, the averaged continuous ranked probability score for y.
yhat, an (ntime + 1) x 3 quantile matrix of the posterior
predictive distribution of y.
coverage_yhat, width_yhat, and interval_score_yhat, the
Winkler interval score for y together with its components.
When a reference Rt trajectory is supplied, as in a simulation
study, the recovery metrics mae_Rt, rmse_Rt, coverage_Rt, and
interval_score_Rt are added as well.
mod <- dgtf_hawkes(seasonality = seas_period(1, init = 2)) sim <- dgtf_simulate_model(mod, ntime = 100, seed = 1) prior <- dgtf_prior(W = inv_gamma(1, 1), rho = inv_gamma(1, 1)) # Small tuning values keep the example fast. Use the vb_control() # defaults, or larger values, in real analyses. ctrl <- vb_control(iter = 50, n_sample = 100, n_particle = 100) fit <- dgtf(sim$y, mod, prior, method = "hva", control = ctrl, seed = 1) pp <- posterior_predict(fit, nrep = 10, Rt = log1p(exp(as.numeric(sim$psi)))) pp summary(pp)mod <- dgtf_hawkes(seasonality = seas_period(1, init = 2)) sim <- dgtf_simulate_model(mod, ntime = 100, seed = 1) prior <- dgtf_prior(W = inv_gamma(1, 1), rho = inv_gamma(1, 1)) # Small tuning values keep the example fast. Use the vb_control() # defaults, or larger values, in real analyses. ctrl <- vb_control(iter = 50, n_sample = 100, n_particle = 100) fit <- dgtf(sim$y, mod, prior, method = "hva", control = ctrl, seed = 1) pp <- posterior_predict(fit, nrep = 10, Rt = log1p(exp(as.numeric(sim$psi)))) pp summary(pp)
Each input chain of length n is split sequentially into halves of
length floor(n/2) (the middle sample is dropped when n is odd), so
a single chain produces 2 sub-chains, two chains produce 4, and so on.
This is the classic split-Rhat of Gelman et al. (2013, Bayesian Data
Analysis, 3rd ed.), not the rank-normalized version of Vehtari et al.
(2021). Values near 1 indicate the chains have mixed; 1.1 is the
traditional warning threshold for this version, while the stricter 1.01
was proposed for the rank-normalized one.
rhat(x)rhat(x)
x |
One of:
|
A scalar when the input is a matrix or a list of vectors, and a named numeric vector with one entry per scalar static parameter when the input is a list of fits.
A 200-step series simulated from a Hawkes-style DGTF model. Ships
with the originating model and the true latent psi path so it
can be used as a ground-truth reference for posterior checks.
sim_hawkessim_hawkes
A dgtf_sim object, that is, a list
holding the numeric vector of observations y together with psi,
lambda, ft, Theta, nlag, and the originating model and
gain.
Generated with dgtf_simulate_model() using seed 1.
Summarizes inferred static parameters, latent states, runtime information, and method-specific convergence diagnostics.
## S3 method for class 'dgtf_fit' summary(object, truth = NULL, ...) ## S3 method for class 'summary.dgtf_fit' print(x, digits = 3L, ...)## S3 method for class 'dgtf_fit' summary(object, truth = NULL, ...) ## S3 method for class 'summary.dgtf_fit' print(x, digits = 3L, ...)
object |
A |
truth |
Optional named numeric vector or list of true values,
named as in |
... |
Additional arguments reserved for future methods. |
x |
A |
digits |
Significant digits for most numeric output. |
For MCMC fits, the table also has ess and rhat columns;
rhat is single-chain split-Rhat (Gelman–Rubin
on the two halves of the chain). It detects within-chain drift but
cannot diagnose multi-modality. For a stronger check, run multiple
independent fits and call rhat(list(fit1, fit2, ...)).
HVA fits instead get a convergence summary of the SMC log marginal likelihood trace.
An object of class summary.dgtf_fit.
x, invisibly.
Tuning parameters for the hybrid variational algorithm, selected in
dgtf() with method = "hva" or its synonym method = "vb".
vb_control( iter = 1000L, n_sample = 1000L, n_particle = 200L, learning_rate = 0.02, eps_step_size = 1e-05, verbose = FALSE, ... )vb_control( iter = 1000L, n_sample = 1000L, n_particle = 200L, learning_rate = 0.02, eps_step_size = 1e-05, verbose = FALSE, ... )
iter |
Number of variational iterations. |
n_sample |
Number of posterior draws to retain after fitting. |
n_particle |
Number of particles in the inner SMC step. |
learning_rate |
Weight given to the newest squared gradient in the running averages of the ADADELTA step-size rule (one minus the decay rate). Larger values adapt the step size faster. |
eps_step_size |
Small constant added to both running averages in the ADADELTA step-size ratio, for numerical stability. |
verbose |
If |
... |
Additional named arguments passed through verbatim to the
C++ engine. Use these for options that the named arguments above do
not cover, such as |
A dgtf_vb_control object.
vb_control(iter = 500, n_sample = 1000)vb_control(iter = 500, n_sample = 1000)