Skip to content

Keep rows of joint MCMC samples together - #4238

Open
divine7022 wants to merge 84 commits into
PecanProject:developfrom
divine7022:joint-mcmc-samples
Open

divine7022 wants to merge 84 commits into
PecanProject:developfrom
divine7022:joint-mcmc-samples

Conversation

@divine7022

@divine7022 divine7022 commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

Description

load.posteriors() only treats PDA output as joint, so any other set of joint MCMC draws gets resampled one trait at a time and ensemble members end up with trait combinations that never occurred together. This PR lets a trait.mcmc object say it's joint, attr(trait.mcmc, "joint") <- TRUE, and keeps those rows together.

  • load.posteriors() reads the joint attribute (PDA detection is unchanged)
  • joint vs independent is decided per PFT, not one flag for all PFTs
  • joint PFTs with the same number of rows share one row index, so draws that are paired across PFTs stay paired
  • error if a joint PFT's traits have different row counts (before, the shorter ones got NA)
  • two small fixes along the way: param.names shifted by one PFT when an earlier PFT had nothing to sample, and method = "random" crashed on joint rows (nrow() on a vector)

Meta-analysis output stays independent on purpose. Separate single.MA() fits start from the same JAGS seed, so pairing their rows would add correlation that isn't real.

The halton, sobol and lhc options for joint rows are left as they were. They spread the row index, not the trait values, so with unordered draws they act like uniform on a fixed set of rows.

These methods help distribute ensemble samples across the available draws, but they don't preserve correlations between traits if each trait is sampled independently. Keeping complete rows together is what preserves the joint relationships in posterior.

Motivation and Context

Review Time Estimate

  • Immediately
  • Within one week
  • When possible

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)

Checklist:

  • My change requires a change to the documentation.
  • My name is in the list of CITATION.cff
  • I agree that PEcAn Project may distribute my contribution under any or all of
    • the same license as the existing code,
    • and/or the BSD 3-clause license.
  • I have updated the CHANGELOG.md.
  • I have updated the documentation accordingly.
  • I have read the CONTRIBUTING document.
  • I have added tests to cover my changes.
  • All new and existing tests passed.

Comment thread modules/uncertainty/R/ensemble.R Outdated
#' @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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

at least as described, this structure seems burdensome -- having to list all the parameters for all the different PFTs -- especially if setting NULL causes traits to ne resampled independently instead of causing all traits to be sampled. Also, having to pair param.names with pft.samples seems error prone, why not name the list by PFT?

not for now, but be aware that work in progress will produce spatial parameter maps rather than PFTs, so we should start thinking soon about how to future proof ongoing design choices.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NULL now means keep all supplied traits together, and named entries are matched by pft name. The normal workflow builds that list for you. Noted on the spatial maps point too 👍

Comment thread modules/uncertainty/R/ensemble.R Outdated
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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know this is just preserving existing functionality, but if you are sampling row indices then none of these "method" choices make any sense.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ryt, those methods were only choosing row numbers. Joint draws now use random rows with replacement. other methods only apply to marginal sampling

# 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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the new description is more confusing than the original one. Also the tone is discouraging, when joint sampling should be default

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've simplified this. Joint sampling is the default now, and function docs say that directly

Comment thread modules/uncertainty/R/load_posteriors.R Resolved
Comment thread modules/uncertainty/R/load_posteriors.R Resolved
Comment thread modules/uncertainty/R/load_posteriors.R Resolved
@infotroph

Copy link
Copy Markdown
Member

Can you explain the use case for a per-PFT joint-vs-independent decision? Especially given Mike's point that it isn't dangerous to treat an independent distribution as joint, I think I myself would only ever want to set this at the whole ensemble level.

I also second the point that we shouldn't rely on attributes for... really anything important: There are enough common operations that drop attributes that my working model is "attributes are not a safe place to store information". I agree with Mike that we can presume MCMC chains have joint structure and should be sampled by row unless the user tells get_ensemble_samples otherwise.

I think it might also help to recast the description of the independent parameter in terms of the function behavior it produces rather than as a declaration of data provenance: get_ensemble_samples(..., independent = TRUE) doesn't mean "parameters were fitted independently, please behave accordingly", it means "take independent draws from each parameter, ignoring any joint structure that might be present"

