Hoping for some guidance / help with implementing custom log likelihood and gradient for research project (details below)

Here is another example without having to change stanc3:

Stan model:

hpp file: cmdstanpy/make_odds.hpp at 2ed87fe2780e80d04d3dc783fac4ddb4762adb22 · stan-dev/cmdstanpy · GitHub

Note that the function is inside the namespace bernoulli_external_model which is the model name + the _model suffix.

Then you need to set the following in the make/local file:

USER_HEADER=path/to/hpp/file.hpp
STANCFLAGS += --allow-undefined

an example with cmdstanr:

library(cmdstanr)

stan_file <- "bernoulli_external.stan"

mod <- cmdstan_model(
  stan_file,
  cpp_options = list(USER_HEADER="/full/path/to/the/external/file/make_odds.hpp"),
  stanc_options = list("allow-undefined")
)
data_list <- list(N = 10, y = c(0,1,0,0,0,0,0,0,0,1))
fit <- mod$sample(data = data_list)

Note that at the moment the USER_HEADER at least for cmdstanr has to be the full absolute path.

1 Like