Skip to content

Commit

Permalink
get_parameter_dims for cmdstanr, docs
Browse files Browse the repository at this point in the history
  • Loading branch information
santikka committed Jul 14, 2024
1 parent 8b25865 commit 9709208
Show file tree
Hide file tree
Showing 57 changed files with 208 additions and 154 deletions.
10 changes: 5 additions & 5 deletions R/as_data_frame.R
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@
#' factors. Samples of the full correlation matrix can be extracted
#' manually as `rstan::extract(fit$stanfit, pars = "corr_matrix_psi")` if
#' necessary.
#' * `sigma`\cr Standard deviations of gaussian responses.
#' * `corr`\cr Pairwise correlations of multivariate gaussian responses.
#' * `sigma`\cr Standard deviations of Gaussian responses.
#' * `corr`\cr Pairwise correlations of multivariate Gaussian responses.
#' * `phi`\cr Describes various distributional parameters, such as:
#' - Dispersion parameter of the Negative Binomial distribution.
#' - Shape parameter of the Gamma distribution.
Expand Down Expand Up @@ -64,10 +64,10 @@
#' should be extracted. Possible options are elements of
#' `unique(x$priors$response)`, and the default is this entire vector.
#' Ignored if the argument `parameters` is supplied.
#' `omega_alpha`, and `omega_psi`. See also [dynamite::get_parameter_types()].
#' `omega_alpha`, and `omega_psi`. See also [get_parameter_types()].
#' @param times \[`double()`]\cr Time point(s) to keep. If `NULL`
#' (the default), all time points are kept.
#' @param groups \[`character()`] Group name(s) to keep. If `NULL`
#' @param groups \[`character()`]\cr Group name(s) to keep. If `NULL`
#' (the default), all groups are kept.
#' @param summary \[`logical(1)`]\cr If `TRUE`, returns posterior
#' mean, standard deviation, and posterior quantiles (as defined by the
Expand All @@ -82,7 +82,7 @@
#' @param ... Ignored.
#' @return A `tibble` containing either samples or summary statistics of the
#' model parameters in a long format. For a wide format, see
#' [dynamite::as_draws()].
#' [as_draws.dynamitefit()].
#' @examples
#' data.table::setDTthreads(1) # For CRAN
#' as.data.frame(
Expand Down
2 changes: 1 addition & 1 deletion R/as_data_table.R
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#' Extract Samples From a `dynamitefit` Object as a Data Table
#'
#' Provides a `data.table` representation of the posterior samples of the model
#' parameters. See [dynamite::as.data.frame.dynamitefit()] for details.
#' parameters. See [as.data.frame.dynamitefit()] for details.
#'
#' @export
#' @export as.data.table
Expand Down
11 changes: 5 additions & 6 deletions R/as_draws.R
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
#' Convert `dynamite` Output to `draws_df` Format
#'
#' Converts the output from a [dynamite::dynamite()] call to a
#' Converts the output from a [dynamite()] call to a
#' `draws_df` format of the \pkg{posterior} package, enabling the use
#' of diagnostics and plotting methods of \pkg{posterior} and \pkg{bayesplot}
#' packages. Note that this function returns variables in a wide format,
#' whereas [dynamite::as.data.frame()] uses the long format.
#' whereas [as.data.frame.dynamitefit()] uses the long format.
#'
#' You can use the arguments `parameters`, `responses` and `types` to extract
#' only a subset of the model parameters (i.e., only certain types of
#' parameters related to a certain response variable).
#'
#' See potential values for the types argument in
#' [dynamite::as.data.frame.dynamitefit()] and
#' [dynamite::get_parameter_names()] for potential values for `parameters`
#' argument.
#' See potential values for the types argument in [as.data.frame.dynamitefit()]
#' and [get_parameter_names()] for potential values for `parameters` argument.
#'
#' @export
#' @family output
#' @aliases as_draws_df
Expand Down
2 changes: 1 addition & 1 deletion R/ci.R
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#' Credible Intervals for Dynamite Model Parameters
#' Credible Intervals for \pkg{dynamite} Model Parameters
#'
#' Extracts credible intervals from `dynamitefit` object.
#'
Expand Down
2 changes: 1 addition & 1 deletion R/coef.R
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#' Extract Regression Coefficients of a Dynamite Model
#' Extract Regression Coefficients of a \pkg{dynamite} Model
#'
#' Extracts either time-varying or time-invariant parameters of the model.
#'
Expand Down
4 changes: 2 additions & 2 deletions R/deprecated.R
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#' Deprecated Functions in the dynamite Package
#' Deprecated Functions in the \pkg{dynamite} Package
#'
#' These functions are provided for compatibility with older versions of the
#' package. They will eventually be completely removed.
Expand All @@ -11,7 +11,7 @@
#' plot_lambdas(x, ...)
#' plot_psis(x, ...)
#' @return A `ggplot` object.
#' @seealso See [dynamite::plot.dynamitefit()] for documentation of the
#' @seealso See [plot.dynamitefit()] for documentation of the
#' parameters of these functions
#' @export plot_betas plot_deltas plot_nus plot_lambdas plot_psis
#' @aliases plot_betas plot_deltas plot_nus plot_lambdas plot_psis
Expand Down
2 changes: 1 addition & 1 deletion R/deterministic.R
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ assign_lags_init <- function(data, idx, ro, lhs, rhs, offset = 1L) {
#' Evaluate Definitions of Deterministic Channels
#'
#' @inheritParams parse_data
#' @param dformulas \[list()]\cr The return object of [dynamite::parse_lags()].
#' @param dformulas \[list()]\cr The return object of [parse_lags()].
#' @noRd
evaluate_deterministic <- function(dformulas, data, group_var, time_var) {
fixed <- as.integer(attr(dformulas$all, "max_lag"))
Expand Down
7 changes: 3 additions & 4 deletions R/dynamice.R
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
#'
#' Applies multiple imputation using [mice::mice()] to the supplied `data`
#' and fits a dynamic multivariate panel model to each imputed data set using
#' [dynamite::dynamite()]. Posterior samples from each imputation run are
#' [dynamite()]. Posterior samples from each imputation run are
#' combined. When using wide format imputation, the long format `data` is
#' automatically converted to a wide format before imputation to preserve the
#' longitudinal structure, and then converted back to long format for
Expand All @@ -19,11 +19,12 @@
#' kept in the return object? The default is `FALSE`. If `TRUE`, the
#' imputations will be included in the `imputed` field in the return object
#' that is otherwise `NULL`.
#' @param stan_csv_dir \[`character(1)`] A directory path to output the
#' @param stan_csv_dir \[`character(1)`]\cr A directory path to output the
#' Stan .csv files when `backend` is `"cmdstanr"`. The files are saved here
#' via `$save_output_files()` to avoid garbage collection between sampling
#' runs with different imputed datasets.
#' @export
#'
dynamice <- function(dformula, data, time, group = NULL,
priors = NULL, backend = "rstan",
verbose = TRUE, verbose_stan = FALSE,
Expand Down Expand Up @@ -150,9 +151,7 @@ dynamice <- function(dformula, data, time, group = NULL,
stanfit <- rstan::sflist2stanfit(sf)
} else {
stanfit <- cmdstanr::as_cmdstan_fit(filenames, check_diagnostics = FALSE)
#stanfit@stanmodel <- methods::new("stanmodel", model_code = tmp$model_code)
}
# TODO does this work in this case?
n_draws <- ifelse_(is.null(stanfit), 0L, get_ndraws(stanfit))
# TODO return object? How is this going to work with update?
structure(
Expand Down
25 changes: 13 additions & 12 deletions R/dynamite-package.R
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
#' The `dynamite` package.
#' The \pkg{dynamite} Package
#'
#' @description Easy-to-use and efficient interface for Bayesian inference of
#' complex panel data consisting of multiple individuals with multiple
#' measurements over time. Supports several observational distributions,
#' time-varying effects and realistic counterfactual predictions which take into
#' account the dynamic structure of the model.
#' measurements over time using dynamic multivariate panel models.
#' Supports several observational distributions, time-varying effects and
#' realistic counterfactual predictions which take into account the dynamic
#' structure of the model.
#'
#' # See Also
#'
#' * The package vignettes
#' * [dynamite::dynamiteformula()] for information on defining models.
#' * [dynamite::dynamite()] for information on fitting models.
#' * [dynamiteformula()] for information on defining models.
#' * [dynamite()] for information on fitting models.
#' * <https://github.com/ropensci/dynamite/issues/> to submit a bug report
#' or a feature request.
#'
Expand Down Expand Up @@ -47,12 +48,12 @@
#' recovered.
"_PACKAGE"

#' Simulated Data of Gaussian Responses
#' Simulated Data of a Gaussian Response
#'
#' Simulated data containing gaussian response variables with two covariates.
#' The dataset was generated from a model with time-varying effects of
#' covariate x and the lagged value of the response variable, time-varying
#' intercept, and time-invariant effect of covariate z. The time-varying
#' Simulated data containing a Gaussian response variable `y` with two
#' covariates. The dataset was generated from a model with time-varying effects
#' of covariate `x` and the lagged value of the response variable, time-varying
#' intercept, and time-invariant effect of covariate `z`. The time-varying
#' coefficients vary according to a spline with 20 degrees of freedom.
#'
#' @family examples
Expand All @@ -68,7 +69,7 @@
#' }
"gaussian_example"

#' Model Fit for the Simulated Data of Gaussian Responses
#' Model Fit for the Simulated Data of a Gaussian Response
#'
#' A `dynamitefit` object obtained by running `dynamite` on the
#' `gaussian_example` dataset as
Expand Down
9 changes: 4 additions & 5 deletions R/dynamite.R
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
#' * `priors`\cr Data frame containing the used priors.
#' * `backend`\cr Either `"rstan"` or `"cmdstanr"` indicating which
#' package was used in sampling.
#' * `permutation`\cr Randomized permutation of the posterior draws.
#' * `call`\cr Original function call as an object of class `call`.
#'
#' @srrstats {G2.9} Potential loss of information is reported by `dynamite`.
Expand Down Expand Up @@ -132,8 +133,8 @@
#' based on Stan, the scalability of the package depends directly on the
#' scalability of Stan.
#' @references
#' Santtu Tikka and Jouni Helske (2023). `dynamite`: An \R Package for Dynamic
#' Multivariate Panel Models. arXiv preprint,
#' Santtu Tikka and Jouni Helske (2023). \pkg{dynamite}: An \R Package for
#' Dynamic Multivariate Panel Models. arXiv preprint,
#' <https://arxiv.org/abs/2302.01607>.
#'
#' Jouni Helske and Santtu Tikka (2022). Estimating Causal Effects
Expand Down Expand Up @@ -496,8 +497,6 @@ dynamite_sampling <- function(sampling, backend, model_code, model,
out <- with(e, {
do.call(model$sample, args)
})
#out <- rstan::read_stan_csv(sampling_out$output_files())
#out@stanmodel <- methods::new("stanmodel", model_code = model_code)
}
}
out
Expand Down Expand Up @@ -700,7 +699,7 @@ remove_redundant_parameters <- function(stan_input, backend,
dots
}

#' Access the Model Formula of a Dynamite Model
#' Access the Model Formula of a \pkg{dynamite} Model
#'
#' The `formula` method returns the model definition as a quoted expression.
#'
Expand Down
8 changes: 4 additions & 4 deletions R/dynamiteformula.R
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#' Model formula for \pkg{dynamite}
#' Model Formula for \pkg{dynamite}
#'
#' Defines a new observational or a new auxiliary channel for the model using
#' standard \R formula syntax. Formulas of individual response variables can be
Expand All @@ -12,7 +12,7 @@
#'
#' * Categorical: `categorical` (with a softmax link using the first category
#' as reference). See the documentation of the `categorical_logit_glm` in the
#' Stan function reference manual (https://mc-stan.org/users/documentation/).
#' Stan function reference manual <https://mc-stan.org/users/documentation/>.
#' * Multinomial: `multinomial` (softmax link, first category is reference).
#' * Gaussian: `gaussian` (identity link, parameterized using mean and standard
#' deviation).
Expand All @@ -37,7 +37,7 @@
#' combined with `+`. For example a formula
#' `obs(y ~ lag(x), family = "gaussian") + obs(x ~ z, family = "poisson")`
#' defines a model with two channels;
#' first we declare that `y` is a gaussian variable depending on a previous
#' first we declare that `y` is a Gaussian variable depending on a previous
#' value of `x` (`lag(x)`), and then we add a second channel declaring `x` as
#' Poisson distributed depending on some exogenous variable `z`
#' (for which we do not define any distribution).
Expand Down Expand Up @@ -106,7 +106,7 @@
#' `random(~1)` leads to a model where in addition to the common intercept,
#' each individual/group has their own intercept with zero-mean normal prior and
#' unknown standard deviation analogously with the typical mixed models. An
#' additional model component [dynamite::random_spec()] can be used to define
#' additional model component [random_spec()] can be used to define
#' whether the random effects are allowed to correlate within and across
#' channels and whether to use centered or noncentered parameterization for
#' the random effects.
Expand Down
8 changes: 4 additions & 4 deletions R/fitted.R
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
#' Extract Fitted Values of a Dynamite Model
#' Extract Fitted Values of a \pkg{dynamite} Model
#'
#' Fitted values for a `dynamitefit` object, i.e.,
#' \eqn{E(y_t | newdata, \theta)} where \eqn{\theta} contains all the
#' model parameters. See also
#' [dynamite::predict.dynamitefit()] for multi-step predictions.
#' model parameters. See also [predict.dynamitefit()] for multi-step
#' predictions.
#'
#' @export
#' @family prediction
Expand Down Expand Up @@ -55,7 +55,7 @@
#' ggplot2::geom_line(ggplot2::aes(y = LakeHuron), colour = "tomato") +
#' ggplot2::theme_bw()
#' }
#' }
#' }
#' }
#'
fitted.dynamitefit <- function(object, newdata = NULL, n_draws = NULL, thin = 1,
Expand Down
35 changes: 23 additions & 12 deletions R/getters.R
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
#' Get Prior Definitions of a Dynamite Model
#' Get Prior Definitions of a \pkg{dynamite} Model
#'
#' Extracts the priors used in the dynamite model as a data frame. You
#' Extracts the priors used in the `dynamite` model as a data frame. You
#' can then alter the priors by changing the contents of the `prior` column and
#' supplying this data frame to `dynamite` function using the argument
#' `priors`. See vignettes for details.
#'
#' @note Only the `prior` column of the output should be altered when defining
#' the user-defined priors for the `dynamite`.
#' the user-defined priors for `dynamite`.
#'
#' @export
#' @family fitting
Expand Down Expand Up @@ -48,7 +48,7 @@ get_priors.dynamitefit <- function(x, ...) {
x$priors
}

#' Extract the Stan Code of the Dynamite Model
#' Extract the Stan Code of the \pkg{dynamite} Model
#'
#' Returns the Stan code of the model. Mostly useful for debugging or for
#' building a customized version of the model.
Expand Down Expand Up @@ -156,7 +156,7 @@ get_code_ <- function(x, blocks = NULL) {
paste_rows(out, .parse = FALSE)
}

#' Extract the Model Data of the Dynamite Model
#' Extract the Model Data of the \pkg{dynamite} Model
#'
#' Returns the input data to the Stan model. Mostly useful for debugging.
#'
Expand Down Expand Up @@ -206,11 +206,11 @@ get_data.dynamitefit <- function(x, ...) {
out$stan_input$sampling_vars
}

#' Get Parameter Dimensions of the Dynamite Model
#' Get Parameter Dimensions of the \pkg{dynamite} Model
#'
#' Extracts the names and dimensions of all parameters used in the
#' `dynamite` model. See also [dynamite::get_parameter_types()] and
#' [dynamite::get_parameter_names()]. The returned dimensions match those of
#' `dynamite` model. See also [get_parameter_types()] and
#' [get_parameter_names()]. The returned dimensions match those of
#' the `stanfit` element of the `dynamitefit` object. When applied to
#' `dynamiteformula` objects, the model is compiled and sampled for 1 iteration
#' to get the parameter dimensions.
Expand Down Expand Up @@ -267,6 +267,17 @@ get_parameter_dims.dynamitefit <- function(x, ...) {
!is.null(x$stanfit),
"No Stan model fit is available."
)
if (x$backend == "cmdstanr") {
return(
get_parameter_dims.dynamiteformula(
x = eval(formula(x)),
data = x$data,
time = x$time_var,
group = x$group_var,
...
)
)
}
pars_text <- get_code(x, blocks = "parameters")
pars <- get_parameters(pars_text)
# TODO no inits
Expand Down Expand Up @@ -298,10 +309,10 @@ get_parameters <- function(x) {
vapply(par_matches, "[[", character(1L), 2L)
}

#' Get Parameter Types of the Dynamite Model
#' Get Parameter Types of the \pkg{dynamite} Model
#'
#' Extracts all parameter types of used in the `dynamitefit` object. See
#' [dynamite::as.data.frame.dynamitefit()] for explanations of different types.
#' [as.data.frame.dynamitefit()] for explanations of different types.
#'
#' @param x \[`dynamitefit`]\cr The model fit object.
#' @param ... Ignored.
Expand All @@ -323,7 +334,7 @@ get_parameter_types.dynamitefit <- function(x, ...) {
unique(d$type)
}

#' Get Parameter Names of the Dynamite Model
#' Get Parameter Names of the \pkg{dynamite} Model
#'
#' Extracts all parameter names of used in the `dynamitefit` object.
#'
Expand All @@ -336,7 +347,7 @@ get_parameter_types.dynamitefit <- function(x, ...) {
#'
#' @param x \[`dynamitefit`]\cr The model fit object.
#' @param types \[`character()`]\cr Extract only names of parameter of a
#' certain type. See [dynamite::get_parameter_types()].
#' certain type. See [get_parameter_types()].
#' @param ... Ignored.
#' @return A `character` vector with parameter names of the input model.
#' @export
Expand Down
2 changes: 1 addition & 1 deletion R/lags.R
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#' Add Lagged Responses as Predictors to Each Channel of a Dynamite Model
#' Add Lagged Responses as Predictors to Each Channel of a \pkg{dynamite} Model
#'
#' Adds the lagged value of the response of each channel specified via
#' [dynamiteformula()] as a predictor to each channel. The added predictors
Expand Down
4 changes: 2 additions & 2 deletions R/latent_factor.R
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#' Define a Common Latent Factor for the Dynamite Model.
#' Define a Common Latent Factor for the \pkg{dynamite} Model.
#'
#' This function can be used as part of [dynamite::dynamiteformula()] to define
#' This function can be used as part of a [dynamiteformula()] to define
#' a common latent factor component. The latent factor is modeled as a spline
#' similarly as a time-varying intercept, but instead of having equal effect on
#' each group, there is an additional loading variable for each group so that
Expand Down
Loading

0 comments on commit 9709208

Please sign in to comment.