Package 'stanr'

Title: A Modern R Interface for Stan
Description: A modern, simpler R interface for Stan.
Authors: Andrew R. Johnson [aut, cre] (ORCID: <https://orcid.org/0000-0001-7000-8065>), Stan Development Team [cph] (Stan sources and headers), Walnutpie Developers [cph] (Walnutpie sources and headers), Lawrence Livermore National Security [cph] (SUNDIALS sources and headers), Intel Corporation [cph] (TBB sources and headers), Posit Software, PBC [cph] (cpp11 sources and headers)
Maintainer: Andrew R. Johnson <[email protected]>
License: BSD_3_clause + file LICENSE
Version: 0.1.5
Built: 2026-10-07 13:21:01 UTC
Source: https://github.com/andrjohns/stanr

Help Index


The stanr package.

Description

A modern, simpler R interface for Stan. Bundles all required Stan, Eigen, and TBB headers internally.

Author(s)

Maintainer: Andrew R. Johnson [email protected] (ORCID)

Authors:

Other contributors:

  • Stan Development Team (Stan sources and headers) [copyright holder]

  • Walnutpie Developers (Walnutpie sources and headers) [copyright holder]

  • Lawrence Livermore National Security (SUNDIALS sources and headers) [copyright holder]

  • Intel Corporation (TBB sources and headers) [copyright holder]

  • Posit Software, PBC (cpp11 sources and headers) [copyright holder]

See Also

Useful links:


Gradient diagnostic results

Description

Access gradient checking results from a StanDiagnose object.

gradients()
lp()
num_failed()

Value

  • ⁠$gradients()⁠ returns a data frame with gradient check results for each parameter, including columns param_idx, value, model, finite_diff, and error.

  • ⁠$lp()⁠ returns the log probability evaluated at the initial parameter values.

  • ⁠$num_failed()⁠ returns the number of parameters that failed the gradient check.

See Also

$draws()

Other StanFit methods: fit-method-draws, fit-method-expose-stan-functions, fit-method-fit-info, fit-method-gq, fit-method-laplace-mode, fit-method-loo, fit-method-lp, fit-method-mcmc, fit-method-mle, fit-method-model-methods, fit-method-print, fit-method-save, fit-method-summary


Extract posterior draws

Description

Extract draws or point estimates from fitted model objects using formats provided by the posterior package. Depending on the fitting method, these are posterior draws from MCMC, approximate posterior draws from variational inference, Laplace approximation, or Pathfinder, standalone generated quantities, or a point estimate from optimization.

Arguments

variables

(character vector) Which variables to extract. If NULL (the default), all variables are returned.

inc_warmup

(logical) Should warmup draws be included? Defaults to FALSE. Errors unless the fit is a $sample() run with save_warmup = TRUE.

format

(string) The format of the returned draws. Must be a valid format from the posterior package. Defaults depend on the fitting method: "draws_array" for MCMC and generated quantities, "draws_matrix" for all other methods.

Value

An object from the posterior package in the requested format.

See Also

$summary()

Other StanFit methods: fit-method-diagnose, fit-method-expose-stan-functions, fit-method-fit-info, fit-method-gq, fit-method-laplace-mode, fit-method-loo, fit-method-lp, fit-method-mcmc, fit-method-mle, fit-method-model-methods, fit-method-print, fit-method-save, fit-method-summary


Expose Stan functions from a fitted model

Description

The ⁠$expose_stan_functions()⁠ method of a StanFit object delegates to the bound StanModel's $expose_stan_functions() – see that topic for the full description of global/verbose, ⁠_rng⁠ reproducibility, caching, and the serialization caveat. ⁠$expose_functions()⁠ is an alias. ⁠$functions⁠ is a read-only active binding returning the model's ⁠$functions⁠ environment – shared with the model and with every other fit from the same model, since exposure is memoized on the model, not per fit.

expose_stan_functions(global = FALSE, verbose = FALSE)
expose_functions(global = FALSE, verbose = FALSE)

Arguments

global

(logical) Should the exposed functions also be assigned into the global environment?

verbose

(logical) Should compiler progress messages be printed?

Value

⁠$expose_stan_functions()⁠/⁠$expose_functions()⁠ return the model's ⁠$functions⁠ environment, invisibly. Both methods, and reading ⁠$functions⁠, error if this fit does not retain a model binding (e.g. after restoring a fit that was saved without its model).

See Also

$expose_stan_functions()

Other StanFit methods: fit-method-diagnose, fit-method-draws, fit-method-fit-info, fit-method-gq, fit-method-laplace-mode, fit-method-loo, fit-method-lp, fit-method-mcmc, fit-method-mle, fit-method-model-methods, fit-method-print, fit-method-save, fit-method-summary


Access fit information

Description

These methods access information stored in a StanFit object.

return_codes()
metadata()
output()
time()
init()
code()

Value

  • ⁠$return_codes()⁠ returns an integer vector with the Stan service's return code replicated once per chain (the in-process services report a single code for the whole run). A return code of 0 indicates success.

  • ⁠$metadata()⁠ returns a named list of fit metadata including the seed, data, arguments, and model name. For adaptive MCMC fits, step_size_adaptation is a numeric vector of one adapted step size per chain; it is absent when sampling ran without adaptation.

  • ⁠$output()⁠ returns a character vector of Stan output messages from the run. Messages from all chains or paths are interleaved in one vector; per-chain attribution is not available.

  • ⁠$time()⁠ returns a list with timing information.

  • ⁠$init()⁠ returns the user-specified initial values, or NULL if none were provided.

  • ⁠$code()⁠ returns the Stan program as a string, or character() if the model is not available.

See Also

$draws()

Other StanFit methods: fit-method-diagnose, fit-method-draws, fit-method-expose-stan-functions, fit-method-gq, fit-method-laplace-mode, fit-method-loo, fit-method-lp, fit-method-mcmc, fit-method-mle, fit-method-model-methods, fit-method-print, fit-method-save, fit-method-summary


Generated quantities chain count

Description

Return the number of chains in a StanGQ object's draws.

Value

An integer giving the number of chains, or 0 if no draws are available.

See Also

$draws()

Other StanFit methods: fit-method-diagnose, fit-method-draws, fit-method-expose-stan-functions, fit-method-fit-info, fit-method-laplace-mode, fit-method-loo, fit-method-lp, fit-method-mcmc, fit-method-mle, fit-method-model-methods, fit-method-print, fit-method-save, fit-method-summary


Extract Laplace mode

Description

Return the mode (point estimate) used as the center of the Laplace approximation. This is either a StanMLE object from a prior call to $optimize(), or a numeric vector provided directly.

Value

The mode object or numeric vector.

See Also

$draws()

Other StanFit methods: fit-method-diagnose, fit-method-draws, fit-method-expose-stan-functions, fit-method-fit-info, fit-method-gq, fit-method-loo, fit-method-lp, fit-method-mcmc, fit-method-mle, fit-method-model-methods, fit-method-print, fit-method-save, fit-method-summary


Leave-one-out cross-validation (LOO-CV)

Description

The ⁠$loo()⁠ method computes approximate LOO-CV using the loo package. In order to use this method you must compute and save the pointwise log-likelihood in your Stan program. See loo::loo.array() and the loo package vignettes for details.

Arguments

variables

(string) The name of the variable in the Stan program containing the pointwise log-likelihood. The default is to look for "log_lik". This argument is passed to the $draws() method.

r_eff

(multiple options) How to handle the r_eff argument for loo(). r_eff measures the amount of autocorrelation in MCMC draws, and is used to compute more accurate ESS and MCSE estimates for pointwise and total ELPDs.

  • TRUE will call loo::relative_eff() to compute the r_eff argument to pass to loo::loo.array().

  • FALSE (the default) or NULL will avoid computing r_eff, which can be very slow. The reported ESS and MCSE estimates may be over-optimistic if the posterior draws are far from independent.

  • If r_eff is anything else, that object will be passed as the r_eff argument to loo::loo.array().

moment_match

(logical) Whether to use a moment-matching correction for problematic observations. The default is FALSE. Using moment_match = TRUE uses the fit's model methods (see fit-method-model-methods) to automatically supply the functions for the log_lik_i, unconstrain_pars, log_prob_upars, and log_lik_i_upars arguments to loo::loo_moment_match().

...

Other arguments (e.g., cores, save_psis, etc.) passed to loo::loo.array() or loo::loo_moment_match.default() (if moment_match = TRUE is set).

Value

The object returned by loo::loo.array() or loo::loo_moment_match.default().

References

  • Vehtari, A., Gelman, A., and Gabry, J. (2017). Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC. Statistics and Computing, 27(5), 1413-1432. doi:10.1007/s11222-016-9696-4.

  • Vehtari, A., Simpson, D., Gelman, A., Yao, Y., and Gabry, J. (2024). Pareto smoothed importance sampling. Journal of Machine Learning Research, 25(72), 1-58.

  • Paananen, T., Piironen, J., Buerkner, P.-C., and Vehtari, A. (2021). Implicitly adaptive importance sampling. Statistics and Computing, 31, 16. doi:10.1007/s11222-020-09982-2 (for moment_match = TRUE).

See Also

The loo package website with documentation and vignettes.

Other StanFit methods: fit-method-diagnose, fit-method-draws, fit-method-expose-stan-functions, fit-method-fit-info, fit-method-gq, fit-method-laplace-mode, fit-method-lp, fit-method-mcmc, fit-method-mle, fit-method-model-methods, fit-method-print, fit-method-save, fit-method-summary


Extract log density draws

Description

Extract the log density (lp__) or log density approximation (lp_approx__) as a numeric vector. ⁠$lp_approx()⁠ is only available on StanLaplace, StanVB, and StanPathfinder objects.

lp()
lp_approx()

Value

A numeric vector, with one element per (post-warmup) draw, or a single value for optimization.

See Also

$draws()

Other StanFit methods: fit-method-diagnose, fit-method-draws, fit-method-expose-stan-functions, fit-method-fit-info, fit-method-gq, fit-method-laplace-mode, fit-method-loo, fit-method-mcmc, fit-method-mle, fit-method-model-methods, fit-method-print, fit-method-save, fit-method-summary


MCMC-specific methods

Description

Methods specific to StanMCMC objects for accessing sampler diagnostics, chain information, and model evaluation.

sampler_diagnostics(inc_warmup = FALSE, format = "draws_array")
num_chains()
diagnostic_summary(diagnostics = c("divergences", "treedepth", "ebfmi"),
                    quiet = FALSE)
inv_metric(matrix = TRUE)
loo(variables = "log_lik", r_eff = FALSE, moment_match = FALSE, ...)

Arguments

matrix

(logical) For ⁠$inv_metric()⁠: return each chain's inverse metric as a matrix? For a diagonal metric, TRUE (the default) wraps the adapted diagonal in diag(); FALSE returns it as a vector. For a dense metric, the matrix is always returned and matrix = FALSE is an error.

diagnostics

(character vector) For ⁠$diagnostic_summary()⁠: which diagnostics to check. One or more of "divergences", "treedepth", and "ebfmi". The default checks all three; NULL or "" checks none.

quiet

(logical) For ⁠$diagnostic_summary()⁠: should messages about problems found in the requested diagnostics be suppressed? The default, FALSE, prints them in addition to returning the values. Diagnostics that could not be computed at all (rather than computed and found problematic) always warn, regardless of quiet.

Value

  • ⁠$sampler_diagnostics()⁠ returns sampler diagnostics (e.g., divergent__, treedepth__, accept__) as a posterior draws object.

  • ⁠$num_chains()⁠ returns the number of MCMC chains.

  • ⁠$diagnostic_summary()⁠ returns a list with one element per requested diagnostic: num_divergent (divergent transitions per chain), num_max_treedepth (iterations per chain that hit the max treedepth), and/or ebfmi (E-BFMI per chain). An element is NA for every chain if the corresponding diagnostic was not collected (e.g. divergent__/ treedepth__/energy__ are unavailable for the static and walnuts engines, or are all-NA for fixed_param runs).

  • ⁠$inv_metric()⁠ returns a list (one element per chain) of the inverse mass matrix adapted during sampling. Errors if the fit was not sampled with adaptation.

  • ⁠$loo()⁠ returns a LOO-CV object from the loo package.

See Also

$draws(), $loo()

Other StanFit methods: fit-method-diagnose, fit-method-draws, fit-method-expose-stan-functions, fit-method-fit-info, fit-method-gq, fit-method-laplace-mode, fit-method-loo, fit-method-lp, fit-method-mle, fit-method-model-methods, fit-method-print, fit-method-save, fit-method-summary


Extract point estimate

Description

Extract the maximum likelihood or maximum a posteriori estimate from a StanMLE object as a named numeric vector.

Arguments

variables

(character vector) Which variables to extract. If NULL (the default), all variables are returned.

Value

A named numeric vector of parameter estimates. Always reflects the final optimization iteration, regardless of whether $optimize() was run with save_iterations = TRUE.

See Also

$draws(), which under save_iterations = TRUE returns the full optimization path (one row per saved iteration) instead of a single row for the final estimate.

Other StanFit methods: fit-method-diagnose, fit-method-draws, fit-method-expose-stan-functions, fit-method-fit-info, fit-method-gq, fit-method-laplace-mode, fit-method-loo, fit-method-lp, fit-method-mcmc, fit-method-model-methods, fit-method-print, fit-method-save, fit-method-summary


Compute log probability and transformations

Description

These methods compute the log probability, gradients, Hessians, and parameter transformations using the compiled Stan model. They require the model to be available, and lazily initialize the native model pointer on first use.

log_prob(unconstrained_variables, jacobian = TRUE)
grad_log_prob(unconstrained_variables, jacobian = TRUE)
hessian(unconstrained_variables, jacobian = TRUE)
constrain_variables(unconstrained_variables,
                    transformed_parameters = TRUE,
                    generated_quantities = TRUE)
unconstrain_variables(variables)
unconstrain_draws(draws = NULL, format = NULL, inc_warmup = FALSE)
variable_skeleton(transformed_parameters = TRUE,
                  generated_quantities = TRUE)

Arguments

unconstrained_variables

(numeric vector) The unconstrained parameter values at which to evaluate the function.

jacobian

(logical) Should the log density be adjusted by the abs-determinant of the Jacobian of the inverse transformation?

variables

(named list) Constrained parameter values to unconstrain.

draws

A posterior draws object, or NULL to use the fit's draws.

format

(string) The format of the returned draws. Must be a valid format from the posterior package. Defaults depend on the fitting method: "draws_array" for MCMC and generated quantities, "draws_matrix" for all other methods.

inc_warmup

(logical) Should warmup draws be included? Defaults to FALSE. Errors unless the fit is a $sample() run with save_warmup = TRUE.

transformed_parameters

(logical) Include transformed parameters?

generated_quantities

(logical) Include generated quantities?

Value

  • ⁠$log_prob()⁠ returns the log probability as a numeric scalar.

  • ⁠$grad_log_prob()⁠ returns the gradient as a numeric vector, with the log probability attached as the log_prob attribute.

  • ⁠$hessian()⁠ returns a list with elements log_prob, grad_log_prob, and hessian.

  • ⁠$constrain_variables()⁠ returns a named list of constrained parameter values.

  • ⁠$unconstrain_variables()⁠ returns a numeric vector of unconstrained parameter values.

  • ⁠$unconstrain_draws()⁠ returns a posterior draws object with unconstrained parameter values.

  • ⁠$variable_skeleton()⁠ returns a named list with the structure of the constrained parameter space.

See Also

Other StanFit methods: fit-method-diagnose, fit-method-draws, fit-method-expose-stan-functions, fit-method-fit-info, fit-method-gq, fit-method-laplace-mode, fit-method-loo, fit-method-lp, fit-method-mcmc, fit-method-mle, fit-method-print, fit-method-save, fit-method-summary


Print fit summary

Description

Print a summary table of posterior draws or point estimates.

Arguments

digits

(integer) Number of digits for numeric summary statistics.

max_rows

(integer) Maximum number of rows to print.

Value

The fitted model object, invisibly.

See Also

$summary()

Other StanFit methods: fit-method-diagnose, fit-method-draws, fit-method-expose-stan-functions, fit-method-fit-info, fit-method-gq, fit-method-laplace-mode, fit-method-loo, fit-method-lp, fit-method-mcmc, fit-method-mle, fit-method-model-methods, fit-method-save, fit-method-summary


Save fitted model object

Description

Methods for saving fitted model objects.

save_object(file, ...)

Arguments

file

(string) Path where the file should be saved.

...

Additional arguments passed to base::saveRDS().

Value

  • ⁠$save_object()⁠ returns the normalized file path, invisibly.

See Also

$draws()

Other StanFit methods: fit-method-diagnose, fit-method-draws, fit-method-expose-stan-functions, fit-method-fit-info, fit-method-gq, fit-method-laplace-mode, fit-method-loo, fit-method-lp, fit-method-mcmc, fit-method-mle, fit-method-model-methods, fit-method-print, fit-method-summary


Summarize posterior draws

Description

Compute summary statistics for posterior draws or point estimates using posterior::summarise_draws().

Arguments

...

Additional arguments passed to posterior::summarise_draws().

Value

A data frame of summary statistics.

See Also

$draws(), $print()

Other StanFit methods: fit-method-diagnose, fit-method-draws, fit-method-expose-stan-functions, fit-method-fit-info, fit-method-gq, fit-method-laplace-mode, fit-method-loo, fit-method-lp, fit-method-mcmc, fit-method-mle, fit-method-model-methods, fit-method-print, fit-method-save


Check Stan program syntax

Description

The ⁠$check_syntax()⁠ method of a StanModel object runs the Stan program through stanc without compiling the generated C++. It is a cheap way to validate a program before calling $compile().

Arguments

pedantic

(logical) Should stanc's pedantic-mode warnings be requested? The default is FALSE.

quiet

(logical) Should the success message be suppressed? The default is FALSE.

Value

TRUE, invisibly. Errors if the program has a syntax error.

See Also

$compile()

Other StanModel methods: model-method-compile, model-method-diagnose, model-method-expose-stan-functions, model-method-format, model-method-generate-quantities, model-method-laplace, model-method-model-info, model-method-optimize, model-method-pathfinder, model-method-sample, model-method-variables, model-method-variational


Compile a Stan program

Description

The ⁠$compile()⁠ method of a StanModel object compiles the Stan program using the in-process backend. In most cases the user does not need to explicitly call ⁠$compile()⁠ as compilation occurs automatically when calling stan_model(). However it is possible to set compile = FALSE in the call to stan_model() and subsequently call ⁠$compile()⁠ directly.

Arguments

force_recompile

(logical) Should the model be recompiled even if it has not been modified since it was last compiled? The default is FALSE.

quiet

(logical) Should verbose output from compilation be suppressed? The default is TRUE.

compile_standalone

(logical) Should the Stan program's functions block be exposed as part of this compilation? Defaults to whatever was set at stan_model() construction time. See $expose_stan_functions().

Value

The StanModel object, invisibly.

See Also

$is_compiled() and stan_model()

Other StanModel methods: model-method-check-syntax, model-method-diagnose, model-method-expose-stan-functions, model-method-format, model-method-generate-quantities, model-method-laplace, model-method-model-info, model-method-optimize, model-method-pathfinder, model-method-sample, model-method-variables, model-method-variational


Run gradient diagnostics

Description

The ⁠$diagnose()⁠ method of a StanModel object runs Stan's "diagnose" method to check the correctness of gradients computed by Stan. Returns a StanDiagnose object.

Arguments

data

(named list) Values for all or part of the data block in the Stan program. Each element is named after the corresponding Stan variable and shaped as follows:

Stan type R shape
complex complex scalar (e.g. 1+2i)
complex_vector[n], complex_row_vector[n], ⁠array[n] complex⁠ complex vector of length n
complex_matrix[r, c] complex matrix, r x c
tuple(T1, ..., Tk) unnamed list of length k, element j shaped as Tj
⁠array[n] tuple(...)⁠ list of n tuple-shaped lists
⁠array[n, m] tuple(...)⁠ list (over the first index) of lists (over the second index) of tuples

A length-1 R vector is read as a scalar, so a vector[1], ⁠array[1] ...⁠, or length-1 tuple-slot container value must be given an explicit shape (as.array(x) or dim(x) <- 1L) to match its declared dimension.

Real-valued input is accepted wherever a complex type is declared – it is coerced automatically, including inside tuple slots. All other Stan types use their ordinary R representation (numeric/integer scalars, vectors, matrices, arrays).

As a power-user escape hatch, tuple variables can instead be supplied pre-flattened using dotted names (e.g. list(t.1 = ..., t.2 = ...) for a tuple t), bypassing the list-shape conversion above; this is not the primary documented path. One caveat applies: a dotted entry for a complex tuple slot is assumed to hold exactly one complex value per enclosing array element, which is only correct when that slot is itself a plain (non-container) complex – for anything else (e.g. a complex_vector tuple slot), use the list shapes above instead.

seed

(integer) The random seed for reproducibility.

init

Initial values for parameters. Either NULL (equivalent to the default radius of 2), a non-negative number, used as the range of CmdStan-style random initialization (Uniform(-init, init) on the unconstrained scale; the default is 2), or a named list / named numeric vector of constrained parameter values. Supplied values are shared by all chains; parameters not covered by the supplied values are randomly initialized with the default range. A named list may include tuple-shaped list entries and R complex values for tuple(...)/complex parameters, using the same canonical shapes (and the same dotted-name escape hatch) documented for data.

epsilon

(number) The finite difference step size.

error

(number) The maximum allowed relative error.

show_messages

(logical) When TRUE (the default), print progress and informational output (e.g. iteration and timing messages) to the console. Set to FALSE to silence it. Suppressed output is still recorded and available via the fit's ⁠$output()⁠ method.

show_exceptions

(logical) When TRUE (the default), print informational messages about numerical exceptions – e.g. Metropolis proposal rejections and rejected initial values. Set to FALSE to silence them. Suppressed messages are still recorded and available via the fit's ⁠$output()⁠ method.

Value

A StanDiagnose object containing gradient check results.

See Also

$sample()

Other StanModel methods: model-method-check-syntax, model-method-compile, model-method-expose-stan-functions, model-method-format, model-method-generate-quantities, model-method-laplace, model-method-model-info, model-method-optimize, model-method-pathfinder, model-method-sample, model-method-variables, model-method-variational


Expose Stan functions as R functions

Description

The ⁠$expose_stan_functions()⁠ method of a StanModel object compiles the functions declared in the Stan program's functions block and makes them callable from R. ⁠$expose_functions()⁠ is an alias (cmdstanr's name for the same method).

