Functions to debug and profile stan models in R


I’ve found that sometimes I have simple errors in my code that can be hard to debug from the error thrown in the sampling command. Additionally, it can be hard to profile the code using sampling since there is a lot going on with the HMC sampler.

It’s not really clear how to get the log prob value from the stan model, but I was able to come up with this. I was following the rstan thread, and wanted to share this here in case anyone wants to use it, and also in hopes that this sort of thing would be easier in the new rstan version.

checkStanModel <- function(stan.model){
    x <- new(stan.model@mk_cppmodule(stan.model),,rstan:::grab_cxxfun(stan.model@dso))
profileStanModel <- function(stan.model,n=1000){
    x <- new(stan.model@mk_cppmodule(stan.model),,rstan:::grab_cxxfun(stan.model@dso))   


There’s a built in for evaluating log density from a compiled model with data. It’s log_prob and grad_log_prob if you need gradient. That’s on the unconstrained scale, so you may need to transform from constrained to unconstrained.


It felt like there must be a better way… How do I get the compiled model with the data? I couldn’t figure out a way to do it without calling sampling.


I don’t think it is possible, though you could ask @bgoodri or @jonah. One of my main goals for RStan and PyStan 3 is to fix this so that there is an object for compiled program plus data (basically, the posterior density object).