| 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 |
A modern, simpler R interface for Stan. Bundles all required Stan, Eigen, and TBB headers internally.
Maintainer: Andrew R. Johnson [email protected] (ORCID)
Authors:
Andrew R. Johnson [email protected] (ORCID)
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]
Useful links:
Access gradient checking results from a StanDiagnose object.
gradients() lp() num_failed()
$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.
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 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.
variables |
(character vector) Which variables to extract. If |
inc_warmup |
(logical) Should warmup draws be included? Defaults to
|
format |
(string) The format of the returned draws. Must be a valid
format from the posterior package. Defaults depend on the fitting
method: |
An object from the posterior package in the requested format.
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
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)
global |
(logical) Should the exposed functions also be assigned into the global environment? |
verbose |
(logical) Should compiler progress messages be printed? |
$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).
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
These methods access information stored in a StanFit object.
return_codes() metadata() output() time() init() code()
$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.
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
Return the number of chains in a StanGQ object's draws.
An integer giving the number of chains, or 0 if no draws are
available.
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
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.
The mode object or numeric vector.
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
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.
variables |
(string) The name of the variable in the Stan program
containing the pointwise log-likelihood. The default is to look for
|
r_eff |
(multiple options) How to handle the
|
moment_match |
(logical) Whether to use a
moment-matching correction for problematic
observations. The default is |
... |
Other arguments (e.g., |
The object returned by loo::loo.array() or
loo::loo_moment_match.default().
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).
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 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()
A numeric vector, with one element per (post-warmup) draw, or a single value for optimization.
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
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, ...)
matrix |
(logical) For |
diagnostics |
(character vector) For |
quiet |
(logical) For |
$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.
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 the maximum likelihood or maximum a posteriori estimate
from a StanMLE object as a named numeric vector.
variables |
(character vector) Which variables to extract. If |
A named numeric vector of parameter estimates. Always reflects the
final optimization iteration, regardless of whether
$optimize() was run with save_iterations = TRUE.
$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
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)
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 |
format |
(string) The format of the returned draws. Must be a valid
format from the posterior package. Defaults depend on the fitting
method: |
inc_warmup |
(logical) Should warmup draws be included? Defaults to
|
transformed_parameters |
(logical) Include transformed parameters? |
generated_quantities |
(logical) Include generated quantities? |
$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.
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 a summary table of posterior draws or point estimates.
digits |
(integer) Number of digits for numeric summary statistics. |
max_rows |
(integer) Maximum number of rows to print. |
The fitted model object, invisibly.
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
Methods for saving fitted model objects.
save_object(file, ...)
file |
(string) Path where the file should be saved. |
... |
Additional arguments passed to |
$save_object() returns the normalized file path, invisibly.
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
Compute summary statistics for posterior draws or point
estimates using posterior::summarise_draws().
... |
Additional arguments passed to |
A data frame of summary statistics.
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
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().
pedantic |
(logical) Should |
quiet |
(logical) Should the success message be suppressed? The
default is |
TRUE, invisibly. Errors if the program has a syntax error.
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
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.
force_recompile |
(logical) Should the model be recompiled even if it
has not been modified since it was last compiled? The default is |
quiet |
(logical) Should verbose output from compilation be suppressed?
The default is |
compile_standalone |
(logical) Should the Stan program's |
The StanModel object, invisibly.
$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
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.
data |
(named list) Values for all or part of the data
A length-1 R vector is read as a scalar, so a Real-valued input is accepted wherever a As a power-user escape hatch, tuple variables can instead be supplied
pre-flattened using dotted names (e.g. |
||||||||||||||
seed |
(integer) The random seed for reproducibility. |
||||||||||||||
init |
Initial values for parameters. Either |
||||||||||||||
epsilon |
(number) The finite difference step size. |
||||||||||||||
error |
(number) The maximum allowed relative error. |
||||||||||||||
show_messages |
(logical) When |
||||||||||||||
show_exceptions |
(logical) When |
A StanDiagnose object containing gradient check results.
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
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.
global |
(logical) Should the exposed functions also be assigned
into the global environment? The default, |
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 |
The StanModel object's $functions environment, invisibly.
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.
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.
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
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.
overwrite_file |
(logical) Should the formatted code be written back
to |
canonicalize |
(logical or character) |
backup |
(logical) When |
max_line_length |
(integer) Maximum output line width. The default,
|
quiet |
(logical) Should the backup message be suppressed? The
default is |
The formatted Stan code as a string.
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
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.
fitted_params |
A |
||||||||||||||
data |
(named list) Values for all or part of the data
A length-1 R vector is read as a scalar, so a Real-valued input is accepted wherever a As a power-user escape hatch, tuple variables can instead be supplied
pre-flattened using dotted names (e.g. |
||||||||||||||
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 |
||||||||||||||
show_exceptions |
(logical) When |
||||||||||||||
opencl_ids |
(integer vector) |
A StanGQ object containing the generated quantities.
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
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.
data |
(named list) Values for all or part of the data
A length-1 R vector is read as a scalar, so a Real-valued input is accepted wherever a As a power-user escape hatch, tuple variables can instead be supplied
pre-flattened using dotted names (e.g. |
||||||||||||||
seed |
(integer) The random seed for reproducibility. |
||||||||||||||
init |
Initial values for parameters. Either |
||||||||||||||
mode |
A numeric vector of parameter values at the mode, or a
|
||||||||||||||
opt_args |
(list) Additional arguments to pass to
|
||||||||||||||
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 |
||||||||||||||
show_exceptions |
(logical) When |
||||||||||||||
opencl_ids |
(integer vector) |
A StanLaplace object containing approximate posterior draws.
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
StanModel objectThese 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()
$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.
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
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.
data |
(named list) Values for all or part of the data
A length-1 R vector is read as a scalar, so a Real-valued input is accepted wherever a As a power-user escape hatch, tuple variables can instead be supplied
pre-flattened using dotted names (e.g. |
||||||||||||||
seed |
(integer) The random seed for reproducibility. |
||||||||||||||
init |
Initial values for parameters. Either |
||||||||||||||
algorithm |
(string) The optimization algorithm: |
||||||||||||||
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 |
||||||||||||||
num_threads |
(integer) The total number of threads to use. Defaults to all available threads. |
||||||||||||||
show_messages |
(logical) When |
||||||||||||||
show_exceptions |
(logical) When |
||||||||||||||
opencl_ids |
(integer vector) |
A StanMLE object containing the point estimate.
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
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.
data |
(named list) Values for all or part of the data
A length-1 R vector is read as a scalar, so a Real-valued input is accepted wherever a As a power-user escape hatch, tuple variables can instead be supplied
pre-flattened using dotted names (e.g. |
||||||||||||||
seed |
(integer) The random seed for reproducibility. |
||||||||||||||
init |
Initial values for parameters. Either |
||||||||||||||
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 |
||||||||||||||
show_exceptions |
(logical) When |
||||||||||||||
opencl_ids |
(integer vector) |
A StanPathfinder object containing approximate posterior draws.
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
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.
data |
(named list) Values for all or part of the data
A length-1 R vector is read as a scalar, so a Real-valued input is accepted wherever a As a power-user escape hatch, tuple variables can instead be supplied
pre-flattened using dotted names (e.g. |
||||||||||||||
seed |
(integer) The random seed for reproducibility. |
||||||||||||||
refresh |
(integer) How often (in iterations) to print progress. |
||||||||||||||
init |
Initial values for parameters. Either |
||||||||||||||
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
|
||||||||||||||
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: |
||||||||||||||
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 |
||||||||||||||
show_exceptions |
(logical) When |
||||||||||||||
diagnostics |
(character vector) Which sampler diagnostics to check
immediately after sampling, printing a warning message for any problems
found – see |
||||||||||||||
engine |
(string) The sampling engine: |
||||||||||||||
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) |
||||||||||||||
min_micro_steps |
(integer) |
||||||||||||||
max_hamiltonian_error |
(number) |
||||||||||||||
mass_init_count |
(number) |
||||||||||||||
mass_additive_smoothing |
(number) |
||||||||||||||
max_macro_steps_target |
(number) |
||||||||||||||
step_learning_rate |
(number) |
||||||||||||||
step_gradient_decay |
(number) |
||||||||||||||
step_sq_gradient_decay |
(number) |
||||||||||||||
step_stabilization |
(number) |
||||||||||||||
step_learn_rate_decay |
(number) |
||||||||||||||
opencl_ids |
(integer vector) |
A StanMCMC object containing posterior draws and diagnostics.
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
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.
A list with information on input and output variables for each of the Stan model blocks.
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
## 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)## 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)
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.
data |
(named list) Values for all or part of the data
A length-1 R vector is read as a scalar, so a Real-valued input is accepted wherever a As a power-user escape hatch, tuple variables can instead be supplied
pre-flattened using dotted names (e.g. |
||||||||||||||
seed |
(integer) The random seed for reproducibility. |
||||||||||||||
init |
Initial values for parameters. Either |
||||||||||||||
algorithm |
(string) The variational inference algorithm: |
||||||||||||||
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 |
||||||||||||||
show_exceptions |
(logical) When |
||||||||||||||
opencl_ids |
(integer vector) |
A StanVB object containing approximate posterior draws.
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 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.
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" )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" )
stan_file |
(string) The path to a |
code |
(string) A Stan program as a single string. If |
compile |
(logical) Should the model be compiled? The default is
|
model_name |
(string) The name to use for the model. If |
include_paths |
(character vector) Paths to directories where Stan
should look for files specified in |
user_header |
(string) A path to a single C++ header file to prepend to
the generated model code. A legacy alias for |
cpp_options |
(list) C++ compilation options, merged into the Makevars flags used to compile the model. Each element is either:
Entries are applied in list order, so the same name may appear more
than once, e.g. |
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 |
precompiled_headers |
(logical) Should precompiled headers be used to
speed up compilation? The default is |
quiet |
(logical) Should verbose output from compilation be suppressed?
The default is |
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 |
compile_standalone |
(logical) Should the Stan program's |
backend |
(string) Either |
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.
StanModel, $compile(),
$sample()
## 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)## 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)
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.
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 )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 )
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 |
|
A string containing the generated C++ model implementation.
A StanDiagnose object is returned by
$diagnose() and contains the results of Stan's
gradient checking diagnostics.
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 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).
All StanFit objects share the following methods:
| Method | Description |
$draws() |
Extract posterior draws or point estimates. |
$summary() |
Summarize posterior draws or point estimates. |
$print() |
Print a summary of the fit. |
| 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. |
| Method | Description |
$lp() |
Extract the log density (lp__) draws.
|
| 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. |
| Method | Description |
$expose_stan_functions() |
Expose the model's functions block as R functions. |
$functions |
Environment holding the exposed functions (shared with the model). |
| Method | Description |
$save_object() |
Save the fitted model object to a file. |
A StanGQ object is returned by
$generate_quantities() and contains
the generated quantities computed from posterior draws.
In addition to the methods inherited from StanFit,
StanGQ objects have:
| Method | Description |
$num_chains() |
Return the number of chains in the draws. |
A StanLaplace object is returned by
$laplace() and contains draws from a Gaussian
approximation to the posterior centered at the mode.
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. |
A StanMCMC object is returned by $sample()
and contains MCMC posterior draws, sampler diagnostics, and fit metadata.
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. |
A StanMLE object is returned by
$optimize() and contains a point estimate
(MAP or MLE) and optimization metadata.
In addition to the methods inherited from StanFit,
StanMLE objects have:
| Method | Description |
$mle() |
Extract the point estimate as a numeric vector. |
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.
StanModel objects have the following associated methods,
many of which have their own (linked) documentation pages:
| Method | Description |
$code() |
Return Stan program as a string. |
$print() |
Print the Stan program. |
| 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. |
| 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. |
| Method | Description |
$diagnose() |
Run Stan's "diagnose" method to test gradients, return StanDiagnose object.
|
| Method | Description |
$expose_stan_functions() |
Expose the program's functions block as R functions. |
$functions |
Environment holding the exposed functions. |
| 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.
|
A StanPathfinder object is returned by
$pathfinder() and contains approximate
posterior draws from the Pathfinder algorithm.
In addition to the methods inherited from StanFit,
StanPathfinder objects have:
| Method | Description |
$lp_approx() |
Extract the log density approximation draws. |
A StanVB object is returned by
$variational() and contains approximate
posterior draws from Automatic Differentiation Variational Inference (ADVI).
In addition to the methods inherited from StanFit,
StanVB objects have:
| Method | Description |
$lp_approx() |
Extract the log density approximation draws. |