@dlebauer

Copy link
Copy Markdown
Member

ignoring any joint structure that might be present

Is this a good idea? In the case of allocation parameters forcing independent draws would produce invalid results.

More generally, it looses information. What is the use case?

@infotroph

infotroph commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

ignoring any joint structure that might be present

Is this a good idea?

No, it's not a good idea to ignore joint structure. I wasn't trying to say it was desirable, but that setting independent = TRUE has that effect and we should describe it clearly to help people realize the implications.

In fact if y'all stats experts were to suggest removing the independent = TRUE option entirely and making the behavior be "marginal distributions are sampled independently, MCMC jointly by row, full stop", I think you'd convince me but I don't think I'm qualified to be the one proposing it.

@mdietze

mdietze commented Nov 11, 2026

Copy link
Copy Markdown
Member

I think the primary place "independent" sampling comes up meaningfully is if you're doing a OAT sensitivity, but that's an entirely different function. The other place it comes up is when you're generating a space-filling initial designs (e.g. LHC) for things like emulator-based calibration. I'd argue that in that case the ideal thing to do is to generate a design that is over-dispersed relative to the multivariate manifold the posterior falls along, but no one has implemented that yet -- right now if you set independent = FALSE and select one of these non-random designs you don't actually get that design you just get a nonsensical row index resampling that, in the end, is probably just as random and anything else. All together, I think it's probably worth retaining "independent" as a flag, but I like Chris's suggestion that we shift to think of this as a user request not an attribute of the data itself.

@divine7022

Copy link
Copy Markdown
Member Author