expose_stan_functions(global = FALSE, verbose = FALSE)
expose_functions(global = FALSE, verbose = FALSE)

Exposed functions are always assigned into the ⁠$functions⁠ member environment (e.g. mod$functions$my_fun(...)); global = TRUE additionally assigns each one into the global environment, so it can also be called directly (my_fun(...)). Repeat calls are cheap: once a model's functions have been compiled – whether by an earlier ⁠$expose_stan_functions()⁠ call, or automatically via compile_standalone = TRUE at stan_model() time – a later call just performs the requested ⁠$functions⁠/global assignments, without recompiling.

A Stan function whose name ends in ⁠_rng⁠ gets a trailing seed = NULL argument on its R wrapper. All exposed ⁠_rng⁠ functions share one underlying RNG, seeded once per ⁠$expose_stan_functions()⁠ call from R's own RNG stream (so calling set.seed() before exposing makes draws reproducible); passing seed explicitly to a call reseeds the generator immediately before that call.

Stan tuple(...) arguments/returns map to/from unnamed R lists (one element per slot; arrays of tuples become lists of such lists), and complex / complex_vector / complex_row_vector / complex_matrix map to/from R's native complex type. An overloaded Stan function (same name, different signature) exposes only the first-defined overload, with a warning.

Arguments

