Exposing built-in functions?

The expose_stan_functions function is a great way to use your custom user-defined functions within R. Is there also a way to expose the built-in functions?

I ask because I’m looking to generate random samples from an LKJ correlation distribution, but there aren’t a lot of options in terms of R packages. My workaround is to write a simple wrapper around the function I want in stan and then to expose that:

functions{
    matrix lkj_corr2_rng(int K, real eta) {
    return lkj_corr_rng(K, eta);
  }
}

But if there were a way to just get the original built-in functions with something like expose_builtin_stan_functions('lkj_corr_rng'), that would be super helpful.

I can’t answer the query about exposing built in functions, but for random LKJ samples there is always https://github.com/rmcelreath/rethinking/blob/master/R/distributions.r#L214 (I think the ‘Ben’ mentioned in the comment there is @bgoodri, so I would be surprised if this wasn’t the same way samples were generated in Stan/Math, though it might be a little slower for being done in R).

1 Like

I’ve had some issues downloading the rethinking package in the past so I was hoping to avoid that option…but I should probably just give it another shot

I think the only other way is directly via Stan Headers and Rcpp: https://cran.r-project.org/web/packages/StanHeaders/vignettes/stanmath.html

1 Like

With the most recent StanHeaders on CRAN, you could do

library(StanHeaders)
stanFunction("lkj_corr_rng", K = 3L, eta = 1)

except that does not actually work with _rng functions, so you first need to do

source("https://raw.githubusercontent.com/stan-dev/rstan/develop/StanHeaders/R/stanFunction.R")

to get the fixed version of the stanFunction function.

5 Likes