Skip to content

Commit 323c14d

Browse files
authored
Merge pull request #801 from stan-dev/issue-793-model-methods
Fix init_model_methods for models with no data
2 parents e8fc2d3 + 99bfe0f commit 323c14d

3 files changed

Lines changed: 17 additions & 1 deletion

File tree

R/utils.R

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -759,7 +759,8 @@ expose_model_methods <- function(env, verbose = FALSE, hessian = FALSE) {
759759
}
760760

761761
initialize_model_pointer <- function(env, data, seed = 0) {
762-
ptr_and_rng <- env$model_ptr(data, seed)
762+
datafile_path <- ifelse(is.null(data), "", data)
763+
ptr_and_rng <- env$model_ptr(datafile_path, seed)
763764
env$model_ptr_ <- ptr_and_rng$model_ptr
764765
env$model_rng_ <- ptr_and_rng$base_rng
765766
env$num_upars_ <- env$get_num_upars(env$model_ptr_)

inst/include/model_methods.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,15 @@
66
#include <cmdstan/io/json/json_data.hpp>
77
#else
88
#include <stan/io/json/json_data.hpp>
9+
#include <stan/io/empty_var_context.hpp>
910
#endif
1011

1112
std::shared_ptr<stan::io::var_context> var_context(std::string file_path) {
13+
if (file_path == "") {
14+
stan::io::empty_var_context empty_context;
15+
return std::make_shared<stan::io::empty_var_context>(empty_context);
16+
}
17+
1218
std::fstream stream(file_path.c_str(), std::fstream::in);
1319
#ifdef CMDSTAN_JSON
1420
using json_data_t = cmdstan::json::json_data;

tests/testthat/test-model-methods.R

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,3 +268,12 @@ test_that("unconstrain_draws returns correct values", {
268268
unconstrained_draws <- fit$unconstrain_draws(draws = fit$draws())[[1]]
269269
expect_equal(as.numeric(x_draws), exp(as.numeric(unconstrained_draws)))
270270
})
271+
272+
test_that("Model methods can be initialised for models with no data", {
273+
skip_if(os_is_wsl())
274+
275+
stan_file <- write_stan_file("parameters { real x; } model { x ~ std_normal(); }")
276+
mod <- cmdstan_model(stan_file, compile_model_methods = TRUE, force_recompile = TRUE)
277+
expect_no_error(fit <- mod$sample())
278+
expect_equal(fit$log_prob(5), -12.5)
279+
})

0 commit comments

Comments
 (0)