From ca40d20b6d7a954a47a99c1b430b7792cae5b22a Mon Sep 17 00:00:00 2001 From: Aki Vehtari Date: Tue, 17 Nov 2026 11:15:44 +0200 Subject: [PATCH 01/14] Move CSV file preparation of read_cmdstan_csv() into a helper --- R/csv.R | 34 ++++++++++++++++++++++++---------- 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/R/csv.R b/R/csv.R index f8384194f..9f82d9a56 100644 --- a/R/csv.R +++ b/R/csv.R @@ -179,17 +179,8 @@ 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() @@ -792,6 +783,29 @@ parse_generated_quantities_time <- function(line) { time } +#' 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` From 2c4999c6555da0d11aa79787dd7b7a440b6d8361 Mon Sep 17 00:00:00 2001 From: Aki Vehtari Date: Tue, 17 Nov 2026 11:15:49 +0200 Subject: [PATCH 02/14] Add cmdstan_csv_to_parquet() to convert CmdStan CSV files to Parquet --- DESCRIPTION | 1 + NAMESPACE | 1 + R/parquet.R | 353 ++++++++++++++++++++++++++++++++++ _pkgdown.yml | 1 + man/cmdstan_csv_to_parquet.Rd | 123 ++++++++++++ 5 files changed, 479 insertions(+) create mode 100644 R/parquet.R create mode 100644 man/cmdstan_csv_to_parquet.Rd 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..24fbc9497 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) diff --git a/R/parquet.R b/R/parquet.R new file mode 100644 index 000000000..79aeafb92 --- /dev/null +++ b/R/parquet.R @@ -0,0 +1,353 @@ +#' 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 gives at most one Parquet row group in each output file. +#' 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. +#' +#' Thus `posterior::as_draws_df(nanoparquet::read_parquet(file))` gives the +#' draws, 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 two entries: +#' * `stan.format_version`: the version of this file layout, now `"1"`. +#' * `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) and the +#' `time` in seconds. +#' +#' 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_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 +#' kv <- nanoparquet::read_parquet_metadata(pq_file)$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) + if (anyDuplicated(normalizePath(out_files, mustWork = FALSE))) { + 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 <- max(1, ceiling(1e7 / n_columns)) + } + + 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 { + nanoparquet::write_parquet( + x, path, + compression = compression, metadata = key_value, 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) NULL + ) + if (is.null(chunk) || 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), ".", + 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) { + per_chain <- c( + "id", "seed", "init", "step_size", "step_size_adaptation", + "fitted_params", "inv_metric", "time" + ) + metadata <- csv_metadata[[1]] + out <- 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) + out$num_chains <- length(csv_metadata) + out$chains <- lapply(csv_metadata, function(x) { + chain <- 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 + }) + as.character(jsonlite::toJSON( + out, + auto_unbox = TRUE, digits = NA, null = "null", na = "null" + )) +} diff --git a/_pkgdown.yml b/_pkgdown.yml index f0806aab8..11d7c10d1 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -68,6 +68,7 @@ reference: - write_stan_file - print_stan_file - draws_to_csv + - cmdstan_csv_to_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..ae967c953 --- /dev/null +++ b/man/cmdstan_csv_to_parquet.Rd @@ -0,0 +1,123 @@ +% 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 gives at most one Parquet row group in each output file. +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. +} + +Thus \code{posterior::as_draws_df(nanoparquet::read_parquet(file))} gives the +draws, 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 two entries: +\itemize{ +\item \code{stan.format_version}: the version of this file layout, now \code{"1"}. +\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) and the +\code{time} in seconds. +} + +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 +kv <- nanoparquet::read_parquet_metadata(pq_file)$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_csv]{read_cmdstan_csv()}}, \code{\link[=fit-method-output_files]{$output_files()}} +} From 8545e8436e8b84002eea85c461c7cf3ff5866ac1 Mon Sep 17 00:00:00 2001 From: Aki Vehtari Date: Tue, 17 Nov 2026 11:15:54 +0200 Subject: [PATCH 03/14] Add tests for cmdstan_csv_to_parquet() --- tests/testthat/test-parquet.R | 256 ++++++++++++++++++++++++++++++++++ 1 file changed, 256 insertions(+) create mode 100644 tests/testthat/test-parquet.R diff --git a/tests/testthat/test-parquet.R b/tests/testthat/test-parquet.R new file mode 100644 index 000000000..620d40b6b --- /dev/null +++ b/tests/testthat/test-parquet.R @@ -0,0 +1,256 @@ +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))) +} + +# 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) + 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]])) +}) + +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() 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 itself 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) +}) + +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 and keeps old output", { + 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() checks its arguments", { + 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" + ) +}) From 170802a8a843c0b61f8cf1055b18db4df35a5dc2 Mon Sep 17 00:00:00 2001 From: Aki Vehtari Date: Tue, 17 Nov 2026 11:19:39 +0200 Subject: [PATCH 04/14] Handle new output paths, empty output and malformed CSV in cmdstan_csv_to_parquet() --- R/parquet.R | 22 ++++++++++++++----- man/cmdstan_csv_to_parquet.Rd | 4 +++- tests/testthat/test-parquet.R | 41 +++++++++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 6 deletions(-) diff --git a/R/parquet.R b/R/parquet.R index 79aeafb92..23fa167d1 100644 --- a/R/parquet.R +++ b/R/parquet.R @@ -61,7 +61,9 @@ #' `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) and the -#' `time` in seconds. +#' `time` in seconds. 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. #' #' Read the metadata with [nanoparquet::read_parquet_metadata()] and #' [jsonlite::fromJSON()]. @@ -109,7 +111,9 @@ cmdstan_csv_to_parquet <- function(files, checkmate::assert_flag(overwrite) compression <- match.arg(compression) out_files <- c(file, warmup_file) - if (anyDuplicated(normalizePath(out_files, mustWork = FALSE))) { + # 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))) { @@ -144,8 +148,11 @@ cmdstan_csv_to_parquet <- function(files, 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 <- max(1, ceiling(1e7 / n_columns)) + 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", @@ -303,13 +310,14 @@ parse_csv_lines <- function(lines, col_names, path, rows_before) { data.table = FALSE, showProgress = FALSE )), - error = function(e) NULL + error = function(e) e ) - if (is.null(chunk) || nrow(chunk) != length(lines) || + 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 ) } @@ -335,6 +343,10 @@ parquet_stan_metadata <- function(csv_metadata) { 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 <- x[intersect(per_chain, names(x))] diff --git a/man/cmdstan_csv_to_parquet.Rd b/man/cmdstan_csv_to_parquet.Rd index ae967c953..9ac088095 100644 --- a/man/cmdstan_csv_to_parquet.Rd +++ b/man/cmdstan_csv_to_parquet.Rd @@ -84,7 +84,9 @@ the CmdStan version and the sampler arguments, and \code{variables}, \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) and the -\code{time} in seconds. +\code{time} in seconds. 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. } Read the metadata with \code{\link[nanoparquet:read_parquet_metadata]{nanoparquet::read_parquet_metadata()}} and diff --git a/tests/testthat/test-parquet.R b/tests/testthat/test-parquet.R index 620d40b6b..fd42c4999 100644 --- a/tests/testthat/test-parquet.R +++ b/tests/testthat/test-parquet.R @@ -230,7 +230,48 @@ test_that("cmdstan_csv_to_parquet() stops at a malformed line and keeps old outp 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( From 2b7405449b29bdbecdc5f930b63f45081a1ae3f3 Mon Sep 17 00:00:00 2001 From: Aki Vehtari Date: Tue, 17 Nov 2026 11:26:46 +0200 Subject: [PATCH 05/14] Correct the row group description of chunk_rows --- R/parquet.R | 6 +++--- man/cmdstan_csv_to_parquet.Rd | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/R/parquet.R b/R/parquet.R index 23fa167d1..e8b6659c8 100644 --- a/R/parquet.R +++ b/R/parquet.R @@ -15,9 +15,9 @@ #' 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 gives at most one Parquet row group in each output file. -#' The default is `NULL`, which selects about 10 million values for each -#' chunk. +#' 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 diff --git a/man/cmdstan_csv_to_parquet.Rd b/man/cmdstan_csv_to_parquet.Rd index 9ac088095..3ae5f15de 100644 --- a/man/cmdstan_csv_to_parquet.Rd +++ b/man/cmdstan_csv_to_parquet.Rd @@ -26,9 +26,9 @@ 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 gives at most one Parquet row group in each output file. -The default is \code{NULL}, which selects about 10 million values for each -chunk.} +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"}.} From 13bab24db153dad511651543e72c43dca2db5955 Mon Sep 17 00:00:00 2001 From: Aki Vehtari Date: Tue, 17 Nov 2026 12:19:28 +0200 Subject: [PATCH 06/14] Format cmdstan_csv_to_parquet() and its tests with Air --- R/parquet.R | 119 +++++++++++++++------ tests/testthat/test-parquet.R | 195 ++++++++++++++++++++++++++-------- 2 files changed, 241 insertions(+), 73 deletions(-) diff --git a/R/parquet.R b/R/parquet.R index e8b6659c8..9c1b2e5f7 100644 --- a/R/parquet.R +++ b/R/parquet.R @@ -97,12 +97,14 @@ #' 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) { +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) @@ -112,7 +114,10 @@ cmdstan_csv_to_parquet <- function(files, 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)) + 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) } @@ -135,19 +140,23 @@ cmdstan_csv_to_parquet <- function(files, if (metadata$method != "sample") { stop( "Only CSV files from the MCMC sampler are supported, not method '", - metadata$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")) { + 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) + 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 @@ -162,13 +171,18 @@ cmdstan_csv_to_parquet <- function(files, write_chunk <- function(x, path) { if (file.exists(path)) { nanoparquet::append_parquet( - x, path, - compression = compression, options = pq_options + x, + path, + compression = compression, + options = pq_options ) } else { nanoparquet::write_parquet( - x, path, - compression = compression, metadata = key_value, options = pq_options + x, + path, + compression = compression, + metadata = key_value, + options = pq_options ) } } @@ -183,7 +197,11 @@ cmdstan_csv_to_parquet <- function(files, 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") + tmp_warmup <- tempfile( + ".tmp_", + tmpdir = dirname(warmup_file), + fileext = ".parquet" + ) } on.exit(unlink(c(tmp_file, tmp_warmup)), add = TRUE) @@ -198,8 +216,12 @@ cmdstan_csv_to_parquet <- function(files, 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) + 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)) @@ -215,7 +237,10 @@ cmdstan_csv_to_parquet <- function(files, 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) + 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) @@ -225,21 +250,36 @@ cmdstan_csv_to_parquet <- function(files, 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) + 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, ".", + "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), + stats::setNames( + rep(list(double()), length(state$out_names)), + state$out_names + ), check.names = FALSE ) empty <- add_index_columns(empty, integer(), integer(), integer()) @@ -312,11 +352,19 @@ parse_csv_lines <- function(lines, col_names, path, rows_before) { )), error = function(e) e ) - if (inherits(chunk, "error") || nrow(chunk) != length(lines) || - !all(vapply(chunk, is.double, logical(1)))) { + 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), ".", + "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 ) @@ -333,8 +381,14 @@ parse_csv_lines <- function(lines, col_names, path, rows_before) { #' parquet_stan_metadata <- function(csv_metadata) { per_chain <- c( - "id", "seed", "init", "step_size", "step_size_adaptation", - "fitted_params", "inv_metric", "time" + "id", + "seed", + "init", + "step_size", + "step_size_adaptation", + "fitted_params", + "inv_metric", + "time" ) metadata <- csv_metadata[[1]] out <- metadata[setdiff(names(metadata), per_chain)] @@ -360,6 +414,9 @@ parquet_stan_metadata <- function(csv_metadata) { }) as.character(jsonlite::toJSON( out, - auto_unbox = TRUE, digits = NA, null = "null", na = "null" + auto_unbox = TRUE, + digits = NA, + null = "null", + na = "null" )) } diff --git a/tests/testthat/test-parquet.R b/tests/testthat/test-parquet.R index fd42c4999..98e6efd68 100644 --- a/tests/testthat/test-parquet.R +++ b/tests/testthat/test-parquet.R @@ -3,8 +3,13 @@ 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 + method = "sample", + seed = 123, + chains = 2, + iter_warmup = 100, + iter_sampling = 100, + thin = 3, + save_warmup = TRUE ) read_parquet_draws <- function(path) { @@ -12,7 +17,9 @@ read_parquet_draws <- function(path) { } read_parquet_stan_metadata <- function(path) { - kv <- nanoparquet::read_parquet_metadata(path)$file_meta_data$key_value_metadata[[1]] + 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"]) @@ -20,12 +27,22 @@ read_parquet_stan_metadata <- function(path) { } 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))) + object <- posterior::subset_draws( + object, + variable = posterior::variables(expected) + ) + expect_equal( + as.data.frame(object), + as.data.frame(posterior::as_draws_df(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())) { +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]) @@ -43,8 +60,10 @@ test_that("cmdstan_csv_to_parquet() gives the draws of $draws()", { # 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 + fit_parquet$output_files(), + out, + warmup_file = out_warmup, + chunk_rows = 7 ), out ) @@ -57,7 +76,10 @@ test_that("cmdstan_csv_to_parquet() gives the draws of $draws()", { 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)) + 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")) @@ -71,7 +93,12 @@ test_that("cmdstan_csv_to_parquet() result does not depend on chunk_rows", { 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) + 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) @@ -81,7 +108,10 @@ test_that("cmdstan_csv_to_parquet() result does not depend on chunk_rows", { 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) + expect_identical( + nrow(nanoparquet::read_parquet_metadata(out_default)$row_groups), + 2L + ) }) test_that("cmdstan_csv_to_parquet() stores the CmdStan metadata", { @@ -94,19 +124,35 @@ test_that("cmdstan_csv_to_parquet() stores the CmdStan metadata", { expect_identical(meta$num_chains, 2L) expect_identical(meta$thin, 3L) 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_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_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" + 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) @@ -118,20 +164,32 @@ test_that("cmdstan_csv_to_parquet() stores a dense metric", { 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 + 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]] + 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, + '"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")) + 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) @@ -141,14 +199,20 @@ test_that("cmdstan_csv_to_parquet() reads compressed CSV files", { 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)) + expect_identical( + nanoparquet::read_parquet(out_gz), + nanoparquet::read_parquet(out_csv) + ) }) 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 + 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") @@ -156,21 +220,35 @@ test_that("cmdstan_csv_to_parquet() writes columns when there are no draws", { 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))) + 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 + 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) + 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) + 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) }) @@ -178,8 +256,12 @@ test_that("cmdstan_csv_to_parquet() replaces an old warmup file", { 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 + method = "sample", + seed = 123, + chains = 1, + iter_warmup = 30, + iter_sampling = 20, + fixed_param = TRUE ) # CmdStan itself accepts save_warmup with fixed_param, but writes no warmup draws files <- edit_csv_files(fit$output_files(), function(lines, i) { @@ -188,7 +270,11 @@ test_that("cmdstan_csv_to_parquet() writes no warmup draws for fixed_param", { 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_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) }) @@ -222,7 +308,12 @@ test_that("cmdstan_csv_to_parquet() stops at a malformed line and keeps old outp 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), + cmdstan_csv_to_parquet( + files, + out, + chunk_rows = chunk_rows, + overwrite = TRUE + ), "Malformed data line" ) } @@ -239,26 +330,40 @@ test_that("cmdstan_csv_to_parquet() stops at a non-numeric value", { lines }) out <- withr::local_tempfile(fileext = ".parquet") - expect_error(cmdstan_csv_to_parquet(files, out), "Malformed data line .* rows 1 and") + 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[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") + 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_error( + cmdstan_csv_to_parquet(files, out), + "differs from the first file" + ) expect_false(file.exists(out)) }) @@ -266,7 +371,8 @@ 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"), + fit_parquet$output_files(), + file.path(dir, "x.parquet"), warmup_file = file.path(dir, ".", "x.parquet") ), "must be different" @@ -284,14 +390,19 @@ test_that("cmdstan_csv_to_parquet() checks its arguments", { 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 + 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()), + cmdstan_csv_to_parquet( + fit_optimize$output_files(), + withr::local_tempfile() + ), "Only CSV files from the MCMC sampler" ) }) From ec4e8cbe5b96fed7564e1702ee57c0040f7407e5 Mon Sep 17 00:00:00 2001 From: Aki Vehtari Date: Tue, 17 Nov 2026 12:23:15 +0200 Subject: [PATCH 07/14] Test tuple, complex and bzip2 input of cmdstan_csv_to_parquet() and shorten long lines --- R/parquet.R | 3 +- man/cmdstan_csv_to_parquet.Rd | 3 +- tests/testthat/test-parquet.R | 67 +++++++++++++++++++++++++++++++++-- 3 files changed, 69 insertions(+), 4 deletions(-) diff --git a/R/parquet.R b/R/parquet.R index 9c1b2e5f7..e9fcedc02 100644 --- a/R/parquet.R +++ b/R/parquet.R @@ -92,7 +92,8 @@ #' )) #' #' # metadata -#' kv <- nanoparquet::read_parquet_metadata(pq_file)$file_meta_data$key_value_metadata[[1]] +#' 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 #' } diff --git a/man/cmdstan_csv_to_parquet.Rd b/man/cmdstan_csv_to_parquet.Rd index 3ae5f15de..526bd8302 100644 --- a/man/cmdstan_csv_to_parquet.Rd +++ b/man/cmdstan_csv_to_parquet.Rd @@ -114,7 +114,8 @@ draws_beta <- posterior::as_draws_df(nanoparquet::read_parquet( )) # metadata -kv <- nanoparquet::read_parquet_metadata(pq_file)$file_meta_data$key_value_metadata[[1]] +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 } diff --git a/tests/testthat/test-parquet.R b/tests/testthat/test-parquet.R index 98e6efd68..bda508765 100644 --- a/tests/testthat/test-parquet.R +++ b/tests/testthat/test-parquet.R @@ -205,6 +205,69 @@ test_that("cmdstan_csv_to_parquet() reads compressed CSV files", { ) }) +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) +}) + test_that("cmdstan_csv_to_parquet() writes columns when there are no draws", { fit <- testing_fit( "logistic", @@ -263,7 +326,7 @@ test_that("cmdstan_csv_to_parquet() writes no warmup draws for fixed_param", { iter_sampling = 20, fixed_param = TRUE ) - # CmdStan itself accepts save_warmup with fixed_param, but writes no warmup draws + # 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) }) @@ -295,7 +358,7 @@ test_that("cmdstan_csv_to_parquet() warns about a chain with missing draws", { expect_identical(nrow(nanoparquet::read_parquet(out)), 34L + 29L) }) -test_that("cmdstan_csv_to_parquet() stops at a malformed line and keeps old output", { +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) From 4866460e58b5713b427cb9304a66ca7fa3d69518 Mon Sep 17 00:00:00 2001 From: Aki Vehtari Date: Tue, 17 Nov 2026 15:50:42 +0200 Subject: [PATCH 08/14] Move the metadata merge and column selection of read_cmdstan_csv() into helpers --- R/csv.R | 267 +++++++++++++++++++++++++++++++++----------------------- 1 file changed, 158 insertions(+), 109 deletions(-) diff --git a/R/csv.R b/R/csv.R index 9f82d9a56..4818afcd2 100644 --- a/R/csv.R +++ b/R/csv.R @@ -186,67 +186,15 @@ read_cmdstan_csv <- function( 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 @@ -265,52 +213,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) @@ -392,10 +301,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" @@ -783,6 +689,149 @@ 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 From 5707e057f8b87d01a45c7f9941591dc3b65fd68b Mon Sep 17 00:00:00 2001 From: Aki Vehtari Date: Tue, 17 Nov 2026 17:07:58 +0200 Subject: [PATCH 09/14] Add read_cmdstan_parquet() and Parquet input for as_cmdstan_fit() --- NAMESPACE | 1 + R/csv.R | 52 +++++- R/fit.R | 13 +- R/parquet.R | 335 ++++++++++++++++++++++++++++++++-- _pkgdown.yml | 1 + man/cmdstan_csv_to_parquet.Rd | 16 +- man/read_cmdstan_csv.Rd | 12 +- man/read_cmdstan_parquet.Rd | 82 +++++++++ 8 files changed, 482 insertions(+), 30 deletions(-) create mode 100644 man/read_cmdstan_parquet.Rd diff --git a/NAMESPACE b/NAMESPACE index 24fbc9497..fbdccbd6b 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -44,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 4818afcd2..eea3d1c2b 100644 --- a/R/csv.R +++ b/R/csv.R @@ -125,6 +125,12 @@ #' 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. +#' #' @seealso [draws_to_csv()] for creating compatible CSV files and #' [`$output_files()`][fit-method-output_files] for locating files created by #' CmdStanR @@ -448,19 +454,40 @@ 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 - ) + is_parquet <- length(files) == 1 && + grepl("\\.parquet$", files, ignore.case = TRUE) + 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") { @@ -475,7 +502,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), 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 index e9fcedc02..220f62fd2 100644 --- a/R/parquet.R +++ b/R/parquet.R @@ -45,8 +45,14 @@ #' file in `files`. `.iteration` starts from 1 in each chain. `.draw` #' numbers the draws of all chains consecutively. #' -#' Thus `posterior::as_draws_df(nanoparquet::read_parquet(file))` gives the -#' draws, and the `col_select` argument of [nanoparquet::read_parquet()] +#' [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 @@ -63,7 +69,8 @@ #' `inv_metric` (an array, or an array of rows for a dense metric) and the #' `time` in seconds. 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. +#' `accept_stat__`. Use the Parquet schema to get all column names. The CSV +#' values `true` and `false` are JSON booleans. #' #' Read the metadata with [nanoparquet::read_parquet_metadata()] and #' [jsonlite::fromJSON()]. @@ -74,7 +81,8 @@ #' of draws than the sampler arguments give, for example a chain that stopped #' early. #' -#' @seealso [read_cmdstan_csv()], [`$output_files()`][fit-method-output_files] +#' @seealso [read_cmdstan_parquet()], [read_cmdstan_csv()], +#' [`$output_files()`][fit-method-output_files] #' #' @examples #' \dontrun{ @@ -381,18 +389,17 @@ parse_csv_lines <- function(lines, col_names, path, rows_before) { #' @return A JSON string. #' parquet_stan_metadata <- function(csv_metadata) { - per_chain <- c( - "id", - "seed", - "init", - "step_size", - "step_size_adaptation", - "fitted_params", - "inv_metric", - "time" - ) + per_chain <- parquet_per_chain_fields metadata <- csv_metadata[[1]] out <- metadata[setdiff(names(metadata), per_chain)] + # read_csv_metadata() turns the CSV values true and false into integers; + # write them as JSON booleans + is_flag <- vapply( + out, + function(x) is.integer(x) && length(x) == 1, + logical(1) + ) + out[is_flag] <- lapply(out[is_flag], as.logical) # I() keeps vectors of length 1 as JSON arrays variables <- repair_variable_names(metadata$variables) out$variables <- I(variables) @@ -421,3 +428,303 @@ parquet_stan_metadata <- function(csv_metadata) { na = "null" )) } + +# 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()]). The default is +#' `NULL`, which reads no warmup draws and sets `metadata$save_warmup` to +#' `0`. +#' +#' @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`. +#' +#' @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) + if (!is.null(warmup_file)) { + checkmate::assert_file_exists(warmup_file, access = "r") + } + format <- assert_valid_draws_format(format) + merged <- merge_csv_metadata(read_parquet_csv_metadata(file)) + metadata <- merged$metadata + if (is.null(warmup_file)) { + metadata$save_warmup <- 0L + } + 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 + ) + ) +} + +#' Rebuild the per-chain CSV metadata from the JSON of a Parquet file. +#' +#' @noRd +#' @param file A Parquet file from `cmdstan_csv_to_parquet()`. +#' @return A list with one element for each chain, in the form of +#' `read_csv_metadata()` output, with the CSV variable names. +#' +read_parquet_csv_metadata <- function(file) { + kv <- nanoparquet::read_parquet_metadata( + file + )$file_meta_data$key_value_metadata[[1]] + version <- kv$value[kv$key == "stan.format_version"] + if (!identical(version, "1")) { + stop( + "'", + file, + "' has no CmdStan metadata of format version 1. ", + "Use a file from cmdstan_csv_to_parquet().", + call. = FALSE + ) + } + json <- jsonlite::fromJSON( + kv$value[kv$key == "stan.metadata"], + 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 <- drop_null(lapply(shared, json_to_r)) + # the JSON has the repaired names; read_csv_metadata() gives the CSV names + shared$variables <- unrepair_variable_names(shared$variables) + lapply(json$chains, function(chain) { + chain <- drop_null(lapply(chain, json_to_r)) + if (!is.null(chain$time)) { + chain$time <- as.data.frame(chain$time) + } + c(shared, chain) + }) +} + +drop_null <- function(x) { + x[!vapply(x, is.null, logical(1))] +} + +#' Convert a value of `jsonlite::fromJSON(simplifyVector = FALSE)` to the +#' types of `read_csv_metadata()`. +#' +#' @noRd +#' @param x A parsed JSON value. +#' @return Numbers as doubles, booleans as integers 0 and 1, arrays as +#' vectors, arrays of arrays as matrices (rows), objects as named lists. +#' +json_to_r <- function(x) { + if (is.null(x) || is.character(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, json_to_r)) + } + if (length(x) == 0) { + return(NULL) + } + if (all(vapply(x, is.list, logical(1)))) { + return(do.call(rbind, lapply(x, function(row) as.numeric(unlist(row))))) + } + values <- unlist(x) + if (is.logical(values)) { + as.integer(values) + } else if (is.numeric(values)) { + as.numeric(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.data.frame(nanoparquet::read_parquet( + path, + col_select = c(columns, ".chain", ".iteration") + )) + if (nrow(pq) == 0) { + return(list()) + } + row_order <- order(pq$.chain, pq$.iteration) + if (is.unsorted(row_order)) { + pq <- pq[row_order, , drop = FALSE] + } + n_rows <- tabulate(pq$.chain, nbins = num_chains) + if (sum(n_rows) != nrow(pq) || any(n_rows != n_rows[1])) { + stop( + "The chains in '", + path, + "' have different numbers of draws.", + call. = FALSE + ) + } + 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)) { + out[,, j] <- pq[[names[j]]] + } + 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 + } + ), + private = list( + warmup_file_ = NULL, + 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 11d7c10d1..e534bbceb 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -69,6 +69,7 @@ reference: - 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 index 526bd8302..ec0611a40 100644 --- a/man/cmdstan_csv_to_parquet.Rd +++ b/man/cmdstan_csv_to_parquet.Rd @@ -67,8 +67,14 @@ file in \code{files}. \code{.iteration} starts from 1 in each chain. \code{.draw numbers the draws of all chains consecutively. } -Thus \code{posterior::as_draws_df(nanoparquet::read_parquet(file))} gives the -draws, and the \code{col_select} argument of \code{\link[nanoparquet:read_parquet]{nanoparquet::read_parquet()}} +\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 @@ -86,7 +92,8 @@ the CmdStan version and the sampler arguments, and \code{variables}, \code{inv_metric} (an array, or an array of rows for a dense metric) and the \code{time} in seconds. 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. +\code{accept_stat__}. Use the Parquet schema to get all column names. The CSV +values \code{true} and \code{false} are JSON booleans. } Read the metadata with \code{\link[nanoparquet:read_parquet_metadata]{nanoparquet::read_parquet_metadata()}} and @@ -122,5 +129,6 @@ metadata$chains$step_size_adaptation } \seealso{ -\code{\link[=read_cmdstan_csv]{read_cmdstan_csv()}}, \code{\link[=fit-method-output_files]{$output_files()}} +\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..9b81de126 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,12 @@ 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. } \examples{ diff --git a/man/read_cmdstan_parquet.Rd b/man/read_cmdstan_parquet.Rd new file mode 100644 index 000000000..4c959fff7 --- /dev/null +++ b/man/read_cmdstan_parquet.Rd @@ -0,0 +1,82 @@ +% 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()}}). The default is +\code{NULL}, which reads no warmup draws and sets \code{metadata$save_warmup} to +\code{0}.} +} +\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}. +} +\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()}} +} From 9ddbbecf64d5dda0b7444ef9956d7d40d349ea7b Mon Sep 17 00:00:00 2001 From: Aki Vehtari Date: Tue, 17 Nov 2026 17:08:03 +0200 Subject: [PATCH 10/14] Test read_cmdstan_parquet() and as_cmdstan_fit() with a Parquet file --- tests/testthat/test-parquet.R | 112 ++++++++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) diff --git a/tests/testthat/test-parquet.R b/tests/testthat/test-parquet.R index bda508765..c2271bc64 100644 --- a/tests/testthat/test-parquet.R +++ b/tests/testthat/test-parquet.R @@ -37,6 +37,15 @@ expect_same_draws <- function(object, 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, @@ -123,6 +132,9 @@ test_that("cmdstan_csv_to_parquet() stores the CmdStan 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, @@ -159,6 +171,10 @@ test_that("cmdstan_csv_to_parquet() stores a dense metric", { 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", { @@ -266,6 +282,10 @@ test_that("cmdstan_csv_to_parquet() names tuple and complex variables", { 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", { @@ -340,6 +360,10 @@ test_that("cmdstan_csv_to_parquet() writes no warmup draws for fixed_param", { )) 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", { @@ -469,3 +493,91 @@ test_that("cmdstan_csv_to_parquet() checks its arguments", { "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, 0L) + 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 + expect_error(as_cmdstan_fit(out)$draws(inc_warmup = TRUE), "without them") + expect_error( + as_cmdstan_fit(files, warmup_file = out_warmup), + "can only be used with a Parquet file" + ) +}) From e0d53b9f87f7eb53b15dbcdb4fc1601ba1697a9f Mon Sep 17 00:00:00 2001 From: Aki Vehtari Date: Tue, 17 Nov 2026 17:19:42 +0200 Subject: [PATCH 11/14] Keep Parquet metadata exact and check the files in read_cmdstan_parquet() --- R/csv.R | 11 +- R/parquet.R | 190 ++++++++++++++++++++++++++-------- man/cmdstan_csv_to_parquet.Rd | 7 +- man/read_cmdstan_csv.Rd | 4 +- man/read_cmdstan_parquet.Rd | 9 +- 5 files changed, 165 insertions(+), 56 deletions(-) diff --git a/R/csv.R b/R/csv.R index eea3d1c2b..ff28b38e5 100644 --- a/R/csv.R +++ b/R/csv.R @@ -129,7 +129,9 @@ #' [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. +#' 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 @@ -464,8 +466,11 @@ as_cmdstan_fit <- function( format = getOption("cmdstanr_draws_format"), warmup_file = NULL ) { - is_parquet <- length(files) == 1 && - grepl("\\.parquet$", files, ignore.case = TRUE) + 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, diff --git a/R/parquet.R b/R/parquet.R index 220f62fd2..aed9feafd 100644 --- a/R/parquet.R +++ b/R/parquet.R @@ -58,8 +58,9 @@ #' readers (for example \pkg{arrow}, \pkg{duckdb} and \pkg{polars}) can also #' read the file. #' -#' The key-value metadata of the Parquet file has two entries: +#' The key-value metadata of the Parquet file has three 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`, @@ -70,7 +71,9 @@ #' `time` in seconds. 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. +#' 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()]. @@ -186,11 +189,12 @@ cmdstan_csv_to_parquet <- function( options = pq_options ) } else { + draws_kind <- if (identical(path, tmp_warmup)) "warmup" else "sampling" nanoparquet::write_parquet( x, path, compression = compression, - metadata = key_value, + metadata = c(key_value, stan.draws = draws_kind), options = pq_options ) } @@ -420,12 +424,14 @@ parquet_stan_metadata <- function(csv_metadata) { } 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 = NA, + digits = I(17), null = "null", - na = "null" + na = "string" )) } @@ -452,14 +458,15 @@ parquet_per_chain_fields <- c( #' @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()]). The default is -#' `NULL`, which reads no warmup draws and sets `metadata$save_warmup` to -#' `0`. +#' 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`. +#' `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 @@ -497,14 +504,32 @@ read_cmdstan_parquet <- function( 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 + ) + } } - format <- assert_valid_draws_format(format) - merged <- merge_csv_metadata(read_parquet_csv_metadata(file)) + csv_metadata <- parquet_csv_metadata(key_value$metadata) + merged <- merge_csv_metadata(csv_metadata) metadata <- merged$metadata - if (is.null(warmup_file)) { - metadata$save_warmup <- 0L + 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) @@ -546,19 +571,19 @@ read_cmdstan_parquet <- function( ) } -#' Rebuild the per-chain CSV metadata from the JSON of a Parquet file. +#' Read and check the key-value metadata of a Parquet file. #' #' @noRd #' @param file A Parquet file from `cmdstan_csv_to_parquet()`. -#' @return A list with one element for each chain, in the form of -#' `read_csv_metadata()` output, with the CSV variable names. +#' @param draws `"sampling"` or `"warmup"`, the expected `stan.draws` value. +#' @return A list with the JSON text `metadata`. #' -read_parquet_csv_metadata <- function(file) { +parquet_key_value <- function(file, draws) { kv <- nanoparquet::read_parquet_metadata( file )$file_meta_data$key_value_metadata[[1]] - version <- kv$value[kv$key == "stan.format_version"] - if (!identical(version, "1")) { + value <- function(key) kv$value[kv$key == key] + if (!identical(value("stan.format_version"), "1")) { stop( "'", file, @@ -567,21 +592,39 @@ read_parquet_csv_metadata <- function(file) { call. = FALSE ) } - json <- jsonlite::fromJSON( - kv$value[kv$key == "stan.metadata"], - simplifyVector = 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 <- drop_null(lapply(shared, json_to_r)) + shared <- parquet_drop_null(lapply(shared, parquet_json_to_r)) # the JSON has the repaired names; read_csv_metadata() gives the CSV names shared$variables <- unrepair_variable_names(shared$variables) lapply(json$chains, function(chain) { - chain <- drop_null(lapply(chain, json_to_r)) + chain <- parquet_drop_null(lapply(chain, parquet_json_to_r)) if (!is.null(chain$time)) { chain$time <- as.data.frame(chain$time) } @@ -589,20 +632,41 @@ read_parquet_csv_metadata <- function(file) { }) } -drop_null <- function(x) { +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 as doubles, booleans as integers 0 and 1, arrays as -#' vectors, arrays of arrays as matrices (rows), objects as named lists. -#' -json_to_r <- function(x) { - if (is.null(x) || is.character(x)) { +#' @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)) { @@ -612,22 +676,19 @@ json_to_r <- function(x) { return(as.numeric(x)) } if (!is.null(names(x))) { - return(lapply(x, json_to_r)) + 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, function(row) as.numeric(unlist(row))))) + return(do.call(rbind, lapply(x, to_numbers))) } - values <- unlist(x) - if (is.logical(values)) { - as.integer(values) - } else if (is.numeric(values)) { - as.numeric(values) - } else { - values + 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 @@ -651,19 +712,19 @@ read_parquet_chains <- function( if (length(columns) == 0) { return(list()) } - pq <- as.data.frame(nanoparquet::read_parquet( + pq <- as.list(nanoparquet::read_parquet( path, col_select = c(columns, ".chain", ".iteration") )) - if (nrow(pq) == 0) { + if (length(pq$.chain) == 0) { return(list()) } row_order <- order(pq$.chain, pq$.iteration) - if (is.unsorted(row_order)) { - pq <- pq[row_order, , drop = FALSE] + if (!is.unsorted(row_order)) { + row_order <- NULL } n_rows <- tabulate(pq$.chain, nbins = num_chains) - if (sum(n_rows) != nrow(pq) || any(n_rows != n_rows[1])) { + if (sum(n_rows) != length(pq$.chain) || any(n_rows != n_rows[1])) { stop( "The chains in '", path, @@ -671,6 +732,9 @@ read_parquet_chains <- function( 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) @@ -681,7 +745,9 @@ read_parquet_chains <- function( dimnames = list(NULL, NULL, names) ) for (j in seq_along(names)) { - out[,, j] <- pq[[names[j]]] + column <- pq[[names[j]]] + out[,, j] <- if (is.null(row_order)) column else column[row_order] + pq[[names[j]]] <<- NULL } out } @@ -713,10 +779,42 @@ CmdStanMCMC_Parquet <- R6::R6Class( }, 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_, diff --git a/man/cmdstan_csv_to_parquet.Rd b/man/cmdstan_csv_to_parquet.Rd index ec0611a40..1cbd06d14 100644 --- a/man/cmdstan_csv_to_parquet.Rd +++ b/man/cmdstan_csv_to_parquet.Rd @@ -80,9 +80,10 @@ reads only some of the variables. Include \code{.chain}, \code{.iteration} and readers (for example \pkg{arrow}, \pkg{duckdb} and \pkg{polars}) can also read the file. -The key-value metadata of the Parquet file has two entries: +The key-value metadata of the Parquet file has three 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}, @@ -93,7 +94,9 @@ the CmdStan version and the sampler arguments, and \code{variables}, \code{time} in seconds. 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. +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 diff --git a/man/read_cmdstan_csv.Rd b/man/read_cmdstan_csv.Rd index 9b81de126..0c6741d0e 100644 --- a/man/read_cmdstan_csv.Rd +++ b/man/read_cmdstan_csv.Rd @@ -172,7 +172,9 @@ produces an informative error. \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. +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 index 4c959fff7..fe2a432d5 100644 --- a/man/read_cmdstan_parquet.Rd +++ b/man/read_cmdstan_parquet.Rd @@ -37,15 +37,16 @@ The default depends on the method used to fit the model. See 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()}}). The default is -\code{NULL}, which reads no warmup draws and sets \code{metadata$save_warmup} to -\code{0}.} +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}. +\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 From a463745d843f37e3f0f767ba512091fda7dcc09f Mon Sep 17 00:00:00 2001 From: Aki Vehtari Date: Tue, 17 Nov 2026 17:19:47 +0200 Subject: [PATCH 12/14] Test exact metadata, one-parameter metrics and file checks of read_cmdstan_parquet() --- tests/testthat/test-parquet.R | 159 +++++++++++++++++++++++++++++++++- 1 file changed, 157 insertions(+), 2 deletions(-) diff --git a/tests/testthat/test-parquet.R b/tests/testthat/test-parquet.R index c2271bc64..103509d9d 100644 --- a/tests/testthat/test-parquet.R +++ b/tests/testthat/test-parquet.R @@ -531,7 +531,7 @@ test_that("read_cmdstan_parquet() gives the result of read_cmdstan_csv()", { x <- read_cmdstan_parquet(out) expect_null(x$warmup_draws) expect_null(x$warmup_sampler_diagnostics) - expect_identical(x$metadata$save_warmup, 0L) + expect_identical(x$metadata$save_warmup, 1L) expect_equal(x$post_warmup_draws, read_cmdstan_csv(files)$post_warmup_draws) }) @@ -575,9 +575,164 @@ test_that("as_cmdstan_fit() makes a fit from a Parquet file", { 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 - expect_error(as_cmdstan_fit(out)$draws(inc_warmup = TRUE), "without them") + 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("read_cmdstan_parquet() keeps the metadata values exact", { + # 18 significant digits and a nan in the inverse metric + fit <- testing_fit( + "logistic", + method = "sample", + seed = 123, + chains = 2, + iter_warmup = 100, + iter_sampling = 10, + sig_figs = 18 + ) + 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" + ) +}) From 2d1d970ffbf4f923fb60d75f9dc160f10df5cff3 Mon Sep 17 00:00:00 2001 From: Aki Vehtari Date: Tue, 17 Nov 2026 17:36:18 +0200 Subject: [PATCH 13/14] Store metadata values that differ between chains per chain in the Parquet file --- R/parquet.R | 69 ++++++++++++++++++++++++++--------- man/cmdstan_csv_to_parquet.Rd | 9 +++-- man/read_cmdstan_parquet.Rd | 6 ++- 3 files changed, 62 insertions(+), 22 deletions(-) diff --git a/R/parquet.R b/R/parquet.R index aed9feafd..883869f62 100644 --- a/R/parquet.R +++ b/R/parquet.R @@ -58,7 +58,7 @@ #' 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 entries: +#' 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 @@ -67,9 +67,10 @@ #' `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) and the -#' `time` in seconds. For the `fixed_param` sampler, `variables` and -#' `sampler_diagnostics` do not list the columns `lp__` and +#' `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"` @@ -393,17 +394,34 @@ parse_csv_lines <- function(lines, col_names, path, rows_before) { #' @return A JSON string. #' parquet_stan_metadata <- function(csv_metadata) { - per_chain <- parquet_per_chain_fields metadata <- csv_metadata[[1]] - out <- metadata[setdiff(names(metadata), per_chain)] - # read_csv_metadata() turns the CSV values true and false into integers; - # write them as JSON booleans - is_flag <- vapply( - out, - function(x) is.integer(x) && length(x) == 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) ) - out[is_flag] <- lapply(out[is_flag], as.logical) + 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) @@ -415,7 +433,7 @@ parquet_stan_metadata <- function(csv_metadata) { } out$num_chains <- length(csv_metadata) out$chains <- lapply(csv_metadata, function(x) { - chain <- x[intersect(per_chain, names(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) } @@ -484,7 +502,11 @@ parquet_per_chain_fields <- c( #' 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) +#' x <- read_cmdstan_parquet( +#' pq_file, +#' variables = "beta", +#' warmup_file = pq_warmup +#' ) #' str(x$post_warmup_draws) #' str(x$post_warmup_sampler_diagnostics) #' @@ -592,6 +614,15 @@ parquet_key_value <- function(file, draws) { 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( "'", @@ -620,9 +651,13 @@ parquet_csv_metadata <- function(json) { names(json), c("chains", "num_chains", "stan_variable_sizes") )] - shared <- parquet_drop_null(lapply(shared, parquet_json_to_r)) - # the JSON has the repaired names; read_csv_metadata() gives the CSV names - shared$variables <- unrepair_variable_names(shared$variables) + 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)) { diff --git a/man/cmdstan_csv_to_parquet.Rd b/man/cmdstan_csv_to_parquet.Rd index 1cbd06d14..0b68e6c50 100644 --- a/man/cmdstan_csv_to_parquet.Rd +++ b/man/cmdstan_csv_to_parquet.Rd @@ -80,7 +80,7 @@ reads only some of the variables. Include \code{.chain}, \code{.iteration} and 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 entries: +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}. @@ -90,9 +90,10 @@ 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) and the -\code{time} in seconds. For the \code{fixed_param} sampler, \code{variables} and -\code{sampler_diagnostics} do not list the columns \code{lp__} and +\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"} diff --git a/man/read_cmdstan_parquet.Rd b/man/read_cmdstan_parquet.Rd index fe2a432d5..13f6adf12 100644 --- a/man/read_cmdstan_parquet.Rd +++ b/man/read_cmdstan_parquet.Rd @@ -67,7 +67,11 @@ 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) +x <- read_cmdstan_parquet( + pq_file, + variables = "beta", + warmup_file = pq_warmup +) str(x$post_warmup_draws) str(x$post_warmup_sampler_diagnostics) From c2a8eabeade7a564c68846d29eb6e4faeeabf453 Mon Sep 17 00:00:00 2001 From: Aki Vehtari Date: Tue, 17 Nov 2026 17:36:24 +0200 Subject: [PATCH 14/14] Test the exact round trip of the Parquet metadata JSON --- tests/testthat/test-parquet.R | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/tests/testthat/test-parquet.R b/tests/testthat/test-parquet.R index 103509d9d..2ee4c6db0 100644 --- a/tests/testthat/test-parquet.R +++ b/tests/testthat/test-parquet.R @@ -597,16 +597,37 @@ test_that("as_cmdstan_fit() makes a fit from a Parquet file", { ) }) -test_that("read_cmdstan_parquet() keeps the metadata values exact", { - # 18 significant digits and a nan in the inverse metric +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, - sig_figs = 18 + iter_sampling = 10 ) files <- edit_csv_files(fit$output_files(), function(lines, i) { if (i == 2) {