global

(logical) Should the exposed functions also be assigned into the global environment? The default, FALSE, only populates ⁠$functions⁠.

verbose

(logical) Should compiler progress messages be printed? No compilation happens (so this has no effect) if the functions were already compiled, e.g. via compile_standalone = TRUE.

Value

The StanModel object's ⁠$functions⁠ environment, invisibly.

Caching

Compiled functions are cached on disk the same way compiled models are (see stan_model()) – a warm cache skips recompilation entirely, including across R sessions.

Serialization

Exposed function objects in ⁠$functions⁠ are compiled bindings and, like any compiled function from this package, do not survive saveRDS()/readRDS(). After restoring a saved StanModel or StanFit, call ⁠$expose_stan_functions()⁠ again to repopulate ⁠$functions⁠ – this rebuilds from the on-disk cache and does not recompile.

See Also

stan_model() for the compile_standalone argument, which exposes functions as part of the model's own compilation.

Other StanModel methods: model-method-check-syntax, model-method-compile, model-method-diagnose, model-method-format, model-method-generate-quantities, model-method-laplace, model-method-model-info, model-method-optimize, model-method-pathfinder, model-method-sample, model-method-variables, model-method-variational


Format a Stan program

Description

The ⁠$format()⁠ method of a StanModel object reformats the Stan program using stanc's auto-formatter and returns the result as a string. Unlike $check_syntax(), it does not work on programs with unresolved ⁠#include⁠ directives, since formatting would inline their contents.

