diff --git a/R/utils.R b/R/utils.R index 7e732c0a5..bf65b513d 100644 --- a/R/utils.R +++ b/R/utils.R @@ -759,7 +759,8 @@ expose_model_methods <- function(env, verbose = FALSE, hessian = FALSE) { } initialize_model_pointer <- function(env, data, seed = 0) { - ptr_and_rng <- env$model_ptr(data, seed) + datafile_path <- ifelse(is.null(data), "", data) + ptr_and_rng <- env$model_ptr(datafile_path, seed) env$model_ptr_ <- ptr_and_rng$model_ptr env$model_rng_ <- ptr_and_rng$base_rng env$num_upars_ <- env$get_num_upars(env$model_ptr_) diff --git a/inst/include/model_methods.cpp b/inst/include/model_methods.cpp index 65c673d22..196d7db68 100644 --- a/inst/include/model_methods.cpp +++ b/inst/include/model_methods.cpp @@ -6,9 +6,15 @@ #include #else #include +#include #endif std::shared_ptr var_context(std::string file_path) { + if (file_path == "") { + stan::io::empty_var_context empty_context; + return std::make_shared(empty_context); + } + std::fstream stream(file_path.c_str(), std::fstream::in); #ifdef CMDSTAN_JSON using json_data_t = cmdstan::json::json_data; diff --git a/tests/testthat/test-model-methods.R b/tests/testthat/test-model-methods.R index 31a99ada2..8352a04f3 100644 --- a/tests/testthat/test-model-methods.R +++ b/tests/testthat/test-model-methods.R @@ -268,3 +268,12 @@ test_that("unconstrain_draws returns correct values", { unconstrained_draws <- fit$unconstrain_draws(draws = fit$draws())[[1]] expect_equal(as.numeric(x_draws), exp(as.numeric(unconstrained_draws))) }) + +test_that("Model methods can be initialised for models with no data", { + skip_if(os_is_wsl()) + + stan_file <- write_stan_file("parameters { real x; } model { x ~ std_normal(); }") + mod <- cmdstan_model(stan_file, compile_model_methods = TRUE, force_recompile = TRUE) + expect_no_error(fit <- mod$sample()) + expect_equal(fit$log_prob(5), -12.5) +})