Include function from Stan Math Library in Rstan

I’m trying to include log_modified_bessel_first_kind.hpp from the Stan Math Library in rstan as described in https://cran.r-project.org/web/packages/rstan/vignettes/external.html,
but I keep getting the following error:

Error in dyn.load(libLFile) : 
  unable to load shared object '/localscratch/susanne.pieschner/tmp/Rtmpub14ra/file13ad23d92f15c.so':
  /localscratch/susanne.pieschner/tmp/Rtmpub14ra/file13ad23d92f15c.so: undefined symbol: _ZN37model13ad2297ddae5_external_namespace30log_modified_bessel_first_kindIddEEN5boost4math5tools12promote_argsIT_T0_ffffE4typeERKS5_RKS6_PSo
Error in sink(type = "output") : invalid connection

Any ideas on how to resolve this?

Oh is the goal that you want to use log_modified_bessel_first_king in your Stan model and that function isn’t exposed?

Can you share the code? These C++ include things are pretty finicky.

Thank you for your reply!

Yes, I would like to use the function log_modified_bessel_first_kind in a Stan model. I haven’t build the actual model yet, but just tried whether I can manage to use the function at all, so I’ve tried the following in R:

mc <-
'
functions { real log_modified_bessel_first_kind(real y, real z); }
model {} // use the log_modified_bessel_first_kind() function somehow
generated quantities {
real bessel_value;
bessel_value = log_modified_bessel_first_kind(1.5, 3.5);
}
'

stan_model_object <- 
stan_model(model_code = mc, model_name = "external", allow_undefined = TRUE, 
includes = paste0('\n#include "',  file.path('/usr/local/lib/R/site-library/StanHeaders/include/stan/math/prim/scal/fun/log_modified_bessel_first_kind.hpp'), '"\n'))

which returns the error that I posted in my previous comment.

Alright I think the thing is you gotta write a little wrapper function. The signature generated by stanc3 includes a std::ostream* argument which the Math library function doesn’t have.

So drop this in a file called ‘interface.hpp’ in your working directory:

template <typename T0__, typename T1__>
  typename boost::math::tools::promote_args<T0__, T1__>::type
log_modified_bessel_first_kind(const T0__& y,
                               const T1__& z, std::ostream* pstream__) {
  return stan::math::log_modified_bessel_first_kind(y, z);
}

Then this compiles:

library(rstan)

mc <- 'functions { real log_modified_bessel_first_kind(real y, real z); }
model {} // use the log_modified_bessel_first_kind() function somehow
generated quantities {
real bessel_value;
bessel_value = log_modified_bessel_first_kind(1.5, 3.5);
}'

stan_model_object <- stan_model(model_code = mc, model_name = "external", allow_undefined = TRUE, verbose = TRUE,
                                includes = paste0('\n#include "', getwd(), '/interface.hpp"\n'))

Thank you!