Arguments

overwrite_file

(logical) Should the formatted code be written back to $stan_file()? The default is FALSE. Requires a model created with stan_file, and does not update this object's in-memory code – construct a new StanModel to pick up the change.

canonicalize

(logical or character) FALSE (the default) formats without canonicalizing, TRUE also canonicalizes deprecated syntax, and a character vector requests specific canonicalizations (e.g. c("braces", "parentheses")).

backup

(logical) When overwrite_file = TRUE, should the original file be backed up first? The default is TRUE.

max_line_length

(integer) Maximum output line width. The default, NULL, uses stanc's default.

quiet

(logical) Should the backup message be suppressed? The default is FALSE.

Value

The formatted Stan code as a string.

See Also

$check_syntax(), $code()

Other StanModel methods: model-method-check-syntax, model-method-compile, model-method-diagnose, model-method-expose-stan-functions, model-method-generate-quantities, model-method-laplace, model-method-model-info, model-method-optimize, model-method-pathfinder, model-method-sample, model-method-variables, model-method-variational


Run generated quantities

Description

The ⁠$generate_quantities()⁠ method of a StanModel object runs Stan's "generate quantities" method, which evaluates the generated quantities block of the Stan program for a set of parameter values. Returns a StanGQ object.

Arguments

fitted_params

A StanFit object, or anything accepted by posterior::as_draws_matrix(), containing draws with every model parameter present by name (e.g. beta[1], not a positional column).

data

(named list) Values for all or part of the data block in the Stan program. Each element is named after the corresponding Stan variable and shaped as follows:

Stan type R shape
complex complex scalar (e.g. 1+2i)
complex_vector[n], complex_row_vector[n], ⁠array[n] complex⁠ complex vector of length n
complex_matrix[r, c] complex matrix, r x c
tuple(T1, ..., Tk) unnamed list of length k, element j shaped as Tj
⁠array[n] tuple(...)⁠ list of n tuple-shaped lists
⁠array[n, m] tuple(...)⁠ list (over the first index) of lists (over the second index) of tuples

A length-1 R vector is read as a scalar, so a vector[1], ⁠array[1] ...⁠, or length-1 tuple-slot container value must be given an explicit shape (as.array(x) or dim(x) <- 1L) to match its declared dimension.

Real-valued input is accepted wherever a complex type is declared – it is coerced automatically, including inside tuple slots. All other Stan types use their ordinary R representation (numeric/integer scalars, vectors, matrices, arrays).

As a power-user escape hatch, tuple variables can instead be supplied pre-flattened using dotted names (e.g. list(t.1 = ..., t.2 = ...) for a tuple t), bypassing the list-shape conversion above; this is not the primary documented path. One caveat applies: a dotted entry for a complex tuple slot is assumed to hold exactly one complex value per enclosing array element, which is only correct when that slot is itself a plain (non-container) complex – for anything else (e.g. a complex_vector tuple slot), use the list shapes above instead.

seed

(integer) The random seed for reproducibility.

num_threads

(integer) The total number of threads to use. Defaults to all available threads.

show_messages

(logical) When TRUE (the default), print progress and informational output (e.g. iteration and timing messages) to the console. Set to FALSE to silence it. Suppressed output is still recorded and available via the fit's ⁠$output()⁠ method.

show_exceptions

(logical) When TRUE (the default), print informational messages about numerical exceptions – e.g. Metropolis proposal rejections and rejected initial values. Set to FALSE to silence them. Suppressed messages are still recorded and available via the fit's ⁠$output()⁠ method.

opencl_ids

(integer vector) c(platform_id, device_id) identifying the OpenCL platform/device to run on. Only meaningful for a model compiled with use_opencl = TRUE (see stan_model()); errors if the model was not compiled with OpenCL support. Defaults to NULL, meaning select_opencl_device() is never called and the platform/device baked in at compile time (0/0) is used.

Value

A StanGQ object containing the generated quantities.

See Also

$sample()

Other StanModel methods: model-method-check-syntax, model-method-compile, model-method-diagnose, model-method-expose-stan-functions, model-method-format, model-method-laplace, model-method-model-info, model-method-optimize, model-method-pathfinder, model-method-sample, model-method-variables, model-method-variational


Run Laplace approximation

Description

The ⁠$laplace()⁠ method of a StanModel object runs Stan's "laplace" method to draw from a Gaussian approximation to the posterior centered at the mode. Returns a StanLaplace object.

Arguments

data

(named list) Values for all or part of the data block in the Stan program. Each element is named after the corresponding Stan variable and shaped as follows:

Stan type R shape
complex complex scalar (e.g. 1+2i)
complex_vector[n], complex_row_vector[n], ⁠array[n] complex⁠ complex vector of length n
complex_matrix[r, c] complex matrix, r x c
tuple(T1, ..., Tk) unnamed list of length k, element j shaped as Tj
⁠array[n] tuple(...)⁠ list of n tuple-shaped lists
⁠array[n, m] tuple(...)⁠ list (over the first index) of lists (over the second index) of tuples

A length-1 R vector is read as a scalar, so a vector[1], ⁠array[1] ...⁠, or length-1 tuple-slot container value must be given an explicit shape (as.array(x) or dim(x) <- 1L) to match its declared dimension.

Real-valued input is accepted wherever a complex type is declared – it is coerced automatically, including inside tuple slots. All other Stan types use their ordinary R representation (numeric/integer scalars, vectors, matrices, arrays).

As a power-user escape hatch, tuple variables can instead be supplied pre-flattened using dotted names (e.g. list(t.1 = ..., t.2 = ...) for a tuple t), bypassing the list-shape conversion above; this is not the primary documented path. One caveat applies: a dotted entry for a complex tuple slot is assumed to hold exactly one complex value per enclosing array element, which is only correct when that slot is itself a plain (non-container) complex – for anything else (e.g. a complex_vector tuple slot), use the list shapes above instead.

seed

(integer) The random seed for reproducibility.

init

Initial values for parameters. Either NULL (equivalent to the default radius of 2), a non-negative number, used as the range of CmdStan-style random initialization (Uniform(-init, init) on the unconstrained scale; the default is 2), or a named list / named numeric vector of constrained parameter values. Supplied values are shared by all chains; parameters not covered by the supplied values are randomly initialized with the default range. A named list may include tuple-shaped list entries and R complex values for tuple(...)/complex parameters, using the same canonical shapes (and the same dotted-name escape hatch) documented for data.

mode

A numeric vector of parameter values at the mode, or a StanMLE object from $optimize(). If NULL, optimization is run first.

opt_args

(list) Additional arguments to pass to $optimize() when finding the mode.

jacobian

(logical) Should the log density be adjusted by the abs-determinant of the Jacobian of the inverse transformation?

draws

(integer) The number of draws from the Laplace approximation.

calculate_lp

(logical) Should the log density of the Laplace approximation be calculated?

num_threads

(integer) The total number of threads to use. Defaults to all available threads.

show_messages

(logical) When TRUE (the default), print progress and informational output (e.g. iteration and timing messages) to the console. Set to FALSE to silence it. Suppressed output is still recorded and available via the fit's ⁠$output()⁠ method.

show_exceptions

(logical) When TRUE (the default), print informational messages about numerical exceptions – e.g. Metropolis proposal rejections and rejected initial values. Set to FALSE to silence them. Suppressed messages are still recorded and available via the fit's ⁠$output()⁠ method.

opencl_ids

(integer vector) c(platform_id, device_id) identifying the OpenCL platform/device to run on. Only meaningful for a model compiled with use_opencl = TRUE (see stan_model()); errors if the model was not compiled with OpenCL support. Defaults to NULL, meaning select_opencl_device() is never called and the platform/device baked in at compile time (0/0) is used.

Value

A StanLaplace object containing approximate posterior draws.

See Also

$optimize(), $variational()

Other StanModel methods: model-method-check-syntax, model-method-compile, model-method-diagnose, model-method-expose-stan-functions, model-method-format, model-method-generate-quantities, model-method-model-info, model-method-optimize, model-method-pathfinder, model-method-sample, model-method-variables, model-method-variational


Access information from a StanModel object

Description

These methods access information stored in a StanModel object and print its Stan program.

stan_file()
has_stan_file()
code()
print()
model_name()
include_paths()
stan_version()
is_compiled()
cpp_options()
stanc_options()
use_opencl()

