The $expose_functions() method of a CmdStanModel object will compile the functions in the Stan program's functions block and expose them for use in R. This can also be specified via the compile_standalone argument to the $compile() method.

This method is also available for fitted model objects (CmdStanMCMC, CmdStanVB, etc.). See Examples.

Note: there may be many compiler warnings emitted during compilation but these can be ignored so long as they are warnings and not errors.

expose_functions(global = FALSE, verbose = FALSE)

Arguments

global

(logical) Should the functions be added to the Global Environment? The default is FALSE, in which case the functions are available via the functions field of the R6 object.

verbose

(logical) Should detailed information about generated code be printed to the console? Defaults to FALSE.

Examples

# \dontrun{
stan_file <- write_stan_file(
 "
 functions {
   real a_plus_b(real a, real b) {
     return a + b;
   }
 }
 parameters {
   real x;
 }
 model {
   x ~ std_normal();
 }
 "
)
mod <- cmdstan_model(stan_file)
mod$expose_functions()
#> Compiling standalone functions...
mod$functions$a_plus_b(1, 2)
#> [1] 3

fit <- mod$sample(refresh = 0)
#> Running MCMC with 4 sequential chains...
#> 
#> Chain 1 finished in 0.0 seconds.
#> Chain 2 finished in 0.0 seconds.
#> Chain 3 finished in 0.0 seconds.
#> Chain 4 finished in 0.0 seconds.
#> 
#> All 4 chains finished successfully.
#> Mean chain execution time: 0.0 seconds.
#> Total execution time: 0.6 seconds.
#> 
fit$expose_functions() # already compiled because of above but this would compile them otherwise
#> Functions already compiled, nothing to do!
fit$functions$a_plus_b(1, 2)
#> [1] 3
# }