Learn R Programming

rstan (version 2.17.3)

expose_stan_functions: Expose user-defined Stan functions to R for testing and simulation

Description

The Stan modeling language allows users to define their own functions in a functions block at the top of a Stan program. The expose_stan_functions utility function uses sourceCpp to export those user-defined functions to the specified environment for testing inside R or for doing posterior predictive simulations in R rather than in the generated quantities block of a Stan program.

Usage

expose_stan_functions(stanmodel, ...)

Arguments

stanmodel

A '>stanmodel object, a '>stanfit object, a list produced by stanc or the path to a Stan program (.stan file). In any of these cases, the underlying Stan program should contain a non-empty functions block.

Further arguments passed to sourceCpp.

Value

The names of the new functions in env are returned invisibly.

Details

There are a few special types of user-defined Stan functions for which some additional details are relevant:

(P)RNG functions

If a user-defined Stan function ends in _rng, then it can use the Boost pseudo-random number generator used by Stan. When exposing such functions to R, a seed argument will be added to the formals. This seed argument defaults to 0L, but any non-negative integer can be passed as the seed the first time any user-defined function ending in _rng is called. In other words, the Boost pseudo-random number generator is initialized with the given seed but is declared with the static C++ keyword, meaning that it will not be reinitialized by subsequent calls to user-defined functions ending in _rng.

LP functions

If a user-defined Stan function ends in _lp, then it can modify the log-probability used by Stan to evaluate Metropolis proposals or as an objective function for optimization. When exposing such functions to R, a lp__ argument will be added to the formals. This lp__ argument defaults to zero, but a double precision scalar may be passed to this argument when the function is called from R. Such a user-defined Stan function can terminate with return target(); or can execute print(target()); to verify that the calculation is correct.

See Also

sourceCpp

Examples

Run this code
# NOT RUN {
  mc <- 
  '
  functions {
    int fibonacci(int x);
    int fibonacci(int x) {
      if (x <= 0) reject("x must be positive");
      return x <= 2 ? 1 : fibonacci(x - 1) + fibonacci(x - 2);
    }
  }
  '
  cppcode <- stanc(model_code = mc, model_name = "Fibonacci")
  
# }
# NOT RUN {
  expose_stan_functions(cppcode)
  
# }

Run the code above in your browser using DataLab