Repository navigation
Keep rows of joint MCMC samples together - #4238
divine7022 wants to merge 84 commits into
Conversation
| #' @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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 👍
| 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 |
There was a problem hiding this comment.
I know this is just preserving existing functionality, but if you are sampling row indices then none of these "method" choices make any sense.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
I think the new description is more confusing than the original one. Also the tone is discouraging, when joint sampling should be default
There was a problem hiding this comment.
I've simplified this. Joint sampling is the default now, and function docs say that directly
|
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 |
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? |
No, it's not a good idea to ignore joint structure. I wasn't trying to say it was desirable, but that setting In fact if y'all stats experts were to suggest removing the |
|
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. |
|
@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 pecan/modules/meta.analysis/R/single.MA.R Lines 119 to 124 in 368c3b7 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 ? |
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.
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. |
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.
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. |
| #' @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. |
There was a problem hiding this comment.
This isn't a new problem, but the description doesn't actually clarify what the acceptable arguments for "method" are.
| #' @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. |
There was a problem hiding this comment.
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)
| #' @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. |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
| #' @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. |
There was a problem hiding this comment.
- same point about not inferring independence from other arguments
- Per earlier discussion, NULL should just mean that we sample every parameter and shouldn't be tied to joint vs independent
- 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
There was a problem hiding this comment.
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
| 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]]] |
There was a problem hiding this comment.
not clear why this variable name is joint
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
per earlier comment, recommend not relying on param.names to indicated independent vs joint
There was a problem hiding this comment.
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
| # 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. |
There was a problem hiding this comment.
fair, it was. I rewrote it to just say what changed
611986a
|
|
||
| ### Changed | ||
|
|
||
| - `PEcAn.uncertainty::get.ensemble.samples()` draws joint MCMC rows at random with replacement, whatever `method` is (#4238). |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
yep, same problem as NEWS. I rewrote it to match
| # 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) |
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
| #' 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. |
There was a problem hiding this comment.
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?
| #' @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.
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 atrait.mcmcobject say it's joint,attr(trait.mcmc, "joint") <- TRUE, and keeps those rows together.load.posteriors()reads thejointattribute (PDA detection is unchanged)NA)param.namesshifted by one PFT when an earlier PFT had nothing to sample, andmethod = "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,sobolandlhcoptions for joint rows are left as they were. They spread the row index, not the trait values, so with unordered draws they act likeuniformon 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
Types of changes
Checklist: