stan-dev / rstan

RStan, the R interface to Stan
https://mc-stan.org
1.04k stars 267 forks source link

read_stan_csv error #1134

Closed YuxuanJiang9302 closed 4 months ago

YuxuanJiang9302 commented 4 months ago

Summary:

There seem to be an error of the function read_stan_csv in rstan version 2.32.6, and I was told this is the place to report a possible bug.

Description:

I was trying to use the read_stan_csv function to convert a cmdstanr fit object to a rstan fit object on my own model (in order to use bridge sampling to calculate a bayes factor), which gave me an error. I tried using read_stan_csv with the Bernoulli exmaple, which gave me the same error.

Reproducible Steps:

The code is:

library("rstan")
#rstan version 2.32.6
#stan version 2.32.2

library(cmdstanr)
#cmdstanr version 0.8.1
#cmdstan version 2.35.0

file <- file.path(cmdstan_path(), "examples", "bernoulli", "bernoulli.stan")
mod <- cmdstan_model(file)

data_list <- list(N = 10, y = c(0,1,0,0,0,0,0,0,0,1))

fit <- mod$sample(
  data = data_list,
  seed = 123,
  chains = 4,
  parallel_chains = 4,
  refresh = 500, 
  save_warmup= TRUE
)

fit_rstan <- read_stan_csv(fit$output_files())

The error message is:

> fit_rstan <- read_stan_csv(fit$output_files())
Error in if (max(save_warmup) == 0L) { : 
  missing value where TRUE/FALSE needed
In addition: Warning messages:
1: In parse_stancsv_comments(comments) : NAs introduced by coercion
2: In parse_stancsv_comments(comments) : NAs introduced by coercion
3: In parse_stancsv_comments(comments) : NAs introduced by coercion
4: In parse_stancsv_comments(comments) : NAs introduced by coercion

I looked inside the function read_stan_csv, and the error comes form line 76 inside this function: save_warmup only contains NA value. This is probably because at line 21, the function parse_stancsv_comments has an error. Inside parse_stancsv_comments, values$save_warmup is "false" or "true", so at line 75,as.integer(values[[save_warmup]]) is as.integer("true") from my input which would produce the NAs introduced by coercion error. Change that to as.integer(as.logical(values[[save_warmup]])) would probably fix it.

RStan Version:

2.32.6

R Version:

R version 4.4.1 (2024-06-14)

Operating System:

macOS 14.5

jgabry commented 4 months ago

Thanks. I think this is probably the same issue that this pull request addressed: https://github.com/stan-dev/rstan/pull/1131