Value

  • ⁠$stan_file()⁠ returns a path as a string, or character() if the model was created from code (not a file).

  • ⁠$has_stan_file()⁠ returns TRUE if the model was created with a Stan file and FALSE otherwise.

  • ⁠$code()⁠ returns the Stan program as a single string.

  • ⁠$print()⁠ prints the Stan program and returns the StanModel object invisibly.

  • ⁠$model_name()⁠ returns the model name as a string.

  • ⁠$include_paths()⁠ returns a character vector of absolute paths.

  • ⁠$stan_version()⁠ returns the Stan version bundled with the package as a string.

  • ⁠$is_compiled()⁠ returns TRUE if the model has been compiled.

  • ⁠$cpp_options()⁠ returns the cpp_options list the model was created with (see stan_model()).

  • ⁠$stanc_options()⁠ returns a named list of stanc options.

  • ⁠$use_opencl()⁠ returns TRUE if the model was created with use_opencl = TRUE and FALSE otherwise.

See Also

$compile() and stan_model()

Other StanModel methods: model-method-check-syntax, model-method-compile, model-method-diagnose, model-method-expose-stan-functions, model-method-format, model-method-generate-quantities, model-method-laplace, model-method-optimize, model-method-pathfinder, model-method-sample, model-method-variables, model-method-variational


Run optimization

Description

The ⁠$optimize()⁠ method of a StanModel object runs Stan's "optimize" method to find the maximum a posteriori (MAP) estimate or maximum likelihood estimate (MLE). Returns a StanMLE object.

Arguments

data

(named list) Values for all or part of the data block in the Stan program. Each element is named after the corresponding Stan variable and shaped as follows:

Stan type R shape
complex complex scalar (e.g. 1+2i)
complex_vector[n], complex_row_vector[n], ⁠array[n] complex⁠ complex vector of length n
complex_matrix[r, c] complex matrix, r x c
tuple(T1, ..., Tk) unnamed list of length k, element j shaped as Tj
⁠array[n] tuple(...)⁠ list of n tuple-shaped lists
⁠array[n, m] tuple(...)⁠ list (over the first index) of lists (over the second index) of tuples

A length-1 R vector is read as a scalar, so a vector[1], ⁠array[1] ...⁠, or length-1 tuple-slot container value must be given an explicit shape (as.array(x) or dim(x) <- 1L) to match its declared dimension.

Real-valued input is accepted wherever a complex type is declared – it is coerced automatically, including inside tuple slots. All other Stan types use their ordinary R representation (numeric/integer scalars, vectors, matrices, arrays).

As a power-user escape hatch, tuple variables can instead be supplied pre-flattened using dotted names (e.g. list(t.1 = ..., t.2 = ...) for a tuple t), bypassing the list-shape conversion above; this is not the primary documented path. One caveat applies: a dotted entry for a complex tuple slot is assumed to hold exactly one complex value per enclosing array element, which is only correct when that slot is itself a plain (non-container) complex – for anything else (e.g. a complex_vector tuple slot), use the list shapes above instead.

seed

(integer) The random seed for reproducibility.

init

Initial values for parameters. Either NULL (equivalent to the default radius of 2), a non-negative number, used as the range of CmdStan-style random initialization (Uniform(-init, init) on the unconstrained scale; the default is 2), or a named list / named numeric vector of constrained parameter values. Supplied values are shared by all chains; parameters not covered by the supplied values are randomly initialized with the default range. A named list may include tuple-shaped list entries and R complex values for tuple(...)/complex parameters, using the same canonical shapes (and the same dotted-name escape hatch) documented for data.

algorithm

(string) The optimization algorithm: "lbfgs", "bfgs", or "newton".

jacobian

(logical) Should the log density be adjusted by the abs-determinant of the Jacobian of the inverse transformation?

init_alpha

(number) Initial step size for LBFGS.

iter

(integer) Maximum number of optimization iterations.

tol_obj

(number) Absolute tolerance for changes in objective value.

tol_rel_obj

(number) Relative tolerance for changes in objective value.

tol_grad

(number) Absolute tolerance for the norm of the gradient.

tol_rel_grad

(number) Relative tolerance for the norm of the gradient.

tol_param

(number) Absolute tolerance for changes in parameter values.

history_size

(integer) Number of corrections in LBFGS approximation.

save_iterations

(logical) Should optimization iterations be saved? When TRUE, $draws() on the returned StanMLE exposes the full optimization path (one row per saved iteration, including the initial point) instead of a single row for the final estimate. $mle() is unaffected either way and always reflects the final iteration.

num_threads

(integer) The total number of threads to use. Defaults to all available threads.

show_messages

(logical) When TRUE (the default), print progress and informational output (e.g. iteration and timing messages) to the console. Set to FALSE to silence it. Suppressed output is still recorded and available via the fit's ⁠$output()⁠ method.

show_exceptions

(logical) When TRUE (the default), print informational messages about numerical exceptions – e.g. Metropolis proposal rejections and rejected initial values. Set to FALSE to silence them. Suppressed messages are still recorded and available via the fit's ⁠$output()⁠ method.

opencl_ids

(integer vector) c(platform_id, device_id) identifying the OpenCL platform/device to run on. Only meaningful for a model compiled with use_opencl = TRUE (see stan_model()); errors if the model was not compiled with OpenCL support. Defaults to NULL, meaning select_opencl_device() is never called and the platform/device baked in at compile time (0/0) is used.

Value

A StanMLE object containing the point estimate.

See Also

$sample(), $laplace()

Other StanModel methods: model-method-check-syntax, model-method-compile, model-method-diagnose, model-method-expose-stan-functions, model-method-format, model-method-generate-quantities, model-method-laplace, model-method-model-info, model-method-pathfinder, model-method-sample, model-method-variables, model-method-variational


Run Pathfinder

Description

The ⁠$pathfinder()⁠ method of a StanModel object runs Stan's "pathfinder" method, which uses a parallel iterative optimization approach to approximate the posterior distribution. Returns a StanPathfinder object.

Arguments

data

(named list) Values for all or part of the data block in the Stan program. Each element is named after the corresponding Stan variable and shaped as follows:

Stan type R shape
complex complex scalar (e.g. 1+2i)
complex_vector[n], complex_row_vector[n], ⁠array[n] complex⁠ complex vector of length n
complex_matrix[r, c] complex matrix, r x c
tuple(T1, ..., Tk) unnamed list of length k, element j shaped as Tj
⁠array[n] tuple(...)⁠ list of n tuple-shaped lists
⁠array[n, m] tuple(...)⁠ list (over the first index) of lists (over the second index) of tuples

A length-1 R vector is read as a scalar, so a vector[1], ⁠array[1] ...⁠, or length-1 tuple-slot container value must be given an explicit shape (as.array(x) or dim(x) <- 1L) to match its declared dimension.

Real-valued input is accepted wherever a complex type is declared – it is coerced automatically, including inside tuple slots. All other Stan types use their ordinary R representation (numeric/integer scalars, vectors, matrices, arrays).

As a power-user escape hatch, tuple variables can instead be supplied pre-flattened using dotted names (e.g. list(t.1 = ..., t.2 = ...) for a tuple t), bypassing the list-shape conversion above; this is not the primary documented path. One caveat applies: a dotted entry for a complex tuple slot is assumed to hold exactly one complex value per enclosing array element, which is only correct when that slot is itself a plain (non-container) complex – for anything else (e.g. a complex_vector tuple slot), use the list shapes above instead.

seed

(integer) The random seed for reproducibility.

init

Initial values for parameters. Either NULL (equivalent to the default radius of 2), a non-negative number, used as the range of CmdStan-style random initialization (Uniform(-init, init) on the unconstrained scale; the default is 2), or a named list / named numeric vector of constrained parameter values. Supplied values are shared by all chains; parameters not covered by the supplied values are randomly initialized with the default range. A named list may include tuple-shaped list entries and R complex values for tuple(...)/complex parameters, using the same canonical shapes (and the same dotted-name escape hatch) documented for data.

num_paths

(integer) The number of paths to use.

single_path_draws

(integer) Number of draws per path.

draws

(integer) Total number of draws from the approximation.

max_lbfgs_iters

(integer) Maximum LBFGS iterations per path.

num_elbo_draws

(integer) Number of draws for ELBO estimation.

save_single_paths

(logical) Should single path results be saved?

psis_resample

(logical) Should Pareto smoothed importance sampling resampling be used?

calculate_lp

(logical) Should the log density be calculated?