@mdietze one thing before the workflow goes joint by default. get_parameter_samples defaults to joint now, but run.write.configs still takes independent from load_pft_posteriors(), which only marks run joint when the posterior file name has mcmc.pda.* in it. e8febf1 made the workflow joint and a plain MA run broke on it, when a trait doesn’t converge, single.MA() reruns it with 10x the iterations and a different thin (

PEcAn.logger::logger.warn("model did not converge; re-running with j.iter * 10")
jags.out <- rjags::coda.samples(
model = j.model,
variable.names = vars,
n.iter = j.iter * 10,
thin = max(c(2, j.iter / (500 * 2)))
), and pecan.ma() burns in with window(start = j.iter / 2), which only trims the first run. with the default iter = 3000 and 4 chains that’s 3004 draws for a trait that converged and 40000 for one that was rerun, so the traits can’t be drawn by row.

my take is a separate PR so pecan.ma() returns the same number of draws for every trait, then switch the workflow to presume MCMC is joint like you and Chris suggested. ok with that order ?

@mdietze

mdietze commented Nov 19, 2026

Copy link
Copy Markdown
Member

run.write.configs still takes independent from load_pft_posteriors()

I thought we were / had shifted the design so that run.write.configs isn't generating the draws? If you provide a design, which is what you should do, then there should not be any draws occurring downstream. If we want backwards compatibility, which I think we should be deprecating, then we should call the design generation within run.write.configs rather than having a different duplicate solution (which is what I thought Om had already implemented). Again, there shouldn't be any randomization/draws downstream from the design generation.

that’s 3004 draws for a trait that converged and 40000 for one that was rerun, so the traits can’t be drawn by row.

Well, there's a difference between can't and shouldn't. I you have 40k draws you shouldn't sample from the first 3004, but you definitely can. But I get the larger point that if you trigger the rerun the 40k should have burnin removed and then be thinned down to match the shorter run. Agree that should be a separate PR.

Also, 3000 iter * 4 chains should return 12k rows not 3004.

@divine7022

Copy link
Copy Markdown
Member Author

I thought we were / had shifted the design so that run.write.configs isn't generating the draws?

yes, generating design inside runModule is already deprecated and warns. that path does call generate_joint_ensemble_design(), but it draws the samples itself first, a copy of generator's own draw, so the ensemble design, SA design and samples.Rdata share one draw. agree that copy should go. that's outside this PR.

Also, 3000 iter * 4 chains should return 12k rows not 3004.

single.MA() thins by 2 at iter = 3000 and pecan.ma() keeps the second half, so 4 chains x 751 = 3004. when JAGS adapts, window start counts the 1000 adaptation iterations, so less gets trimmed and it keeps 5004.
filed #4276 to burn in with update() and thin the rerun down to the same draws per trait.

Comment thread modules/uncertainty/R/ensemble.R Outdated
#' @param env.samples env samples
#' @param method the method used to generate the ensemble samples. Random generators: uniform, uniform with latin hypercube permutation. Quasi-random generators: halton, sobol, torus. Random generation draws random variates whereas quasi-random generation is deterministic but well equidistributed. Default is uniform. For small ensemble size with relatively large parameter number (e.g ensemble size < 5 and # of traits > 5) use methods other than halton.
#' @param param.names a list of parameter names that were fitted either by MA or PDA, important argument, if NULL parameters will be resampled independently
#' @param method the method used to generate the ensemble samples for 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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't a new problem, but the description doesn't actually clarify what the acceptable arguments for "method" are.

Suggested change
#' @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.
#' @param method the method used to generate the ensemble samples for traits sampled independently. Random generators: uniform, lhc (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.

@divine7022 divine7022 Nov 26, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call. Digging in, old doc was also wrong in two places, torus isn't accepted (supported_methods rejects it before that branch), and the default has been random, not uniform. So I took your suggestion minus torus, plus random, with the default fixed in e31da10. Same list is on ens.sample.method in get_parameter_samples() now too (d18055e)

Comment thread modules/uncertainty/R/ensemble.R Outdated
#' @param method the method used to generate the ensemble samples. Random generators: uniform, uniform with latin hypercube permutation. Quasi-random generators: halton, sobol, torus. Random generation draws random variates whereas quasi-random generation is deterministic but well equidistributed. Default is uniform. For small ensemble size with relatively large parameter number (e.g ensemble size < 5 and # of traits > 5) use methods other than halton.
#' @param param.names a list of parameter names that were fitted either by MA or PDA, important argument, if NULL parameters will be resampled independently
#' @param method the method used to generate the ensemble samples for 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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This bit is confusing, both in how it's written and what it implies about the design. As written, the only way for "method" to have any effect is to set ensemble.size = 1, in which case setting "method" is also pretty pointless.

Per larger discussion, it seems like the best way to control whether sampling is independent vs. joint is by having "independent" be a function argument, not by trying to infer that decision from other attributes

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, that read badly. I made independent an argument again and dropped that sentence. With TRUE every parameter goes through method; with FALSE (default) method still handles anything not drawn by row, which in practice is env and the prior only parameters

Comment thread modules/uncertainty/R/ensemble.R Outdated
#' @param param.names a list of parameter names that were fitted either by MA or PDA, important argument, if NULL parameters will be resampled independently
#' @param method the method used to generate the ensemble samples for 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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. same point about not inferring independence from other arguments
  2. Per earlier discussion, NULL should just mean that we sample every parameter and shouldn't be tied to joint vs independent
  3. when we're talking about model parameters, can we just call them parameters (or param[s]) as a variable name) not traits? I'd recommend a find-replace on all the files in this PR

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 and 2: independent is the switch now. TRUE samples every parameter independently no matter what param.names says. With FALSE, param.names is list drawn together by row, and NULL means all of them. I kept the list so get_parameter_samples() can sample prior-only parameters marginally instead of forcing them onto MCMC rows. Or would you rather it go entirely ?
3: done in both functions and the test helpers. I stopped short of trait_mcmc_list and trait.samples since they're exported argument and saved output; #4241 seems like the place for those

Comment thread modules/uncertainty/R/ensemble.R Outdated
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 <- names(pft.samples[[pft.i]]) %in% param.names[[names(pft.samples)[pft.i]]]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not clear why this variable name is joint

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeh, joint didn't say much. I renamed it to by.row, since what it actually marks is which parameters a member takes from one row, and added comment saying so


# ---- Handle independence flag ----
# When samples are independent (fitted individually), set param.names to NULL.
# independent = TRUE asks for each parameter to be sampled on its own, so drop param.names.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

per earlier comment, recommend not relying on param.names to indicated independent vs joint

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that block is gone in d18055e and independent goes straight through now. param.names only says which parameters have MCMC samples to draw by row, and is ignored when independent = TRUE. Why I kept it is in my reply on your NULL/param.names comment in ensemble.R

Comment thread modules/uncertainty/NEWS.md Outdated
# 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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

confusing

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fair, it was. I rewrote it to just say what changed
611986a

Comment thread CHANGELOG.md Outdated

### Changed

- `PEcAn.uncertainty::get.ensemble.samples()` draws joint MCMC rows at random with replacement, whatever `method` is (#4238).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same as earlier, comment is unclear as it doesn't actually represent what the change is, as this statement implies all sampling is joint and method is never used, but reality is that independent sampling is still supported, and when sampling is independent method is still used

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yep, same problem as NEWS. I rewrote it to match

Comment on lines +112 to +113
# 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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't follow the comment here, but env.samples is about to be removed in #4229 -- will it still apply after that?

#' 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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
#' The model run is indexed first by model run, then by parameter.
#' The model run is indexed first by model run, then by parameter.
#'
#" @section Joint vs Independent Sampling:
#' By default, all parameters are sampled jointly by taking uniform random draws
#' from the row indices of the parameter matrix and using all the parameter
#' values from each selected row. This is probably what you want: It preserves
#' any existing correlations between parameters (e.g. in matrices built by MCMC
#' sampling), and still produces correctly uniform samples when the parameters
#' are uncorrelated.
#' Two arguments can change this behavior:
#' * To sample _some_ parameters of each PFT jointly but others independently,
#' list the parameters to be sampled jointly in `param.names`.
#' * To completely ignore existing correlations and sample _every_ parameter
#' independently in each PFT, set `independent = TRUE`. Only recommended if you
#' need a non-uniform sample and are confident the columns of the parameter
#' matrix were generated independently too (e.g. halton design when all params
#' were drawn from marginal distributions).
#'
#' @section Sampling Methods:
#' The `method` argument is used only for parameters sampled independently.
#' Joint sampling always uses "uniform".
#' Accepted fully random methods are "uniform" (or identically "random") and
#' "lhc" (latin hypercube permutation). Accepted quasi-random methods are
#' "halton" and "sobol"; both give deviates that are deterministic but well
#' equidistributed.
#' 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 a list of parameter names that were fitted either by MA or PDA, important argument, if NULL parameters will be resampled independently
#' @param method the method used to generate the ensemble samples for parameters sampled independently. Random generators: random and uniform (the same uniform random draw), lhc (latin hypercube permutation). Quasi-random generators: halton, sobol. Random generation draws random variates whereas quasi-random generation is deterministic but well equidistributed. Default is random. For small ensemble size with relatively large parameter number (e.g ensemble size < 5 and # of parameters > 5) use methods other than halton.
#' @param param.names list named by PFT of the parameters that have joint samples, e.g. MCMC draws. If NULL (default), every parameter of each PFT. Used only when \code{independent = FALSE}, where these are drawn by row together and any others with \code{method}.
#' @param independent logical. If FALSE (default), parameters are sampled jointly within each PFT, preserving their correlations: each ensemble member takes all of them (or only those in \code{param.names}) from one row, drawn at random with replacement. If TRUE, every parameter is sampled independently using \code{method}, ignoring any joint structure.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This behavior is much better than before! But I was still confused how these three args interact, especially because I kept scanning "...when independent = FALSE ... with method..." as in conflict with "...method used ... for parameters sampled independently." Is the following accurate and clear to other folks?

Suggested change
#' @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 method the method used to generate the ensemble samples for any
#' parameters that are sampled independently. See details.
#' @param param.names list named by PFT of the parameters to sample jointly.
#' If NULL (default), treated as listing every parameter of each PFT.
#' Ignored when \code{independent} is TRUE.
#' @param independent logical: Ignore correlations between parameters and sample
#' independently from each parameter in each PFT? See details.

If we're iterating even more I'd consider renaming param.names to something like joint_params, but I recognize that's a long-preexisting argument and renaming it gracefully would be a can of worms.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants