I have a workflow where I write unit test for my Stan functions in R, but run my test scripts through Makefiles. Often the test code changes faster than the Stan code and if there was a convenient way to save the functions that expose_stan_functions() exposes (like you can save the stanmodel object it would avoid needless recompilations and speed up testing.
Does anyone have any experiences or ideas with this?
Just saving the object returned by Rcpp::sourceCpp() using saveRDS() does not keep dso around, so that didnβt work. For the stanmodel object the magic seems to happen in cxxfunplus.R, but I canβt quite figure out how that would be adapted for expose_stan_functions().
My impression is that it does not work, and it is a Rcpp limitation. You can look at args(Rcpp::sourceCpp) and see that it has a cacheDir argument that defaults to tempdir. If you set that option to something permanent, that may be a start.
That led me to the solution! Iβd been thinking too complicated. No need to fiddle with the source of expose_stan_functions().
By setting rcpp.cache.dir with options() I get access to the .so and .cpp.R files, which I can rename and use as Makefile targets. After substituting the new filename of the .so in the .cpp.R, the latter can be sourced from my test scripts.
Thank you guys for pointing me in this direction. This rcpp.cache.dir is a life-saver. A few notes for anyone who finds this: If you want to avoid recompilation every time you load the exposed stan functions, you have to follow these steps:
set the rcpp.cache.dir option as described avove
Use the stanc_builder function with the (default) obfuscate_model_name=FALSE setting in order to ensure that the same c++ code is generated each time
pass the result from stanc_builder into expose_stan_functions
Also make sure that a recent enough Rcpp is installed which supports dso caching.
@bgoodri: Should we make expose_stan_functions by default such that the model name is not obfuscated? This would lead to easier caching of this. Maybe we could even switch on the caching stuff if rstan_auto_write is set to true?
User who use exposed stan functions will love this caching.