num_threads

(integer) The total number of threads to use. Defaults to all available threads.

show_messages

(logical) When TRUE (the default), print progress and informational output (e.g. iteration and timing messages) to the console. Set to FALSE to silence it. Suppressed output is still recorded and available via the fit's ⁠$output()⁠ method.

show_exceptions

(logical) When TRUE (the default), print informational messages about numerical exceptions – e.g. Metropolis proposal rejections and rejected initial values. Set to FALSE to silence them. Suppressed messages are still recorded and available via the fit's ⁠$output()⁠ method.

opencl_ids

(integer vector) c(platform_id, device_id) identifying the OpenCL platform/device to run on. Only meaningful for a model compiled with use_opencl = TRUE (see stan_model()); errors if the model was not compiled with OpenCL support. Defaults to NULL, meaning select_opencl_device() is never called and the platform/device baked in at compile time (0/0) is used.

Value

A StanPathfinder object containing approximate posterior draws.

See Also

$sample(), $variational()

Other StanModel methods: model-method-check-syntax, model-method-compile, model-method-diagnose, model-method-expose-stan-functions, model-method-format, model-method-generate-quantities, model-method-laplace, model-method-model-info, model-method-optimize, model-method-sample, model-method-variables, model-method-variational


Run MCMC sampling

Description

The ⁠$sample()⁠ method of a StanModel object runs Stan's "sample" method, which uses Hamiltonian Monte Carlo (HMC) with the No-U-Turn Sampler (NUTS) to draw from the posterior distribution. Returns a StanMCMC object.

Arguments

data

(named list) Values for all or part of the data block in the Stan program. Each element is named after the corresponding Stan variable and shaped as follows:

Stan type R shape
complex complex scalar (e.g. 1+2i)
complex_vector[n], complex_row_vector[n], ⁠array[n] complex⁠ complex vector of length n
complex_matrix[r, c] complex matrix, r x c
tuple(T1, ..., Tk) unnamed list of length k, element j shaped as Tj
⁠array[n] tuple(...)⁠ list of n tuple-shaped lists
⁠array[n, m] tuple(...)⁠ list (over the first index) of lists (over the second index) of tuples

A length-1 R vector is read as a scalar, so a vector[1], ⁠array[1] ...⁠, or length-1 tuple-slot container value must be given an explicit shape (as.array(x) or dim(x) <- 1L) to match its declared dimension.

Real-valued input is accepted wherever a complex type is declared – it is coerced automatically, including inside tuple slots. All other Stan types use their ordinary R representation (numeric/integer scalars, vectors, matrices, arrays).

As a power-user escape hatch, tuple variables can instead be supplied pre-flattened using dotted names (e.g. list(t.1 = ..., t.2 = ...) for a tuple t), bypassing the list-shape conversion above; this is not the primary documented path. One caveat applies: a dotted entry for a complex tuple slot is assumed to hold exactly one complex value per enclosing array element, which is only correct when that slot is itself a plain (non-container) complex – for anything else (e.g. a complex_vector tuple slot), use the list shapes above instead.

seed

(integer) The random seed for reproducibility.

refresh

(integer) How often (in iterations) to print progress.

init

Initial values for parameters. Either NULL (equivalent to the default radius of 2), a non-negative number, used as the range of CmdStan-style random initialization (Uniform(-init, init) on the unconstrained scale; the default is 2), or a named list / named numeric vector of constrained parameter values. Supplied values are shared by all chains; parameters not covered by the supplied values are randomly initialized with the default range. A named list may include tuple-shaped list entries and R complex values for tuple(...)/complex parameters, using the same canonical shapes (and the same dotted-name escape hatch) documented for data.

chains

(integer) The number of MCMC chains.

chain_ids

(integer vector) The IDs for each chain.

num_threads

(integer) The total number of threads to use. Defaults to all available threads.

iter_warmup

(integer) The number of warmup iterations.

iter_sampling

(integer) The number of sampling iterations.

save_warmup

(logical) Should warmup samples be saved? Ignored when fixed_param = TRUE, since that mode runs no warmup and so has nothing to save.

thin

(integer) Thin interval.

max_treedepth

(integer) Maximum tree depth for NUTS.

adapt_engaged

(logical) Should step size adaptation be used?

adapt_delta

(number) Target acceptance statistic for HMC.

step_size

(number) Step size for HMC.

metric

Character string indicating the metric to use: "diag_e", "dense_e", or "unit_e".

inv_metric

(numeric) Initial inverse mass matrix values.

init_buffer

(integer) Adaptation phase: initial buffer length.

term_buffer

(integer) Adaptation phase: terminal buffer length.

window

(integer) Adaptation phase: window length.

fixed_param

(logical) Treat all parameters as fixed (no adaptation).

show_messages

(logical) When TRUE (the default), print progress and informational output (e.g. iteration and timing messages) to the console. Set to FALSE to silence it. Suppressed output is still recorded and available via the fit's ⁠$output()⁠ method.

show_exceptions

(logical) When TRUE (the default), print informational messages about numerical exceptions – e.g. Metropolis proposal rejections and rejected initial values. Set to FALSE to silence them. Suppressed messages are still recorded and available via the fit's ⁠$output()⁠ method.

diagnostics

(character vector) Which sampler diagnostics to check immediately after sampling, printing a warning message for any problems found – see $diagnostic_summary(). One or more of "divergences", "treedepth", and "ebfmi". The default checks all three; NULL or "" skips the check entirely. Ignored when fixed_param = TRUE.

engine

(string) The sampling engine: "nuts", "static", or "walnuts" (see walnutpie). walnuts only supports metric = "diag_e" and adapt_engaged = TRUE. It reuses max_treedepth as the maximum trajectory doublings, adapt_delta as the step size acceptance target, and step_size as the initial step size; refresh, step_size_jitter, init_buffer, term_buffer, window, and adapt_gamma/adapt_kappa/adapt_t0 are ignored, and no sampler diagnostics or progress output are produced.

int_time

(number) Integration time for static HMC.

step_size_jitter

(number) Jitter for step size after adaptation.

adapt_gamma

(number) Adaptation hyperparameter for dual averaging.

adapt_kappa

(number) Adaptation hyperparameter for dual averaging.

adapt_t0

(number) Adaptation hyperparameter for dual averaging.

max_step_halvings

(integer) walnuts only: maximum number of step size halvings per macro step.

min_micro_steps

(integer) walnuts only: minimum number of micro steps per macro step.

max_hamiltonian_error

(number) walnuts only: maximum allowed error in the Hamiltonian at a macro step.

mass_init_count

(number) walnuts only: initial count for the mass matrix estimator.

mass_additive_smoothing

(number) walnuts only: additive smoothing for the mass matrix estimator.

max_macro_steps_target

(number) walnuts only: target number of macro steps per iteration.

step_learning_rate

(number) walnuts only: learning rate for the Adam step size adaptation.

step_gradient_decay

(number) walnuts only: gradient decay rate for the Adam step size adaptation.

step_sq_gradient_decay

(number) walnuts only: squared gradient decay rate for the Adam step size adaptation.

step_stabilization

(number) walnuts only: stabilization term for the Adam step size adaptation.

step_learn_rate_decay

(number) walnuts only: learning rate decay exponent for the Adam step size adaptation.

opencl_ids

(integer vector) c(platform_id, device_id) identifying the OpenCL platform/device to run on. Only meaningful for a model compiled with use_opencl = TRUE (see stan_model()); errors if the model was not compiled with OpenCL support. Defaults to NULL, meaning select_opencl_device() is never called and the platform/device baked in at compile time (0/0) is used.

Value

A StanMCMC object containing posterior draws and diagnostics.

See Also

$optimize(), $variational()

Other StanModel methods: model-method-check-syntax, model-method-compile, model-method-diagnose, model-method-expose-stan-functions, model-method-format, model-method-generate-quantities, model-method-laplace, model-method-model-info, model-method-optimize, model-method-pathfinder, model-method-variables, model-method-variational


Input and output variables of a Stan program

Description

The ⁠$variables()⁠ method of a StanModel object returns a list, each element representing a Stan model block: data, parameters, transformed_parameters and generated_quantities.

Each element contains a list of variables, with each variable represented as a list with information on its scalar type (real or int) and number of dimensions.

The number of dimensions reported is the number of indexing dimensions in the declared Stan variable, equivalently the number of indices needed to access one scalar element. This means a scalar has 0 dimensions, a vector or one-dimensional array has 1, and a matrix or two-dimensional array has 2. Array dimensions are added to any vector or matrix dimensions, so ⁠array[J] matrix[N, K]⁠ has 3 dimensions.

