Skip to content

Commit

Permalink
Merge pull request #857 from stan-dev/single-length-init
Browse files Browse the repository at this point in the history
Fix handling of single-length inits for containers
  • Loading branch information
andrjohns authored Sep 27, 2023
2 parents 021049b + 50616d0 commit 77a1443
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
7 changes: 7 additions & 0 deletions R/args.R
Original file line number Diff line number Diff line change
Expand Up @@ -896,6 +896,13 @@ process_init_list <- function(init, num_procs, model_variables = NULL) {
if (!all(is_parameter_value_supplied)) {
missing_parameter_values[[i]] <- parameter_names[!is_parameter_value_supplied]
}
for (par_name in parameter_names[is_parameter_value_supplied]) {
# Make sure that initial values for single-element containers don't get
# unboxed when writing to JSON
if (model_variables$parameters[[par_name]]$dimensions == 1 && length(init[[i]][[par_name]]) == 1) {
init[[i]][[par_name]] <- array(init[[i]][[par_name]], dim = 1)
}
}
}
if (length(missing_parameter_values) > 0) {
warning_message <- c(
Expand Down
22 changes: 22 additions & 0 deletions tests/testthat/test-model-init.R
Original file line number Diff line number Diff line change
Expand Up @@ -270,3 +270,25 @@ test_that("print message if not all parameters are initialized", {
fixed = TRUE
)
})

test_that("Initial values for single-element containers treated correctly", {
modcode <- "
data {
real y_mean;
}
parameters {
vector[1] y;
}
model {
y_mean ~ normal(y[1], 1);
}
"
mod <- cmdstan_model(write_stan_file(modcode), force_recompile = TRUE)
expect_no_error(
fit <- mod$sample(
data = list(y_mean = 0),
init = list(list(y = c(0))),
chains = 1
)
)
})

0 comments on commit 77a1443

Please sign in to comment.