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

allow empty data list #403

Merged
merged 4 commits into from
Dec 14, 2020
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
4 changes: 4 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
* Fixed reading inverse mass matrix with values written in scientific format in
the CSV. (#394)

* Fixed error caused by an empty data list. Previously if a model didn't require
data then `data` had to either be NULL or be a non-empty list, but now `list()`
is allowed. (#403)

### New features

* Added `$sample_mpi()` for MCMC sampling with MPI. (#350)
Expand Down
3 changes: 3 additions & 0 deletions R/data.R
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,9 @@ list_to_array <- function(x, name = NULL) {
#' CmdStan, or a named list of \R objects to pass to [write_stan_json()].
#' @return Path to data file.
process_data <- function(data) {
if (length(data) == 0) {
data <- NULL
}
if (is.null(data)) {
path <- data
} else if (is.character(data)) {
Expand Down
4 changes: 4 additions & 0 deletions tests/testthat/test-data.R
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ if (not_on_cran()) {
fit_optimize <- testing_fit("bernoulli", method = "optimize", seed = 123)
}

test_that("empty data list converted to NULL", {
expect_null(process_data(list()))
})

test_that("NAs detected in data list", {
expect_false(any_na_elements(list(y = 1)))
expect_true(any_na_elements(list(y = 1, N = NA)))
Expand Down
18 changes: 18 additions & 0 deletions tests/testthat/test-model-data.R
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,21 @@ test_that("error if data contains NA elements", {
expect_error(mod$sample(data = data_list2), "Data includes NA values")
expect_error(mod$sample(data = data_list3), "Data includes NA values")
})

test_that("empty data list doesn't error if no data block", {
mod <- cmdstan_model(write_stan_file("
parameters {
real x;
}
model {
x ~ normal(0, 1);
}
"))

expect_sample_output(
fit <- mod$sample(data = list(), chains = 1)
)

# would error if fitting failed
expect_silent(fit$draws())
})