⁠transformed data⁠ is not included, as variables in that block are not part of the model's input or output.

Value

A list with information on input and output variables for each of the Stan model blocks.

See Also

Other StanModel methods: model-method-check-syntax, model-method-compile, model-method-diagnose, model-method-expose-stan-functions, model-method-format, model-method-generate-quantities, model-method-laplace, model-method-model-info, model-method-optimize, model-method-pathfinder, model-method-sample, model-method-variational

Examples

## Not run: 
mod <- stan_model(
  code = "
  data {
    int N;
    array[2, 3] int y;
  }
  parameters {
    real alpha;
    vector[N] beta;
    array[2] matrix[3, 4] theta;
  }
  ",
  compile = FALSE
)

vars <- mod$variables()
str(vars)

## End(Not run)

Run variational inference (ADVI)

Description

The ⁠$variational()⁠ method of a StanModel object runs Stan's "variational" method, which uses Automatic Differentiation Variational Inference (ADVI) to approximate the posterior distribution. Returns a StanVB object.

Arguments

data

(named list) Values for all or part of the data block in the Stan program. Each element is named after the corresponding Stan variable and shaped as follows:

Stan type R shape
complex complex scalar (e.g. 1+2i)
complex_vector[n], complex_row_vector[n], ⁠array[n] complex⁠ complex vector of length n
complex_matrix[r, c] complex matrix, r x c
tuple(T1, ..., Tk) unnamed list of length k, element j shaped as Tj
⁠array[n] tuple(...)⁠ list of n tuple-shaped lists
⁠array[n, m] tuple(...)⁠ list (over the first index) of lists (over the second index) of tuples

A length-1 R vector is read as a scalar, so a vector[1], ⁠array[1] ...⁠, or length-1 tuple-slot container value must be given an explicit shape (as.array(x) or dim(x) <- 1L) to match its declared dimension.

Real-valued input is accepted wherever a complex type is declared – it is coerced automatically, including inside tuple slots. All other Stan types use their ordinary R representation (numeric/integer scalars, vectors, matrices, arrays).

As a power-user escape hatch, tuple variables can instead be supplied pre-flattened using dotted names (e.g. list(t.1 = ..., t.2 = ...) for a tuple t), bypassing the list-shape conversion above; this is not the primary documented path. One caveat applies: a dotted entry for a complex tuple slot is assumed to hold exactly one complex value per enclosing array element, which is only correct when that slot is itself a plain (non-container) complex – for anything else (e.g. a complex_vector tuple slot), use the list shapes above instead.

seed

(integer) The random seed for reproducibility.

init

Initial values for parameters. Either NULL (equivalent to the default radius of 2), a non-negative number, used as the range of CmdStan-style random initialization (Uniform(-init, init) on the unconstrained scale; the default is 2), or a named list / named numeric vector of constrained parameter values. Supplied values are shared by all chains; parameters not covered by the supplied values are randomly initialized with the default range. A named list may include tuple-shaped list entries and R complex values for tuple(...)/complex parameters, using the same canonical shapes (and the same dotted-name escape hatch) documented for data.

algorithm

(string) The variational inference algorithm: "meanfield" or "fullrank".

iter

(integer) The number of ADVI iterations.

grad_samples

(integer) Number of samples to use for gradient estimation.

elbo_samples

(integer) Number of samples for ELBO evaluation.

eta

(number) Learning rate for ADVI.

adapt_engaged

(logical) Should the learning rate be adapted?

adapt_iter

(integer) Number of iterations for learning rate adaptation.

tol_rel_obj

(number) Relative tolerance for ELBO convergence.

eval_elbo

(integer) How often to evaluate the ELBO.

draws

(integer) The number of draws from the variational approximation.

num_threads

(integer) The total number of threads to use. Defaults to all available threads.

show_messages

(logical) When TRUE (the default), print progress and informational output (e.g. iteration and timing messages) to the console. Set to FALSE to silence it. Suppressed output is still recorded and available via the fit's ⁠$output()⁠ method.

show_exceptions

(logical) When TRUE (the default), print informational messages about numerical exceptions – e.g. Metropolis proposal rejections and rejected initial values. Set to FALSE to silence them. Suppressed messages are still recorded and available via the fit's ⁠$output()⁠ method.

opencl_ids

(integer vector) c(platform_id, device_id) identifying the OpenCL platform/device to run on. Only meaningful for a model compiled with use_opencl = TRUE (see stan_model()); errors if the model was not compiled with OpenCL support. Defaults to NULL, meaning select_opencl_device() is never called and the platform/device baked in at compile time (0/0) is used.

Value

A StanVB object containing approximate posterior draws.

See Also

$sample(), $pathfinder()

Other StanModel methods: model-method-check-syntax, model-method-compile, model-method-diagnose, model-method-expose-stan-functions, model-method-format, model-method-generate-quantities, model-method-laplace, model-method-model-info, model-method-optimize, model-method-pathfinder, model-method-sample, model-method-variables


Create a Stan model object

Description

Create a new StanModel object from a Stan program file or from Stan code as a string. The StanModel object stores the Stan program source and compiled model, and provides methods for fitting the model using Stan's inference algorithms.

See the compile argument for control over whether and how compilation happens.

Usage

stan_model(
  stan_file = NULL,
  code = NULL,
  compile = TRUE,
  model_name = NULL,
  include_paths = NULL,
  user_header = NULL,
  cpp_options = list(),
  stanc_options = list(),
  force_recompile = getOption("stanr_force_recompile", FALSE),
  precompiled_headers = TRUE,
  quiet = TRUE,
  external_cpp = NULL,
  use_opencl = FALSE,
  compile_standalone = FALSE,
  backend = "compiled"
)

Arguments

stan_file

(string) The path to a .stan file containing a Stan program. If stan_file is not specified then code must be specified.

code

(string) A Stan program as a single string. If code is not specified then stan_file must be specified.

compile

(logical) Should the model be compiled? The default is TRUE. If FALSE compilation can be done later via the $compile() method.

model_name

(string) The name to use for the model. If NULL (the default), the model name is derived from the Stan file name (if provided) or set to "model".

include_paths

(character vector) Paths to directories where Stan should look for files specified in ⁠#include⁠ directives.

user_header

(string) A path to a single C++ header file to prepend to the generated model code. A legacy alias for external_cpp; supplied headers are appended to external_cpp and treated identically.

cpp_options

(list) C++ compilation options, merged into the Makevars flags used to compile the model. Each element is either:

  • A named element, e.g. list(CXX = "g++"). This overrides any value computed internally for that name (e.g. CXXFLAGS), replacing it rather than adding to it.

  • An unnamed string of the form "<NAME> = <value>", e.g. "CXX = g++". Equivalent to the named form above – also overrides.

  • An unnamed string of the form "<NAME> += <value>", e.g. "CXXFLAGS += -Wno-psabi". Appends ⁠<value>⁠ to any existing value for ⁠<NAME>⁠ instead of replacing it (space-separated), matching how ⁠+=⁠ behaves in a Makevars file.

Entries are applied in list order, so the same name may appear more than once, e.g. list(CXXFLAGS = "-O3", "CXXFLAGS += -Wall") first overrides CXXFLAGS, then appends to it.

stanc_options

(list) Stan-to-C++ transpiler options. Not yet supported.

force_recompile

(logical) Should the model be recompiled even if it has not been modified? The default is FALSE, but can be set via the stanr_force_recompile option.

precompiled_headers

(logical) Should precompiled headers be used to speed up compilation? The default is TRUE. Automatically disabled when cpp_options overrides compiler flags (e.g. CXXFLAGS), since the precompiled header is not built with those flags.

quiet

(logical) Should verbose output from compilation be suppressed? The default is TRUE.

external_cpp

(character vector) Paths to C++ files to prepend to the generated model code. Useful for defining custom functions.

use_opencl

(logical) Should the model be compiled with OpenCL support? The default is FALSE. When TRUE, stanc generates OpenCL-accelerated code for the functions that support it (most notably bernoulli_logit_glm and other GLM likelihoods), and the compiled model can run its computation on an OpenCL device. Which platform/device is used at runtime is controlled by the opencl_ids argument of the fit methods (e.g. $sample()), not by this argument; opencl_ids = NULL (the default there) means select_opencl_device() is simply never called, so the platform/device baked in at compile time (0/0) is used. The default OpenCL link flags are "-framework OpenCL" on macOS and "-lOpenCL" elsewhere.

