Testing user-defined functions with newer Stan functions

How would one go about testing a user defined function in R that relies on Stan functions that aren’t available for the current rstan Stan version?

I’m using cmdstanr, which does not expose user-defined functions (relevant thread here: Cmdstanr & sourceCpp / cppfunction for exposing functions). Exposing the function does not work with rstan which uses Stan (v.2.21) that does not include the newer function.

e.g., I’d like to test a user defined function that calls neg_binomial_2_lupmf (available since v2.25). But, rstan::expose_stan_functions() raises a syntax error:


model_code <-
  functions {
    real my_lpmf(int y) {
      return neg_binomial_2_lupmf(y | 0, 1);
expose_stan_functions(stanc(model_code = model_code))
#  error in 'model303634c7170e_model_code' at line 5, column 33
#   -------------------------------------------------
#      3:     real my_fn() {
#      4:       int y = 0;
#      5:       return neg_binomial_2_lupmf(y | 0, 1);
#                                         ^
#      6:    }
#   -------------------------------------------------

# Error in stanc(model_code = model_code) : 
#   failed to parse Stan model 'model_code' due to the above error.

As a workaround, I suppose I could pass test data to the model, and call the function in the generated quantities block, then check that the values are correct in an R session. But this is not very satisfying or general.

Any other ideas for testing user defined functions that rstan::expose_stan_functions() cannot expose in R?

1 Like

Is there a reason you can’t work with rstan 2.26?

# Uncomment the next line if you have previously installed rstan
# remove.packages(c("StanHeaders", "rstan"))
install.packages("StanHeaders", repos = c("https://mc-stan.org/r-packages/", getOption("repos")))
install.packages("rstan", repos = c("https://mc-stan.org/r-packages/", getOption("repos")))

Makes sense! Thanks @jsocolar - I updated rstan to use Stan v2.26.1 which should solve the problem.

I’m running into some possibly unrelated issues that I’ll need to dig into.


expose_stan_functions(stanc(model_code = model_code))
# ...
# make: *** [file5154dc358ac.o] Error 1
# WARNING: The tools required to build C++ code for R were not found.
# Please install GNU development tools including a C++ compiler.
# Error: $ operator is invalid for atomic vectors
1 Like

I’ve heard of similar issues to this on systems that lack an install of v8. Not sure if that’s what’s happening for you, but it might be worth digging into. See also