diff --git a/CHANGELOG.md b/CHANGELOG.md index cbcd5f9e0e..24f41820a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,7 @@ For more information about this file see also [Keep a Changelog](http://keepacha - Added statewide synthetic fertilization and compost amendment event workflows for CA ag parcels. Outputs share an ensemble naming so a downstream cleaner unions them into one fertilization event type for SIPNET. ### Fixed +- `PEcAn.uncertainty::get.ensemble.samples()` matches `param.names` to PFTs by name, not position, and errors when parameters sampled jointly differ in length instead of returning truncated or `NA` draws (#4238). - `PEcAn.uncertainty::read.ensemble.output()` uses `NA` for missing variables, so each member’s result uses only its own output (#4204). - Fixed broken meteorological data, flux network, and API documentation links in the PEcAn book and data.atmosphere package (#4071). - `PEcAn.uncertainty::generate_joint_ensemble_design(sobol = TRUE)` now errors on looped inputs and quasi-random parameter methods, which split into dependent `X1` and `X2` halves and gave wrong Sobol indices (#4134). @@ -81,6 +82,7 @@ For more information about this file see also [Keep a Changelog](http://keepacha ### Changed +- `PEcAn.uncertainty::get.ensemble.samples()` now samples parameters jointly by default: each ensemble member takes all parameters of a PFT from one randomly drawn row of that PFT's samples. Set the new argument `independent = TRUE` to sample every parameter independently with `method`, the old default (#4238). - Sensitivity analysis runs are now written by `write.ensemble.configs`; `write.sa.configs` has been removed. The run design carries labels saying which parameter and quantile each run is, and the run ids, database entries and manifest rows are built from those. - Added `ensemble_downscale()`, a refactored version of `SDA_downscale()`. - `PEcAn.uncertainty::get.parameter.samples()`: replaced the `save_to_disk` flag (from #3860) with an `outdir` argument (default `settings$outdir`) controlling whether `samples.Rdata` is written; `outdir = NULL` skips the save. Existing callers are unaffected (@omkarrr2533, #4016) diff --git a/modules/uncertainty/NEWS.md b/modules/uncertainty/NEWS.md index 84d7500bc3..7b36a9c19a 100644 --- a/modules/uncertainty/NEWS.md +++ b/modules/uncertainty/NEWS.md @@ -1,5 +1,7 @@ # PEcAn.uncertainty 1.9.0.9000 +* `get.ensemble.samples()` now samples parameters jointly by default: each ensemble member takes all parameters of a PFT from one randomly drawn row of that PFT's samples. Set the new argument `independent = TRUE` to sample every parameter independently with `method`, the old default (#4238). +* `get.ensemble.samples()` matches `param.names` to PFTs by name, not position, and errors when parameters sampled jointly differ in length instead of returning truncated or `NA` draws (#4238). * `read.ensemble.output()` uses `NA` for missing variables, so each member’s result uses only its own output (#4204). * `generate_joint_ensemble_design(sobol = TRUE)` now errors when an input is sampled by `"looping"` or parameters by `"halton"` or `"sobol"`. These split into dependent `X1` and `X2` halves and gave wrong Sobol indices (#4134). * In `run.sensitivity.analysis()`, load `samples` once before the variables loop, avoiding repeated disk reads (#3859). diff --git a/modules/uncertainty/R/ensemble.R b/modules/uncertainty/R/ensemble.R index 494c65e9df..691f2234fd 100644 --- a/modules/uncertainty/R/ensemble.R +++ b/modules/uncertainty/R/ensemble.R @@ -77,23 +77,24 @@ read.ensemble.output <- function(ensemble.size, pecandir, outdir, start.year, en #' Get parameter values used in ensemble #' -#' Returns a matrix of randomly or quasi-randomly sampled trait values -#' to be assigned to traits over several model runs. -#' given the number of model runs and a list of sample distributions for traits -#' The model run is indexed first by model run, then by trait +#' Returns a matrix of randomly or quasi-randomly sampled parameter values +#' to be assigned to parameters over several model runs. +#' given the number of model runs and a list of sample distributions for parameters +#' The model run is indexed first by model run, then by parameter. #' #' @param ensemble.size number of runs in model ensemble -#' @param pft.samples random samples from parameter distribution, e.g. from a MCMC chain +#' @param pft.samples list named by PFT of random samples from parameter distribution, e.g. from a MCMC chain #' @param env.samples env samples -#' @param method the method used to generate the ensemble samples. Random generators: uniform, uniform with latin hypercube permutation. Quasi-random generators: halton, sobol, torus. Random generation draws random variates whereas quasi-random generation is deterministic but well equidistributed. Default is uniform. For small ensemble size with relatively large parameter number (e.g ensemble size < 5 and # of traits > 5) use methods other than halton. -#' @param param.names a list of parameter names that were fitted either by MA or PDA, important argument, if NULL parameters will be resampled independently +#' @param method the method used to generate the ensemble samples for parameters sampled independently. Random generators: random and uniform (the same uniform random draw), lhc (latin hypercube permutation). Quasi-random generators: halton, sobol. Random generation draws random variates whereas quasi-random generation is deterministic but well equidistributed. Default is random. For small ensemble size with relatively large parameter number (e.g ensemble size < 5 and # of parameters > 5) use methods other than halton. +#' @param param.names list named by PFT of the parameters that have joint samples, e.g. MCMC draws. If NULL (default), every parameter of each PFT. Used only when \code{independent = FALSE}, where these are drawn by row together and any others with \code{method}. +#' @param independent logical. If FALSE (default), parameters are sampled jointly within each PFT, preserving their correlations: each ensemble member takes all of them (or only those in \code{param.names}) from one row, drawn at random with replacement. If TRUE, every parameter is sampled independently using \code{method}, ignoring any joint structure. #' @param ... Other arguments passed on to the sampling method #' #' @return named list of data.frames with sampled indices as an attribute #' @export #' @author David LeBauer, Istem Fer get.ensemble.samples <- function( ensemble.size, pft.samples, env.samples, - method = "random", param.names = NULL, ...) { + method = "random", param.names = NULL, independent = FALSE, ...) { # Define supported methods supported_methods <- c("random", "uniform", "halton", "sobol", "lhc") @@ -108,6 +109,8 @@ get.ensemble.samples <- function( ensemble.size, pft.samples, env.samples, } else if (ensemble.size == 1) { ans <- PEcAn.utils::get.sa.sample.list(pft.samples, env.samples, 0.5) } else { + # resolved before `env` joins pft.samples, so env.samples are never drawn by row + if (is.null(param.names)) param.names <- lapply(pft.samples, names) pft.samples[[length(pft.samples) + 1]] <- env.samples names(pft.samples)[length(pft.samples)] <- "env" pft2col <- NULL @@ -160,40 +163,34 @@ get.ensemble.samples <- function( ensemble.size, pft.samples, env.samples, ensemble.samples[[pft.i]] <- matrix(nrow = ensemble.size, ncol = length(pft.samples[[pft.i]])) sampled.indices[[pft.i]] <- matrix(nrow = ensemble.size, ncol = length(pft.samples[[pft.i]])) - # meaning we want to keep MCMC samples together - if (length(pft.samples[[pft.i]]) > 0 && !is.null(param.names)) { - if (method == "halton") { - same.i <- floor(randtoolbox::halton(ensemble.size) * length(pft.samples[[pft.i]][[1]]))+1 - } else if (method == "sobol") { - same.i <- floor(randtoolbox::sobol(ensemble.size, scrambling = 3) * length(pft.samples[[pft.i]][[1]]))+1 - } else if (method == "torus") { - same.i <- floor(randtoolbox::torus(ensemble.size) * length(pft.samples[[pft.i]][[1]]))+1 - } else if (method == "lhc") { - same.i <- floor(c(PEcAn.emulator::lhc(t(matrix(0:1, ncol = 1, nrow = 2)), ensemble.size) * length(pft.samples[[pft.i]][[1]])))+1 - } else if (method == "uniform") { - same.i <- sample.int(length(pft.samples[[pft.i]][[1]]), ensemble.size) - } else if (method == "random") { - PEcAn.logger::logger.info("Using random row sampling for MCMC draws") - same.i <- sample(nrow(pft.samples[[pft.i]][[1]]), ensemble.size, replace = TRUE) - } else { - PEcAn.logger::logger.error("Sampling method %s is not recognized", method) + # TRUE for parameters sampled jointly: a member takes all of them from one row + by.row <- !independent & names(pft.samples[[pft.i]]) %in% param.names[[names(pft.samples)[pft.i]]] + if (any(by.row)) { + n.rows <- unique(lengths(pft.samples[[pft.i]][by.row])) + if (length(n.rows) > 1) { + PEcAn.logger::logger.severe( + "Parameters to sample jointly for PFT", names(pft.samples)[pft.i], + "differ in length:", toString(n.rows) + ) } + # draws whole rows, so a space-filling design over [0, 1] does not apply + same.i <- sample.int(n.rows, ensemble.size, replace = TRUE) } - for (trait.i in seq(pft.samples[[pft.i]])) { + for (param.i in seq(pft.samples[[pft.i]])) { col.i <- col.i + 1 - if (names(pft.samples[[pft.i]])[trait.i] %in% param.names[[pft.i]]) { - ensemble.samples[[pft.i]][, trait.i] <- pft.samples[[pft.i]][[trait.i]][same.i] - sampled.indices[[pft.i]][, trait.i] <- same.i + if (by.row[param.i]) { + ensemble.samples[[pft.i]][, param.i] <- pft.samples[[pft.i]][[param.i]][same.i] + sampled.indices[[pft.i]][, param.i] <- same.i } else { - # Extract original trait values - trait.values <- pft.samples[[pft.i]][[trait.i]] - sampled.values <- stats::quantile(trait.values, random.samples[, col.i]) + # Extract original parameter values + param.values <- pft.samples[[pft.i]][[param.i]] + sampled.values <- stats::quantile(param.values, random.samples[, col.i]) - ensemble.samples[[pft.i]][, trait.i] <- stats::quantile(pft.samples[[pft.i]][[trait.i]], + ensemble.samples[[pft.i]][, param.i] <- stats::quantile(pft.samples[[pft.i]][[param.i]], random.samples[, col.i]) - sampled.indices[[pft.i]][, trait.i] <- sapply(sampled.values, - function(val) {which.min(abs(trait.values - val)) }) + sampled.indices[[pft.i]][, param.i] <- sapply(sampled.values, + function(val) {which.min(abs(param.values - val)) }) } } ensemble.samples[[pft.i]] <- as.data.frame(ensemble.samples[[pft.i]]) diff --git a/modules/uncertainty/R/get_parameter_samples.R b/modules/uncertainty/R/get_parameter_samples.R index 70910fc54d..9ac6441f66 100644 --- a/modules/uncertainty/R/get_parameter_samples.R +++ b/modules/uncertainty/R/get_parameter_samples.R @@ -8,23 +8,25 @@ #' #' @param pft_names character vector of PFT names #' @param prior_distns_list list of data frames (one per PFT), each with -#' columns: distn, parama, paramb, n. Row names are trait names. -#' @param trait_mcmc_list list of trait MCMC results (one per PFT). +#' columns: distn, parama, paramb, n. Row names are parameter names. +#' @param trait_mcmc_list list of parameter MCMC results (one per PFT). #' Each element should be a named list of \code{coda::mcmc.list} objects, #' or NULL if no MCMC results exist for that PFT. #' @param ensemble.size integer. Number of runs in model ensemble. -#' @param ens.sample.method character. One of "halton", "sobol", "torus", -#' "lhc", "uniform". +#' @param ens.sample.method character. One of "random", "uniform", "lhc", +#' "halton", "sobol". #' @param sa_quantiles numeric vector of quantiles for sensitivity analysis, #' or NULL to skip SA sampling. #' @param do_ensemble logical. Whether to generate ensemble samples. -#' @param independent logical. TRUE means parameters were fitted individually -#' (standard MA) and can be resampled independently. FALSE means they were -#' fitted together (e.g. PDA) and correlations should be preserved. +#' @param independent logical. If FALSE (default), parameters with MCMC samples +#' are sampled jointly within each PFT, preserving their correlations (each +#' ensemble member takes one complete MCMC draw of a PFT). If TRUE, every +#' parameter is sampled independently using \code{ens.sample.method}, +#' ignoring any joint structure. #' #' @return named list with five elements: #' \describe{ -#' \item{trait.samples}{Named list by PFT, then by trait. Each leaf is a +#' \item{trait.samples}{Named list by PFT, then by parameter. Each leaf is a #' numeric vector of parameter samples.} #' \item{sa.samples}{Sensitivity analysis samples (list), or empty list #' if \code{sa_quantiles} is NULL.} @@ -69,7 +71,7 @@ get_parameter_samples <- function(pft_names, ens.sample.method = "uniform", sa_quantiles = NULL, do_ensemble = TRUE, - independent = TRUE) { + independent = FALSE) { # ---- Input validation ---- if (is.list(pft_names)) { @@ -103,9 +105,9 @@ get_parameter_samples <- function(pft_names, for (i in seq_along(pft_names)) { pft.name <- pft_names[i] prior.distns <- prior_distns_list[[i]] - trait.mcmc <- if (!is.null(trait_mcmc_list)) trait_mcmc_list[[i]] else NULL + param.mcmc <- if (!is.null(trait_mcmc_list)) trait_mcmc_list[[i]] else NULL - # Determine which traits have priors defined + # Determine which parameters have priors defined if (!is.null(prior.distns)) { priors <- rownames(prior.distns) } else { @@ -113,15 +115,15 @@ get_parameter_samples <- function(pft_names, } # Determine sample count: use MCMC chain length if available, else 20000 - if (!is.null(trait.mcmc) && length(trait.mcmc) > 0) { - param.names[[i]] <- names(trait.mcmc) + if (!is.null(param.mcmc) && length(param.mcmc) > 0) { + param.names[[i]] <- names(param.mcmc) names(param.names)[i] <- pft.name samples.num <- min( - sapply(trait.mcmc, function(x) nrow(as.matrix(x))) + sapply(param.mcmc, function(x) nrow(as.matrix(x))) ) - ## Report which traits use MA results vs priors + ## Report which parameters use MA results vs priors if (length(param.names[[i]]) > 0) { PEcAn.logger::logger.info( "PFT", pft.name, "has MCMC samples for:\n", @@ -149,11 +151,11 @@ get_parameter_samples <- function(pft_names, # If no priors defined, fall back to MCMC param names if (is.null(priors)) priors <- param.names[[i]] - PEcAn.logger::logger.info("using ", samples.num, " samples per trait") + PEcAn.logger::logger.info("using ", samples.num, " samples per parameter") n_priors <- length(priors) if (n_priors == 0) { - PEcAn.logger::logger.info("No traits to sample for PFT", pft.name) + PEcAn.logger::logger.info("No parameters to sample for PFT", pft.name) next } @@ -168,11 +170,11 @@ get_parameter_samples <- function(pft_names, q_samples <- matrix(q_samples, ncol = 1) } - # Sample each trait: from MCMC if available, otherwise from prior + # Sample each parameter: from MCMC if available, otherwise from prior for (prior in priors) { if (prior %in% param.names[[i]]) { # Extract MCMC samples across all chains - samples <- trait.mcmc[[prior]] |> + samples <- param.mcmc[[prior]] |> purrr::map(\(x) x[, "beta.o"]) |> unlist() |> as.matrix() @@ -188,14 +190,6 @@ get_parameter_samples <- function(pft_names, } } - # ---- Handle independence flag ---- - # When samples are independent (fitted individually), set param.names to NULL. - # This is important downstream: when param.names is not NULL, - # get.ensemble.samples() preserves correlations between MCMC parameters. - if (independent) { - param.names <- NULL - } - # ---- Sensitivity analysis samples ---- if (!is.null(sa_quantiles)) { # get.quantiles() expects a settings-style list with $quantile elements. @@ -231,7 +225,8 @@ get_parameter_samples <- function(pft_names, pft.samples = trait.samples, env.samples = env.samples, method = ens.sample.method, - param.names = param.names + param.names = param.names, + independent = independent ) } } @@ -252,7 +247,7 @@ get_parameter_samples <- function(pft_names, #' using the specified sampling method. #' #' @param n integer, number of samples -#' @param dim integer, number of dimensions (traits) +#' @param dim integer, number of dimensions (parameters) #' @param method character, sampling method #' @return matrix of dimension n x dim with values in [0, 1] #' @noRd diff --git a/modules/uncertainty/man/get.ensemble.samples.Rd b/modules/uncertainty/man/get.ensemble.samples.Rd index cdd050c18d..655be33db2 100644 --- a/modules/uncertainty/man/get.ensemble.samples.Rd +++ b/modules/uncertainty/man/get.ensemble.samples.Rd @@ -10,19 +10,22 @@ get.ensemble.samples( env.samples, method = "random", param.names = NULL, + independent = FALSE, ... ) } \arguments{ \item{ensemble.size}{number of runs in model ensemble} -\item{pft.samples}{random samples from parameter distribution, e.g. from a MCMC chain} +\item{pft.samples}{list named by PFT of random samples from parameter distribution, e.g. from a MCMC chain} \item{env.samples}{env samples} -\item{method}{the method used to generate the ensemble samples. Random generators: uniform, uniform with latin hypercube permutation. Quasi-random generators: halton, sobol, torus. Random generation draws random variates whereas quasi-random generation is deterministic but well equidistributed. Default is uniform. For small ensemble size with relatively large parameter number (e.g ensemble size < 5 and # of traits > 5) use methods other than halton.} +\item{method}{the method used to generate the ensemble samples for parameters sampled independently. Random generators: random and uniform (the same uniform random draw), lhc (latin hypercube permutation). Quasi-random generators: halton, sobol. Random generation draws random variates whereas quasi-random generation is deterministic but well equidistributed. Default is random. For small ensemble size with relatively large parameter number (e.g ensemble size < 5 and # of parameters > 5) use methods other than halton.} -\item{param.names}{a list of parameter names that were fitted either by MA or PDA, important argument, if NULL parameters will be resampled independently} +\item{param.names}{list named by PFT of the parameters that have joint samples, e.g. MCMC draws. If NULL (default), every parameter of each PFT. Used only when \code{independent = FALSE}, where these are drawn by row together and any others with \code{method}.} + +\item{independent}{logical. If FALSE (default), parameters are sampled jointly within each PFT, preserving their correlations: each ensemble member takes all of them (or only those in \code{param.names}) from one row, drawn at random with replacement. If TRUE, every parameter is sampled independently using \code{method}, ignoring any joint structure.} \item{...}{Other arguments passed on to the sampling method} } @@ -30,10 +33,10 @@ get.ensemble.samples( named list of data.frames with sampled indices as an attribute } \description{ -Returns a matrix of randomly or quasi-randomly sampled trait values -to be assigned to traits over several model runs. -given the number of model runs and a list of sample distributions for traits -The model run is indexed first by model run, then by trait +Returns a matrix of randomly or quasi-randomly sampled parameter values +to be assigned to parameters over several model runs. +given the number of model runs and a list of sample distributions for parameters +The model run is indexed first by model run, then by parameter. } \author{ David LeBauer, Istem Fer diff --git a/modules/uncertainty/man/get_parameter_samples.Rd b/modules/uncertainty/man/get_parameter_samples.Rd index 8686225a47..cacc7233a4 100644 --- a/modules/uncertainty/man/get_parameter_samples.Rd +++ b/modules/uncertainty/man/get_parameter_samples.Rd @@ -12,37 +12,39 @@ get_parameter_samples( ens.sample.method = "uniform", sa_quantiles = NULL, do_ensemble = TRUE, - independent = TRUE + independent = FALSE ) } \arguments{ \item{pft_names}{character vector of PFT names} \item{prior_distns_list}{list of data frames (one per PFT), each with -columns: distn, parama, paramb, n. Row names are trait names.} +columns: distn, parama, paramb, n. Row names are parameter names.} -\item{trait_mcmc_list}{list of trait MCMC results (one per PFT). +\item{trait_mcmc_list}{list of parameter MCMC results (one per PFT). Each element should be a named list of \code{coda::mcmc.list} objects, or NULL if no MCMC results exist for that PFT.} \item{ensemble.size}{integer. Number of runs in model ensemble.} -\item{ens.sample.method}{character. One of "halton", "sobol", "torus", -"lhc", "uniform".} +\item{ens.sample.method}{character. One of "random", "uniform", "lhc", +"halton", "sobol".} \item{sa_quantiles}{numeric vector of quantiles for sensitivity analysis, or NULL to skip SA sampling.} \item{do_ensemble}{logical. Whether to generate ensemble samples.} -\item{independent}{logical. TRUE means parameters were fitted individually -(standard MA) and can be resampled independently. FALSE means they were -fitted together (e.g. PDA) and correlations should be preserved.} +\item{independent}{logical. If FALSE (default), parameters with MCMC samples +are sampled jointly within each PFT, preserving their correlations (each +ensemble member takes one complete MCMC draw of a PFT). If TRUE, every +parameter is sampled independently using \code{ens.sample.method}, +ignoring any joint structure.} } \value{ named list with five elements: \describe{ - \item{trait.samples}{Named list by PFT, then by trait. Each leaf is a + \item{trait.samples}{Named list by PFT, then by parameter. Each leaf is a numeric vector of parameter samples.} \item{sa.samples}{Sensitivity analysis samples (list), or empty list if \code{sa_quantiles} is NULL.} diff --git a/modules/uncertainty/tests/testthat/test-get_parameter_samples.R b/modules/uncertainty/tests/testthat/test-get_parameter_samples.R index e964921c8d..5dec6e24a1 100644 --- a/modules/uncertainty/tests/testthat/test-get_parameter_samples.R +++ b/modules/uncertainty/tests/testthat/test-get_parameter_samples.R @@ -11,25 +11,25 @@ skip_if_not_installed("PEcAn.utils") skip_if_not_installed("PEcAn.logger") # ---- Helper: create mock prior distributions ---- -make_mock_priors <- function(traits = c("SLA", "Vcmax")) { +make_mock_priors <- function(params = c("SLA", "Vcmax")) { data.frame( - distn = rep("norm", length(traits)), - parama = c(20, 40)[seq_along(traits)], - paramb = c(5, 10)[seq_along(traits)], - n = c(50, 30)[seq_along(traits)], - row.names = traits, + distn = rep("norm", length(params)), + parama = c(20, 40)[seq_along(params)], + paramb = c(5, 10)[seq_along(params)], + n = c(50, 30)[seq_along(params)], + row.names = params, stringsAsFactors = FALSE ) } # ---- Helper: create mock MCMC results ---- -make_mock_trait_mcmc <- function(traits = "SLA", n_samples = 100, seed = 42) { +make_mock_mcmc <- function(params = "SLA", n_samples = 100, seed = 42) { set.seed(seed) result <- list() - for (trait in traits) { + for (param in params) { chain <- matrix(rnorm(n_samples, mean = 20, sd = 2), ncol = 1) colnames(chain) <- "beta.o" - result[[trait]] <- coda::mcmc.list(coda::mcmc(chain)) + result[[param]] <- coda::mcmc.list(coda::mcmc(chain)) } result } @@ -121,7 +121,7 @@ test_that("prior-only sampling produces correct structure", { # ==================== test_that("MCMC samples are used when available", { priors <- make_mock_priors(c("SLA", "Vcmax")) - mcmc <- make_mock_trait_mcmc("SLA", n_samples = 200) + mcmc <- make_mock_mcmc("SLA", n_samples = 200) result <- get_parameter_samples( pft_names = "test_pft", @@ -263,28 +263,32 @@ test_that("different sampling methods all produce valid output", { # ==================== # TEST 10: Independent flag behavior # ==================== -test_that("independent = FALSE preserves param.names for correlated sampling", { - priors <- make_mock_priors("SLA") - mcmc <- make_mock_trait_mcmc("SLA", n_samples = 100) +# b is exactly 2 * a in every row, so a member drawn by whole row keeps b == 2 * a +make_joint_mcmc <- function(n = 100) { + a <- stats::rnorm(n) + chain <- function(x) coda::mcmc.list(coda::mcmc(matrix(x, dimnames = list(NULL, "beta.o")))) + list(a = chain(a), b = chain(2 * a)) +} - result_ind <- get_parameter_samples( - pft_names = "test_pft", - prior_distns_list = list(priors), - trait_mcmc_list = list(mcmc), - ensemble.size = 10, - do_ensemble = TRUE, - independent = TRUE +test_that("by default MCMC rows stay together, even after an empty PFT", { + result <- get_parameter_samples( + pft_names = c("empty", "joint"), + prior_distns_list = list(NULL, NULL), + trait_mcmc_list = list(NULL, make_joint_mcmc()), + ensemble.size = 20 ) + x <- result$ensemble.samples$joint + expect_equal(x$b, 2 * x$a) +}) - result_dep <- get_parameter_samples( - pft_names = "test_pft", - prior_distns_list = list(priors), - trait_mcmc_list = list(mcmc), - ensemble.size = 10, - do_ensemble = TRUE, - independent = FALSE +test_that("independent = TRUE does not keep MCMC rows together", { + result <- get_parameter_samples( + pft_names = "joint", + prior_distns_list = list(NULL), + trait_mcmc_list = list(make_joint_mcmc()), + ensemble.size = 20, + independent = TRUE ) - - expect_false(is.null(result_ind$ensemble.samples)) - expect_false(is.null(result_dep$ensemble.samples)) + apart <- result$ensemble.samples$joint + expect_false(isTRUE(all.equal(apart$b, 2 * apart$a))) }) diff --git a/modules/uncertainty/tests/testthat/test_ensemble.R b/modules/uncertainty/tests/testthat/test_ensemble.R index 5e070cf208..aab49d7a56 100644 --- a/modules/uncertainty/tests/testthat/test_ensemble.R +++ b/modules/uncertainty/tests/testthat/test_ensemble.R @@ -160,3 +160,33 @@ test_that("get.ensemble.samples", { # pft_samp has 5 rows -> all indices <= 5 expect_true(all(sapply(res_idx, \(mat)all(mat %in% 1:5)))) }) + +test_that("get.ensemble.samples by default draws every parameter of a PFT from one row", { + # 20 members from 10 rows, so rows are drawn with replacement + a <- stats::rnorm(10) + pft_samp <- list(p = list(a = a, b = 2 * a, c = -a)) + res <- get.ensemble.samples(20, pft_samp, list(x = a, y = 2 * a)) + expect_equal(res$p$b, 2 * res$p$a) + expect_equal(res$p$c, -res$p$a) + expect_true(all(res$p$a %in% a)) + # env.samples belong to no PFT, so they are still sampled independently + expect_false(isTRUE(all.equal(res$env$y, 2 * res$env$x))) +}) + +test_that("get.ensemble.samples draws the parameters in param.names by whole row", { + a <- stats::rnorm(50) + pft_samp <- list(p = list(a = a, b = 2 * a, c = -a)) + res <- get.ensemble.samples(20, pft_samp, list(), param.names = list(p = c("a", "b"))) + expect_equal(res$p$b, 2 * res$p$a) + expect_true(all(res$p$a %in% a)) + # c is not listed, so it does not follow the row of a and b + expect_false(isTRUE(all.equal(res$p$c, -res$p$a))) +}) + +test_that("get.ensemble.samples rejects parameters sampled jointly that differ in length", { + pft_samp <- list(p = list(a = 1:5, b = 1:4)) + expect_error( + get.ensemble.samples(3, pft_samp, list(), param.names = list(p = c("a", "b"))), + "differ in length: 5, 4" + ) +})