Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix init_model_methods for models with no data #801

Merged
merged 2 commits into from
Jul 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -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_)
Expand Down
6 changes: 6 additions & 0 deletions inst/include/model_methods.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,15 @@
#include <cmdstan/io/json/json_data.hpp>
#else
#include <stan/io/json/json_data.hpp>
#include <stan/io/empty_var_context.hpp>
#endif

std::shared_ptr<stan::io::var_context> var_context(std::string file_path) {
if (file_path == "") {
stan::io::empty_var_context empty_context;
return std::make_shared<stan::io::empty_var_context>(empty_context);
}

std::fstream stream(file_path.c_str(), std::fstream::in);
#ifdef CMDSTAN_JSON
using json_data_t = cmdstan::json::json_data;
Expand Down
9 changes: 9 additions & 0 deletions tests/testthat/test-model-methods.R
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
Loading