Cmdstan binary in R package

Hi there!

I maintain a few R packages, which use rstantools to hook a Stan model into R via rstan. Now, I would like to provide a cmdstan binary of the model with my R package in order to be able to allow for a cmdstanr backend to be used for various reasons.

The question I have is how can I deploy a binary of the cmdstan model with my R package when it is installed? When looking around there are almost everywhere comments like

# Generated by rstantools.  Do not edit by hand.

This is in configure and src/Makevars… so which file can I edit to add my additional deployment code. Essentially I would like to use cmdstanr to compile the model and store it in the bin folder under the package (or whatever is allowed by CRAN).

Any suggestions?

@Jonah , @bgoodri or @hsbadr ?

(right now I am compiling the model once per R session, which works, but is annoying to do, of course)


Mentioning @rok_cesnovar as I think this needs to be done via cmdstanr.

See Update with cmdstan backend throws error, or requires recompilation · Issue #1135 · paul-buerkner/brms · GitHub for some discussion on this and a working example. Adding this to cmdstanr is on the feature list but its priority was bumped down a bit as brms does not have such a big need for it, it turns out (this was later discussed in another thread, but I can’t find it right now sorry).

To answer this for reference for others: With cmdstanr 0.5.0 the write_stan_file function can essentially solve all things I want to achieve, which is to avoid model recompiles between R sessions. The new function chooses the file name based on the hash of the Stan model and it also allows to configure the directory where the models are stored as a global option. In addition, the function will not overwrite an existing file in case a model with the same filename (which corresponds to its contents by the hash) already exists. This way the model just once on the directory specified globally by the user and most importantly is only ever compiled once. That’s all I need… and great to know for use with brms (for which this feature was likely designed). Thanks @martinmodrak who contributed this neat logic to cmdstanr.