Skip to content

Commit

Permalink
better documentation and mcmc_plot options
Browse files Browse the repository at this point in the history
  • Loading branch information
Nicholas Clark committed Nov 8, 2023
1 parent e94d8f2 commit 6c932ef
Show file tree
Hide file tree
Showing 47 changed files with 168 additions and 169 deletions.
1 change: 1 addition & 0 deletions R/conditional_effects.R
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
#' and create more bespoke conditional effects plots.
#' @name conditional_effects.mvgam
#' @author Nicholas J Clark
#' @seealso \code{\link[marginaleffects]{plot_predictions}}, \code{\link[marginaleffects]{plot_slopes}}
#' @examples
#' \dontrun{
#' # Simulate some data
Expand Down
10 changes: 2 additions & 8 deletions R/forecast.mvgam.R
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
#'@importFrom parallel clusterExport stopCluster setDefaultCluster
#'@importFrom stats predict
#'@importFrom rlang missing_arg
#'@param object \code{list} object returned from \code{mvgam}. See [mvgam()]
#'@inheritParams predict.mvgam
#'@param newdata Optional \code{dataframe} or \code{list} of test data containing at least 'series' and 'time'
#'in addition to any other variables included in the linear predictor of the original \code{formula}. If included, the
#'covariate information in \code{newdata} will be used to generate forecasts from the fitted model equations. If
Expand All @@ -19,17 +19,11 @@
#'if the fitted model contained multivariate trends (either as a dynamic factor or \code{VAR} process),
#'as it saves recomputing the full set of trends for each series individually
#'@param n_cores \code{integer} specifying number of cores for generating forecasts in parallel
#'@param type When this has the value \code{link} the linear predictor is calculated on the link scale.
#'If \code{expected} is used, predictions reflect the expectation of the response (the mean)
#'but ignore uncertainty in the observation process. When \code{response} (default) is used,
#'the predictions take uncertainty in the observation process into account to return
#'predictions on the outcome scale. When \code{trend} is used, only the forecast distribution for the
#'latent trend is returned
#'@param ... Ignored
#'@details Posterior predictions are drawn from the fitted \code{mvgam} and used to simulate a forecast distribution
#'@return An object of class \code{mvgam_forecast} containing hindcast and forecast distributions.
#'See \code{\link{mvgam_forecast-class}} for details.
#'
#'@seealso \code{\link{hindcast}}, \code{\link{score}}
#'@export
forecast <- function(object, ...){
UseMethod("forecast", object)
Expand Down
6 changes: 3 additions & 3 deletions R/formula.mvgam.R
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
#'Extract model.frame from a fitted mvgam object
#'Extract formulae from mvgam objects
#'
#'@rdname formula.mvgam
#'@param x `mvgam` or `mvgam_prefit` object
#'@param trend_effects \code{logical}, return the model.frame from the
#'@param trend_effects \code{logical}, return the formula from the
#'observation model (if \code{FALSE}) or from the underlying process
#'model (if\code{TRUE})
#'@param ... Ignored
#'@author Nicholas J Clark
#'@return A \code{matrix} containing the fitted model frame
#'@return A \code{formula} object
#'@export
formula.mvgam = function(x, trend_effects = FALSE, ...){
# Check trend_effects
Expand Down
9 changes: 1 addition & 8 deletions R/get_mvgam_priors.R
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,6 @@
#'changed for a given `mvgam` model, as well listing their default distributions
#'
#' @inheritParams mvgam
#'@param use_stan Logical. If \code{TRUE} and if \code{rstan} is installed, the model will be compiled and sampled using
#'the Hamiltonian Monte Carlo with a call to \code{\link[cmdstanr]{cmdstan_model}} or, if `cmdstanr` is not available,
#'a call to \code{\link[rstan]{stan}}. Note that this functionality is still in development and
#'not all options that are available in \code{JAGS} can be used, including: no option for a Tweedie family and no option for
#'dynamic factor trends. However, as \code{Stan} can estimate Hilbert base approximate Gaussian Processes, which
#'are much more computationally tractable than full GPs for time series with `>100` observations, estimation
#'in \code{Stan} can support latent GP trends while estimation in \code{JAGS} cannot
#'@details Users can supply a model formula, prior to fitting the model, so that default priors can be inspected and
#'altered. To make alterations, change the contents of the `prior` column and supplying this
#'\code{data.frame} to the `mvgam` function using the argument `priors`. If using `Stan` as the backend,
Expand All @@ -26,7 +19,7 @@
#' ensure that the code is legal (i.e. to check that lower bounds are smaller than upper bounds, for
#' example)
#'@author Nicholas J Clark
#'@seealso \code{\link{mvgam}}
#'@seealso \code{\link{mvgam}} \code{\link[brms]{prior}}
#'@return either a \code{data.frame} containing the prior definitions (if any suitable
#'priors can be altered by the user) or \code{NULL}, indicating that no priors in the model
#'can be modified through the `mvgam` interface
Expand Down
10 changes: 2 additions & 8 deletions R/hindcast.mvgam.R
Original file line number Diff line number Diff line change
@@ -1,23 +1,17 @@
#'@title Extract hindcasts for a fitted \code{mvgam} object
#'@name hindcast.mvgam
#'@importFrom stats predict
#'@param object \code{list} object returned from \code{mvgam}. See [mvgam()]
#'@inheritParams predict.mvgam
#'@param series Either a \code{integer} specifying which series in the set is to be forecast,
#'or the character string \code{'all'}, specifying that all series should be forecast. This is preferable
#'if the fitted model contained multivariate trends (either as a dynamic factor or \code{VAR} process),
#'as it saves recomputing the full set of trends for each series individually
#'@param type When this has the value \code{link} the linear predictor is calculated on the link scale.
#'If \code{expected} is used, predictions reflect the expectation of the response (the mean)
#'but ignore uncertainty in the observation process. When \code{response} (default) is used,
#'the predictions take uncertainty in the observation process into account to return
#'predictions on the outcome scale. When \code{trend} is used, only the hindcast distribution for the
#'latent trend is returned
#'@param ... Ignored
#'@details Posterior retrodictions are drawn from the fitted \code{mvgam} and
#'organized into a convenient format
#'@return An object of class \code{mvgam_forecast} containing hindcast distributions.
#'See \code{\link{mvgam_forecast-class}} for details.
#'
#'#'@seealso \code{\link{forecast.mvgam}}
#'@export
hindcast <- function(object, ...){
UseMethod("hindcast", object)
Expand Down
2 changes: 1 addition & 1 deletion R/index-mvgam.R
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ NULL

#' @rdname index-mvgam
#' @importFrom posterior variables
#' @param x \code{list} object of class `mvgam`
#' @param x \code{list} object returned from \code{mvgam}. See [mvgam()]
#' @method variables mvgam
#' @export
#' @export variables
Expand Down
21 changes: 17 additions & 4 deletions R/mcmc_plot.mvgam.R
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,18 @@
#' @param type The type of the plot.
#' Supported types are (as names) \code{hist}, \code{dens},
#' \code{hist_by_chain}, \code{dens_overlay},
#' \code{violin}, \code{intervals}, \code{areas}, \code{acf},
#' \code{acf_bar},\code{trace}, \code{trace_highlight}, \code{scatter},
#' \code{violin}, \code{intervals}, \code{areas},
#' \code{areas_ridges}, \code{combo}, \code{acf},
#' \code{acf_bar}, \code{trace}, \code{trace_highlight},
#' \code{scatter}, \code{hex}, \code{pairs}, \code{violin},
#' \code{rhat}, \code{rhat_hist}, \code{neff}, \code{neff_hist}
#' and \code{nuts_energy}.
#' For an overview on the various plot types see
#' \code{\link[bayesplot:MCMC-overview]{MCMC-overview}}.
#' @return A \code{\link[ggplot2:ggplot]{ggplot}} object
#' that can be further customized using the \pkg{ggplot2} package.
#'
#' @seealso \code{\link{mvgam_draws}} for an overview of some of the shortcut strings
#' that can be used for argument `variable`
#' @examples
#' \dontrun{
#' simdat <- sim_mvgam(n_series = 1, trend_model = 'AR1')
Expand All @@ -26,6 +29,8 @@
#' data = simdat$data_train)
#' mcmc_plot(mod)
#' mcmc_plot(mod, type = 'neff_hist')
#' mcmc_plot(mod, variable = 'betas', type = 'areas')
#' mcmc_plot(mod, variable = 'trend_params', type = 'combo')
#' }
#' @export
mcmc_plot.mvgam = function(object,
Expand Down Expand Up @@ -75,13 +80,21 @@ mcmc_plot.mvgam = function(object,
# x refers to a data.frame of draws
draws <- as.array(object, variable = variable, regex = regex,
use_alias = use_alias)
sel_variables <- dimnames(draws)[[2]]
sel_variables <- dimnames(draws)$variable
if(type %in% c("scatter", "hex") && length(sel_variables) != 2L){
stop("Exactly 2 parameters must be selected for this type.",
"\nParameters selected: ",
paste0("'", sel_variables, "'", collapse = ", "),
call. = FALSE)
}

if(type == 'pairs' && length(sel_variables) == 1L){
stop("2 or more parameters must be selected for this type.",
"\nParameters selected: ",
paste0("'", sel_variables, "'", collapse = ", "),
call. = FALSE)
}

mcmc_args$x <- draws
}
}
Expand Down
1 change: 1 addition & 0 deletions R/mvgam.R
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
#' \item`student_t()` for real-valued data
#' \item`Gamma()` for non-negative real-valued data}
#'Note that only `nb()` and `poisson()` are available if using `JAGS` as the backend.
#'Default is `poisson()`.
#'See \code{\link{mvgam_families}} for more details
#'@param use_lv \code{logical}. If \code{TRUE}, use dynamic factors to estimate series'
#'latent trends in a reduced dimension format. Defaults to \code{FALSE}
Expand Down
3 changes: 1 addition & 2 deletions R/plot.mvgam.R
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
#'
#'This function takes a fitted \code{mvgam} object and produces plots of smooth functions, forecasts, trends and
#'uncertainty components
#'
#'@param x \code{list} object returned from \code{mvgam}. See [mvgam()]
#'@param type \code{character} specifying which type of plot to return. Options are:
#'series,
Expand All @@ -14,7 +13,7 @@
#'trend,
#'uncertainty,
#'factors
#'@param residuals \code{logical}. If \code{TRUE} and `type = residuals`, posterior quantiles of partial residuals are added
#'@param residuals \code{logical}. If \code{TRUE} and `type = 'smooths'`, posterior quantiles of partial residuals are added
#'to plots of 1-D smooths as a series of ribbon rectangles.
#'Partial residuals for a smooth term are the median Dunn-Smyth residuals that would be obtained by dropping the term
#'concerned from the model, while leaving all other estimates fixed (i.e. the
Expand Down
2 changes: 1 addition & 1 deletion R/plot_mvgam_factors.R
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
#'This function takes a fitted \code{mvgam} object and returns plots and summary statistics for
#'the latent dynamic factors
#'
#'@param object \code{list} object returned from \code{mvgam}
#'@inheritParams plot.mvgam
#'@param plot \code{logical} specifying whether factors should be plotted
#'@author Nicholas J Clark
#'@details If the model in \code{object} was estimated using dynamic factors, it is possible that not all factors
Expand Down
2 changes: 1 addition & 1 deletion R/plot_mvgam_fc.R
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#'Plot mvgam posterior predictions for a specified series
#'@importFrom stats formula terms
#'@param object \code{list} object returned from \code{mvgam}
#'@inheritParams plot.mvgam
#'@param series \code{integer} specifying which series in the set is to be plotted
#'@param newdata Optional \code{dataframe} or \code{list} of test data containing at least 'series' and 'time'
#'in addition to any other variables included in the linear predictor of the original \code{formula}. If included, the
Expand Down
4 changes: 1 addition & 3 deletions R/plot_mvgam_pterms.R
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@
#'
#'@importFrom graphics layout title rug bxp
#'@importFrom stats coef predict
#'@param object \code{list} object returned from \code{mvgam}
#'@param trend_effects logical. If `TRUE` and a `trend_formula` was used in model
#'fitting, terms from the trend (i.e. process) model will be plotted
#'@inheritParams plot.mvgam
#'@details Posterior empirical quantiles of each parametric term's partial effect estimates
#'(on the link scale) are calculated and visualised as ribbon plots. These effects can
#'be interpreted as the partial effect that a parametric term contributes when all other
Expand Down
4 changes: 1 addition & 3 deletions R/plot_mvgam_randomeffects.R
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
#'This function plots posterior empirical quantiles for random effect smooths (bs = re)
#'
#'@importFrom graphics layout title
#'@param object \code{list} object returned from \code{mvgam}
#'@param trend_effects logical. If `TRUE` and a `trend_formula` was used in model
#'fitting, terms from the trend (i.e. process) model will be plotted
#'@inheritParams plot.mvgam
#'@details Posterior empirical quantiles of random effect coefficient estimates
#'(on the link scale) are calculated and visualised as ribbon plots.
#'Labels for coefficients are taken from the levels of the original factor variable
Expand Down
2 changes: 1 addition & 1 deletion R/plot_mvgam_resids.R
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
#'@importFrom graphics layout title
#'@importFrom stats complete.cases qqnorm qqline acf pacf na.pass
#'@importFrom mgcv bam
#'@param object \code{list} object returned from \code{mvgam}
#'@inheritParams plot.mvgam
#'@param series \code{integer} specifying which series in the set is to be plotted
#'@param newdata Optional \code{dataframe} or \code{list} of test data containing at least 'series', 'y', and 'time'
#'in addition to any other variables included in the linear predictor of \code{formula}. If included, the
Expand Down
4 changes: 1 addition & 3 deletions R/plot_mvgam_smooth.R
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@
#'
#'@importFrom grDevices hcl.colors
#'@importFrom stats quantile predict
#'@param object \code{list} object returned from \code{mvgam}
#'@param trend_effects logical. If `TRUE` and a `trend_formula` was used in model
#'fitting, terms from the trend (i.e. process) model will be plotted
#'@inheritParams plot.mvgam
#'@param series \code{integer} specifying which series in the set is to be plotted
#'@param smooth either a \code{character} or \code{integer} specifying which smooth term to be plotted
#'@param residuals \code{logical}. If \code{TRUE} then posterior quantiles of partial residuals are added
Expand Down
2 changes: 1 addition & 1 deletion R/plot_mvgam_trend.R
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#'Plot mvgam latent trend for a specified series
#'@importFrom graphics par lines polygon box abline
#'@importFrom stats sd quantile
#'@param object \code{list} object returned from \code{mvgam}
#'@inheritParams plot.mvgam
#'@param series \code{integer} specifying which series in the set is to be plotted
#'@param newdata Optional \code{dataframe} or \code{list} of test data containing at least 'series' and 'time'
#'in addition to any other variables included in the linear predictor of the original \code{formula}.
Expand Down
2 changes: 1 addition & 1 deletion R/plot_mvgam_uncertainty.R
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#'Plot mvgam forecast uncertainty contributions for a specified series
#'@importFrom graphics legend
#'@importFrom stats predict
#'@param object \code{list} object returned from \code{mvgam}
#'@inheritParams plot.mvgam
#'@param series \code{integer} specifying which series in the set is to be plotted
#'@param newdata A \code{dataframe} or \code{list} containing at least 'series' and 'time' for the forecast horizon, in
#'addition to any other variables included in the linear predictor of \code{formula}
Expand Down
14 changes: 14 additions & 0 deletions R/ppc.mvgam.R
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,21 @@
#'series (for \code{type == 'hist'}), kernel density or empirical CDF estimates for
#'posterior predictions (for \code{type == 'density'} or \code{type == 'cdf'}) or a Probability
#'Integral Transform histogram (for \code{type == 'pit'}).
#' @examples
#' \dontrun{
#' # Simulate some smooth effects and fit a model
#' set.seed(0)
#' dat <- mgcv::gamSim(1, n = 200, scale = 2)
#' dat$time <- 1:NROW(dat)
#' mod <- mvgam(y ~ s(x0) + s(x1) + s(x2) + s(x3),
#' data = dat,
#' family = gaussian())
#'
#' # Posterior checks
#' ppc(mod, type = 'hist')
#' ppc(mod, type = 'density')
#' ppc(mod, type = 'cdf')
#' }
#'@export
ppc <- function(object, ...){
UseMethod("ppc", object)
Expand Down
2 changes: 1 addition & 1 deletion R/predict.mvgam.R
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#'Predict from the GAM component of an mvgam model
#'@importFrom stats predict
#'@param object Object of class `mvgam`
#'@param object \code{list} object returned from \code{mvgam}. See [mvgam()]
#'@param newdata Optional \code{dataframe} or \code{list} of test data containing the
#'variables included in the linear predictor of \code{formula}. If not supplied,
#'predictions are generated for the original observations used for the model fit.
Expand Down
12 changes: 7 additions & 5 deletions R/score.mvgam_forecast.R
Original file line number Diff line number Diff line change
Expand Up @@ -32,21 +32,23 @@
#'will only contain the linear predictors
#'@examples
#'\dontrun{
#'#Simulate observations for three count-valued time series
#'# Simulate observations for three count-valued time series
#'data <- sim_mvgam()
#'#Fit a dynamic model using 'newdata' to automatically produce forecasts
#'# Fit a dynamic model using 'newdata' to automatically produce forecasts
#'mod <- mvgam(y ~ 1,
#' trend_model = 'RW',
#' data = data$data_train,
#' newdata = data$data_test)
#'
#'#Extract forecasts into a 'mvgam_forecast' object
#'# Extract forecasts into a 'mvgam_forecast' object
#'fc <- forecast(mod)
#'
#'#Score forecasts
#'score(fc, score = 'drps')
#'# Compute Discrete Rank Probability Scores and 0.90 interval coverages
#'fc_scores <- score(fc, score = 'drps')
#'str(fc_scores)
#'}
#'@method score mvgam_forecast
#'@seealso \code{\link{forecast.mvgam}}
#'@export
score.mvgam_forecast = function(object, score = 'crps',
log = FALSE, weights,
Expand Down
Loading

0 comments on commit 6c932ef

Please sign in to comment.