From c35a499bf595aae115dd44d779d8654acd82be37 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 10 Nov 2026 19:24:55 -0500 Subject: [PATCH 01/82] read joint flag from trait.mcmc attribute --- modules/uncertainty/R/load_posteriors.R | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/modules/uncertainty/R/load_posteriors.R b/modules/uncertainty/R/load_posteriors.R index 351bf9eec78..46918e5e19f 100644 --- a/modules/uncertainty/R/load_posteriors.R +++ b/modules/uncertainty/R/load_posteriors.R @@ -17,8 +17,12 @@ #' @param hostname \strong{Deprecated.} Hostname for DB file lookup, used #' only in the legacy fallback path. #' @return list with \code{prior.distns}, \code{trait.mcmc}, \code{is.joint}. -#' \code{is.joint} is \code{TRUE} when MCMC samples represent a joint -#' posterior (e.g. from PDA) and parameter correlations should be preserved. +#' \code{is.joint} is \code{TRUE} when each row of the MCMC samples is one +#' joint draw across traits, so rows must be kept together: either the +#' samples carry \code{attr(trait.mcmc, "joint") <- TRUE}, or they come from +#' PDA (a \code{mcmc.pda.*} file next to them, or "pda" in the file name on +#' the legacy path). Other MCMC samples, such as meta-analysis output, are +#' sampled one trait at a time. #' @keywords internal #' @author Siddhey Patil load.posteriors <- function(posterior.file, @@ -110,6 +114,7 @@ load.posteriors.from.path <- function(path) { "Found Monte Carlo samples (", obj_name, ") in: ", f ) result$trait.mcmc <- obj + result$is.joint <- isTRUE(attr(obj, "joint")) break } # Single mcmc.list (not wrapped in a named list) @@ -252,7 +257,7 @@ load.posteriors.legacy <- function(outdir = NULL, # In the legacy DB path, detect joint posterior via filename # heuristic (PDA convention: trait.mcmc.pda.*) fname_lower <- tolower(files$file_name[idx]) - if (grepl("pda", fname_lower)) { + if (isTRUE(attr(result$trait.mcmc, "joint")) || grepl("pda", fname_lower)) { result$is.joint <- TRUE } break # Use first MCMC found @@ -283,7 +288,7 @@ load.posteriors.legacy <- function(outdir = NULL, # In the legacy outdir-scan path, detect joint posterior via # filename heuristic (PDA convention: trait.mcmc.pda.*) fname_lower <- tolower(basename(f)) - if (grepl("pda", fname_lower)) { + if (isTRUE(attr(result$trait.mcmc, "joint")) || grepl("pda", fname_lower)) { result$is.joint <- TRUE } break From 1182f19a6fa81d69427fcfabad4ba9ca88626617 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 10 Nov 2026 19:24:55 -0500 Subject: [PATCH 02/82] document joint attribute in load.posteriors --- modules/uncertainty/man/load.posteriors.Rd | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/modules/uncertainty/man/load.posteriors.Rd b/modules/uncertainty/man/load.posteriors.Rd index 13a295765eb..0d425c8ccc2 100644 --- a/modules/uncertainty/man/load.posteriors.Rd +++ b/modules/uncertainty/man/load.posteriors.Rd @@ -30,8 +30,12 @@ only in the legacy fallback path.} } \value{ list with \code{prior.distns}, \code{trait.mcmc}, \code{is.joint}. - \code{is.joint} is \code{TRUE} when MCMC samples represent a joint - posterior (e.g. from PDA) and parameter correlations should be preserved. + \code{is.joint} is \code{TRUE} when each row of the MCMC samples is one + joint draw across traits, so rows must be kept together: either the + samples carry \code{attr(trait.mcmc, "joint") <- TRUE}, or they come from + PDA (a \code{mcmc.pda.*} file next to them, or "pda" in the file name on + the legacy path). Other MCMC samples, such as meta-analysis output, are + sampled one trait at a time. } \description{ Detects posterior type by file contents, not filenames. From e63c45c937246be41b495f72666f1fda3ae18600 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 10 Nov 2026 19:24:55 -0500 Subject: [PATCH 03/82] return independent flag per pft --- modules/uncertainty/R/load_pft_posteriors.R | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/modules/uncertainty/R/load_pft_posteriors.R b/modules/uncertainty/R/load_pft_posteriors.R index e5f8e314704..b5995615389 100644 --- a/modules/uncertainty/R/load_pft_posteriors.R +++ b/modules/uncertainty/R/load_pft_posteriors.R @@ -9,9 +9,9 @@ #' #' Posterior type is detected by content, not filename, via #' \code{\link{load.posteriors}}: MCMC chains take precedence over distribution -#' summaries. When a PFT's posterior is a joint fit (e.g. from PDA), the -#' returned \code{independent} flag is set to \code{FALSE} so downstream -#' sampling preserves the parameter correlations. +#' summaries. When a PFT's posterior is joint (see \code{\link{load.posteriors}}), +#' its entry in the returned \code{independent} flag is \code{FALSE} so +#' downstream sampling keeps its MCMC rows together. #' #' @param settings PEcAn settings object. Uses \code{settings$pfts} (name, #' outdir, posteriorid per PFT), \code{settings$database$bety} for the @@ -26,8 +26,8 @@ #' PFT (\code{NULL} entry where none was found).} #' \item{trait_mcmc_list}{list of trait MCMC results, one per PFT #' (\code{NULL} entry where the PFT has no MCMC chains).} -#' \item{independent}{logical, \code{FALSE} if any PFT carries a joint -#' posterior, \code{TRUE} otherwise.} +#' \item{independent}{logical vector, one per PFT: \code{FALSE} where the +#' PFT carries a joint posterior, \code{TRUE} otherwise.} #' } #' #' @seealso \code{\link{get_parameter_samples}} for the sampling step that @@ -88,7 +88,7 @@ load_pft_posteriors <- function(settings, ## Load priors and posteriors for each PFT prior_distns_list <- vector("list", length(pft.names)) trait_mcmc_list <- vector("list", length(pft.names)) - independent <- TRUE + independent <- rep(TRUE, length(pft.names)) for (i in seq_along(pft.names)) { posterior <- load.posteriors( @@ -105,10 +105,9 @@ load_pft_posteriors <- function(settings, if (!is.null(posterior$trait.mcmc)) { trait_mcmc_list[[i]] <- posterior$trait.mcmc - # Joint posteriors (e.g. from PDA) should preserve correlations - if (posterior$is.joint) { - independent <- FALSE - } + # Per PFT, so one joint posterior doesn't tie together the rows of + # another PFT's meta-analysis chains + independent[i] <- !posterior$is.joint } # else trait_mcmc_list[[i]] stays NULL } From 3abde1c41adc438a789f2fb98132ecbbb64255b9 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 10 Nov 2026 19:24:55 -0500 Subject: [PATCH 04/82] document per pft independent flag --- modules/uncertainty/man/load_pft_posteriors.Rd | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/modules/uncertainty/man/load_pft_posteriors.Rd b/modules/uncertainty/man/load_pft_posteriors.Rd index a1d82ed60b4..c7c46d9e116 100644 --- a/modules/uncertainty/man/load_pft_posteriors.Rd +++ b/modules/uncertainty/man/load_pft_posteriors.Rd @@ -22,8 +22,8 @@ A list with four elements: PFT (\code{NULL} entry where none was found).} \item{trait_mcmc_list}{list of trait MCMC results, one per PFT (\code{NULL} entry where the PFT has no MCMC chains).} - \item{independent}{logical, \code{FALSE} if any PFT carries a joint - posterior, \code{TRUE} otherwise.} + \item{independent}{logical vector, one per PFT: \code{FALSE} where the + PFT carries a joint posterior, \code{TRUE} otherwise.} } } \description{ @@ -37,9 +37,9 @@ their own copy. \details{ Posterior type is detected by content, not filename, via \code{\link{load.posteriors}}: MCMC chains take precedence over distribution -summaries. When a PFT's posterior is a joint fit (e.g. from PDA), the -returned \code{independent} flag is set to \code{FALSE} so downstream -sampling preserves the parameter correlations. +summaries. When a PFT's posterior is joint (see \code{\link{load.posteriors}}), +its entry in the returned \code{independent} flag is \code{FALSE} so +downstream sampling keeps its MCMC rows together. } \seealso{ \code{\link{get_parameter_samples}} for the sampling step that From cb720ed6fdabc9662e5c6888b5eba9ec15acb1ed Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 10 Nov 2026 19:24:56 -0500 Subject: [PATCH 05/82] accept per pft independent, match param.names by pft name --- modules/uncertainty/R/get_parameter_samples.R | 33 ++++++++++++++----- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/modules/uncertainty/R/get_parameter_samples.R b/modules/uncertainty/R/get_parameter_samples.R index 70910fc54d9..9499049af84 100644 --- a/modules/uncertainty/R/get_parameter_samples.R +++ b/modules/uncertainty/R/get_parameter_samples.R @@ -18,9 +18,11 @@ #' @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, one value for all PFTs or one per PFT. TRUE +#' means the PFT's MCMC samples are resampled one trait at a time (e.g. +#' meta-analysis, where each trait is fit separately). FALSE means each row +#' is one joint draw across traits (e.g. PDA), so ensemble members take whole +#' rows; PFTs with the same number of rows share one row index. #' #' @return named list with five elements: #' \describe{ @@ -87,6 +89,12 @@ get_parameter_samples <- function(pft_names, length(trait_mcmc_list) == length(pft_names) ) } + stopifnot( + is.logical(independent), + !anyNA(independent), + length(independent) %in% c(1, length(pft_names)) + ) + independent <- rep_len(independent, length(pft_names)) # Force numeric for compatibility with downstream sampling code ensemble.size <- as.numeric(ensemble.size) @@ -189,11 +197,20 @@ 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 + # param.names tells get.ensemble.samples() which traits to keep together by + # row, matched to trait.samples by position. Keep it only for PFTs whose rows + # are joint draws, and only for PFTs that made it into trait.samples (a PFT + # with nothing to sample is skipped above). + joint.names <- stats::setNames( + lapply(seq_along(pft_names), function(i) { + if (independent[i]) character(0) else unlist(param.names[[i]]) + }), + pft_names + ) + param.names <- if (any(lengths(joint.names) > 0)) { + joint.names[names(trait.samples)] + } else { + NULL } # ---- Sensitivity analysis samples ---- From 3e9729ac419f1acaa4dc20c90fc11294864cbb24 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 10 Nov 2026 19:24:56 -0500 Subject: [PATCH 06/82] document per pft independent in get_parameter_samples --- modules/uncertainty/man/get_parameter_samples.Rd | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/modules/uncertainty/man/get_parameter_samples.Rd b/modules/uncertainty/man/get_parameter_samples.Rd index 8686225a47e..eaa3fa5c8c8 100644 --- a/modules/uncertainty/man/get_parameter_samples.Rd +++ b/modules/uncertainty/man/get_parameter_samples.Rd @@ -35,9 +35,11 @@ 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, one value for all PFTs or one per PFT. TRUE +means the PFT's MCMC samples are resampled one trait at a time (e.g. +meta-analysis, where each trait is fit separately). FALSE means each row +is one joint draw across traits (e.g. PDA), so ensemble members take whole +rows; PFTs with the same number of rows share one row index.} } \value{ named list with five elements: From a222719f022d80dc8f29ceb739d8fb88c6cbecfa Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 10 Nov 2026 19:24:56 -0500 Subject: [PATCH 07/82] share joint row index across pfts, check row counts, fix random method --- modules/uncertainty/R/ensemble.R | 52 +++++++++++++++++++++----------- 1 file changed, 34 insertions(+), 18 deletions(-) diff --git a/modules/uncertainty/R/ensemble.R b/modules/uncertainty/R/ensemble.R index 746457ac3f8..c7674b80d3f 100644 --- a/modules/uncertainty/R/ensemble.R +++ b/modules/uncertainty/R/ensemble.R @@ -69,7 +69,7 @@ read.ensemble.output <- function(ensemble.size, pecandir, outdir, start.year, en #' @param pft.samples 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 param.names a list, one element per PFT in the order of \code{pft.samples}, naming the traits whose samples are joint draws (one row per draw). Those traits are sampled by whole rows, with one row index shared by all PFTs that have the same number of rows. If NULL, every trait is resampled independently. #' @param ... Other arguments passed on to the sampling method #' #' @return named list of data.frames with sampled indices as an attribute @@ -137,35 +137,51 @@ get.ensemble.samples <- function( ensemble.size, pft.samples, env.samples, ensemble.samples <- list() sampled.indices <- list() + joint.rows <- list() col.i <- 0 for (pft.i in seq(pft.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") { + # Traits in param.names are joint draws, so a member takes a whole row. + # PFTs with the same number of rows share one row index, so rows drawn + # together across PFTs also stay together. + joint.traits <- intersect(names(pft.samples[[pft.i]]), unlist(param.names[pft.i])) + if (length(joint.traits) > 0) { + n.rows <- unique(lengths(pft.samples[[pft.i]][joint.traits])) + if (length(n.rows) != 1) { + PEcAn.logger::logger.severe( + "Joint samples for PFT", names(pft.samples)[pft.i], + "need the same number of rows for every trait, got", + paste(n.rows, collapse = ", ") + ) + } + key <- as.character(n.rows) + if (is.null(joint.rows[[key]])) { + if (method == "halton") { + joint.rows[[key]] <- floor(randtoolbox::halton(ensemble.size) * n.rows) + 1 + } else if (method == "sobol") { + joint.rows[[key]] <- floor(randtoolbox::sobol(ensemble.size, scrambling = 3) * n.rows) + 1 + } else if (method == "torus") { + joint.rows[[key]] <- floor(randtoolbox::torus(ensemble.size) * n.rows) + 1 + } else if (method == "lhc") { + joint.rows[[key]] <- floor(c(PEcAn.emulator::lhc(t(matrix(0:1, ncol = 1, nrow = 2)), ensemble.size) * n.rows)) + 1 + } else if (method == "uniform") { + joint.rows[[key]] <- sample.int(n.rows, 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) + joint.rows[[key]] <- sample.int(n.rows, ensemble.size, replace = TRUE) + } else { + PEcAn.logger::logger.error("Sampling method %s is not recognized", method) + } } + same.i <- joint.rows[[key]] } for (trait.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]]) { + if (names(pft.samples[[pft.i]])[trait.i] %in% joint.traits) { ensemble.samples[[pft.i]][, trait.i] <- pft.samples[[pft.i]][[trait.i]][same.i] sampled.indices[[pft.i]][, trait.i] <- same.i } else { From 71f8328f19952a20b1b55e8d0f2a3c94e7f1f773 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 10 Nov 2026 19:24:56 -0500 Subject: [PATCH 08/82] update param.names doc for joint rows --- modules/uncertainty/man/get.ensemble.samples.Rd | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/uncertainty/man/get.ensemble.samples.Rd b/modules/uncertainty/man/get.ensemble.samples.Rd index cdd050c18d3..7877ed509d6 100644 --- a/modules/uncertainty/man/get.ensemble.samples.Rd +++ b/modules/uncertainty/man/get.ensemble.samples.Rd @@ -22,7 +22,7 @@ get.ensemble.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{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}{a list, one element per PFT in the order of \code{pft.samples}, naming the traits whose samples are joint draws (one row per draw). Those traits are sampled by whole rows, with one row index shared by all PFTs that have the same number of rows. If NULL, every trait is resampled independently.} \item{...}{Other arguments passed on to the sampling method} } From 86e33ebf50747687db7d020fc3ecfb5e2db74558 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 10 Nov 2026 19:24:56 -0500 Subject: [PATCH 09/82] test joint attribute and per pft flag --- .../tests/testthat/test.load_posteriors.R | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/modules/uncertainty/tests/testthat/test.load_posteriors.R b/modules/uncertainty/tests/testthat/test.load_posteriors.R index 46005e5b15a..6854e7ca024 100644 --- a/modules/uncertainty/tests/testthat/test.load_posteriors.R +++ b/modules/uncertainty/tests/testthat/test.load_posteriors.R @@ -283,6 +283,23 @@ test_that("non-PDA mcmc is not detected as joint", { }) +test_that("mcmc marked joint is detected as joint", { + tmpdir <- withr::local_tempdir() + + trait.mcmc <- make_trait_mcmc(trait_a = rnorm(100), trait_b = rnorm(100)) + attr(trait.mcmc, "joint") <- TRUE + save(trait.mcmc, file = file.path(tmpdir, "trait.mcmc.Rdata")) + + result <- load.posteriors(posterior.file = tmpdir) + expect_true(result$is.joint) + + invisible(capture.output( + legacy <- load.posteriors(posterior.file = NA, outdir = tmpdir) + )) + expect_true(legacy$is.joint) +}) + + test_that("joint detection works via filename heuristic in legacy path", { tmpdir <- withr::local_tempdir() @@ -315,3 +332,21 @@ test_that("MCMC detected by coda class, not variable name", { expect_is(result$trait.mcmc, "list") expect_equal(names(result$trait.mcmc), "SLA") }) + + +test_that("load_pft_posteriors flags joint posteriors per PFT", { + joint_dir <- withr::local_tempdir() + ma_dir <- withr::local_tempdir() + + trait.mcmc <- make_trait_mcmc(trait_a = rnorm(100)) + save(trait.mcmc, file = file.path(ma_dir, "trait.mcmc.Rdata")) + attr(trait.mcmc, "joint") <- TRUE + save(trait.mcmc, file = file.path(joint_dir, "trait.mcmc.Rdata")) + + settings <- list(pfts = list(list(name = "joint_pft"), list(name = "ma_pft"))) + invisible(capture.output( + loaded <- load_pft_posteriors(settings, c(joint_dir, ma_dir)) + )) + + expect_identical(loaded$independent, c(FALSE, TRUE)) +}) From 9b945cc83c4ad4647c1d9fdfe6d1d4816cd11d7d Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 10 Nov 2026 19:24:56 -0500 Subject: [PATCH 10/82] test joint rows across pfts --- .../testthat/test-get_parameter_samples.R | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/modules/uncertainty/tests/testthat/test-get_parameter_samples.R b/modules/uncertainty/tests/testthat/test-get_parameter_samples.R index e964921c8d4..92a49503b14 100644 --- a/modules/uncertainty/tests/testthat/test-get_parameter_samples.R +++ b/modules/uncertainty/tests/testthat/test-get_parameter_samples.R @@ -288,3 +288,80 @@ test_that("independent = FALSE preserves param.names for correlated sampling", { expect_false(is.null(result_ind$ensemble.samples)) expect_false(is.null(result_dep$ensemble.samples)) }) + + +# TEST 11: Joint MCMC samples keep their rows +# Two traits that are exact mirror images row by row, so any member that +# mixes rows breaks b == -a +make_paired_mcmc <- function(n_samples = 200, shift = 0, seed = 1) { + set.seed(seed) + a <- rnorm(n_samples) + lapply(list(a = a + shift, b = -a - shift), function(x) { + coda::mcmc.list(coda::mcmc(matrix(x, ncol = 1, dimnames = list(NULL, "beta.o")))) + }) +} + +test_that("joint PFT keeps rows together, independent PFT does not", { + result <- get_parameter_samples( + pft_names = c("joint_pft", "ma_pft"), + prior_distns_list = list(NULL, NULL), + trait_mcmc_list = list(make_paired_mcmc(), make_paired_mcmc()), + ensemble.size = 50, + do_ensemble = TRUE, + independent = c(FALSE, TRUE) + ) + joint <- result$ensemble.samples$joint_pft + ma <- result$ensemble.samples$ma_pft + + expect_equal(joint$b, -joint$a) + expect_true(all(joint$a %in% result$trait.samples$joint_pft$a)) + expect_false(isTRUE(all.equal(ma$b, -ma$a))) +}) + +test_that("joint PFTs with the same number of rows share a row index", { + for (method in c("uniform", "random", "halton")) { + result <- get_parameter_samples( + pft_names = c("pft1", "pft2"), + prior_distns_list = list(NULL, NULL), + trait_mcmc_list = list(make_paired_mcmc(), make_paired_mcmc(shift = 100)), + ensemble.size = 50, + ens.sample.method = method, + do_ensemble = TRUE, + independent = FALSE + ) + expect_equal( + result$ensemble.samples$pft2$a, + result$ensemble.samples$pft1$a + 100, + info = method + ) + } +}) + +test_that("a PFT with nothing to sample does not shift joint rows", { + result <- get_parameter_samples( + pft_names = c("empty_pft", "joint_pft"), + prior_distns_list = list(NULL, NULL), + trait_mcmc_list = list(NULL, make_paired_mcmc()), + ensemble.size = 50, + do_ensemble = TRUE, + independent = FALSE + ) + joint <- result$ensemble.samples$joint_pft + expect_equal(joint$b, -joint$a) +}) + +test_that("joint traits with different numbers of rows fail", { + mcmc <- make_paired_mcmc() + mcmc$b <- coda::mcmc.list(coda::mcmc(mcmc$b[[1]][1:150, , drop = FALSE])) + expect_error( + get_parameter_samples( + pft_names = "joint_pft", + prior_distns_list = list(NULL), + trait_mcmc_list = list(mcmc), + ensemble.size = 50, + do_ensemble = TRUE, + independent = FALSE + ), + "same number of rows" + ) +}) From 0b47b4ca22060fb0de8865c28ce8dc8a2552c830 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 10 Nov 2026 19:24:56 -0500 Subject: [PATCH 11/82] add joint mcmc sampling to changelog --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e14e5b8155..826930b45a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,8 @@ For more information about this file see also [Keep a Changelog](http://keepacha ### Added +- `PEcAn.uncertainty`: MCMC samples can be marked as joint draws with `attr(trait.mcmc, "joint") <- TRUE`. Ensemble members then take whole rows of the samples instead of resampling each trait on its own, and PFTs with the same number of rows share one row index. Other MCMC samples, such as meta-analysis output, are still resampled one trait at a time; PDA output is still recognized as joint. + - `PEcAn.settings::setEnsemblePaths()` can now include site-specific components in the paths it generates (#4100). - `PEcAn.SIPNET::model2netcdf.SIPNET()` now also writes `soil_organic_carbon_content` (soil pool only, excluding litter) alongside `TotSoilCarb` (soil + litter) (#4160). - Added regression tests to `PEcAn.settings` confirming `check.ensemble.settings()` does not add an `ensemble` block to settings that lack one (#3024). @@ -48,6 +50,8 @@ 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`: joint sampling is now decided per PFT. Before, one PDA posterior made every PFT's MCMC samples be resampled by row, and each PFT drew its own rows; a PFT with nothing to sample could also shift which PFT's trait list was used for the next one, and `method = "random"` failed with "invalid first argument" when a joint PFT sat next to one sampled from priors (#3674). - `PEcAn.utils::match_file()` anchors file prefixes to the beginning of the filename, so a request for `foo/site1` no longer matches `foo/old-site1` (but still finds `foo/site1-old` as previously) (#4196, @Shubham-Padkonde). - PEcAnAssimSequential: `simple.local()` and `piecew.poly.local()` now scale distances by their `scalef` argument instead of the undefined `rloc`; `GEF()`, `GEF.MultiSite()` and `EnKF.MultiSite()` read their extra arguments from `...` explicitly instead of assigning them into the global environment; `SDA_remote_launcher()` no longer references an undefined `stop.on.error`. Together these clear most of the package's "no visible binding for global variable" check notes (#2758). - `PEcAn.SIPNET::write.config.SIPNET()` wrote `stem_respiration_rate` and `root_respiration_rate` as per day rates into SIPNET's per year `baseVegResp` and `baseFineRootResp`, 365x too low. From 775064e2f863da26923ded364b70d6566e1ec28d Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 10 Nov 2026 19:24:56 -0500 Subject: [PATCH 12/82] add joint mcmc sampling to uncertainty news --- modules/uncertainty/NEWS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/uncertainty/NEWS.md b/modules/uncertainty/NEWS.md index b2bae33c81e..d394370e6e9 100644 --- a/modules/uncertainty/NEWS.md +++ b/modules/uncertainty/NEWS.md @@ -1,5 +1,6 @@ # PEcAn.uncertainty 1.9.0.9000 +* MCMC samples marked with `attr(trait.mcmc, "joint") <- TRUE` are treated as joint draws: `get.ensemble.samples()` gives each member a whole row, with one row index shared by PFTs that have the same number of rows. `get_parameter_samples()` argument `independent` and the `independent` returned by `load_pft_posteriors()` are now one value per PFT, so a joint posterior no longer changes how other PFTs are sampled. A joint PFT whose traits have different numbers of rows is now an error. * In `run.sensitivity.analysis()`, load `samples` once before the variables loop, avoiding repeated disk reads (#3859). * `get.ensemble.samples()` now again returns a list of dataframes as it did before v1.9.0. The returned list also now has attribute `sampled.indices`, From 3ad58ff507a6930ae817b674040ff285e502bdf0 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:25 -0500 Subject: [PATCH 13/82] preserve supplied joint draws in ensemble samples --- modules/uncertainty/R/ensemble.R | 131 +++++++++++++++++++------------ 1 file changed, 82 insertions(+), 49 deletions(-) diff --git a/modules/uncertainty/R/ensemble.R b/modules/uncertainty/R/ensemble.R index c7674b80d3f..dbc4d235a5e 100644 --- a/modules/uncertainty/R/ensemble.R +++ b/modules/uncertainty/R/ensemble.R @@ -60,49 +60,106 @@ 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 sampled parameter values for model runs, preserving supplied joint +#' draws unless independent sampling is requested. #' #' @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 named list of PFTs, each containing named parameter +#' samples, e.g. from MCMC chains. The name "env" is reserved. #' @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, one element per PFT in the order of \code{pft.samples}, naming the traits whose samples are joint draws (one row per draw). Those traits are sampled by whole rows, with one row index shared by all PFTs that have the same number of rows. If NULL, every trait is resampled independently. +#' @param method sampling method for marginal traits: "random", "uniform", +#' "halton", "sobol", or "lhc". Joint draws are sampled randomly by row. +#' @param param.names named list of joint trait names per PFT. NULL selects all +#' supplied traits; an empty entry selects none. Unnamed lists match PFT order. #' @param ... Other arguments passed on to the sampling method +#' @param independent logical. Sample each parameter separately, discarding +#' supplied dependence, instead of preserving parameter correlations. +#' +#' @details Joint draws preserve parameter correlations (by keeping complete +#' MCMC rows together). Rows are sampled with replacement. PFTs with equal +#' numbers of joint draws share row indices, so paired input tables must have +#' matching row order. Equal row counts do not establish common provenance; +#' unrelated tables must contain genuinely independent draws. Environment +#' samples and traits outside \code{param.names} are sampled marginally. +#' A one-member joint ensemble selects a complete draw; marginal traits use +#' their medians. Independent sampling can violate joint parameter constraints. #' #' @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) { + + stopifnot( + is.logical(independent), length(independent) == 1L, !is.na(independent), + is.list(pft.samples), + is.numeric(ensemble.size), length(ensemble.size) == 1L, + is.finite(ensemble.size), ensemble.size == floor(ensemble.size) + ) + pft.names <- names(pft.samples) + if (length(pft.samples) > 0) { + stopifnot(!is.null(pft.names), !anyNA(pft.names), + all(nzchar(pft.names)), !anyDuplicated(pft.names), + !"env" %in% pft.names) + } + if (independent) { + param.names <- lapply(pft.samples, function(x) character(0)) + } else if (is.null(param.names)) { + param.names <- lapply(pft.samples, names) + } else { + stopifnot(is.list(param.names), length(param.names) == length(pft.samples)) + if (is.null(names(param.names))) { + names(param.names) <- pft.names + } else { + stopifnot(!anyNA(names(param.names)), all(nzchar(names(param.names))), + !anyDuplicated(names(param.names)), + setequal(names(param.names), pft.names)) + param.names <- param.names[pft.names] + } + } + for (pft.name in pft.names) { + trait.names <- names(pft.samples[[pft.name]]) + if (length(pft.samples[[pft.name]]) > 0) { + stopifnot(!is.null(trait.names), !anyNA(trait.names), + all(nzchar(trait.names)), !anyDuplicated(trait.names)) + } + traits <- param.names[[pft.name]] + stopifnot(is.null(traits) || is.character(traits), !anyNA(traits), + !anyDuplicated(traits), all(traits %in% names(pft.samples[[pft.name]]))) + if (length(traits) > 0) { + n.rows <- unique(lengths(pft.samples[[pft.name]][traits])) + if (length(n.rows) != 1L || n.rows == 0L) { + PEcAn.logger::logger.severe( + "Joint samples for PFT", pft.name, + "need the same number of rows, greater than zero, for every trait; got", + paste(n.rows, collapse = ", ") + ) + } + } + } # Define supported methods supported_methods <- c("random", "uniform", "halton", "sobol", "lhc") if (!method %in% supported_methods) { - stop("Invalid sampling method") + PEcAn.logger::logger.severe("Invalid sampling method:", method) } ## force as numeric for compatibility with Fortran code in halton() ensemble.size <- as.numeric(ensemble.size) if (ensemble.size <= 0) { ans <- NULL - } else if (ensemble.size == 1) { + } else if (ensemble.size == 1 && !any(lengths(param.names) > 0)) { ans <- PEcAn.utils::get.sa.sample.list(pft.samples, env.samples, 0.5) } else { - pft.samples[[length(pft.samples) + 1]] <- env.samples - names(pft.samples)[length(pft.samples)] <- "env" - pft2col <- NULL - for (i in seq_along(pft.samples)) { - pft2col <- c(pft2col, rep(i, length(pft.samples[[i]]))) - } - - total.sample.num <- sum(sapply(pft.samples, length)) + pft.samples <- c(pft.samples, list(env = env.samples)) + total.sample.num <- sum(lengths(pft.samples)) - sum(lengths(param.names)) random.samples <- NULL - if (method == "halton") { + if (ensemble.size == 1 || total.sample.num == 0) { + random.samples <- matrix(0.5, ensemble.size, total.sample.num) + } else if (method == "halton") { PEcAn.logger::logger.info("Using ", method, "method for sampling") random.samples <- randtoolbox::halton(n = ensemble.size, dim = total.sample.num, ...) ## force as a matrix in case length(samples) = 1 @@ -127,7 +184,7 @@ get.ensemble.samples <- function( ensemble.size, pft.samples, env.samples, ensemble.size, total.sample.num) } else { - PEcAn.logger::logger.info("Method ", method, " has not been implemented yet, using uniform random sampling") + PEcAn.logger::logger.info("Using random sampling") # uniform random random.samples <- matrix(stats::runif(ensemble.size * total.sample.num), ensemble.size, @@ -144,47 +201,23 @@ 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]])) - # Traits in param.names are joint draws, so a member takes a whole row. - # PFTs with the same number of rows share one row index, so rows drawn - # together across PFTs also stay together. - joint.traits <- intersect(names(pft.samples[[pft.i]]), unlist(param.names[pft.i])) + joint.traits <- param.names[[names(pft.samples)[pft.i]]] if (length(joint.traits) > 0) { - n.rows <- unique(lengths(pft.samples[[pft.i]][joint.traits])) - if (length(n.rows) != 1) { - PEcAn.logger::logger.severe( - "Joint samples for PFT", names(pft.samples)[pft.i], - "need the same number of rows for every trait, got", - paste(n.rows, collapse = ", ") - ) - } + n.rows <- length(pft.samples[[pft.i]][[joint.traits[1]]]) key <- as.character(n.rows) if (is.null(joint.rows[[key]])) { - if (method == "halton") { - joint.rows[[key]] <- floor(randtoolbox::halton(ensemble.size) * n.rows) + 1 - } else if (method == "sobol") { - joint.rows[[key]] <- floor(randtoolbox::sobol(ensemble.size, scrambling = 3) * n.rows) + 1 - } else if (method == "torus") { - joint.rows[[key]] <- floor(randtoolbox::torus(ensemble.size) * n.rows) + 1 - } else if (method == "lhc") { - joint.rows[[key]] <- floor(c(PEcAn.emulator::lhc(t(matrix(0:1, ncol = 1, nrow = 2)), ensemble.size) * n.rows)) + 1 - } else if (method == "uniform") { - joint.rows[[key]] <- sample.int(n.rows, ensemble.size) - } else if (method == "random") { - PEcAn.logger::logger.info("Using random row sampling for MCMC draws") - joint.rows[[key]] <- sample.int(n.rows, ensemble.size, replace = TRUE) - } else { - PEcAn.logger::logger.error("Sampling method %s is not recognized", method) - } + # shared indices retain the caller's pairing between equal-sized banks + joint.rows[[key]] <- sample.int(n.rows, ensemble.size, replace = TRUE) } same.i <- joint.rows[[key]] } for (trait.i in seq(pft.samples[[pft.i]])) { - col.i <- col.i + 1 if (names(pft.samples[[pft.i]])[trait.i] %in% joint.traits) { ensemble.samples[[pft.i]][, trait.i] <- pft.samples[[pft.i]][[trait.i]][same.i] sampled.indices[[pft.i]][, trait.i] <- same.i } else { + col.i <- col.i + 1 # Extract original trait values trait.values <- pft.samples[[pft.i]][[trait.i]] sampled.values <- stats::quantile(trait.values, random.samples[, col.i]) From c8794ef69de3c4166d0766c25a463b4bf46c7299 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:25 -0500 Subject: [PATCH 14/82] keep mcmc draws joint and distribution samples independent --- modules/uncertainty/R/get_parameter_samples.R | 74 +++++++------------ 1 file changed, 27 insertions(+), 47 deletions(-) diff --git a/modules/uncertainty/R/get_parameter_samples.R b/modules/uncertainty/R/get_parameter_samples.R index 9499049af84..ef056ea7953 100644 --- a/modules/uncertainty/R/get_parameter_samples.R +++ b/modules/uncertainty/R/get_parameter_samples.R @@ -13,16 +13,19 @@ #' 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. Marginal sampling method: "halton", +#' "sobol", "lhc", "random", or "uniform". #' @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, one value for all PFTs or one per PFT. TRUE -#' means the PFT's MCMC samples are resampled one trait at a time (e.g. -#' meta-analysis, where each trait is fit separately). FALSE means each row -#' is one joint draw across traits (e.g. PDA), so ensemble members take whole -#' rows; PFTs with the same number of rows share one row index. +#' @param independent logical. Sample each parameter separately, discarding +#' supplied dependence, instead of preserving parameter correlations. +#' +#' @details MCMC samples are sampled jointly by default (by keeping complete +#' draws together). Traits available only as distributions remain marginal. +#' Equal-sized MCMC tables share row indices and must preserve any paired row +#' order. Independent sampling may violate joint constraints such as allocation +#' sums. See \code{\link{get.ensemble.samples}} for the sampling contract. #' #' @return named list with five elements: #' \describe{ @@ -59,7 +62,7 @@ #' str(result$ensemble.samples) #' } #' -#' @seealso \code{\link{get.parameter.samples}} for the backward-compatible +#' @seealso \code{\link{get.parameter.samples}} for the disk-based #' wrapper that handles file I/O and database lookups. #' #' @author David LeBauer, Shawn Serbin, Istem Fer, Om Kapale @@ -71,7 +74,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)) { @@ -92,9 +95,8 @@ get_parameter_samples <- function(pft_names, stopifnot( is.logical(independent), !anyNA(independent), - length(independent) %in% c(1, length(pft_names)) + length(independent) == 1L ) - independent <- rep_len(independent, length(pft_names)) # Force numeric for compatibility with downstream sampling code ensemble.size <- as.numeric(ensemble.size) @@ -165,10 +167,10 @@ get_parameter_samples <- function(pft_names, next } - # Generate quantile matrix for prior-based sampling + marginal.priors <- setdiff(priors, param.names[[i]]) q_samples <- .generate_quantile_samples( n = samples.num, - dim = n_priors, + dim = length(marginal.priors), method = ens.sample.method ) # Ensure q_samples is always a matrix (some methods return vector when dim=1) @@ -189,29 +191,18 @@ get_parameter_samples <- function(pft_names, samples <- PEcAn.priors::get.sample( prior.distns[prior, ], samples.num, - q_samples[, priors == prior] + q_samples[, match(prior, marginal.priors)] ) } trait.samples[[pft.name]][[prior]] <- samples } } - # ---- Handle independence flag ---- - # param.names tells get.ensemble.samples() which traits to keep together by - # row, matched to trait.samples by position. Keep it only for PFTs whose rows - # are joint draws, and only for PFTs that made it into trait.samples (a PFT - # with nothing to sample is skipped above). - joint.names <- stats::setNames( - lapply(seq_along(pft_names), function(i) { - if (independent[i]) character(0) else unlist(param.names[[i]]) - }), - pft_names - ) - param.names <- if (any(lengths(joint.names) > 0)) { - joint.names[names(trait.samples)] - } else { - NULL - } + # an explicit selector keeps distribution-only traits marginal + names(param.names) <- pft_names + param.names <- Map(function(traits, samples) { + intersect(as.character(traits), names(samples)) + }, param.names[names(trait.samples)], trait.samples) # ---- Sensitivity analysis samples ---- if (!is.null(sa_quantiles)) { @@ -234,21 +225,15 @@ get_parameter_samples <- function(pft_names, # ---- Ensemble samples ---- if (do_ensemble) { - if (ensemble.size == 1) { - ## Run at median if only one run in ensemble - ensemble.samples <- PEcAn.utils::get.sa.sample.list( - pft = trait.samples, - env = env.samples, - quantiles = 0.5 - ) - } else if (ensemble.size > 1) { + if (ensemble.size > 0) { ## Subset trait.samples to ensemble size ensemble.samples <- get.ensemble.samples( ensemble.size = ensemble.size, pft.samples = trait.samples, env.samples = env.samples, method = ens.sample.method, - param.names = param.names + param.names = param.names, + independent = independent ) } } @@ -281,13 +266,8 @@ get_parameter_samples <- function(pft_names, "sobol" = randtoolbox::sobol(n = n, dim = dim, scrambling = 3), "torus" = randtoolbox::torus(n = n, dim = dim), "lhc" = PEcAn.emulator::lhc(t(matrix(0:1, ncol = dim, nrow = 2)), n), - "uniform" = matrix(stats::runif(n * dim), n, dim), - { - PEcAn.logger::logger.info( - "Method ", method, - " has not been implemented yet, using uniform random sampling" - ) - matrix(stats::runif(n * dim), n, dim) - } + "uniform" =, + "random" = matrix(stats::runif(n * dim), n, dim), + PEcAn.logger::logger.severe("Invalid sampling method:", method) ) } From 6aff1968614f84e2be56f524b89122c35cb3009c Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:26 -0500 Subject: [PATCH 15/82] separate posterior loading from sampling choices --- modules/uncertainty/R/load_posteriors.R | 48 +++---------------------- 1 file changed, 5 insertions(+), 43 deletions(-) diff --git a/modules/uncertainty/R/load_posteriors.R b/modules/uncertainty/R/load_posteriors.R index 46918e5e19f..d73dc3f4460 100644 --- a/modules/uncertainty/R/load_posteriors.R +++ b/modules/uncertainty/R/load_posteriors.R @@ -16,13 +16,7 @@ #' legacy fallback path. #' @param hostname \strong{Deprecated.} Hostname for DB file lookup, used #' only in the legacy fallback path. -#' @return list with \code{prior.distns}, \code{trait.mcmc}, \code{is.joint}. -#' \code{is.joint} is \code{TRUE} when each row of the MCMC samples is one -#' joint draw across traits, so rows must be kept together: either the -#' samples carry \code{attr(trait.mcmc, "joint") <- TRUE}, or they come from -#' PDA (a \code{mcmc.pda.*} file next to them, or "pda" in the file name on -#' the legacy path). Other MCMC samples, such as meta-analysis output, are -#' sampled one trait at a time. +#' @return list with \code{prior.distns} and \code{trait.mcmc}. #' @keywords internal #' @author Siddhey Patil load.posteriors <- function(posterior.file, @@ -57,13 +51,12 @@ load.posteriors <- function(posterior.file, #' \code{post.distns} and \code{prior.distns}. #' #' @param path file path or directory path -#' @return List with \code{prior.distns}, \code{trait.mcmc}, \code{is.joint} +#' @return List with \code{prior.distns} and \code{trait.mcmc} #' @keywords internal load.posteriors.from.path <- function(path) { result <- list( prior.distns = NULL, - trait.mcmc = NULL, - is.joint = FALSE + trait.mcmc = NULL ) if (!file.exists(path)) { @@ -114,7 +107,6 @@ load.posteriors.from.path <- function(path) { "Found Monte Carlo samples (", obj_name, ") in: ", f ) result$trait.mcmc <- obj - result$is.joint <- isTRUE(attr(obj, "joint")) break } # Single mcmc.list (not wrapped in a named list) @@ -155,22 +147,6 @@ load.posteriors.from.path <- function(path) { ) } - # Detect joint posterior: check for a companion mcmc.pda.* file in the - # same directory, which PDA always creates alongside trait.mcmc.pda.* - if (!is.null(result$trait.mcmc)) { - scan_dir <- if (dir.exists(path)) path else dirname(path) - pda_companions <- list.files( - scan_dir, pattern = "^mcmc\\.pda\\.", ignore.case = TRUE - ) - if (length(pda_companions) > 0) { - result$is.joint <- TRUE - PEcAn.logger::logger.info( - "Detected joint posterior (PDA companion file found in ", - scan_dir, ")" - ) - } - } - return(result) } @@ -185,7 +161,7 @@ load.posteriors.from.path <- function(path) { #' @param posteriorid Posterior ID for database lookup #' @param con db connection #' @param hostname host name for dbfile lookup -#' @return List with \code{prior.distns}, \code{trait.mcmc}, \code{is.joint} +#' @return List with \code{prior.distns} and \code{trait.mcmc} #' @keywords internal load.posteriors.legacy <- function(outdir = NULL, posteriorid = NULL, @@ -193,8 +169,7 @@ load.posteriors.legacy <- function(outdir = NULL, hostname = NULL) { result <- list( prior.distns = NULL, - trait.mcmc = NULL, - is.joint = FALSE + trait.mcmc = NULL ) ## Step 1: Load distribution summaries from outdir @@ -250,16 +225,9 @@ load.posteriors.legacy <- function(outdir = NULL, "Found Monte Carlo samples in DB-referenced file: ", fpath ) result$trait.mcmc <- env$trait.mcmc - # Detect PDA samples to preserve correlations if (exists("post.distns", envir = env, inherits = FALSE)) { result$prior.distns <- result$prior.distns %||% env$post.distns } - # In the legacy DB path, detect joint posterior via filename - # heuristic (PDA convention: trait.mcmc.pda.*) - fname_lower <- tolower(files$file_name[idx]) - if (isTRUE(attr(result$trait.mcmc, "joint")) || grepl("pda", fname_lower)) { - result$is.joint <- TRUE - } break # Use first MCMC found } } @@ -285,12 +253,6 @@ load.posteriors.legacy <- function(outdir = NULL, "Found Monte Carlo samples in outdir file: ", f ) result$trait.mcmc <- env$trait.mcmc - # In the legacy outdir-scan path, detect joint posterior via - # filename heuristic (PDA convention: trait.mcmc.pda.*) - fname_lower <- tolower(basename(f)) - if (isTRUE(attr(result$trait.mcmc, "joint")) || grepl("pda", fname_lower)) { - result$is.joint <- TRUE - } break } } From d1b3c288f87909b9785328df9e678b0c93bda8e8 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:26 -0500 Subject: [PATCH 16/82] return pft posterior data for sampling --- modules/uncertainty/R/load_pft_posteriors.R | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/modules/uncertainty/R/load_pft_posteriors.R b/modules/uncertainty/R/load_pft_posteriors.R index b5995615389..ac063e06bd6 100644 --- a/modules/uncertainty/R/load_pft_posteriors.R +++ b/modules/uncertainty/R/load_pft_posteriors.R @@ -9,9 +9,8 @@ #' #' Posterior type is detected by content, not filename, via #' \code{\link{load.posteriors}}: MCMC chains take precedence over distribution -#' summaries. When a PFT's posterior is joint (see \code{\link{load.posteriors}}), -#' its entry in the returned \code{independent} flag is \code{FALSE} so -#' downstream sampling keeps its MCMC rows together. +#' summaries. Downstream joint sampling preserves parameter correlations +#' (for MCMC samples, by keeping complete draws together). #' #' @param settings PEcAn settings object. Uses \code{settings$pfts} (name, #' outdir, posteriorid per PFT), \code{settings$database$bety} for the @@ -19,15 +18,13 @@ #' @param posterior.files character vector of posterior filenames, one per PFT, #' \code{NA} where none is specified. Length must match \code{settings$pfts}. #' -#' @return A list with four elements: +#' @return A list with three elements: #' \describe{ #' \item{pft_names}{character vector of PFT names ("NULL" where unnamed).} #' \item{prior_distns_list}{list of prior distribution data frames, one per #' PFT (\code{NULL} entry where none was found).} #' \item{trait_mcmc_list}{list of trait MCMC results, one per PFT #' (\code{NULL} entry where the PFT has no MCMC chains).} -#' \item{independent}{logical vector, one per PFT: \code{FALSE} where the -#' PFT carries a joint posterior, \code{TRUE} otherwise.} #' } #' #' @seealso \code{\link{get_parameter_samples}} for the sampling step that @@ -88,7 +85,6 @@ load_pft_posteriors <- function(settings, ## Load priors and posteriors for each PFT prior_distns_list <- vector("list", length(pft.names)) trait_mcmc_list <- vector("list", length(pft.names)) - independent <- rep(TRUE, length(pft.names)) for (i in seq_along(pft.names)) { posterior <- load.posteriors( @@ -105,17 +101,13 @@ load_pft_posteriors <- function(settings, if (!is.null(posterior$trait.mcmc)) { trait_mcmc_list[[i]] <- posterior$trait.mcmc - # Per PFT, so one joint posterior doesn't tie together the rows of - # another PFT's meta-analysis chains - independent[i] <- !posterior$is.joint } # else trait_mcmc_list[[i]] stays NULL } list( pft_names = pft.names, prior_distns_list = prior_distns_list, - trait_mcmc_list = trait_mcmc_list, - independent = independent + trait_mcmc_list = trait_mcmc_list ) } From 09741051ad451907d0a8671c79fa2eebb58dd720 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:26 -0500 Subject: [PATCH 17/82] forward sampling choice through parameter wrapper --- modules/uncertainty/R/get.parameter.samples.R | 40 +++++++++---------- 1 file changed, 18 insertions(+), 22 deletions(-) diff --git a/modules/uncertainty/R/get.parameter.samples.R b/modules/uncertainty/R/get.parameter.samples.R index d40be4be249..5d41add9865 100644 --- a/modules/uncertainty/R/get.parameter.samples.R +++ b/modules/uncertainty/R/get.parameter.samples.R @@ -2,7 +2,7 @@ #' #' Loads posterior distributions and MCMC chain results from disk, generates #' parameter samples for ensemble and sensitivity analysis runs, and optionally -#' saves results to `samples.Rdata`. This is the backward-compatible wrapper +#' saves results to `samples.Rdata`. This is the deprecated wrapper #' that delegates computation to \code{\link[PEcAn.uncertainty]{get_parameter_samples}}. #' #' @details @@ -11,8 +11,8 @@ #' \item{`post.distns.Rdata` or `prior.distns.Rdata`}{Posterior (or prior) #' distribution summaries produced by \code{run.meta.analysis.pft}. A data #' frame with columns `distn`, `parama`, `paramb`, `n`.} -#' \item{`trait.mcmc.Rdata`}{(Optional) MCMC chain samples from the -#' meta-analysis. Named list of `mcmc.list` objects, one per trait. +#' \item{`trait.mcmc.Rdata`}{(Optional) posterior MCMC samples. +#' Named list of `mcmc.list` objects, one per trait. #' If present, samples are drawn from the chains directly; otherwise, #' independent samples are drawn from `post.distns`.} #' } @@ -34,22 +34,22 @@ #' }} #' } #' -#' **Downstream contract:** `samples.Rdata` is loaded by \code{run.write.configs} -#' (in `PEcAn.workflow`) to generate model configuration files. It is also -#' loaded by \code{\link[PEcAn.uncertainty]{get.results}} and \code{\link[PEcAn.uncertainty]{run.sensitivity.analysis}} to retrieve -#' sample metadata for post-processing. This implicit file-based coupling is -#' a refactoring target. +#' **Downstream contract:** The workflow passes the parameter bundle directly to +#' \code{run.write.configs} in memory. That writer can also load `samples.Rdata` +#' when no bundle is supplied. \code{\link[PEcAn.uncertainty]{get.results}} can +#' read the saved file when ensemble-specific samples are unavailable, and +#' \code{\link[PEcAn.uncertainty]{run.sensitivity.analysis}} reads it for traits. #' #' @param settings PEcAn settings object #' @param ensemble.size number of runs in model ensemble #' @param posterior.files list of filenames to read from -#' @param ens.sample.method one of `"halton"`, `"sobol"`, `"torus"`, `"lhc"`, -#' `"uniform"` -#' @param outdir character path; directory to write `samples.Rdata` to for -#' provenance. Defaults to `settings$outdir`, preserving the legacy -#' always-save behaviour for existing callers (none of which pass it). -#' Pass `outdir = NULL` to skip the save entirely; the pure -#' `get_parameter_samples()` never writes to disk regardless. +#' @param ens.sample.method marginal sampling method: `"halton"`, `"sobol"`, +#' `"lhc"`, `"random"`, or `"uniform"`. +#' @param outdir directory for `samples.Rdata`, defaulting to `settings$outdir`. +#' Use `NULL` to return samples without saving a file. +#' @param independent Logical scalar. If `FALSE` (default), preserve +#' dependence among supplied MCMC parameters. If `TRUE`, sample each +#' parameter separately, ignoring supplied dependence. #' #' @return Named list with 5 elements: `trait.samples`, `sa.samples`, #' `ensemble.samples`, `runs.samples`, `env.samples`. Returned invisibly. @@ -64,7 +64,9 @@ get.parameter.samples <- function(settings, ensemble.size = 1, posterior.files = rep(NA, length(settings$pfts)), ens.sample.method = "uniform", - outdir = settings$outdir) { + outdir = settings$outdir, + independent = FALSE) { + stopifnot(is.logical(independent), length(independent) == 1L, !is.na(independent)) .Deprecated("get_parameter_samples") ### Identify PFTs in the input settings.xml file @@ -80,7 +82,6 @@ get.parameter.samples <- function(settings, pft.names <- loaded$pft_names prior_distns_list <- loaded$prior_distns_list trait_mcmc_list <- loaded$trait_mcmc_list - independent <- loaded$independent ## ---- Delegate to pure function ---- result <- get_parameter_samples( @@ -94,11 +95,6 @@ get.parameter.samples <- function(settings, independent = independent ) - ## ---- Save to disk for provenance (opt-in via `outdir`) ---- - # `outdir` defaults to `settings$outdir`, so existing callers (none of which - # pass it) write `samples.Rdata` exactly as before. Pass `outdir = NULL` to - # skip the save for a purely in-memory call; the pure get_parameter_samples() - # never writes to disk at all. if (!is.null(outdir)) { ensemble.samples <- result$ensemble.samples trait.samples <- result$trait.samples From eb2c06da4256cf9c3a4abe286fd0d93f125dc495 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:26 -0500 Subject: [PATCH 18/82] pass sampling choice through ensemble design generation --- modules/uncertainty/R/generate_joint_ensemble_design.R | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/modules/uncertainty/R/generate_joint_ensemble_design.R b/modules/uncertainty/R/generate_joint_ensemble_design.R index 85272e5cbb9..222bf4560e0 100644 --- a/modules/uncertainty/R/generate_joint_ensemble_design.R +++ b/modules/uncertainty/R/generate_joint_ensemble_design.R @@ -44,6 +44,9 @@ #' \code{load_pft_posteriors} and \code{get_parameter_samples}. #' @param sobol Logical. If TRUE, returns a \code{sensitivity::soboljansen} #' object for Sobol sensitivity analysis. +#' @param independent Logical scalar: \code{FALSE} preserves supplied MCMC +#' dependence; \code{TRUE} discards it and samples parameters separately. +#' Used only when \code{samples = NULL}; supplied samples are reused unchanged. #' #' @return If \code{sobol = FALSE}, a list with \code{design_matrix} (the design, #' one row per run, whose \code{param} column indexes the samples), \code{X} @@ -60,7 +63,9 @@ generate_joint_ensemble_design <- function(settings, ensemble_size, samples = NULL, - sobol = FALSE) { + sobol = FALSE, + independent = FALSE) { + stopifnot(is.logical(independent), length(independent) == 1L, !is.na(independent)) if (sobol) { ensemble_size <- as.numeric(ensemble_size) * 2 } @@ -110,7 +115,7 @@ generate_joint_ensemble_design <- function(settings, ens.sample.method = ens.sample.method, sa_quantiles = settings$sensitivity.analysis$quantiles, do_ensemble = TRUE, - independent = loaded$independent + independent = independent ) } # Here we assumed the length of parameters is identical to the ensemble size. From 994c4c11527e787b1b2de9b9c732ed7ea3dc6b45 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:26 -0500 Subject: [PATCH 19/82] keep oat quantiles separate from ensemble sampling --- modules/uncertainty/R/generate_OAT_SA_design.R | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/modules/uncertainty/R/generate_OAT_SA_design.R b/modules/uncertainty/R/generate_OAT_SA_design.R index c59bcae02b7..2771c859469 100644 --- a/modules/uncertainty/R/generate_OAT_SA_design.R +++ b/modules/uncertainty/R/generate_OAT_SA_design.R @@ -87,8 +87,7 @@ generate_OAT_SA_design <- function(settings, samples = NULL) { ensemble.size = settings$ensemble$size %||% 1, ens.sample.method = settings$ensemble$samplingspace$parameters$method %||% "uniform", sa_quantiles = settings$sensitivity.analysis$quantiles, - do_ensemble = FALSE, - independent = loaded$independent + do_ensemble = FALSE ) } @@ -171,4 +170,4 @@ generate_OAT_SA_design <- function(settings, samples = NULL) { design_matrix$sa_quantile <- sa_quantile return(list(design_matrix = design_matrix, X = design_matrix, samples = samples)) -} \ No newline at end of file +} From 0482e1ff34f8416794359147d6402fb0ea483966 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:26 -0500 Subject: [PATCH 20/82] pass sampling choice through configuration workflow --- base/workflow/R/runModule.run.write.configs.R | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/base/workflow/R/runModule.run.write.configs.R b/base/workflow/R/runModule.run.write.configs.R index 6a0ecc881d7..962dd2ada9e 100644 --- a/base/workflow/R/runModule.run.write.configs.R +++ b/base/workflow/R/runModule.run.write.configs.R @@ -27,6 +27,9 @@ #' A bare design data.frame is not accepted: its \code{param} indices are only #' meaningful together with the samples they index into, so the design and its #' samples must travel together. +#' @param independent Logical scalar: \code{FALSE} preserves supplied MCMC +#' dependence; \code{TRUE} discards it and samples parameters separately. +#' Only applies to new ensemble samples; supplied bundles are reused unchanged. #' @return A modified settings object, invisibly #' #' @@ -37,7 +40,9 @@ runModule.run.write.configs <- function(settings, overwrite = TRUE, - input_design = NULL) { + input_design = NULL, + independent = FALSE) { + stopifnot(is.logical(independent), length(independent) == 1L, !is.na(independent)) if (PEcAn.settings::is.MultiSettings(settings)) { if (overwrite && file.exists(file.path(settings$rundir, "runs.txt"))) { @@ -50,12 +55,13 @@ runModule.run.write.configs <- function(settings, } # prepare designs once for all sites (consistent sampling) - designs <- .prepare_input_designs(settings[1], input_design) + designs <- .prepare_input_designs(settings[1], input_design, independent) return(PEcAn.settings::papply(settings, runModule.run.write.configs, overwrite = FALSE, - input_design = designs)) + input_design = designs, + independent = independent)) } else if (PEcAn.settings::is.Settings(settings)) { # only default the sampling method for a run that actually has an ensemble, @@ -67,7 +73,7 @@ runModule.run.write.configs <- function(settings, } # prepare designs (may already be normalized from MultiSettings) - designs <- .prepare_input_designs(settings, input_design) + designs <- .prepare_input_designs(settings, input_design, independent) # check to see if there are posterior.files tags under pft posterior.files <- settings$pfts %>% @@ -153,6 +159,8 @@ runModule.run.write.configs <- function(settings, #' #' @param settings A single PEcAn settings object #' @param input_design Input design specification (see \code{runModule.run.write.configs}) +#' @param independent Logical scalar passed to \code{get_parameter_samples} +#' when generating new samples. Supplied samples are reused unchanged. #' @return A list with \code{ensemble} and \code{sensitivity} entries (each a #' data.frame or NULL) and a \code{samples} entry holding the parameter bundle #' used for the run. When the run has an ensemble or sensitivity analysis the @@ -181,7 +189,8 @@ runModule.run.write.configs <- function(settings, #' #' @keywords internal -.prepare_input_designs <- function(settings, input_design) { +.prepare_input_designs <- function(settings, input_design, independent = FALSE) { + stopifnot(is.logical(independent), length(independent) == 1L, !is.na(independent)) # Already-normalized designs (e.g. threaded from a MultiSettings parent): # pass straight through. samples.Rdata was already written by the top-level @@ -256,7 +265,7 @@ runModule.run.write.configs <- function(settings, ens.sample.method = settings$ensemble$samplingspace$parameters$method %||% "uniform", sa_quantiles = settings$sensitivity.analysis$quantiles, do_ensemble = need_ensemble, - independent = loaded$independent + independent = independent ) } @@ -315,4 +324,4 @@ runModule.run.write.configs <- function(settings, } return(designs) -} \ No newline at end of file +} From cb24bfc82485d595b416a4a9dd83a046d2a43a1e Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:26 -0500 Subject: [PATCH 21/82] preserve independent sampling in standalone ed script --- models/ed/scripts/write.configs.rscript.R | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/models/ed/scripts/write.configs.rscript.R b/models/ed/scripts/write.configs.rscript.R index c3ea5caff60..1c5b551ecc8 100644 --- a/models/ed/scripts/write.configs.rscript.R +++ b/models/ed/scripts/write.configs.rscript.R @@ -116,7 +116,8 @@ if('sensitivity.analysis' %in% names(settings)) { ## Write ENSEMBLE if('ensemble' %in% names(settings) && settings$ensemble$size > 0) { ## subset the trait.samples to ensemble size using Halton sequence - ensemble.samples <- get.ensemble.samples(settings$ensemble$size, trait.samples, env.samples) + ensemble.samples <- get.ensemble.samples(settings$ensemble$size, trait.samples, env.samples, + independent = TRUE) write.ensemble.configs(settings$pfts, ensemble.samples, host, outdir, settings) } From 1913cb7e94c5569684568e8ca4c0b2c34be99770 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:26 -0500 Subject: [PATCH 22/82] document joint and marginal ensemble sampling --- .../uncertainty/man/get.ensemble.samples.Rd | 31 ++++++++++++++----- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/modules/uncertainty/man/get.ensemble.samples.Rd b/modules/uncertainty/man/get.ensemble.samples.Rd index 7877ed509d6..bfd7f1336b0 100644 --- a/modules/uncertainty/man/get.ensemble.samples.Rd +++ b/modules/uncertainty/man/get.ensemble.samples.Rd @@ -10,30 +10,45 @@ 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}{named list of PFTs, each containing named parameter +samples, e.g. from MCMC chains. The name "env" is reserved.} \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}{sampling method for marginal traits: "random", "uniform", +"halton", "sobol", or "lhc". Joint draws are sampled randomly by row.} -\item{param.names}{a list, one element per PFT in the order of \code{pft.samples}, naming the traits whose samples are joint draws (one row per draw). Those traits are sampled by whole rows, with one row index shared by all PFTs that have the same number of rows. If NULL, every trait is resampled independently.} +\item{param.names}{named list of joint trait names per PFT. NULL selects all +supplied traits; an empty entry selects none. Unnamed lists match PFT order.} \item{...}{Other arguments passed on to the sampling method} + +\item{independent}{logical. Sample each parameter separately, discarding +supplied dependence, instead of preserving parameter correlations.} } \value{ 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 sampled parameter values for model runs, preserving supplied joint +draws unless independent sampling is requested. +} +\details{ +Joint draws preserve parameter correlations (by keeping complete + MCMC rows together). Rows are sampled with replacement. PFTs with equal + numbers of joint draws share row indices, so paired input tables must have + matching row order. Equal row counts do not establish common provenance; + unrelated tables must contain genuinely independent draws. Environment + samples and traits outside \code{param.names} are sampled marginally. + A one-member joint ensemble selects a complete draw; marginal traits use + their medians. Independent sampling can violate joint parameter constraints. } \author{ David LeBauer, Istem Fer From 365a9c3d6cbd1ae586cd01c740fa2918f5616e4f Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:27 -0500 Subject: [PATCH 23/82] document parameter sampling defaults and constraints --- .../uncertainty/man/get_parameter_samples.Rd | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/modules/uncertainty/man/get_parameter_samples.Rd b/modules/uncertainty/man/get_parameter_samples.Rd index eaa3fa5c8c8..f0d9209d415 100644 --- a/modules/uncertainty/man/get_parameter_samples.Rd +++ b/modules/uncertainty/man/get_parameter_samples.Rd @@ -12,7 +12,7 @@ get_parameter_samples( ens.sample.method = "uniform", sa_quantiles = NULL, do_ensemble = TRUE, - independent = TRUE + independent = FALSE ) } \arguments{ @@ -27,19 +27,16 @@ 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. Marginal sampling method: "halton", +"sobol", "lhc", "random", or "uniform".} \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, one value for all PFTs or one per PFT. TRUE -means the PFT's MCMC samples are resampled one trait at a time (e.g. -meta-analysis, where each trait is fit separately). FALSE means each row -is one joint draw across traits (e.g. PDA), so ensemble members take whole -rows; PFTs with the same number of rows share one row index.} +\item{independent}{logical. Sample each parameter separately, discarding +supplied dependence, instead of preserving parameter correlations.} } \value{ named list with five elements: @@ -62,6 +59,12 @@ directly, with no file I/O and no database calls. } \details{ For the original disk-based wrapper, see \code{\link{get.parameter.samples}}. + +MCMC samples are sampled jointly by default (by keeping complete + draws together). Traits available only as distributions remain marginal. + Equal-sized MCMC tables share row indices and must preserve any paired row + order. Independent sampling may violate joint constraints such as allocation + sums. See \code{\link{get.ensemble.samples}} for the sampling contract. } \examples{ \dontrun{ @@ -87,7 +90,7 @@ str(result$ensemble.samples) } \seealso{ -\code{\link{get.parameter.samples}} for the backward-compatible +\code{\link{get.parameter.samples}} for the disk-based wrapper that handles file I/O and database lookups. } \author{ From 14fa75610920d14811567b91608a9c9451773ac0 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:27 -0500 Subject: [PATCH 24/82] document posterior loader return values --- modules/uncertainty/man/load.posteriors.Rd | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/modules/uncertainty/man/load.posteriors.Rd b/modules/uncertainty/man/load.posteriors.Rd index 0d425c8ccc2..8717890f07a 100644 --- a/modules/uncertainty/man/load.posteriors.Rd +++ b/modules/uncertainty/man/load.posteriors.Rd @@ -29,13 +29,7 @@ legacy fallback path.} only in the legacy fallback path.} } \value{ -list with \code{prior.distns}, \code{trait.mcmc}, \code{is.joint}. - \code{is.joint} is \code{TRUE} when each row of the MCMC samples is one - joint draw across traits, so rows must be kept together: either the - samples carry \code{attr(trait.mcmc, "joint") <- TRUE}, or they come from - PDA (a \code{mcmc.pda.*} file next to them, or "pda" in the file name on - the legacy path). Other MCMC samples, such as meta-analysis output, are - sampled one trait at a time. +list with \code{prior.distns} and \code{trait.mcmc}. } \description{ Detects posterior type by file contents, not filenames. From 590e2916fd756bd2433e1f5dafde7ffaa1dc6707 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:27 -0500 Subject: [PATCH 25/82] document posterior data loaded from paths --- modules/uncertainty/man/load.posteriors.from.path.Rd | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/uncertainty/man/load.posteriors.from.path.Rd b/modules/uncertainty/man/load.posteriors.from.path.Rd index da97351be04..98a9c155b40 100644 --- a/modules/uncertainty/man/load.posteriors.from.path.Rd +++ b/modules/uncertainty/man/load.posteriors.from.path.Rd @@ -10,7 +10,7 @@ load.posteriors.from.path(path) \item{path}{file path or directory path} } \value{ -List with \code{prior.distns}, \code{trait.mcmc}, \code{is.joint} +List with \code{prior.distns} and \code{trait.mcmc} } \description{ Scans \code{.Rdata} files at \code{path} and detects MCMC samples From bfe0e6ff62ebbfbd13782166eff39582f96289c6 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:27 -0500 Subject: [PATCH 26/82] document legacy posterior loader return values --- modules/uncertainty/man/load.posteriors.legacy.Rd | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/uncertainty/man/load.posteriors.legacy.Rd b/modules/uncertainty/man/load.posteriors.legacy.Rd index 8bb9b074725..658a0ee520b 100644 --- a/modules/uncertainty/man/load.posteriors.legacy.Rd +++ b/modules/uncertainty/man/load.posteriors.legacy.Rd @@ -21,7 +21,7 @@ load.posteriors.legacy( \item{hostname}{host name for dbfile lookup} } \value{ -List with \code{prior.distns}, \code{trait.mcmc}, \code{is.joint} +List with \code{prior.distns} and \code{trait.mcmc} } \description{ \strong{Deprecated.} This path is used only when From 2fc3e430b21dea8506327b5cd933cb8fee813a8f Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:27 -0500 Subject: [PATCH 27/82] document pft posterior loading contract --- modules/uncertainty/man/load_pft_posteriors.Rd | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/modules/uncertainty/man/load_pft_posteriors.Rd b/modules/uncertainty/man/load_pft_posteriors.Rd index c7c46d9e116..59677879d1d 100644 --- a/modules/uncertainty/man/load_pft_posteriors.Rd +++ b/modules/uncertainty/man/load_pft_posteriors.Rd @@ -15,15 +15,13 @@ optional BETY lookup, and \code{settings$host$name}.} \code{NA} where none is specified. Length must match \code{settings$pfts}.} } \value{ -A list with four elements: +A list with three elements: \describe{ \item{pft_names}{character vector of PFT names ("NULL" where unnamed).} \item{prior_distns_list}{list of prior distribution data frames, one per PFT (\code{NULL} entry where none was found).} \item{trait_mcmc_list}{list of trait MCMC results, one per PFT (\code{NULL} entry where the PFT has no MCMC chains).} - \item{independent}{logical vector, one per PFT: \code{FALSE} where the - PFT carries a joint posterior, \code{TRUE} otherwise.} } } \description{ @@ -37,9 +35,8 @@ their own copy. \details{ Posterior type is detected by content, not filename, via \code{\link{load.posteriors}}: MCMC chains take precedence over distribution -summaries. When a PFT's posterior is joint (see \code{\link{load.posteriors}}), -its entry in the returned \code{independent} flag is \code{FALSE} so -downstream sampling keeps its MCMC rows together. +summaries. Downstream joint sampling preserves parameter correlations +(for MCMC samples, by keeping complete draws together). } \seealso{ \code{\link{get_parameter_samples}} for the sampling step that From 0730c9246dedcecb027d0804a5bc3e81c8200fe6 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:27 -0500 Subject: [PATCH 28/82] document parameter wrapper sampling options --- .../uncertainty/man/get.parameter.samples.Rd | 34 ++++++++++--------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/modules/uncertainty/man/get.parameter.samples.Rd b/modules/uncertainty/man/get.parameter.samples.Rd index 2b7de125eeb..f03d6f48dbe 100644 --- a/modules/uncertainty/man/get.parameter.samples.Rd +++ b/modules/uncertainty/man/get.parameter.samples.Rd @@ -9,7 +9,8 @@ get.parameter.samples( ensemble.size = 1, posterior.files = rep(NA, length(settings$pfts)), ens.sample.method = "uniform", - outdir = settings$outdir + outdir = settings$outdir, + independent = FALSE ) } \arguments{ @@ -19,14 +20,15 @@ get.parameter.samples( \item{posterior.files}{list of filenames to read from} -\item{ens.sample.method}{one of \code{"halton"}, \code{"sobol"}, \code{"torus"}, \code{"lhc"}, -\code{"uniform"}} +\item{ens.sample.method}{marginal sampling method: \code{"halton"}, \code{"sobol"}, +\code{"lhc"}, \code{"random"}, or \code{"uniform"}.} -\item{outdir}{character path; directory to write \code{samples.Rdata} to for -provenance. Defaults to \code{settings$outdir}, preserving the legacy -always-save behaviour for existing callers (none of which pass it). -Pass \code{outdir = NULL} to skip the save entirely; the pure -\code{get_parameter_samples()} never writes to disk regardless.} +\item{outdir}{directory for \code{samples.Rdata}, defaulting to \code{settings$outdir}. +Use \code{NULL} to return samples without saving a file.} + +\item{independent}{Logical scalar. If \code{FALSE} (default), preserve +dependence among supplied MCMC parameters. If \code{TRUE}, sample each +parameter separately, ignoring supplied dependence.} } \value{ Named list with 5 elements: \code{trait.samples}, \code{sa.samples}, @@ -35,7 +37,7 @@ Named list with 5 elements: \code{trait.samples}, \code{sa.samples}, \description{ Loads posterior distributions and MCMC chain results from disk, generates parameter samples for ensemble and sensitivity analysis runs, and optionally -saves results to \code{samples.Rdata}. This is the backward-compatible wrapper +saves results to \code{samples.Rdata}. This is the deprecated wrapper that delegates computation to \code{\link[PEcAn.uncertainty]{get_parameter_samples}}. } \details{ @@ -44,8 +46,8 @@ that delegates computation to \code{\link[PEcAn.uncertainty]{get_parameter_sampl \item{\code{post.distns.Rdata} or \code{prior.distns.Rdata}}{Posterior (or prior) distribution summaries produced by \code{run.meta.analysis.pft}. A data frame with columns \code{distn}, \code{parama}, \code{paramb}, \code{n}.} -\item{\code{trait.mcmc.Rdata}}{(Optional) MCMC chain samples from the -meta-analysis. Named list of \code{mcmc.list} objects, one per trait. +\item{\code{trait.mcmc.Rdata}}{(Optional) posterior MCMC samples. +Named list of \code{mcmc.list} objects, one per trait. If present, samples are drawn from the chains directly; otherwise, independent samples are drawn from \code{post.distns}.} } @@ -67,11 +69,11 @@ metadata). }} } -\strong{Downstream contract:} \code{samples.Rdata} is loaded by \code{run.write.configs} -(in \code{PEcAn.workflow}) to generate model configuration files. It is also -loaded by \code{\link[PEcAn.uncertainty]{get.results}} and \code{\link[PEcAn.uncertainty]{run.sensitivity.analysis}} to retrieve -sample metadata for post-processing. This implicit file-based coupling is -a refactoring target. +\strong{Downstream contract:} The workflow passes the parameter bundle directly to +\code{run.write.configs} in memory. That writer can also load \code{samples.Rdata} +when no bundle is supplied. \code{\link[PEcAn.uncertainty]{get.results}} can +read the saved file when ensemble-specific samples are unavailable, and +\code{\link[PEcAn.uncertainty]{run.sensitivity.analysis}} reads it for traits. } \author{ David LeBauer, Shawn Serbin, Istem Fer, Om Kapale From da613cf56677a40da77b6c2a6ef553eb0dcff243 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:27 -0500 Subject: [PATCH 29/82] document ensemble design sampling option --- modules/uncertainty/man/generate_joint_ensemble_design.Rd | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/modules/uncertainty/man/generate_joint_ensemble_design.Rd b/modules/uncertainty/man/generate_joint_ensemble_design.Rd index 4e2d6c01fa7..3bf3d409f5b 100644 --- a/modules/uncertainty/man/generate_joint_ensemble_design.Rd +++ b/modules/uncertainty/man/generate_joint_ensemble_design.Rd @@ -8,7 +8,8 @@ generate_joint_ensemble_design( settings, ensemble_size, samples = NULL, - sobol = FALSE + sobol = FALSE, + independent = FALSE ) } \arguments{ @@ -34,6 +35,10 @@ are used directly instead of loading posteriors and sampling. When \item{sobol}{Logical. If TRUE, returns a \code{sensitivity::soboljansen} object for Sobol sensitivity analysis.} + +\item{independent}{Logical scalar: \code{FALSE} preserves supplied MCMC +dependence; \code{TRUE} discards it and samples parameters separately. +Used only when \code{samples = NULL}; supplied samples are reused unchanged.} } \value{ If \code{sobol = FALSE}, a list with \code{design_matrix} (the design, From c3c80088f45900d692aeffc31a5bf8f19cf43109 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:27 -0500 Subject: [PATCH 30/82] document input preparation sampling option --- base/workflow/man/dot-prepare_input_designs.Rd | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/base/workflow/man/dot-prepare_input_designs.Rd b/base/workflow/man/dot-prepare_input_designs.Rd index f77994b1dc9..2d37c58b918 100644 --- a/base/workflow/man/dot-prepare_input_designs.Rd +++ b/base/workflow/man/dot-prepare_input_designs.Rd @@ -4,12 +4,15 @@ \alias{.prepare_input_designs} \title{Prepare input designs for ensemble and sensitivity analysis} \usage{ -.prepare_input_designs(settings, input_design) +.prepare_input_designs(settings, input_design, independent = FALSE) } \arguments{ \item{settings}{A single PEcAn settings object} \item{input_design}{Input design specification (see \code{runModule.run.write.configs})} + +\item{independent}{Logical scalar passed to \code{get_parameter_samples} +when generating new samples. Supplied samples are reused unchanged.} } \value{ A list with \code{ensemble} and \code{sensitivity} entries (each a From edbf8d747316c9a9ddf7ab4dd9575084d4572ee4 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:27 -0500 Subject: [PATCH 31/82] document workflow sampling option --- base/workflow/man/runModule.run.write.configs.Rd | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/base/workflow/man/runModule.run.write.configs.Rd b/base/workflow/man/runModule.run.write.configs.Rd index b0691af80ba..3b9b524e25b 100644 --- a/base/workflow/man/runModule.run.write.configs.Rd +++ b/base/workflow/man/runModule.run.write.configs.Rd @@ -4,7 +4,12 @@ \alias{runModule.run.write.configs} \title{Generate model-specific run configuration files for one or more PEcAn runs} \usage{ -runModule.run.write.configs(settings, overwrite = TRUE, input_design = NULL) +runModule.run.write.configs( + settings, + overwrite = TRUE, + input_design = NULL, + independent = FALSE +) } \arguments{ \item{settings}{a PEcAn Settings or MultiSettings object} @@ -26,6 +31,10 @@ for \code{settings$run$inputs} tags such as \code{met} or \code{soil}) and A bare design data.frame is not accepted: its \code{param} indices are only meaningful together with the samples they index into, so the design and its samples must travel together.} + +\item{independent}{Logical scalar: \code{FALSE} preserves supplied MCMC +dependence; \code{TRUE} discards it and samples parameters separately. +Only applies to new ensemble samples; supplied bundles are reused unchanged.} } \value{ A modified settings object, invisibly From b5999483214b2cf218c158e982692385923d5bd0 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:28 -0500 Subject: [PATCH 32/82] test ensemble row sampling and named selectors --- .../tests/testthat/test_ensemble.R | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/modules/uncertainty/tests/testthat/test_ensemble.R b/modules/uncertainty/tests/testthat/test_ensemble.R index 5e070cf208b..3ff5baee8cf 100644 --- a/modules/uncertainty/tests/testthat/test_ensemble.R +++ b/modules/uncertainty/tests/testthat/test_ensemble.R @@ -160,3 +160,58 @@ 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("direct ensemble calls preserve supplied rows", { + withr::local_seed(2) + samples <- list(pft = list(a = 1:10, b = -(1:10))) + result <- get.ensemble.samples(30, samples, list()) + expect_equal(result$pft$b, -result$pft$a) + expect_true(all(result$pft$a %in% 1:10)) + expect_equal(nrow(result$pft), 30) +}) + +test_that("joint selectors match by PFT name rather than list position", { + withr::local_seed(2) + samples <- list(first = list(a = 1:20, b = -(1:20)), + second = list(a = 1:20, b = -(1:20))) + result <- get.ensemble.samples( + 30, samples, list(), + param.names = list(second = character(0), first = c("a", "b")) + ) + expect_equal(result$first$b, -result$first$a) + expect_false(isTRUE(all.equal(result$second$b, -result$second$a))) + positional <- get.ensemble.samples( + 30, samples, list(), param.names = list(c("a", "b"), character(0)) + ) + expect_equal(positional$first$b, -positional$first$a) +}) + +test_that("malformed joint selectors and missing trait names fail", { + samples <- list(first = list(a = 1:20), second = list(b = 1:20)) + invalid <- list( + list(first = "a", wrong = "b"), + list(first = "a", first = "b"), + list(first = "a", "b"), + list(first = "unknown", second = "b"), + list("a") + ) + for (selector in invalid) { + expect_error(get.ensemble.samples(2, samples, list(), param.names = selector)) + } + expect_error(get.ensemble.samples(2, list(pft = list(1:20)), list())) + expect_error(get.ensemble.samples(2, samples, list(), independent = c(TRUE, FALSE))) + expect_error(get.ensemble.samples(2, list(pft = list(a = numeric(0))), list())) +}) + +test_that("different bank sizes and environment samples are sampled separately", { + withr::local_seed(4) + samples <- list(first = list(a = 1:7, b = -(1:7)), + second = list(a = 1:11, b = -(1:11))) + result <- get.ensemble.samples(30, samples, list(c = 1:17)) + expect_equal(result$first$b, -result$first$a) + expect_equal(result$second$b, -result$second$a) + indices <- attr(result, "sampled.indices") + expect_false(identical(indices$first[, 1], indices$second[, 1])) + expect_false(identical(indices$first[, 1], indices$env[, 1])) + expect_error(get.ensemble.samples(2, list(env = list(a = 1:7)), list())) +}) From 014f1080c43fc1aad467e9b4e405b497d6836e3c Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:28 -0500 Subject: [PATCH 33/82] test joint draws and marginal parameter sampling --- .../testthat/test-get_parameter_samples.R | 149 +++++++++++++----- 1 file changed, 111 insertions(+), 38 deletions(-) diff --git a/modules/uncertainty/tests/testthat/test-get_parameter_samples.R b/modules/uncertainty/tests/testthat/test-get_parameter_samples.R index 92a49503b14..39c930803a1 100644 --- a/modules/uncertainty/tests/testthat/test-get_parameter_samples.R +++ b/modules/uncertainty/tests/testthat/test-get_parameter_samples.R @@ -1,9 +1,7 @@ -# ============================================================ # Tests for get_parameter_samples() # # These tests verify the extracted pure function works correctly # WITHOUT any database, file I/O, or PEcAn settings object. -# ============================================================ # Skip entire file if required PEcAn packages are not installed skip_if_not_installed("PEcAn.priors") @@ -35,9 +33,7 @@ make_mock_trait_mcmc <- function(traits = "SLA", n_samples = 100, seed = 42) { } -# ==================== # TEST 1: Returns actual data, not NULL -# ==================== test_that("get_parameter_samples returns a non-NULL list with correct names", { priors <- make_mock_priors(c("SLA")) @@ -61,9 +57,7 @@ test_that("get_parameter_samples returns a non-NULL list with correct names", { }) -# ==================== # TEST 2: No files written (pure function guarantee) -# ==================== test_that("get_parameter_samples writes no files to disk", { temp_dir <- tempfile("pure_test_") dir.create(temp_dir) @@ -88,9 +82,7 @@ test_that("get_parameter_samples writes no files to disk", { }) -# ==================== # TEST 3: Prior-only sampling (no MCMC) -# ==================== test_that("prior-only sampling produces correct structure", { priors <- make_mock_priors(c("SLA", "Vcmax")) @@ -116,9 +108,7 @@ test_that("prior-only sampling produces correct structure", { }) -# ==================== # TEST 4: MCMC sampling path -# ==================== test_that("MCMC samples are used when available", { priors <- make_mock_priors(c("SLA", "Vcmax")) mcmc <- make_mock_trait_mcmc("SLA", n_samples = 200) @@ -140,9 +130,7 @@ test_that("MCMC samples are used when available", { }) -# ==================== # TEST 5: Multiple PFTs -# ==================== test_that("multiple PFTs are handled correctly", { priors1 <- make_mock_priors("SLA") priors2 <- make_mock_priors("Vcmax") @@ -166,9 +154,7 @@ test_that("multiple PFTs are handled correctly", { }) -# ==================== # TEST 6: Sensitivity analysis samples -# ==================== test_that("SA samples are generated when quantiles are provided", { priors <- make_mock_priors("SLA") @@ -201,9 +187,7 @@ test_that("SA samples are NOT generated when quantiles is NULL", { }) -# ==================== # TEST 7: Ensemble size = 1 (median run) -# ==================== test_that("ensemble.size = 1 produces median samples", { priors <- make_mock_priors("SLA") @@ -220,9 +204,7 @@ test_that("ensemble.size = 1 produces median samples", { }) -# ==================== # TEST 8: Input validation -# ==================== test_that("pure function rejects mismatched inputs", { priors <- make_mock_priors("SLA") @@ -236,9 +218,7 @@ test_that("pure function rejects mismatched inputs", { }) -# ==================== # TEST 9: Sampling methods -# ==================== test_that("different sampling methods all produce valid output", { priors <- make_mock_priors("SLA") @@ -260,9 +240,7 @@ 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) @@ -290,9 +268,7 @@ test_that("independent = FALSE preserves param.names for correlated sampling", { }) -# TEST 11: Joint MCMC samples keep their rows -# Two traits that are exact mirror images row by row, so any member that -# mixes rows breaks b == -a +# mixing rows breaks b == -a make_paired_mcmc <- function(n_samples = 200, shift = 0, seed = 1) { set.seed(seed) a <- rnorm(n_samples) @@ -301,21 +277,35 @@ make_paired_mcmc <- function(n_samples = 200, shift = 0, seed = 1) { }) } -test_that("joint PFT keeps rows together, independent PFT does not", { - result <- get_parameter_samples( - pft_names = c("joint_pft", "ma_pft"), +test_that("joint sampling is default and independence is an ensemble request", { + withr::local_seed(1) + mcmc <- list(make_paired_mcmc(), make_paired_mcmc(shift = 100)) + joint <- get_parameter_samples( + pft_names = c("pft1", "pft2"), prior_distns_list = list(NULL, NULL), - trait_mcmc_list = list(make_paired_mcmc(), make_paired_mcmc()), - ensemble.size = 50, - do_ensemble = TRUE, - independent = c(FALSE, TRUE) + trait_mcmc_list = mcmc, + ensemble.size = 50 ) - joint <- result$ensemble.samples$joint_pft - ma <- result$ensemble.samples$ma_pft - - expect_equal(joint$b, -joint$a) - expect_true(all(joint$a %in% result$trait.samples$joint_pft$a)) - expect_false(isTRUE(all.equal(ma$b, -ma$a))) + independent <- get_parameter_samples( + pft_names = c("pft1", "pft2"), + prior_distns_list = list(NULL, NULL), + trait_mcmc_list = mcmc, + ensemble.size = 50, + independent = TRUE + ) + for (pft in c("pft1", "pft2")) { + expect_equal(joint$ensemble.samples[[pft]]$b, -joint$ensemble.samples[[pft]]$a) + expect_true(all(joint$ensemble.samples[[pft]]$a %in% joint$trait.samples[[pft]]$a)) + expect_false(isTRUE(all.equal( + independent$ensemble.samples[[pft]]$b, -independent$ensemble.samples[[pft]]$a + ))) + } + expect_error(get_parameter_samples( + pft_names = c("pft1", "pft2"), + prior_distns_list = list(NULL, NULL), + trait_mcmc_list = mcmc, + independent = c(FALSE, TRUE) + )) }) test_that("joint PFTs with the same number of rows share a row index", { @@ -365,3 +355,86 @@ test_that("joint traits with different numbers of rows fail", { "same number of rows" ) }) + +test_that("joint singleton and oversized ensembles retain allocation draws", { + withr::local_seed(1) + allocation <- list( + leaf = c(0.45, 0.45, 0.05), + wood = c(0.45, 0.05, 0.45), + root = c(0.05, 0.45, 0.45) + ) + mcmc <- lapply(allocation, function(x) { + coda::mcmc.list(coda::mcmc(matrix(x, ncol = 1, dimnames = list(NULL, "beta.o")))) + }) + for (size in c(1, 50)) { + for (method in c("uniform", "halton")) { + result <- get_parameter_samples( + pft_names = "pft", + prior_distns_list = list(NULL), + trait_mcmc_list = list(mcmc), + ensemble.size = size, + ens.sample.method = method + )$ensemble.samples$pft + expect_equal(rowSums(result), rep(0.95, size), info = method) + expect_equal(nrow(result), size) + } + } +}) + +test_that("distribution-only traits remain marginal beside joint draws", { + withr::local_seed(1) + priors <- data.frame( + distn = "norm", parama = c(0, 0, 20), paramb = c(1, 1, 2), n = 50, + row.names = c("a", "b", "c") + ) + result <- get_parameter_samples( + pft_names = "pft", + prior_distns_list = list(priors), + trait_mcmc_list = list(make_paired_mcmc()), + ensemble.size = 50 + ) + sampled <- result$ensemble.samples$pft + indices <- attr(result$ensemble.samples, "sampled.indices")$pft + expect_equal(sampled$b, -sampled$a) + expect_true(stats::sd(sampled$c) > 0) + expect_false(identical(indices[, match("a", names(sampled))], + indices[, match("c", names(sampled))])) +}) + +test_that("a distribution-only PFT does not become a joint table", { + withr::local_seed(1) + result <- get_parameter_samples( + pft_names = "pft", prior_distns_list = list(make_mock_priors("SLA")), + ensemble.size = 20 + ) + expect_false(all(result$ensemble.samples$pft$SLA %in% result$trait.samples$pft$SLA)) +}) + +test_that("the joint selector respects the sampled parameter inventory", { + withr::local_seed(1) + mcmc <- make_paired_mcmc() + priors <- data.frame(distn = "norm", parama = 0, paramb = 1, n = 50, + row.names = "a") + result <- get_parameter_samples( + pft_names = "pft", prior_distns_list = list(priors), + trait_mcmc_list = list(mcmc), ensemble.size = 20 + ) + expect_named(result$ensemble.samples$pft, "a") + expect_true(all(result$ensemble.samples$pft$a %in% mcmc$a[[1]][, "beta.o"])) +}) + +test_that("joint draws do not consume dimensions of a marginal design", { + traits <- paste0("trait", seq_len(1112)) + chain <- coda::mcmc.list(coda::mcmc(matrix( + 1:3, ncol = 1, dimnames = list(NULL, "beta.o") + ))) + mcmc <- stats::setNames(rep(list(chain), length(traits)), traits) + result <- get_parameter_samples( + pft_names = "pft", prior_distns_list = list(NULL), + trait_mcmc_list = list(mcmc), ensemble.size = 5, + ens.sample.method = "sobol" + )$ensemble.samples$pft + expect_named(result, traits) + expect_true(all(vapply(result, identical, logical(1), result[[1]]))) + expect_true(all(result[[1]] %in% 1:3)) +}) From a21c9402a0826d5f11804d8ed6b363a60265f7b5 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:28 -0500 Subject: [PATCH 34/82] test posterior loading preserves joint draws --- .../tests/testthat/test.load_posteriors.R | 59 +++++++++++-------- 1 file changed, 33 insertions(+), 26 deletions(-) diff --git a/modules/uncertainty/tests/testthat/test.load_posteriors.R b/modules/uncertainty/tests/testthat/test.load_posteriors.R index 6854e7ca024..4fffe668323 100644 --- a/modules/uncertainty/tests/testthat/test.load_posteriors.R +++ b/modules/uncertainty/tests/testthat/test.load_posteriors.R @@ -32,7 +32,7 @@ test_that("load from single distns file works", { ) expect_null(result$trait.mcmc) - expect_false(result$is.joint) + expect_named(result, c("prior.distns", "trait.mcmc")) expect_is(result$prior.distns, "data.frame") expect_equal(rownames(result$prior.distns), c("trait_a", "trait_b")) }) @@ -52,7 +52,7 @@ test_that("load from single mcmc file works", { expect_is(result$trait.mcmc, "list") expect_equal(names(result$trait.mcmc), c("trait_a", "trait_b")) expect_null(result$prior.distns) - expect_false(result$is.joint) + expect_named(result, c("prior.distns", "trait.mcmc")) }) @@ -79,7 +79,7 @@ test_that("load from directory with both mcmc and distns prefers mcmc", { expect_is(result$trait.mcmc, "list") expect_equal(names(result$trait.mcmc), c("trait_a")) expect_is(result$prior.distns, "data.frame") - expect_false(result$is.joint) + expect_named(result, c("prior.distns", "trait.mcmc")) }) @@ -232,7 +232,7 @@ test_that("nonexistent path returns empty result with error", { expect_null(result$prior.distns) expect_null(result$trait.mcmc) - expect_false(result$is.joint) + expect_named(result, c("prior.distns", "trait.mcmc")) }) @@ -251,7 +251,7 @@ test_that("empty directory returns empty result", { }) -test_that("joint detection works via companion file in from.path", { +test_that("PDA samples load alongside their companion file", { tmpdir <- withr::local_tempdir() # Create PDA-style MCMC file @@ -264,46 +264,53 @@ test_that("joint detection works via companion file in from.path", { result <- load.posteriors(posterior.file = tmpdir) - expect_true(result$is.joint) + expect_equal(result$trait.mcmc, trait.mcmc) expect_is(result$trait.mcmc, "list") }) -test_that("non-PDA mcmc is not detected as joint", { +test_that("MCMC samples load from trait.mcmc.Rdata", { tmpdir <- withr::local_tempdir() - # Create MA-style MCMC file (no companion mcmc.pda.* file) trait.mcmc <- make_trait_mcmc(trait_a = rnorm(100)) save(trait.mcmc, file = file.path(tmpdir, "trait.mcmc.Rdata")) result <- load.posteriors(posterior.file = tmpdir) - expect_false(result$is.joint) + expect_equal(result$trait.mcmc, trait.mcmc) expect_is(result$trait.mcmc, "list") }) -test_that("mcmc marked joint is detected as joint", { +test_that("both posterior loading paths preserve joint draws", { tmpdir <- withr::local_tempdir() - trait.mcmc <- make_trait_mcmc(trait_a = rnorm(100), trait_b = rnorm(100)) - attr(trait.mcmc, "joint") <- TRUE + withr::local_seed(1) + a <- rnorm(100) + trait.mcmc <- make_trait_mcmc(trait_a = a, trait_b = -a) save(trait.mcmc, file = file.path(tmpdir, "trait.mcmc.Rdata")) result <- load.posteriors(posterior.file = tmpdir) - expect_true(result$is.joint) invisible(capture.output( legacy <- load.posteriors(posterior.file = NA, outdir = tmpdir) )) - expect_true(legacy$is.joint) + for (posterior in list(result, legacy)) { + samples <- get_parameter_samples( + pft_names = "pft", + prior_distns_list = list(NULL), + trait_mcmc_list = list(posterior$trait.mcmc), + ensemble.size = 20 + )$ensemble.samples$pft + expect_equal(samples$trait_b, -samples$trait_a) + expect_true(all(samples$trait_a %in% a)) + } }) -test_that("joint detection works via filename heuristic in legacy path", { +test_that("legacy loading accepts PDA filenames", { tmpdir <- withr::local_tempdir() - # Create mcmc file with pda in name (legacy path uses filename heuristic) trait.mcmc <- make_trait_mcmc(trait_a = rnorm(100)) save(trait.mcmc, file = file.path(tmpdir, "mcmc.pda.Rdata")) @@ -314,7 +321,7 @@ test_that("joint detection works via filename heuristic in legacy path", { ) )) - expect_true(result$is.joint) + expect_equal(result$trait.mcmc, trait.mcmc) expect_is(result$trait.mcmc, "list") }) @@ -334,19 +341,19 @@ test_that("MCMC detected by coda class, not variable name", { }) -test_that("load_pft_posteriors flags joint posteriors per PFT", { - joint_dir <- withr::local_tempdir() - ma_dir <- withr::local_tempdir() +test_that("load_pft_posteriors returns posterior samples for each PFT", { + first_dir <- withr::local_tempdir() + second_dir <- withr::local_tempdir() trait.mcmc <- make_trait_mcmc(trait_a = rnorm(100)) - save(trait.mcmc, file = file.path(ma_dir, "trait.mcmc.Rdata")) - attr(trait.mcmc, "joint") <- TRUE - save(trait.mcmc, file = file.path(joint_dir, "trait.mcmc.Rdata")) + save(trait.mcmc, file = file.path(second_dir, "trait.mcmc.Rdata")) + save(trait.mcmc, file = file.path(first_dir, "trait.mcmc.Rdata")) - settings <- list(pfts = list(list(name = "joint_pft"), list(name = "ma_pft"))) + settings <- list(pfts = list(list(name = "pft1"), list(name = "pft2"))) invisible(capture.output( - loaded <- load_pft_posteriors(settings, c(joint_dir, ma_dir)) + loaded <- load_pft_posteriors(settings, c(first_dir, second_dir)) )) - expect_identical(loaded$independent, c(FALSE, TRUE)) + expect_named(loaded, c("pft_names", "prior_distns_list", "trait_mcmc_list")) + expect_equal(loaded$trait_mcmc_list, list(trait.mcmc, trait.mcmc)) }) From da4f3c32c610c2a04df07249e94f94b05d40ed3a Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:28 -0500 Subject: [PATCH 35/82] test parameter wrapper sampling requests --- .../testthat/test-get.parameter.samples.R | 41 +++++++++++-------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/modules/uncertainty/tests/testthat/test-get.parameter.samples.R b/modules/uncertainty/tests/testthat/test-get.parameter.samples.R index d2160254c75..889e5c04ee9 100644 --- a/modules/uncertainty/tests/testthat/test-get.parameter.samples.R +++ b/modules/uncertainty/tests/testthat/test-get.parameter.samples.R @@ -1,4 +1,3 @@ -# ============================================================ # Tests for the get.parameter.samples() wrapper (Layer 2) # # These exercise the WRAPPER's behaviour, not the pure @@ -15,7 +14,6 @@ # # load.posteriors() and get_parameter_samples() are stubbed with # mockery so these run with no database and no real MCMC objects. -# ============================================================ skip_if_not_installed("mockery") skip_if_not_installed("PEcAn.logger") @@ -36,8 +34,7 @@ fake_posterior <- function() { distn = "norm", parama = 20, paramb = 5, n = 50, row.names = "SLA", stringsAsFactors = FALSE ), - trait.mcmc = NULL, - is.joint = FALSE + trait.mcmc = NULL ) } @@ -65,8 +62,7 @@ test_that("samples.Rdata is written to settings$outdir by default", { list( pft_names = list("temperate.deciduous"), prior_distns_list = list(fake_posterior()$prior.distns), - trait_mcmc_list = list(fake_posterior()$trait.mcmc), - independent = TRUE + trait_mcmc_list = list(fake_posterior()$trait.mcmc) ) ) mockery::stub(get.parameter.samples, "get_parameter_samples", fake_samples_result()) @@ -88,8 +84,7 @@ test_that("explicit outdir overrides settings$outdir for the save", { list( pft_names = list("temperate.deciduous"), prior_distns_list = list(fake_posterior()$prior.distns), - trait_mcmc_list = list(fake_posterior()$trait.mcmc), - independent = TRUE + trait_mcmc_list = list(fake_posterior()$trait.mcmc) ) ) mockery::stub(get.parameter.samples, "get_parameter_samples", fake_samples_result()) @@ -111,8 +106,7 @@ test_that("outdir = NULL skips the save entirely", { list( pft_names = list("temperate.deciduous"), prior_distns_list = list(fake_posterior()$prior.distns), - trait_mcmc_list = list(fake_posterior()$trait.mcmc), - independent = TRUE + trait_mcmc_list = list(fake_posterior()$trait.mcmc) ) ) mockery::stub(get.parameter.samples, "get_parameter_samples", fake_samples_result()) @@ -138,8 +132,7 @@ test_that("samples.Rdata bundles the 5 expected objects", { list( pft_names = list("temperate.deciduous"), prior_distns_list = list(fake_posterior()$prior.distns), - trait_mcmc_list = list(fake_posterior()$trait.mcmc), - independent = TRUE + trait_mcmc_list = list(fake_posterior()$trait.mcmc) ) ) mockery::stub(get.parameter.samples, "get_parameter_samples", fake_samples_result()) @@ -168,8 +161,7 @@ test_that("returns the get_parameter_samples result invisibly", { list( pft_names = list("temperate.deciduous"), prior_distns_list = list(fake_posterior()$prior.distns), - trait_mcmc_list = list(fake_posterior()$trait.mcmc), - independent = TRUE + trait_mcmc_list = list(fake_posterior()$trait.mcmc) ) ) mockery::stub(get.parameter.samples, "get_parameter_samples", fake) @@ -193,8 +185,7 @@ test_that("loaded posteriors are delegated to get_parameter_samples", { loaded <- list( pft_names = list("temperate.deciduous"), prior_distns_list = list(post$prior.distns), - trait_mcmc_list = list(post$trait.mcmc), - independent = TRUE + trait_mcmc_list = list(post$trait.mcmc) ) mockery::stub(get.parameter.samples, "load_pft_posteriors", loaded) mock_gps <- mockery::mock(fake_samples_result()) @@ -205,5 +196,21 @@ test_that("loaded posteriors are delegated to get_parameter_samples", { mockery::expect_called(mock_gps, 1) args <- mockery::mock_args(mock_gps)[[1]] expect_identical(args$prior_distns_list[[1]], post$prior.distns) - expect_true(args$independent) + expect_false(args$independent) +}) + +test_that("the wrapper forwards an explicit independent request", { + settings <- make_test_settings(NULL) + loaded <- list( + pft_names = list("temperate.deciduous"), + prior_distns_list = list(NULL), + trait_mcmc_list = list(NULL) + ) + sampler <- mockery::mock(fake_samples_result()) + mockery::stub(get.parameter.samples, "load_pft_posteriors", loaded) + mockery::stub(get.parameter.samples, "get_parameter_samples", sampler) + + suppressWarnings(get.parameter.samples(settings, outdir = NULL, independent = TRUE)) + + expect_true(mockery::mock_args(sampler)[[1]]$independent) }) From 324e6815a0ff581927e77b6c01bbdb3d3f137049 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:28 -0500 Subject: [PATCH 36/82] test ensemble design sampling requests --- .../test-generate_joint_ensemble_design.R | 25 ++++++++++++++++--- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/modules/uncertainty/tests/testthat/test-generate_joint_ensemble_design.R b/modules/uncertainty/tests/testthat/test-generate_joint_ensemble_design.R index f7ab988ce4e..3e398e350e5 100644 --- a/modules/uncertainty/tests/testthat/test-generate_joint_ensemble_design.R +++ b/modules/uncertainty/tests/testthat/test-generate_joint_ensemble_design.R @@ -7,8 +7,7 @@ fake_loaded_posteriors <- function() { list( pft_names = list("pft1"), prior_distns_list = list(NULL), - trait_mcmc_list = list(NULL), - independent = TRUE + trait_mcmc_list = list(NULL) ) } @@ -59,6 +58,24 @@ test_that("generated samples are returned alongside the design", { expect_identical(result$samples, fake_parameter_samples()) }) +test_that("ensemble sampling follows the caller's scalar request", { + settings <- make_test_settings() + mockery::stub(generate_joint_ensemble_design, "PEcAn.uncertainty::input.ens.gen", + function(...) list(ids = rep(1L, 5))) + mockery::stub(generate_joint_ensemble_design, "load_pft_posteriors", + function(...) fake_loaded_posteriors()) + sampler <- mockery::mock(fake_parameter_samples(), cycle = TRUE) + mockery::stub(generate_joint_ensemble_design, "get_parameter_samples", sampler) + + generate_joint_ensemble_design(settings, ensemble_size = 5) + generate_joint_ensemble_design(settings, ensemble_size = 5, independent = TRUE) + + mockery::expect_called(sampler, 2) + calls <- mockery::mock_args(sampler) + expect_false(calls[[1]]$independent) + expect_true(calls[[2]]$independent) +}) + test_that("passed-in samples skip the loader and sampler", { settings <- make_test_settings() @@ -73,7 +90,7 @@ test_that("passed-in samples skip the loader and sampler", { established <- fake_parameter_samples() result <- generate_joint_ensemble_design( - settings, ensemble_size = 5, samples = established + settings, ensemble_size = 5, samples = established, independent = TRUE ) mockery::expect_called(loader, 0) @@ -269,4 +286,4 @@ test_that("the bundle carries SA samples when the settings ask for a sensitivity # way .prepare_input_designs would sample it args <- mockery::mock_args(sampler)[[1]] expect_identical(args$sa_quantiles, c(0.025, 0.5, 0.975)) -}) \ No newline at end of file +}) From 781b749eb1e3e760d6323fa9358aab7a32a10469 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:28 -0500 Subject: [PATCH 37/82] test oat quantile sampling requests --- .../tests/testthat/test-generate_OAT_SA_design.R | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/uncertainty/tests/testthat/test-generate_OAT_SA_design.R b/modules/uncertainty/tests/testthat/test-generate_OAT_SA_design.R index e52e782ffa7..d6c3c4dd68a 100644 --- a/modules/uncertainty/tests/testthat/test-generate_OAT_SA_design.R +++ b/modules/uncertainty/tests/testthat/test-generate_OAT_SA_design.R @@ -8,8 +8,7 @@ oat_loaded_posteriors <- function() { list( pft_names = list("pft1"), prior_distns_list = list(NULL), - trait_mcmc_list = list(NULL), - independent = TRUE + trait_mcmc_list = list(NULL) ) } @@ -80,6 +79,7 @@ test_that("parameters are sampled in memory when no samples are supplied", { # SA sampling draws quantiles, not an ensemble args <- mockery::mock_args(sampler)[[1]] expect_false(args$do_ensemble) + expect_false("independent" %in% names(args)) expect_identical(args$sa_quantiles, c(0.25, 0.5, 0.75)) # design is built from the freshly sampled sa.samples, and returned with them @@ -175,4 +175,4 @@ test_that("adding labels leaves the rest of the design alone", { expect_equal(nrow(design), 7) expect_equal(design$param, seq_len(7)) expect_true(all(design$met == 1)) -}) \ No newline at end of file +}) From d251c9ff8d882ab78eeb781c28db73f9ef2735e7 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:28 -0500 Subject: [PATCH 38/82] test workflow sampling requests and shared bundles --- .../test-runModule.run.write.configs.R | 57 +++++++++++++++++-- 1 file changed, 53 insertions(+), 4 deletions(-) diff --git a/base/workflow/tests/testthat/test-runModule.run.write.configs.R b/base/workflow/tests/testthat/test-runModule.run.write.configs.R index b3d1ff50f8c..5252abaae7d 100644 --- a/base/workflow/tests/testthat/test-runModule.run.write.configs.R +++ b/base/workflow/tests/testthat/test-runModule.run.write.configs.R @@ -22,8 +22,7 @@ fake_loaded <- function() { list( pft_names = list("temperate.deciduous"), prior_distns_list = list(NULL), - trait_mcmc_list = list(NULL), - independent = TRUE + trait_mcmc_list = list(NULL) ) } @@ -92,6 +91,56 @@ test_that(".prepare_input_designs hands the sampled bundle to the generator", { expect_identical(designs$samples, bundle) }) +test_that("workflow sampling follows the caller's scalar request", { + tmp <- withr::local_tempdir() + settings <- make_prep_settings(tmp) + sampler <- mockery::mock(fake_bundle(), cycle = TRUE) + mockery::stub(.prepare_input_designs, + "PEcAn.uncertainty::load_pft_posteriors", function(...) fake_loaded()) + mockery::stub(.prepare_input_designs, + "PEcAn.uncertainty::get_parameter_samples", sampler) + mockery::stub(.prepare_input_designs, + "PEcAn.uncertainty::generate_joint_ensemble_design", + function(...) list(design_matrix = data.frame(param = 1:3))) + + suppressWarnings(.prepare_input_designs(settings, NULL)) + suppressWarnings(.prepare_input_designs(settings, NULL, independent = TRUE)) + + mockery::expect_called(sampler, 2) + calls <- mockery::mock_args(sampler) + expect_false(calls[[1]]$independent) + expect_true(calls[[2]]$independent) +}) + +test_that("multisite preparation passes one shared bundle and sampling request", { + tmp <- withr::local_tempdir() + first <- PEcAn.settings::as.Settings(make_prep_settings(tmp)) + first$rundir <- tmp + second <- first + second$run <- list(site = list(id = "second")) + settings <- PEcAn.settings::MultiSettings(first, second) + shared <- list( + ensemble = data.frame(param = 1:3), + sensitivity = NULL, + samples = fake_bundle() + ) + prepare <- mockery::mock(shared) + apply_sites <- mockery::mock(settings) + mockery::stub(runModule.run.write.configs, ".prepare_input_designs", prepare) + mockery::stub(runModule.run.write.configs, "PEcAn.settings::papply", apply_sites) + + runModule.run.write.configs(settings, overwrite = FALSE, independent = TRUE) + + mockery::expect_called(prepare, 1) + prepared <- mockery::mock_args(prepare)[[1]] + expect_identical(prepared[[1]], settings[1]) + expect_true(prepared[[3]]) + passed <- mockery::mock_args(apply_sites)[[1]] + expect_identical(passed$input_design, shared) + expect_true(passed$independent) + expect_false(passed$overwrite) +}) + test_that(".prepare_input_designs returns an input_design list unchanged", { gen <- mockery::mock() @@ -138,7 +187,7 @@ test_that(".prepare_input_designs reuses a supplied list(X, samples) and does no mockery::stub(.prepare_input_designs, "PEcAn.uncertainty::generate_joint_ensemble_design", gen) - designs <- .prepare_input_designs(settings, input_design = supplied) + designs <- .prepare_input_designs(settings, input_design = supplied, independent = TRUE) mockery::expect_called(loader, 0) mockery::expect_called(gps, 0) @@ -382,4 +431,4 @@ test_that("a partly labelled design is not mistaken for a sensitivity design", { expect_identical(designs$ensemble, supplied$design_matrix) expect_null(designs$sensitivity) -}) \ No newline at end of file +}) From aa5a43aca4fb72badee9e6cb87f15bd60cb08fee Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:28 -0500 Subject: [PATCH 39/82] describe joint sampling behavior in uncertainty news --- modules/uncertainty/NEWS.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/modules/uncertainty/NEWS.md b/modules/uncertainty/NEWS.md index d394370e6e9..9a26e486ead 100644 --- a/modules/uncertainty/NEWS.md +++ b/modules/uncertainty/NEWS.md @@ -1,6 +1,8 @@ # PEcAn.uncertainty 1.9.0.9000 -* MCMC samples marked with `attr(trait.mcmc, "joint") <- TRUE` are treated as joint draws: `get.ensemble.samples()` gives each member a whole row, with one row index shared by PFTs that have the same number of rows. `get_parameter_samples()` argument `independent` and the `independent` returned by `load_pft_posteriors()` are now one value per PFT, so a joint posterior no longer changes how other PFTs are sampled. A joint PFT whose traits have different numbers of rows is now an error. +* Breaking: ensemble sampling preserves correlations between supplied MCMC parameters by default. Parameters available only as distributions are sampled independently. `independent = TRUE` requests separate sampling of all parameters and can violate joint constraints. +* Joint draws are sampled by whole rows with replacement, including for a one-member ensemble. Equal-length PFT tables share row indices; corresponding rows must be aligned. Joint traits with unequal sample counts are rejected. `method` controls marginal sampling only. +* `get.ensemble.samples()` matches named `param.names` entries by PFT name. `param.names = NULL` selects all supplied PFT parameters for joint sampling; an empty entry selects none. * In `run.sensitivity.analysis()`, load `samples` once before the variables loop, avoiding repeated disk reads (#3859). * `get.ensemble.samples()` now again returns a list of dataframes as it did before v1.9.0. The returned list also now has attribute `sampled.indices`, From 8fda731b83ea24b19b89c1ab089c1db3c13f0c2f Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:29 -0500 Subject: [PATCH 40/82] describe workflow sampling option in news --- base/workflow/NEWS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/base/workflow/NEWS.md b/base/workflow/NEWS.md index 59add5bdc7e..ceb45896d57 100644 --- a/base/workflow/NEWS.md +++ b/base/workflow/NEWS.md @@ -1,6 +1,7 @@ # PEcAn.workflow 1.10.0.9000 ## Changed +* `runModule.run.write.configs()` preserves MCMC parameter correlations by default. Set `independent = TRUE` to sample all parameters separately. * `run.write.configs()` now requires `samples` to contain an `ensemble.samples` (as was already required for `sa.samples`) and no longer re-draws it from `trait.samples`. (#4185) From e8febf10478d1183b035673bc5be6cb5f4faae52 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 12 Nov 2026 12:58:29 -0500 Subject: [PATCH 41/82] record joint ensemble sampling changes --- CHANGELOG.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 826930b45a2..22e0c2ea6b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,8 +10,6 @@ For more information about this file see also [Keep a Changelog](http://keepacha ### Added -- `PEcAn.uncertainty`: MCMC samples can be marked as joint draws with `attr(trait.mcmc, "joint") <- TRUE`. Ensemble members then take whole rows of the samples instead of resampling each trait on its own, and PFTs with the same number of rows share one row index. Other MCMC samples, such as meta-analysis output, are still resampled one trait at a time; PDA output is still recognized as joint. - - `PEcAn.settings::setEnsemblePaths()` can now include site-specific components in the paths it generates (#4100). - `PEcAn.SIPNET::model2netcdf.SIPNET()` now also writes `soil_organic_carbon_content` (soil pool only, excluding litter) alongside `TotSoilCarb` (soil + litter) (#4160). - Added regression tests to `PEcAn.settings` confirming `check.ensemble.settings()` does not add an `ensemble` block to settings that lack one (#3024). @@ -51,7 +49,7 @@ For more information about this file see also [Keep a Changelog](http://keepacha ### Fixed -- `PEcAn.uncertainty`: joint sampling is now decided per PFT. Before, one PDA posterior made every PFT's MCMC samples be resampled by row, and each PFT drew its own rows; a PFT with nothing to sample could also shift which PFT's trait list was used for the next one, and `method = "random"` failed with "invalid first argument" when a joint PFT sat next to one sampled from priors (#3674). +- `PEcAn.uncertainty`: joint ensembles retain complete supplied draws for one or many members, including ensembles larger than the draw bank. Named trait selectors are matched by PFT name, and an empty PFT no longer shifts subsequent selectors. - `PEcAn.utils::match_file()` anchors file prefixes to the beginning of the filename, so a request for `foo/site1` no longer matches `foo/old-site1` (but still finds `foo/site1-old` as previously) (#4196, @Shubham-Padkonde). - PEcAnAssimSequential: `simple.local()` and `piecew.poly.local()` now scale distances by their `scalef` argument instead of the undefined `rloc`; `GEF()`, `GEF.MultiSite()` and `EnKF.MultiSite()` read their extra arguments from `...` explicitly instead of assigning them into the global environment; `SDA_remote_launcher()` no longer references an undefined `stop.on.error`. Together these clear most of the package's "no visible binding for global variable" check notes (#2758). - `PEcAn.SIPNET::write.config.SIPNET()` wrote `stem_respiration_rate` and `root_respiration_rate` as per day rates into SIPNET's per year `baseVegResp` and `baseFineRootResp`, 365x too low. @@ -78,6 +76,7 @@ For more information about this file see also [Keep a Changelog](http://keepacha ### Changed +- `PEcAn.uncertainty`: breaking change: MCMC parameters are sampled jointly by default; distribution-only parameters remain independent. Set `independent = TRUE` to sample all parameters separately. Joint rows are selected randomly with replacement, with shared row indices for equal-length PFT tables; corresponding source rows must be aligned. The sampling method controls marginal sampling only. - 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) From ef814880cdaba27e56bca0c50ebd66992a8ea6fa Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:37 -0500 Subject: [PATCH 42/82] look up joint traits by pft name and stop on unequal lengths --- modules/uncertainty/R/ensemble.R | 119 ++++++++----------------------- 1 file changed, 31 insertions(+), 88 deletions(-) diff --git a/modules/uncertainty/R/ensemble.R b/modules/uncertainty/R/ensemble.R index dbc4d235a5e..abbaaf6019f 100644 --- a/modules/uncertainty/R/ensemble.R +++ b/modules/uncertainty/R/ensemble.R @@ -60,106 +60,50 @@ read.ensemble.output <- function(ensemble.size, pecandir, outdir, start.year, en #' Get parameter values used in ensemble #' -#' Returns sampled parameter values for model runs, preserving supplied joint -#' draws unless independent sampling is requested. +#' 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 #' #' @param ensemble.size number of runs in model ensemble -#' @param pft.samples named list of PFTs, each containing named parameter -#' samples, e.g. from MCMC chains. The name "env" is reserved. +#' @param pft.samples random samples from parameter distribution, e.g. from a MCMC chain #' @param env.samples env samples -#' @param method sampling method for marginal traits: "random", "uniform", -#' "halton", "sobol", or "lhc". Joint draws are sampled randomly by row. -#' @param param.names named list of joint trait names per PFT. NULL selects all -#' supplied traits; an empty entry selects none. Unnamed lists match PFT order. +#' @param method the method used to generate the ensemble samples for traits sampled independently. 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. +#' When \code{ensemble.size > 1}, traits listed in \code{param.names} ignore \code{method}: each member takes one complete MCMC row, drawn at random with replacement. +#' @param param.names list named by PFT, each element the traits whose MCMC samples are drawn together by row. Joint traits of a PFT must have equal length. NULL samples every trait independently. #' @param ... Other arguments passed on to the sampling method -#' @param independent logical. Sample each parameter separately, discarding -#' supplied dependence, instead of preserving parameter correlations. -#' -#' @details Joint draws preserve parameter correlations (by keeping complete -#' MCMC rows together). Rows are sampled with replacement. PFTs with equal -#' numbers of joint draws share row indices, so paired input tables must have -#' matching row order. Equal row counts do not establish common provenance; -#' unrelated tables must contain genuinely independent draws. Environment -#' samples and traits outside \code{param.names} are sampled marginally. -#' A one-member joint ensemble selects a complete draw; marginal traits use -#' their medians. Independent sampling can violate joint parameter constraints. #' #' @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, ..., - independent = FALSE) { - - stopifnot( - is.logical(independent), length(independent) == 1L, !is.na(independent), - is.list(pft.samples), - is.numeric(ensemble.size), length(ensemble.size) == 1L, - is.finite(ensemble.size), ensemble.size == floor(ensemble.size) - ) - pft.names <- names(pft.samples) - if (length(pft.samples) > 0) { - stopifnot(!is.null(pft.names), !anyNA(pft.names), - all(nzchar(pft.names)), !anyDuplicated(pft.names), - !"env" %in% pft.names) - } - if (independent) { - param.names <- lapply(pft.samples, function(x) character(0)) - } else if (is.null(param.names)) { - param.names <- lapply(pft.samples, names) - } else { - stopifnot(is.list(param.names), length(param.names) == length(pft.samples)) - if (is.null(names(param.names))) { - names(param.names) <- pft.names - } else { - stopifnot(!anyNA(names(param.names)), all(nzchar(names(param.names))), - !anyDuplicated(names(param.names)), - setequal(names(param.names), pft.names)) - param.names <- param.names[pft.names] - } - } - for (pft.name in pft.names) { - trait.names <- names(pft.samples[[pft.name]]) - if (length(pft.samples[[pft.name]]) > 0) { - stopifnot(!is.null(trait.names), !anyNA(trait.names), - all(nzchar(trait.names)), !anyDuplicated(trait.names)) - } - traits <- param.names[[pft.name]] - stopifnot(is.null(traits) || is.character(traits), !anyNA(traits), - !anyDuplicated(traits), all(traits %in% names(pft.samples[[pft.name]]))) - if (length(traits) > 0) { - n.rows <- unique(lengths(pft.samples[[pft.name]][traits])) - if (length(n.rows) != 1L || n.rows == 0L) { - PEcAn.logger::logger.severe( - "Joint samples for PFT", pft.name, - "need the same number of rows, greater than zero, for every trait; got", - paste(n.rows, collapse = ", ") - ) - } - } - } + method = "random", param.names = NULL, ...) { # Define supported methods supported_methods <- c("random", "uniform", "halton", "sobol", "lhc") if (!method %in% supported_methods) { - PEcAn.logger::logger.severe("Invalid sampling method:", method) + stop("Invalid sampling method") } ## force as numeric for compatibility with Fortran code in halton() ensemble.size <- as.numeric(ensemble.size) if (ensemble.size <= 0) { ans <- NULL - } else if (ensemble.size == 1 && !any(lengths(param.names) > 0)) { + } else if (ensemble.size == 1) { ans <- PEcAn.utils::get.sa.sample.list(pft.samples, env.samples, 0.5) } else { - pft.samples <- c(pft.samples, list(env = env.samples)) - total.sample.num <- sum(lengths(pft.samples)) - sum(lengths(param.names)) + pft.samples[[length(pft.samples) + 1]] <- env.samples + names(pft.samples)[length(pft.samples)] <- "env" + pft2col <- NULL + for (i in seq_along(pft.samples)) { + pft2col <- c(pft2col, rep(i, length(pft.samples[[i]]))) + } + + total.sample.num <- sum(sapply(pft.samples, length)) random.samples <- NULL - if (ensemble.size == 1 || total.sample.num == 0) { - random.samples <- matrix(0.5, ensemble.size, total.sample.num) - } else if (method == "halton") { + if (method == "halton") { PEcAn.logger::logger.info("Using ", method, "method for sampling") random.samples <- randtoolbox::halton(n = ensemble.size, dim = total.sample.num, ...) ## force as a matrix in case length(samples) = 1 @@ -184,7 +128,7 @@ get.ensemble.samples <- function( ensemble.size, pft.samples, env.samples, ensemble.size, total.sample.num) } else { - PEcAn.logger::logger.info("Using random sampling") + PEcAn.logger::logger.info("Method ", method, " has not been implemented yet, using uniform random sampling") # uniform random random.samples <- matrix(stats::runif(ensemble.size * total.sample.num), ensemble.size, @@ -194,30 +138,29 @@ get.ensemble.samples <- function( ensemble.size, pft.samples, env.samples, ensemble.samples <- list() sampled.indices <- list() - joint.rows <- list() col.i <- 0 for (pft.i in seq(pft.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]])) - joint.traits <- param.names[[names(pft.samples)[pft.i]]] - if (length(joint.traits) > 0) { - n.rows <- length(pft.samples[[pft.i]][[joint.traits[1]]]) - key <- as.character(n.rows) - if (is.null(joint.rows[[key]])) { - # shared indices retain the caller's pairing between equal-sized banks - joint.rows[[key]] <- sample.int(n.rows, ensemble.size, replace = TRUE) + # meaning we want to keep MCMC samples together + joint <- names(pft.samples[[pft.i]]) %in% param.names[[names(pft.samples)[pft.i]]] + if (any(joint)) { + n.rows <- unique(lengths(pft.samples[[pft.i]][joint])) + if (length(n.rows) > 1) { + PEcAn.logger::logger.severe("PFT", names(pft.samples)[pft.i], "joint traits differ in length:", paste(n.rows, collapse = ", ")) } - same.i <- joint.rows[[key]] + # draws whole MCMC 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]])) { - if (names(pft.samples[[pft.i]])[trait.i] %in% joint.traits) { + col.i <- col.i + 1 + if (joint[trait.i]) { ensemble.samples[[pft.i]][, trait.i] <- pft.samples[[pft.i]][[trait.i]][same.i] sampled.indices[[pft.i]][, trait.i] <- same.i } else { - col.i <- col.i + 1 # Extract original trait values trait.values <- pft.samples[[pft.i]][[trait.i]] sampled.values <- stats::quantile(trait.values, random.samples[, col.i]) From 43e653eb444d0a92742472bf185354c268cb578c Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:37 -0500 Subject: [PATCH 43/82] default get_parameter_samples to joint draws --- modules/uncertainty/R/get_parameter_samples.R | 63 ++++++++++--------- 1 file changed, 33 insertions(+), 30 deletions(-) diff --git a/modules/uncertainty/R/get_parameter_samples.R b/modules/uncertainty/R/get_parameter_samples.R index ef056ea7953..6a9c29f0ce2 100644 --- a/modules/uncertainty/R/get_parameter_samples.R +++ b/modules/uncertainty/R/get_parameter_samples.R @@ -13,19 +13,14 @@ #' 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. Marginal sampling method: "halton", -#' "sobol", "lhc", "random", or "uniform". +#' @param ens.sample.method character. One of "halton", "sobol", "torus", +#' "lhc", "uniform". #' @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. Sample each parameter separately, discarding -#' supplied dependence, instead of preserving parameter correlations. -#' -#' @details MCMC samples are sampled jointly by default (by keeping complete -#' draws together). Traits available only as distributions remain marginal. -#' Equal-sized MCMC tables share row indices and must preserve any paired row -#' order. Independent sampling may violate joint constraints such as allocation -#' sums. See \code{\link{get.ensemble.samples}} for the sampling contract. +#' @param independent logical. FALSE (default) keeps complete MCMC draws +#' together, so correlations between parameters are kept. TRUE samples each +#' parameter independently, ignoring any joint structure. #' #' @return named list with five elements: #' \describe{ @@ -62,7 +57,7 @@ #' str(result$ensemble.samples) #' } #' -#' @seealso \code{\link{get.parameter.samples}} for the disk-based +#' @seealso \code{\link{get.parameter.samples}} for the backward-compatible #' wrapper that handles file I/O and database lookups. #' #' @author David LeBauer, Shawn Serbin, Istem Fer, Om Kapale @@ -92,11 +87,6 @@ get_parameter_samples <- function(pft_names, length(trait_mcmc_list) == length(pft_names) ) } - stopifnot( - is.logical(independent), - !anyNA(independent), - length(independent) == 1L - ) # Force numeric for compatibility with downstream sampling code ensemble.size <- as.numeric(ensemble.size) @@ -167,10 +157,10 @@ get_parameter_samples <- function(pft_names, next } - marginal.priors <- setdiff(priors, param.names[[i]]) + # Generate quantile matrix for prior-based sampling q_samples <- .generate_quantile_samples( n = samples.num, - dim = length(marginal.priors), + dim = n_priors, method = ens.sample.method ) # Ensure q_samples is always a matrix (some methods return vector when dim=1) @@ -191,18 +181,20 @@ get_parameter_samples <- function(pft_names, samples <- PEcAn.priors::get.sample( prior.distns[prior, ], samples.num, - q_samples[, match(prior, marginal.priors)] + q_samples[, priors == prior] ) } trait.samples[[pft.name]][[prior]] <- samples } } - # an explicit selector keeps distribution-only traits marginal - names(param.names) <- pft_names - param.names <- Map(function(traits, samples) { - intersect(as.character(traits), names(samples)) - }, param.names[names(trait.samples)], trait.samples) + # ---- Handle independence flag ---- + # independent = TRUE asks for each parameter to be sampled on its own, so drop param.names. + # 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)) { @@ -225,15 +217,21 @@ get_parameter_samples <- function(pft_names, # ---- Ensemble samples ---- if (do_ensemble) { - if (ensemble.size > 0) { + if (ensemble.size == 1) { + ## Run at median if only one run in ensemble + ensemble.samples <- PEcAn.utils::get.sa.sample.list( + pft = trait.samples, + env = env.samples, + quantiles = 0.5 + ) + } else if (ensemble.size > 1) { ## Subset trait.samples to ensemble size ensemble.samples <- get.ensemble.samples( ensemble.size = ensemble.size, pft.samples = trait.samples, env.samples = env.samples, method = ens.sample.method, - param.names = param.names, - independent = independent + param.names = param.names ) } } @@ -266,8 +264,13 @@ get_parameter_samples <- function(pft_names, "sobol" = randtoolbox::sobol(n = n, dim = dim, scrambling = 3), "torus" = randtoolbox::torus(n = n, dim = dim), "lhc" = PEcAn.emulator::lhc(t(matrix(0:1, ncol = dim, nrow = 2)), n), - "uniform" =, - "random" = matrix(stats::runif(n * dim), n, dim), - PEcAn.logger::logger.severe("Invalid sampling method:", method) + "uniform" = matrix(stats::runif(n * dim), n, dim), + { + PEcAn.logger::logger.info( + "Method ", method, + " has not been implemented yet, using uniform random sampling" + ) + matrix(stats::runif(n * dim), n, dim) + } ) } From 710df1326f84f024e10aa1332ce7a9b86003daff Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:37 -0500 Subject: [PATCH 44/82] restore get.parameter.samples loader flag --- modules/uncertainty/R/get.parameter.samples.R | 40 ++++++++++--------- 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/modules/uncertainty/R/get.parameter.samples.R b/modules/uncertainty/R/get.parameter.samples.R index 5d41add9865..d40be4be249 100644 --- a/modules/uncertainty/R/get.parameter.samples.R +++ b/modules/uncertainty/R/get.parameter.samples.R @@ -2,7 +2,7 @@ #' #' Loads posterior distributions and MCMC chain results from disk, generates #' parameter samples for ensemble and sensitivity analysis runs, and optionally -#' saves results to `samples.Rdata`. This is the deprecated wrapper +#' saves results to `samples.Rdata`. This is the backward-compatible wrapper #' that delegates computation to \code{\link[PEcAn.uncertainty]{get_parameter_samples}}. #' #' @details @@ -11,8 +11,8 @@ #' \item{`post.distns.Rdata` or `prior.distns.Rdata`}{Posterior (or prior) #' distribution summaries produced by \code{run.meta.analysis.pft}. A data #' frame with columns `distn`, `parama`, `paramb`, `n`.} -#' \item{`trait.mcmc.Rdata`}{(Optional) posterior MCMC samples. -#' Named list of `mcmc.list` objects, one per trait. +#' \item{`trait.mcmc.Rdata`}{(Optional) MCMC chain samples from the +#' meta-analysis. Named list of `mcmc.list` objects, one per trait. #' If present, samples are drawn from the chains directly; otherwise, #' independent samples are drawn from `post.distns`.} #' } @@ -34,22 +34,22 @@ #' }} #' } #' -#' **Downstream contract:** The workflow passes the parameter bundle directly to -#' \code{run.write.configs} in memory. That writer can also load `samples.Rdata` -#' when no bundle is supplied. \code{\link[PEcAn.uncertainty]{get.results}} can -#' read the saved file when ensemble-specific samples are unavailable, and -#' \code{\link[PEcAn.uncertainty]{run.sensitivity.analysis}} reads it for traits. +#' **Downstream contract:** `samples.Rdata` is loaded by \code{run.write.configs} +#' (in `PEcAn.workflow`) to generate model configuration files. It is also +#' loaded by \code{\link[PEcAn.uncertainty]{get.results}} and \code{\link[PEcAn.uncertainty]{run.sensitivity.analysis}} to retrieve +#' sample metadata for post-processing. This implicit file-based coupling is +#' a refactoring target. #' #' @param settings PEcAn settings object #' @param ensemble.size number of runs in model ensemble #' @param posterior.files list of filenames to read from -#' @param ens.sample.method marginal sampling method: `"halton"`, `"sobol"`, -#' `"lhc"`, `"random"`, or `"uniform"`. -#' @param outdir directory for `samples.Rdata`, defaulting to `settings$outdir`. -#' Use `NULL` to return samples without saving a file. -#' @param independent Logical scalar. If `FALSE` (default), preserve -#' dependence among supplied MCMC parameters. If `TRUE`, sample each -#' parameter separately, ignoring supplied dependence. +#' @param ens.sample.method one of `"halton"`, `"sobol"`, `"torus"`, `"lhc"`, +#' `"uniform"` +#' @param outdir character path; directory to write `samples.Rdata` to for +#' provenance. Defaults to `settings$outdir`, preserving the legacy +#' always-save behaviour for existing callers (none of which pass it). +#' Pass `outdir = NULL` to skip the save entirely; the pure +#' `get_parameter_samples()` never writes to disk regardless. #' #' @return Named list with 5 elements: `trait.samples`, `sa.samples`, #' `ensemble.samples`, `runs.samples`, `env.samples`. Returned invisibly. @@ -64,9 +64,7 @@ get.parameter.samples <- function(settings, ensemble.size = 1, posterior.files = rep(NA, length(settings$pfts)), ens.sample.method = "uniform", - outdir = settings$outdir, - independent = FALSE) { - stopifnot(is.logical(independent), length(independent) == 1L, !is.na(independent)) + outdir = settings$outdir) { .Deprecated("get_parameter_samples") ### Identify PFTs in the input settings.xml file @@ -82,6 +80,7 @@ get.parameter.samples <- function(settings, pft.names <- loaded$pft_names prior_distns_list <- loaded$prior_distns_list trait_mcmc_list <- loaded$trait_mcmc_list + independent <- loaded$independent ## ---- Delegate to pure function ---- result <- get_parameter_samples( @@ -95,6 +94,11 @@ get.parameter.samples <- function(settings, independent = independent ) + ## ---- Save to disk for provenance (opt-in via `outdir`) ---- + # `outdir` defaults to `settings$outdir`, so existing callers (none of which + # pass it) write `samples.Rdata` exactly as before. Pass `outdir = NULL` to + # skip the save for a purely in-memory call; the pure get_parameter_samples() + # never writes to disk at all. if (!is.null(outdir)) { ensemble.samples <- result$ensemble.samples trait.samples <- result$trait.samples From e86de217ce163607cccbf0029eb96fe996b875ab Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:38 -0500 Subject: [PATCH 45/82] restore independent flag in load_pft_posteriors --- modules/uncertainty/R/load_pft_posteriors.R | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/modules/uncertainty/R/load_pft_posteriors.R b/modules/uncertainty/R/load_pft_posteriors.R index ac063e06bd6..e5f8e314704 100644 --- a/modules/uncertainty/R/load_pft_posteriors.R +++ b/modules/uncertainty/R/load_pft_posteriors.R @@ -9,8 +9,9 @@ #' #' Posterior type is detected by content, not filename, via #' \code{\link{load.posteriors}}: MCMC chains take precedence over distribution -#' summaries. Downstream joint sampling preserves parameter correlations -#' (for MCMC samples, by keeping complete draws together). +#' summaries. When a PFT's posterior is a joint fit (e.g. from PDA), the +#' returned \code{independent} flag is set to \code{FALSE} so downstream +#' sampling preserves the parameter correlations. #' #' @param settings PEcAn settings object. Uses \code{settings$pfts} (name, #' outdir, posteriorid per PFT), \code{settings$database$bety} for the @@ -18,13 +19,15 @@ #' @param posterior.files character vector of posterior filenames, one per PFT, #' \code{NA} where none is specified. Length must match \code{settings$pfts}. #' -#' @return A list with three elements: +#' @return A list with four elements: #' \describe{ #' \item{pft_names}{character vector of PFT names ("NULL" where unnamed).} #' \item{prior_distns_list}{list of prior distribution data frames, one per #' PFT (\code{NULL} entry where none was found).} #' \item{trait_mcmc_list}{list of trait MCMC results, one per PFT #' (\code{NULL} entry where the PFT has no MCMC chains).} +#' \item{independent}{logical, \code{FALSE} if any PFT carries a joint +#' posterior, \code{TRUE} otherwise.} #' } #' #' @seealso \code{\link{get_parameter_samples}} for the sampling step that @@ -85,6 +88,7 @@ load_pft_posteriors <- function(settings, ## Load priors and posteriors for each PFT prior_distns_list <- vector("list", length(pft.names)) trait_mcmc_list <- vector("list", length(pft.names)) + independent <- TRUE for (i in seq_along(pft.names)) { posterior <- load.posteriors( @@ -101,13 +105,18 @@ load_pft_posteriors <- function(settings, if (!is.null(posterior$trait.mcmc)) { trait_mcmc_list[[i]] <- posterior$trait.mcmc + # Joint posteriors (e.g. from PDA) should preserve correlations + if (posterior$is.joint) { + independent <- FALSE + } } # else trait_mcmc_list[[i]] stays NULL } list( pft_names = pft.names, prior_distns_list = prior_distns_list, - trait_mcmc_list = trait_mcmc_list + trait_mcmc_list = trait_mcmc_list, + independent = independent ) } From 8ba1f6d642a1f2e3969dedcff5ce36f6cc1e1517 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:38 -0500 Subject: [PATCH 46/82] restore is.joint detection in load.posteriors --- modules/uncertainty/R/load_posteriors.R | 43 ++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 5 deletions(-) diff --git a/modules/uncertainty/R/load_posteriors.R b/modules/uncertainty/R/load_posteriors.R index d73dc3f4460..351bf9eec78 100644 --- a/modules/uncertainty/R/load_posteriors.R +++ b/modules/uncertainty/R/load_posteriors.R @@ -16,7 +16,9 @@ #' legacy fallback path. #' @param hostname \strong{Deprecated.} Hostname for DB file lookup, used #' only in the legacy fallback path. -#' @return list with \code{prior.distns} and \code{trait.mcmc}. +#' @return list with \code{prior.distns}, \code{trait.mcmc}, \code{is.joint}. +#' \code{is.joint} is \code{TRUE} when MCMC samples represent a joint +#' posterior (e.g. from PDA) and parameter correlations should be preserved. #' @keywords internal #' @author Siddhey Patil load.posteriors <- function(posterior.file, @@ -51,12 +53,13 @@ load.posteriors <- function(posterior.file, #' \code{post.distns} and \code{prior.distns}. #' #' @param path file path or directory path -#' @return List with \code{prior.distns} and \code{trait.mcmc} +#' @return List with \code{prior.distns}, \code{trait.mcmc}, \code{is.joint} #' @keywords internal load.posteriors.from.path <- function(path) { result <- list( prior.distns = NULL, - trait.mcmc = NULL + trait.mcmc = NULL, + is.joint = FALSE ) if (!file.exists(path)) { @@ -147,6 +150,22 @@ load.posteriors.from.path <- function(path) { ) } + # Detect joint posterior: check for a companion mcmc.pda.* file in the + # same directory, which PDA always creates alongside trait.mcmc.pda.* + if (!is.null(result$trait.mcmc)) { + scan_dir <- if (dir.exists(path)) path else dirname(path) + pda_companions <- list.files( + scan_dir, pattern = "^mcmc\\.pda\\.", ignore.case = TRUE + ) + if (length(pda_companions) > 0) { + result$is.joint <- TRUE + PEcAn.logger::logger.info( + "Detected joint posterior (PDA companion file found in ", + scan_dir, ")" + ) + } + } + return(result) } @@ -161,7 +180,7 @@ load.posteriors.from.path <- function(path) { #' @param posteriorid Posterior ID for database lookup #' @param con db connection #' @param hostname host name for dbfile lookup -#' @return List with \code{prior.distns} and \code{trait.mcmc} +#' @return List with \code{prior.distns}, \code{trait.mcmc}, \code{is.joint} #' @keywords internal load.posteriors.legacy <- function(outdir = NULL, posteriorid = NULL, @@ -169,7 +188,8 @@ load.posteriors.legacy <- function(outdir = NULL, hostname = NULL) { result <- list( prior.distns = NULL, - trait.mcmc = NULL + trait.mcmc = NULL, + is.joint = FALSE ) ## Step 1: Load distribution summaries from outdir @@ -225,9 +245,16 @@ load.posteriors.legacy <- function(outdir = NULL, "Found Monte Carlo samples in DB-referenced file: ", fpath ) result$trait.mcmc <- env$trait.mcmc + # Detect PDA samples to preserve correlations if (exists("post.distns", envir = env, inherits = FALSE)) { result$prior.distns <- result$prior.distns %||% env$post.distns } + # In the legacy DB path, detect joint posterior via filename + # heuristic (PDA convention: trait.mcmc.pda.*) + fname_lower <- tolower(files$file_name[idx]) + if (grepl("pda", fname_lower)) { + result$is.joint <- TRUE + } break # Use first MCMC found } } @@ -253,6 +280,12 @@ load.posteriors.legacy <- function(outdir = NULL, "Found Monte Carlo samples in outdir file: ", f ) result$trait.mcmc <- env$trait.mcmc + # In the legacy outdir-scan path, detect joint posterior via + # filename heuristic (PDA convention: trait.mcmc.pda.*) + fname_lower <- tolower(basename(f)) + if (grepl("pda", fname_lower)) { + result$is.joint <- TRUE + } break } } From f7b54e9aad241141c86d731495226a448ac8105a Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:38 -0500 Subject: [PATCH 47/82] drop independent argument from generate_joint_ensemble_design --- modules/uncertainty/R/generate_joint_ensemble_design.R | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/modules/uncertainty/R/generate_joint_ensemble_design.R b/modules/uncertainty/R/generate_joint_ensemble_design.R index 222bf4560e0..85272e5cbb9 100644 --- a/modules/uncertainty/R/generate_joint_ensemble_design.R +++ b/modules/uncertainty/R/generate_joint_ensemble_design.R @@ -44,9 +44,6 @@ #' \code{load_pft_posteriors} and \code{get_parameter_samples}. #' @param sobol Logical. If TRUE, returns a \code{sensitivity::soboljansen} #' object for Sobol sensitivity analysis. -#' @param independent Logical scalar: \code{FALSE} preserves supplied MCMC -#' dependence; \code{TRUE} discards it and samples parameters separately. -#' Used only when \code{samples = NULL}; supplied samples are reused unchanged. #' #' @return If \code{sobol = FALSE}, a list with \code{design_matrix} (the design, #' one row per run, whose \code{param} column indexes the samples), \code{X} @@ -63,9 +60,7 @@ generate_joint_ensemble_design <- function(settings, ensemble_size, samples = NULL, - sobol = FALSE, - independent = FALSE) { - stopifnot(is.logical(independent), length(independent) == 1L, !is.na(independent)) + sobol = FALSE) { if (sobol) { ensemble_size <- as.numeric(ensemble_size) * 2 } @@ -115,7 +110,7 @@ generate_joint_ensemble_design <- function(settings, ens.sample.method = ens.sample.method, sa_quantiles = settings$sensitivity.analysis$quantiles, do_ensemble = TRUE, - independent = independent + independent = loaded$independent ) } # Here we assumed the length of parameters is identical to the ensemble size. From 0ddcffff2c5652957b3dee15e865ef2dce778fcf Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:38 -0500 Subject: [PATCH 48/82] take independent from loader in oat design --- modules/uncertainty/R/generate_OAT_SA_design.R | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/modules/uncertainty/R/generate_OAT_SA_design.R b/modules/uncertainty/R/generate_OAT_SA_design.R index 2771c859469..c59bcae02b7 100644 --- a/modules/uncertainty/R/generate_OAT_SA_design.R +++ b/modules/uncertainty/R/generate_OAT_SA_design.R @@ -87,7 +87,8 @@ generate_OAT_SA_design <- function(settings, samples = NULL) { ensemble.size = settings$ensemble$size %||% 1, ens.sample.method = settings$ensemble$samplingspace$parameters$method %||% "uniform", sa_quantiles = settings$sensitivity.analysis$quantiles, - do_ensemble = FALSE + do_ensemble = FALSE, + independent = loaded$independent ) } @@ -170,4 +171,4 @@ generate_OAT_SA_design <- function(settings, samples = NULL) { design_matrix$sa_quantile <- sa_quantile return(list(design_matrix = design_matrix, X = design_matrix, samples = samples)) -} +} \ No newline at end of file From 90bd23d40ea083cfab51a4d8f38c1714cbfa3f93 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:38 -0500 Subject: [PATCH 49/82] drop independent argument from run.write.configs --- base/workflow/R/runModule.run.write.configs.R | 23 ++++++------------- 1 file changed, 7 insertions(+), 16 deletions(-) diff --git a/base/workflow/R/runModule.run.write.configs.R b/base/workflow/R/runModule.run.write.configs.R index 962dd2ada9e..6a0ecc881d7 100644 --- a/base/workflow/R/runModule.run.write.configs.R +++ b/base/workflow/R/runModule.run.write.configs.R @@ -27,9 +27,6 @@ #' A bare design data.frame is not accepted: its \code{param} indices are only #' meaningful together with the samples they index into, so the design and its #' samples must travel together. -#' @param independent Logical scalar: \code{FALSE} preserves supplied MCMC -#' dependence; \code{TRUE} discards it and samples parameters separately. -#' Only applies to new ensemble samples; supplied bundles are reused unchanged. #' @return A modified settings object, invisibly #' #' @@ -40,9 +37,7 @@ runModule.run.write.configs <- function(settings, overwrite = TRUE, - input_design = NULL, - independent = FALSE) { - stopifnot(is.logical(independent), length(independent) == 1L, !is.na(independent)) + input_design = NULL) { if (PEcAn.settings::is.MultiSettings(settings)) { if (overwrite && file.exists(file.path(settings$rundir, "runs.txt"))) { @@ -55,13 +50,12 @@ runModule.run.write.configs <- function(settings, } # prepare designs once for all sites (consistent sampling) - designs <- .prepare_input_designs(settings[1], input_design, independent) + designs <- .prepare_input_designs(settings[1], input_design) return(PEcAn.settings::papply(settings, runModule.run.write.configs, overwrite = FALSE, - input_design = designs, - independent = independent)) + input_design = designs)) } else if (PEcAn.settings::is.Settings(settings)) { # only default the sampling method for a run that actually has an ensemble, @@ -73,7 +67,7 @@ runModule.run.write.configs <- function(settings, } # prepare designs (may already be normalized from MultiSettings) - designs <- .prepare_input_designs(settings, input_design, independent) + designs <- .prepare_input_designs(settings, input_design) # check to see if there are posterior.files tags under pft posterior.files <- settings$pfts %>% @@ -159,8 +153,6 @@ runModule.run.write.configs <- function(settings, #' #' @param settings A single PEcAn settings object #' @param input_design Input design specification (see \code{runModule.run.write.configs}) -#' @param independent Logical scalar passed to \code{get_parameter_samples} -#' when generating new samples. Supplied samples are reused unchanged. #' @return A list with \code{ensemble} and \code{sensitivity} entries (each a #' data.frame or NULL) and a \code{samples} entry holding the parameter bundle #' used for the run. When the run has an ensemble or sensitivity analysis the @@ -189,8 +181,7 @@ runModule.run.write.configs <- function(settings, #' #' @keywords internal -.prepare_input_designs <- function(settings, input_design, independent = FALSE) { - stopifnot(is.logical(independent), length(independent) == 1L, !is.na(independent)) +.prepare_input_designs <- function(settings, input_design) { # Already-normalized designs (e.g. threaded from a MultiSettings parent): # pass straight through. samples.Rdata was already written by the top-level @@ -265,7 +256,7 @@ runModule.run.write.configs <- function(settings, ens.sample.method = settings$ensemble$samplingspace$parameters$method %||% "uniform", sa_quantiles = settings$sensitivity.analysis$quantiles, do_ensemble = need_ensemble, - independent = independent + independent = loaded$independent ) } @@ -324,4 +315,4 @@ runModule.run.write.configs <- function(settings, } return(designs) -} +} \ No newline at end of file From 2f765091657d273b0ee80d204f2680a4bf239928 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:38 -0500 Subject: [PATCH 50/82] revert ed script sampling call --- models/ed/scripts/write.configs.rscript.R | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/models/ed/scripts/write.configs.rscript.R b/models/ed/scripts/write.configs.rscript.R index 1c5b551ecc8..c3ea5caff60 100644 --- a/models/ed/scripts/write.configs.rscript.R +++ b/models/ed/scripts/write.configs.rscript.R @@ -116,8 +116,7 @@ if('sensitivity.analysis' %in% names(settings)) { ## Write ENSEMBLE if('ensemble' %in% names(settings) && settings$ensemble$size > 0) { ## subset the trait.samples to ensemble size using Halton sequence - ensemble.samples <- get.ensemble.samples(settings$ensemble$size, trait.samples, env.samples, - independent = TRUE) + ensemble.samples <- get.ensemble.samples(settings$ensemble$size, trait.samples, env.samples) write.ensemble.configs(settings$pfts, ensemble.samples, host, outdir, settings) } From f50c28507e4753253e2db6d468408319d2852940 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:38 -0500 Subject: [PATCH 51/82] test joint lookup by name and unequal lengths --- .../tests/testthat/test_ensemble.R | 61 ++++--------------- 1 file changed, 11 insertions(+), 50 deletions(-) diff --git a/modules/uncertainty/tests/testthat/test_ensemble.R b/modules/uncertainty/tests/testthat/test_ensemble.R index 3ff5baee8cf..1f38e631b0c 100644 --- a/modules/uncertainty/tests/testthat/test_ensemble.R +++ b/modules/uncertainty/tests/testthat/test_ensemble.R @@ -161,57 +161,18 @@ test_that("get.ensemble.samples", { expect_true(all(sapply(res_idx, \(mat)all(mat %in% 1:5)))) }) -test_that("direct ensemble calls preserve supplied rows", { - withr::local_seed(2) - samples <- list(pft = list(a = 1:10, b = -(1:10))) - result <- get.ensemble.samples(30, samples, list()) - expect_equal(result$pft$b, -result$pft$a) - expect_true(all(result$pft$a %in% 1:10)) - expect_equal(nrow(result$pft), 30) +test_that("get.ensemble.samples draws joint traits by whole row", { + a <- stats::rnorm(50) + pft_samp <- list(p = list(a = a, b = 2 * a, c = stats::rnorm(80))) + 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)) }) -test_that("joint selectors match by PFT name rather than list position", { - withr::local_seed(2) - samples <- list(first = list(a = 1:20, b = -(1:20)), - second = list(a = 1:20, b = -(1:20))) - result <- get.ensemble.samples( - 30, samples, list(), - param.names = list(second = character(0), first = c("a", "b")) +test_that("get.ensemble.samples rejects joint traits of unequal 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" ) - expect_equal(result$first$b, -result$first$a) - expect_false(isTRUE(all.equal(result$second$b, -result$second$a))) - positional <- get.ensemble.samples( - 30, samples, list(), param.names = list(c("a", "b"), character(0)) - ) - expect_equal(positional$first$b, -positional$first$a) -}) - -test_that("malformed joint selectors and missing trait names fail", { - samples <- list(first = list(a = 1:20), second = list(b = 1:20)) - invalid <- list( - list(first = "a", wrong = "b"), - list(first = "a", first = "b"), - list(first = "a", "b"), - list(first = "unknown", second = "b"), - list("a") - ) - for (selector in invalid) { - expect_error(get.ensemble.samples(2, samples, list(), param.names = selector)) - } - expect_error(get.ensemble.samples(2, list(pft = list(1:20)), list())) - expect_error(get.ensemble.samples(2, samples, list(), independent = c(TRUE, FALSE))) - expect_error(get.ensemble.samples(2, list(pft = list(a = numeric(0))), list())) -}) - -test_that("different bank sizes and environment samples are sampled separately", { - withr::local_seed(4) - samples <- list(first = list(a = 1:7, b = -(1:7)), - second = list(a = 1:11, b = -(1:11))) - result <- get.ensemble.samples(30, samples, list(c = 1:17)) - expect_equal(result$first$b, -result$first$a) - expect_equal(result$second$b, -result$second$a) - indices <- attr(result, "sampled.indices") - expect_false(identical(indices$first[, 1], indices$second[, 1])) - expect_false(identical(indices$first[, 1], indices$env[, 1])) - expect_error(get.ensemble.samples(2, list(env = list(a = 1:7)), list())) }) From ce340a07a50f58a63ab1562e6ef2a381ff2c8c70 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:38 -0500 Subject: [PATCH 52/82] test joint default and pft with nothing to sample --- .../testthat/test-get_parameter_samples.R | 198 +++--------------- 1 file changed, 33 insertions(+), 165 deletions(-) diff --git a/modules/uncertainty/tests/testthat/test-get_parameter_samples.R b/modules/uncertainty/tests/testthat/test-get_parameter_samples.R index 39c930803a1..bc0c01b871c 100644 --- a/modules/uncertainty/tests/testthat/test-get_parameter_samples.R +++ b/modules/uncertainty/tests/testthat/test-get_parameter_samples.R @@ -1,7 +1,9 @@ +# ============================================================ # Tests for get_parameter_samples() # # These tests verify the extracted pure function works correctly # WITHOUT any database, file I/O, or PEcAn settings object. +# ============================================================ # Skip entire file if required PEcAn packages are not installed skip_if_not_installed("PEcAn.priors") @@ -33,7 +35,9 @@ make_mock_trait_mcmc <- function(traits = "SLA", n_samples = 100, seed = 42) { } +# ==================== # TEST 1: Returns actual data, not NULL +# ==================== test_that("get_parameter_samples returns a non-NULL list with correct names", { priors <- make_mock_priors(c("SLA")) @@ -57,7 +61,9 @@ test_that("get_parameter_samples returns a non-NULL list with correct names", { }) +# ==================== # TEST 2: No files written (pure function guarantee) +# ==================== test_that("get_parameter_samples writes no files to disk", { temp_dir <- tempfile("pure_test_") dir.create(temp_dir) @@ -82,7 +88,9 @@ test_that("get_parameter_samples writes no files to disk", { }) +# ==================== # TEST 3: Prior-only sampling (no MCMC) +# ==================== test_that("prior-only sampling produces correct structure", { priors <- make_mock_priors(c("SLA", "Vcmax")) @@ -108,7 +116,9 @@ test_that("prior-only sampling produces correct structure", { }) +# ==================== # TEST 4: MCMC sampling path +# ==================== test_that("MCMC samples are used when available", { priors <- make_mock_priors(c("SLA", "Vcmax")) mcmc <- make_mock_trait_mcmc("SLA", n_samples = 200) @@ -130,7 +140,9 @@ test_that("MCMC samples are used when available", { }) +# ==================== # TEST 5: Multiple PFTs +# ==================== test_that("multiple PFTs are handled correctly", { priors1 <- make_mock_priors("SLA") priors2 <- make_mock_priors("Vcmax") @@ -154,7 +166,9 @@ test_that("multiple PFTs are handled correctly", { }) +# ==================== # TEST 6: Sensitivity analysis samples +# ==================== test_that("SA samples are generated when quantiles are provided", { priors <- make_mock_priors("SLA") @@ -187,7 +201,9 @@ test_that("SA samples are NOT generated when quantiles is NULL", { }) +# ==================== # TEST 7: Ensemble size = 1 (median run) +# ==================== test_that("ensemble.size = 1 produces median samples", { priors <- make_mock_priors("SLA") @@ -204,7 +220,9 @@ test_that("ensemble.size = 1 produces median samples", { }) +# ==================== # TEST 8: Input validation +# ==================== test_that("pure function rejects mismatched inputs", { priors <- make_mock_priors("SLA") @@ -218,7 +236,9 @@ test_that("pure function rejects mismatched inputs", { }) +# ==================== # TEST 9: Sampling methods +# ==================== test_that("different sampling methods all produce valid output", { priors <- make_mock_priors("SLA") @@ -240,7 +260,9 @@ 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) @@ -267,174 +289,20 @@ test_that("independent = FALSE preserves param.names for correlated sampling", { expect_false(is.null(result_dep$ensemble.samples)) }) - -# mixing rows breaks b == -a -make_paired_mcmc <- function(n_samples = 200, shift = 0, seed = 1) { - set.seed(seed) - a <- rnorm(n_samples) - lapply(list(a = a + shift, b = -a - shift), function(x) { - coda::mcmc.list(coda::mcmc(matrix(x, ncol = 1, dimnames = list(NULL, "beta.o")))) - }) +# 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)) } -test_that("joint sampling is default and independence is an ensemble request", { - withr::local_seed(1) - mcmc <- list(make_paired_mcmc(), make_paired_mcmc(shift = 100)) - joint <- get_parameter_samples( - pft_names = c("pft1", "pft2"), - prior_distns_list = list(NULL, NULL), - trait_mcmc_list = mcmc, - ensemble.size = 50 - ) - independent <- get_parameter_samples( - pft_names = c("pft1", "pft2"), - prior_distns_list = list(NULL, NULL), - trait_mcmc_list = mcmc, - ensemble.size = 50, - independent = TRUE - ) - for (pft in c("pft1", "pft2")) { - expect_equal(joint$ensemble.samples[[pft]]$b, -joint$ensemble.samples[[pft]]$a) - expect_true(all(joint$ensemble.samples[[pft]]$a %in% joint$trait.samples[[pft]]$a)) - expect_false(isTRUE(all.equal( - independent$ensemble.samples[[pft]]$b, -independent$ensemble.samples[[pft]]$a - ))) - } - expect_error(get_parameter_samples( - pft_names = c("pft1", "pft2"), - prior_distns_list = list(NULL, NULL), - trait_mcmc_list = mcmc, - independent = c(FALSE, TRUE) - )) -}) - -test_that("joint PFTs with the same number of rows share a row index", { - for (method in c("uniform", "random", "halton")) { - result <- get_parameter_samples( - pft_names = c("pft1", "pft2"), - prior_distns_list = list(NULL, NULL), - trait_mcmc_list = list(make_paired_mcmc(), make_paired_mcmc(shift = 100)), - ensemble.size = 50, - ens.sample.method = method, - do_ensemble = TRUE, - independent = FALSE - ) - expect_equal( - result$ensemble.samples$pft2$a, - result$ensemble.samples$pft1$a + 100, - info = method - ) - } -}) - -test_that("a PFT with nothing to sample does not shift joint rows", { +test_that("by default MCMC rows stay together, even after an empty PFT", { result <- get_parameter_samples( - pft_names = c("empty_pft", "joint_pft"), + pft_names = c("empty", "joint"), prior_distns_list = list(NULL, NULL), - trait_mcmc_list = list(NULL, make_paired_mcmc()), - ensemble.size = 50, - do_ensemble = TRUE, - independent = FALSE + trait_mcmc_list = list(NULL, make_joint_mcmc()), + ensemble.size = 20 ) - joint <- result$ensemble.samples$joint_pft - expect_equal(joint$b, -joint$a) -}) - -test_that("joint traits with different numbers of rows fail", { - mcmc <- make_paired_mcmc() - mcmc$b <- coda::mcmc.list(coda::mcmc(mcmc$b[[1]][1:150, , drop = FALSE])) - expect_error( - get_parameter_samples( - pft_names = "joint_pft", - prior_distns_list = list(NULL), - trait_mcmc_list = list(mcmc), - ensemble.size = 50, - do_ensemble = TRUE, - independent = FALSE - ), - "same number of rows" - ) -}) - -test_that("joint singleton and oversized ensembles retain allocation draws", { - withr::local_seed(1) - allocation <- list( - leaf = c(0.45, 0.45, 0.05), - wood = c(0.45, 0.05, 0.45), - root = c(0.05, 0.45, 0.45) - ) - mcmc <- lapply(allocation, function(x) { - coda::mcmc.list(coda::mcmc(matrix(x, ncol = 1, dimnames = list(NULL, "beta.o")))) - }) - for (size in c(1, 50)) { - for (method in c("uniform", "halton")) { - result <- get_parameter_samples( - pft_names = "pft", - prior_distns_list = list(NULL), - trait_mcmc_list = list(mcmc), - ensemble.size = size, - ens.sample.method = method - )$ensemble.samples$pft - expect_equal(rowSums(result), rep(0.95, size), info = method) - expect_equal(nrow(result), size) - } - } -}) - -test_that("distribution-only traits remain marginal beside joint draws", { - withr::local_seed(1) - priors <- data.frame( - distn = "norm", parama = c(0, 0, 20), paramb = c(1, 1, 2), n = 50, - row.names = c("a", "b", "c") - ) - result <- get_parameter_samples( - pft_names = "pft", - prior_distns_list = list(priors), - trait_mcmc_list = list(make_paired_mcmc()), - ensemble.size = 50 - ) - sampled <- result$ensemble.samples$pft - indices <- attr(result$ensemble.samples, "sampled.indices")$pft - expect_equal(sampled$b, -sampled$a) - expect_true(stats::sd(sampled$c) > 0) - expect_false(identical(indices[, match("a", names(sampled))], - indices[, match("c", names(sampled))])) -}) - -test_that("a distribution-only PFT does not become a joint table", { - withr::local_seed(1) - result <- get_parameter_samples( - pft_names = "pft", prior_distns_list = list(make_mock_priors("SLA")), - ensemble.size = 20 - ) - expect_false(all(result$ensemble.samples$pft$SLA %in% result$trait.samples$pft$SLA)) -}) - -test_that("the joint selector respects the sampled parameter inventory", { - withr::local_seed(1) - mcmc <- make_paired_mcmc() - priors <- data.frame(distn = "norm", parama = 0, paramb = 1, n = 50, - row.names = "a") - result <- get_parameter_samples( - pft_names = "pft", prior_distns_list = list(priors), - trait_mcmc_list = list(mcmc), ensemble.size = 20 - ) - expect_named(result$ensemble.samples$pft, "a") - expect_true(all(result$ensemble.samples$pft$a %in% mcmc$a[[1]][, "beta.o"])) -}) - -test_that("joint draws do not consume dimensions of a marginal design", { - traits <- paste0("trait", seq_len(1112)) - chain <- coda::mcmc.list(coda::mcmc(matrix( - 1:3, ncol = 1, dimnames = list(NULL, "beta.o") - ))) - mcmc <- stats::setNames(rep(list(chain), length(traits)), traits) - result <- get_parameter_samples( - pft_names = "pft", prior_distns_list = list(NULL), - trait_mcmc_list = list(mcmc), ensemble.size = 5, - ens.sample.method = "sobol" - )$ensemble.samples$pft - expect_named(result, traits) - expect_true(all(vapply(result, identical, logical(1), result[[1]]))) - expect_true(all(result[[1]] %in% 1:3)) + x <- result$ensemble.samples$joint + expect_equal(x$b, 2 * x$a) }) From 5561187c9590260eeb28b319da376ca9992a3de3 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:39 -0500 Subject: [PATCH 53/82] sample ma output independently in modular chain test --- .../uncertainty/inst/integrationTests/test.modular.chain.R | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/modules/uncertainty/inst/integrationTests/test.modular.chain.R b/modules/uncertainty/inst/integrationTests/test.modular.chain.R index 6abf5567f46..dd1711a2aa1 100644 --- a/modules/uncertainty/inst/integrationTests/test.modular.chain.R +++ b/modules/uncertainty/inst/integrationTests/test.modular.chain.R @@ -77,7 +77,9 @@ test_modular_chain <- function(pft_name, modeltype, trait_names, trait_mcmc_list = list(ma$trait.mcmc), ensemble.size = ensemble.size, sa_quantiles = c(0.025, 0.25, 0.5, 0.75, 0.975), - do_ensemble = TRUE + do_ensemble = TRUE, + # meta-analysis fits each trait on its own, so its rows are not joint draws + independent = TRUE ) test_that("get_parameter_samples consumes MA output and returns the samples list", { From 8140ce82bbc4d50461f0c379c68bc646b81ea81e Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:39 -0500 Subject: [PATCH 54/82] restore load.posteriors tests --- .../tests/testthat/test.load_posteriors.R | 66 ++++--------------- 1 file changed, 12 insertions(+), 54 deletions(-) diff --git a/modules/uncertainty/tests/testthat/test.load_posteriors.R b/modules/uncertainty/tests/testthat/test.load_posteriors.R index 4fffe668323..46005e5b15a 100644 --- a/modules/uncertainty/tests/testthat/test.load_posteriors.R +++ b/modules/uncertainty/tests/testthat/test.load_posteriors.R @@ -32,7 +32,7 @@ test_that("load from single distns file works", { ) expect_null(result$trait.mcmc) - expect_named(result, c("prior.distns", "trait.mcmc")) + expect_false(result$is.joint) expect_is(result$prior.distns, "data.frame") expect_equal(rownames(result$prior.distns), c("trait_a", "trait_b")) }) @@ -52,7 +52,7 @@ test_that("load from single mcmc file works", { expect_is(result$trait.mcmc, "list") expect_equal(names(result$trait.mcmc), c("trait_a", "trait_b")) expect_null(result$prior.distns) - expect_named(result, c("prior.distns", "trait.mcmc")) + expect_false(result$is.joint) }) @@ -79,7 +79,7 @@ test_that("load from directory with both mcmc and distns prefers mcmc", { expect_is(result$trait.mcmc, "list") expect_equal(names(result$trait.mcmc), c("trait_a")) expect_is(result$prior.distns, "data.frame") - expect_named(result, c("prior.distns", "trait.mcmc")) + expect_false(result$is.joint) }) @@ -232,7 +232,7 @@ test_that("nonexistent path returns empty result with error", { expect_null(result$prior.distns) expect_null(result$trait.mcmc) - expect_named(result, c("prior.distns", "trait.mcmc")) + expect_false(result$is.joint) }) @@ -251,7 +251,7 @@ test_that("empty directory returns empty result", { }) -test_that("PDA samples load alongside their companion file", { +test_that("joint detection works via companion file in from.path", { tmpdir <- withr::local_tempdir() # Create PDA-style MCMC file @@ -264,53 +264,29 @@ test_that("PDA samples load alongside their companion file", { result <- load.posteriors(posterior.file = tmpdir) - expect_equal(result$trait.mcmc, trait.mcmc) + expect_true(result$is.joint) expect_is(result$trait.mcmc, "list") }) -test_that("MCMC samples load from trait.mcmc.Rdata", { +test_that("non-PDA mcmc is not detected as joint", { tmpdir <- withr::local_tempdir() + # Create MA-style MCMC file (no companion mcmc.pda.* file) trait.mcmc <- make_trait_mcmc(trait_a = rnorm(100)) save(trait.mcmc, file = file.path(tmpdir, "trait.mcmc.Rdata")) result <- load.posteriors(posterior.file = tmpdir) - expect_equal(result$trait.mcmc, trait.mcmc) + expect_false(result$is.joint) expect_is(result$trait.mcmc, "list") }) -test_that("both posterior loading paths preserve joint draws", { - tmpdir <- withr::local_tempdir() - - withr::local_seed(1) - a <- rnorm(100) - trait.mcmc <- make_trait_mcmc(trait_a = a, trait_b = -a) - save(trait.mcmc, file = file.path(tmpdir, "trait.mcmc.Rdata")) - - result <- load.posteriors(posterior.file = tmpdir) - - invisible(capture.output( - legacy <- load.posteriors(posterior.file = NA, outdir = tmpdir) - )) - for (posterior in list(result, legacy)) { - samples <- get_parameter_samples( - pft_names = "pft", - prior_distns_list = list(NULL), - trait_mcmc_list = list(posterior$trait.mcmc), - ensemble.size = 20 - )$ensemble.samples$pft - expect_equal(samples$trait_b, -samples$trait_a) - expect_true(all(samples$trait_a %in% a)) - } -}) - - -test_that("legacy loading accepts PDA filenames", { +test_that("joint detection works via filename heuristic in legacy path", { tmpdir <- withr::local_tempdir() + # Create mcmc file with pda in name (legacy path uses filename heuristic) trait.mcmc <- make_trait_mcmc(trait_a = rnorm(100)) save(trait.mcmc, file = file.path(tmpdir, "mcmc.pda.Rdata")) @@ -321,7 +297,7 @@ test_that("legacy loading accepts PDA filenames", { ) )) - expect_equal(result$trait.mcmc, trait.mcmc) + expect_true(result$is.joint) expect_is(result$trait.mcmc, "list") }) @@ -339,21 +315,3 @@ test_that("MCMC detected by coda class, not variable name", { expect_is(result$trait.mcmc, "list") expect_equal(names(result$trait.mcmc), "SLA") }) - - -test_that("load_pft_posteriors returns posterior samples for each PFT", { - first_dir <- withr::local_tempdir() - second_dir <- withr::local_tempdir() - - trait.mcmc <- make_trait_mcmc(trait_a = rnorm(100)) - save(trait.mcmc, file = file.path(second_dir, "trait.mcmc.Rdata")) - save(trait.mcmc, file = file.path(first_dir, "trait.mcmc.Rdata")) - - settings <- list(pfts = list(list(name = "pft1"), list(name = "pft2"))) - invisible(capture.output( - loaded <- load_pft_posteriors(settings, c(first_dir, second_dir)) - )) - - expect_named(loaded, c("pft_names", "prior_distns_list", "trait_mcmc_list")) - expect_equal(loaded$trait_mcmc_list, list(trait.mcmc, trait.mcmc)) -}) From 794b7c21b6ce09ac1f02c3362d3775056d37f7d8 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:39 -0500 Subject: [PATCH 55/82] restore get.parameter.samples tests --- .../testthat/test-get.parameter.samples.R | 41 ++++++++----------- 1 file changed, 17 insertions(+), 24 deletions(-) diff --git a/modules/uncertainty/tests/testthat/test-get.parameter.samples.R b/modules/uncertainty/tests/testthat/test-get.parameter.samples.R index 889e5c04ee9..d2160254c75 100644 --- a/modules/uncertainty/tests/testthat/test-get.parameter.samples.R +++ b/modules/uncertainty/tests/testthat/test-get.parameter.samples.R @@ -1,3 +1,4 @@ +# ============================================================ # Tests for the get.parameter.samples() wrapper (Layer 2) # # These exercise the WRAPPER's behaviour, not the pure @@ -14,6 +15,7 @@ # # load.posteriors() and get_parameter_samples() are stubbed with # mockery so these run with no database and no real MCMC objects. +# ============================================================ skip_if_not_installed("mockery") skip_if_not_installed("PEcAn.logger") @@ -34,7 +36,8 @@ fake_posterior <- function() { distn = "norm", parama = 20, paramb = 5, n = 50, row.names = "SLA", stringsAsFactors = FALSE ), - trait.mcmc = NULL + trait.mcmc = NULL, + is.joint = FALSE ) } @@ -62,7 +65,8 @@ test_that("samples.Rdata is written to settings$outdir by default", { list( pft_names = list("temperate.deciduous"), prior_distns_list = list(fake_posterior()$prior.distns), - trait_mcmc_list = list(fake_posterior()$trait.mcmc) + trait_mcmc_list = list(fake_posterior()$trait.mcmc), + independent = TRUE ) ) mockery::stub(get.parameter.samples, "get_parameter_samples", fake_samples_result()) @@ -84,7 +88,8 @@ test_that("explicit outdir overrides settings$outdir for the save", { list( pft_names = list("temperate.deciduous"), prior_distns_list = list(fake_posterior()$prior.distns), - trait_mcmc_list = list(fake_posterior()$trait.mcmc) + trait_mcmc_list = list(fake_posterior()$trait.mcmc), + independent = TRUE ) ) mockery::stub(get.parameter.samples, "get_parameter_samples", fake_samples_result()) @@ -106,7 +111,8 @@ test_that("outdir = NULL skips the save entirely", { list( pft_names = list("temperate.deciduous"), prior_distns_list = list(fake_posterior()$prior.distns), - trait_mcmc_list = list(fake_posterior()$trait.mcmc) + trait_mcmc_list = list(fake_posterior()$trait.mcmc), + independent = TRUE ) ) mockery::stub(get.parameter.samples, "get_parameter_samples", fake_samples_result()) @@ -132,7 +138,8 @@ test_that("samples.Rdata bundles the 5 expected objects", { list( pft_names = list("temperate.deciduous"), prior_distns_list = list(fake_posterior()$prior.distns), - trait_mcmc_list = list(fake_posterior()$trait.mcmc) + trait_mcmc_list = list(fake_posterior()$trait.mcmc), + independent = TRUE ) ) mockery::stub(get.parameter.samples, "get_parameter_samples", fake_samples_result()) @@ -161,7 +168,8 @@ test_that("returns the get_parameter_samples result invisibly", { list( pft_names = list("temperate.deciduous"), prior_distns_list = list(fake_posterior()$prior.distns), - trait_mcmc_list = list(fake_posterior()$trait.mcmc) + trait_mcmc_list = list(fake_posterior()$trait.mcmc), + independent = TRUE ) ) mockery::stub(get.parameter.samples, "get_parameter_samples", fake) @@ -185,7 +193,8 @@ test_that("loaded posteriors are delegated to get_parameter_samples", { loaded <- list( pft_names = list("temperate.deciduous"), prior_distns_list = list(post$prior.distns), - trait_mcmc_list = list(post$trait.mcmc) + trait_mcmc_list = list(post$trait.mcmc), + independent = TRUE ) mockery::stub(get.parameter.samples, "load_pft_posteriors", loaded) mock_gps <- mockery::mock(fake_samples_result()) @@ -196,21 +205,5 @@ test_that("loaded posteriors are delegated to get_parameter_samples", { mockery::expect_called(mock_gps, 1) args <- mockery::mock_args(mock_gps)[[1]] expect_identical(args$prior_distns_list[[1]], post$prior.distns) - expect_false(args$independent) -}) - -test_that("the wrapper forwards an explicit independent request", { - settings <- make_test_settings(NULL) - loaded <- list( - pft_names = list("temperate.deciduous"), - prior_distns_list = list(NULL), - trait_mcmc_list = list(NULL) - ) - sampler <- mockery::mock(fake_samples_result()) - mockery::stub(get.parameter.samples, "load_pft_posteriors", loaded) - mockery::stub(get.parameter.samples, "get_parameter_samples", sampler) - - suppressWarnings(get.parameter.samples(settings, outdir = NULL, independent = TRUE)) - - expect_true(mockery::mock_args(sampler)[[1]]$independent) + expect_true(args$independent) }) From 1519f544bd3cc77100d4b94b52a66499a38a5fd7 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:39 -0500 Subject: [PATCH 56/82] restore joint ensemble design tests --- .../test-generate_joint_ensemble_design.R | 25 +++---------------- 1 file changed, 4 insertions(+), 21 deletions(-) diff --git a/modules/uncertainty/tests/testthat/test-generate_joint_ensemble_design.R b/modules/uncertainty/tests/testthat/test-generate_joint_ensemble_design.R index 3e398e350e5..f7ab988ce4e 100644 --- a/modules/uncertainty/tests/testthat/test-generate_joint_ensemble_design.R +++ b/modules/uncertainty/tests/testthat/test-generate_joint_ensemble_design.R @@ -7,7 +7,8 @@ fake_loaded_posteriors <- function() { list( pft_names = list("pft1"), prior_distns_list = list(NULL), - trait_mcmc_list = list(NULL) + trait_mcmc_list = list(NULL), + independent = TRUE ) } @@ -58,24 +59,6 @@ test_that("generated samples are returned alongside the design", { expect_identical(result$samples, fake_parameter_samples()) }) -test_that("ensemble sampling follows the caller's scalar request", { - settings <- make_test_settings() - mockery::stub(generate_joint_ensemble_design, "PEcAn.uncertainty::input.ens.gen", - function(...) list(ids = rep(1L, 5))) - mockery::stub(generate_joint_ensemble_design, "load_pft_posteriors", - function(...) fake_loaded_posteriors()) - sampler <- mockery::mock(fake_parameter_samples(), cycle = TRUE) - mockery::stub(generate_joint_ensemble_design, "get_parameter_samples", sampler) - - generate_joint_ensemble_design(settings, ensemble_size = 5) - generate_joint_ensemble_design(settings, ensemble_size = 5, independent = TRUE) - - mockery::expect_called(sampler, 2) - calls <- mockery::mock_args(sampler) - expect_false(calls[[1]]$independent) - expect_true(calls[[2]]$independent) -}) - test_that("passed-in samples skip the loader and sampler", { settings <- make_test_settings() @@ -90,7 +73,7 @@ test_that("passed-in samples skip the loader and sampler", { established <- fake_parameter_samples() result <- generate_joint_ensemble_design( - settings, ensemble_size = 5, samples = established, independent = TRUE + settings, ensemble_size = 5, samples = established ) mockery::expect_called(loader, 0) @@ -286,4 +269,4 @@ test_that("the bundle carries SA samples when the settings ask for a sensitivity # way .prepare_input_designs would sample it args <- mockery::mock_args(sampler)[[1]] expect_identical(args$sa_quantiles, c(0.025, 0.5, 0.975)) -}) +}) \ No newline at end of file From 8243f43ed28ee178046dec0bbf5a91bc5b048a9e Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:39 -0500 Subject: [PATCH 57/82] restore oat design tests --- .../tests/testthat/test-generate_OAT_SA_design.R | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/uncertainty/tests/testthat/test-generate_OAT_SA_design.R b/modules/uncertainty/tests/testthat/test-generate_OAT_SA_design.R index d6c3c4dd68a..e52e782ffa7 100644 --- a/modules/uncertainty/tests/testthat/test-generate_OAT_SA_design.R +++ b/modules/uncertainty/tests/testthat/test-generate_OAT_SA_design.R @@ -8,7 +8,8 @@ oat_loaded_posteriors <- function() { list( pft_names = list("pft1"), prior_distns_list = list(NULL), - trait_mcmc_list = list(NULL) + trait_mcmc_list = list(NULL), + independent = TRUE ) } @@ -79,7 +80,6 @@ test_that("parameters are sampled in memory when no samples are supplied", { # SA sampling draws quantiles, not an ensemble args <- mockery::mock_args(sampler)[[1]] expect_false(args$do_ensemble) - expect_false("independent" %in% names(args)) expect_identical(args$sa_quantiles, c(0.25, 0.5, 0.75)) # design is built from the freshly sampled sa.samples, and returned with them @@ -175,4 +175,4 @@ test_that("adding labels leaves the rest of the design alone", { expect_equal(nrow(design), 7) expect_equal(design$param, seq_len(7)) expect_true(all(design$met == 1)) -}) +}) \ No newline at end of file From 72c3cae017e1c5e08ad6e2490db8c63d149cfe0e Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:39 -0500 Subject: [PATCH 58/82] restore run.write.configs tests --- .../test-runModule.run.write.configs.R | 57 ++----------------- 1 file changed, 4 insertions(+), 53 deletions(-) diff --git a/base/workflow/tests/testthat/test-runModule.run.write.configs.R b/base/workflow/tests/testthat/test-runModule.run.write.configs.R index 5252abaae7d..b3d1ff50f8c 100644 --- a/base/workflow/tests/testthat/test-runModule.run.write.configs.R +++ b/base/workflow/tests/testthat/test-runModule.run.write.configs.R @@ -22,7 +22,8 @@ fake_loaded <- function() { list( pft_names = list("temperate.deciduous"), prior_distns_list = list(NULL), - trait_mcmc_list = list(NULL) + trait_mcmc_list = list(NULL), + independent = TRUE ) } @@ -91,56 +92,6 @@ test_that(".prepare_input_designs hands the sampled bundle to the generator", { expect_identical(designs$samples, bundle) }) -test_that("workflow sampling follows the caller's scalar request", { - tmp <- withr::local_tempdir() - settings <- make_prep_settings(tmp) - sampler <- mockery::mock(fake_bundle(), cycle = TRUE) - mockery::stub(.prepare_input_designs, - "PEcAn.uncertainty::load_pft_posteriors", function(...) fake_loaded()) - mockery::stub(.prepare_input_designs, - "PEcAn.uncertainty::get_parameter_samples", sampler) - mockery::stub(.prepare_input_designs, - "PEcAn.uncertainty::generate_joint_ensemble_design", - function(...) list(design_matrix = data.frame(param = 1:3))) - - suppressWarnings(.prepare_input_designs(settings, NULL)) - suppressWarnings(.prepare_input_designs(settings, NULL, independent = TRUE)) - - mockery::expect_called(sampler, 2) - calls <- mockery::mock_args(sampler) - expect_false(calls[[1]]$independent) - expect_true(calls[[2]]$independent) -}) - -test_that("multisite preparation passes one shared bundle and sampling request", { - tmp <- withr::local_tempdir() - first <- PEcAn.settings::as.Settings(make_prep_settings(tmp)) - first$rundir <- tmp - second <- first - second$run <- list(site = list(id = "second")) - settings <- PEcAn.settings::MultiSettings(first, second) - shared <- list( - ensemble = data.frame(param = 1:3), - sensitivity = NULL, - samples = fake_bundle() - ) - prepare <- mockery::mock(shared) - apply_sites <- mockery::mock(settings) - mockery::stub(runModule.run.write.configs, ".prepare_input_designs", prepare) - mockery::stub(runModule.run.write.configs, "PEcAn.settings::papply", apply_sites) - - runModule.run.write.configs(settings, overwrite = FALSE, independent = TRUE) - - mockery::expect_called(prepare, 1) - prepared <- mockery::mock_args(prepare)[[1]] - expect_identical(prepared[[1]], settings[1]) - expect_true(prepared[[3]]) - passed <- mockery::mock_args(apply_sites)[[1]] - expect_identical(passed$input_design, shared) - expect_true(passed$independent) - expect_false(passed$overwrite) -}) - test_that(".prepare_input_designs returns an input_design list unchanged", { gen <- mockery::mock() @@ -187,7 +138,7 @@ test_that(".prepare_input_designs reuses a supplied list(X, samples) and does no mockery::stub(.prepare_input_designs, "PEcAn.uncertainty::generate_joint_ensemble_design", gen) - designs <- .prepare_input_designs(settings, input_design = supplied, independent = TRUE) + designs <- .prepare_input_designs(settings, input_design = supplied) mockery::expect_called(loader, 0) mockery::expect_called(gps, 0) @@ -431,4 +382,4 @@ test_that("a partly labelled design is not mistaken for a sensitivity design", { expect_identical(designs$ensemble, supplied$design_matrix) expect_null(designs$sensitivity) -}) +}) \ No newline at end of file From 64c6aa42eada09fc929890a522a7f8b47ad44da8 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:40 -0500 Subject: [PATCH 59/82] regenerate get.ensemble.samples docs --- .../uncertainty/man/get.ensemble.samples.Rd | 32 ++++++------------- 1 file changed, 9 insertions(+), 23 deletions(-) diff --git a/modules/uncertainty/man/get.ensemble.samples.Rd b/modules/uncertainty/man/get.ensemble.samples.Rd index bfd7f1336b0..3bafd2b6b97 100644 --- a/modules/uncertainty/man/get.ensemble.samples.Rd +++ b/modules/uncertainty/man/get.ensemble.samples.Rd @@ -10,45 +10,31 @@ 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}{named list of PFTs, each containing named parameter -samples, e.g. from MCMC chains. The name "env" is reserved.} +\item{pft.samples}{random samples from parameter distribution, e.g. from a MCMC chain} \item{env.samples}{env samples} -\item{method}{sampling method for marginal traits: "random", "uniform", -"halton", "sobol", or "lhc". Joint draws are sampled randomly by row.} +\item{method}{the method used to generate the ensemble samples for traits sampled independently. 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. +When \code{ensemble.size > 1}, traits listed in \code{param.names} ignore \code{method}: each member takes one complete MCMC row, drawn at random with replacement.} -\item{param.names}{named list of joint trait names per PFT. NULL selects all -supplied traits; an empty entry selects none. Unnamed lists match PFT order.} +\item{param.names}{list named by PFT, each element the traits whose MCMC samples are drawn together by row. Joint traits of a PFT must have equal length. NULL samples every trait independently.} \item{...}{Other arguments passed on to the sampling method} - -\item{independent}{logical. Sample each parameter separately, discarding -supplied dependence, instead of preserving parameter correlations.} } \value{ named list of data.frames with sampled indices as an attribute } \description{ -Returns sampled parameter values for model runs, preserving supplied joint -draws unless independent sampling is requested. -} -\details{ -Joint draws preserve parameter correlations (by keeping complete - MCMC rows together). Rows are sampled with replacement. PFTs with equal - numbers of joint draws share row indices, so paired input tables must have - matching row order. Equal row counts do not establish common provenance; - unrelated tables must contain genuinely independent draws. Environment - samples and traits outside \code{param.names} are sampled marginally. - A one-member joint ensemble selects a complete draw; marginal traits use - their medians. Independent sampling can violate joint parameter constraints. +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 } \author{ David LeBauer, Istem Fer From 5d60a2057f0db9c4c516b44b92ebf6c57d08caf1 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:40 -0500 Subject: [PATCH 60/82] regenerate get_parameter_samples docs --- .../uncertainty/man/get_parameter_samples.Rd | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/modules/uncertainty/man/get_parameter_samples.Rd b/modules/uncertainty/man/get_parameter_samples.Rd index f0d9209d415..2b9166d181e 100644 --- a/modules/uncertainty/man/get_parameter_samples.Rd +++ b/modules/uncertainty/man/get_parameter_samples.Rd @@ -27,16 +27,17 @@ 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. Marginal sampling method: "halton", -"sobol", "lhc", "random", or "uniform".} +\item{ens.sample.method}{character. One of "halton", "sobol", "torus", +"lhc", "uniform".} \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. Sample each parameter separately, discarding -supplied dependence, instead of preserving parameter correlations.} +\item{independent}{logical. FALSE (default) keeps complete MCMC draws +together, so correlations between parameters are kept. TRUE samples each +parameter independently, ignoring any joint structure.} } \value{ named list with five elements: @@ -59,12 +60,6 @@ directly, with no file I/O and no database calls. } \details{ For the original disk-based wrapper, see \code{\link{get.parameter.samples}}. - -MCMC samples are sampled jointly by default (by keeping complete - draws together). Traits available only as distributions remain marginal. - Equal-sized MCMC tables share row indices and must preserve any paired row - order. Independent sampling may violate joint constraints such as allocation - sums. See \code{\link{get.ensemble.samples}} for the sampling contract. } \examples{ \dontrun{ @@ -90,7 +85,7 @@ str(result$ensemble.samples) } \seealso{ -\code{\link{get.parameter.samples}} for the disk-based +\code{\link{get.parameter.samples}} for the backward-compatible wrapper that handles file I/O and database lookups. } \author{ From 61635933a5a32aa73e622444e7ea805c6e2eb62d Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:40 -0500 Subject: [PATCH 61/82] regenerate get.parameter.samples docs --- .../uncertainty/man/get.parameter.samples.Rd | 34 +++++++++---------- 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/modules/uncertainty/man/get.parameter.samples.Rd b/modules/uncertainty/man/get.parameter.samples.Rd index f03d6f48dbe..2b7de125eeb 100644 --- a/modules/uncertainty/man/get.parameter.samples.Rd +++ b/modules/uncertainty/man/get.parameter.samples.Rd @@ -9,8 +9,7 @@ get.parameter.samples( ensemble.size = 1, posterior.files = rep(NA, length(settings$pfts)), ens.sample.method = "uniform", - outdir = settings$outdir, - independent = FALSE + outdir = settings$outdir ) } \arguments{ @@ -20,15 +19,14 @@ get.parameter.samples( \item{posterior.files}{list of filenames to read from} -\item{ens.sample.method}{marginal sampling method: \code{"halton"}, \code{"sobol"}, -\code{"lhc"}, \code{"random"}, or \code{"uniform"}.} +\item{ens.sample.method}{one of \code{"halton"}, \code{"sobol"}, \code{"torus"}, \code{"lhc"}, +\code{"uniform"}} -\item{outdir}{directory for \code{samples.Rdata}, defaulting to \code{settings$outdir}. -Use \code{NULL} to return samples without saving a file.} - -\item{independent}{Logical scalar. If \code{FALSE} (default), preserve -dependence among supplied MCMC parameters. If \code{TRUE}, sample each -parameter separately, ignoring supplied dependence.} +\item{outdir}{character path; directory to write \code{samples.Rdata} to for +provenance. Defaults to \code{settings$outdir}, preserving the legacy +always-save behaviour for existing callers (none of which pass it). +Pass \code{outdir = NULL} to skip the save entirely; the pure +\code{get_parameter_samples()} never writes to disk regardless.} } \value{ Named list with 5 elements: \code{trait.samples}, \code{sa.samples}, @@ -37,7 +35,7 @@ Named list with 5 elements: \code{trait.samples}, \code{sa.samples}, \description{ Loads posterior distributions and MCMC chain results from disk, generates parameter samples for ensemble and sensitivity analysis runs, and optionally -saves results to \code{samples.Rdata}. This is the deprecated wrapper +saves results to \code{samples.Rdata}. This is the backward-compatible wrapper that delegates computation to \code{\link[PEcAn.uncertainty]{get_parameter_samples}}. } \details{ @@ -46,8 +44,8 @@ that delegates computation to \code{\link[PEcAn.uncertainty]{get_parameter_sampl \item{\code{post.distns.Rdata} or \code{prior.distns.Rdata}}{Posterior (or prior) distribution summaries produced by \code{run.meta.analysis.pft}. A data frame with columns \code{distn}, \code{parama}, \code{paramb}, \code{n}.} -\item{\code{trait.mcmc.Rdata}}{(Optional) posterior MCMC samples. -Named list of \code{mcmc.list} objects, one per trait. +\item{\code{trait.mcmc.Rdata}}{(Optional) MCMC chain samples from the +meta-analysis. Named list of \code{mcmc.list} objects, one per trait. If present, samples are drawn from the chains directly; otherwise, independent samples are drawn from \code{post.distns}.} } @@ -69,11 +67,11 @@ metadata). }} } -\strong{Downstream contract:} The workflow passes the parameter bundle directly to -\code{run.write.configs} in memory. That writer can also load \code{samples.Rdata} -when no bundle is supplied. \code{\link[PEcAn.uncertainty]{get.results}} can -read the saved file when ensemble-specific samples are unavailable, and -\code{\link[PEcAn.uncertainty]{run.sensitivity.analysis}} reads it for traits. +\strong{Downstream contract:} \code{samples.Rdata} is loaded by \code{run.write.configs} +(in \code{PEcAn.workflow}) to generate model configuration files. It is also +loaded by \code{\link[PEcAn.uncertainty]{get.results}} and \code{\link[PEcAn.uncertainty]{run.sensitivity.analysis}} to retrieve +sample metadata for post-processing. This implicit file-based coupling is +a refactoring target. } \author{ David LeBauer, Shawn Serbin, Istem Fer, Om Kapale From 5a1f3c54794e077f689769cca2c6f06e558fabb8 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:40 -0500 Subject: [PATCH 62/82] regenerate generate_joint_ensemble_design docs --- modules/uncertainty/man/generate_joint_ensemble_design.Rd | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/modules/uncertainty/man/generate_joint_ensemble_design.Rd b/modules/uncertainty/man/generate_joint_ensemble_design.Rd index 3bf3d409f5b..4e2d6c01fa7 100644 --- a/modules/uncertainty/man/generate_joint_ensemble_design.Rd +++ b/modules/uncertainty/man/generate_joint_ensemble_design.Rd @@ -8,8 +8,7 @@ generate_joint_ensemble_design( settings, ensemble_size, samples = NULL, - sobol = FALSE, - independent = FALSE + sobol = FALSE ) } \arguments{ @@ -35,10 +34,6 @@ are used directly instead of loading posteriors and sampling. When \item{sobol}{Logical. If TRUE, returns a \code{sensitivity::soboljansen} object for Sobol sensitivity analysis.} - -\item{independent}{Logical scalar: \code{FALSE} preserves supplied MCMC -dependence; \code{TRUE} discards it and samples parameters separately. -Used only when \code{samples = NULL}; supplied samples are reused unchanged.} } \value{ If \code{sobol = FALSE}, a list with \code{design_matrix} (the design, From f53dc00403dc379e217ee0add7d921e9dca4c5d2 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:40 -0500 Subject: [PATCH 63/82] regenerate load.posteriors docs --- modules/uncertainty/man/load.posteriors.Rd | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/modules/uncertainty/man/load.posteriors.Rd b/modules/uncertainty/man/load.posteriors.Rd index 8717890f07a..13a295765eb 100644 --- a/modules/uncertainty/man/load.posteriors.Rd +++ b/modules/uncertainty/man/load.posteriors.Rd @@ -29,7 +29,9 @@ legacy fallback path.} only in the legacy fallback path.} } \value{ -list with \code{prior.distns} and \code{trait.mcmc}. +list with \code{prior.distns}, \code{trait.mcmc}, \code{is.joint}. + \code{is.joint} is \code{TRUE} when MCMC samples represent a joint + posterior (e.g. from PDA) and parameter correlations should be preserved. } \description{ Detects posterior type by file contents, not filenames. From aad6cfd2381d6f518964719f91bf6cac114451be Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:40 -0500 Subject: [PATCH 64/82] regenerate load.posteriors.from.path docs --- modules/uncertainty/man/load.posteriors.from.path.Rd | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/uncertainty/man/load.posteriors.from.path.Rd b/modules/uncertainty/man/load.posteriors.from.path.Rd index 98a9c155b40..da97351be04 100644 --- a/modules/uncertainty/man/load.posteriors.from.path.Rd +++ b/modules/uncertainty/man/load.posteriors.from.path.Rd @@ -10,7 +10,7 @@ load.posteriors.from.path(path) \item{path}{file path or directory path} } \value{ -List with \code{prior.distns} and \code{trait.mcmc} +List with \code{prior.distns}, \code{trait.mcmc}, \code{is.joint} } \description{ Scans \code{.Rdata} files at \code{path} and detects MCMC samples From 3688ecd497814cd8db9ce60247b814a8db4c710c Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:40 -0500 Subject: [PATCH 65/82] regenerate load.posteriors.legacy docs --- modules/uncertainty/man/load.posteriors.legacy.Rd | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/uncertainty/man/load.posteriors.legacy.Rd b/modules/uncertainty/man/load.posteriors.legacy.Rd index 658a0ee520b..8bb9b074725 100644 --- a/modules/uncertainty/man/load.posteriors.legacy.Rd +++ b/modules/uncertainty/man/load.posteriors.legacy.Rd @@ -21,7 +21,7 @@ load.posteriors.legacy( \item{hostname}{host name for dbfile lookup} } \value{ -List with \code{prior.distns} and \code{trait.mcmc} +List with \code{prior.distns}, \code{trait.mcmc}, \code{is.joint} } \description{ \strong{Deprecated.} This path is used only when From 58c0cae6181f494f9ff5c98f2b56017c24f0cc3c Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:40 -0500 Subject: [PATCH 66/82] regenerate load_pft_posteriors docs --- modules/uncertainty/man/load_pft_posteriors.Rd | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/modules/uncertainty/man/load_pft_posteriors.Rd b/modules/uncertainty/man/load_pft_posteriors.Rd index 59677879d1d..a1d82ed60b4 100644 --- a/modules/uncertainty/man/load_pft_posteriors.Rd +++ b/modules/uncertainty/man/load_pft_posteriors.Rd @@ -15,13 +15,15 @@ optional BETY lookup, and \code{settings$host$name}.} \code{NA} where none is specified. Length must match \code{settings$pfts}.} } \value{ -A list with three elements: +A list with four elements: \describe{ \item{pft_names}{character vector of PFT names ("NULL" where unnamed).} \item{prior_distns_list}{list of prior distribution data frames, one per PFT (\code{NULL} entry where none was found).} \item{trait_mcmc_list}{list of trait MCMC results, one per PFT (\code{NULL} entry where the PFT has no MCMC chains).} + \item{independent}{logical, \code{FALSE} if any PFT carries a joint + posterior, \code{TRUE} otherwise.} } } \description{ @@ -35,8 +37,9 @@ their own copy. \details{ Posterior type is detected by content, not filename, via \code{\link{load.posteriors}}: MCMC chains take precedence over distribution -summaries. Downstream joint sampling preserves parameter correlations -(for MCMC samples, by keeping complete draws together). +summaries. When a PFT's posterior is a joint fit (e.g. from PDA), the +returned \code{independent} flag is set to \code{FALSE} so downstream +sampling preserves the parameter correlations. } \seealso{ \code{\link{get_parameter_samples}} for the sampling step that From 60c2ec6e04b60160c32bfa14df9498b2672cabe8 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:40 -0500 Subject: [PATCH 67/82] regenerate run.write.configs docs --- base/workflow/man/runModule.run.write.configs.Rd | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/base/workflow/man/runModule.run.write.configs.Rd b/base/workflow/man/runModule.run.write.configs.Rd index 3b9b524e25b..b0691af80ba 100644 --- a/base/workflow/man/runModule.run.write.configs.Rd +++ b/base/workflow/man/runModule.run.write.configs.Rd @@ -4,12 +4,7 @@ \alias{runModule.run.write.configs} \title{Generate model-specific run configuration files for one or more PEcAn runs} \usage{ -runModule.run.write.configs( - settings, - overwrite = TRUE, - input_design = NULL, - independent = FALSE -) +runModule.run.write.configs(settings, overwrite = TRUE, input_design = NULL) } \arguments{ \item{settings}{a PEcAn Settings or MultiSettings object} @@ -31,10 +26,6 @@ for \code{settings$run$inputs} tags such as \code{met} or \code{soil}) and A bare design data.frame is not accepted: its \code{param} indices are only meaningful together with the samples they index into, so the design and its samples must travel together.} - -\item{independent}{Logical scalar: \code{FALSE} preserves supplied MCMC -dependence; \code{TRUE} discards it and samples parameters separately. -Only applies to new ensemble samples; supplied bundles are reused unchanged.} } \value{ A modified settings object, invisibly From c0022d00e9ce89e08d191a1228c1cfd37fcde8f0 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:41 -0500 Subject: [PATCH 68/82] regenerate prepare_input_designs docs --- base/workflow/man/dot-prepare_input_designs.Rd | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/base/workflow/man/dot-prepare_input_designs.Rd b/base/workflow/man/dot-prepare_input_designs.Rd index 2d37c58b918..f77994b1dc9 100644 --- a/base/workflow/man/dot-prepare_input_designs.Rd +++ b/base/workflow/man/dot-prepare_input_designs.Rd @@ -4,15 +4,12 @@ \alias{.prepare_input_designs} \title{Prepare input designs for ensemble and sensitivity analysis} \usage{ -.prepare_input_designs(settings, input_design, independent = FALSE) +.prepare_input_designs(settings, input_design) } \arguments{ \item{settings}{A single PEcAn settings object} \item{input_design}{Input design specification (see \code{runModule.run.write.configs})} - -\item{independent}{Logical scalar passed to \code{get_parameter_samples} -when generating new samples. Supplied samples are reused unchanged.} } \value{ A list with \code{ensemble} and \code{sensitivity} entries (each a From 055c0fcad2935c65aef6658d6c0dd61234b9cf88 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:41 -0500 Subject: [PATCH 69/82] describe joint sampling changes in uncertainty news --- modules/uncertainty/NEWS.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/modules/uncertainty/NEWS.md b/modules/uncertainty/NEWS.md index 9a26e486ead..cb053d79dcf 100644 --- a/modules/uncertainty/NEWS.md +++ b/modules/uncertainty/NEWS.md @@ -1,8 +1,9 @@ # PEcAn.uncertainty 1.9.0.9000 -* Breaking: ensemble sampling preserves correlations between supplied MCMC parameters by default. Parameters available only as distributions are sampled independently. `independent = TRUE` requests separate sampling of all parameters and can violate joint constraints. -* Joint draws are sampled by whole rows with replacement, including for a one-member ensemble. Equal-length PFT tables share row indices; corresponding rows must be aligned. Joint traits with unequal sample counts are rejected. `method` controls marginal sampling only. -* `get.ensemble.samples()` matches named `param.names` entries by PFT name. `param.names = NULL` selects all supplied PFT parameters for joint sampling; an empty entry selects none. +* Breaking: `get_parameter_samples()` now defaults to `independent = FALSE`, drawing MCMC parameters by whole row so their correlations are kept. `independent = TRUE` samples each parameter on its own. The workflow still sets the flag from `load_pft_posteriors()`. +* Breaking: `get.ensemble.samples()` stops with an error when the joint traits of a PFT differ in length, instead of indexing all of them by the first trait's length, which silently cut longer chains short or gave `NA`. +* `get.ensemble.samples()` draws joint traits by whole MCMC row at random with replacement, whatever `method` is. +* `get.ensemble.samples()` looks up `param.names` by PFT name instead of position, so a PFT with nothing to sample no longer shifts joint traits onto the next PFT. An unnamed `param.names` list now selects no joint traits. * In `run.sensitivity.analysis()`, load `samples` once before the variables loop, avoiding repeated disk reads (#3859). * `get.ensemble.samples()` now again returns a list of dataframes as it did before v1.9.0. The returned list also now has attribute `sampled.indices`, From 07d29e081f6c64ccbea58b66c8ca2b2540d9b080 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:41 -0500 Subject: [PATCH 70/82] drop workflow sampling option from news --- base/workflow/NEWS.md | 1 - 1 file changed, 1 deletion(-) diff --git a/base/workflow/NEWS.md b/base/workflow/NEWS.md index ceb45896d57..59add5bdc7e 100644 --- a/base/workflow/NEWS.md +++ b/base/workflow/NEWS.md @@ -1,7 +1,6 @@ # PEcAn.workflow 1.10.0.9000 ## Changed -* `runModule.run.write.configs()` preserves MCMC parameter correlations by default. Set `independent = TRUE` to sample all parameters separately. * `run.write.configs()` now requires `samples` to contain an `ensemble.samples` (as was already required for `sa.samples`) and no longer re-draws it from `trait.samples`. (#4185) From 4829d2a5dc5dc12059a07039418e61ca36ad56f8 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 17 Nov 2026 18:27:41 -0500 Subject: [PATCH 71/82] update changelog for joint sampling --- CHANGELOG.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 22e0c2ea6b7..1ff1c2a620c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,8 +48,8 @@ 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`: joint ensembles retain complete supplied draws for one or many members, including ensembles larger than the draw bank. Named trait selectors are matched by PFT name, and an empty PFT no longer shifts subsequent selectors. +- `PEcAn.uncertainty::get.ensemble.samples()` looks up `param.names` by PFT name, so a PFT with nothing to sample no longer shifts joint traits onto the next PFT (#4238). +- `PEcAn.uncertainty::get.ensemble.samples()` stops with an error when the joint traits of a PFT differ in length, instead of indexing all of them by the first trait's length, which silently cut longer chains or gave `NA` (#4238). - `PEcAn.utils::match_file()` anchors file prefixes to the beginning of the filename, so a request for `foo/site1` no longer matches `foo/old-site1` (but still finds `foo/site1-old` as previously) (#4196, @Shubham-Padkonde). - PEcAnAssimSequential: `simple.local()` and `piecew.poly.local()` now scale distances by their `scalef` argument instead of the undefined `rloc`; `GEF()`, `GEF.MultiSite()` and `EnKF.MultiSite()` read their extra arguments from `...` explicitly instead of assigning them into the global environment; `SDA_remote_launcher()` no longer references an undefined `stop.on.error`. Together these clear most of the package's "no visible binding for global variable" check notes (#2758). - `PEcAn.SIPNET::write.config.SIPNET()` wrote `stem_respiration_rate` and `root_respiration_rate` as per day rates into SIPNET's per year `baseVegResp` and `baseFineRootResp`, 365x too low. @@ -76,7 +76,8 @@ For more information about this file see also [Keep a Changelog](http://keepacha ### Changed -- `PEcAn.uncertainty`: breaking change: MCMC parameters are sampled jointly by default; distribution-only parameters remain independent. Set `independent = TRUE` to sample all parameters separately. Joint rows are selected randomly with replacement, with shared row indices for equal-length PFT tables; corresponding source rows must be aligned. The sampling method controls marginal sampling only. +- `PEcAn.uncertainty::get_parameter_samples()` now defaults to `independent = FALSE`, drawing MCMC parameters by whole row; the workflow still takes the flag from `load_pft_posteriors()` (#4238). +- `PEcAn.uncertainty::get.ensemble.samples()` draws joint rows at random with replacement for every `method` (#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) From 274828e393a71bd03a87644e064eb637010b436b Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 24 Nov 2026 12:23:35 -0500 Subject: [PATCH 72/82] revert modular chain test to develop --- .../uncertainty/inst/integrationTests/test.modular.chain.R | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/modules/uncertainty/inst/integrationTests/test.modular.chain.R b/modules/uncertainty/inst/integrationTests/test.modular.chain.R index dd1711a2aa1..6abf5567f46 100644 --- a/modules/uncertainty/inst/integrationTests/test.modular.chain.R +++ b/modules/uncertainty/inst/integrationTests/test.modular.chain.R @@ -77,9 +77,7 @@ test_modular_chain <- function(pft_name, modeltype, trait_names, trait_mcmc_list = list(ma$trait.mcmc), ensemble.size = ensemble.size, sa_quantiles = c(0.025, 0.25, 0.5, 0.75, 0.975), - do_ensemble = TRUE, - # meta-analysis fits each trait on its own, so its rows are not joint draws - independent = TRUE + do_ensemble = TRUE ) test_that("get_parameter_samples consumes MA output and returns the samples list", { From c02bbc26c9104109fab2992f52dfc2446e4646b1 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 24 Nov 2026 12:23:35 -0500 Subject: [PATCH 73/82] trim joint sampling news --- modules/uncertainty/NEWS.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/modules/uncertainty/NEWS.md b/modules/uncertainty/NEWS.md index c14019ae212..68f0d309c84 100644 --- a/modules/uncertainty/NEWS.md +++ b/modules/uncertainty/NEWS.md @@ -1,9 +1,7 @@ # PEcAn.uncertainty 1.9.0.9000 -* Breaking: `get_parameter_samples()` now defaults to `independent = FALSE`, drawing MCMC parameters by whole row so their correlations are kept. `independent = TRUE` samples each parameter on its own. The workflow still sets the flag from `load_pft_posteriors()`. -* Breaking: `get.ensemble.samples()` stops with an error when the joint traits of a PFT differ in length, instead of indexing all of them by the first trait's length, which silently cut longer chains short or gave `NA`. -* `get.ensemble.samples()` draws joint traits by whole MCMC row at random with replacement, whatever `method` is. -* `get.ensemble.samples()` looks up `param.names` by PFT name instead of position, so a PFT with nothing to sample no longer shifts joint traits onto the next PFT. An unnamed `param.names` list now selects no joint traits. +* `get.ensemble.samples()` matches `param.names` to PFTs by name instead of position, and errors when a PFT's joint traits differ in length instead of returning truncated or `NA` draws. +* `get.ensemble.samples()` draws joint MCMC rows at random with replacement, whatever `method` is. * `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). * `get.ensemble.samples()` now again returns a list of dataframes as it did From 6a8eee2e5c8a7de7f34e3c926a4953c14e177445 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Tue, 24 Nov 2026 12:23:35 -0500 Subject: [PATCH 74/82] trim joint sampling changelog --- CHANGELOG.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fbb203a25db..3f8dffc2f62 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,8 +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()` looks up `param.names` by PFT name, so a PFT with nothing to sample no longer shifts joint traits onto the next PFT (#4238). -- `PEcAn.uncertainty::get.ensemble.samples()` stops with an error when the joint traits of a PFT differ in length, instead of indexing all of them by the first trait's length, which silently cut longer chains or gave `NA` (#4238). +- `PEcAn.uncertainty::get.ensemble.samples()` matches `param.names` to PFTs by name instead of position, and errors when a PFT's joint traits differ in length instead of returning truncated or `NA` draws (#4238). - 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). - `PEcAn.DB::query.format.vars()` with an invalid format or input id now stops with "No format found" instead of with a PostgreSQL syntax error (#2078). @@ -82,8 +81,7 @@ For more information about this file see also [Keep a Changelog](http://keepacha ### Changed -- `PEcAn.uncertainty::get_parameter_samples()` now defaults to `independent = FALSE`, drawing MCMC parameters by whole row; the workflow still takes the flag from `load_pft_posteriors()` (#4238). -- `PEcAn.uncertainty::get.ensemble.samples()` draws joint rows at random with replacement for every `method` (#4238). +- `PEcAn.uncertainty::get.ensemble.samples()` draws joint MCMC rows at random with replacement, whatever `method` is (#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) From e31da101a633b7163a3ffeaf26c0a508dc677a7c Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 26 Nov 2026 02:17:01 -0500 Subject: [PATCH 75/82] add independent argument to get.ensemble.samples --- modules/uncertainty/R/ensemble.R | 55 +++++++++++++++++--------------- 1 file changed, 30 insertions(+), 25 deletions(-) diff --git a/modules/uncertainty/R/ensemble.R b/modules/uncertainty/R/ensemble.R index 441ddcc01de..691f2234fd2 100644 --- a/modules/uncertainty/R/ensemble.R +++ b/modules/uncertainty/R/ensemble.R @@ -77,24 +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 for traits sampled independently. 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. -#' When \code{ensemble.size > 1}, traits listed in \code{param.names} ignore \code{method}: each member takes one complete MCMC row, drawn at random with replacement. -#' @param param.names list named by PFT, each element the traits whose MCMC samples are drawn together by row. Joint traits of a PFT must have equal length. NULL samples every trait 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") @@ -109,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 @@ -161,31 +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 - joint <- names(pft.samples[[pft.i]]) %in% param.names[[names(pft.samples)[pft.i]]] - if (any(joint)) { - n.rows <- unique(lengths(pft.samples[[pft.i]][joint])) + # 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("PFT", names(pft.samples)[pft.i], "joint traits differ in length:", paste(n.rows, collapse = ", ")) + PEcAn.logger::logger.severe( + "Parameters to sample jointly for PFT", names(pft.samples)[pft.i], + "differ in length:", toString(n.rows) + ) } - # draws whole MCMC rows, so a space-filling design over [0, 1] does not apply + # 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 (joint[trait.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]]) From d18055ed8189722d713f84640b2e65aa4953b71c Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 26 Nov 2026 02:17:02 -0500 Subject: [PATCH 76/82] pass independent through get_parameter_samples, rename trait.mcmc local --- modules/uncertainty/R/get_parameter_samples.R | 51 +++++++++---------- 1 file changed, 23 insertions(+), 28 deletions(-) diff --git a/modules/uncertainty/R/get_parameter_samples.R b/modules/uncertainty/R/get_parameter_samples.R index 6a9c29f0ce2..9ac6441f664 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. FALSE (default) keeps complete MCMC draws -#' together, so correlations between parameters are kept. TRUE samples each -#' parameter independently, ignoring any joint structure. +#' @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.} @@ -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 ---- - # independent = TRUE asks for each parameter to be sampled on its own, so drop param.names. - # 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 From eb5a30d26a34ed62728403caa894af88be4c7b18 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 26 Nov 2026 02:17:02 -0500 Subject: [PATCH 77/82] test joint default, param.names subset and length check --- .../tests/testthat/test_ensemble.R | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/modules/uncertainty/tests/testthat/test_ensemble.R b/modules/uncertainty/tests/testthat/test_ensemble.R index 1f38e631b0c..aab49d7a565 100644 --- a/modules/uncertainty/tests/testthat/test_ensemble.R +++ b/modules/uncertainty/tests/testthat/test_ensemble.R @@ -161,15 +161,29 @@ test_that("get.ensemble.samples", { expect_true(all(sapply(res_idx, \(mat)all(mat %in% 1:5)))) }) -test_that("get.ensemble.samples draws joint traits by whole row", { +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 = stats::rnorm(80))) + 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 joint traits of unequal length", { +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"))), From 3e20a45dbfdbf8e92ad6e512d886271f22a680b2 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 26 Nov 2026 02:17:02 -0500 Subject: [PATCH 78/82] test that independent does not keep mcmc rows, rename test helpers --- .../testthat/test-get_parameter_samples.R | 58 +++++++------------ 1 file changed, 22 insertions(+), 36 deletions(-) diff --git a/modules/uncertainty/tests/testthat/test-get_parameter_samples.R b/modules/uncertainty/tests/testthat/test-get_parameter_samples.R index bc0c01b871c..5dec6e24a10 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,32 +263,6 @@ 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) - - 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 - ) - - 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 - ) - - expect_false(is.null(result_ind$ensemble.samples)) - expect_false(is.null(result_dep$ensemble.samples)) -}) - # 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) @@ -306,3 +280,15 @@ test_that("by default MCMC rows stay together, even after an empty PFT", { x <- result$ensemble.samples$joint expect_equal(x$b, 2 * x$a) }) + +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 + ) + apart <- result$ensemble.samples$joint + expect_false(isTRUE(all.equal(apart$b, 2 * apart$a))) +}) From ee4031deaf122d372130676fa9d5d2db7b0a0d5f Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 26 Nov 2026 02:17:02 -0500 Subject: [PATCH 79/82] regenerate get.ensemble.samples docs --- .../uncertainty/man/get.ensemble.samples.Rd | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/modules/uncertainty/man/get.ensemble.samples.Rd b/modules/uncertainty/man/get.ensemble.samples.Rd index 3bafd2b6b97..655be33db21 100644 --- a/modules/uncertainty/man/get.ensemble.samples.Rd +++ b/modules/uncertainty/man/get.ensemble.samples.Rd @@ -10,20 +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 for traits sampled independently. 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. -When \code{ensemble.size > 1}, traits listed in \code{param.names} ignore \code{method}: each member takes one complete MCMC row, drawn at random with replacement.} +\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}{list named by PFT, each element the traits whose MCMC samples are drawn together by row. Joint traits of a PFT must have equal length. NULL samples every trait 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} } @@ -31,10 +33,10 @@ When \code{ensemble.size > 1}, traits listed in \code{param.names} ignore \code{ 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 From fec00ebab55a58ddaead0fdd22a001f4c22be76d Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 26 Nov 2026 02:17:02 -0500 Subject: [PATCH 80/82] regenerate get_parameter_samples docs --- .../uncertainty/man/get_parameter_samples.Rd | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/modules/uncertainty/man/get_parameter_samples.Rd b/modules/uncertainty/man/get_parameter_samples.Rd index 2b9166d181e..cacc7233a4e 100644 --- a/modules/uncertainty/man/get_parameter_samples.Rd +++ b/modules/uncertainty/man/get_parameter_samples.Rd @@ -19,30 +19,32 @@ get_parameter_samples( \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. FALSE (default) keeps complete MCMC draws -together, so correlations between parameters are kept. TRUE samples each -parameter independently, ignoring any joint structure.} +\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.} From 611986a974d5e7e496a105a711bccfcb435457db Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 26 Nov 2026 02:17:02 -0500 Subject: [PATCH 81/82] news for independent argument --- modules/uncertainty/NEWS.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/uncertainty/NEWS.md b/modules/uncertainty/NEWS.md index 449280e21c5..7b36a9c19a2 100644 --- a/modules/uncertainty/NEWS.md +++ b/modules/uncertainty/NEWS.md @@ -1,7 +1,7 @@ # PEcAn.uncertainty 1.9.0.9000 -* `get.ensemble.samples()` matches `param.names` to PFTs by name instead of position, and errors when a PFT's joint traits differ in length instead of returning truncated or `NA` draws. -* `get.ensemble.samples()` draws joint MCMC rows at random with replacement, whatever `method` is. +* `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). From 1690dbba9f1b889f828e6015a55f38bb85b95103 Mon Sep 17 00:00:00 2001 From: divne7022 Date: Thu, 26 Nov 2026 02:17:02 -0500 Subject: [PATCH 82/82] changelog for independent argument --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f5d3244d47..24f41820a27 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,7 +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 instead of position, and errors when a PFT's joint traits differ in length instead of returning truncated or `NA` draws (#4238). +- `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). @@ -82,7 +82,7 @@ For more information about this file see also [Keep a Changelog](http://keepacha ### Changed -- `PEcAn.uncertainty::get.ensemble.samples()` draws joint MCMC rows at random with replacement, whatever `method` is (#4238). +- `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)