compile_standalone

(logical) Should the Stan program's functions block be exposed as part of this compilation? The default is FALSE. When TRUE, ⁠$functions⁠ is already populated when stan_model() returns – equivalent to FALSE here plus calling $expose_stan_functions() immediately after, but without a second compile. See $expose_stan_functions() for what gets exposed and how.

backend

(string) Either "compiled" (the default), which compiles the model to a native shared library, or "stanli", which interprets the model instead of compiling it. The "stanli" backend supports constrained-scale initialization, but not use_opencl, external_cpp, or non-empty cpp_options. Its exposed-function backend supports deterministic integer/real scalar and container functions, but not RNG, ⁠_lp⁠, void, complex, or tuple functions.

Value

A StanModel object.

The compiled model is cached persistently on disk as the compiled shared library itself, next to stan_file (named after it, e.g. mymodel.stan gets a sibling .mymodel.so/.mymodel.dll), or under tempdir() when the model was created from a code string, or when stan_file's directory isn't writable. The library embeds a hash of the generated C++, so it's reused across R sessions as long as the Stan program, include_paths, external_cpp, and installed stanr/Stan versions are unchanged, and is silently recompiled and overwritten otherwise – there is no separate cache-clearing step. On a cache hit, the Stan-to-C++ transpiler is skipped entirely, so any transpiler warnings (e.g. from pedantic mode or deprecated syntax) are only surfaced the first time a given model is compiled, not on subsequent cache hits.

See Also

StanModel, $compile(), $sample()

Examples

## Not run: 
# Create a StanModel from Stan code
mod <- stan_model(
  code = "
    parameters {
      real theta;
    }
    model {
      theta ~ normal(0, 1);
    }
  "
)
mod$model_name()
mod$variables()

# Run MCMC sampling
fit <- mod$sample(data = list(), chains = 2)
fit$summary()

## End(Not run)

Compile Stan code to C++

Description

Compiles a Stan program with the bundled stanc3 compiler. Before compilation, ⁠#include⁠ directives are replaced with the contents of the matching file from include_directories. Includes may be nested; directories are searched in the supplied order.

Usage

stanc(
  model_code,
  include_directories = character(),
  standalone_functions = FALSE,
  use_opencl = FALSE,
  optim_level = 0,
  allow_undefined = FALSE,
  warn_pedantic = FALSE,
  warn_uninitialized = FALSE,
  external_cpp = NULL
)

Arguments

model_code

Stan model code as a single string.

include_directories

Character vector of directories to search for Stan include files. Defaults to no include directories.

standalone_functions

Generate standalone function definitions.

use_opencl

Enable OpenCL code generation.

optim_level

stanc optimization level.

allow_undefined

Allow undefined functions.

warn_pedantic

Request pedantic compiler warnings.

warn_uninitialized

Request uninitialized-variable warnings.

external_cpp

NULL (the default), or a character vector of paths to C++ source or header files. Their contents are prepended to the generated C++, in order. Supplying this argument enables allow_undefined so Stan functions implemented by the supplied C++ can be declared in the model.

Value

A string containing the generated C++ model implementation.


StanDiagnose objects

Description

A StanDiagnose object is returned by $diagnose() and contains the results of Stan's gradient checking diagnostics.

Methods

In addition to the methods inherited from StanFit, StanDiagnose objects have:

Method Description
$gradients() Return the gradient check results.
$lp() Return the log probability evaluated at the
initial parameter values.
$num_failed() Return the number of failed gradient checks.

StanFit objects

Description

StanFit is the base class for fitted model objects returned by the inference methods of StanModel. Subclasses include StanMCMC (MCMC sampling), StanMLE (optimization), StanLaplace (Laplace approximation), StanVB (variational inference), StanPathfinder (Pathfinder), StanGQ (generated quantities), and StanDiagnose (gradient diagnostics).

Methods

All StanFit objects share the following methods:

Draws and summaries

Method Description
$draws() Extract posterior draws or point estimates.
$summary() Summarize posterior draws or point estimates.
$print() Print a summary of the fit.

Fit information

Method Description
$return_codes() Return the Stan return codes.
$metadata() Return fit metadata.
$output() Return Stan output messages.
$time() Return timing information.
$init() Return user-specified initial values.
$code() Return the Stan program code.

Log density

Method Description
$lp() Extract the log density (lp__) draws.

Model methods

Method Description
$log_prob() Compute the log probability.
$grad_log_prob() Compute the gradient of the log probability.
$hessian() Compute the Hessian of the log probability.
$constrain_variables() Constrain unconstrained parameters.
$unconstrain_variables() Unconstrain parameters.
$unconstrain_draws() Unconstrain posterior draws.
$variable_skeleton() Return a skeleton of the variable structure.

Function exposure

Method Description
$expose_stan_functions() Expose the model's functions block as R functions.
$functions Environment holding the exposed functions (shared with the model).

Saving

Method Description
$save_object() Save the fitted model object to a file.

StanGQ objects

Description

A StanGQ object is returned by $generate_quantities() and contains the generated quantities computed from posterior draws.

Methods

In addition to the methods inherited from StanFit, StanGQ objects have:

Method Description
$num_chains() Return the number of chains in the draws.

StanLaplace objects

Description

A StanLaplace object is returned by $laplace() and contains draws from a Gaussian approximation to the posterior centered at the mode.

Methods

In addition to the methods inherited from StanFit, StanLaplace objects have:

Method Description
$mode() Return the mode used for the approximation.
$lp_approx() Extract the log density approximation draws.

StanMCMC objects

Description

A StanMCMC object is returned by $sample() and contains MCMC posterior draws, sampler diagnostics, and fit metadata.

Methods

In addition to the methods inherited from StanFit, StanMCMC objects have:

Method Description
$sampler_diagnostics() Extract sampler diagnostics.
$num_chains() Return the number of chains.
$diagnostic_summary() Summarize sampler diagnostics.
$inv_metric() Return the inverse mass matrix.

StanMLE objects

Description

A StanMLE object is returned by $optimize() and contains a point estimate (MAP or MLE) and optimization metadata.

Methods

In addition to the methods inherited from StanFit, StanMLE objects have:

Method Description
$mle() Extract the point estimate as a numeric vector.

StanModel objects

Description

A StanModel object is an R6 object created by stan_model(). The object stores the Stan program source code and compiled model environment, and provides methods for fitting the model using Stan's inference algorithms.

Methods

StanModel objects have the following associated methods, many of which have their own (linked) documentation pages:

Stan code

Method Description
$code() Return Stan program as a string.
$print() Print the Stan program.

Model information

Method Description
$model_name() Return the model name.
$stan_file() Return the path to the Stan file.
$has_stan_file() Check whether the model was created with a Stan file.
$include_paths() Return the Stan include paths.
$stan_version() Return the Stan version used by the package.
$variables() Return input and output variable information.
$cpp_options() Return the C++ options associated with the model.
$stanc_options() Return the stanc options associated with the model.

Compilation

Method Description
$check_syntax() Check the Stan program's syntax without compiling.
$format() Reformat the Stan program using stanc's auto-formatter.
$compile() Compile the Stan program.
$is_compiled() Check whether the model has been compiled.

Diagnostics

Method Description
$diagnose() Run Stan's "diagnose" method to test gradients, return StanDiagnose object.

Function exposure

Method Description
$expose_stan_functions() Expose the program's functions block as R functions.
$functions Environment holding the exposed functions.

Model fitting

Method Description
$sample() Run Stan's "sample" method (HMC/NUTS MCMC), return StanMCMC object.
$optimize() Run Stan's "optimize" method, return StanMLE object.
$laplace() Run Stan's "laplace" method, return StanLaplace object.
$variational() Run Stan's "variational" method (ADVI), return StanVB object.
$pathfinder() Run Stan's "pathfinder" method, return StanPathfinder object.
$generate_quantities() Run Stan's "generate quantities" method, return StanGQ object.

StanPathfinder objects

Description

A StanPathfinder object is returned by $pathfinder() and contains approximate posterior draws from the Pathfinder algorithm.

Methods

In addition to the methods inherited from StanFit, StanPathfinder objects have:

Method Description
$lp_approx() Extract the log density approximation draws.

StanVB objects

Description

A StanVB object is returned by $variational() and contains approximate posterior draws from Automatic Differentiation Variational Inference (ADVI).

Methods

In addition to the methods inherited from StanFit, StanVB objects have:

Method Description
$lp_approx() Extract the log density approximation draws.