Custom c++ using cmdstanr?

Ok, yeah, this uncovered a cmdstan bug. USER_HEADER only works with the deprecated --allow_undefined. Argh…

Would you mind creating an issue for this on cmdstan?

This works:

library(cmdstanr)
model_code <-
"
functions {
  real my_fun(real r);
}
transformed data {
  real s = my_fun(0.0);
}
parameters {
  real y;
}
model {
  y ~ normal(0, 1);
}
"
stan_file <- write_stan_file(model_code, basename = "test.stan")
hpp_code <-
"
#include <iostream>

namespace test_model_namespace {

double my_fun(double r, std::ostream* = nullptr) {
  return r+1.0;
}

}
"
hpp_file <- "test.hpp"
write(hpp_code, file = hpp_file)
mod <- cmdstan_model(stan_file,include_paths=getwd(),
              cpp_options=list(USER_HEADER=file.path(getwd(), hpp_file)),
              stanc_options = list("allow_undefined")
)
fit <- mod$sample()

What you need to be careful with is the std::ostream* argument. Those are required for any external C++ function in Stan.

2 Likes