diff --git a/DESCRIPTION b/DESCRIPTION index c73a30d97..7af79bdb0 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -64,6 +64,7 @@ Suggests: ggplot2, knitr (>= 1.37), loo (>= 2.0.0), + nanoparquet (>= 0.5.0), progressr, qs2, Rcpp, diff --git a/NAMESPACE b/NAMESPACE index 188892921..fbdccbd6b 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -28,6 +28,7 @@ export(as_draws) export(as_mcmc.list) export(check_cmdstan_toolchain) export(check_syntax_stan_file) +export(cmdstan_csv_to_parquet) export(cmdstan_default_install_path) export(cmdstan_default_path) export(cmdstan_make_local) @@ -43,6 +44,7 @@ export(install_cmdstan) export(print_example_program) export(print_stan_file) export(read_cmdstan_csv) +export(read_cmdstan_parquet) export(rebuild_cmdstan) export(register_knitr_engine) export(set_cmdstan_path) diff --git a/R/csv.R b/R/csv.R index f8384194f..ff28b38e5 100644 --- a/R/csv.R +++ b/R/csv.R @@ -125,6 +125,14 @@ #' information not contained in the CSV files. Calling an unavailable method #' produces an informative error. #' +#' `as_cmdstan_fit()` also accepts one Parquet file from +#' [cmdstan_csv_to_parquet()] (MCMC output only), with an optional +#' `warmup_file`. The object then reads the draws with +#' [read_cmdstan_parquet()], and it has the same methods as an object made +#' from the CSV files. `$output_files()` gives the Parquet file, and +#' `$num_chains()` and `$time()` come from the metadata in the file. Without +#' `warmup_file`, `$draws(inc_warmup = TRUE)` gives an error. +#' #' @seealso [draws_to_csv()] for creating compatible CSV files and #' [`$output_files()`][fit-method-output_files] for locating files created by #' CmdStanR @@ -179,83 +187,22 @@ read_cmdstan_csv <- function( ) { temp_dir <- withr::local_tempdir() withr::local_path(toolchain_PATH_env_var()) - # If the CSV files are stored in the WSL filesystem then it is significantly - # faster (~4x) to first copy them (via WSL) to a Windows tempdir before reading - files <- stage_wsl_csv_files(files, temp_dir) format <- assert_valid_draws_format(format) - assert_file_exists( - files, - access = "r", - extension = c("csv", "csv.gz", "csv.bz2") - ) - files <- wsl_safe_path(files, revert = TRUE) - files <- decompress_csv_files(files, temp_dir) + files <- prepare_csv_files(files, temp_dir) metadata <- NULL warmup_draws <- list() draws <- list() warmup_sampler_diagnostics <- list() post_warmup_sampler_diagnostics <- list() - inv_metric <- list() - step_size <- list() - csv_metadata <- list() - time <- data.frame() - file_idx <- 0 - for (output_file in files) { - file_idx <- length(csv_metadata) + 1 - csv_metadata[[file_idx]] <- read_csv_metadata(output_file) - } - if (file_idx > 1) { - check_csv_metadata_matches(csv_metadata) - } - id <- csv_metadata[[1]]$id - if (!is.null(csv_metadata[[1]]$inv_metric)) { - inv_metric[[as.character(id)]] <- csv_metadata[[1]]$inv_metric - } - if (!is.null(csv_metadata[[1]]$step_size_adaptation)) { - step_size[[as.character(id)]] <- csv_metadata[[1]]$step_size_adaptation - } - if (!is.null(csv_metadata[[1]]$time)) { - time <- rbind(time, csv_metadata[[1]]$time) - } + csv_metadata <- lapply(files, read_csv_metadata) if (length(csv_metadata) > 1) { - for (file_id in 2:length(csv_metadata)) { - file_metadata <- csv_metadata[[file_id]] - id <- file_metadata$id - csv_metadata[[1]]$id <- c(csv_metadata[[1]]$id, id) - csv_metadata[[1]]$seed <- c(csv_metadata[[1]]$seed, file_metadata$seed) - csv_metadata[[1]]$init <- c(csv_metadata[[1]]$init, file_metadata$init) - csv_metadata[[1]]$step_size <- c( - csv_metadata[[1]]$step_size, - file_metadata$step_size - ) - csv_metadata[[1]]$step_size_adaptation <- c( - csv_metadata[[1]]$step_size_adaptation, - file_metadata$step_size_adaptation - ) - csv_metadata[[1]]$fitted_params <- c( - csv_metadata[[1]]$fitted_params, - file_metadata$fitted_params - ) - if (!is.null(file_metadata$inv_metric)) { - inv_metric[[as.character(id)]] <- file_metadata$inv_metric - } - if (!is.null(file_metadata$step_size_adaptation)) { - step_size[[as.character(id)]] <- file_metadata$step_size_adaptation - } - if (!is.null(file_metadata$time)) { - time <- rbind(time, file_metadata$time) - } - } - } - metadata <- csv_metadata[[1]] - if (metadata$method == "sample") { - metadata$num_chains <- length(csv_metadata) - } - uniq_seed <- unique(metadata$seed) - if (length(uniq_seed) == 1) { - metadata$seed <- uniq_seed + check_csv_metadata_matches(csv_metadata) } - metadata$time <- time + merged <- merge_csv_metadata(csv_metadata) + metadata <- merged$metadata + inv_metric <- merged$inv_metric + step_size <- merged$step_size + time <- merged$time if (metadata$method == "diagnose") { gradients <- metadata$gradients metadata$gradients <- NULL @@ -274,52 +221,13 @@ read_cmdstan_csv <- function( setdiff(metadata$variables, pathfinder_variables) ) } - if (is.null(variables)) { - # variables = NULL returns all - variables <- metadata$variables - } else if (!any(nzchar(variables))) { - # if variables = "" returns none - variables <- NULL - } else { - # filter using variables - res <- matching_variables( - variables, - repair_variable_names(metadata$variables) - ) - if (length(res$not_found)) { - stop( - "Can't find the following variable(s) in the output: ", - paste(res$not_found, collapse = ", "), - call. = FALSE - ) - } - variables <- unrepair_variable_names(res$matching) - } - if (is.null(sampler_diagnostics)) { - sampler_diagnostics <- metadata$sampler_diagnostics - } else if (!any(nzchar(sampler_diagnostics))) { - # if sampler_diagnostics = "" returns none - sampler_diagnostics <- NULL - } else { - selected_sampler_diag <- rep(FALSE, length(metadata$sampler_diagnostics)) - not_found <- NULL - for (p in sampler_diagnostics) { - matches <- metadata$sampler_diagnostics == p | - startsWith(metadata$sampler_diagnostics, paste0(p, ".")) - if (!any(matches)) { - not_found <- c(not_found, p) - } - selected_sampler_diag <- selected_sampler_diag | matches - } - if (length(not_found)) { - stop( - "Can't find the following sampler diagnostic(s) in the output: ", - paste(not_found, collapse = ", "), - call. = FALSE - ) - } - sampler_diagnostics <- metadata$sampler_diagnostics[selected_sampler_diag] - } + selected_columns <- select_csv_columns( + metadata, + variables, + sampler_diagnostics + ) + variables <- selected_columns$variables + sampler_diagnostics <- selected_columns$sampler_diagnostics num_warmup_draws <- ceiling(metadata$iter_warmup / metadata$thin) selected <- c(sampler_diagnostics, variables) repaired_variables <- repair_variable_names(variables) @@ -401,10 +309,7 @@ read_cmdstan_csv <- function( repaired_variables <- gsub("log_p__", "lp__", repaired_variables) repaired_variables <- gsub("log_q__", "lp_approx__", repaired_variables) } - model_param_dims <- variable_dims(metadata$variables) - metadata$stan_variable_sizes <- model_param_dims - metadata$stan_variables <- names(model_param_dims) - metadata$model_params <- metadata$variables # for backwards compatibility + metadata <- add_variable_metadata(metadata) if (metadata$method == "sample") { if (is.null(format)) { format <- "draws_array" @@ -551,19 +456,43 @@ read_cmdstan_csv <- function( #' diagnostic checks be performed after reading in the files? The default is #' `TRUE` but set to `FALSE` to avoid checking for problems with divergences #' and treedepth. +#' @param warmup_file (string) For a Parquet file in `files`, the optional +#' Parquet file of the warmup draws. See [read_cmdstan_parquet()]. #' as_cmdstan_fit <- function( files, variables = NULL, check_diagnostics = TRUE, - format = getOption("cmdstanr_draws_format") + format = getOption("cmdstanr_draws_format"), + warmup_file = NULL ) { - csv_contents <- read_cmdstan_csv( - files, - variables = if (is.null(variables)) "" else variables, - sampler_diagnostics = if (check_diagnostics) NULL else "", - format = format - ) + parquet_files <- grepl("\\.parquet$", files, ignore.case = TRUE) + if (any(parquet_files) && length(files) > 1) { + stop("Give one Parquet file, not ", length(files), " files.", call. = FALSE) + } + is_parquet <- any(parquet_files) + if (is_parquet) { + csv_contents <- read_cmdstan_parquet( + files, + variables = if (is.null(variables)) "" else variables, + sampler_diagnostics = if (check_diagnostics) NULL else "", + format = format, + warmup_file = warmup_file + ) + } else { + if (!is.null(warmup_file)) { + stop( + "'warmup_file' can only be used with a Parquet file.", + call. = FALSE + ) + } + csv_contents <- read_cmdstan_csv( + files, + variables = if (is.null(variables)) "" else variables, + sampler_diagnostics = if (check_diagnostics) NULL else "", + format = format + ) + } method <- csv_contents$metadata$method if (!is.null(variables)) { if (method == "sample") { @@ -578,7 +507,16 @@ as_cmdstan_fit <- function( } switch( method, - "sample" = CmdStanMCMC_CSV$new(csv_contents, files, check_diagnostics), + "sample" = if (is_parquet) { + CmdStanMCMC_Parquet$new( + csv_contents, + files, + warmup_file, + check_diagnostics + ) + } else { + CmdStanMCMC_CSV$new(csv_contents, files, check_diagnostics) + }, "optimize" = CmdStanMLE_CSV$new(csv_contents, files), "variational" = CmdStanVB_CSV$new(csv_contents, files), "pathfinder" = CmdStanPathfinder_CSV$new(csv_contents, files), @@ -792,6 +730,172 @@ parse_generated_quantities_time <- function(line) { time } +#' Merge the metadata of the CSV files of one run. +#' +#' @noRd +#' @param csv_metadata A list with the `read_csv_metadata()` output of each +#' file. +#' @return A list with `metadata` (the first file's metadata with the +#' per-chain values of all files), `inv_metric` and `step_size` (lists +#' named by chain id) and `time` (a data frame with one row per chain). +#' +merge_csv_metadata <- function(csv_metadata) { + inv_metric <- list() + step_size <- list() + time <- data.frame() + id <- csv_metadata[[1]]$id + if (!is.null(csv_metadata[[1]]$inv_metric)) { + inv_metric[[as.character(id)]] <- csv_metadata[[1]]$inv_metric + } + if (!is.null(csv_metadata[[1]]$step_size_adaptation)) { + step_size[[as.character(id)]] <- csv_metadata[[1]]$step_size_adaptation + } + if (!is.null(csv_metadata[[1]]$time)) { + time <- rbind(time, csv_metadata[[1]]$time) + } + if (length(csv_metadata) > 1) { + for (file_id in 2:length(csv_metadata)) { + file_metadata <- csv_metadata[[file_id]] + id <- file_metadata$id + csv_metadata[[1]]$id <- c(csv_metadata[[1]]$id, id) + csv_metadata[[1]]$seed <- c(csv_metadata[[1]]$seed, file_metadata$seed) + csv_metadata[[1]]$init <- c(csv_metadata[[1]]$init, file_metadata$init) + csv_metadata[[1]]$step_size <- c( + csv_metadata[[1]]$step_size, + file_metadata$step_size + ) + csv_metadata[[1]]$step_size_adaptation <- c( + csv_metadata[[1]]$step_size_adaptation, + file_metadata$step_size_adaptation + ) + csv_metadata[[1]]$fitted_params <- c( + csv_metadata[[1]]$fitted_params, + file_metadata$fitted_params + ) + if (!is.null(file_metadata$inv_metric)) { + inv_metric[[as.character(id)]] <- file_metadata$inv_metric + } + if (!is.null(file_metadata$step_size_adaptation)) { + step_size[[as.character(id)]] <- file_metadata$step_size_adaptation + } + if (!is.null(file_metadata$time)) { + time <- rbind(time, file_metadata$time) + } + } + } + metadata <- csv_metadata[[1]] + if (metadata$method == "sample") { + metadata$num_chains <- length(csv_metadata) + } + uniq_seed <- unique(metadata$seed) + if (length(uniq_seed) == 1) { + metadata$seed <- uniq_seed + } + metadata$time <- time + list( + metadata = metadata, + inv_metric = inv_metric, + step_size = step_size, + time = time + ) +} + +#' Select the CSV columns of the requested variables and sampler diagnostics. +#' +#' @noRd +#' @param metadata Merged metadata, with the CSV variable names. +#' @param variables,sampler_diagnostics As in `read_cmdstan_csv()`. +#' @return A list with the CSV names of the selected `variables` and +#' `sampler_diagnostics` (`NULL` for none). +#' +select_csv_columns <- function(metadata, variables, sampler_diagnostics) { + if (is.null(variables)) { + # variables = NULL returns all + variables <- metadata$variables + } else if (!any(nzchar(variables))) { + # if variables = "" returns none + variables <- NULL + } else { + # filter using variables + res <- matching_variables( + variables, + repair_variable_names(metadata$variables) + ) + if (length(res$not_found)) { + stop( + "Can't find the following variable(s) in the output: ", + paste(res$not_found, collapse = ", "), + call. = FALSE + ) + } + variables <- unrepair_variable_names(res$matching) + } + if (is.null(sampler_diagnostics)) { + sampler_diagnostics <- metadata$sampler_diagnostics + } else if (!any(nzchar(sampler_diagnostics))) { + # if sampler_diagnostics = "" returns none + sampler_diagnostics <- NULL + } else { + selected_sampler_diag <- rep(FALSE, length(metadata$sampler_diagnostics)) + not_found <- NULL + for (p in sampler_diagnostics) { + matches <- metadata$sampler_diagnostics == p | + startsWith(metadata$sampler_diagnostics, paste0(p, ".")) + if (!any(matches)) { + not_found <- c(not_found, p) + } + selected_sampler_diag <- selected_sampler_diag | matches + } + if (length(not_found)) { + stop( + "Can't find the following sampler diagnostic(s) in the output: ", + paste(not_found, collapse = ", "), + call. = FALSE + ) + } + sampler_diagnostics <- metadata$sampler_diagnostics[selected_sampler_diag] + } + list(variables = variables, sampler_diagnostics = sampler_diagnostics) +} + +#' Add the variable dimensions to the metadata. +#' +#' @noRd +#' @param metadata Metadata with the repaired variable names. +#' @return The metadata with `stan_variable_sizes`, `stan_variables` and +#' `model_params`. +#' +add_variable_metadata <- function(metadata) { + model_param_dims <- variable_dims(metadata$variables) + metadata$stan_variable_sizes <- model_param_dims + metadata$stan_variables <- names(model_param_dims) + metadata$model_params <- metadata$variables # for backwards compatibility + metadata +} + +#' Check CmdStan CSV files and make readable copies where needed. +#' +#' Copies CSV files from the WSL filesystem to `dir`, converts WSL paths to +#' Windows paths, and decompresses `.csv.gz` and `.csv.bz2` files to `dir`. +#' +#' @noRd +#' @param files Paths to CmdStan CSV files. +#' @param dir A temporary directory that the caller deletes. +#' @return Paths to uncompressed CSV files. +#' +prepare_csv_files <- function(files, dir) { + # If the CSV files are stored in the WSL filesystem then it is significantly + # faster (~4x) to first copy them (via WSL) to a Windows tempdir before reading + files <- stage_wsl_csv_files(files, dir) + assert_file_exists( + files, + access = "r", + extension = c("csv", "csv.gz", "csv.bz2") + ) + files <- wsl_safe_path(files, revert = TRUE) + decompress_csv_files(files, dir) +} + #' Decompress a compressed CmdStan CSV file #' #' Runs gzip or bzip2 to write the contents of a `.csv.gz` or `.csv.bz2` diff --git a/R/fit.R b/R/fit.R index 474a352ce..f43946471 100644 --- a/R/fit.R +++ b/R/fit.R @@ -1793,6 +1793,15 @@ CmdStanMCMC <- R6::R6Class( warmup_sampler_diagnostics_ = NULL, warmup_draws_ = NULL, inv_metric_ = NULL, + # reads the output files; a fit from a Parquet file overrides this + read_output_ = function(variables, sampler_diagnostics, format) { + read_cmdstan_csv( + files = private$csv_files_(), + variables = variables, + sampler_diagnostics = sampler_diagnostics, + format = format + ) + }, read_csv_ = function( variables = NULL, sampler_diagnostics = NULL, @@ -1804,9 +1813,7 @@ CmdStanMCMC <- R6::R6Class( call. = FALSE ) } - files <- private$csv_files_() - csv_contents <- read_cmdstan_csv( - files = files, + csv_contents <- private$read_output_( variables = variables, sampler_diagnostics = sampler_diagnostics, format = format diff --git a/R/parquet.R b/R/parquet.R new file mode 100644 index 000000000..883869f62 --- /dev/null +++ b/R/parquet.R @@ -0,0 +1,863 @@ +#' Convert CmdStan CSV files to a Parquet file +#' +#' Convert the CSV output files of the CmdStan MCMC sampler to one Parquet +#' file, without reading all draws into memory. The Parquet file contains the +#' columns of a [`draws_df`][posterior::draws_df] object, and the CmdStan +#' metadata. +#' +#' @export +#' @param files (character vector) Paths to CmdStan CSV files from +#' `$sample()`, one file per chain. Files compressed with gzip (`.csv.gz`) +#' or bzip2 (`.csv.bz2`) are first decompressed to a temporary directory. +#' @param file (string) Path of the Parquet file for the post-warmup draws. +#' @param warmup_file (string) Optional path of a second Parquet file for the +#' warmup draws. If the CSV files do not contain warmup draws, this file has +#' the columns but no rows. The default is `NULL`, which drops the warmup +#' draws. +#' @param chunk_rows (positive integer) The number of CSV lines to read at a +#' time. Each chunk is written as new Parquet row groups; nanoparquet splits +#' a chunk with more rows than its `num_rows_per_row_group` option. The +#' default is `NULL`, which selects about 10 million values for each chunk. +#' @param compression (string) The compression of the Parquet files. One of +#' `"zstd"` (the default), `"snappy"`, `"gzip"` or `"uncompressed"`. +#' @param overwrite (logical) Replace existing output files? The default is +#' `FALSE`. +#' +#' @return The path of the Parquet file of the post-warmup draws, invisibly. +#' +#' @details +#' This function requires the \pkg{nanoparquet} package. It reads each CSV +#' file in chunks of `chunk_rows` lines and appends each chunk to the Parquet +#' file. +#' +#' The memory use grows with `chunk_rows` times the number of columns. It does +#' not grow with the number of chunks, with one exception: each append reads +#' and writes the Parquet footer, which grows with the number of row groups +#' times the number of columns. For output with very many columns, use a large +#' `chunk_rows` if the memory allows it. +#' +#' The Parquet file has the following columns: +#' * all columns of the CSV files (`lp__`, the sampler diagnostics, and the +#' model variables), as doubles. The names use the `beta[1,2]` form, as in +#' `$draws()`. +#' * the integer columns `.chain`, `.iteration` and `.draw`, as in a +#' [`draws_df`][posterior::draws_df] object. `.chain` is the position of the +#' file in `files`. `.iteration` starts from 1 in each chain. `.draw` +#' numbers the draws of all chains consecutively. +#' +#' [read_cmdstan_parquet()] reads the file into the same structure as +#' [read_cmdstan_csv()], with the draws (`lp__` and the model variables) and +#' the sampler diagnostics separate. [as_cmdstan_fit()] makes a fitted model +#' object from the file. +#' +#' `posterior::as_draws_df(nanoparquet::read_parquet(file))` gives all +#' columns in one data frame, and the `col_select` argument of +#' [nanoparquet::read_parquet()] +#' reads only some of the variables. Include `.chain`, `.iteration` and +#' `.draw` in `col_select` to keep the chain structure. Other Parquet +#' readers (for example \pkg{arrow}, \pkg{duckdb} and \pkg{polars}) can also +#' read the file. +#' +#' The key-value metadata of the Parquet file has three Stan entries: +#' * `stan.format_version`: the version of this file layout, now `"1"`. +#' * `stan.draws`: `"sampling"` in `file` and `"warmup"` in `warmup_file`. +#' * `stan.metadata`: the CmdStan metadata as a JSON object. It has the +#' values that [read_cmdstan_csv()] reads from the CSV comments, for example +#' the CmdStan version and the sampler arguments, and `variables`, +#' `sampler_diagnostics`, `stan_variable_sizes` and `num_chains`. Element +#' `chains` is an array with one object for each chain: the chain `id`, the +#' `seed`, the adapted step size `step_size_adaptation`, the inverse metric +#' `inv_metric` (an array, or an array of rows for a dense metric), the +#' `time` in seconds, and each other value that differs between the chains +#' (for example `profile_file`). For the `fixed_param` sampler, +#' `variables` and `sampler_diagnostics` do not list the columns `lp__` and +#' `accept_stat__`. Use the Parquet schema to get all column names. The CSV +#' values `true` and `false` are JSON booleans, and the values `NaN`, +#' `Inf`, `-Inf` and `NA` are the JSON strings `"NaN"`, `"Inf"`, `"-Inf"` +#' and `"NA"`. +#' +#' Read the metadata with [nanoparquet::read_parquet_metadata()] and +#' [jsonlite::fromJSON()]. +#' +#' Only output of the MCMC sampler (`$sample()`) is supported. All CSV +#' files must come from the same model and the same sampler arguments, as in +#' [read_cmdstan_csv()]. The function warns if a chain has a different number +#' of draws than the sampler arguments give, for example a chain that stopped +#' early. +#' +#' @seealso [read_cmdstan_parquet()], [read_cmdstan_csv()], +#' [`$output_files()`][fit-method-output_files] +#' +#' @examples +#' \dontrun{ +#' fit <- cmdstanr_example("logistic", save_warmup = TRUE) +#' pq_file <- file.path(tempdir(), "logistic.parquet") +#' cmdstan_csv_to_parquet(fit$output_files(), pq_file) +#' +#' # all draws +#' draws <- posterior::as_draws_df(nanoparquet::read_parquet(pq_file)) +#' +#' # only some variables +#' draws_beta <- posterior::as_draws_df(nanoparquet::read_parquet( +#' pq_file, +#' col_select = c("beta[1]", "beta[2]", ".chain", ".iteration", ".draw") +#' )) +#' +#' # metadata +#' pq_metadata <- nanoparquet::read_parquet_metadata(pq_file) +#' kv <- pq_metadata$file_meta_data$key_value_metadata[[1]] +#' metadata <- jsonlite::fromJSON(kv$value[kv$key == "stan.metadata"]) +#' metadata$chains$step_size_adaptation +#' } +#' +cmdstan_csv_to_parquet <- function( + files, + file, + warmup_file = NULL, + chunk_rows = NULL, + compression = c("zstd", "snappy", "gzip", "uncompressed"), + overwrite = FALSE +) { + require_suggested_package("nanoparquet") + checkmate::assert_character(files, min.len = 1, any.missing = FALSE) + checkmate::assert_string(file) + checkmate::assert_string(warmup_file, null.ok = TRUE) + checkmate::assert_count(chunk_rows, positive = TRUE, null.ok = TRUE) + checkmate::assert_flag(overwrite) + compression <- match.arg(compression) + out_files <- c(file, warmup_file) + # normalizePath() changes only paths that exist, so normalize the directories + out_paths <- file.path( + normalizePath(dirname(out_files), mustWork = FALSE), + basename(out_files) + ) + if (anyDuplicated(out_paths)) { + stop("'file' and 'warmup_file' must be different paths.", call. = FALSE) + } + if (!overwrite && any(file.exists(out_files))) { + stop( + "Output file already exists: ", + paste(out_files[file.exists(out_files)], collapse = ", "), + ". Use 'overwrite = TRUE' to replace it.", + call. = FALSE + ) + } + temp_dir <- withr::local_tempdir() + withr::local_path(toolchain_PATH_env_var()) + files <- prepare_csv_files(files, temp_dir) + csv_metadata <- lapply(files, read_csv_metadata) + if (length(files) > 1) { + check_csv_metadata_matches(csv_metadata) + } + metadata <- csv_metadata[[1]] + if (metadata$method != "sample") { + stop( + "Only CSV files from the MCMC sampler are supported, not method '", + metadata$method, + "'.", + call. = FALSE + ) + } + # the fixed_param sampler writes no warmup draws + n_warmup <- 0 + if ( + isTRUE(metadata$save_warmup == 1) && + !isTRUE(metadata$algorithm == "fixed_param") + ) { + n_warmup <- ceiling(metadata$iter_warmup / metadata$thin) + } + n_post_warmup <- ceiling(metadata$iter_sampling / metadata$thin) + if (is.null(chunk_rows)) { + n_columns <- length(metadata$variables) + + length(metadata$sampler_diagnostics) + chunk_rows <- ceiling(1e7 / max(1, n_columns)) + } + # readLines() allocates a vector of length chunk_rows, so limit chunk_rows + # to about the number of lines in a file (draws, header and comments) + chunk_rows <- max(1, min(chunk_rows, n_warmup + n_post_warmup + 10000)) + + key_value <- c( + stan.format_version = "1", + stan.metadata = parquet_stan_metadata(csv_metadata) + ) + pq_options <- nanoparquet::parquet_options(keep_row_groups = TRUE) + write_chunk <- function(x, path) { + if (file.exists(path)) { + nanoparquet::append_parquet( + x, + path, + compression = compression, + options = pq_options + ) + } else { + draws_kind <- if (identical(path, tmp_warmup)) "warmup" else "sampling" + nanoparquet::write_parquet( + x, + path, + compression = compression, + metadata = c(key_value, stan.draws = draws_kind), + options = pq_options + ) + } + } + add_index_columns <- function(x, chain, iteration, draw) { + x$.chain <- rep(as.integer(chain), nrow(x)) + x$.iteration <- as.integer(iteration) + x$.draw <- as.integer(draw) + x + } + + # write to temporary files next to the output files, then rename them + tmp_file <- tempfile(".tmp_", tmpdir = dirname(file), fileext = ".parquet") + tmp_warmup <- NULL + if (!is.null(warmup_file)) { + tmp_warmup <- tempfile( + ".tmp_", + tmpdir = dirname(warmup_file), + fileext = ".parquet" + ) + } + on.exit(unlink(c(tmp_file, tmp_warmup)), add = TRUE) + + state <- new.env(parent = emptyenv()) + state$csv_names <- NULL + state$num_draws <- 0 + state$num_warmup_draws <- 0 + for (i in seq_along(files)) { + state$row <- 0 + write_lines <- function(lines, header) { + if (is.null(state$csv_names)) { + state$csv_names <- header + state$out_names <- repair_variable_names(header) + } else if (!identical(header, state$csv_names)) { + stop( + "The CSV header of '", + files[i], + "' differs from the first file.", + call. = FALSE + ) + } + chunk <- parse_csv_lines(lines, state$out_names, files[i], state$row) + rows <- state$row + seq_len(nrow(chunk)) + state$row <- state$row + nrow(chunk) + is_warmup <- rows <= n_warmup + if (any(is_warmup) && !is.null(tmp_warmup)) { + w <- chunk[is_warmup, , drop = FALSE] + draws <- state$num_warmup_draws + seq_len(nrow(w)) + state$num_warmup_draws <- state$num_warmup_draws + nrow(w) + write_chunk(add_index_columns(w, i, rows[is_warmup], draws), tmp_warmup) + } + if (!all(is_warmup)) { + p <- chunk[!is_warmup, , drop = FALSE] + draws <- state$num_draws + seq_len(nrow(p)) + state$num_draws <- state$num_draws + nrow(p) + write_chunk( + add_index_columns(p, i, rows[!is_warmup] - n_warmup, draws), + tmp_file + ) + } + } + header <- for_each_csv_chunk(files[i], chunk_rows, write_lines) + if (!identical(header, state$csv_names)) { + # a file without draws: check the header here + if (is.null(state$csv_names)) { + state$csv_names <- header + state$out_names <- repair_variable_names(header) + } else { + stop( + "The CSV header of '", + files[i], + "' differs from the first file.", + call. = FALSE + ) + } + } + if (state$row != n_warmup + n_post_warmup) { + warning( + "Chain ", + i, + " ('", + files[i], + "') has ", + state$row, + " draws, but the ", + "sampler arguments give ", + n_warmup + n_post_warmup, + ".", + call. = FALSE + ) + } + } + # an output file without draws still gets the columns and the metadata + empty <- as.data.frame( + stats::setNames( + rep(list(double()), length(state$out_names)), + state$out_names + ), + check.names = FALSE + ) + empty <- add_index_columns(empty, integer(), integer(), integer()) + for (path in c(tmp_file, tmp_warmup)) { + if (!file.exists(path)) { + write_chunk(empty, path) + } + } + if (!file.rename(tmp_file, file)) { + stop("Could not write '", file, "'.", call. = FALSE) + } + if (!is.null(warmup_file) && !file.rename(tmp_warmup, warmup_file)) { + stop("Could not write '", warmup_file, "'.", call. = FALSE) + } + invisible(file) +} + +#' Call a function for each chunk of data lines of a CmdStan CSV file. +#' +#' @noRd +#' @param path Path to an uncompressed CmdStan CSV file. +#' @param chunk_rows The number of lines to read at a time. +#' @param fun A function with arguments `lines` (the data lines of a chunk, +#' without comments and empty lines) and `header` (the column names). +#' @return The column names from the CSV header. +#' +for_each_csv_chunk <- function(path, chunk_rows, fun) { + con <- base::file(path, open = "r") + on.exit(close(con), add = TRUE) + header <- NULL + repeat { + lines <- readLines(con, n = chunk_rows) + if (length(lines) == 0) { + break + } + lines <- lines[nzchar(lines) & !startsWith(lines, "#")] + if (is.null(header) && length(lines) > 0) { + header <- strsplit(lines[1], ",", fixed = TRUE)[[1]] + lines <- lines[-1] + } + if (length(lines) > 0) { + fun(lines, header) + } + } + if (is.null(header)) { + stop("No CSV header found in '", path, "'.", call. = FALSE) + } + header +} + +#' Parse data lines of a CmdStan CSV file into a data frame of doubles. +#' +#' @noRd +#' @param lines Data lines, without comments and the header. +#' @param col_names The column names. +#' @param path The CSV file, for error messages. +#' @param rows_before The number of data rows of the file before `lines`. +#' @return A data frame with one row for each line. +#' +parse_csv_lines <- function(lines, col_names, path, rows_before) { + chunk <- tryCatch( + suppressWarnings(data.table::fread( + text = lines, + header = FALSE, + sep = ",", + col.names = col_names, + colClasses = rep("double", length(col_names)), + data.table = FALSE, + showProgress = FALSE + )), + error = function(e) e + ) + if ( + inherits(chunk, "error") || + nrow(chunk) != length(lines) || + !all(vapply(chunk, is.double, logical(1))) + ) { + stop( + "Malformed data line in '", + path, + "' between data rows ", + rows_before + 1, + " and ", + rows_before + length(lines), + ".", + if (inherits(chunk, "error")) paste0(" ", conditionMessage(chunk)), + call. = FALSE + ) + } + chunk +} + +#' Make the JSON metadata of a Parquet file from CmdStan CSV metadata. +#' +#' @noRd +#' @param csv_metadata A list with one element of `read_csv_metadata()` +#' output for each chain. +#' @return A JSON string. +#' +parquet_stan_metadata <- function(csv_metadata) { + metadata <- csv_metadata[[1]] + # also store per chain every field that differs between the chains, for + # example profile_file + all_names <- unique(unlist(lapply(csv_metadata, names))) + differs <- vapply( + all_names, + function(name) { + !all(vapply( + csv_metadata, + function(x) identical(x[[name]], metadata[[name]]), + logical(1) + )) + }, + logical(1) + ) + per_chain <- union(parquet_per_chain_fields, all_names[differs]) + # read_csv_metadata() turns the CSV values true and false into integers; + # write them as JSON booleans + flags_to_logical <- function(x) { + is_flag <- vapply( + x, + function(value) is.integer(value) && length(value) == 1, + logical(1) + ) + x[is_flag] <- lapply(x[is_flag], as.logical) + x + } + out <- flags_to_logical(metadata[setdiff(names(metadata), per_chain)]) + # I() keeps vectors of length 1 as JSON arrays + variables <- repair_variable_names(metadata$variables) + out$variables <- I(variables) + out$sampler_diagnostics <- I(as.character(metadata$sampler_diagnostics)) + out$stan_variable_sizes <- lapply(variable_dims(variables), I) + if (length(out$stan_variable_sizes) == 0) { + # a named empty list gives a JSON object, not an array + out$stan_variable_sizes <- stats::setNames(list(), character()) + } + out$num_chains <- length(csv_metadata) + out$chains <- lapply(csv_metadata, function(x) { + chain <- flags_to_logical(x[intersect(per_chain, names(x))]) + if (!is.null(chain$inv_metric) && is.null(dim(chain$inv_metric))) { + chain$inv_metric <- I(chain$inv_metric) + } + if (is.data.frame(chain$time)) { + chain$time <- as.list(chain$time) + } + chain + }) + # 17 significant digits keep the doubles exact; NaN, Inf, -Inf and NA are + # JSON strings + as.character(jsonlite::toJSON( + out, + auto_unbox = TRUE, + digits = I(17), + null = "null", + na = "string" + )) +} + +# the metadata fields that can differ between chains +parquet_per_chain_fields <- c( + "id", + "seed", + "init", + "step_size", + "step_size_adaptation", + "fitted_params", + "inv_metric", + "time" +) + +#' Read CmdStan output from a Parquet file +#' +#' Read the draws and the metadata from a Parquet file that +#' [cmdstan_csv_to_parquet()] wrote. The result is the same as the result of +#' [read_cmdstan_csv()] for the CSV files of the MCMC sampler. To make a fitted +#' model object from a Parquet file, use [as_cmdstan_fit()]. +#' +#' @export +#' @inheritParams read_cmdstan_csv +#' @param file (string) Path of a Parquet file from [cmdstan_csv_to_parquet()]. +#' @param warmup_file (string) Optional path of the Parquet file of the warmup +#' draws (the `warmup_file` of [cmdstan_csv_to_parquet()]), from the same +#' run as `file`. The default is `NULL`, which reads no warmup draws. +#' +#' @return A named list with the same elements as [read_cmdstan_csv()] gives +#' for the MCMC sampler: `metadata`, `time`, `inv_metric`, `step_size`, +#' `warmup_draws`, `post_warmup_draws`, `warmup_sampler_diagnostics` and +#' `post_warmup_sampler_diagnostics`. The values are the same; the fields of +#' `metadata` can be in a different order. Without `warmup_file`, the +#' warmup elements are `NULL` also if `metadata$save_warmup` is 1. +#' +#' @details +#' This function requires the \pkg{nanoparquet} package. It reads only the +#' columns of the requested variables and sampler diagnostics. As in +#' [read_cmdstan_csv()], the draws contain `lp__` and the model variables, and +#' the sampler diagnostics are separate. +#' +#' @seealso [cmdstan_csv_to_parquet()], [read_cmdstan_csv()], +#' [as_cmdstan_fit()] +#' +#' @examples +#' \dontrun{ +#' fit <- cmdstanr_example("logistic", save_warmup = TRUE) +#' pq_file <- file.path(tempdir(), "logistic.parquet") +#' pq_warmup <- file.path(tempdir(), "logistic_warmup.parquet") +#' cmdstan_csv_to_parquet(fit$output_files(), pq_file, warmup_file = pq_warmup) +#' +#' x <- read_cmdstan_parquet( +#' pq_file, +#' variables = "beta", +#' warmup_file = pq_warmup +#' ) +#' str(x$post_warmup_draws) +#' str(x$post_warmup_sampler_diagnostics) +#' +#' # a fitted model object +#' fit2 <- as_cmdstan_fit(pq_file, warmup_file = pq_warmup) +#' fit2$summary() +#' } +#' +read_cmdstan_parquet <- function( + file, + variables = NULL, + sampler_diagnostics = NULL, + format = getOption("cmdstanr_draws_format", NULL), + warmup_file = NULL +) { + require_suggested_package("nanoparquet") + checkmate::assert_string(file) + checkmate::assert_file_exists(file, access = "r") + checkmate::assert_string(warmup_file, null.ok = TRUE) + format <- assert_valid_draws_format(format) + key_value <- parquet_key_value(file, "sampling") + if (!is.null(warmup_file)) { + checkmate::assert_file_exists(warmup_file, access = "r") + warmup_key_value <- parquet_key_value(warmup_file, "warmup") + if (!identical(warmup_key_value$metadata, key_value$metadata)) { + stop( + "'", + warmup_file, + "' and '", + file, + "' are not from the same run.", + call. = FALSE + ) + } + } + csv_metadata <- parquet_csv_metadata(key_value$metadata) + merged <- merge_csv_metadata(csv_metadata) + metadata <- merged$metadata + if (metadata$method != "sample") { + stop( + "Only output of the MCMC sampler is supported, not method '", + metadata$method, + "'.", + call. = FALSE + ) + } + selected <- select_csv_columns(metadata, variables, sampler_diagnostics) + variables <- repair_variable_names(selected$variables) + sampler_diagnostics <- selected$sampler_diagnostics + post_warmup <- read_parquet_chains( + file, + variables, + sampler_diagnostics, + metadata$num_chains + ) + warmup <- list() + if (!is.null(warmup_file) && isTRUE(metadata$save_warmup == 1)) { + warmup <- read_parquet_chains( + warmup_file, + variables, + sampler_diagnostics, + metadata$num_chains + ) + } + metadata$inv_metric <- NULL + metadata$variables <- repair_variable_names(metadata$variables) + metadata <- add_variable_metadata(metadata) + if (is.null(format)) { + format <- "draws_array" + } + as_draws_format <- as_draws_format_fun(format) + as_draws_or_null <- function(x) if (length(x) > 0) as_draws_format(x) + list( + metadata = metadata, + time = list(total = NA_integer_, chains = merged$time), + inv_metric = merged$inv_metric, + step_size = merged$step_size, + warmup_draws = as_draws_or_null(warmup$draws), + post_warmup_draws = as_draws_or_null(post_warmup$draws), + warmup_sampler_diagnostics = as_draws_or_null(warmup$sampler_diagnostics), + post_warmup_sampler_diagnostics = as_draws_or_null( + post_warmup$sampler_diagnostics + ) + ) +} + +#' Read and check the key-value metadata of a Parquet file. +#' +#' @noRd +#' @param file A Parquet file from `cmdstan_csv_to_parquet()`. +#' @param draws `"sampling"` or `"warmup"`, the expected `stan.draws` value. +#' @return A list with the JSON text `metadata`. +#' +parquet_key_value <- function(file, draws) { + kv <- nanoparquet::read_parquet_metadata( + file + )$file_meta_data$key_value_metadata[[1]] + value <- function(key) kv$value[kv$key == key] + if (!identical(value("stan.format_version"), "1")) { + stop( + "'", + file, + "' has no CmdStan metadata of format version 1. ", + "Use a file from cmdstan_csv_to_parquet().", + call. = FALSE + ) + } + if (length(value("stan.draws")) == 0) { + stop( + "'", + file, + "' has no 'stan.draws' key. ", + "Write it again with cmdstan_csv_to_parquet().", + call. = FALSE + ) + } + if (!identical(value("stan.draws"), draws)) { + stop( + "'", + file, + "' does not have the ", + draws, + " draws.", + call. = FALSE + ) + } + list(metadata = value("stan.metadata")) +} + +#' Rebuild the per-chain CSV metadata from the JSON of a Parquet file. +#' +#' @noRd +#' @param json The `stan.metadata` JSON text of a Parquet file. +#' @return A list with one element for each chain, in the form of +#' `read_csv_metadata()` output, with the CSV variable names. +#' +parquet_csv_metadata <- function(json) { + json <- jsonlite::fromJSON(json, simplifyVector = FALSE) + # merge_csv_metadata() sets num_chains, and add_variable_metadata() sets + # the variable sizes + shared <- json[setdiff( + names(json), + c("chains", "num_chains", "stan_variable_sizes") + )] + shared <- lapply(shared, parquet_json_to_r) + # names are always strings, also a name such as "NA"; the JSON has the + # repaired names, and read_csv_metadata() gives the CSV names + names_of <- function(x) if (length(x) > 0) as.character(unlist(x)) + shared$variables <- unrepair_variable_names(names_of(json$variables)) + shared$sampler_diagnostics <- names_of(json$sampler_diagnostics) + shared <- parquet_drop_null(shared) + lapply(json$chains, function(chain) { + chain <- parquet_drop_null(lapply(chain, parquet_json_to_r)) + if (!is.null(chain$time)) { + chain$time <- as.data.frame(chain$time) + } + c(shared, chain) + }) +} + +parquet_drop_null <- function(x) { + x[!vapply(x, is.null, logical(1))] +} + +# the JSON strings of the doubles NA, NaN, Inf and -Inf +parquet_json_special <- c("NA", "NaN", "Inf", "-Inf") + +#' Convert a value of `jsonlite::fromJSON(simplifyVector = FALSE)` to the +#' types of `read_csv_metadata()`. +#' +#' @noRd +#' @param x A parsed JSON value. +#' @return Numbers (also the strings `"NA"`, `"NaN"`, `"Inf"` and `"-Inf"`) +#' as doubles, booleans as integers 0 and 1, arrays as vectors, arrays of +#' arrays as matrices (rows), objects as named lists. +#' +parquet_json_to_r <- function(x) { + is_number <- function(e) { + is.numeric(e) || (is.character(e) && e %in% parquet_json_special) + } + to_numbers <- function(values) { + vapply( + values, + function(e) suppressWarnings(as.numeric(e)), + double(1), + USE.NAMES = FALSE + ) + } + if (is.null(x)) { + return(NULL) + } + if (is.character(x)) { + if (x %in% parquet_json_special) { + return(to_numbers(list(x))) + } + return(x) + } + if (is.logical(x)) { + return(as.integer(x)) + } + if (is.numeric(x)) { + return(as.numeric(x)) + } + if (!is.null(names(x))) { + return(lapply(x, parquet_json_to_r)) + } + if (length(x) == 0) { + return(NULL) + } + if (all(vapply(x, is.list, logical(1)))) { + return(do.call(rbind, lapply(x, to_numbers))) + } + if (all(vapply(x, is_number, logical(1)))) { + return(to_numbers(x)) + } + values <- unlist(x) + if (is.logical(values)) as.integer(values) else values +} + +#' Read columns of a Parquet file into arrays of iterations, chains and +#' variables. +#' +#' @noRd +#' @param path A Parquet file from `cmdstan_csv_to_parquet()`. +#' @param variables The repaired names of the variable columns. +#' @param sampler_diagnostics The names of the sampler diagnostic columns. +#' @param num_chains The number of chains. +#' @return A list with the arrays `draws` and `sampler_diagnostics`; an +#' empty list if the file has no rows or no columns are requested. +#' +read_parquet_chains <- function( + path, + variables, + sampler_diagnostics, + num_chains +) { + columns <- c(variables, sampler_diagnostics) + if (length(columns) == 0) { + return(list()) + } + pq <- as.list(nanoparquet::read_parquet( + path, + col_select = c(columns, ".chain", ".iteration") + )) + if (length(pq$.chain) == 0) { + return(list()) + } + row_order <- order(pq$.chain, pq$.iteration) + if (!is.unsorted(row_order)) { + row_order <- NULL + } + n_rows <- tabulate(pq$.chain, nbins = num_chains) + if (sum(n_rows) != length(pq$.chain) || any(n_rows != n_rows[1])) { + stop( + "The chains in '", + path, + "' have different numbers of draws.", + call. = FALSE + ) + } + pq$.chain <- NULL + pq$.iteration <- NULL + # copy one column at a time into the array and free it + to_array <- function(names) { + if (length(names) == 0) { + return(NULL) + } + out <- array( + NA_real_, + c(n_rows[1], num_chains, length(names)), + dimnames = list(NULL, NULL, names) + ) + for (j in seq_along(names)) { + column <- pq[[names[j]]] + out[,, j] <- if (is.null(row_order)) column else column[row_order] + pq[[names[j]]] <<- NULL + } + out + } + list( + draws = to_array(variables), + sampler_diagnostics = to_array(sampler_diagnostics) + ) +} + +#' A fitted model object made from a Parquet file +#' +#' Like `CmdStanMCMC_CSV`, but it reads further variables from the Parquet +#' file. +#' +#' @noRd +#' +CmdStanMCMC_Parquet <- R6::R6Class( + classname = "CmdStanMCMC_Parquet", + inherit = CmdStanMCMC_CSV, + public = list( + initialize = function( + contents, + file, + warmup_file = NULL, + check_diagnostics = TRUE + ) { + private$warmup_file_ <- warmup_file + super$initialize(contents, file, check_diagnostics) + }, + num_chains = function() { + private$metadata_$num_chains + }, + draws = function( + variables = NULL, + inc_warmup = FALSE, + format = getOption("cmdstanr_draws_format", "draws_array") + ) { + private$check_warmup_file_(inc_warmup) + super$draws( + variables = variables, + inc_warmup = inc_warmup, + format = format + ) + }, + sampler_diagnostics = function( + inc_warmup = FALSE, + format = getOption("cmdstanr_draws_format", "draws_array") + ) { + private$check_warmup_file_(inc_warmup) + super$sampler_diagnostics(inc_warmup = inc_warmup, format = format) + } + ), + private = list( + warmup_file_ = NULL, + check_warmup_file_ = function(inc_warmup) { + if ( + inc_warmup && + is.null(private$warmup_file_) && + isTRUE(private$metadata_$save_warmup == 1) + ) { + stop( + "The warmup draws are in a separate Parquet file. ", + "Give it as 'warmup_file' to as_cmdstan_fit().", + call. = FALSE + ) + } + }, + read_output_ = function(variables, sampler_diagnostics, format) { + read_cmdstan_parquet( + private$output_files_, + variables = variables, + sampler_diagnostics = sampler_diagnostics, + format = format, + warmup_file = private$warmup_file_ + ) + } + ) +) diff --git a/_pkgdown.yml b/_pkgdown.yml index f0806aab8..e534bbceb 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -68,6 +68,8 @@ reference: - write_stan_file - print_stan_file - draws_to_csv + - cmdstan_csv_to_parquet + - read_cmdstan_parquet - as_mcmc.list - as_draws.CmdStanMCMC - cmdstan_coercion diff --git a/man/cmdstan_csv_to_parquet.Rd b/man/cmdstan_csv_to_parquet.Rd new file mode 100644 index 000000000..0b68e6c50 --- /dev/null +++ b/man/cmdstan_csv_to_parquet.Rd @@ -0,0 +1,138 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/parquet.R +\name{cmdstan_csv_to_parquet} +\alias{cmdstan_csv_to_parquet} +\title{Convert CmdStan CSV files to a Parquet file} +\usage{ +cmdstan_csv_to_parquet( + files, + file, + warmup_file = NULL, + chunk_rows = NULL, + compression = c("zstd", "snappy", "gzip", "uncompressed"), + overwrite = FALSE +) +} +\arguments{ +\item{files}{(character vector) Paths to CmdStan CSV files from +\verb{$sample()}, one file per chain. Files compressed with gzip (\code{.csv.gz}) +or bzip2 (\code{.csv.bz2}) are first decompressed to a temporary directory.} + +\item{file}{(string) Path of the Parquet file for the post-warmup draws.} + +\item{warmup_file}{(string) Optional path of a second Parquet file for the +warmup draws. If the CSV files do not contain warmup draws, this file has +the columns but no rows. The default is \code{NULL}, which drops the warmup +draws.} + +\item{chunk_rows}{(positive integer) The number of CSV lines to read at a +time. Each chunk is written as new Parquet row groups; nanoparquet splits +a chunk with more rows than its \code{num_rows_per_row_group} option. The +default is \code{NULL}, which selects about 10 million values for each chunk.} + +\item{compression}{(string) The compression of the Parquet files. One of +\code{"zstd"} (the default), \code{"snappy"}, \code{"gzip"} or \code{"uncompressed"}.} + +\item{overwrite}{(logical) Replace existing output files? The default is +\code{FALSE}.} +} +\value{ +The path of the Parquet file of the post-warmup draws, invisibly. +} +\description{ +Convert the CSV output files of the CmdStan MCMC sampler to one Parquet +file, without reading all draws into memory. The Parquet file contains the +columns of a \code{\link[posterior:draws_df]{draws_df}} object, and the CmdStan +metadata. +} +\details{ +This function requires the \pkg{nanoparquet} package. It reads each CSV +file in chunks of \code{chunk_rows} lines and appends each chunk to the Parquet +file. + +The memory use grows with \code{chunk_rows} times the number of columns. It does +not grow with the number of chunks, with one exception: each append reads +and writes the Parquet footer, which grows with the number of row groups +times the number of columns. For output with very many columns, use a large +\code{chunk_rows} if the memory allows it. + +The Parquet file has the following columns: +\itemize{ +\item all columns of the CSV files (\code{lp__}, the sampler diagnostics, and the +model variables), as doubles. The names use the \code{beta[1,2]} form, as in +\verb{$draws()}. +\item the integer columns \code{.chain}, \code{.iteration} and \code{.draw}, as in a +\code{\link[posterior:draws_df]{draws_df}} object. \code{.chain} is the position of the +file in \code{files}. \code{.iteration} starts from 1 in each chain. \code{.draw} +numbers the draws of all chains consecutively. +} + +\code{\link[=read_cmdstan_parquet]{read_cmdstan_parquet()}} reads the file into the same structure as +\code{\link[=read_cmdstan_csv]{read_cmdstan_csv()}}, with the draws (\code{lp__} and the model variables) and +the sampler diagnostics separate. \code{\link[=as_cmdstan_fit]{as_cmdstan_fit()}} makes a fitted model +object from the file. + +\code{posterior::as_draws_df(nanoparquet::read_parquet(file))} gives all +columns in one data frame, and the \code{col_select} argument of +\code{\link[nanoparquet:read_parquet]{nanoparquet::read_parquet()}} +reads only some of the variables. Include \code{.chain}, \code{.iteration} and +\code{.draw} in \code{col_select} to keep the chain structure. Other Parquet +readers (for example \pkg{arrow}, \pkg{duckdb} and \pkg{polars}) can also +read the file. + +The key-value metadata of the Parquet file has three Stan entries: +\itemize{ +\item \code{stan.format_version}: the version of this file layout, now \code{"1"}. +\item \code{stan.draws}: \code{"sampling"} in \code{file} and \code{"warmup"} in \code{warmup_file}. +\item \code{stan.metadata}: the CmdStan metadata as a JSON object. It has the +values that \code{\link[=read_cmdstan_csv]{read_cmdstan_csv()}} reads from the CSV comments, for example +the CmdStan version and the sampler arguments, and \code{variables}, +\code{sampler_diagnostics}, \code{stan_variable_sizes} and \code{num_chains}. Element +\code{chains} is an array with one object for each chain: the chain \code{id}, the +\code{seed}, the adapted step size \code{step_size_adaptation}, the inverse metric +\code{inv_metric} (an array, or an array of rows for a dense metric), the +\code{time} in seconds, and each other value that differs between the chains +(for example \code{profile_file}). For the \code{fixed_param} sampler, +\code{variables} and \code{sampler_diagnostics} do not list the columns \code{lp__} and +\code{accept_stat__}. Use the Parquet schema to get all column names. The CSV +values \code{true} and \code{false} are JSON booleans, and the values \code{NaN}, +\code{Inf}, \code{-Inf} and \code{NA} are the JSON strings \code{"NaN"}, \code{"Inf"}, \code{"-Inf"} +and \code{"NA"}. +} + +Read the metadata with \code{\link[nanoparquet:read_parquet_metadata]{nanoparquet::read_parquet_metadata()}} and +\code{\link[jsonlite:fromJSON]{jsonlite::fromJSON()}}. + +Only output of the MCMC sampler (\verb{$sample()}) is supported. All CSV +files must come from the same model and the same sampler arguments, as in +\code{\link[=read_cmdstan_csv]{read_cmdstan_csv()}}. The function warns if a chain has a different number +of draws than the sampler arguments give, for example a chain that stopped +early. +} +\examples{ +\dontrun{ +fit <- cmdstanr_example("logistic", save_warmup = TRUE) +pq_file <- file.path(tempdir(), "logistic.parquet") +cmdstan_csv_to_parquet(fit$output_files(), pq_file) + +# all draws +draws <- posterior::as_draws_df(nanoparquet::read_parquet(pq_file)) + +# only some variables +draws_beta <- posterior::as_draws_df(nanoparquet::read_parquet( + pq_file, + col_select = c("beta[1]", "beta[2]", ".chain", ".iteration", ".draw") +)) + +# metadata +pq_metadata <- nanoparquet::read_parquet_metadata(pq_file) +kv <- pq_metadata$file_meta_data$key_value_metadata[[1]] +metadata <- jsonlite::fromJSON(kv$value[kv$key == "stan.metadata"]) +metadata$chains$step_size_adaptation +} + +} +\seealso{ +\code{\link[=read_cmdstan_parquet]{read_cmdstan_parquet()}}, \code{\link[=read_cmdstan_csv]{read_cmdstan_csv()}}, +\code{\link[=fit-method-output_files]{$output_files()}} +} diff --git a/man/read_cmdstan_csv.Rd b/man/read_cmdstan_csv.Rd index eb41926e8..0c6741d0e 100644 --- a/man/read_cmdstan_csv.Rd +++ b/man/read_cmdstan_csv.Rd @@ -16,7 +16,8 @@ as_cmdstan_fit( files, variables = NULL, check_diagnostics = TRUE, - format = getOption("cmdstanr_draws_format") + format = getOption("cmdstanr_draws_format"), + warmup_file = NULL ) } \arguments{ @@ -55,6 +56,9 @@ and memory for models with many parameters.} diagnostic checks be performed after reading in the files? The default is \code{TRUE} but set to \code{FALSE} to avoid checking for problems with divergences and treedepth.} + +\item{warmup_file}{(string) For a Parquet file in \code{files}, the optional +Parquet file of the warmup draws. See \code{\link[=read_cmdstan_parquet]{read_cmdstan_parquet()}}.} } \value{ \code{as_cmdstan_fit()} returns a fitted model object (\link{CmdStanMCMC}, \link{CmdStanVB}, @@ -163,6 +167,14 @@ files do not record whether the chains ran in parallel. All other fitted-model methods are unavailable because they require information not contained in the CSV files. Calling an unavailable method produces an informative error. + +\code{as_cmdstan_fit()} also accepts one Parquet file from +\code{\link[=cmdstan_csv_to_parquet]{cmdstan_csv_to_parquet()}} (MCMC output only), with an optional +\code{warmup_file}. The object then reads the draws with +\code{\link[=read_cmdstan_parquet]{read_cmdstan_parquet()}}, and it has the same methods as an object made +from the CSV files. \verb{$output_files()} gives the Parquet file, and +\verb{$num_chains()} and \verb{$time()} come from the metadata in the file. Without +\code{warmup_file}, \verb{$draws(inc_warmup = TRUE)} gives an error. } \examples{ diff --git a/man/read_cmdstan_parquet.Rd b/man/read_cmdstan_parquet.Rd new file mode 100644 index 000000000..13f6adf12 --- /dev/null +++ b/man/read_cmdstan_parquet.Rd @@ -0,0 +1,87 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/parquet.R +\name{read_cmdstan_parquet} +\alias{read_cmdstan_parquet} +\title{Read CmdStan output from a Parquet file} +\usage{ +read_cmdstan_parquet( + file, + variables = NULL, + sampler_diagnostics = NULL, + format = getOption("cmdstanr_draws_format", NULL), + warmup_file = NULL +) +} +\arguments{ +\item{file}{(string) Path of a Parquet file from \code{\link[=cmdstan_csv_to_parquet]{cmdstan_csv_to_parquet()}}.} + +\item{variables}{(character vector) Optionally, the names of the variables +(parameters, transformed parameters, and generated quantities) to read in. +\itemize{ +\item If \code{NULL} (the default) then all variables are included. +\item If an empty string (\code{variables=""}) then none are included. +\item For non-scalar variables all elements or specific elements can be selected: +\itemize{ +\item \code{variables = "theta"} selects all elements of \code{theta}; +\item \code{variables = c("theta[1]", "theta[3]")} selects only the 1st and 3rd elements. +} +}} + +\item{sampler_diagnostics}{(character vector) Works the same way as +\code{variables} but for sampler diagnostic variables (e.g., \code{"treedepth__"}, +\code{"accept_stat__"}, etc.). Ignored if the model was not fit using MCMC.} + +\item{format}{(string) The format for storing the draws or point estimates. +The default depends on the method used to fit the model. See +\link[=fit-method-draws]{draws} for details, in particular the note about speed +and memory for models with many parameters.} + +\item{warmup_file}{(string) Optional path of the Parquet file of the warmup +draws (the \code{warmup_file} of \code{\link[=cmdstan_csv_to_parquet]{cmdstan_csv_to_parquet()}}), from the same +run as \code{file}. The default is \code{NULL}, which reads no warmup draws.} +} +\value{ +A named list with the same elements as \code{\link[=read_cmdstan_csv]{read_cmdstan_csv()}} gives +for the MCMC sampler: \code{metadata}, \code{time}, \code{inv_metric}, \code{step_size}, +\code{warmup_draws}, \code{post_warmup_draws}, \code{warmup_sampler_diagnostics} and +\code{post_warmup_sampler_diagnostics}. The values are the same; the fields of +\code{metadata} can be in a different order. Without \code{warmup_file}, the +warmup elements are \code{NULL} also if \code{metadata$save_warmup} is 1. +} +\description{ +Read the draws and the metadata from a Parquet file that +\code{\link[=cmdstan_csv_to_parquet]{cmdstan_csv_to_parquet()}} wrote. The result is the same as the result of +\code{\link[=read_cmdstan_csv]{read_cmdstan_csv()}} for the CSV files of the MCMC sampler. To make a fitted +model object from a Parquet file, use \code{\link[=as_cmdstan_fit]{as_cmdstan_fit()}}. +} +\details{ +This function requires the \pkg{nanoparquet} package. It reads only the +columns of the requested variables and sampler diagnostics. As in +\code{\link[=read_cmdstan_csv]{read_cmdstan_csv()}}, the draws contain \code{lp__} and the model variables, and +the sampler diagnostics are separate. +} +\examples{ +\dontrun{ +fit <- cmdstanr_example("logistic", save_warmup = TRUE) +pq_file <- file.path(tempdir(), "logistic.parquet") +pq_warmup <- file.path(tempdir(), "logistic_warmup.parquet") +cmdstan_csv_to_parquet(fit$output_files(), pq_file, warmup_file = pq_warmup) + +x <- read_cmdstan_parquet( + pq_file, + variables = "beta", + warmup_file = pq_warmup +) +str(x$post_warmup_draws) +str(x$post_warmup_sampler_diagnostics) + +# a fitted model object +fit2 <- as_cmdstan_fit(pq_file, warmup_file = pq_warmup) +fit2$summary() +} + +} +\seealso{ +\code{\link[=cmdstan_csv_to_parquet]{cmdstan_csv_to_parquet()}}, \code{\link[=read_cmdstan_csv]{read_cmdstan_csv()}}, +\code{\link[=as_cmdstan_fit]{as_cmdstan_fit()}} +} diff --git a/tests/testthat/test-parquet.R b/tests/testthat/test-parquet.R new file mode 100644 index 000000000..2ee4c6db0 --- /dev/null +++ b/tests/testthat/test-parquet.R @@ -0,0 +1,759 @@ +skip_if_not_installed("nanoparquet", minimum_version = "0.5.0") +set_cmdstan_path() + +fit_parquet <- testing_fit( + "logistic", + method = "sample", + seed = 123, + chains = 2, + iter_warmup = 100, + iter_sampling = 100, + thin = 3, + save_warmup = TRUE +) + +read_parquet_draws <- function(path) { + posterior::as_draws_df(as.data.frame(nanoparquet::read_parquet(path))) +} + +read_parquet_stan_metadata <- function(path) { + kv <- nanoparquet::read_parquet_metadata( + path + )$file_meta_data$key_value_metadata[[1]] + list( + format_version = kv$value[kv$key == "stan.format_version"], + metadata = jsonlite::fromJSON(kv$value[kv$key == "stan.metadata"]) + ) +} + +expect_same_draws <- function(object, expected) { + object <- posterior::subset_draws( + object, + variable = posterior::variables(expected) + ) + expect_equal( + as.data.frame(object), + as.data.frame(posterior::as_draws_df(expected)) + ) +} + +# compare with read_cmdstan_csv(); the order of the metadata fields differs +expect_same_contents <- function(object, expected) { + sort_metadata <- function(x) { + x$metadata <- x$metadata[sort(names(x$metadata))] + x + } + expect_equal(sort_metadata(object), sort_metadata(expected)) +} + +# copy CSV files to a temporary directory and change their lines with fun +edit_csv_files <- function( + files, + fun, + dir = withr::local_tempdir(.local_envir = parent.frame()) +) { + out <- file.path(dir, basename(files)) + for (i in seq_along(files)) { + writeLines(fun(readLines(files[i]), i), out[i]) + } + out +} + +data_line_index <- function(lines) { + which(nzchar(lines) & !startsWith(lines, "#"))[-1] +} + +test_that("cmdstan_csv_to_parquet() gives the draws of $draws()", { + out <- withr::local_tempfile(fileext = ".parquet") + out_warmup <- withr::local_tempfile(fileext = ".parquet") + # chunks of 7 lines cross the adaptation comments and the warmup end + expect_identical( + cmdstan_csv_to_parquet( + fit_parquet$output_files(), + out, + warmup_file = out_warmup, + chunk_rows = 7 + ), + out + ) + draws <- read_parquet_draws(out) + expect_identical(posterior::nchains(draws), 2L) + expect_identical(posterior::niterations(draws), 34L) + expect_same_draws(draws, fit_parquet$draws()) + expect_same_draws(draws, fit_parquet$sampler_diagnostics()) + + warmup <- read_parquet_draws(out_warmup) + all_draws <- fit_parquet$draws(inc_warmup = TRUE) + expect_identical(posterior::niterations(warmup), 34L) + expect_same_draws( + warmup, + posterior::subset_draws(all_draws, iteration = 1:34) + ) + + pq_names <- names(nanoparquet::read_parquet(out)) + expect_identical(utils::tail(pq_names, 3), c(".chain", ".iteration", ".draw")) + expect_identical(list.files(dirname(out), pattern = "^\\.tmp_"), character()) +}) + +test_that("cmdstan_csv_to_parquet() result does not depend on chunk_rows", { + out_default <- withr::local_tempfile(fileext = ".parquet") + out_one <- withr::local_tempfile(fileext = ".parquet") + warmup_default <- withr::local_tempfile(fileext = ".parquet") + warmup_one <- withr::local_tempfile(fileext = ".parquet") + files <- fit_parquet$output_files() + cmdstan_csv_to_parquet(files, out_default, warmup_file = warmup_default) + cmdstan_csv_to_parquet( + files, + out_one, + warmup_file = warmup_one, + chunk_rows = 1 + ) + expect_identical( + nanoparquet::read_parquet(out_one), + nanoparquet::read_parquet(out_default) + ) + expect_identical( + nanoparquet::read_parquet(warmup_one), + nanoparquet::read_parquet(warmup_default) + ) + # the default gives one row group for each chain + expect_identical( + nrow(nanoparquet::read_parquet_metadata(out_default)$row_groups), + 2L + ) +}) + +test_that("cmdstan_csv_to_parquet() stores the CmdStan metadata", { + out <- withr::local_tempfile(fileext = ".parquet") + cmdstan_csv_to_parquet(fit_parquet$output_files(), out) + m <- read_parquet_stan_metadata(out) + expect_identical(m$format_version, "1") + meta <- m$metadata + expect_identical(meta$method, "sample") + expect_identical(meta$num_chains, 2L) + expect_identical(meta$thin, 3L) + # the CSV values true and false are JSON booleans + expect_true(meta$save_warmup) + expect_true(meta$adapt_engaged) + expect_identical(meta$chains$id, 1:2) + expect_equal( + meta$chains$step_size_adaptation, + fit_parquet$metadata()$step_size_adaptation + ) + expect_equal( + meta$chains$inv_metric[[2]], + unname(fit_parquet$inv_metric(matrix = FALSE)[[2]]) + ) + expect_identical(meta$variables, fit_parquet$metadata()$variables) + expect_equal( + meta$stan_variable_sizes, + fit_parquet$metadata()$stan_variable_sizes + ) + expect_identical( + meta$sampler_diagnostics, + posterior::variables(fit_parquet$sampler_diagnostics()) + ) + expect_named(meta$chains$time, c("chain_id", "warmup", "sampling", "total")) +}) + +test_that("cmdstan_csv_to_parquet() stores a dense metric", { + fit <- testing_fit( + "logistic", + method = "sample", + seed = 123, + chains = 1, + iter_warmup = 300, + iter_sampling = 10, + metric = "dense_e" + ) + out <- withr::local_tempfile(fileext = ".parquet") + cmdstan_csv_to_parquet(fit$output_files(), out) + meta <- read_parquet_stan_metadata(out)$metadata + expect_identical(dim(meta$chains$inv_metric[[1]]), c(4L, 4L)) + expect_equal(meta$chains$inv_metric[[1]], unname(fit$inv_metric()[[1]])) + expect_same_contents( + read_cmdstan_parquet(out), + read_cmdstan_csv(fit$output_files()) + ) +}) + +test_that("cmdstan_csv_to_parquet() keeps one-element vectors as JSON arrays", { + fit <- testing_fit( + "bernoulli", + method = "sample", + seed = 123, + chains = 1, + iter_warmup = 100, + iter_sampling = 10 + ) + out <- withr::local_tempfile(fileext = ".parquet") + cmdstan_csv_to_parquet(fit$output_files(), out) + kv <- nanoparquet::read_parquet_metadata( + out + )$file_meta_data$key_value_metadata[[1]] + json <- kv$value[kv$key == "stan.metadata"] + expect_match( + json, + '"stan_variable_sizes":{"lp__":[1],"theta":[1]}', + fixed = TRUE + ) + expect_match(json, '"inv_metric":[', fixed = TRUE) +}) + +test_that("cmdstan_csv_to_parquet() reads compressed CSV files", { + csv_files <- fit_parquet$output_files() + gz_files <- file.path( + withr::local_tempdir(), + paste0(basename(csv_files), ".gz") + ) + for (i in seq_along(csv_files)) { + con <- gzfile(gz_files[i], "w") + writeLines(readLines(csv_files[i]), con) + close(con) + } + out_csv <- withr::local_tempfile(fileext = ".parquet") + out_gz <- withr::local_tempfile(fileext = ".parquet") + cmdstan_csv_to_parquet(csv_files, out_csv) + cmdstan_csv_to_parquet(gz_files, out_gz) + expect_identical( + nanoparquet::read_parquet(out_gz), + nanoparquet::read_parquet(out_csv) + ) +}) + +test_that("cmdstan_csv_to_parquet() reads bzip2 CSV files from $sample()", { + fit <- testing_fit( + "logistic", + method = "sample", + seed = 123, + chains = 2, + iter_warmup = 100, + iter_sampling = 100, + thin = 3, + save_warmup = TRUE, + compress = "bzip2" + ) + expect_match(fit$output_files(), "\\.csv\\.bz2$") + out_csv <- withr::local_tempfile(fileext = ".parquet") + out_bz2 <- withr::local_tempfile(fileext = ".parquet") + cmdstan_csv_to_parquet(fit_parquet$output_files(), out_csv) + cmdstan_csv_to_parquet(fit$output_files(), out_bz2) + expect_identical( + nanoparquet::read_parquet(out_bz2), + nanoparquet::read_parquet(out_csv) + ) +}) + +test_that("cmdstan_csv_to_parquet() names tuple and complex variables", { + stan_file <- write_stan_file( + " + parameters { + complex z; + vector[2] v; + } + model { + get_real(z) ~ normal(0, 1); + get_imag(z) ~ normal(0, 1); + v ~ normal(0, 1); + } + generated quantities { + tuple(real, array[2] real) t = (get_real(z), {v[1], v[2]}); + array[2] tuple(int, complex) at = {(1, z), (2, 2 * z)}; + complex_vector[2] zv = [z, 2 * z]'; + } + ", + dir = withr::local_tempdir() + ) + utils::capture.output( + fit <- cmdstan_model(stan_file)$sample( + chains = 2, + iter_warmup = 100, + iter_sampling = 20, + refresh = 0, + seed = 1 + ) + ) + out <- withr::local_tempfile(fileext = ".parquet") + cmdstan_csv_to_parquet(fit$output_files(), out) + draws <- read_parquet_draws(out) + expect_true(all(c("z[real]", "z[imag]") %in% posterior::variables(draws))) + expect_true(any(grepl(":", posterior::variables(draws), fixed = TRUE))) + expect_same_draws(draws, fit$draws()) + meta <- read_parquet_stan_metadata(out)$metadata + expect_identical(meta$variables, fit$metadata()$variables) + expect_equal(meta$stan_variable_sizes, fit$metadata()$stan_variable_sizes) + expect_same_contents( + read_cmdstan_parquet(out), + read_cmdstan_csv(fit$output_files()) + ) +}) + +test_that("cmdstan_csv_to_parquet() writes columns when there are no draws", { + fit <- testing_fit( + "logistic", + method = "sample", + seed = 123, + chains = 2, + iter_warmup = 50, + iter_sampling = 0 + ) + out <- withr::local_tempfile(fileext = ".parquet") + out_warmup <- withr::local_tempfile(fileext = ".parquet") + cmdstan_csv_to_parquet(fit$output_files(), out, warmup_file = out_warmup) + for (path in c(out, out_warmup)) { + pq <- nanoparquet::read_parquet(path) + expect_identical(nrow(pq), 0L) + expect_true(all( + c("lp__", "beta[1]", ".chain", ".iteration", ".draw") %in% names(pq) + )) + } +}) + +test_that("cmdstan_csv_to_parquet() replaces an old warmup file", { + fit <- testing_fit( + "logistic", + method = "sample", + seed = 123, + chains = 1, + iter_warmup = 50, + iter_sampling = 20 + ) + out <- withr::local_tempfile(fileext = ".parquet") + out_warmup <- withr::local_tempfile(fileext = ".parquet") + cmdstan_csv_to_parquet( + fit_parquet$output_files(), + out, + warmup_file = out_warmup + ) + expect_identical(nrow(nanoparquet::read_parquet(out_warmup)), 68L) + cmdstan_csv_to_parquet( + fit$output_files(), + out, + warmup_file = out_warmup, + overwrite = TRUE + ) + expect_identical(nrow(nanoparquet::read_parquet(out)), 20L) + expect_identical(nrow(nanoparquet::read_parquet(out_warmup)), 0L) +}) + +test_that("cmdstan_csv_to_parquet() writes no warmup draws for fixed_param", { + fit <- testing_fit( + "bernoulli", + method = "sample", + seed = 123, + chains = 1, + iter_warmup = 30, + iter_sampling = 20, + fixed_param = TRUE + ) + # CmdStan accepts save_warmup with fixed_param but writes no warmup draws + files <- edit_csv_files(fit$output_files(), function(lines, i) { + sub("save_warmup = (false|0)", "save_warmup = true", lines) + }) + expect_true(any(grepl("save_warmup = true", readLines(files)))) + out <- withr::local_tempfile(fileext = ".parquet") + out_warmup <- withr::local_tempfile(fileext = ".parquet") + expect_no_warning(cmdstan_csv_to_parquet( + files, + out, + warmup_file = out_warmup + )) + expect_same_draws(read_parquet_draws(out), fit$draws()) + expect_identical(nrow(nanoparquet::read_parquet(out_warmup)), 0L) + x <- read_cmdstan_parquet(out, warmup_file = out_warmup) + expect_equal(x$post_warmup_draws, fit$draws()) + expect_null(x$warmup_draws) + expect_null(x$post_warmup_sampler_diagnostics) +}) + +test_that("cmdstan_csv_to_parquet() warns about a chain with missing draws", { + files <- edit_csv_files(fit_parquet$output_files(), function(lines, i) { + if (i == 2) { + idx <- data_line_index(lines) + lines <- lines[-utils::tail(idx, 5)] + } + lines + }) + out <- withr::local_tempfile(fileext = ".parquet") + expect_warning( + cmdstan_csv_to_parquet(files, out), + "Chain 2 .* has 63 draws, but the sampler arguments give 68" + ) + expect_identical(nrow(nanoparquet::read_parquet(out)), 34L + 29L) +}) + +test_that("cmdstan_csv_to_parquet() stops at a malformed line", { + files <- edit_csv_files(fit_parquet$output_files(), function(lines, i) { + if (i == 2) { + idx <- utils::tail(data_line_index(lines), 1) + lines[idx] <- sub(",[^,]*$", "", lines[idx]) + } + lines + }) + out <- withr::local_tempfile(fileext = ".parquet") + cmdstan_csv_to_parquet(fit_parquet$output_files(), out) + old <- nanoparquet::read_parquet(out) + for (chunk_rows in list(NULL, 1, 7)) { + expect_error( + cmdstan_csv_to_parquet( + files, + out, + chunk_rows = chunk_rows, + overwrite = TRUE + ), + "Malformed data line" + ) + } + expect_identical(nanoparquet::read_parquet(out), old) + expect_identical(list.files(dirname(out), pattern = "^\\.tmp_"), character()) +}) + +test_that("cmdstan_csv_to_parquet() stops at a non-numeric value", { + files <- edit_csv_files(fit_parquet$output_files(), function(lines, i) { + if (i == 1) { + idx <- data_line_index(lines)[3] + lines[idx] <- sub("^[^,]*", "abc", lines[idx]) + } + lines + }) + out <- withr::local_tempfile(fileext = ".parquet") + expect_error( + cmdstan_csv_to_parquet(files, out), + "Malformed data line .* rows 1 and" + ) + expect_false(file.exists(out)) +}) + +test_that("cmdstan_csv_to_parquet() stops when the CSV headers differ", { + swap_columns <- function(lines) { + idx <- which(nzchar(lines) & !startsWith(lines, "#"))[1] + lines[idx] <- sub( + "stepsize__,treedepth__", + "treedepth__,stepsize__", + lines[idx], + fixed = TRUE + ) + lines + } + files <- edit_csv_files(fit_parquet$output_files(), function(lines, i) { + if (i == 2) swap_columns(lines) else lines + }) + out <- withr::local_tempfile(fileext = ".parquet") + expect_error( + cmdstan_csv_to_parquet(files, out), + "differs from the first file" + ) + # a second file with a header but no draws + files <- edit_csv_files(fit_parquet$output_files(), function(lines, i) { + if (i == 2) swap_columns(lines[-data_line_index(lines)]) else lines + }) + expect_error( + cmdstan_csv_to_parquet(files, out), + "differs from the first file" + ) + expect_false(file.exists(out)) +}) + +test_that("cmdstan_csv_to_parquet() checks its arguments", { + dir <- withr::local_tempdir() + expect_error( + cmdstan_csv_to_parquet( + fit_parquet$output_files(), + file.path(dir, "x.parquet"), + warmup_file = file.path(dir, ".", "x.parquet") + ), + "must be different" + ) + expect_identical(list.files(dir, all.files = TRUE, no.. = TRUE), character()) + out <- withr::local_tempfile(fileext = ".parquet") + cmdstan_csv_to_parquet(fit_parquet$output_files(), out) + expect_error( + cmdstan_csv_to_parquet(fit_parquet$output_files(), out), + "already exists" + ) + expect_no_error( + cmdstan_csv_to_parquet(fit_parquet$output_files(), out, overwrite = TRUE) + ) + same_path <- file.path(dirname(out), ".", basename(out)) + expect_error( + cmdstan_csv_to_parquet( + fit_parquet$output_files(), + out, + warmup_file = same_path, + overwrite = TRUE + ), + "must be different" + ) + fit_optimize <- testing_fit("logistic", method = "optimize", seed = 123) + expect_error( + cmdstan_csv_to_parquet( + fit_optimize$output_files(), + withr::local_tempfile() + ), + "Only CSV files from the MCMC sampler" + ) +}) + +test_that("read_cmdstan_parquet() gives the result of read_cmdstan_csv()", { + files <- fit_parquet$output_files() + out <- withr::local_tempfile(fileext = ".parquet") + out_warmup <- withr::local_tempfile(fileext = ".parquet") + cmdstan_csv_to_parquet(files, out, warmup_file = out_warmup) + expect_same_contents( + read_cmdstan_parquet(out, warmup_file = out_warmup), + read_cmdstan_csv(files) + ) + selections <- list( + list(variables = "beta", sampler_diagnostics = ""), + list(variables = "", sampler_diagnostics = "divergent__"), + list(variables = c("alpha", "beta[2]"), format = "draws_df") + ) + for (args in selections) { + expect_same_contents( + do.call( + read_cmdstan_parquet, + c(list(out, warmup_file = out_warmup), args) + ), + do.call(read_cmdstan_csv, c(list(files), args)) + ) + } + expect_error( + read_cmdstan_parquet(out, variables = "gamma"), + "Can't find the following variable(s) in the output: gamma", + fixed = TRUE + ) + expect_error( + read_cmdstan_parquet(out, sampler_diagnostics = "gamma__"), + "Can't find the following sampler diagnostic(s)", + fixed = TRUE + ) + # without the warmup file + x <- read_cmdstan_parquet(out) + expect_null(x$warmup_draws) + expect_null(x$warmup_sampler_diagnostics) + expect_identical(x$metadata$save_warmup, 1L) + expect_equal(x$post_warmup_draws, read_cmdstan_csv(files)$post_warmup_draws) +}) + +test_that("read_cmdstan_parquet() rejects other Parquet files", { + out <- withr::local_tempfile(fileext = ".parquet") + nanoparquet::write_parquet(data.frame(a = 1), out) + expect_error(read_cmdstan_parquet(out), "no CmdStan metadata") +}) + +test_that("as_cmdstan_fit() makes a fit from a Parquet file", { + files <- fit_parquet$output_files() + out <- withr::local_tempfile(fileext = ".parquet") + out_warmup <- withr::local_tempfile(fileext = ".parquet") + cmdstan_csv_to_parquet(files, out, warmup_file = out_warmup) + fit_pq <- as_cmdstan_fit(out, warmup_file = out_warmup) + fit_csv <- as_cmdstan_fit(files) + expect_s3_class(fit_pq, "CmdStanMCMC") + expect_identical(fit_pq$output_files(), out) + expect_identical(fit_pq$num_chains(), 2L) + expect_equal(fit_pq$draws(), fit_parquet$draws()) + expect_equal( + fit_pq$draws(inc_warmup = TRUE), + fit_parquet$draws(inc_warmup = TRUE) + ) + expect_equal( + fit_pq$sampler_diagnostics(inc_warmup = TRUE), + fit_parquet$sampler_diagnostics(inc_warmup = TRUE) + ) + expect_equal(fit_pq$inv_metric(), fit_parquet$inv_metric()) + expect_equal(fit_pq$time(), fit_csv$time()) + expect_equal( + fit_pq$metadata()[sort(names(fit_pq$metadata()))], + fit_csv$metadata()[sort(names(fit_csv$metadata()))] + ) + expect_equal( + suppressWarnings(fit_pq$summary()), + suppressWarnings(fit_parquet$summary()) + ) + expect_error(fit_pq$code(), "not available") + # variables selects the draws that the object reads first + fit_alpha <- as_cmdstan_fit(out, variables = "alpha") + expect_equal(fit_alpha$draws(), fit_parquet$draws("alpha")) + # without the warmup file, the object has no warmup draws + fit_no_warmup <- as_cmdstan_fit(out) + expect_error( + fit_no_warmup$draws(inc_warmup = TRUE), + "separate Parquet file" + ) + expect_error( + fit_no_warmup$sampler_diagnostics(inc_warmup = TRUE), + "separate Parquet file" + ) + expect_equal(fit_no_warmup$draws(), fit_parquet$draws()) + # a lazy read after saveRDS() and readRDS() + rds <- withr::local_tempfile(fileext = ".rds") + saveRDS(as_cmdstan_fit(out), rds) + fit_loaded <- readRDS(rds) + expect_equal(fit_loaded$draws("beta"), fit_parquet$draws("beta")) + expect_error(as_cmdstan_fit(c(out, out)), "one Parquet file") + expect_error( + as_cmdstan_fit(files, warmup_file = out_warmup), + "can only be used with a Parquet file" + ) +}) + +test_that("the Parquet metadata JSON keeps doubles exact", { + # CmdStan writes the step size and the metric with 6 digits, so test the + # JSON with other values + csv_metadata <- lapply(fit_parquet$output_files(), read_csv_metadata) + csv_metadata[[1]]$inv_metric <- c(1 / 3, pi, NaN, Inf) + csv_metadata[[2]]$step_size_adaptation <- 1 / 7 + csv_metadata[[2]]$inv_metric <- c(-Inf, NA, exp(1), 1e-300) + back <- parquet_csv_metadata(parquet_stan_metadata(csv_metadata)) + for (i in 1:2) { + # the reader drops num_chains; merge_csv_metadata() sets it + expected_names <- setdiff(names(csv_metadata[[i]]), "num_chains") + expect_setequal(names(back[[i]]), expected_names) + # profile_file differs between the chains + for (name in expected_names) { + expect_identical( + back[[i]][[name]], + csv_metadata[[i]][[name]], + info = name + ) + } + } +}) + +test_that("read_cmdstan_parquet() reads a nan in the metric", { + fit <- testing_fit( + "logistic", + method = "sample", + seed = 123, + chains = 2, + iter_warmup = 100, + iter_sampling = 10 + ) + files <- edit_csv_files(fit$output_files(), function(lines, i) { + if (i == 2) { + idx <- grep("Diagonal elements of inverse mass matrix", lines) + 1 + lines[idx] <- sub("# [^,]*", "# nan", lines[idx]) + } + lines + }) + out <- withr::local_tempfile(fileext = ".parquet") + cmdstan_csv_to_parquet(files, out) + x <- read_cmdstan_parquet(out) + csv <- read_cmdstan_csv(files) + expect_true(is.nan(csv$inv_metric[[2]][1])) + expect_identical(x$inv_metric, csv$inv_metric) + expect_identical(x$step_size, csv$step_size) + expect_same_contents(x, csv) +}) + +test_that("read_cmdstan_parquet() reads one-parameter metrics", { + for (metric in c("diag_e", "dense_e")) { + fit <- testing_fit( + "bernoulli", + method = "sample", + seed = 123, + chains = 1, + iter_warmup = 200, + iter_sampling = 10, + metric = metric + ) + out <- withr::local_tempfile(fileext = ".parquet") + cmdstan_csv_to_parquet(fit$output_files(), out) + expect_same_contents( + read_cmdstan_parquet(out), + read_cmdstan_csv(fit$output_files()) + ) + } +}) + +test_that("read_cmdstan_parquet() reads fixed_param output and an init file", { + fit_fixed <- testing_fit( + "bernoulli", + method = "sample", + seed = 123, + chains = 2, + iter_sampling = 20, + fixed_param = TRUE + ) + out <- withr::local_tempfile(fileext = ".parquet") + cmdstan_csv_to_parquet(fit_fixed$output_files(), out) + expect_same_contents( + read_cmdstan_parquet(out), + read_cmdstan_csv(fit_fixed$output_files()) + ) + expect_equal(as_cmdstan_fit(out)$draws(), fit_fixed$draws()) + # the CSV metadata has the path of the init file + fit_init <- testing_fit( + "logistic", + method = "sample", + seed = 123, + chains = 1, + iter_warmup = 50, + iter_sampling = 10, + init = list(list(alpha = 0, beta = c(0, 0, 0))) + ) + out_init <- withr::local_tempfile(fileext = ".parquet") + cmdstan_csv_to_parquet(fit_init$output_files(), out_init) + x <- read_cmdstan_parquet(out_init) + expect_type(x$metadata$init, "character") + expect_same_contents(x, read_cmdstan_csv(fit_init$output_files())) +}) + +test_that("read_cmdstan_parquet() checks the files", { + files <- fit_parquet$output_files() + out <- withr::local_tempfile(fileext = ".parquet") + out_warmup <- withr::local_tempfile(fileext = ".parquet") + cmdstan_csv_to_parquet(files, out, warmup_file = out_warmup) + expect_error( + read_cmdstan_parquet(out_warmup, warmup_file = out), + "does not have the sampling draws" + ) + expect_error( + read_cmdstan_parquet(out, warmup_file = out), + "does not have the warmup draws" + ) + # a warmup file from another run + fit_other <- testing_fit( + "logistic", + method = "sample", + seed = 456, + chains = 2, + iter_warmup = 100, + iter_sampling = 100, + thin = 3, + save_warmup = TRUE + ) + other <- withr::local_tempfile(fileext = ".parquet") + other_warmup <- withr::local_tempfile(fileext = ".parquet") + cmdstan_csv_to_parquet( + fit_other$output_files(), + other, + warmup_file = other_warmup + ) + expect_error( + read_cmdstan_parquet(out, warmup_file = other_warmup), + "not from the same run" + ) + # metadata of another method + kv <- nanoparquet::read_parquet_metadata( + out + )$file_meta_data$key_value_metadata[[1]] + metadata <- stats::setNames(kv$value, kv$key) + metadata <- metadata[names(metadata) != "ARROW:schema"] + metadata["stan.metadata"] <- sub( + '"method":"sample"', + '"method":"optimize"', + metadata["stan.metadata"], + fixed = TRUE + ) + out_optimize <- withr::local_tempfile(fileext = ".parquet") + nanoparquet::write_parquet( + data.frame(lp__ = 1, .chain = 1L, .iteration = 1L), + out_optimize, + metadata = metadata + ) + expect_error( + read_cmdstan_parquet(out_optimize), + "Only output of the MCMC sampler" + ) +})