diff --git a/DESCRIPTION b/DESCRIPTION index 236fc962..a3ea5e0c 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Package: dMod2 Type: Package Title: Parameter Estimation in Dynamical Models -Version: 0.17.1 +Version: 0.18.0 Date: 2026-11-25 Authors@R: c( person("Simon", "Beyer", email = "simon.beyer@fdm.uni-freiburg.de", diff --git a/NAMESPACE b/NAMESPACE index fb6951fe..a2ebec49 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -57,6 +57,7 @@ S3method(controls,objfn) S3method(covariates,data.frame) S3method(covariates,datalist) S3method(format,eqnvec) +S3method(format,hyperprior) S3method(getConditions,fn) S3method(getConditions,list) S3method(getDerivs,list) @@ -123,6 +124,7 @@ S3method(print,em) S3method(print,eqnlist) S3method(print,eqnvec) S3method(print,eventlist) +S3method(print,hyperprior) S3method(print,objfn) S3method(print,objlist) S3method(print,obsfn) @@ -192,6 +194,7 @@ export(as.parvec) export(as.prdlist) export(assignCompartment) export(attrs) +export(betaPrior) export(branch) export(combine) export(compile) @@ -243,9 +246,12 @@ export(getLocalDLLs) export(getParameters) export(getReactions) export(getSymbols) +export(halfCauchyPrior) +export(halfNormalPrior) export(importPEtab) export(importSbml) export(insert) +export(invGammaPrior) export(is.datalist) export(is.eqnlist) export(is.eqnvec) @@ -299,7 +305,6 @@ export(reconstControl) export(reduceReplicates) export(reml) export(remlLeverage) -export(repar) export(replaceSymbols) export(res) export(resolveRecurrence) diff --git a/NEWS.md b/NEWS.md index 0d0c788d..a358f73f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,53 @@ +# dMod2 0.18.0 + +* `symmetryDetection()` and `symmetryReduction()` need symident >= 0.18.2: under `equilibrate` + with continued conditions, the Lie order certificate ranks at resting points drawn forward + instead of at the start of the continuation, and reconstruction and checks take curve samples + where a direct solve of the resting balances needs msolve past short work limits. +* `em()` and `msem()` with spike-and-slab random effects of a given `mean` or `spike` fit in phases, + each from the estimates and inner modes of the phase before. `control$sparseFit$phases` lists + the approximations of the sum over subsets in the order they run, `"meanfield"`, `"ec"` and + `"exact"` (default all three), each with `maxECM` and `epsECM`. `"meanfield"` factorizes the + inclusion per random effect from the Laplace integrals of a reference subset and of the subsets + that differ from it in one random effect. `"exact"` beyond `termBudget` is skipped after `"ec"` + and an error without it. `control$sparseFit$burnin` (`FALSE` by default, `TRUE` or a list of + `start` and `iterlim`) first fits the fixed effects in one trust region with a start subset of + the spike-and-slab random effects in the slab, `"random"` (default), `"spike"`, `"slab"` or + given names; the others stay at the spike. The fit reports `phases`, a row per phase, and + `burnin`, the start subset; an error names the phase. `msem()` draws the start subset per + attempt; `multistart` has the columns `phase` and `subset`. +* Hyperpriors of spike-and-slab random effects: `spikeSlab(prob = betaPrior(a, b))` integrates + `prob` out, with the beta-binomial weight of the number of deviations in the slab over the groups + of a block, in the exact sum, mean field, EC, SAEM and the quadrature; `tau = halfCauchyPrior()`, + `halfNormalPrior()` or `invGammaPrior()` estimates `tau` as the posterior mode, and with + `integrate = TRUE` the phase `"exact"` integrates over `log tau`. `fit$slab` reports the posterior + of `prob` and the priors, `fit$hyperprior` the term of the scale prior in `value`. SAEM and the + quadrature take `betaPrior()` for deviations of one group. `em()` notes a spike-and-slab block of + one group with `prob` or `tau` estimated. +* `distributedComputing()` saves the job workspace uncompressed where `zstd` is found but fails; + before, the tasks started without a workspace and failed. The warning about failed tasks shows the + last lines of the output of the first failed task. +* The PSOCK clusters of `mstrust()`, `profile()`, `msem()` with a condition axis and of the + compilation on Windows open on a port drawn from the process id and the clock, not from the + random stream, and skip a port in use. Jobs with the same seed on one node no longer fail with + "port ... cannot be opened", and `.Random.seed` stays as it is. +* The expectation consistent (EC) approximation takes the expected Hessian of the data term, so that + it converges with an error model of the prediction. It expands the data term at the subset of + inclusion above 1/2 of the step before. +* `profile()` with the default `method = "integrate"` corrects every step by a short fit of the other + parameters with `trust()` (`algoControl$reoptimize = TRUE`), so that the path does not drift from + the constrained optimum; `reoptimize = FALSE` restores the integration alone. +* `repar()` is no longer exported: transformations are built with `define()`, which sets an entry, + `insert()`, which replaces a symbol wherever it occurs, and `branch()`. Both stop with the + expected order where the substitution is passed in place of the transformation. +* Renamed: `control$sparseFit$budget` to `termBudget`; `maxEcm`, `epsEcm` and `maxEcmPerStage` of + `control$quadrature` to `maxECM`, `epsECM` and `maxECMPerStage`. +* `steadyStates()` (AlyssaPetit 1.5) takes `zeroLoops`: `TRUE` sets to zero the largest set of + states that are only produced through one another, whose fluxes all vanish where the set is zero + and on which no conserved quantity lies, as a feedback loop that is off. A state of a conserved quantity whose balance is + left without a positive unknown is solved in a further round, with another state of the quantity + kept free. An unknown without an equation is not tried again within a run of the greedy search. + # dMod2 0.17.1 * Requires cppDE >= 0.13.16, whose derivatives of `exp10()` are finite at a spike of `-Inf`. diff --git a/R/EM.R b/R/EM.R index 006584bf..6b281df9 100644 --- a/R/EM.R +++ b/R/EM.R @@ -142,11 +142,22 @@ #' `p0` of a deviation of 0; a column `data` where a sparse random effect #' reaches no data of the group; such an effect rests at 0 with the prior.} #' \item{`slab`}{the hyperparameters of the spike-and-slab and -#' Dirichlet-process blocks.} +#' Dirichlet-process blocks; with hyperpriors also `lower` and `upper`, the +#' 95 % interval of a `prob` integrated out or a `tau` integrated over, and +#' `prior`, the hyperprior.} +#' \item{`hyperprior`}{with a scale prior on `tau`, -2 log of the prior +#' density at the estimate, which `value` holds as well.} #' \item{`valueSE`}{the standard error of `value` where it comes from #' importance sampling.} #' \item{`coupling`}{`"expectationConsistent"` where a group needed it, #' else `NULL`.} +#' \item{`phases`}{with spike-and-slab random effects of a given `mean` or +#' `spike`, a row per phase: `approx` (`"burnin"` for the burn-in), +#' `iterations` (0 for a skipped phase), `value` (-2 log L of the +#' approximation, for the burn-in data plus penalty), `converged`, +#' `seconds` and `failed`, the subsets of weight 0.} +#' \item{`burnin`}{the spike-and-slab random effects in the slab at the +#' start of the burn-in, `NULL` without burn-in.} #' \item{`boundary`}{the hyperparameters set to 0, see `control`.} #' \item{`etaModes`, `etaSE`, `shrinkage`}{the modes of the random effects per #' group, their conditional standard errors, and per random effect @@ -190,7 +201,7 @@ #' (`"resolution"`). `converged` means stationary at the levels reached, #' capped ones included; the fit returns the iterate of lowest -2 log L on #' the highest levels.} -#' \item{`maxEcmPerStage`, `cm1Control`, `maxCm1Iter`}{rebuilds per stage +#' \item{`maxECMPerStage`, `cm1Control`, `maxCm1Iter`}{rebuilds per stage #' (default 10, `stopReason` `"iterlim"` where they run out), [trust()] #' settings and iterations of a step (default 30).} #' \item{`pruneTol`}{nodes whose weight lies this much in log below the @@ -200,7 +211,7 @@ #' proposal at the mode of each group. A group is flagged where the two #' -2 log L differ by more than three standard errors plus the error the #' level of the group allows, or the Pareto shape of the weights exceeds 0.7.} -#' \item{`epsEcm`, `maxEcm`}{for `"laplaceEM"`: the extrapolated distance to +#' \item{`epsECM`, `maxECM`}{for `"laplaceEM"`: the extrapolated distance to #' the fixed point at which it stops, default 1e-5, and the iteration limit, #' default 200.} #' } @@ -276,26 +287,25 @@ #' \item{`trustControl`}{the [trust()] settings of the outer search. The modes #' are found as by FOCEI, by the group kernel, where the Gauss-Newton step is #' below 1e-8; of `control$innerControl` only `sqpIterlim` applies.} -#' \item{`maxEcm`, `epsEcm`, `budget`, `ec`}{of the sum over subsets, see below.} +#' \item{`burnin`, `phases`, `termBudget`, `ec`}{of the sum over subsets, +#' see below.} #' } #' -#' Spike-and-slab random effects with `mean` or `spike` other than 0, see -#' [spikeSlab()], take a separate path of `method = "focei"`, beside normal +#' Spike-and-slab random effects with `mean` or `spike` other than 0, or with +#' a hyperprior ([betaPrior()]), see [spikeSlab()], take a separate path of +#' `method = "focei"`, beside normal #' random effects of the same grouping but no Dirichlet-process ones. The #' integral of a group is the sum over all subsets of the spike-and-slab random #' effects, each subset a Laplace integral over the normal random effects and #' the slab ones of the subset at the inner mode, the other random effects at #' the spike; `spike = -Inf` switches the -#' parameter off. The number of subsets summed over all groups is at most -#' `budget` (default 4096). The fixed effects and hyperparameters follow by EM: +#' parameter off. The fixed effects and hyperparameters follow by EM: #' `prob` is the mean inclusion probability, `tau^2` the mean squared deviation #' from `mean` under the slab, and the fixed effects minimize the data term #' plus slab prior summed over the subsets with their weights, jointly with #' the subset modes; the log determinant of the Laplace integral enters the #' weights only; Omega is the mean of the posterior second moments of the -#' normal random effects, restricted to the block structure. EM stops after -#' `maxEcm` iterations (default 200) or when no -#' estimate changes by more than `epsEcm` (default 1e-6). The `p0` column of +#' normal random effects, restricted to the block structure. The `p0` column of #' the random table is the posterior probability of the spike. #' #' `method = "saem"` draws them by the moves of section SAEM: a spike at @@ -317,15 +327,43 @@ #' moves by trust steps on the frozen nodes, which are rebuilt after each step #' until a Newton step would lower -2 log L by less than `tolDecrement` #' (`stopReason` `"decrement"`). Of `control$quadrature` this path reads `tol`, -#' `maxLevel` and `maxNodes` (per subset), `tolDecrement`, `maxEcmPerStage`, +#' `maxLevel` and `maxNodes` (per subset), `tolDecrement`, `maxECMPerStage`, #' `cm1Control` and `maxCm1Iter`. #' -#' Groups beyond the budget, the largest first, take the expectation consistent -#' (EC) approximation in a coordinate in which the spike is 0: the rate +#' `phases` lists the approximations of the sum over subsets in the order they +#' run, each from the estimates and inner modes of the phase before: a +#' character vector, or a named list whose entries set `maxECM`, the ECM +#' iterations (default 200), and `epsECM`, the largest change of an estimate +#' at which the phase ends (default 1e-2, in the last phase 1e-6). Each name +#' at most once; default `c("meanfield", "ec", "exact")`: +#' \describe{ +#' \item{`"meanfield"`}{factorized inclusion per random effect, from the +#' Laplace integrals of a reference subset and of the subsets that differ +#' from it in one random effect; the reference is the subset of inclusion +#' above 1/2. A subset whose inner search fails has weight 0.} +#' \item{`"ec"`}{EC for every group, see below.} +#' \item{`"exact"`}{the sum over all subsets. Where the subsets summed over +#' the groups exceed `termBudget` (default 4096), the phase is skipped and +#' the fit ends with phase `"ec"`; without it, an error.} +#' } +#' `burnin` fits the fixed effects first, with `prob`, `tau` and `Omega` held, +#' in one trust region at the joint mode of a start subset of the +#' spike-and-slab random effects in the slab, the prior densities as penalty; +#' the others stay at the spike. `FALSE` (default) no burn-in, `TRUE` the +#' defaults, or a list of `start`, `"random"` (default, each in the slab with +#' probability `prob`, drawn from the random number stream), `"spike"`, `"slab"` +#' or the names of the random effects in the slab, and `iterlim`, the trust +#' iterations (default 200). The first phase starts from that subset. The fit +#' reports `burnin`, the start subset. `converged` is that of the last phase; +#' an error names the phase. +#' +#' EC is the +#' expectation consistent approximation in a coordinate in which the spike is 0: the rate #' \eqn{b^\eta}{b^eta} for `spike = -Inf`, where the slab is log-normal, and #' \eqn{\eta}{eta} minus the spike else. The data term is a Gaussian in that -#' coordinate, expanded first at the mode with every random effect in the slab -#' and again at the EC mean until it is stable; normal random effects enter it +#' coordinate, expanded first at the mode with the random effects of inclusion +#' above 1/2 of the step before in the slab (at the first step every one), and +#' again at the EC mean until it is stable; normal random effects enter it #' exactly, without sites. These groups take the subset of #' inclusion probability above 1/2 for the fixed effects. Entries of #' `control$sparseFit$ec`: `nodes` of the Gauss-Hermite rule of the log-normal @@ -350,6 +388,7 @@ em <- function(obj, random, init = NULL, fixed = NULL, cont <- .emContinue(obj, random, init, fixed) random <- cont$random; init <- cont$init; fixed <- cont$fixed design <- .emDesign(obj, random) + .hyperpriorHint(design, names(fixed)) start <- .emStart(design, init, fixed, sd = control$sd %||% 0.3) control$modes <- cont$modes control$selected <- cont$selected @@ -361,10 +400,10 @@ em <- function(obj, random, init = NULL, fixed = NULL, .checkEmControl <- function(control) { known <- list(control = c("sd", "inner", "innerControl", "trustControl", "secondOrderCorrection", "derivMode", "quadrature", "saem", "sparseFit", "boundary"), - sparseFit = c("maxOuter", "trustControl", "maxEcm", "epsEcm", "budget", "ec"), + sparseFit = c("maxOuter", "trustControl", "termBudget", "burnin", "phases", "ec"), ec = c("nodes", "maxSweeps", "tolSweep", "maxRelinearize", "tolRelinearize"), - quadrature = c("tol", "levels", "maxLevel", "maxNodes", "tolDecrement", "maxEcmPerStage", - "cm1Control", "maxCm1Iter", "pruneTol", "certificate", "epsEcm", "maxEcm"), + quadrature = c("tol", "levels", "maxLevel", "maxNodes", "tolDecrement", "maxECMPerStage", + "cm1Control", "maxCm1Iter", "pruneTol", "certificate", "epsECM", "maxECM"), saem = c("nBurnin", "nEM", "nMcmc", "nLaplace", "laplaceEvery", "laplaceScale", "window", "mcTol", "particles", "cm1Control", "nFlip", "nodes", "integral"), innerControl = c("rinit", "rmax", "iterlim", "mtol", "steptol", "eigenFloorRelative", "sqpIterlim")) @@ -376,6 +415,11 @@ em <- function(obj, random, init = NULL, fixed = NULL, stop("em: unknown entries of `", where, "`: ", paste(bad, collapse = ", "), ".", call. = FALSE) } + .spikePhases(control$sparseFit) + .spikeBurninOf(control$sparseFit) + tb <- control$sparseFit$termBudget + if (!is.null(tb) && !(is.numeric(tb) && length(tb) == 1L && !is.na(tb) && tb >= 0)) + stop("em: `control$sparseFit$termBudget` is one number of at least 0.", call. = FALSE) inner <- control[["inner"]] if (!is.null(inner) && !(length(inner) == 1L && inner %in% c("nested", "sqp"))) stop("em: `control$inner` is \"nested\" or \"sqp\".", call. = FALSE) @@ -390,6 +434,19 @@ em <- function(obj, random, init = NULL, fixed = NULL, stop("em: `control$boundary` is FALSE or one number of at least 0.", call. = FALSE) } +## A message where a spike-and-slab block of a design with one group estimates prob or tau: from the few +## deviations of the block an estimate of prob tends to 0 or 1, one of tau follows the modes. +.hyperpriorHint <- function(design, fixed = character(0)) { + if (!is.null(design$groupings) || length(design$groups) != 1L) return(invisible()) + estimated <- function(b, kind, prior) is.na(b[[kind]]) && is.null(prior) && !b$hyper[[kind]] %in% fixed + one <- Filter(function(b) b$dist == "spikeSlab" && + (estimated(b, "prob", b$probPrior) || estimated(b, "tau", b$tauPrior)), design$blocks) + if (length(one)) + message("em: a spike-and-slab block of one group estimates prob or tau from the few deviations of the block; ", + "spikeSlab(prob = betaPrior(), tau = halfCauchyPrior()) are priors for this case.") + invisible() +} + ## `expr` evaluated with `cores` cores over the conditions of an evaluation. .withCores <- function(cores, expr) { old <- options(dMod2.cores = as.integer(cores)) @@ -403,7 +460,9 @@ em <- function(obj, random, init = NULL, fixed = NULL, #' @description Runs [em()] from `fits` starts, the first at `init`, the others #' perturbed by normal noise of standard deviation `sd` (on the log scale for #' concentrations and slab standard deviations, on the logit scale -#' for slab probabilities), and returns the best fit. +#' for slab probabilities), and returns the best fit. With the burn-in of +#' spike-and-slab random effects at `start = "random"`, each attempt also draws +#' the start subset; `set.seed()` reproduces the starts. #' #' @inheritParams em #' @param fits Number of starts. Default 20. @@ -414,7 +473,8 @@ em <- function(obj, random, init = NULL, fixed = NULL, #' perturbs, the others keeping their start. Default 0.5. #' @param retry Logical. If `TRUE` (default), a fit that fails with an error, #' for instance at a start where a steady state of [Pimpl()] has no stable -#' root, is repeated from a new perturbed start, up to `nTries` attempts. +#' root or in a phase of the sum over subsets (`control$sparseFit`), is +#' repeated from a new perturbed start, up to `nTries` attempts. #' @param nTries Maximum number of attempts per start, including the first. #' Default `10`. #' @param verbose Logical. If `TRUE`, print the table of the starts; the fits @@ -438,8 +498,10 @@ em <- function(obj, random, init = NULL, fixed = NULL, #' every attempt failed.} #' \item{`failures`}{why evaluations in the trust region failed, and how #' often.} -#' \item{`error`, `boundary`}{the error of a failed start, the variances -#' the fit set to 0.} +#' \item{`error`, `phase`, `boundary`}{the error of a failed start, the +#' failed phase of the last attempt, the variances the fit set to 0.} +#' \item{`subset`}{the random effects in the slab during the burn-in, +#' separated by commas.} #' } #' [plotValues()] draws it as a waterfall. #' @seealso [em()] @@ -455,6 +517,7 @@ msem <- function(obj, random, init = NULL, fixed = NULL, cont <- .emContinue(obj, random, init, fixed) random <- cont$random; init <- cont$init; fixed <- cont$fixed design <- .emDesign(obj, random) + .hyperpriorHint(design, names(fixed)) center <- .emStart(design, init, fixed, sd = control$sd %||% 0.3) control$modes <- cont$modes control$selected <- cont$selected @@ -487,10 +550,10 @@ msem <- function(obj, random, init = NULL, fixed = NULL, }, dMod2DerivModeMessage = function(m) { note <<- conditionMessage(m) invokeRestart("muffleMessage") - }), error = function(e) conditionMessage(e)) + }), error = function(e) structure(conditionMessage(e), phase = e$phase %||% NA_integer_)) if (!is.character(fit)) break } - if (is.character(fit)) return(structure(fit, tries = a)) + if (is.character(fit)) return(structure(fit, tries = a, phase = attr(fit, "phase"))) fit$derivModeNote <- note fit$tries <- a fit @@ -516,7 +579,11 @@ msem <- function(obj, random, init = NULL, fixed = NULL, else as.character(r$stopReason %||% NA_character_), ""), failures = vapply(runs, function(r) if (is.character(r) || !length(r$failures)) "" else paste0(names(r$failures), " (", r$failures, ")", collapse = "; "), ""), - error = vapply(runs, function(r) if (is.character(r)) r else NA_character_, ""), + error = vapply(runs, function(r) if (is.character(r)) as.character(r) else NA_character_, ""), + phase = vapply(runs, function(r) if (!is.character(r)) NA_integer_ + else as.integer(attr(r, "phase") %||% NA_integer_), 0L), + subset = vapply(runs, function(r) if (is.character(r) || is.null(r$burnin)) NA_character_ + else paste(r$burnin, collapse = ","), ""), boundary = vapply(runs, function(r) if (is.character(r)) "" else paste(r$boundary, collapse = ", "), "")) if (verbose) print(table) if (!any(ok)) stop("msem: every fit failed; the first error: ", table$error[1], call. = FALSE) @@ -640,7 +707,9 @@ msem <- function(obj, random, init = NULL, fixed = NULL, return(.emResult(design, .fitFoceiJoint(design, joint, start, fixed, control), method, fixed)) } if (any(vapply(design$blocks, function(b) b$dist != "normal", TRUE))) { - general <- any(vapply(design$blocks, function(b) b$dist == "spikeSlab" && (b$mean != 0 || b$spike != 0), TRUE)) + # a given slab mean or spike, or a hyperprior, takes the sum over subsets + general <- any(vapply(design$blocks, function(b) b$dist == "spikeSlab" && + (b$mean != 0 || b$spike != 0 || !is.null(b$probPrior) || !is.null(b$tauPrior)), TRUE)) noProcess <- !any(vapply(design$blocks, function(b) b$dist == "dirichletProcess", TRUE)) if (general || (method == "quadrature" && noProcess)) { # stops where a spike at -Inf is not the rate 0 @@ -659,6 +728,9 @@ msem <- function(obj, random, init = NULL, fixed = NULL, if (method != "focei") stop("em: spike-and-slab and Dirichlet-process random effects are fitted by method = \"focei\" ", "or \"saem\".", call. = FALSE) + if (!is.null(control$sparseFit$phases) || !isFALSE(control$sparseFit$burnin %||% FALSE)) + stop("em: `control$sparseFit$phases` and `burnin` apply to spikeSlab() with `mean` or `spike` other than 0 ", + "or a hyperprior, and to method = \"quadrature\".", call. = FALSE) return(.emResult(design, .fitSparse(design, start, fixed, control, verbose), method, fixed)) } joint <- design$objfn + .normalPrior(design) diff --git a/R/PEtabInterface.R b/R/PEtabInterface.R index 0d272faa..af9d34a7 100644 --- a/R/PEtabInterface.R +++ b/R/PEtabInterface.R @@ -1230,8 +1230,8 @@ readPEtabTables <- function(yamlPath) { # The replacement has to be parenthesized as a whole: `^` is right # associative, so substituting into `K^2` would give `10^(K^2)` instead of # `(10^K)^2`. - if (length(log_pars)) tr <- repar(tr, "x <- (exp(x))", x = log_pars) - if (length(log10_pars)) tr <- repar(tr, "x <- (10^(x))", x = log10_pars) + if (length(log_pars)) tr <- .repar(tr, "x <- (exp(x))", x = log_pars) + if (length(log10_pars)) tr <- .repar(tr, "x <- (10^(x))", x = log10_pars) tr } @@ -1248,7 +1248,7 @@ readPEtabTables <- function(yamlPath) { if (kind == "init") { tr[cn] <- v } else if (identical(scope, "all")) { - tr <- repar(tr, paste0(cn, " <- ", v)) + tr <- .repar(tr, paste0(cn, " <- ", v)) } } tr diff --git a/R/alignment.R b/R/alignment.R index d64d7c54..dfabd313 100644 --- a/R/alignment.R +++ b/R/alignment.R @@ -1073,6 +1073,7 @@ print.alignmentmodel <- function(x, ...) { group = rows[[i]]$group, id = rows[[i]]$id, dist = rows[[i]]$dist, prob = rows[[i]]$prob, concentration = rows[[i]]$concentration, tau = rows[[i]]$tau, mean = rows[[i]]$mean %||% 0, spike = rows[[i]]$spike %||% 0, + probPrior = I(list(rows[[i]]$probPrior)), tauPrior = I(list(rows[[i]]$tauPrior)), stem = rows[[i]]$stem, stringsAsFactors = FALSE))) # per condition the value of a reading column where all readings of the condition share it, else NA single <- function(x) vapply(split(x, factor(cond, conds)), function(v) { @@ -1733,7 +1734,8 @@ simulate.alignment <- function(object, nsim = 1, seed = NULL, ...) { pars <- object$parameters lapply(seq_len(nsim), function(i) { if (!is.null(object$randomEffects)) - pars[names(.etaVector(object$fit))] <- .drawEtas(object$fit$design, c(object$fit$argument, object$fit$fixed))[names(.etaVector(object$fit))] + pars[names(.etaVector(object$fit))] <- .drawEtas(object$fit$design, c(object$fit$argument, object$fit$fixed), + object$fit$probPosterior)[names(.etaVector(object$fit))] y <- .alignmentEval(m, seq_len(nrow(m$data)), pars, deriv = FALSE)$y noise <- if (m$distribution == "t") stats::rt(nrow(y), m$df) else stats::rnorm(nrow(y)) d <- m$data diff --git a/R/compile.R b/R/compile.R index cf547ccc..913e9376 100644 --- a/R/compile.R +++ b/R/compile.R @@ -59,7 +59,7 @@ ## `FUN`, a function of base R only, over `X` on a PSOCK cluster of `cores` ## workers, for Windows, which cannot fork. The workers run no package code. .compileOnCluster <- function(X, FUN, cores) { - cl <- parallel::makeCluster(min(as.integer(cores), length(X))) + cl <- .makePSOCK(min(as.integer(cores), length(X))) on.exit(parallel::stopCluster(cl)) environment(FUN) <- globalenv() parallel::parLapplyLB(cl, X, FUN) diff --git a/R/emResults.R b/R/emResults.R index 22a5e767..74a5c2e8 100644 --- a/R/emResults.R +++ b/R/emResults.R @@ -24,7 +24,9 @@ prdfn = design$prdfn, data = design$data, errfn = design$errfn, design = design, trace = fit$trace, stageTrace = fit$stageTrace, certificate = fit$certificate, valueSE = fit$valueSE, coupling = fit$coupling, derivMode = fit$derivMode, - hessianExact = fit$hessianExact, innerModes = fit$innerModes) + hessianExact = fit$hessianExact, innerModes = fit$innerModes, phases = fit$phases, + burnin = fit$burnin, probPosterior = fit$probPosterior, + hyperprior = fit$hyperprior, tauPosterior = fit$tauPosterior) if (is.null(design$groupings)) { gr <- .groupingResult(design, pars, .emCurvature(fit), fit$etaModes, fit$etaCov, fit$clusters, fit$spike, design$reach, lowrank = if (!is.null(fit$hessian)) fit$lowrank) @@ -45,7 +47,7 @@ lapply(per, `[[`, f), names(per))) out$eta <- fit$etas } - out$slab <- .slabTable(design, pars, names(fixed)) + out$slab <- .slabTable(design, pars, names(fixed), c(fit$probPosterior, fit$tauPosterior)) class(out) <- c("em", "list") out } @@ -126,17 +128,37 @@ estimate = est, se = se, stringsAsFactors = FALSE)[keep, , drop = FALSE] } -## The hyperparameters of the spike-and-slab and cluster blocks: the probability of a deviation -## or the concentration, and the slab standard deviation. -.slabTable <- function(design, pars, fixed = NULL) { +## The hyperparameters of the spike-and-slab and cluster blocks: the probability of a deviation, under a beta +## prior the posterior mean with the 95 % interval of the posterior Beta of `posterior`, a tau integrated over +## log tau at exp of the posterior mean of log tau with the normal 95 % interval, +## or the concentration, and the slab standard deviation; with hyperpriors their description. +.slabTable <- function(design, pars, fixed = NULL, posterior = list()) { blocks <- Filter(function(b) b$dist %in% c("spikeSlab", "dirichletProcess"), design$blocks) if (!length(blocks)) return(NULL) - value <- function(b, kind) if (is.na(b[[kind]])) pars[[b$hyper[[kind]]]] else b[[kind]] - do.call(rbind, lapply(blocks, function(b) data.frame( - name = unname(b$hyper), distribution = b$dist, symbols = paste(b$short, collapse = ", "), - estimate = vapply(names(b$hyper), function(k) value(b, k), 0), - fixed = !is.na(unlist(b[names(b$hyper)])) | unname(b$hyper) %in% fixed, row.names = NULL, - stringsAsFactors = FALSE))) + rows <- do.call(rbind, lapply(blocks, function(b) { + kinds <- names(b$hyper) + prior <- list(prob = b$probPrior, tau = b$tauPrior) + post <- lapply(kinds, function(k) posterior[[b$hyper[[k]]]]) + estimate <- vapply(seq_along(kinds), function(i) { + k <- kinds[i] + p <- post[[i]] + if (!is.null(p)) return(if ("a" %in% names(p)) p[["a"]] / sum(p) else exp(p[["logMean"]])) + if (is.na(b[[k]])) pars[[b$hyper[[k]]]] else b[[k]] + }, 0) + bound <- function(q) vapply(post, function(p) { + if (is.null(p)) return(NA_real_) + if ("a" %in% names(p)) return(stats::qbeta(q, p[["a"]], p[["b"]])) + exp(p[["logMean"]] + stats::qnorm(q) * p[["logSd"]]) + }, 0) + data.frame(name = unname(b$hyper), distribution = b$dist, symbols = paste(b$short, collapse = ", "), + estimate = estimate, lower = bound(0.025), upper = bound(0.975), + prior = vapply(kinds, function(k) if (is.null(prior[[k]])) "" else .describeHyperprior(prior[[k]]), ""), + fixed = !is.na(unlist(b[kinds])) | unname(b$hyper) %in% fixed, row.names = NULL, + stringsAsFactors = FALSE) + })) + # the columns of the hyperpriors appear where a block has one + if (all(rows$prior == "")) rows[c("lower", "upper", "prior")] <- NULL + rows } ## The random effects per group: mode and conditional standard error; for spike-and-slab and @@ -632,7 +654,7 @@ simulate.em <- function(object, nsim = 1, seed = NULL, ...) { design <- object$design pars <- c(object$argument, object$fixed) lapply(seq_len(nsim), function(i) { - eta <- .drawEtas(design, pars) + eta <- .drawEtas(design, pars, object$probPosterior) conds <- names(design$data) pred <- setNames(.predictMany(design$prdfn, times = lapply(conds, function(cn) .emGrid(design, cn)), parsList = rep(list(c(object$argument, eta)), length(conds)), @@ -658,8 +680,8 @@ simulate.em <- function(object, nsim = 1, seed = NULL, ...) { ## One draw of the random effects of every group: normal blocks from Omega, spike-and-slab and ## cluster coordinates from their hyperparameters, clusters by the Chinese restaurant with the -## population value seated first. -.drawEtas <- function(design, pars) { +## population value seated first; `prob` under a beta prior drawn from the posterior in `posterior`. +.drawEtas <- function(design, pars, posterior = list()) { out <- setNames(numeric(length(.allEtas(design))), .allEtas(design)) for (sd in .subDesigns(design)) { E <- sd$etaNames @@ -685,7 +707,9 @@ simulate.em <- function(object, nsim = 1, seed = NULL, ...) { } next } - slab <- stats::rbinom(n, 1, value("prob")) == 1L + post <- posterior[[b$hyper[["prob"]]]] %||% if (!is.null(b$probPrior)) c(a = b$probPrior$a, b = b$probPrior$b) + prob <- if (is.null(post)) value("prob") else stats::rbeta(1, post[["a"]], post[["b"]]) + slab <- stats::rbinom(n, 1, prob) == 1L out[as.vector(E[, b$stems, drop = FALSE])] <- ifelse(slab, stats::rnorm(n, b$mean %||% 0, value("tau")), b$spike %||% 0) } diff --git a/R/nlmeDesign.R b/R/nlmeDesign.R index aadec11e..d2a3d325 100644 --- a/R/nlmeDesign.R +++ b/R/nlmeDesign.R @@ -367,12 +367,13 @@ .allEtas <- function(design) unlist(lapply(.subDesigns(design), function(sd) as.vector(sd$etaNames))) -## One distribution block: the stems (random-effect columns) and short names, the distribution -## and the fixed hyperparameters, NA when estimated. +## One distribution block: the stems (random-effect columns) and short names, the distribution, +## the fixed hyperparameters, NA when estimated, and the hyperpriors of `prob` and `tau`, NULL without. .designBlock <- function(rows) { list(dist = rows$dist[1], prob = rows$prob[1], concentration = rows$concentration[1], tau = rows$tau[1], mean = rows$mean[1] %||% 0, spike = rows$spike[1] %||% 0, stems = rows$stem, - short = sub("^eta_", "", rows$stem)) + short = sub("^eta_", "", rows$stem), probPrior = (rows$probPrior %||% list(NULL))[[1]], + tauPrior = (rows$tauPrior %||% list(NULL))[[1]]) } ## Names of the hyperparameters of the blocks of one distribution, `hyper` named by `kinds` @@ -387,8 +388,12 @@ }, blocks, suffix) } -## The estimated hyperparameters of a block, named by kind. -.estimatedHypers <- function(b) b$hyper[is.na(unlist(b[names(b$hyper)]))] +## The estimated hyperparameters of a block, named by kind; `prob` under a beta prior is integrated out. +.estimatedHypers <- function(b) { + h <- b$hyper[is.na(unlist(b[names(b$hyper)]))] + if (!is.null(b$probPrior)) h <- h[names(h) != "prob"] + h +} ## Cholesky layout of the normal random effects: one lower-triangular factor over all normal diff --git a/R/nlmeDiagnostics.R b/R/nlmeDiagnostics.R index 001ce185..0cefa643 100644 --- a/R/nlmeDiagnostics.R +++ b/R/nlmeDiagnostics.R @@ -24,7 +24,7 @@ utils::globalVariables(c("lo", "mid", "hi", "percentile", "blq", "blqLo", "blqMi data <- Map(function(d, o) d[o, , drop = FALSE], design$data, rowsOf) node <- if (!is.null(design$errfn)) .fnNode(design$errfn) one <- function() { - eta <- .drawEtas(design, pars) + eta <- .drawEtas(design, pars, object$probPosterior) preds <- setNames(.predictMany(design$prdfn, times = grids, parsList = rep(list(c(object$argument, eta)), length(conds)), conditions = conds, fixed = object$fixed, deriv = FALSE), conds) errs <- if (!is.null(node)) { diff --git a/R/nlmeQuadrature.R b/R/nlmeQuadrature.R index 0a0a7fe0..89ccaf08 100644 --- a/R/nlmeQuadrature.R +++ b/R/nlmeQuadrature.R @@ -492,7 +492,7 @@ qc <- control$quadrature %||% list() levels <- qc$levels %||% (lay$K + 1L) tol <- qc$tol %||% 0.1 - nIt <- qc$maxEcmPerStage %||% 10L + nIt <- qc$maxECMPerStage %||% 10L q <- .quadratureObjective(design, start, fixed, modifyList(control, qc)) if (!is.null(etaInit)) q$state$modes <- etaInit psi <- start @@ -545,7 +545,7 @@ ## Laplace-EM: CM-1 on the frozen nodes of level K + 1 (one node would drop the posterior ## variance), Omega from the moments eta* eta*' + (H / 2)^-1, until the extrapolated distance -## to the fixed point is below `epsEcm`; the reported value at level K + 2. +## to the fixed point is below `epsECM`; the reported value at level K + 2. .fitLaplaceEM <- function(design, start, fixed, control = list(), verbose = FALSE) { lay <- design$normal qc <- control$quadrature %||% list() @@ -558,7 +558,7 @@ tolControl = list(ftol = 1e-8, mtol = 1e-8)), qc$cm1Control, label = "cm1Control") rows <- list(); conv <- FALSE; last <- Inf - for (it in seq_len(qc$maxEcm %||% 200L)) { + for (it in seq_len(qc$maxECM %||% 200L)) { if (it > 1L) q$rebuild(psi, lay$K + 1L) before <- psi # with every structural parameter fixed only Omega moves @@ -580,7 +580,7 @@ rows[[length(rows) + 1L]] <- data.frame(level = lay$K + 1L, ecmIter = it, OFV = cm$value, deltaPsi = dpsi, distance = distance) if (verbose) message(sprintf("em(laplaceEM) ecm %d: -2 log L %.6f, |delta psi| %.2e", it, cm$value, dpsi)) - if (max(dpsi, distance) < (qc$epsEcm %||% 1e-5)) { conv <- TRUE; break } + if (max(dpsi, distance) < (qc$epsECM %||% 1e-5)) { conv <- TRUE; break } } q$rebuild(psi, lay$K + 2L) .quadratureResult(design, q, psi, fixed, length(rows), conv, do.call(rbind, rows), exact) diff --git a/R/nlmeSaem.R b/R/nlmeSaem.R index 3f96f4bc..b7737fc3 100644 --- a/R/nlmeSaem.R +++ b/R/nlmeSaem.R @@ -482,7 +482,7 @@ ## the slab value integrated out by Gauss-Hermite, independence Metropolis-Hastings on the exact posterior ## (methods-nlme, SAEM); for a spike at -Inf `override` holds the proposal mean and sd per group. .slabCollapsed <- function(V, Z, value, dataAt, model, prob, tau, j, scale, gh, spike = 0 * tau, mu = 0 * tau, - override = NULL) { + override = NULL, beta = NULL) { G <- nrow(V); J <- ncol(V) go <- !is.na(j) base <- V; dir <- matrix(0, G, J); m <- sd <- rep(NA_real_, G) @@ -517,6 +517,8 @@ # log p(y, eta) of a group on the line at x from the data term d, with the prior of every # coordinate of the group lp1 <- matrix(log(prob), G, J, byrow = TRUE); lp0 <- matrix(log1p(-prob), G, J, byrow = TRUE) + # the coordinates under a beta prior on prob enter by the count of their block instead + if (!is.null(beta)) lp1[, !is.na(beta$block)] <- lp0[, !is.na(beta$block)] <- 0 sdSlab <- matrix(tau, G, J, byrow = TRUE) muSlab <- matrix(mu, G, J, byrow = TRUE) xOff <- ifelse(go, spike[ig[, 2]], 0) @@ -524,6 +526,7 @@ z <- Z; z[ig] <- slab v <- lineAt(ifelse(go, x, 0)) out <- rowSums(ifelse(z, lp1 + stats::dnorm(v, muSlab, sdSlab, log = TRUE), lp0)) - d / 2 + if (!is.null(beta)) out <- out + .betaCountPrior(z, beta) ifelse(go, out, NA_real_) } # the data term on the line at the columns of `x`, all in one evaluation; where that fails each @@ -576,6 +579,19 @@ out } +## Per group the log prior of the indicators `z` (groups x stems) under the beta priors of `beta`: per block +## log B(a + n, b + K - n) / B(a, b) with n of the K coordinates of the block that reach data in the slab. +.betaCountPrior <- function(z, beta) { + out <- numeric(nrow(z)) + for (bl in unique(stats::na.omit(beta$block))) { + cols <- which(beta$block == bl) + n <- rowSums(z[, cols, drop = FALSE] & beta$reach[, cols, drop = FALSE]) + K <- rowSums(beta$reach[, cols, drop = FALSE]) + out <- out + lbeta(beta$a[[bl]] + n, beta$b[[bl]] + K - n) - lbeta(beta$a[[bl]], beta$b[[bl]]) + } + out +} + ## A random-walk Metropolis step on all slab values of every group where the indicator is set, of ## size `step` per group times `sd` per coordinate; the acceptance per group. .slabWalk <- function(V, Z, value, dataAt, tau, step, sd, mu = 0 * tau) { @@ -611,7 +627,16 @@ blockOf <- function(st) Filter(function(b) st %in% b$stems, design$blocks)[[1]] spikeS <- vapply(slabStems, function(st) blockOf(st)$spike %||% 0, 0) meanS <- vapply(slabStems, function(st) blockOf(st)$mean %||% 0, 0) - general <- any(spikeS != 0 | meanS != 0) + # beta priors on prob: per slab stem the block, and the shapes by block + betaBlock <- vapply(slabStems, function(st) { + b <- blockOf(st) + if (is.null(b$probPrior)) NA_integer_ else match(TRUE, vapply(design$blocks, identical, TRUE, b)) + }, 0L) + betaS <- if (any(!is.na(betaBlock))) list(block = betaBlock, + a = lapply(design$blocks, function(b) b$probPrior$a), b = lapply(design$blocks, function(b) b$probPrior$b)) + hyperprior <- any(vapply(slabStems, function(st) !is.null(blockOf(st)$probPrior) || !is.null(blockOf(st)$tauPrior), + TRUE)) + general <- any(spikeS != 0 | meanS != 0) || hyperprior if (general && length(dpStems)) stop("em: spikeSlab() with `mean` or `spike` other than 0 is fitted by method = \"saem\" beside no ", "Dirichlet-process random effects.", call. = FALSE) @@ -668,6 +693,11 @@ for (st in sl$stem) chain$full[Dp[, st]] <- mode0[, st] Ds <- Dp[, slabStems, drop = FALSE] reach <- .reachOf(design)[, slabStems, drop = FALSE] + # the moves of all groups at once keep the posterior where a beta prior couples no two groups + for (bl in unique(stats::na.omit(betaBlock))) + if (sum(rowSums(reach[, which(betaBlock == bl), drop = FALSE]) > 0) > 1L) + stop("em: method = \"saem\" takes betaPrior() for spike-and-slab random effects that reach the data of one ", + "group.", call. = FALSE) spikeM <- matrix(spikeS, G, length(slabStems), byrow = TRUE) # a slab start without a finite slab-alone mode is the slab mean chain$full[Ds] <- ifelse(is.finite(chain$full[Ds]), chain$full[Ds], rep(meanS, each = G)) @@ -710,7 +740,7 @@ chain <- .saemClusterSweep(chain, Dp, dpStems, density, Oinv, logDet, hyp, burnin) if (length(slabStems)) { slabs <- .saemSlabMoves(chain, design, objs, E, Ds, reach, fixed, hyp, slabStems, density, Oinv, logDet, - saem, gh, burnin, spikeS, meanS) + saem, gh, burnin, spikeS, meanS, betaS) chain <- slabs$chain moves <- slabs$moves } @@ -756,10 +786,15 @@ hypS <- .stemHypers(sl, c(chain$hyper, fixed)) est <- .spikeEStep(design, objs, lay2, chain$full[.setdiff(names(outer), lay$cholPars)], fixed, list(prob = hypS$prob[lay2$stem], tau = hypS$tau[lay2$stem]), list(), .spikeBases(design), - control$sparseFit$budget %||% .spikeBudget, control$sparseFit$ec, NULL, list(), + control$sparseFit$termBudget %||% .spikeBudget, control$sparseFit$ec, NULL, list(), .spikeOmega(design, c(chain$full, fixed))) extra <- .extraObjective(design) - value <- sum(vapply(est, `[[`, 0, "m2logI")) + + # -2 log p(tau) of the scale priors at the estimate, and the posterior of prob under a beta prior + penalty <- sum(vapply(unique(lay2$block), function(b) + .spikeTauPenalty(hypS$tau[[lay2$stem[lay2$block == b][1]]], design$blocks[[b]]$tauPrior), 0)) + probPosterior <- Filter(Negate(is.null), setNames(lapply(unique(lay2$block), function(b) + .spikeProbPosterior(lay2, est, b)), lay2$probName[match(unique(lay2$block), lay2$block)])) + value <- sum(vapply(est, `[[`, 0, "m2logI")) + penalty + if (!is.null(extra)) extra(chain$full[.setdiff(names(outer), lay$cholPars)], fixed = fixed, deriv = FALSE)$value else 0 cov <- lapply(design$groups, function(g) { e <- est[[g]] @@ -771,7 +806,8 @@ }) return(list(argument = psi, value = value, gradient = NULL, hessian = NULL, etaModes = picked$modes, etaCov = setNames(cov, design$groups), clusters = picked$clusters, spike = picked$spike, - converged = stationary, iterations = nrow(trace), stageTrace = trace)) + converged = stationary, iterations = nrow(trace), stageTrace = trace, probPosterior = probPosterior, + hyperprior = if (any(!vapply(design$blocks, function(b) is.null(b$tauPrior), TRUE))) penalty)) } # -2 log L as em(method = "focei") defines it, with the second derivatives the models provide reachAll <- .reachOf(design) @@ -848,7 +884,8 @@ ## refreshed: per sweep the collapsed birth or death move on every indicator once, then random-walk steps on the ## slab values; the Rao-Blackwellized inclusion and slab second moment per coordinate and the acceptance rates. .saemSlabMoves <- function(chain, design, objs, E, Ds, reach, fixed, hyp, slabStems, density, Oinv, logDet, - saem, gh, burnin, spikeS = 0 * hyp$tau[slabStems], meanS = 0 * hyp$tau[slabStems]) { + saem, gh, burnin, spikeS = 0 * hyp$tau[slabStems], meanS = 0 * hyp$tau[slabStems], + betaS = NULL) { G <- nrow(Ds) tauS <- hyp$tau[slabStems]; probS <- hyp$prob[slabStems] groupPars <- function() lapply(seq_len(G), function(g) { @@ -911,7 +948,7 @@ for (r in seq_len(max(lengths(visit), 0L))) { j <- vapply(visit, function(i) if (r <= length(i)) i[r] else NA_integer_, 0L) fl <- .slabCollapsed(V, incl, value, blockAt, model, probS, tauS, j, saem$laplaceScale, gh, spikeS, meanS, - newton(V, j)) + newton(V, j), if (!is.null(betaS)) c(betaS, list(reach = reach))) V <- fl$V; incl <- fl$Z; value <- fl$value tried <- tried + c(sum(fl$birth, na.rm = TRUE), sum(!fl$birth, na.rm = TRUE)) taken <- taken + c(sum(fl$ok & fl$birth, na.rm = TRUE), sum(fl$ok & !fl$birth, na.rm = TRUE)) @@ -982,7 +1019,8 @@ b <- blocks[[j]] tn <- unname(b$hyper["tau"]); cn <- unname(b$hyper["concentration"]); pn <- unname(b$hyper["prob"]) if (tn %in% hypers && averaged["free", j] > 1e-8) - chain$hyper[[tn]] <- bound(sqrt(averaged["slab2", j] / averaged["free", j]), chain$hyper[[tn]]) + chain$hyper[[tn]] <- bound(.spikeTauMode(averaged["slab2", j], averaged["free", j], b$tauPrior, + chain$hyper[[tn]]), chain$hyper[[tn]]) if (cn %in% hypers) chain$hyper[[cn]] <- bound(.ewensConcentration(averaged["free", j], rep(G, length(b$stems))), chain$hyper[[cn]]) if (pn %in% hypers && averaged["groups", j] > 0) { diff --git a/R/nlmeSparse.R b/R/nlmeSparse.R index 50468154..eb35b893 100644 --- a/R/nlmeSparse.R +++ b/R/nlmeSparse.R @@ -12,7 +12,8 @@ do.call(rbind, lapply(seq_along(blocks), function(i) { b <- blocks[[i]] data.frame(stem = b$stems, block = i, dist = b$dist, probName = name(b, "prob"), - concentrationName = name(b, "concentration"), tauName = name(b, "tau"), prob = b$prob, + concentrationName = name(b, "concentration"), tauName = name(b, "tau"), + prob = if (is.null(b$probPrior)) b$prob else b$probPrior$a / (b$probPrior$a + b$probPrior$b), concentration = b$concentration, tau = b$tau, stringsAsFactors = FALSE) })) } diff --git a/R/nlmeSpikeEC.R b/R/nlmeSpikeEC.R index b99a7f47..c508a4bd 100644 --- a/R/nlmeSpikeEC.R +++ b/R/nlmeSpikeEC.R @@ -51,8 +51,9 @@ } ## EC over the slab candidates `cand` of group `g`, the normal etas `nrm` exact in the Gaussian, expanded first at -## `start`: -2 log I, inclusion probabilities, E[(eta - mean)^2 | slab], E[eta eta'] of the normal etas and the -## subset of inclusion above 1/2; NULL where EC or the relinearization does not converge. +## `start`: -2 log I, inclusion probabilities, E[(eta - mean)^2 | slab], E[eta eta'] of the normal etas, the +## subset of inclusion above 1/2 and per site the log masses of spike and slab under the cavity and the log +## mass of their mixture; NULL where EC or the relinearization does not converge. .spikeECGroup <- function(design, objs, g, theta, fixed, etas, cand, nrm, pr, alpha, prob, lb, start, control = list()) { conds <- design$conditions[[g]] @@ -80,8 +81,9 @@ for (outer in seq_len(control$maxRelinearize %||% 30L)) { um <- pmax(um, floorU) eta <- setNames(etaOf(um), co) + # the expected Hessian, positive semidefinite also with an error model of the prediction out <- Reduce(`+`, .objEvalMany(objs[conds], rep(list(eta), length(conds)), deriv = TRUE, - fixed = c(theta, fixed, alpha[.setdiff(etas, co)]))) + fixed = c(theta, fixed, alpha[.setdiff(etas, co)]), hessian = "expected")) if (!is.finite(out$value)) return(NULL) D <- ifelse(rate, 1 / (um * lbc), 1) gu <- D * out$gradient[co] @@ -143,7 +145,7 @@ Sigma <- chol2inv(chol(A + diag(lam, N))) m <- drop(Sigma %*% (a + gam)) # the tilted moments and site constants of every site at the converged posterior - logC <- incl <- dev2 <- numeric(J) + logC <- incl <- dev2 <- massSpike <- massSlab <- logZsite <- numeric(J) for (j in seq_len(J)) { v <- Sigma[j, j] pc <- 1 / v - lam[j] @@ -157,6 +159,7 @@ top <- max(lSpike, lSlab) logZj <- top + log(exp(lSpike - top) + exp(lSlab - top)) incl[j] <- exp(lSlab - logZj) + massSpike[j] <- lSpike - log1p(-prob[[e]]); massSlab[j] <- lSlab - log(prob[[e]]); logZsite[j] <- logZj dev2[j] <- s$dev2 # the site constant: the tilted mass over the mass of cavity times site p <- 1 / vc + lam[j]; r <- mc / vc + gam[j] @@ -171,5 +174,6 @@ k <- J + seq_along(nrm) normalMoment <- if (length(nrm)) Sigma[k, k, drop = FALSE] + tcrossprod(m[k]) list(m2logI = -2 * logI, inclusion = setNames(incl, cand), dev2 = setNames(dev2, cand), - normalMoment = normalMoment, on = cand[incl > 0.5]) + normalMoment = normalMoment, on = cand[incl > 0.5], massSpike = setNames(massSpike, cand), + massSlab = setNames(massSlab, cand), logZsite = setNames(logZsite, cand)) } diff --git a/R/nlmeSpikeSubsets.R b/R/nlmeSpikeSubsets.R index 35e30107..995460e0 100644 --- a/R/nlmeSpikeSubsets.R +++ b/R/nlmeSpikeSubsets.R @@ -6,13 +6,79 @@ ## The most Laplace integrals per evaluation, summed over the groups. .spikeBudget <- 4096L -## Per stem of the spike-and-slab blocks: block, slab mean, spike and the hyperparameter names. +## The approximations of the sum over subsets that a phase takes. +.spikeApprox <- c("meanfield", "ec", "exact") + +## TRUE for one number of at least `from`, and for `.isCount()` a whole one. +.isNumberFrom <- function(x, from) is.numeric(x) && length(x) == 1L && !is.na(x) && x >= from +.isCount <- function(x) .isNumberFrom(x, 1) && x == round(x) + +## The burn-in of control$sparseFit: NULL without, else `start` and `iterlim`. +.spikeBurninOf <- function(sf) { + b <- sf$burnin %||% FALSE + if (isFALSE(b)) return(NULL) + if (isTRUE(b)) b <- list() + start <- if (is.list(b)) b$start %||% "random" + iterlim <- if (is.list(b)) b$iterlim %||% 200L + ok <- is.list(b) && all(names(b) %in% c("start", "iterlim")) && is.character(start) && !anyNA(start) && + .isCount(iterlim) + if (!ok) + stop("em: `control$sparseFit$burnin` is FALSE, TRUE or a list of `start` (\"random\", \"spike\", \"slab\" or ", + "names of spike-and-slab random effects) and `iterlim` (a whole number of at least 1).", call. = FALSE) + list(start = start, iterlim = as.integer(iterlim)) +} + +## The phases of control$sparseFit in the order they run, each with `approx`, `maxECM` and `epsECM`; epsECM +## defaults to 1e-2, in the last phase to 1e-6. +.spikePhases <- function(sf) { + ph <- sf$phases %||% .spikeApprox + if (is.character(ph)) ph <- setNames(rep(list(list()), length(ph)), ph) + entryOk <- function(p) is.list(p) && all(names(p) %in% c("maxECM", "epsECM")) && + (is.null(p$maxECM) || .isCount(p$maxECM)) && (is.null(p$epsECM) || .isNumberFrom(p$epsECM, 0)) + ok <- is.list(ph) && length(ph) > 0L && !is.null(names(ph)) && all(names(ph) %in% .spikeApprox) && + !anyDuplicated(names(ph)) && + all(vapply(ph, entryOk, TRUE)) + if (!ok) + stop("em: `control$sparseFit$phases` names each of \"meanfield\", \"ec\" and \"exact\" at most once, as a ", + "character vector or a list of lists with `maxECM` (a whole number of at least 1) and `epsECM`.", + call. = FALSE) + last <- length(ph) + Map(function(approx, p, i) list(approx = approx, maxECM = as.integer(p$maxECM %||% 200L), + epsECM = p$epsECM %||% if (i == last) 1e-6 else 1e-2), + names(ph), ph, seq_along(ph)) +} + +## The spike-and-slab etas in the slab during the burn-in from `start`: each with the probability `prob` of the +## stem, none, every one, or the given ones; the others stay at the spike. +.spikeBurninSet <- function(start, design, lay, prob) { + E <- design$etaNames[, lay$stem, drop = FALSE] + etas <- as.vector(E) + if (identical(start, "random")) return(etas[stats::runif(length(etas)) < prob[rep(lay$stem, each = nrow(E))]]) + if (identical(start, "spike")) return(character(0)) + if (identical(start, "slab")) return(etas) + bad <- .setdiff(start, etas) + if (length(bad)) + stop("em: `control$sparseFit$burnin$start` names no spike-and-slab random effect: ", paste(bad, collapse = ", "), + ".", call. = FALSE) + start +} + +## The error `e` of phase `i` with approximation `approx` as a condition with the phase in field `phase`. +.spikePhaseError <- function(e, i, approx, several) { + msg <- conditionMessage(e) + if (several) msg <- sprintf("em: phase %d (%s): %s", i, approx, sub("^em: ", "", msg)) + structure(class = c("dMod2PhaseError", "error", "condition"), list(message = msg, call = NULL, phase = i)) +} + +## Per stem of the spike-and-slab blocks: block, slab mean, spike, the hyperparameter names and the shapes of a +## beta prior on `prob`, NA without. .spikeLayout <- function(design) { blocks <- design$blocks do.call(rbind, lapply(which(vapply(blocks, function(b) b$dist == "spikeSlab", TRUE)), function(i) { b <- blocks[[i]] data.frame(stem = b$stems, block = i, mean = b$mean, spike = b$spike, prob = b$prob, tau = b$tau, - probName = b$hyper[["prob"]], tauName = b$hyper[["tau"]], stringsAsFactors = FALSE) + probName = b$hyper[["prob"]], tauName = b$hyper[["tau"]], betaA = b$probPrior$a %||% NA_real_, + betaB = b$probPrior$b %||% NA_real_, stringsAsFactors = FALSE) })) } @@ -48,8 +114,9 @@ ## The Laplace integral of group `g` over the etas `on` (the normal etas and the slab etas of the subset, ## the other slab etas at the spike): -2 log Z with the normalizer of the prior, the mode and the -## covariance 2 H^-1; NULL where the inner search fails. -.spikeSubset <- function(design, objs, g, theta, fixed, etas, on, pr, start) { +## covariance 2 H^-1; NULL where the inner search fails. With `laplace = FALSE` the value of data plus prior +## at the mode and the mode alone. +.spikeSubset <- function(design, objs, g, theta, fixed, etas, on, pr, start, laplace = TRUE) { conds <- design$conditions[[g]] off <- .setdiff(etas, on) base <- c(theta, fixed) @@ -76,6 +143,7 @@ paste(on, collapse = ", "), " and the others at the spike failed: ", conditionMessage(e), call. = FALSE)) if (!is.finite(fit$value)) return(NULL) + if (!laplace) return(list(m2logZ = fit$value, mode = fit$argument)) at <- objfun(fit$argument, fixed = fx) H <- (at$hessian + t(at$hessian)) / 2 ch <- tryCatch(chol(H / 2), error = function(e) NULL) @@ -165,19 +233,23 @@ as.matrix(expand.grid(rep(list(c(FALSE, TRUE)), n))) > 0 } -## The E-step of every group: per subset of the slab etas that reach the group data the weight, mode and -## covariance; -2 log I per group; the probability of the spike per eta. Groups beyond `budget` subsets, -## the largest first, take EC (.spikeECGroup()) and the subset of inclusion above 1/2 as their one part. -.spikeEStep <- function(design, objs, lay, theta, fixed, hyp, warm, bases, budget, control = list(), - quadrature = NULL, gridWarm = list(), omega = NULL) { +## The E-step of every group by the approximation `approx`: per subset of the slab etas that reach the group +## data the weight, mode and covariance; -2 log I per group; the probability of the slab per eta; `ref`, the +## candidates of inclusion above 1/2. "exact" sums exactly over the subsets of the groups within `termBudget` +## subsets, the smallest first, and takes EC for the others; "burnin" takes the one subset `ref` at the joint +## mode, without integral. EC and mean field take the subset of inclusion above 1/2 as their one part, and +## expand around `ref` of the step before. +.spikeEStep <- function(design, objs, lay, theta, fixed, hyp, warm, bases, termBudget, control = list(), + quadrature = NULL, gridWarm = list(), omega = NULL, approx = "exact", ref = list()) { E <- design$etaNames reach <- .reachOf(design) stems <- lay$stem nstems <- design$normal$stems lbStem <- setNames(ifelse(stems %in% names(bases), log(bases[stems]), NA_real_), stems) sizes <- setNames(rowSums(reach[design$groups, stems, drop = FALSE]), design$groups) - exact <- design$groups[order(sizes)][cumsum(2^sort(sizes)) <= budget] - lapply(setNames(nm = design$groups), function(g) { + exact <- if (approx == "exact") design$groups[order(sizes)][cumsum(2^sort(sizes)) <= termBudget] else character(0) + betaBlocks <- unique(lay$block[!is.na(lay$betaA)]) + out <- lapply(setNames(nm = design$groups), function(g) { slab <- unname(E[g, stems]) nrm <- unname(E[g, nstems]) etas <- c(slab, nrm) @@ -188,6 +260,7 @@ probG <- setNames(hyp$prob[stems], slab) pr <- .spikePriorOf(mu, tauG, nrm, omega$Oinv, omega$logdetO) cand <- unname(E[g, stems[reach[g, stems]]]) + refG <- .intersect(ref[[g]] %||% cand, cand) keyOf <- function(on) paste(on, collapse = ",") startOf <- function(on) { v <- alpha @@ -195,11 +268,22 @@ v[on] <- warm[[g]][[keyOf(on)]] %||% c(mu, setNames(rep(0, length(nrm)), nrm))[on] v } + group <- list(slab = slab, normal = nrm, etas = etas, cand = cand, mu = mu, alpha = alpha) + if (approx == "burnin") { + on <- c(nrm, refG) + r <- .spikeSubset(design, objs, g, theta, fixed, etas, on, pr, startOf(on), laplace = FALSE) + if (is.null(r)) stop("em: the joint mode of group ", g, " is not finite.", call. = FALSE) + r$on <- on + r$weight <- 1 + return(c(list(parts = list(r), m2logI = r$m2logZ, inclusion = probG, ref = refG), group)) + } + if (approx == "meanfield") + return(c(.spikeMeanField(design, objs, g, theta, fixed, etas, cand, nrm, pr, probG, refG, startOf), group)) if (!g %in% exact) { - # the data term first expanded at the mode with every candidate in the slab - start <- startOf(c(nrm, cand)) - full <- .spikeSubset(design, objs, g, theta, fixed, etas, c(nrm, cand), pr, start) - if (!is.null(full)) start[c(nrm, cand)] <- full$mode + # the data term first expanded at the mode with the candidates of `ref` in the slab + start <- startOf(c(nrm, refG)) + full <- .spikeSubset(design, objs, g, theta, fixed, etas, c(nrm, refG), pr, start) + if (!is.null(full)) start[c(nrm, refG)] <- full$mode ec <- .spikeECGroup(design, objs, g, theta, fixed, etas, cand, nrm, pr, alpha, probG, setNames(lbStem, slab), start, control) if (is.null(ec)) @@ -211,17 +295,23 @@ r$weight <- 1 inclusion <- probG inclusion[cand] <- ec$inclusion[cand] - return(list(parts = list(r), m2logI = ec$m2logI, inclusion = inclusion, slab = slab, normal = nrm, - etas = etas, cand = cand, mu = mu, alpha = alpha, - ec = list(inclusion = ec$inclusion, dev2 = ec$dev2, normalMoment = ec$normalMoment))) + return(c(list(parts = list(r), m2logI = ec$m2logI, inclusion = inclusion, ref = ec$on, + factor = list(base = -ec$m2logI / 2 - sum(ec$logZsite), w0 = ec$massSpike, w1 = ec$massSlab, + logZ = ec$logZsite), + perCandidate = list(inclusion = ec$inclusion, dev2 = ec$dev2, normalMoment = ec$normalMoment)), + group)) } S <- .subsets(length(cand)) + # candidates under a beta prior on `prob` enter by their count per block, the others by the product + betaBlock <- setNames(ifelse(is.na(lay$betaA), NA_integer_, lay$block), slab)[cand] + prodC <- is.na(betaBlock) parts <- lapply(seq_len(nrow(S)), function(i) { on <- c(nrm, cand[S[i, ]]) r <- .spikeSubset(design, objs, g, theta, fixed, etas, on, pr, startOf(on)) if (is.null(r)) return(NULL) r$on <- on - r$logw <- sum(log(probG[cand[S[i, ]]])) + sum(log1p(-probG[cand[!S[i, ]]])) - r$m2logZ / 2 + r$logw <- sum(log(probG[cand[S[i, ] & prodC]])) + sum(log1p(-probG[cand[!S[i, ] & prodC]])) - r$m2logZ / 2 + r$count <- vapply(betaBlocks, function(b) sum(S[i, ] & betaBlock %in% b), 0L) r }) parts <- Filter(Negate(is.null), parts) @@ -241,23 +331,207 @@ } lw <- vapply(parts, `[[`, 0, "logw") } - logI <- max(lw) + log(sum(exp(lw - max(lw)))) - for (i in seq_along(parts)) parts[[i]]$weight <- exp(parts[[i]]$logw - logI) - inclusion <- setNames(vapply(slab, function(e) { - if (!e %in% cand) return(probG[[e]]) - sum(vapply(parts, function(p) if (e %in% p$on) p$weight else 0, 0)) - }, 0), slab) - list(parts = parts, m2logI = -2 * logI, inclusion = inclusion, slab = slab, normal = nrm, etas = etas, - cand = cand, mu = mu, alpha = alpha) + # with a beta prior the groups of a block are summed jointly, by .spikeBetaSum() + if (length(betaBlocks)) return(c(list(parts = parts, probG = probG), group)) + .spikeWeights(parts, -2 * .logSumExp(lw), probG, group) }) + if (!length(betaBlocks)) return(out) + factorized <- names(Filter(function(e) !is.null(e$factor), out)) + if (length(factorized)) out <- .spikeBetaFactorized(out, lay, factorized) + if (approx != "exact" || !length(exact)) return(out) + .spikeBetaSum(out, lay, exact) +} + +## The weights of the subsets `parts` of a group from their log weight and -2 log I, `m2logI`; the inclusion per +## slab eta, the prior `probG` for an eta off the group data. +.spikeWeights <- function(parts, m2logI, probG, group) { + for (i in seq_along(parts)) parts[[i]]$weight <- exp(parts[[i]]$logw + m2logI / 2) + inclusion <- setNames(vapply(group$slab, function(e) { + if (!e %in% group$cand) return(probG[[e]]) + sum(vapply(parts, function(p) if (e %in% p$on) p$weight else 0, 0)) + }, 0), group$slab) + c(list(parts = parts, m2logI = m2logI, inclusion = inclusion, ref = group$cand[inclusion[group$cand] > 0.5]), + group) +} + +## The log of the sum of exp(`x`). +.logSumExp <- function(x) { + top <- max(x) + if (!is.finite(top)) return(top) + top + log(sum(exp(x - top))) +} + +## Log weights by count vector, named "n1,n2,..." over the beta blocks: the table of the log weights of the sum +## of the counts. +.convolveCounts <- function(t1, t2) { + out <- list() + for (k1 in names(t1)) for (k2 in names(t2)) { + k <- paste(.countsOf(k1) + .countsOf(k2), collapse = ",") + out[[k]] <- c(out[[k]], t1[[k1]] + t2[[k2]]) + } + vapply(out, .logSumExp, 0) +} + +.countsOf <- function(key) as.integer(strsplit(key, ",", fixed = TRUE)[[1]]) + +## The exact sum over the subsets of the groups `exact` in `est` (from .spikeEStep()) with `prob` under a beta +## prior integrated out: per beta block the weight B(a + n, b + K - n) / B(a, b) of the count n of slab etas over +## all groups, K the etas of the block that reach data. The groups of a block are summed jointly by convolving +## their sums by count; -2 log I of the joint sum is shared equally by the groups. +.spikeBetaSum <- function(est, lay, exact) { + blocks <- unique(lay$block[!is.na(lay$betaA)]) + a <- lay$betaA[match(blocks, lay$block)] + b <- lay$betaB[match(blocks, lay$block)] + # the slab etas of a group follow the order of the stems in `lay` + K <- vapply(blocks, function(bl) sum(vapply(est[exact], function(e) + sum(lay$block[match(e$cand, e$slab)] == bl), 0L)), 0L) + logW <- function(key) { + n <- .countsOf(key) + sum(lbeta(a + n, b + K - n) - lbeta(a, b)) + } + tables <- lapply(est[exact], function(e) { + keys <- vapply(e$parts, function(p) paste(p$count, collapse = ","), "") + vapply(split(vapply(e$parts, `[[`, 0, "logw"), keys), .logSumExp, 0) + }) + zero <- setNames(0, paste(integer(length(blocks)), collapse = ",")) + total <- Reduce(.convolveCounts, tables, zero) + logI <- .logSumExp(total + vapply(names(total), logW, 0)) + for (g in exact) { + others <- Reduce(.convolveCounts, tables[.setdiff(exact, g)], zero) + e <- est[[g]] + for (i in seq_along(e$parts)) { + own <- e$parts[[i]]$count + joint <- vapply(names(others), function(k) logW(paste(own + .countsOf(k), collapse = ",")), 0) + e$parts[[i]]$logw <- e$parts[[i]]$logw + .logSumExp(others + joint) + } + est[[g]] <- .spikeWeights(e$parts, -2 * logI, e$probG, e[c("slab", "normal", "etas", "cand", "mu", "alpha")]) + est[[g]]$m2logI <- -2 * logI / length(exact) + } + est +} + +## Mean field over the inclusion of the candidates `cand` of group `g`: log Z of a subset linear in the +## indicators around the reference subset `ref`, from the Laplace integrals of the reference and of every +## subset that differs from it in one candidate, so that the sum over subsets factorizes per candidate. The +## reference moves to the candidates of inclusion above 1/2 until it stays; a subset whose inner search fails +## has weight 0 and is counted in `failed`. +.spikeMeanField <- function(design, objs, g, theta, fixed, etas, cand, nrm, pr, prob, ref, startOf) { + seen <- new.env() + # the key of the empty subset is "s", not "", which an environment refuses + keyOf <- function(on) paste0("s", paste(sort(on), collapse = ",")) + laplaceOf <- function(on) { + on <- cand[cand %in% on] + key <- keyOf(on) + if (!is.null(seen[[key]])) return(seen[[key]]$r) + r <- tryCatch(.spikeSubset(design, objs, g, theta, fixed, etas, c(nrm, on), pr, startOf(c(nrm, on))), + error = function(e) NULL) + if (!is.null(r)) r$on <- c(nrm, on) + assign(key, list(r = r), envir = seen) + r + } + visited <- character(0) + repeat { + base <- laplaceOf(ref) + if (is.null(base)) stop("em: the inner search of group ", g, " at the reference subset failed.", call. = FALSE) + flips <- lapply(cand, function(j) laplaceOf(if (j %in% ref) .setdiff(ref, j) else c(ref, j))) + # log odds of the slab per candidate: the subsets with and without it, the others as in the reference + flip <- vapply(flips, function(r) if (is.null(r)) Inf else r$m2logZ, 0) + inRef <- cand %in% ref + m2On <- ifelse(inRef, base$m2logZ, flip) + m2Off <- ifelse(inRef, flip, base$m2logZ) + logOdds <- log(prob[cand]) - log1p(-prob[cand]) + (m2Off - m2On) / 2 + inclusion <- stats::plogis(logOdds) + visited <- c(visited, keyOf(ref)) + nxt <- cand[inclusion > 0.5] + if (setequal(nxt, ref) || keyOf(nxt) %in% visited || length(visited) > length(cand)) break + ref <- nxt + } + failed <- sum(vapply(as.list(seen), function(x) is.null(x$r), TRUE)) + # log I: prior and integral of the reference, times 1 + exp(flip log odds) per candidate + flipLogit <- ifelse(inRef, -logOdds, logOdds) + log1pExp <- ifelse(flipLogit > 0, flipLogit + log1p(exp(-flipLogit)), log1p(exp(flipLogit))) + logPriorRef <- sum(log(prob[cand[inRef]])) + sum(log1p(-prob[cand[!inRef]])) + logI <- logPriorRef - base$m2logZ / 2 + sum(log1pExp) + dev2 <- setNames(vapply(seq_along(cand), function(k) { + r <- if (inRef[k]) base else flips[[k]] + if (is.null(r)) return(0) + j <- match(cand[k], r$on) + (r$mode[[cand[k]]] - pr$mu[[cand[k]]])^2 + r$cov[j, j] + }, 0), cand) + q <- match(nrm, base$on) + normalMoment <- if (length(nrm)) tcrossprod(base$mode[nrm]) + base$cov[q, q, drop = FALSE] + base$weight <- 1 + inc <- prob + inc[cand] <- inclusion + # log Z of a subset differs from that of the reference by `delta` per candidate on the other side + delta <- ifelse(is.finite(flip), (base$m2logZ - flip) / 2, -Inf) + w1 <- setNames(ifelse(inRef, 0, delta), cand) + w0 <- setNames(ifelse(inRef, delta, 0), cand) + logZ <- .logSumExp2(log(prob[cand]) + w1, log1p(-prob[cand]) + w0) + factor <- list(base = -base$m2logZ / 2, w0 = w0, w1 = w1, logZ = logZ) + list(parts = list(base), m2logI = -2 * logI, inclusion = inc, ref = ref, failed = failed, factor = factor, + perCandidate = list(inclusion = setNames(inclusion, cand), dev2 = dev2, normalMoment = normalMoment)) +} + +## Mean field or EC over the groups `groups` of `est` with `prob` under a beta prior integrated out. Both factorize +## over the candidates: per group `factor` holds `base`, log I without the candidates, plus per candidate the log +## masses `w0` of the spike and `w1` of the slab and `logZ` of their mixture under the prior, so that log I is +## base + sum(logZ). The candidates under a beta prior take the weight of .spikeBetaSum() by convolving one +## count table per candidate in place of their mixtures; -2 log I is shared equally by the groups. +.spikeBetaFactorized <- function(est, lay, groups) { + blocks <- unique(lay$block[!is.na(lay$betaA)]) + a <- lay$betaA[match(blocks, lay$block)] + b <- lay$betaB[match(blocks, lay$block)] + units <- list(); base <- 0 + for (g in groups) { + e <- est[[g]] + f <- e$factor + block <- lay$block[match(e$cand, e$slab)] + beta <- !is.na(lay$betaA[match(e$cand, e$slab)]) + base <- base + f$base + sum(f$logZ[e$cand][!beta]) + for (k in which(beta)) { + unit <- as.integer(blocks == block[k]) + eta <- e$cand[k] + units[[length(units) + 1L]] <- list(g = g, eta = eta, unit = unit, w1 = f$w1[[eta]], + table = setNames(c(f$w0[[eta]], f$w1[[eta]]), c(paste(0L * unit, collapse = ","), paste(unit, collapse = ",")))) + } + } + K <- vapply(blocks, function(bl) sum(vapply(units, function(u) u$unit[blocks == bl], 0L)), 0L) + logW <- function(keys) vapply(keys, function(key) { + n <- .countsOf(key) + sum(lbeta(a + n, b + K - n) - lbeta(a, b)) + }, 0) + zero <- setNames(0, paste(integer(length(blocks)), collapse = ",")) + tables <- lapply(units, `[[`, "table") + total <- Reduce(.convolveCounts, tables, zero) + logBeta <- .logSumExp(total + logW(names(total))) + for (i in seq_along(units)) { + u <- units[[i]] + rest <- Reduce(.convolveCounts, tables[-i], zero) + on <- vapply(names(rest), function(k) paste(.countsOf(k) + u$unit, collapse = ","), "") + incl <- exp(u$w1 + .logSumExp(rest + logW(on)) - logBeta) + est[[u$g]]$inclusion[[u$eta]] <- incl + est[[u$g]]$perCandidate$inclusion[[u$eta]] <- incl + } + for (g in groups) { + est[[g]]$m2logI <- -2 * (base + logBeta) / length(groups) + est[[g]]$ref <- est[[g]]$cand[est[[g]]$inclusion[est[[g]]$cand] > 0.5] + } + est +} + +## Elementwise log(exp(x) + exp(y)). +.logSumExp2 <- function(x, y) { + top <- pmax(x, y) + ifelse(is.finite(top), top + log(exp(x - top) + exp(y - top)), top) } ## E[eta eta'] of the normal etas of every group under the Laplace posteriors of the subsets with their -## weights; EC groups by the EC Gaussian. +## weights; EC and mean-field groups from their per-candidate moments. .spikeNormalMoments <- function(est) { lapply(est, function(e) { q <- e$normal - if (!is.null(e$ec)) return(e$ec$normalMoment) + if (!is.null(e$perCandidate)) return(e$perCandidate$normalMoment) Reduce(`+`, lapply(e$parts, function(p) { j <- match(q, p$on) p$weight * (tcrossprod(p$mode[q]) + p$cov[j, j, drop = FALSE]) @@ -272,25 +546,46 @@ list(Oinv = chol2inv(t(L)), logdetO = 2 * sum(log(diag(L)))) } -## The M-step of the hyperparameters: prob as the mean inclusion, tau^2 as the mean of -## (eta - mean)^2 under the slab, per block; fixed values stay. -.spikeHyperStep <- function(lay, est, hyp, hypers) { +## Under a beta prior on `prob` of block `b`, the shapes of Beta(a + n, b + K - n), n the expected number of slab +## etas among the K etas of the block that reach data; NULL without a beta prior. +.spikeProbPosterior <- function(lay, est, b) { + rows <- lay$block == b + if (is.na(lay$betaA[rows][1])) return(NULL) + n <- K <- 0 + for (e in est) { + on <- .intersect(e$slab[rows], e$cand) + n <- n + sum(e$inclusion[on]) + K <- K + length(on) + } + c(a = lay$betaA[rows][1] + n, b = lay$betaB[rows][1] + K - n) +} + +## The M-step of the hyperparameters: prob as the mean inclusion, under a beta prior the predictive +## probability of the slab (a + n_-k) / (a + b + K - 1) that EC and the burn-in take, tau^2 as the mean of +## (eta - mean)^2 under the slab, under a scale prior the posterior mode of .spikeTauMode(), per block; +## `tauPriors` by block; fixed values stay. +.spikeHyperStep <- function(lay, est, hyp, hypers, tauPriors = list()) { stems <- lay$stem for (b in unique(lay$block)) { st <- lay$stem[lay$block == b] k <- match(st, stems) incl <- unlist(lapply(est, function(e) e$inclusion[k])) if (lay$probName[lay$block == b][1] %in% hypers) hyp$prob[st] <- min(max(mean(incl), 1e-6), 1 - 1e-6) + # under a beta prior, the predictive probability of the slab given the expected count of the others + post <- .spikeProbPosterior(lay, est, b) + if (!is.null(post)) + hyp$prob[st] <- (post[["a"]] - mean(incl, na.rm = TRUE)) / (sum(post) - 1) if (!lay$tauName[lay$block == b][1] %in% hypers) next num <- den <- 0 for (e in est) { own <- e$slab[k] - if (!is.null(e$ec)) { - on <- .intersect(names(e$ec$inclusion), own) - num <- num + sum(e$ec$inclusion[on] * e$ec$dev2[on]) - den <- den + sum(e$ec$inclusion[on]) + pc <- e$perCandidate + if (!is.null(pc)) { + on <- .intersect(names(pc$inclusion), own) + num <- num + sum(pc$inclusion[on] * pc$dev2[on]) + den <- den + sum(pc$inclusion[on]) } - for (p in if (is.null(e$ec)) e$parts) { + for (p in if (is.null(pc)) e$parts) { on <- .intersect(p$on, own) if (!length(on)) next j <- match(on, p$on) @@ -302,11 +597,50 @@ num <- num + sum(hyp$prob[st[match(blind, own)]] * hyp$tau[st[match(blind, own)]]^2) den <- den + sum(hyp$prob[st[match(blind, own)]]) } - if (den > 0) hyp$tau[st] <- sqrt(num / den) + if (den > 0) hyp$tau[st] <- .spikeTauMode(num, den, tauPriors[[b]], hyp$tau[st[1]]) } hyp } +## The tau that minimizes den log tau^2 + num / tau^2 - 2 log p(tau): without a prior sqrt(num / den); under an +## inverse-gamma prior on tau^2 in closed form; under a half-Cauchy or half-normal prior on tau by Newton steps +## in log tau, from `tau0`, where the objective is convex. +.spikeTauMode <- function(num, den, prior = NULL, tau0 = 1) { + if (is.null(prior)) return(sqrt(num / den)) + if (prior$dist == "invGamma") return(sqrt((num + 2 * prior$rate) / (den + 2 * prior$shape + 2))) + if (num <= 0) return(tau0) + u <- log(unname(tau0)) + for (i in seq_len(100L)) { + pen <- .spikeTauPenalty(exp(u), prior, derivs = TRUE) + d1 <- 2 * den - 2 * num * exp(-2 * u) + pen[["d1"]] + d2 <- 4 * num * exp(-2 * u) + pen[["d2"]] + step <- max(min(-d1 / d2, 1), -1) + u <- u + step + if (abs(step) < 1e-12) break + } + exp(u) +} + +## -2 log p(tau) of a scale prior, the density in tau for half-Cauchy and half-normal and in tau^2 for the +## inverse gamma; with `derivs` also the first and second derivative in log tau. +.spikeTauPenalty <- function(tau, prior, derivs = FALSE) { + if (is.null(prior)) return(if (derivs) c(value = 0, d1 = 0, d2 = 0) else 0) + v <- unname(tau)^2 + out <- switch(prior$dist, + halfCauchy = { + r <- v / prior$scale^2 + c(value = -2 * log(2 / (pi * prior$scale)) + 2 * log1p(r), d1 = 4 * r / (1 + r), d2 = 8 * r / (1 + r)^2) + }, + halfNormal = { + r <- v / prior$scale^2 + c(value = -2 * log(2 / (prior$scale * sqrt(2 * pi))) + r, d1 = 2 * r, d2 = 4 * r) + }, + invGamma = c(value = -2 * (prior$shape * log(prior$rate) - lgamma(prior$shape)) + 2 * (prior$shape + 1) * log(v) + + 2 * prior$rate / v, + d1 = 4 * (prior$shape + 1) - 4 * prior$rate / v, d2 = 8 * prior$rate / v)) + if (derivs) out else out[["value"]] +} + ## The M-step of the parameters: the weighted subset objectives (data plus prior) minimized jointly in `theta` ## and one copy of the subset etas per subset, every copy then the inner mode at the new `theta`; the log ## determinant of the Laplace integrals enters the weights only. @@ -319,8 +653,11 @@ if (p$weight < 1e-8) next k <- length(items) + 1L copies <- if (length(p$on)) paste0(".s", k, ".", p$on) else character(0) + # a part of a node of the integral over tau has the slab width of the node + prPart <- pr + if (!is.null(p$tau)) prPart$tau[match(names(p$tau), lay$stem)] <- p$tau items[[k]] <- list(g = g, on = p$on, copies = copies, w = p$weight, mode = p$mode, - off = e$alpha[.setdiff(e$etas, p$on)], pr = pr) + off = e$alpha[.setdiff(e$etas, p$on)], pr = prPart) } } init <- unlist(lapply(items, function(it) setNames(it$mode, it$copies))) @@ -364,7 +701,15 @@ ## -2 log L on the frozen nodes of every subset (a subset without a grid by the Laplace node at the mode) in ## the fixed effects, Cholesky parameters, log tau and logit prob, gradient by Fisher's and Hessian by Louis' ## identity; mu-referenced normal etas frozen in phi. `back` maps the argument to the parameters. -.spikeFrozen <- function(design, est, lay, theta, omegaPars, hyp, hypers, fixed, extra) { +.spikeFrozen <- function(design, est, lay, theta, omegaPars, hyp, hypers, fixed, extra, tauPriors = list()) { + # a beta prior on prob weights the count of slab etas of a block, here within one group + betaBlocks <- unique(lay$block[!is.na(lay$betaA)]) + for (bl in betaBlocks) { + holders <- Filter(function(e) any(lay$block[match(e$cand, e$slab)] == bl), est) + if (length(holders) > 1L) + stop("em: method = \"quadrature\" takes betaPrior() for spike-and-slab random effects that reach the data ", + "of one group.", call. = FALSE) + } nl <- design$normal groups <- lapply(names(est), function(g) { e <- est[[g]] @@ -446,14 +791,20 @@ } inCand <- e$slab %in% e$cand prob <- h$prob[lay$stem] + betaC <- inCand & !is.na(lay$betaA) + prodC <- inCand & is.na(lay$betaA) + K <- vapply(betaBlocks, function(bl) sum(betaC & lay$block == bl), 0L) + a <- lay$betaA[match(betaBlocks, lay$block)] + bb <- lay$betaB[match(betaBlocks, lay$block)] for (b in seq_len(B)) { on <- .intersect(G$subset[[b]], e$slab) st <- lay$stem[match(on, e$slab)] tau <- h$tau[st] dev2 <- ((G$eta[b, on] - e$mu[on]) / tau)^2 z <- e$slab %in% G$subset[[b]] + count <- vapply(betaBlocks, function(bl) sum(z & betaC & lay$block == bl), 0L) logInt[b] <- logInt[b] + sum(-0.5 * log(2 * pi) - log(tau) - dev2 / 2) + - sum(ifelse(z, log(prob), log1p(-prob))[inCand]) + sum(ifelse(z, log(prob), log1p(-prob))[prodC]) + sum(lbeta(a + count, bb + K - count) - lbeta(a, bb)) if (!deriv) next for (n in .intersect(tauFree, act)) { k <- lay$tauName[match(st, lay$stem)] == n @@ -472,6 +823,14 @@ total <- total - 2 * ns$logL if (deriv) { gr <- gr + ns$gradient[act]; H <- H + ns$hessian[act, act] } } + # -2 log p(tau) of the scale priors on the log tau coordinates + for (n in tauFree) { + prior <- tauPriors[[lay$block[match(n, lay$tauName)]]] + if (is.null(prior)) next + pen <- .spikeTauPenalty(h$tau[[lay$stem[match(n, lay$tauName)]]], prior, derivs = TRUE) + total <- total + pen[["value"]] + if (deriv && n %in% act) { gr[n] <- gr[n] + pen[["d1"]]; H[n, n] <- H[n, n] + pen[["d2"]] } + } out <- objlist(value = total, gradient = gr, hessian = H) if (!is.null(extra) && length(thA)) { ex <- extra(pars[thA], fixed = fixed, deriv = deriv) @@ -488,8 +847,8 @@ } ## Fit of a design whose random effects are spike-and-slab ones, beside normal ones, by the sum over -## subsets: EM on the Laplace integrals, then with `quadrature` (control$quadrature) trust steps on -## frozen quadrature nodes. +## subsets: EM on the Laplace integrals in the phases of control$sparseFit, each from the estimates and inner +## modes of the one before, then with `quadrature` (control$quadrature) trust steps on frozen quadrature nodes. .fitSpikeSubsets <- function(design, start, fixed, control = list(), verbose = FALSE, quadrature = NULL) { .requireM3(design, NULL, "FOCEI") if (any(vapply(design$blocks, function(b) b$dist == "dirichletProcess", TRUE))) @@ -506,54 +865,180 @@ st$theta <- start[.setdiff(names(start), c(hypers, cholPars))] st$omegaPars <- start[.intersect(cholPars, names(start))] st$hyp <- list(prob = value("prob", "probName"), tau = value("tau", "tauName")) - st$warm <- list(); st$gridWarm <- list(); st$rows <- list() - budget <- control$sparseFit$budget %||% .spikeBudget + beta <- !is.na(lay$betaA) + st$hyp$prob[beta] <- lay$betaA[beta] / (lay$betaA[beta] + lay$betaB[beta]) + # the scale priors of the blocks whose tau is estimated, and -2 log p(tau) of them at the current tau + tauPriors <- lapply(design$blocks, function(b) if (isTRUE(b$hyper["tau"] %in% hypers)) b$tauPrior) + # a block whose tau the phase "exact" integrates over log tau, on a Gauss-Hermite grid of mean and sd in log tau + integrated <- Filter(function(b) isTRUE(tauPriors[[b]]$integrate), unique(lay$block)) + if (length(integrated) > 1L) + stop("em: `integrate = TRUE` applies to the tau of one spike-and-slab block.", call. = FALSE) + if (length(integrated) && !is.null(quadrature)) + stop("em: method = \"quadrature\" takes the posterior mode of tau; drop `integrate = TRUE`.", call. = FALSE) + intStems <- lay$stem[lay$block %in% integrated] + st$tauGrid <- if (length(integrated)) c(mean = log(st$hyp$tau[[intStems[1]]]), sd = 0.5) + st$integratedNow <- FALSE + # -2 log p(tau) of the scale priors, but of the tau the current E-step integrated + penaltyOf <- function() sum(vapply(unique(lay$block), function(b) + if (st$integratedNow && b %in% integrated) 0 + else .spikeTauPenalty(st$hyp$tau[lay$stem[lay$block == b][1]], tauPriors[[b]]), 0)) + st$warm <- list(); st$gridWarm <- list(); st$rows <- list(); st$ref <- list() + sf <- control$sparseFit + termBudget <- sf$termBudget %||% .spikeBudget + phases <- .spikePhases(sf) bases <- .spikeBases(design) + burn <- .spikeBurninOf(sf) + burnSet <- if (!is.null(burn)) .spikeBurninSet(burn$start, design, lay, st$hyp$prob) + if (!is.null(burnSet)) + st$ref <- lapply(setNames(nm = design$groups), + function(g) .intersect(unname(design$etaNames[g, lay$stem]), burnSet)) omegaOf <- function() .spikeOmega(design, c(st$omegaPars, fixed)) keyOf <- function(e) vapply(e$parts, function(p) paste(p$on, collapse = ","), "") - eStep <- function(qc) { - est <- .spikeEStep(design, objs, lay, st$theta, fixed, st$hyp, st$warm, bases, budget, control$sparseFit$ec, qc, - st$gridWarm, omegaOf()) - st$warm <- lapply(est, function(e) setNames(lapply(e$parts, `[[`, "mode"), keyOf(e))) + extraOf <- function() (if (is.null(extra)) 0 else extra(st$theta, fixed = fixed, deriv = FALSE)$value) + penaltyOf() + eStep <- function(qc, approx) { + if (approx == "exact" && length(integrated)) return(eStepTau(qc)) + eStepAt(qc, approx, st$hyp) + } + eStepAt <- function(qc, approx, hyp) { + st$integratedNow <- FALSE + est <- .spikeEStep(design, objs, lay, st$theta, fixed, hyp, st$warm, bases, termBudget, sf$ec, qc, + st$gridWarm, omegaOf(), approx, st$ref) + # the inner modes of every subset met so far start the inner searches of later steps and phases + for (g in names(est)) for (p in est[[g]]$parts) + if (length(p$on)) st$warm[[g]][[paste(p$on, collapse = ",")]] <- p$mode st$gridWarm <- lapply(est, function(e) setNames(lapply(e$parts, `[[`, "indices"), keyOf(e))) + st$ref <- lapply(est, `[[`, "ref") est } - record <- function(stage, k, value, delta) { - st$rows[[length(st$rows) + 1L]] <- data.frame(stage = stage, ecmIter = k, OFV = value, delta = delta) + # the exact sum integrated over log tau by 7 Gauss-Hermite nodes on st$tauGrid: the parts of every node weighted + # by the posterior of the node, which moves the grid to the posterior mean and sd of log tau + eStepTau <- function(qc) { + gh <- .gaussHermite(7L) + prior <- tauPriors[[integrated]] + u <- st$tauGrid[["mean"]] + sqrt(2) * st$tauGrid[["sd"]] * gh$x + nodes <- lapply(u, function(ui) { + h <- st$hyp + h$tau[intStems] <- exp(ui) + eStepAt(qc, "exact", h) + }) + m2 <- vapply(nodes, function(est) sum(vapply(est, `[[`, 0, "m2logI")), 0) + # the prior density in log tau: of tau, or of tau^2 for the inverse gamma + logJacobian <- if (prior$dist == "invGamma") log(2) + 2 * u else u + lw <- -(m2 + vapply(exp(u), .spikeTauPenalty, 0, prior = prior)) / 2 + logJacobian + log(gh$w) + gh$x^2 + logI <- .logSumExp(lw) + log(sqrt(2) * st$tauGrid[["sd"]]) + w <- exp(lw - .logSumExp(lw)) + mean <- sum(w * u) + st$tauGrid <- c(mean = mean, sd = max(sqrt(sum(w * (u - mean)^2)), 1e-3)) + st$hyp$tau[intStems] <- exp(mean) + merged <- lapply(setNames(nm = names(nodes[[1]])), function(g) { + e <- nodes[[1]][[g]] + e$parts <- unlist(Map(function(est, wi, ui) lapply(est[[g]]$parts, function(p) { + p$weight <- p$weight * wi + p$tau <- setNames(rep(exp(ui), length(intStems)), intStems) + p + }), nodes, w, u), recursive = FALSE) + e$inclusion <- Reduce(`+`, Map(function(est, wi) wi * est[[g]]$inclusion, nodes, w)) + e$m2logI <- -2 * logI / length(nodes[[1]]) + e$ref <- e$cand[e$inclusion[e$cand] > 0.5] + e + }) + st$ref <- lapply(merged, `[[`, "ref") + st$integratedNow <- TRUE + merged + } + record <- function(stage, phase, k, value, delta) { + st$rows[[length(st$rows) + 1L]] <- data.frame(stage = stage, phase = phase, ecmIter = k, OFV = value, + delta = delta) if (verbose) message(sprintf("em(spike subsets) %s %d: -2 log L %.6f, change %.2e", stage, k, value, delta)) } - # Laplace stage: EM until no estimate changes by more than epsEcm + # the phase "exact" beyond termBudget ends the fit at EC, without EC it stops + approxes <- vapply(phases, `[[`, "", "approx") + nSubsets <- sum(2^rowSums(.reachOf(design)[design$groups, lay$stem, drop = FALSE])) + skipExact <- nSubsets > termBudget + if (skipExact && "exact" %in% approxes && !"ec" %in% approxes) + stop("em: the exact sum runs over ", format(nSubsets), " subsets, more than `termBudget` (", format(termBudget), + "); add \"ec\" to `control$sparseFit$phases` or raise `termBudget`.", call. = FALSE) + phaseRows <- list() + several <- length(phases) + as.integer(!is.null(burn)) > 1L + # burn-in: one trust region over the fixed effects and the slab etas of the start subset at the joint mode, + # the others at the spike, prob, tau and Omega held + if (!is.null(burn)) { + t0 <- proc.time()[["elapsed"]] + m <- tryCatch({ + est <- eStep(NULL, "burnin") + m <- list(value = sum(vapply(est, `[[`, 0, "m2logI")) + extraOf(), iterations = 0L, converged = TRUE) + if (length(st$theta)) { + ms <- .spikeM(design, objs, est, extra, lay, st$hyp, omegaOf()) + m <- .innerTrust(list(objfun = ms$objfun, parinit = c(st$theta, ms$init), fixed = fixed, rinit = 1, + rmax = 10, iterlim = burn$iterlim)) + st$theta <- m$argument[names(st$theta)] + # .spikeM() names the copy of the etas of item k `.s.`; the burn-in has one item per group + for (k in seq_along(est)) { + on <- est[[k]]$parts[[1]]$on + if (length(on)) + st$warm[[names(est)[k]]][[paste(on, collapse = ",")]] <- setNames(m$argument[paste0(".s", k, ".", on)], on) + } + } + m + }, error = function(e) stop(.spikePhaseError(e, 1L, "burnin", several))) + record("burnin", 1L, m$iterations, m$value, NA_real_) + phaseRows[[1L]] <- data.frame(phase = 1L, approx = "burnin", iterations = as.integer(m$iterations), + value = m$value, converged = isTRUE(m$converged), + seconds = proc.time()[["elapsed"]] - t0, failed = 0L) + } + + # Laplace stage: per phase ECM until no estimate changes by more than epsECM conv <- FALSE - for (k in seq_len(control$sparseFit$maxEcm %||% 200L)) { - est <- eStep(NULL) - before <- c(st$theta, unlist(st$hyp), st$omegaPars) - st$hyp <- .spikeHyperStep(lay, est, st$hyp, hypers) - if (length(st$omegaPars)) - st$omegaPars[] <- .updateNormal(design, .spikeNormalMoments(est), fixed)[names(st$omegaPars)] - if (length(st$theta)) { - ms <- .spikeM(design, objs, est, extra, lay, st$hyp, omegaOf()) - m <- .innerTrust(list(objfun = ms$objfun, parinit = c(st$theta, ms$init), fixed = fixed, rinit = 1, rmax = 10, - iterlim = 100L)) - st$theta <- m$argument[names(st$theta)] + for (j in seq_along(phases)) { + ph <- phases[[j]] + i <- j + as.integer(!is.null(burn)) + if (ph$approx == "exact" && skipExact) { + phaseRows[[i]] <- data.frame(phase = i, approx = "exact", iterations = 0L, value = NA_real_, converged = NA, + seconds = 0, failed = 0L) + next } - delta <- max(abs(c(st$theta, unlist(st$hyp), st$omegaPars) - before)) - record("laplace", k, sum(vapply(est, `[[`, 0, "m2logI")), delta) - conv <- delta < (control$sparseFit$epsEcm %||% 1e-6) - if (conv) break + t0 <- proc.time()[["elapsed"]] + conv <- FALSE + k <- 0L + last <- NA_real_ + failed <- 0L + tryCatch(for (k in seq_len(ph$maxECM)) { + est <- eStep(NULL, ph$approx) + failed <- failed + sum(vapply(est, function(e) e$failed %||% 0L, 0L)) + before <- c(st$theta, unlist(st$hyp), st$omegaPars) + held <- if (st$integratedNow) lay$tauName[match(integrated, lay$block)] + st$hyp <- .spikeHyperStep(lay, est, st$hyp, .setdiff(hypers, held), tauPriors) + if (length(st$omegaPars)) + st$omegaPars[] <- .updateNormal(design, .spikeNormalMoments(est), fixed)[names(st$omegaPars)] + if (length(st$theta)) { + ms <- .spikeM(design, objs, est, extra, lay, st$hyp, omegaOf()) + m <- .innerTrust(list(objfun = ms$objfun, parinit = c(st$theta, ms$init), fixed = fixed, rinit = 1, + rmax = 10, iterlim = 100L)) + st$theta <- m$argument[names(st$theta)] + } + delta <- max(abs(c(st$theta, unlist(st$hyp), st$omegaPars) - before)) + last <- sum(vapply(est, `[[`, 0, "m2logI")) + record("laplace", i, k, last, delta) + conv <- delta < ph$epsECM + if (conv) break + }, error = function(e) stop(.spikePhaseError(e, i, ph$approx, several))) + phaseRows[[i]] <- data.frame(phase = i, approx = ph$approx, iterations = k, value = last + extraOf(), + converged = conv, seconds = proc.time()[["elapsed"]] - t0, failed = failed) } stopReason <- if (conv) "converged" else "iterlim" + final <- utils::tail(.setdiff(approxes, if (skipExact) "exact"), 1L) # quadrature stage: a trust step over every parameter on the frozen nodes, until a Newton step on the # rebuilt nodes gains less than tolDecrement if (!is.null(quadrature)) { conv <- FALSE; stopReason <- "iterlim" - for (k in seq_len(quadrature$maxEcmPerStage %||% 10L)) { - est <- eStep(quadrature) - fr <- .spikeFrozen(design, est, lay, st$theta, st$omegaPars, st$hyp, hypers, fixed, extra) + for (k in seq_len(quadrature$maxECMPerStage %||% 10L)) { + est <- eStep(quadrature, final) + fr <- .spikeFrozen(design, est, lay, st$theta, st$omegaPars, st$hyp, hypers, fixed, extra, tauPriors) ev <- fr$objfun(fr$init) dec <- .newtonDecrement(ev) - record("quadrature", k, ev$value, dec) + record("quadrature", length(phaseRows), k, ev$value, dec) if (dec < (quadrature$tolDecrement %||% 1e-4)) { conv <- TRUE; stopReason <- "decrement"; break } tc <- modifyList(list(rinit = 1, rmax = 10), quadrature$cm1Control %||% list()) m <- .innerTrust(modifyList(tc, list(objfun = fr$objfun, parinit = fr$init, @@ -563,9 +1048,9 @@ } } - est <- eStep(quadrature) + est <- eStep(quadrature, final) theta <- st$theta; hyp <- st$hyp - total <- sum(vapply(est, `[[`, 0, "m2logI")) + total <- sum(vapply(est, `[[`, 0, "m2logI")) + penaltyOf() if (!is.null(extra)) total <- total + extra(theta, fixed = fixed, deriv = FALSE)$value E <- design$etaNames modes <- clusters <- spike <- matrix(NA_real_, nrow(E), ncol(E), dimnames = dimnames(E)) @@ -591,5 +1076,11 @@ list(argument = c(theta, st$omegaPars, hyperValues[hypers]), value = total, gradient = NULL, hessian = NULL, information = NULL, etaModes = modes, etaCov = setNames(cov, design$groups), clusters = clusters, spike = spike, converged = conv, iterations = length(st$rows), stopReason = stopReason, - stageTrace = do.call(rbind, st$rows)) + stageTrace = do.call(rbind, st$rows), phases = do.call(rbind, phaseRows), burnin = burnSet, + hyperprior = if (any(!vapply(tauPriors, is.null, TRUE))) penaltyOf(), + tauPosterior = if (st$integratedNow) + setNames(list(c(logMean = st$tauGrid[["mean"]], logSd = st$tauGrid[["sd"]])), + lay$tauName[match(integrated, lay$block)]), + probPosterior = Filter(Negate(is.null), setNames(lapply(unique(lay$block), function(b) + .spikeProbPosterior(lay, est, b)), lay$probName[match(unique(lay$block), lay$block)]))) } diff --git a/R/objClass.R b/R/objClass.R index 09572244..98a67e4a 100644 --- a/R/objClass.R +++ b/R/objClass.R @@ -587,16 +587,19 @@ normT <- function(data, x, errmodel = NULL, df, times = NULL, attrName = "data", # Evaluate single-condition objectives, one parameter vector each and `fixed` for all, with the # predictions in one batched request. Falls back to the reference loop on a -# missing handle, mixed prdfns, a condition owned twice, or a failing batch. +# missing handle, mixed prdfns, a condition owned twice, or a failing batch; `hessian` other than NULL +# (as "expected") goes to every objective in the reference loop. .objEvalMany <- function(objList, parsList, deriv = TRUE, deriv2 = FALSE, - cores = getOption("dMod2.cores", 1L), fixed = NULL) { + cores = getOption("dMod2.cores", 1L), fixed = NULL, hessian = NULL) { n <- length(parsList) objs <- if (is.function(objList)) rep(list(objList), n) else objList stopifnot(length(objs) == n) - serial <- function() lapply(seq_len(n), function(j) - objs[[j]](parsList[[j]], fixed = fixed, deriv = deriv, deriv2 = deriv2, cores = cores)) - if (n < 2L) return(serial()) + serial <- function() lapply(seq_len(n), function(j) { + if (is.null(hessian)) return(objs[[j]](parsList[[j]], fixed = fixed, deriv = deriv, deriv2 = deriv2, cores = cores)) + objs[[j]](parsList[[j]], fixed = fixed, deriv = deriv, deriv2 = deriv2, cores = cores, hessian = hessian) + }) + if (n < 2L || !is.null(hessian)) return(serial()) prd <- attr(objs[[1L]], "prdfn", exact = TRUE) conds <- vapply(objs, function(o) { diff --git a/R/parameters.R b/R/parameters.R index fc58d3f5..dca40f5e 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -1089,7 +1089,9 @@ Pimpl <- function(trafo, parameters = NULL, forcings = NULL, condition = NULL, #' @param trafo Named character or [eqnvec], or a list of those named by #' condition as `branch()` returns it. `NULL` starts a new one. #' @param expr `"lhs <- rhs"` string. The symbols in it are replaced by the -#' arguments in `...` of the same name; see [repar()]. For `insert()` on a +#' arguments in `...` of the same name; inside a name, `_` separates symbols, +#' so `"Delta_x"` with `x = "a"` becomes `"Delta_a"`. A `"lhs ~ rhs"` string +#' is an error: `~` is reserved for model formulas. For `insert()` on a #' branched transformation also one or several effect formulas, e.g. #' `cl ~ wt + (1 | ID)`, which replace the symbol by a linear predictor #' over the columns of the branch table with fixed and random effects; see @@ -1119,17 +1121,18 @@ Pimpl <- function(trafo, parameters = NULL, forcings = NULL, condition = NULL, #' #' @return Same shape as `trafo`, or a list named by condition for #' `branch()`. -#' @seealso [repar()], [P()] +#' @seealso [P()] #' @export #' @example inst/examples/define.R define <- function(trafo, expr, ..., conditionMatch = NULL) { if (missing(trafo)) trafo <- NULL + .trafoFirst(trafo, expr) dots <- substitute(alist(...)) callerEnv <- parent.frame() re <- attr(trafo, "randomEffects", exact = TRUE) .reparBranches(trafo, dots, callerEnv, conditionMatch, function(tr, args) { .guardEffectSymbols(.substitutionSides(expr, args)$lhs, re) - do.call(repar, c(list(expr = expr, trafo = tr, reset = TRUE), args)) + do.call(.repar, c(list(expr = expr, trafo = tr, reset = TRUE), args)) }) } @@ -1138,6 +1141,7 @@ define <- function(trafo, expr, ..., conditionMatch = NULL) { #' @rdname define insert <- function(trafo, expr, ..., conditionMatch = NULL) { if (missing(trafo)) trafo <- NULL + .trafoFirst(trafo, expr) dots <- substitute(alist(...)) callerEnv <- parent.frame() # effect formulas, one or several; named dots are their placeholders @@ -1156,7 +1160,7 @@ insert <- function(trafo, expr, ..., conditionMatch = NULL) { gates <- vapply(args, is.logical, logical(1)) if (!all(unlist(args[gates]))) return(tr) .guardEffectSymbols(.substitutionSides(expr, args[!gates])$lhs, re) - do.call(repar, c(list(expr = expr, trafo = tr), args[!gates])) + do.call(.repar, c(list(expr = expr, trafo = tr), args[!gates])) }) } @@ -1246,38 +1250,10 @@ branch <- function(trafo, table = NULL, gsub(.numprefix, "", gsub(":", "_", x, fixed = TRUE), fixed = TRUE) -#' Reparameterization -#' -#' @description Replaces the left-hand side of `"lhs <- rhs"` by the -#' right-hand side in `trafo`, after the symbols of `expr` are replaced by the -#' arguments in `...`. [define()] and [insert()] build on it. -#' -#' @param trafo Named character, [eqnvec] or a list of those. Default `NULL` -#' starts from the identity of the left-hand sides, so the result maps each -#' left-hand side to the matching right-hand side. -#' @param expr `"lhs <- rhs"` string. Inside a name, `_` separates symbols, -#' so `"Delta_x"` with `x = "a"` becomes `"Delta_a"`. A `"lhs ~ rhs"` -#' string or a formula is an error: `~` is reserved for model formulas. -#' @param ... Named character or numeric vectors of equal length, replacing -#' the symbols of `expr` of the same name; element `i` of each gives the -#' `i`-th substitution. -#' @param reset `FALSE` (default) replaces the left-hand side wherever it -#' occurs in the expressions, `TRUE` sets the entry it names. -#' @return Same shape as `trafo`. -#' @seealso [define()], [insert()] -#' @export -#' @examples -#' innerpars <- letters[1:3] -#' constraints <- c(a = "b + c") -#' mycondition <- "cond1" -#' trafo <- repar(NULL, "x <- x", x = innerpars) -#' trafo <- repar(trafo, "x <- y", x = names(constraints), y = constraints) -#' trafo <- repar(trafo, "x <- exp(x)", x = innerpars) -#' trafo <- repar(trafo, "x <- x + Delta_x_condition", -#' x = innerpars, condition = mycondition) -repar <- function(trafo = NULL, expr, ..., reset = FALSE) { - if (.isReparExpr(trafo) && (missing(expr) || !.isReparExpr(expr))) - stop("repar: the order is repar(trafo, expr).", call. = FALSE) +# The left-hand side of `expr` replaced by the right-hand side in `trafo`, after +# the symbols of `expr` are replaced by the vectors in `...`; with `reset` the entry +# named by the left-hand side is set instead. The core of define() and insert(). +.repar <- function(trafo = NULL, expr, ..., reset = FALSE) { sides <- .substitutionSides(expr, list(...)) lhs <- sides$lhs; rhs <- sides$rhs @@ -1288,6 +1264,12 @@ repar <- function(trafo = NULL, expr, ..., reset = FALSE) { else { trafo[lhs] <- rhs; trafo } } +# Stops where a substitution is passed in place of the transformation. +.trafoFirst <- function(trafo, expr) { + if (.isReparExpr(trafo) && (missing(expr) || !.isReparExpr(expr))) + stop("define() and insert(): the order is (trafo, expr).", call. = FALSE) +} + # A substitution string, or a formula or `~` string given in place of one, as # opposed to a transformation. .isReparExpr <- function(x) diff --git a/R/randomEffects.R b/R/randomEffects.R index 8decba2b..8eca0487 100644 --- a/R/randomEffects.R +++ b/R/randomEffects.R @@ -72,10 +72,12 @@ print.randomeffects <- function(x, ...) { paste(unique(tm$group), collapse = ", "))) for (b in seq_along(x$blocks)) { r <- tm[x$blocks[[b]], , drop = FALSE] - given <- function(v) if (is.na(v)) "estimated" else format(v) + given <- function(v, prior = NULL) if (!is.null(prior)) .describeHyperprior(prior) + else if (is.na(v)) "estimated" else format(v) dist <- switch(r$dist[1], normal = "normal", - spikeSlab = sprintf("spikeSlab, prob %s, tau %s, mean %s, spike %s", given(r$prob[1]), - given(r$tau[1]), format(r$mean[1]), format(r$spike[1])), + spikeSlab = sprintf("spikeSlab, prob %s, tau %s, mean %s, spike %s", + given(r$prob[1], r$probPrior[[1]]), given(r$tau[1], r$tauPrior[[1]]), + format(r$mean[1]), format(r$spike[1])), dirichletProcess = sprintf("dirichletProcess, concentration %s, tau %s", given(r$concentration[1]), given(r$tau[1]))) cat(sprintf(" block %d (%s, %s): %s\n", b, dist, r$group[1], paste(r$stem, collapse = ", "))) @@ -114,10 +116,12 @@ print.randomeffects <- function(x, ...) { #' [em()] estimates `prob`, `concentration` and `tau` unless given. #' #' @param prob Probability that a group deviates, in (0, 1); `NULL` -#' (default) estimates it. +#' (default) estimates it; [betaPrior()] integrates it out. #' @param concentration Concentration of the Ewens prior, positive; `NULL` #' (default) estimates it. -#' @param tau Standard deviation of the slab; `NULL` (default) estimates it. +#' @param tau Standard deviation of the slab; `NULL` (default) estimates it; +#' a scale prior such as [halfCauchyPrior()] estimates it as the posterior +#' mode (spike-and-slab only). #' @param mean Mean of the slab, one finite number, not estimated. #' @param spike Value of the spike, one finite number or `-Inf`, not #' estimated. `-Inf` needs the random effect as a summand in the exponent @@ -131,14 +135,24 @@ normal <- function() .redist("normal") #' @export #' @rdname normal spikeSlab <- function(prob = NULL, tau = NULL, mean = 0, spike = 0) { + probPrior <- if (inherits(prob, "hyperprior")) prob + tauPrior <- if (inherits(tau, "hyperprior")) tau + if (!is.null(probPrior) && probPrior$dist != "beta") + stop("spikeSlab: the prior of `prob` is betaPrior().", call. = FALSE) + if (!is.null(tauPrior) && !tauPrior$dist %in% c("halfCauchy", "halfNormal", "invGamma")) + stop("spikeSlab: the prior of `tau` is halfCauchyPrior(), halfNormalPrior() or invGammaPrior().", call. = FALSE) + if (!is.null(probPrior)) prob <- NULL + if (!is.null(tauPrior)) tau <- NULL if (!.positiveOrNull(prob) || (!is.null(prob) && prob >= 1)) - stop("spikeSlab: `prob` is NULL or one number in (0, 1).", call. = FALSE) - if (!.positiveOrNull(tau)) stop("spikeSlab: `tau` is NULL or one positive number.", call. = FALSE) + stop("spikeSlab: `prob` is NULL, one number in (0, 1) or betaPrior().", call. = FALSE) + if (!.positiveOrNull(tau)) + stop("spikeSlab: `tau` is NULL, one positive number or a scale prior.", call. = FALSE) if (!is.numeric(mean) || length(mean) != 1L || !is.finite(mean)) stop("spikeSlab: `mean` is one finite number.", call. = FALSE) if (!is.numeric(spike) || length(spike) != 1L || is.na(spike) || spike == Inf) stop("spikeSlab: `spike` is one finite number or -Inf.", call. = FALSE) - .redist("spikeSlab", prob = prob, tau = tau, mean = mean, spike = spike) + .redist("spikeSlab", prob = prob, tau = tau, mean = mean, spike = spike, probPrior = probPrior, + tauPrior = tauPrior) } #' @export @@ -152,16 +166,109 @@ dirichletProcess <- function(concentration = NULL, tau = NULL) { .positiveOrNull <- function(x) is.null(x) || (is.numeric(x) && length(x) == 1L && x > 0) -.redist <- function(dist, prob = NULL, concentration = NULL, tau = NULL, mean = 0, spike = 0) + +#' Hyperpriors of spike-and-slab random effects +#' +#' @description Priors on the hyperparameters of [spikeSlab()], in place of +#' a given value or an estimate, for blocks with few groups, where an +#' estimate of `prob` tends to 0 or 1 and an estimate of `tau` follows the +#' modes. +#' +#' - `betaPrior(a, b)`: `prob` ~ Beta(a, b), integrated out. The prior +#' weight of a subset of `k` slab deviations among `K` is +#' \eqn{B(a + k, b + K - k) / B(a, b)}; `betaPrior(1, 1)` makes every number +#' of slab deviations equally likely. +#' - `halfCauchyPrior(scale)`, `halfNormalPrior(scale)`: on `tau`. +#' - `invGammaPrior(shape, rate)`: on `tau^2`. +#' +#' [em()] estimates `tau` under a scale prior as the posterior mode, or with +#' `integrate = TRUE` integrates the phase `"exact"` over `log tau`; see +#' section Sparse random effects of [em()]. +#' +#' @param a,b Shape parameters of the Beta prior, positive. +#' @param scale Scale of the half-Cauchy or half-normal prior, positive. +#' @param shape,rate Shape and rate of the inverse-gamma prior, positive. +#' @param integrate Logical. `FALSE` (default) takes the posterior mode of +#' `tau`, `TRUE` integrates over `log tau` in the phase `"exact"`. +#' @return An object of class `hyperprior`. +#' @seealso [spikeSlab()], [em()] +#' @examples +#' spikeSlab(prob = betaPrior(1, 1), tau = halfCauchyPrior(1), mean = -1, spike = -Inf) +#' @export +betaPrior <- function(a = 1, b = 1) { + if (!.positiveNumber(a) || !.positiveNumber(b)) stop("betaPrior: `a` and `b` are positive numbers.", call. = FALSE) + .hyperprior("beta", a = a, b = b) +} + +#' @export +#' @rdname betaPrior +halfCauchyPrior <- function(scale = 1, integrate = FALSE) { + if (!.positiveNumber(scale)) stop("halfCauchyPrior: `scale` is a positive number.", call. = FALSE) + .hyperprior("halfCauchy", scale = scale, integrate = .flag(integrate, "halfCauchyPrior")) +} + +#' @export +#' @rdname betaPrior +halfNormalPrior <- function(scale = 1, integrate = FALSE) { + if (!.positiveNumber(scale)) stop("halfNormalPrior: `scale` is a positive number.", call. = FALSE) + .hyperprior("halfNormal", scale = scale, integrate = .flag(integrate, "halfNormalPrior")) +} + +#' @export +#' @rdname betaPrior +invGammaPrior <- function(shape = 1, rate = 1, integrate = FALSE) { + if (!.positiveNumber(shape) || !.positiveNumber(rate)) + stop("invGammaPrior: `shape` and `rate` are positive numbers.", call. = FALSE) + .hyperprior("invGamma", shape = shape, rate = rate, integrate = .flag(integrate, "invGammaPrior")) +} + +.positiveNumber <- function(x) is.numeric(x) && length(x) == 1L && is.finite(x) && x > 0 + +.flag <- function(x, fn) { + if (!(is.logical(x) && length(x) == 1L && !is.na(x))) stop(fn, ": `integrate` is TRUE or FALSE.", call. = FALSE) + x +} + +.hyperprior <- function(dist, ...) structure(list(dist = dist, ...), class = "hyperprior") + +## A short description of a hyperprior, as "Beta(1, 1), integrated" or "half-Cauchy(1), mode". +.describeHyperprior <- function(x) { + mode <- if (isTRUE(x$integrate)) "integrated" else "mode" + switch(x$dist, + beta = sprintf("Beta(%s, %s), integrated", format(x$a), format(x$b)), + halfCauchy = sprintf("half-Cauchy(%s), %s", format(x$scale), mode), + halfNormal = sprintf("half-normal(%s), %s", format(x$scale), mode), + invGamma = sprintf("inverse gamma(%s, %s) on tau^2, %s", format(x$shape), format(x$rate), mode)) +} + +#' @export +format.hyperprior <- function(x, ...) { + integrate <- if (isTRUE(x$integrate)) ", integrate = TRUE" else "" + switch(x$dist, + beta = sprintf("betaPrior(%s, %s)", format(x$a), format(x$b)), + halfCauchy = sprintf("halfCauchyPrior(%s%s)", format(x$scale), integrate), + halfNormal = sprintf("halfNormalPrior(%s%s)", format(x$scale), integrate), + invGamma = sprintf("invGammaPrior(%s, %s%s)", format(x$shape), format(x$rate), integrate)) +} + +#' @export +print.hyperprior <- function(x, ...) { + cat(format(x), "\n") + invisible(x) +} + +.redist <- function(dist, prob = NULL, concentration = NULL, tau = NULL, mean = 0, spike = 0, probPrior = NULL, + tauPrior = NULL) structure(list(dist = dist, prob = prob %||% NA_real_, concentration = concentration %||% NA_real_, - tau = tau %||% NA_real_, mean = mean, spike = spike), class = "redist") + tau = tau %||% NA_real_, mean = mean, spike = spike, probPrior = probPrior, tauPrior = tauPrior), + class = "redist") #' @export print.redist <- function(x, ...) { - arg <- function(v) if (is.na(v)) "NULL" else format(v) + arg <- function(v, prior = NULL) if (!is.null(prior)) format(prior) else if (is.na(v)) "NULL" else format(v) cat(switch(x$dist, normal = "normal()", - spikeSlab = sprintf("spikeSlab(prob = %s, tau = %s, mean = %s, spike = %s)", arg(x$prob), - arg(x$tau), format(x$mean %||% 0), format(x$spike %||% 0)), + spikeSlab = sprintf("spikeSlab(prob = %s, tau = %s, mean = %s, spike = %s)", arg(x$prob, x$probPrior), + arg(x$tau, x$tauPrior), format(x$mean %||% 0), format(x$spike %||% 0)), dirichletProcess = sprintf("dirichletProcess(concentration = %s, tau = %s)", arg(x$concentration), arg(x$tau))), "\n") invisible(x) @@ -336,6 +443,7 @@ print.redist <- function(x, ...) { id = rt$id, dist = rt$dist$dist, prob = rt$dist$prob, concentration = rt$dist$concentration, tau = rt$dist$tau, mean = rt$dist$mean %||% 0, spike = rt$dist$spike %||% 0, + probPrior = rt$dist$probPrior, tauPrior = rt$dist$tauPrior, stem = stems[k], etas = ifelse(none, NA_character_, paste0(stems[k], "_", .effectName(g))), z = Z[, k], @@ -398,7 +506,8 @@ print.redist <- function(x, ...) { row <- data.frame(symbol = r$symbol, origin = pf$origin, term = r$term, column = r$column, group = r$group, id = r$id, dist = r$dist, prob = r$prob, concentration = r$concentration, tau = r$tau, - mean = r$mean, spike = r$spike, stem = r$stem, stringsAsFactors = FALSE) + mean = r$mean, spike = r$spike, probPrior = I(list(r$probPrior)), + tauPrior = I(list(r$tauPrior)), stem = r$stem, stringsAsFactors = FALSE) terms <- rbind(terms, row) col <- setNames(rep(NA_character_, length(conds)), conds) col[rownames(tr)] <- r$etas @@ -434,7 +543,8 @@ print.redist <- function(x, ...) { column = character(0), group = character(0), id = character(0), dist = character(0), prob = numeric(0), concentration = numeric(0), tau = numeric(0), - mean = numeric(0), spike = numeric(0), stem = character(0)) + mean = numeric(0), spike = numeric(0), probPrior = I(list()), tauPrior = I(list()), + stem = character(0)) key <- ifelse(terms$dist != "normal", paste(terms$dist, terms$origin, terms$term, sep = "\r"), ifelse(is.na(terms$id), paste("term", terms$symbol, terms$term, sep = "\r"), paste("id", terms$id, terms$group, terms$dist, sep = "\r"))) diff --git a/R/remoteComputing.R b/R/remoteComputing.R index a698e54b..f5f7aa3a 100644 --- a/R/remoteComputing.R +++ b/R/remoteComputing.R @@ -158,13 +158,13 @@ detectFreeCores <- function(machine = NULL) { sum(nchar(files) + 1L) > .compileCmdLimit() ## Write the job workspace through zstd, as an uncompressed one can be several -## GB; without the binary it is saved uncompressed. Returns the file written. +## GB; without a working binary it is saved uncompressed. Returns the file written. .saveWorkspace <- function(input, file, envir = .GlobalEnv, level = 3L) { - - if (!nzchar(Sys.which("zstd"))) { + plain <- function() { save(list = input, file = file, envir = envir, compress = FALSE) - return(file) + file } + if (!nzchar(Sys.which("zstd"))) return(plain()) out <- paste0(file, ".zst") # by name: cmd.exe, which runs the pipe on Windows, drops quotes around the command @@ -172,12 +172,18 @@ detectFreeCores <- function(machine = NULL) { " -q -f -o ", shQuote(out)), "wb") ## close() pcloses, so zstd has finished before tar sees the file. ok <- try(save(list = input, file = con, envir = envir), silent = TRUE) - close(con) - if (inherits(ok, "try-error")) { + status <- suppressWarnings(close(con)) + if (inherits(ok, "try-error") && !grepl("pipe|write", conditionMessage(attr(ok, "condition")))) { unlink(out) stop("Could not write the job workspace: ", attr(ok, "condition")$message, call. = FALSE) } + # a zstd that fails writes no or an empty file and leaves the exit status in close() + if (inherits(ok, "try-error") || !identical(as.integer(status %||% 0L), 0L) || + !file.exists(out) || !file.size(out)) { + unlink(out) + return(plain()) + } out } @@ -907,7 +913,7 @@ print.dMod2Target <- function(x, ...) { failed <- sum(state == "failed") if (finished && failed) warning(failed, " of ", m$ntasks, " tasks failed; log(i) shows the output of task i", - call. = FALSE) + .tailNote(which(state == "failed")[1L], output), call. = FALSE) invisible(finished) } @@ -928,13 +934,17 @@ print.dMod2Target <- function(x, ...) { if (combine) .combineResults(out) else out } - log <- function(i, lines = 20L) { - i <- .wholeNumber(i, "i", null = FALSE) - if (i > m$ntasks) stop("the job has ", m$ntasks, " tasks", call. = FALSE) + output <- function(i, lines) { k <- m$taskHost[i] - out <- suppressWarnings(.onMachine( + suppressWarnings(.onMachine( m$hosts[k], paste0("tail -n ", as.integer(lines), " task_", i, ".out 2>/dev/null; true"), file.path(m$folder, k), m$wd, intern = TRUE)) + } + + log <- function(i, lines = 20L) { + i <- .wholeNumber(i, "i", null = FALSE) + if (i > m$ntasks) stop("the job has ", m$ntasks, " tasks", call. = FALSE) + out <- output(i, lines) cat(out, sep = "\n") invisible(out) } @@ -971,7 +981,16 @@ print.dMod2Target <- function(x, ...) { structure(list(check = check, wait = wait, get = get, log = log, purge = purge, terminate = terminate), - class = "dMod2Job", manifest = m) + class = "dMod2Job", manifest = m, output = output) +} + +## The last lines of the output of the failed task `i`, appended to the warning of a failed job. +.tailNote <- function(i, output, lines = 5L) { + if (is.na(i)) return("") + out <- tryCatch(output(i, lines), error = function(e) character(0)) + out <- out[nzchar(trimws(out))] + if (!length(out)) return("") + paste0("\n task ", i, ":\n ", paste(out, collapse = "\n ")) } ## Where a job runs, from the job manifest. @@ -1252,13 +1271,15 @@ distributedComputing <- function(expr, tasks = NULL, on = localNode(), jobname = .waitTasks(m, .pollInterval(m)) out <- job$get(combine = FALSE) result <- suppressWarnings(.combineResults(out)) - failed <- sum(vapply(out, function(r) is.null(r) || inherits(r, "try-error"), NA)) + bad <- vapply(out, function(r) is.null(r) || inherits(r, "try-error"), NA) + failed <- sum(bad) if (!failed) { job$purge(local = TRUE) return(result) } warning(failed, " of ", n, " tasks failed; the job is kept: recover = TRUE returns the job ", - "functions, and log(i) shows the output of task i", call. = FALSE) + "functions, and log(i) shows the output of task i", + .tailNote(which(bad)[1L], attr(job, "output")), call. = FALSE) result } @@ -1397,6 +1418,23 @@ slurmTemplate <- function(login = NULL, from = login, edit = interactive(), ## .parallelLapply --------------------------------------------------------------- +# A PSOCK cluster of `cores` workers on a port of 11000 to 11999 drawn from the process id and the +# clock, not from the random stream: sessions with the same seed on one node get different ports, +# and .Random.seed stays as it is. A port in use is skipped; R_PARALLEL_PORT, if a number, comes first. +.makePSOCK <- function(cores, tries = 50L) { + first <- suppressWarnings(as.integer(Sys.getenv("R_PARALLEL_PORT"))) + start <- (Sys.getpid() * 7919 + as.numeric(Sys.time()) * 1000) %% 1000 + ports <- 11000L + as.integer((start + 389 * seq_len(tries)) %% 1000) + if (!is.na(first)) ports <- unique(c(first, ports)) + for (port in ports) { + cluster <- tryCatch(parallel::makeCluster(cores, port = port), error = function(e) e) + if (!inherits(cluster, "error")) return(cluster) + if (!grepl("cannot be opened", conditionMessage(cluster))) stop(cluster) + } + stop("no free port for a PSOCK cluster among ", tries, " tries in 11000 to 11999", call. = FALSE) +} + + # Cross-platform parallel-apply. Unix forks via doParallel; Windows uses a # PSOCK cluster with the library paths of the session. Driven through # foreach::%dopar% so the caller body is the same on both platforms. @@ -1416,7 +1454,7 @@ slurmTemplate <- function(login = NULL, from = login, edit = interactive(), use_psock <- Sys.info()[["sysname"]] == "Windows" || wants_inner if (use_psock) { - cluster <- parallel::makeCluster(cores) + cluster <- .makePSOCK(cores) on.exit({ parallel::stopCluster(cluster) doParallel::stopImplicitCluster() diff --git a/R/statistics.R b/R/statistics.R index 4d2e2c22..798117e4 100644 --- a/R/statistics.R +++ b/R/statistics.R @@ -68,7 +68,7 @@ #' profiled parameter alone and the others are reoptimized at every step. #' \code{"hessian"} / \code{"identity"}.} #' \item{\code{reoptimize}}{Whether every step is followed by a fit of the -#' other parameters with [trust()]. \code{FALSE} / \code{TRUE}.} +#' other parameters with [trust()]. \code{TRUE} for both methods.} #' \item{\code{correction}}{Relative correction above which \code{gamma} #' is halved; below half of it \code{gamma} doubles up to the initial #' value. \code{1} for both methods.} @@ -157,7 +157,7 @@ profile.objfn <- function(fitted, pars, whichPar, alpha = 0.05, optimize = list(stepsize = 1e-2, min = 1e-4, max = Inf, atol = 1e-1, rtol = 1e-1, limit = 100, stop = "value")) aControl <- switch(method, - integrate = list(gamma = 1, W = "hessian", reoptimize = FALSE, correction = 1, + integrate = list(gamma = 1, W = "hessian", reoptimize = TRUE, correction = 1, reg = .Machine$double.eps), optimize = list(gamma = 0, W = "identity", reoptimize = TRUE, correction = 1, reg = 0)) oControl <- switch(method, diff --git a/R/steadyStates.R b/R/steadyStates.R index 36c6b05f..a6b6ec4c 100644 --- a/R/steadyStates.R +++ b/R/steadyStates.R @@ -2,10 +2,14 @@ #' #' Computes symbolic steady-state expressions for use in a parameter #' transformation, following the AlyssaPetit method \[1\], \[2\]. States whose -#' own balance gives a ratio of positive sums are solved from it first. The +#' mass only leaks are set to zero first, with `zeroLoops = TRUE` also states +#' that are only produced through one another. States whose own balance gives a +#' ratio of positive sums are solved from it first. The #' cycles of the graph of states left are cut then: at a state of a conserved #' quantity, or at a state whose balance is solved for a rate constant of one -#' flux side instead. Each cut state stays a free parameter. The remaining +#' flux side instead. Each cut state stays a free parameter. A state of a +#' conserved quantity whose balance is left without a positive unknown is solved +#' in a further round, with another state of the quantity free. The remaining #' states and the rate constants of the cuts are then solved, each from a #' balance or a combination of balances in amounts, such that the result is a #' ratio of sums of positive terms. Only if that fails, a flux side with @@ -40,6 +44,13 @@ #' @param priority Character vector of state and rate-parameter names, most #' preferred first: named states are solved rather than kept free and solved #' earlier, named rate parameters are preferred as pivots. Default `NULL`. +#' @param zeroLoops Logical. `FALSE` (default) looks for a steady state with +#' every state away from zero. `TRUE` sets to zero the largest set of states +#' that are only produced through one another, such as a ligand that only +#' the receptor complexes it forms activate: all fluxes of these states vanish +#' where they are zero, and no conserved quantity lies on them. This is the +#' steady state of a feedback loop that is off, as under +#' `symmetryDetection(equilibrate = TRUE)`. #' @param resolve Logical, whether the result is passed through #' [resolveRecurrence()] so that no equation refers to another. Default #' `TRUE`. @@ -58,7 +69,7 @@ #' @references \[2\] #' #' -#' @seealso [repar()], [P()] +#' @seealso [define()], [P()] #' #' @export #' @importFrom utils write.table @@ -78,13 +89,13 @@ #' #' # Parameter transformation that puts the model in steady state #' parameters <- getParameters(reactions) -#' trafo <- repar(eqnvec(setNames(parameters, parameters)), "x <- y", -#' x = names(steadies), y = steadies) +#' trafo <- define(NULL, "x <- x", x = parameters) +#' trafo <- insert(trafo, "x <- y", x = names(steadies), y = steadies) #' trafo steadyStates <- function(model, file = NULL, forcings = NULL, givenCQs = NULL, neglect = NULL, testSteady = c("fast", "skip"), walltime = 0L, simplify = TRUE, solveQuadratic = FALSE, - priority = NULL, resolve = TRUE, verbose = FALSE) { + priority = NULL, zeroLoops = FALSE, resolve = TRUE, verbose = FALSE) { .require_ns("reticulate", "steadyStates()") testSteady <- match.arg(testSteady) @@ -149,7 +160,8 @@ steadyStates <- function(model, file = NULL, forcings = NULL, solveQuadratic = as.logical(solveQuadratic), priority = as.list(as.character(priority)), verbose = verbose, - volumes = as.list(volumes)) + volumes = as.list(volumes), + zeroLoops = isTRUE(zeroLoops)) if (is.null(m_ss) || identical(m_ss, 0L)) return(0) diff --git a/R/symmetryDetection.R b/R/symmetryDetection.R index c991708a..13a03dcd 100644 --- a/R/symmetryDetection.R +++ b/R/symmetryDetection.R @@ -324,7 +324,8 @@ discreteSymmetries <- function(object, order = NULL, points = 5L, cores = 1, mem #' @param generalDegNum,generalDegDen Numerator and denominator degree bounds of the #' general sparse rational fit. Default to 4 and 3. #' @param gapOrderCap Maximum order of the power series in the time between -#' events. Defaults to 8. +#' events. Curve samples of resting conditions start at this order and double +#' it at most twice where a kernel at eps = 1 needs more. Defaults to 8. #' @param minSupportCandCap Maximum number of column subsets searched for #' directions with small support. Defaults to 20000. #' @param perPrimeCap Maximum number of samples per prime for the reconstruction @@ -392,7 +393,7 @@ reconstControl <- function(relevanceCap = 6L, relevanceCapDir = 24L, relevanceCa # ---- the interface to the Python package symident -------------------------------- -.symidentMin <- "0.18.1" +.symidentMin <- "0.18.2" .symidentReq <- paste0("symident>=", .symidentMin) # whether symident is installed in version .symidentMin or later diff --git a/_pkgdown.yml b/_pkgdown.yml index d29f8831..ffc87f85 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -67,6 +67,9 @@ navbar: href: articles/methods-nlme.html - text: "Sparsity priors" href: articles/methods-sparsity-priors.html + - text: "---" + - text: "Index" + href: articles/index-terms.html examples: text: Examples menu: @@ -136,6 +139,7 @@ articles: - '`articles/methods-multiple-shooting`' - '`articles/methods-nlme`' - '`articles/methods-sparsity-priors`' + - '`articles/index-terms`' - title: "Examples: signaling models" navbar: ~ @@ -222,7 +226,6 @@ reference: - Pimpl - parfn - define - - repar - print.parfn - Id - prodfn @@ -308,6 +311,7 @@ reference: contents: - randomEffects - normal + - betaPrior - em - msem - print.em diff --git a/dev/build-index.R b/dev/build-index.R new file mode 100644 index 00000000..ff1150dd --- /dev/null +++ b/dev/build-index.R @@ -0,0 +1,38 @@ +# The subject index of the site: every span [term]{#def-...} of the articles, alphabetically, linked to +# the place where the text defines the term. An attribute index="..." in the span sets the entry text. +# Run from the package root: Rscript dev/build-index.R; writes vignettes/articles/index-terms.Rmd. +dir <- "vignettes/articles" +files <- setdiff(list.files(dir, "\\.Rmd$", full.names = TRUE), file.path(dir, "index-terms.Rmd")) +span <- "\\[((?:[^][]|\\[[^]]*\\])+)\\]\\{#(def-[A-Za-z0-9-]+)([^}]*)\\}" + +entries <- do.call(rbind, lapply(files, function(f) { + src <- readLines(f, warn = FALSE) + title <- sub('^title:\\s*"?(.*?)"?\\s*$', "\\1", grep("^title:", src, value = TRUE)[1]) + hits <- regmatches(src, gregexpr(span, src, perl = TRUE)) + hits <- unlist(hits) + if (!length(hits)) return(NULL) + m <- regmatches(hits, regexec(span, hits, perl = TRUE)) + term <- vapply(m, `[`, "", 2) + attrs <- vapply(m, `[`, "", 4) + given <- sub('.*index="([^"]*)".*', "\\1", attrs) + term <- ifelse(grepl('index="', attrs), given, term) + data.frame(term = term, anchor = vapply(m, `[`, "", 3), + page = sub("\\.Rmd$", ".html", basename(f)), title = title) +})) + +key <- tolower(gsub("[^A-Za-z0-9 ]", "", gsub("\\$[^$]*\\$", "", entries$term))) +key[!nzchar(trimws(key))] <- tolower(entries$term[!nzchar(trimws(key))]) +entries <- entries[order(key, entries$title), ] +key <- sort(key) +letter <- toupper(substr(trimws(key), 1, 1)) +letter[!grepl("[A-Z]", letter)] <- "Symbols" + +out <- c("---", 'title: "Index"', "---", "", + "Terms of the guide and the methods articles, each linked to the place where the text defines it.", "") +for (l in unique(letter)) { + e <- entries[letter == l, ] + out <- c(out, paste("##", l), "", + sprintf("- [%s](%s#%s), %s", e$term, e$page, e$anchor, e$title), "") +} +writeLines(out, file.path(dir, "index-terms.Rmd")) +cat(nrow(entries), "entries\n") diff --git a/dev/build-site.R b/dev/build-site.R index 5b541e08..08ee1332 100644 --- a/dev/build-site.R +++ b/dev/build-site.R @@ -6,6 +6,7 @@ workers <- as.integer(commandArgs(TRUE)[1]) if (is.na(workers)) workers <- 8L unlink("docs", recursive = TRUE) +source("dev/build-index.R") pkg <- pkgdown::as_pkgdown(".") pkgdown::init_site(pkg) diff --git a/examples/oppeltNPJSystBiolAppl2018/results/reduction.rds b/examples/oppeltNPJSystBiolAppl2018/results/reduction.rds index 97b98cc2..00bf1775 100644 Binary files a/examples/oppeltNPJSystBiolAppl2018/results/reduction.rds and b/examples/oppeltNPJSystBiolAppl2018/results/reduction.rds differ diff --git a/examples/oppeltNPJSystBiolAppl2018/results/symmetries.rds b/examples/oppeltNPJSystBiolAppl2018/results/symmetries.rds index bbc17dba..13ab755d 100644 Binary files a/examples/oppeltNPJSystBiolAppl2018/results/symmetries.rds and b/examples/oppeltNPJSystBiolAppl2018/results/symmetries.rds differ diff --git a/inst/WORDLIST b/inst/WORDLIST index 33095897..364b56a2 100644 --- a/inst/WORDLIST +++ b/inst/WORDLIST @@ -19,18 +19,22 @@ BDF BLOQ BLQ BLoQ +BaF BaF3 Bachmann Bergstrand Bigl Bigr Bilevel +Biomedicine +Biometrics Birkhäuser Blackwellized BlotIt Boehm Brendel CFU +CIE CIE2000 CMD CVODE @@ -54,9 +58,11 @@ F4 FOCE FOCEI Fehling +Fides FitzHugh Fk Forcings +Freiburg Fröhlich Fujita Funaki @@ -64,21 +70,25 @@ GFP Genz Gerstner GiB +Godfrey Gretz Griebel Hager Hauber HepG2 +Hessians Holford Hopf Horbelt Huh7 Huschens +Hyperpriors IET IFN IKK IPRED IRES +IRF IRF9 IWRES Immunoblots @@ -96,6 +106,8 @@ L1 L10 L2 L5 +LOQ +Lehmann Leong Leyffer Lindstrom @@ -109,6 +121,7 @@ MathML Mavoglurant Mentré Modelname +Mol Monro Moré Multistart @@ -124,6 +137,8 @@ Nocedal Nonmonotone O'Reilly OIM +Observability +Observables Ogungbenro Okabe OpenMP @@ -136,6 +151,7 @@ PLOS PLoS PNAS PPL +PRED PSOCK PWRES Peifer @@ -145,6 +161,8 @@ Pharmacokinetics Phosphorylated Pigeolet Pimpl +Polychrome +Pos Pre Proteome PyPI @@ -165,10 +183,12 @@ S9 SAEM SBML SBML's +SHP SHP1 SIGKILL SIGTERM SLURM +SOCS SOCS3 SR1 STAT1 @@ -184,18 +204,22 @@ Sorger SuiteSparse Swameye SymPy +Syst TG TNFα TSV Tapia Teusel +Theophylline Timmer Tiwari Tsamandouras Tsitouras USP18 Voss +WD Wallin +Warfarin Wendling Wilk Woodbury @@ -203,7 +227,10 @@ Xcode YAML Zhang Zhou +actinomycin +adjoint adjoints +al archiver arg atol @@ -220,6 +247,7 @@ cdots chi2 circ const +coumarin cowplot cppDE cppDE's @@ -234,7 +262,9 @@ deSolve decorrelated dephosphorylation det +deterministically dfrac +dichromatic diclofenac dimerization distributedComputing @@ -249,10 +279,14 @@ eigenbasis eigendecomposition eigenpairs endosomes +eps eqnlist eqnlists eqnvec +equilibrated +equilibration erythroid +et evaluable eventlist feedbacks @@ -260,12 +294,15 @@ forcings frac frac1K ge +getter ggplot ggplot2 ggplots globalizations hepatoma homotopy +hyperprior +hyperpriors i10 iN iS @@ -273,7 +310,10 @@ ij ik immunoblots infty +integrand +integrators interpolant +invariants isoform jk jss @@ -286,9 +326,13 @@ ldots le leftarrow libsbml +ligand +linearized linearizes lloq +lme lme4 +loess log10 log2 lowerCamelCase @@ -303,6 +347,8 @@ mavoglurant md metanames mis +monomial +monomials msolve mstrust mtol @@ -313,6 +359,7 @@ nM nabla ni nleqslv +nlmixr nlmixr2 nlmixr2data nonpositive @@ -324,7 +371,9 @@ numpy objfn objlist objlists +observability observableId +observables odemodel openxlsx operatorname @@ -360,17 +409,22 @@ pre preconditioner preequilibration propto +prothrombin pseudoinverse purrr qPCR qquad +quadratically +quadratures rVert recompiles reimplemented +reimport reoptimizations reoptimized reoptimizes reparameterization +reticulate ri rtol rvert @@ -378,10 +432,14 @@ scaling's scipy setminus siRNA +spectrometry stabilise +stoichiometric subfolder +subproblem subseteq substeps +summand summands superlinear symengine @@ -396,6 +454,7 @@ tfrac tfrac12 tfrac1n th +theophylline thetaMax tibbles tol @@ -404,6 +463,7 @@ trafo tsv uncompiled unconverged +undamped underbrace unparsable v088 @@ -412,5 +472,6 @@ v2 valueSE varepsilon vartheta +warfarin zstd α diff --git a/inst/code/AlyssaPetit.py b/inst/code/AlyssaPetit.py index ed349f81..6eba68ce 100644 --- a/inst/code/AlyssaPetit.py +++ b/inst/code/AlyssaPetit.py @@ -1,4 +1,4 @@ -# AlyssaPetit version 1.4 +# AlyssaPetit version 1.5 # Use with python 3.x # # A new core on the same interface as v1.3. Every flux is expanded into atoms, @@ -20,6 +20,10 @@ # separate rate constants is cut with free flux ratios only if nothing else solves. # Where the greedy choice of unknowns then runs into a dead end, the unknowns whose # solutions block it go last and the search restarts. +# States rest at zero where their mass only leaks; with zeroLoops also where they +# form the largest set whose fluxes all vanish with the set at zero. +# A state of a conserved quantity whose balance is left over is solved in a +# further round, another state of the quantity kept free. import os import sys @@ -464,6 +468,19 @@ def _read_model(filename, injections): stoich=[[col[i] for i in keep] for col in stoich] return states, fluxes, stoich +def _drop_zero(states, fluxes, stoich, zs): + # The model with the states zs at 0: their rows removed, fluxes that vanish dropped. + rep={s: 0 for s in zs} + keep=[i for i, s in enumerate(states) if s not in rep] + nf, ns=[], [] + for f, col in zip(fluxes, stoich): + f=f.xreplace(rep) + if f==0: + continue + nf.append(f) + ns.append([col[i] for i in keep]) + return [states[i] for i in keep], nf, ns + def _zero_states(states, fluxes, stoich, volumes): # States that are 0 at every steady state: a set whose mass only leaks # (v1.3's linear program, in amounts). They are removed and substituted by 0. @@ -478,19 +495,81 @@ def _zero_states(states, fluxes, stoich, volumes): break zs=[states[i] for i in cluster] zero+=zs - rep={s: 0 for s in zs} - keep=[i for i in range(len(states)) if i not in cluster] - nf, ns=[], [] - for f, col in zip(fluxes, stoich): - f=f.xreplace(rep) - if f==0: - continue - nf.append(f) - ns.append([col[i] for i in keep]) - states=[states[i] for i in keep] - fluxes, stoich=nf, ns + states, fluxes, stoich=_drop_zero(states, fluxes, stoich, zs) return states, fluxes, stoich, zero +def _vanishes_at(f, sub): + # The flux is 0 where the symbols of sub are 0, with a denominator that is not. + num, den=sympy.fraction(sympy.together(f)) + return sympy.expand(num.xreplace(sub))==0 and sympy.expand(den.xreplace(sub))!=0 + +def _left_kernel_modp(J, p): + # Basis of the left kernel of the square matrix J (lists of ints) over GF(p). + n=len(J) + A=[[J[i][k] % p for i in range(n)] for k in range(n)] + piv=[] + r=0 + for c in range(n): + k=next((i for i in range(r, n) if A[i][c]), None) + if k is None: + continue + A[r], A[k]=A[k], A[r] + inv=pow(A[r][c], -1, p) + A[r]=[v*inv % p for v in A[r]] + for i in range(n): + if i!=r and A[i][c]: + f=A[i][c] + A[i]=[(a-f*b) % p for a, b in zip(A[i], A[r])] + piv.append(c) + r+=1 + out=[] + for c in (c for c in range(n) if c not in piv): + v=[0]*n + v[c]=1 + for i, pc in enumerate(piv): + v[pc]=-A[i][c] % p + out.append(v) + return out + +def _zero_face(states, fluxes, stoich): + """The largest set of states whose fluxes all vanish where the set is 0, with + the Jacobian of their balances on the set invertible at random values: a face + of the steady states at 0. A conserved quantity over the set makes the Jacobian + singular; the states of the quantity are left out.""" + p=_MODP_PRIMES[0] + touch={s: [j for j, col in enumerate(stoich) if col[i]!=0] for i, s in enumerate(states)} + face=[s for s in states if touch[s]] + rng=random.Random(1) + while face: + sub={s: 0 for s in face} + drop={s for s in face if not all(_vanishes_at(fluxes[j], sub) for j in touch[s])} + if drop: + face=[s for s in face if s not in drop] + continue + row={s: i for i, s in enumerate(states)} + J=[[sympy.Add(*[stoich[j][row[s]]*sympy.diff(fluxes[j], x) for j in touch[s]]).xreplace(sub) + for x in face] for s in face] + syms=set().union(*(e.free_symbols for r in J for e in r)) + exp_syms=set().union(set(), *(_collect_exponent_syms(e) for r in J for e in r)) + vals=None + for _ in range(20): + env={x: (rng.randint(2, 5) if x in exp_syms else rng.randint(1, p-1)) for x in syms} + try: + vals=[[_eval_modp(e, env, p) for e in r] for r in J] + break + except _ResampleModp: + continue + except _UnsupportedModp: + return [] + if vals is None: + return [] + left=_left_kernel_modp(vals, p) + if not left: + return face + out={face[i] for v in left for i in range(len(face)) if v[i]} + face=[s for s in face if s not in out] + return [] + def _atoms(states, fluxes, stoich, volumes=None): # Expand every flux into atoms; the balance of state i, in amounts (times the # volume of the state), is sum_a B[i][a] * atom_a with exact rational B. In @@ -902,6 +981,9 @@ def _greedy(order, cands, nonlin, atoms, basis, Rnp, r, check_time, B_rows, row_ deps={} solved=[] ratios=[] + # the forced atoms of an unknown and the span of the used balances only grow + # during a run: an unknown without an equation stays without one + dead=set() state_set=set(row_of) unknowns=set(cands)|state_set atom_syms=[at.free_symbols for at in atoms] @@ -924,7 +1006,7 @@ def root_of_some_state(): quad=None tried_quad=not quadratic for u in order: - if u in sol: + if u in sol or u in dead: continue if not tried_quad and u not in state_set: tried_quad=True @@ -940,6 +1022,7 @@ def root_of_some_state(): if res is not None: picked=(u, res) break + dead.add(u) if picked is None and quad is None and not tried_quad: quad=root_of_some_state() if quad is not None: @@ -1123,7 +1206,7 @@ def _state_graph_after(states, atoms, B, solved): return {s: _unsolved_refs(succ, solved) for s, succ in graph.items() if s not in solved} def _cut_cycles(states, atoms, B, cands, cqs, prio_rank, given, solved=None, locked=(), - ratios=True, replay=()): + ratios=True, replay=(), avoid=()): """Free states and rate constants that remove every cycle of the state graph. A cycle is cut at a state of a conserved quantity, whose balance is then the @@ -1135,7 +1218,8 @@ def _cut_cycles(states, atoms, B, cands, cqs, prio_rank, given, solved=None, loc constant named in `priority` first and a state named there last, conserved quantity, then side type, rewired balances, number of terms, number of cycles through the state, and occurrence in other balances; a side with one - rate constant before one with ratios. States in `solved` (state -> + rate constant before one with ratios. A state in `avoid` is kept free for a + conserved quantity only after the other states of the quantity. States in `solved` (state -> referenced states) are solved directly beforehand and leave the graph, rate constants in `locked` are not cut at, and the cuts in `replay` are made first, in their order. @@ -1185,7 +1269,7 @@ def rank(*names): # a given quantity keeps the first state on a cycle free k=next((k for k, c in enumerate(cqs) if not used[k] and c.get(s, 0)!=0), None) if k is not None: - first=0 if not given else list(cqs[k]).index(s) + first=(s in avoid, 0 if not given else list(cqs[k]).index(s)) rows.append(((len(prio_rank), str(s) in prio_rank, 0, first, 0, 0, 0)+tail+(0, str(s)), ('cq', s, k, ()))) continue @@ -1361,7 +1445,7 @@ def _direct_pass(states, atoms, B, cands, neglect, cqs, keep=()): def Alyssa(model_csv, injections=(), givenCQs=(), neglect=(), testSteady='fast', walltime=0, simplify=True, solveQuadratic=False, priority=(), - verbose=True, volumes=None): + verbose=True, volumes=None, zeroLoops=False): global _VERBOSE _VERBOSE=2 if verbose=='full' else int(bool(verbose)) del _NOTES[:] @@ -1380,6 +1464,13 @@ def Alyssa(model_csv, injections=(), givenCQs=(), neglect=(), testSteady='fast', ODE=[sympy.Add(*[col[i]*f for f, col in zip(fluxes, stoich)]) for i in range(len(states))] vol=ParseVolumes(volumes) states, fluxes, stoich, zero=_zero_states(states, fluxes, stoich, vol) + face=_zero_face(states, fluxes, stoich) if zeroLoops else [] + if face: + _note('zeroLoops: the states '+', '.join(str(s) for s in face)+' rest at 0, their fluxes ' + 'vanish where all of them are 0') + states, fluxes, stoich=_drop_zero(states, fluxes, stoich, face) + states, fluxes, stoich, more=_zero_states(states, fluxes, stoich, vol) + zero+=face+more vol_syms=set().union(*(v.free_symbols for v in vol.values())) if vol else set() def balances(fluxes, held, positive=frozenset()): @@ -1417,7 +1508,7 @@ def balances(fluxes, held, positive=frozenset()): keep=set().union(*cqs) direct, locked=_direct_pass(states, atoms, B, cands_all, neglect, cqs, keep) - def attempt(direct, locked, use_ratios): + def attempt(direct, locked, use_ratios, avoid): # A ratio cut substitutes flux_p = r_p * flux_g0 on the side of the cut into # every flux; the side then has the common rate constant g0, and the cuts # start over with those made so far. @@ -1427,11 +1518,11 @@ def attempt(direct, locked, use_ratios): while True: at, Bm, bs, Rn, ca, nl, cq=M cut=_cut_cycles(states, at, Bm, ca, cq, prio_rank, bool(givenCQs), direct, locked, - use_ratios, replay) + use_ratios, replay, avoid) # direct solutions are taken back if they leave more cycles without a cut if direct and cut[3] and not replay: plain=_cut_cycles(states, at, Bm, ca, cq, prio_rank, bool(givenCQs), None, (), - use_ratios) + use_ratios, (), avoid) if len(plain[3]) summary { @@ -50,6 +65,12 @@ main details.fold[open] > summary { margin-bottom: 0.5rem; } +/* A figure never runs over the text column; it scales down with the height in proportion. */ +main img { + max-width: 100%; + height: auto; +} + /* A figure in a div of class wide takes the full width of the text column. */ main div.wide img { max-width: 100%; diff --git a/tests/testthat/test-arguments.R b/tests/testthat/test-arguments.R index 302d91ad..00da04f0 100644 --- a/tests/testthat/test-arguments.R +++ b/tests/testthat/test-arguments.R @@ -35,20 +35,20 @@ test_that("plotArray takes more simulations than the profile has points", { "ggplot") }) -test_that("repar takes the transformation first and refuses the other order", { +test_that("define and insert take the transformation first and refuse the other order", { tr <- c(a = "a", b = "b") - expect_identical(repar(tr, "x <- exp(x)", x = "a"), c(a = "exp(a)", b = "b")) - expect_error(repar("x <- exp(x)", tr, x = "a"), "repar\\(trafo, expr\\)") - expect_equal(unclass(repar(NULL, "x <- x", x = "a")), c(a = "a")) + expect_identical(insert(tr, "x <- exp(x)", x = "a"), c(a = "exp(a)", b = "b")) + expect_error(insert("x <- exp(x)", tr, x = "a"), "\\(trafo, expr\\)") + expect_error(define("x <- exp(x)", tr, x = "a"), "\\(trafo, expr\\)") + expect_equal(unclass(define(NULL, "x <- x", x = "a")), c(a = "a")) }) test_that("a substitution is written with <-; ~ and formulas are refused", { tr <- c(a = "a", b = "b") - expect_identical(repar(tr, "a <- b + 1"), c(a = "b + 1", b = "b")) - expect_error(repar(tr, "a ~ b"), "lhs <- rhs") + expect_identical(insert(tr, "a <- b + 1"), c(a = "b + 1", b = "b")) expect_error(insert(tr, "a ~ b"), "reserved for model formulas") expect_error(define(tr, a ~ b), "reserved for model formulas") - expect_error(repar(tr, "a == b"), "lhs <- rhs") + expect_error(insert(tr, "a == b"), "lhs <- rhs") }) test_that("a transformation started from NULL keeps the right-hand side", { diff --git a/tests/testthat/test-mstrust.R b/tests/testthat/test-mstrust.R index be239a85..154ad371 100644 --- a/tests/testthat/test-mstrust.R +++ b/tests/testthat/test-mstrust.R @@ -208,10 +208,14 @@ test_that("the integrated profile takes the exact Hessian where the objective ha fit <- trust(obj, c(a = 1, b = 1.5), rinit = 1, rmax = 10, hessianMethod = "exact") along <- function(pr) max(abs(pr$value - vapply(pr$a, function(a) optimize(function(b) obj(c(b = b), fixed = c(a = a))$value, c(0, 5))$objective, 0))) - exact <- profile(obj, fit$argument, "a", limits = c(-1, 1), cores = 1) - gn <- profile(obj, fit$argument, "a", limits = c(-1, 1), cores = 1, deriv2 = FALSE) + alone <- list(reoptimize = FALSE) + exact <- profile(obj, fit$argument, "a", limits = c(-1, 1), cores = 1, algoControl = alone) + gn <- profile(obj, fit$argument, "a", limits = c(-1, 1), cores = 1, deriv2 = FALSE, algoControl = alone) expect_lt(along(exact), 1e-4) expect_gt(along(gn), 1e-3) + # by default every step is refitted, so the Gauss-Newton path follows the optimum as well + refit <- profile(obj, fit$argument, "a", limits = c(-1, 1), cores = 1, deriv2 = FALSE) + expect_lt(along(refit), 1e-4) }) test_that("a reoptimized profile follows the other parameters when the profiled one is on a small scale", { @@ -575,7 +579,8 @@ test_that("profile checks whichPar and the stop criterion and drops failed profi if (abs(c(pars, fixed)[["b"]] - 2) > 1e-12) stop("boom") obj(pars, fixed = fixed, ...) } - expect_message(pr <- profile(failB, p0, c("a", "b"), limits = c(-1, 1), cores = 1), + expect_message(expect_warning(pr <- profile(failB, p0, c("a", "b"), limits = c(-1, 1), cores = 1), + "reoptimizations failed"), "profile b.*boom") expect_setequal(unique(pr$whichPar), c("a", "b")) bad <- function(pars, ...) stop("boom") diff --git a/tests/testthat/test-parallelBackend.R b/tests/testthat/test-parallelBackend.R index 1f89e886..ef537f0d 100644 --- a/tests/testthat/test-parallelBackend.R +++ b/tests/testthat/test-parallelBackend.R @@ -36,6 +36,25 @@ test_that(".parallelLapply propagates worker errors", { }) + +test_that("a PSOCK cluster leaves the random stream alone and skips a port in use", { + # sessions with the same seed on one node: the port comes from the process and the clock + set.seed(1) + seed <- .Random.seed + cl <- dMod2:::.makePSOCK(1L) + on.exit(parallel::stopCluster(cl), add = TRUE) + expect_identical(.Random.seed, seed) + expect_identical(parallel::clusterEvalQ(cl, 1 + 1)[[1]], 2) + + # the first port taken: the cluster opens on the next one + busy <- serverSocket(11999L) + on.exit(close(busy), add = TRUE) + withr::local_envvar(R_PARALLEL_PORT = "11999") + cl2 <- dMod2:::.makePSOCK(1L) + on.exit(parallel::stopCluster(cl2), add = TRUE) + expect_identical(parallel::clusterEvalQ(cl2, 2 + 2)[[1]], 4) +}) + ## ---- Two-axis core budget ------------------------------------------------ test_that(".splitCores reads a scalar as the outer axis only", { diff --git a/tests/testthat/test-plots.R b/tests/testthat/test-plots.R index 643ad14b..abdeb8dd 100644 --- a/tests/testthat/test-plots.R +++ b/tests/testthat/test-plots.R @@ -3,14 +3,16 @@ pdf(NULL) # a is coupled to b and c, d is independent -.coupled <- function(pars, ...) { - a <- pars[["a"]]; b <- pars[["b"]]; c <- pars[["c"]]; d <- pars[["d"]] +.coupled <- function(pars, fixed = NULL, ...) { + p <- c(pars, fixed) + a <- p[["a"]]; b <- p[["b"]]; c <- p[["c"]]; d <- p[["d"]] v <- (a - b)^2 + (a - 2*c)^2 + 0.1*(a - 1)^2 + (d - 1)^2 g <- c(a = 2*(a - b) + 2*(a - 2*c) + 0.2*(a - 1), b = -2*(a - b), c = -4*(a - 2*c), d = 2*(d - 1)) H <- matrix(0, 4, 4, dimnames = list(names(g), names(g))) H["a", "a"] <- 4.2; H["a", "b"] <- H["b", "a"] <- -2; H["a", "c"] <- H["c", "a"] <- -4 H["b", "b"] <- 2; H["c", "c"] <- 8; H["d", "d"] <- 2 - objlist(value = v, gradient = g, hessian = H) + free <- names(pars) + objlist(value = v, gradient = g[free], hessian = H[free, free, drop = FALSE]) } .coupledProfile <- function() profile(.coupled, c(a = 1, b = 1, c = 0.5, d = 1), whichPar = "a", limits = c(-1, 1), cores = 1) diff --git a/tests/testthat/test-quadrature.R b/tests/testthat/test-quadrature.R index c9b2d1ea..3abe8f5b 100644 --- a/tests/testthat/test-quadrature.R +++ b/tests/testthat/test-quadrature.R @@ -192,7 +192,7 @@ test_that("a fit returns the best iterate when the rebuilds run out", { fit <- suppressMessages(em(m$objE, randomEffects(m$pw), c(mu = 0.7, mu_w = 0.1, s = log(0.3)), method = "quadrature", verbose = FALSE, control = list(quadrature = list(maxLevel = 2, tol = 1e-12, tolDecrement = 0, - maxEcmPerStage = 2, certificate = FALSE)))) + maxECMPerStage = 2, certificate = FALSE)))) tr <- fit$stageTrace expect_false(fit$converged) expect_identical(fit$stopReason, "iterlim") diff --git a/tests/testthat/test-remote-libs.R b/tests/testthat/test-remote-libs.R index c7f5792a..091fd495 100644 --- a/tests/testthat/test-remote-libs.R +++ b/tests/testthat/test-remote-libs.R @@ -131,6 +131,21 @@ test_that("tasks run on localhost without ssh, with task, taskId and the calling expect_identical(nrow(dMod2Jobs()), 0L) }) +test_that("a zstd that fails leaves the workspace uncompressed, and the tasks read it", { + skip_on_cran() + # the stand-in zstd is a POSIX shell script + skip_on_os("windows") + local_no_ssh() + bin <- withr::local_tempdir() + writeLines(c("#!/bin/sh", "cat > /dev/null", "exit 1"), file.path(bin, "zstd")) + Sys.chmod(file.path(bin, "zstd"), "755") + withr::local_envvar(PATH = paste(bin, Sys.getenv("PATH"), sep = .Platform$path.sep)) + x0 <- 3 + out <- suppressMessages(distributedComputing(x0 + task, tasks = list(a = 1, b = 2), input = "x0", + jobname = "jz", wait = TRUE)) + expect_identical(out, list(a = 4, b = 5)) +}) + test_that("detectFreeCores() reports the local machine", { skip_on_cran() free <- detectFreeCores("localhost") @@ -482,7 +497,7 @@ test_that("a failing task returns the error, a running job keeps the name, and t local_no_ssh() expect_warning(out <- suppressMessages(distributedComputing( stop("no"), input = character(0), jobname = "je", wait = TRUE)), - "1 of 1 tasks failed; the job is kept") + "1 of 1 tasks failed; the job is kept.*task 1:.*Error.*no") expect_length(out, 0L) failed <- distributedComputing(NULL, jobname = "je", recover = TRUE) expect_output(failed$log(1), "no") diff --git a/tests/testthat/test-reverse.R b/tests/testthat/test-reverse.R index 3791af0b..19be3fed 100644 --- a/tests/testthat/test-reverse.R +++ b/tests/testthat/test-reverse.R @@ -43,7 +43,7 @@ skip_on_cran() condition = "C1", derivMode = fr, modelname = "rv_pe", outdir = d) # One trafo per condition, each with a separate parameter. pc <- Reduce("+", lapply(c("C1", "C2"), function(cn) - P(repar(tr, paste0("logk1 <- logk1 + dk_", cn)), condition = cn, derivMode = fr, + P(insert(tr, paste0("logk1 <- logk1 + dk_", cn)), condition = cn, derivMode = fr, modelname = paste0("rv_p2_", cn), outdir = d))) ev <- eventlist(var = "A", time = "t_dose", value = "d_amt", method = "add") diff --git a/tests/testthat/test-spikeSlabSubsets.R b/tests/testthat/test-spikeSlabSubsets.R index 1750d2eb..136de907 100644 --- a/tests/testthat/test-spikeSlabSubsets.R +++ b/tests/testthat/test-spikeSlabSubsets.R @@ -137,35 +137,45 @@ test_that("with counts and an error model of the prediction the production term expect_equal(unname(fit$argument["x"]), 100, tolerance = 0.1) }) +test_that("EC with an error model of the prediction selects as the exact sum", { + exact <- .spkFit(.spk$counts, .spk$pSel, init = c(x = 100), errmodel = .spk$err, + control = list(sparseFit = list(phases = "exact")))$fit + ec <- .spkFit(.spk$counts, .spk$pSel, init = c(x = 100), errmodel = .spk$err, + control = list(sparseFit = list(phases = "ec")))$fit + expect_true(ec$converged) + expect_equal(ec$random$p0 > 0.5, exact$random$p0 > 0.5) + expect_equal(ec$value, exact$value, tolerance = 0.01) +}) + +# -2 log Z of the subset `on` of the etas of `fit` (slab N(log(0.5), tau^2), the others at -Inf) at the estimate x of +# `fit`, by a product rule of 20 Gauss-Hermite nodes per coordinate around the mode +.spkTensorM2logZ <- function(obj, fit, on, tau = 1) { + withr::local_dir(.spk$dir) + etas <- fit$random$parameter + gh <- dMod2:::.gaussHermite(20) + prior <- constraintL2(setNames(rep(log(0.5), length(on)), on), sigma = tau) + fx <- c(fit$argument["x"], setNames(rep(-Inf, length(setdiff(etas, on))), setdiff(etas, on))) + tr <- trust(obj + prior, setNames(rep(log(0.5), length(on)), on), fixed = fx, hessianMethod = "gn") + R <- chol(tr$hessian / 2) + z <- as.matrix(expand.grid(rep(list(gh$x), length(on)))) + w <- apply(as.matrix(expand.grid(rep(list(gh$w), length(on)))), 1, prod) + lt <- vapply(seq_len(nrow(z)), function(i) { + eta <- setNames(tr$argument + sqrt(2) * backsolve(R, z[i, ]), on) + -(obj(eta, fixed = fx, deriv = FALSE)$value + prior(eta, deriv = FALSE)$value) / 2 + sum(z[i, ]^2) + }, 0) + log(w) + top <- max(lt) + -2 * (top + log(sum(exp(lt - top))) + length(on) / 2 * log(2) - sum(log(diag(R)))) + + length(on) * log(2 * pi * tau^2) +} + test_that("quadrature per subset agrees with a tensor Gauss-Hermite rule", { r <- .spkCounts("quadrature") fit <- r$fit expect_true(fit$converged) expect_equal(fit$method, "quadrature") p0 <- setNames(fit$random$p0, fit$random$eta) - - # -2 log Z of a subset by a product rule of 20 nodes per coordinate around the mode - withr::local_dir(.spk$dir) - tau <- 1 - etas <- fit$random$parameter - gh <- dMod2:::.gaussHermite(20) - m2logZ <- function(on) { - prior <- constraintL2(setNames(rep(log(0.5), length(on)), on), sigma = tau) - fx <- c(fit$argument["x"], setNames(rep(-Inf, length(setdiff(etas, on))), setdiff(etas, on))) - tr <- trust(r$obj + prior, setNames(rep(log(0.5), length(on)), on), fixed = fx, hessianMethod = "gn") - R <- chol(tr$hessian / 2) - z <- as.matrix(expand.grid(rep(list(gh$x), length(on)))) - w <- apply(as.matrix(expand.grid(rep(list(gh$w), length(on)))), 1, prod) - lt <- vapply(seq_len(nrow(z)), function(i) { - eta <- setNames(tr$argument + sqrt(2) * backsolve(R, z[i, ]), on) - -(r$obj(eta, fixed = fx, deriv = FALSE)$value + prior(eta, deriv = FALSE)$value) / 2 + sum(z[i, ]^2) - }, 0) + log(w) - top <- max(lt) - -2 * (top + log(sum(exp(lt - top))) + length(on) / 2 * log(2) - sum(log(diag(R)))) + - length(on) * log(2 * pi * tau^2) - } - z1 <- m2logZ("eta_k1_all") - z2 <- m2logZ(c("eta_k0_all", "eta_k1_all")) + z1 <- .spkTensorM2logZ(r$obj, fit, "eta_k1_all") + z2 <- .spkTensorM2logZ(r$obj, fit, c("eta_k0_all", "eta_k1_all")) expect_lt(abs(p0[["k0"]] - 1 / (1 + exp(-(z2 - z1) / 2))), 5e-3) laplace <- .spkCounts("focei")$fit expect_false(isTRUE(all.equal(laplace$random$p0, fit$random$p0, tolerance = 1e-3))) @@ -260,10 +270,293 @@ test_that("EC beyond the budget agrees with the sum over all subsets", { fit <- function(...) em(normL2(data, .spk$g2 * .spk$x2 * .spk$pEC), randomEffects(.spk$pEC), init = c(x = 0.5, y = 2), verbose = FALSE, ...) exact <- fit() - ec <- fit(control = list(sparseFit = list(budget = 8))) + ec <- fit(control = list(sparseFit = list(termBudget = 8))) expect_true(ec$converged) expect_equal(ec$random$p0, exact$random$p0, tolerance = 0.1) expect_equal(ec$random$p0 > 0.5, exact$random$p0 > 0.5) expect_equal(ec$value, exact$value, tolerance = 0.01) expect_equal(ec$argument, exact$argument, tolerance = 1e-3) }) + +# data of the four candidate rates; em() of the fixture pEC with sparseFit settings +.spkECData <- local({ + times <- seq(0, 10, by = 0.5) + set.seed(2) + noisy <- function(n, v) data.frame(name = n, time = times, value = v + rnorm(length(times), 0, 0.05), + sigma = 0.05) + datalist(C1 = rbind(noisy("x", 2 - 1.5 * exp(-0.5 * times)), noisy("y", 2 * exp(-0.3 * times)))) +}) +.spkECObj <- function() withr::with_dir(.spk$dir, normL2(.spkECData, .spk$g2 * .spk$x2 * .spk$pEC)) +.spkECFit <- function(init, ...) withr::with_dir(.spk$dir, em(.spkECObj(), randomEffects(.spk$pEC), init = init, + verbose = FALSE, control = list(sparseFit = list(...)))) + +test_that("mean field selects as the exact sum", { + near <- c(x = 0.5, y = 2) + exact <- .spkShared("ec_exact", .spkECFit(near, phases = "exact")) + mf <- .spkECFit(near, phases = "meanfield") + expect_true(mf$converged) + expect_equal(mf$random$p0 > 0.5, exact$random$p0 > 0.5) + expect_equal(mf$random$p0, exact$random$p0, tolerance = 0.01) + expect_equal(mf$value, exact$value, tolerance = 1e-3) + expect_equal(mf$phases$approx, "meanfield") + # the default phases end with the exact sum + def <- .spkECFit(near) + expect_equal(def$phases$approx, c("meanfield", "ec", "exact")) + expect_equal(def$value, exact$value, tolerance = 1e-6) +}) + +test_that("from a far start EC alone fails, after a burn-in and mean field it converges", { + far <- c(x = 20, y = 20) + expect_error(.spkECFit(far, phases = "ec"), + "^em: the expectation consistent \\(EC\\) approximation of group all did not converge") + ref <- .spkECFit(c(x = 0.5, y = 2), phases = "ec") + for (start in c("spike", "slab")) { + fit <- .spkECFit(far, burnin = list(start = start), phases = list(meanfield = list(), ec = list(maxECM = 50))) + expect_true(fit$converged) + expect_equal(fit$phases$approx, c("burnin", "meanfield", "ec")) + expect_true(all(fit$phases$converged)) + expect_equal(fit$phases$value[3], fit$value) + expect_equal(fit$value, ref$value, tolerance = 1e-6) + expect_equal(fit$argument, ref$argument, tolerance = 1e-4) + expect_equal(fit$random$p0, ref$random$p0, tolerance = 1e-4) + expect_equal(unique(fit$stageTrace$phase), 1:3) + } + expect_equal(fit$burnin, ref$random$parameter) +}) + +test_that("a burn-in from a given subset, and msem() with random subsets", { + far <- c(x = 20, y = 20) + ref <- .spkECFit(c(x = 0.5, y = 2), phases = "ec") + given <- c("eta_a0_all", "eta_a1_all", "eta_b1_all") + fit <- .spkECFit(far, burnin = list(start = given), phases = c("meanfield", "ec")) + expect_equal(fit$burnin, given) + expect_equal(fit$value, ref$value, tolerance = 1e-6) + expect_error(.spkECFit(far, burnin = list(start = c("eta_a0_all", "eta_z_all"))), + "names no spike-and-slab random effect: eta_z_all") + + withr::local_dir(.spk$dir) + ctl <- list(sparseFit = list(burnin = TRUE, phases = c("meanfield", "ec"))) + run <- function() { + set.seed(3) + msem(.spkECObj(), randomEffects(.spk$pEC), far, control = ctl, fits = 4, sd = 0.3) + } + ms <- run() + tab <- ms$multistart + expect_true(all(tab$converged)) + expect_true(all(is.na(tab$phase))) + expect_true(all(unlist(strsplit(tab$subset, ",")) %in% ref$random$parameter)) + expect_gt(length(unique(tab$subset)), 1) + expect_equal(run()$multistart$subset, tab$subset) + expect_equal(ms$value, ref$value, tolerance = 1e-6) + set.seed(1) + expect_error(msem(.spkECObj(), randomEffects(.spk$pEC), far, control = list(sparseFit = list(phases = "ec")), + fits = 2, sd = 0.3, retry = FALSE), + "every fit failed.*did not converge") +}) + +test_that("burnin, phases and termBudget are checked, a failed phase is named", { + near <- c(x = 0.5, y = 2) + e <- tryCatch(.spkECFit(c(x = 20, y = 20), phases = c("ec", "exact")), error = function(e) e) + expect_s3_class(e, "dMod2PhaseError") + expect_equal(e$phase, 1L) + expect_match(conditionMessage(e), "^em: phase 1 \\(ec\\): the expectation consistent") + expect_error(.spkECFit(near, phases = c("ec", "laplace")), "`control\\$sparseFit\\$phases` names each of") + expect_error(.spkECFit(near, phases = c("ec", "ec")), "at most once") + expect_error(.spkECFit(near, phases = list(ec = list(maxECM = 0))), "`maxECM` \\(a whole number of at least 1\\)") + expect_error(.spkECFit(near, burnin = "random"), "`control\\$sparseFit\\$burnin` is FALSE, TRUE or a list") + expect_error(.spkECFit(near, burnin = list(start = "spike", iterlim = 0)), "`iterlim` \\(a whole number") + expect_error(.spkECFit(near, budget = 8), "unknown entries of `control\\$sparseFit`: budget") + expect_error(.spkECFit(near, approx = "ec"), "unknown entries of `control\\$sparseFit`: approx") + # beyond termBudget the phase "exact" is skipped after EC, and stops without it + expect_error(.spkECFit(near, phases = c("meanfield", "exact"), termBudget = 8), + "16 subsets, more than `termBudget` \\(8\\); add \"ec\"") + ec <- .spkECFit(near, phases = "ec") + skipped <- .spkECFit(near, phases = c("ec", "exact"), termBudget = 8) + expect_equal(skipped$value, ec$value, tolerance = 1e-8) + expect_equal(skipped$phases$iterations[2], 0L) + expect_true(is.na(skipped$phases$converged[2])) + expect_true(skipped$converged) +}) + +# the random effects `re` with `prob` and `tau` of every spike-and-slab term replaced: a number or NA, or a hyperprior +.spkReprior <- function(re, prob = NA, tau = NULL) { + slab <- re$terms$dist == "spikeSlab" + if (inherits(prob, "hyperprior")) { re$terms$prob[slab] <- NA; re$terms$probPrior[slab] <- list(prob) } + else re$terms$prob[slab] <- prob + if (inherits(tau, "hyperprior")) { re$terms$tau[slab] <- NA; re$terms$tauPrior[slab] <- list(tau) } + else if (!is.null(tau)) re$terms$tau[slab] <- tau + re +} +# the four candidate rates with the data of y read at sigma `sy` +.spkBetaObj <- function(sy) { + d <- .spkECData + y <- d$C1$name == "y" + d$C1$sigma[y] <- sy + set.seed(5) + if (sy > 0.05) d$C1$value[y] <- 2 * exp(-0.3 * seq(0, 10, by = 0.5)) + rnorm(sum(y), 0, sy) + withr::with_dir(.spk$dir, normL2(d, .spk$g2 * .spk$x2 * .spk$pEC)) +} +.spkBetaFit <- function(obj, random, init, ...) withr::with_dir(.spk$dir, + em(obj, random, init = init, verbose = FALSE, control = list(sparseFit = list(...)))) +# -2 log of the integral over prob in (0, 1) of the beta density times exp(-V(prob) / 2), by Gauss-Legendre +.spkOverProb <- function(V, a = 1, b = 1, n = 12) { + off <- seq_len(n - 1L) / sqrt(4 * seq_len(n - 1L)^2 - 1) + J <- matrix(0, n, n) + J[cbind(seq_len(n - 1L), 2:n)] <- J[cbind(2:n, seq_len(n - 1L))] <- off + e <- eigen(J, symmetric = TRUE) + rho <- (e$values + 1) / 2 + w <- e$vectors[1, ]^2 + v <- vapply(rho, V, 0) + min(v) - 2 * log(sum(w * stats::dbeta(rho, a, b) * exp(-(v - min(v)) / 2))) +} + +test_that("a beta prior on prob integrates the marginal of a given prob over the beta density", { + obj <- .spkBetaObj(0.05) + re <- randomEffects(.spk$pEC) + init <- c(x = 0.5, y = 2) + # -2 log L at the start, before the first M-step + value <- function(r) .spkBetaFit(obj, r, init, phases = list(exact = list(maxECM = 1)))$phases$value[1] + beta <- value(.spkReprior(re, betaPrior(2, 3))) + expect_equal(beta, .spkOverProb(function(p) value(.spkReprior(re, p)), 2, 3), tolerance = 1e-8) +}) + +test_that("the groups of a block under a beta prior are summed jointly over their count", { + withr::local_dir(.spk$dir) + obj <- normL2(.spk$two, .spk$g * .spk$x * .spk$pGrp) + re <- randomEffects(.spk$pGrp) + init <- c(x = 1, k0 = 0, k1 = log(0.5)) + value <- function(r) em(obj, r, init = init, verbose = FALSE, + control = list(sparseFit = list(phases = list(exact = list(maxECM = 1)))))$phases$value[1] + beta <- value(.spkReprior(re, betaPrior(1, 1))) + expect_equal(beta, .spkOverProb(function(p) value(.spkReprior(re, p))), tolerance = 1e-8) +}) + +test_that("where empirical Bayes takes prob to 1, a beta prior keeps it inside", { + obj <- .spkBetaObj(2) + re <- randomEffects(.spk$pEC) + init <- c(x = 0.5, y = 2) + # an M-step may end at the resolution of the parameters, with a warning of trust() + eb <- suppressWarnings(.spkBetaFit(obj, .spkReprior(re, NA), c(init, prob_all = 0.5), phases = "exact")) + beta <- .spkBetaFit(obj, .spkReprior(re, betaPrior(1, 1)), init, phases = "exact") + p0 <- function(f) setNames(f$random$p0, f$random$eta) + expect_gt(eb$slab$estimate[1], 0.999) + expect_lt(p0(eb)[["b0"]], 1e-3) + expect_lt(beta$slab$estimate[1], 0.9) + expect_gt(p0(beta)[["b0"]], 0.2) + expect_equal(beta$slab$prior[1], "Beta(1, 1), integrated") + expect_true(beta$slab$lower[1] < beta$slab$estimate[1] && beta$slab$estimate[1] < beta$slab$upper[1]) + expect_false("prob_all" %in% names(beta$argument)) +}) + +test_that("mean field and EC with a beta prior sum as the exact phase", { + re <- .spkReprior(randomEffects(.spk$pEC), betaPrior(1, 1)) + init <- c(x = 0.5, y = 2) + for (sy in c(0.05, 1)) { + obj <- .spkBetaObj(sy) + exact <- .spkBetaFit(obj, re, init, phases = "exact") + mf <- .spkBetaFit(obj, re, init, phases = "meanfield") + expect_equal(mf$random$p0, exact$random$p0, tolerance = 0.01) + expect_equal(mf$value, exact$value, tolerance = 1e-3) + } + obj <- .spkBetaObj(0.05) + ec <- .spkBetaFit(obj, re, init, phases = "ec") + exact <- .spkBetaFit(obj, re, init, phases = "exact") + expect_equal(ec$random$p0 > 0.5, exact$random$p0 > 0.5) + expect_equal(ec$value, exact$value, tolerance = 0.01) +}) + +test_that("tau under a scale prior is the posterior mode of the M-step", { + m2Q <- function(tau, num, den, prior) den * log(tau^2) + num / tau^2 + dMod2:::.spikeTauPenalty(tau, prior) + priors <- list(halfCauchyPrior(1), halfNormalPrior(0.5), invGammaPrior(2, 1)) + for (prior in priors) for (nd in list(c(3, 2), c(0.1, 3))) { + mode <- dMod2:::.spikeTauMode(nd[1], nd[2], prior, 1) + ref <- if (prior$dist == "invGamma") + sqrt(stats::optimize(function(v) m2Q(sqrt(v), nd[1], nd[2], prior), c(1e-6, 1e3), tol = 1e-12)$minimum) + else stats::optimize(function(t) m2Q(t, nd[1], nd[2], prior), c(1e-6, 1e3), tol = 1e-12)$minimum + expect_equal(mode, ref, tolerance = 1e-6) + } + + obj <- .spkBetaObj(0.05) + re <- .spkReprior(randomEffects(.spk$pEC), betaPrior(1, 1), halfCauchyPrior(1)) + fit <- .spkBetaFit(obj, re, c(x = 0.5, y = 2, tau_all = 1), phases = "exact") + expect_true(fit$converged) + tau <- fit$argument[["tau_all"]] + expect_equal(fit$hyperprior, dMod2:::.spikeTauPenalty(tau, halfCauchyPrior(1))) + expect_equal(fit$slab$prior, c("Beta(1, 1), integrated", "half-Cauchy(1), mode")) + free <- .spkBetaFit(obj, .spkReprior(randomEffects(.spk$pEC), betaPrior(1, 1), NA_real_), + c(x = 0.5, y = 2, tau_all = 1), phases = "exact") + expect_lt(tau, free$argument[["tau_all"]]) +}) + +test_that("quadrature takes a beta prior on prob and a scale prior on tau", { + withr::local_dir(.spk$dir) + obj <- normL2(.spk$counts, .spk$g * .spk$x * .spk$pSel, errmodel = .spk$err) + re <- .spkReprior(randomEffects(.spk$pSel), betaPrior(1, 1)) + fit <- function(re, init, method) em(obj, re, init = init, method = method, verbose = FALSE) + quad <- fit(re, c(x = 100), "quadrature") + expect_true(quad$converged) + # with k1 in the slab, k0 off or on: one or two of the two candidates, prior weights B(2, 2) and B(3, 1) + z1 <- .spkTensorM2logZ(obj, quad, "eta_k1_all") + z2 <- .spkTensorM2logZ(obj, quad, c("eta_k0_all", "eta_k1_all")) + p0 <- setNames(quad$random$p0, quad$random$eta) + expect_lt(abs(p0[["k0"]] - 1 / (1 + beta(3, 1) / beta(2, 2) * exp(-(z2 - z1) / 2))), 5e-3) + + reTau <- .spkReprior(randomEffects(.spk$pSel), betaPrior(1, 1), halfNormalPrior(0.5)) + tau <- fit(reTau, c(x = 100, tau_all = 0.5), "quadrature") + expect_true(tau$converged) + expect_equal(tau$hyperprior, dMod2:::.spikeTauPenalty(tau$argument[["tau_all"]], halfNormalPrior(0.5))) + free <- fit(.spkReprior(randomEffects(.spk$pSel), betaPrior(1, 1), NA_real_), c(x = 100, tau_all = 0.5), "quadrature") + expect_lt(tau$argument[["tau_all"]], free$argument[["tau_all"]]) +}) + +test_that("the phase exact integrates tau over log tau under a scale prior with integrate = TRUE", { + obj <- .spkBetaObj(0.05) + re <- randomEffects(.spk$pEC) + fx <- c(x = 0.5, y = 2) + prior <- halfCauchyPrior(1, integrate = TRUE) + fit <- withr::with_dir(.spk$dir, em(obj, .spkReprior(re, betaPrior(1, 1), prior), init = c(tau_all = 1), fixed = fx, + verbose = FALSE, control = list(sparseFit = list(phases = "exact")))) + expect_true(fit$converged) + expect_equal(fit$slab$prior[2], "half-Cauchy(1), integrated") + # the exact marginal at a given tau integrated over log tau by Simpson's rule + V <- function(tau) suppressWarnings(withr::with_dir(.spk$dir, em(obj, .spkReprior(re, betaPrior(1, 1), tau), + fixed = fx, verbose = FALSE, control = list(sparseFit = list(phases = "exact")))))$value + u <- seq(-3, 2, length.out = 31) + lf <- -(vapply(exp(u), V, 0) + vapply(exp(u), dMod2:::.spikeTauPenalty, 0, prior = prior)) / 2 + u + w <- c(1, rep(c(4, 2), length.out = length(u) - 2), 1) * diff(u)[1] / 3 + expect_equal(fit$value, -2 * (max(lf) + log(sum(w * exp(lf - max(lf))))), tolerance = 1e-4) + counts <- withr::with_dir(.spk$dir, normL2(.spk$counts, .spk$g * .spk$x * .spk$pSel, errmodel = .spk$err)) + expect_error(withr::with_dir(.spk$dir, em(counts, .spkReprior(randomEffects(.spk$pSel), 0.5, prior), + init = c(x = 100, tau_all = 1), method = "quadrature", verbose = FALSE)), + "takes the posterior mode of tau; drop `integrate = TRUE`") +}) + +test_that("SAEM, msem() and print() take the hyperpriors", { + re <- .spkReprior(randomEffects(.spk$pEC), betaPrior(1, 1)) + expect_output(print(re), "prob Beta\\(1, 1\\), integrated") + expect_output(print(spikeSlab(prob = betaPrior(2, 3), tau = halfCauchyPrior(1))), + "spikeSlab\\(prob = betaPrior\\(2, 3\\), tau = halfCauchyPrior\\(1\\)") + obj <- .spkBetaObj(2) + init <- c(x = 0.5, y = 2) + exact <- .spkBetaFit(obj, re, init, phases = "exact") + set.seed(2) + saem <- withr::with_dir(.spk$dir, em(obj, re, init = init, method = "saem", verbose = FALSE)) + expect_lt(max(abs(saem$random$p0 - exact$random$p0)), 0.1) + expect_equal(saem$value, exact$value, tolerance = 1e-3) + expect_equal(saem$slab$prior[1], "Beta(1, 1), integrated") + + set.seed(1) + ms <- suppressWarnings(withr::with_dir(.spk$dir, msem(obj, re, init, control = list(sparseFit = list(phases = "exact")), + fits = 3, sd = 0.2, keepFits = TRUE))) + expect_true(all(ms$multistart$converged)) + expect_true(all(vapply(ms$fits, function(f) !"prob_all" %in% names(f$argument), TRUE))) + expect_equal(ms$slab$prior[1], "Beta(1, 1), integrated") + + withr::local_dir(.spk$dir) + grp <- .spkReprior(randomEffects(.spk$pGrp), betaPrior(1, 1)) + expect_error(em(normL2(.spk$two, .spk$g * .spk$x * .spk$pGrp), grp, init = c(x = 1, k0 = 0, k1 = log(0.5)), + method = "saem", verbose = FALSE), + "takes betaPrior\\(\\) for spike-and-slab random effects that reach") + expect_error(spikeSlab(prob = halfCauchyPrior()), "the prior of `prob` is betaPrior") + expect_error(betaPrior(0, 1), "positive numbers") +}) diff --git a/tests/testthat/test-steadystates.R b/tests/testthat/test-steadystates.R index d396242e..03ccbf80 100644 --- a/tests/testthat/test-steadystates.R +++ b/tests/testthat/test-steadystates.R @@ -11,7 +11,7 @@ test_that("a closed cycle started in the steady state stays there", { x <- Xs(odemodel(cycle, modelname = "ssCycle", compile = FALSE)) inner <- getParameters(x) - p <- P(repar(setNames(inner, inner), "lhs<-rhs", lhs = names(ss), rhs = ss), + p <- P(insert(setNames(inner, inner), "lhs<-rhs", lhs = names(ss), rhs = ss), condition = "steady", compile = FALSE) compile(x, p, output = "ssCycle_all", cores = test_cores()) @@ -717,3 +717,49 @@ test_that("a cut does not link to a state cut before", { expect_true(all(chk$values > 0)) expect_lt(max(abs(chk$residual)), 1e-10) }) + +test_that("zeroLoops sets states produced only through one another to zero", { + withr::local_dir(tempdir()) + r <- eqnlist() |> + addReaction("", "M", "k_tx") |> addReaction("M", "", "k_dg_M*M") |> + addReaction("", "L", "k_sec*M") |> addReaction("L", "", "k_dg_L*L") |> + addReaction("L", "T", "k_act*X*L") |> addReaction("T", "", "k_dg_T*T") |> + addReaction("", "X", "k_x*T") |> addReaction("X", "", "k_dg_X*X") + ss <- steadyStates(r, zeroLoops = TRUE, verbose = FALSE) + expect_identical(unname(ss[c("T", "X")]), c("0", "0")) + expect_false(any(c("k_x", "k_act") %in% names(ss))) + chk <- .ssResidual(r, ss) + expect_lt(max(abs(chk$residual)), 1e-10) + + # by default the loop stays away from zero + ss <- steadyStates(r, verbose = FALSE) + expect_false(identical(ss, 0)) + expect_false(any(ss[c("T", "X")] == "0")) + chk <- .ssResidual(r, ss) + expect_true(all(chk$values > 0)) + expect_lt(max(abs(chk$residual)), 1e-10) +}) + +test_that("a state of a conserved quantity whose balance is left over is solved", { + # the first state of each given quantity kept free leaves the balances of Smad2 and Smad3 + withr::local_dir(tempdir()) + r <- eqnlist() |> + addReaction("", "Ra", "k_ra") |> addReaction("Ra", "", "k_dg_ra*Ra") |> + addReaction("", "Rb", "k_rb") |> addReaction("Rb", "", "k_dg_rb*Rb") |> + addReaction("Smad2", "pSmad2", "(k_p2a*Ra + k_p2b*Rb)*Smad2/(1 + Ra + Rb)") |> + addReaction("Smad3", "pSmad3", "(k_p3a*Ra + k_p3b*Rb)*Smad3/(1 + Ra + Rb)") |> + addReaction("pSmad2", "Smad2", "k_dephos2*pSmad2") |> + addReaction("pSmad3", "Smad3", "k_dephos3*pSmad3") |> + addReaction("pSmad2 + pSmad3 + Smad4", "C234", "k_form*pSmad2*pSmad3*Smad4") |> + addReaction("C234", "pSmad2 + pSmad3 + Smad4", "k_dec*C234") |> + addReaction("C234", "Smad2 + pSmad3 + Smad4", "k_dephos_C*C234") |> + addReaction("C234", "pSmad2 + Smad3 + Smad4", "k_dephos_C*C234") + cq <- c("Smad2 + pSmad2 + C234 = t2", "Smad3 + pSmad3 + C234 = t3", "Smad4 + C234 = t4") + ss <- steadyStates(r, givenCQs = cq, verbose = FALSE) + expect_false(identical(ss, 0)) + if (identical(ss, 0)) return() + expect_setequal(names(ss)[ss == names(ss)], c("pSmad2", "pSmad3", "Smad4")) + chk <- .ssResidual(r, ss) + expect_true(all(chk$values > 0)) + expect_lt(max(abs(chk$residual)), 1e-10) +}) diff --git a/tests/testthat/test-trafoDSL.R b/tests/testthat/test-trafoDSL.R index 051011c9..7be58d3f 100644 --- a/tests/testthat/test-trafoDSL.R +++ b/tests/testthat/test-trafoDSL.R @@ -27,7 +27,7 @@ test_that("identifiers may end in an underscore", { trafo <- define(trafo, "S_ <- N_ - I0_") expect_equal(insert(trafo, "gamma_ <- gamma_CA")[["gamma_"]], "gamma_CA") - expect_equal(repar(trafo, "I0_ <- I0_NY")[["S_"]], "N_ - I0_NY") + expect_equal(insert(trafo, "I0_ <- I0_NY")[["S_"]], "N_ - I0_NY") expect_equal(insert(trafo, "x <- exp(x)", x = "a__b")[["a__b"]], "exp(a__b)") }) diff --git a/vignettes/articles/dMod2.Rmd b/vignettes/articles/dMod2.Rmd index e1485a20..097d3892 100644 --- a/vignettes/articles/dMod2.Rmd +++ b/vignettes/articles/dMod2.Rmd @@ -20,7 +20,8 @@ starts and profiled. The [guide](guide-model.html) covers each step on a larger ## Data and conditions Bile acid in buffer and cells, measured with closed and opened tight junctions, one data set per -condition. +[condition]{#def-condition}. A condition, here `closed` or `open`, is one experimental setting with +own data and own model parameters. ```{r data} ``` @@ -37,8 +38,10 @@ from the canaliculi back into the buffer. ```{r reactions} ``` -`odemodel()` generates C++ code for ODE and sensitivities, `Xs()` makes the prediction function, -`Y()` the observables: cells and canaliculi are measured together, both observables with scale `s`. +`odemodel()` generates C++ code for ODE and sensitivities, `Xs()` makes the +[prediction function]{#def-prdfn} (`prdfn`) from parameters to trajectories, `Y()` the +[observation function]{#def-obsfn} (`obsfn`) from trajectories to observables: cells and canaliculi are +measured together, both observables with scale `s`. Expressions follow the [expression language of cppDE](https://dmodverse.github.io/cppDE/reference/expressions.html), including switches such as `piecewise()`. @@ -46,17 +49,25 @@ including switches such as `piecewise()`. ```{r model} ``` -`P()` maps estimated to model parameters, all on log10 scale, with an empty buffer at the start. +`P()` is a [parameter transformation]{#def-parfn} (`parfn`). It maps the +[outer parameters]{#def-outer-parameters}, which the optimizer sees (`K_IMPORT`, `S`, ... on log10 +scale), to the [inner parameters]{#def-inner-parameters} of ODE and observables in one condition +(`k_import`, `s`, ...), with an empty buffer at the start. `branch()` makes one transformation per condition, open junctions with a separate reflux rate `K_REFLUX_OPEN`. All three function objects compile into one shared object. ```{r trafo} ``` +`+` and `branch()` join conditions; `*` composes function objects by the chain rule, so every +call returns values with their derivatives in the outer parameters, the objective value, gradient +and Hessian. + ## Likelihood, prior and fit -`normL2()` returns $-2 \log L$ of the data; a weak prior from `constraintL2()` keeps parameters -the data do not determine finite. +`normL2()` returns an [objective function]{#def-objfn} (`objfn`), here $-2 \log L$ of the data; a +weak prior from `constraintL2()` keeps parameters the data do not determine finite, and the sum is +$-2 \log$ of the posterior. ```{r objective} ``` @@ -111,20 +122,4 @@ systematically; the [bile acid project](bileAcidTransport.html) fixes the scale, canaliculi in steady state and goes on to prediction bands. `K_EXPORT_SINUS` and `K_REFLUX_OPEN` are bounded on one side only, a practical non-identifiability. -## Terminology - -| term | meaning | -|---|---| -| outer parameters | parameters the optimizer sees, here `K_IMPORT`, `S`, ... on log10 scale | -| inner parameters | parameters of ODE and observables in one condition, here `k_import`, `s`, ... | -| condition | one experimental setting with own data and inner parameters, here `closed`, `open` | -| `parfn` | parameter transformation, outer to inner: `P()`, `Pexpl()`, `Pimpl()` | -| `prdfn` | prediction function, parameters to trajectories: `Xs()`, `Xf()` | -| `obsfn` | observation function, trajectories to observables or errors: `Y()` | -| `objfn` | objective function, $-2 \log L$ or with a prior $-2 \log$ of the posterior: `normL2()`, `constraintL2()` | - -`+` and `branch()` join conditions; `*` composes function objects by the chain rule, so every -call returns values with their derivatives in the outer parameters, the objective value, gradient -and Hessian. - [1. Setting up models →](guide-model.html) diff --git a/vignettes/articles/guide-alignment.Rmd b/vignettes/articles/guide-alignment.Rmd index f1e55505..e089f685 100644 --- a/vignettes/articles/guide-alignment.Rmd +++ b/vignettes/articles/guide-alignment.Rmd @@ -15,7 +15,7 @@ saved <- stored("results/guide-alignment.rds", "results/guide-alignment.R", envi ``` Western blots, plate readers and similar assays read on experiment-specific scales. -`alignmentModel()` and `align()` bring all experiments onto one common scale by maximum likelihood, +`alignmentModel()` and `align()` bring all experiments onto one common scale by [maximum likelihood](methods-objective.html#def-maximum-likelihood), with the reading model written as an expression, as in the R package [blotIt](https://github.com/JetiLab/blotIt). @@ -37,7 +37,7 @@ three lanes. Simulated: 20 % biological variability per sample, exposure and bac ## Alignment model -A reading is value `yi` times gel scale `sj` plus background `bj`, with relative error. Each +A reading is value `yi` times gel scale `sj` plus background `bj`, with [relative error](methods-objective.html#def-relative-error). Each symbol is a linear predictor over the data columns, on log scale. `technical = "lane"` averages the lanes of a sample, see [technical and biological replicates](#technical-and-biological-replicates). @@ -49,7 +49,7 @@ The geometric mean of the values is held at 1 within each block of experiments s ## Fit by restricted likelihood -`align()` fits from several perturbed starts and keeps the best; error parameters by restricted +`align()` fits from several perturbed starts and keeps the best; [error parameters](methods-objective.html#def-error-parameters) by restricted maximum likelihood. The fits of this chapter are loaded from `results/guide-alignment.rds`, computed by `results/guide-alignment.R`. @@ -95,7 +95,7 @@ ggplot(fit$aligned, aes(time, value)) + Technical replicates (lanes, wells) measure the same sample and share the biological deviation of that sample. `technical = "lane"` averages them before the alignment; readings agreeing in all columns but `value`, `lloq` and the technical columns form one sample. The mean is geometric for a -relative error model, arithmetic for an absolute one. The same data with every lane as a reading: +relative [error model](methods-objective.html#def-error-model), arithmetic for an absolute one. The same data with every lane as a reading: ```{r lanes, eval = FALSE} ``` @@ -120,8 +120,8 @@ The lane fit reports standard errors smaller by about $\sqrt{3}$; the errors rea ## Random background per gel -A random effect per gel around a common background, integrated by FOCEI as in -[Nonlinear mixed-effects models](guide-nlme.html). A prior on `omega_bj_bj`, the log standard +A [random effect](methods-nlme.html#def-random-effect) per gel around a common background, integrated by [FOCEI](methods-nlme.html#def-focei) as in +[Nonlinear mixed-effects models](guide-nlme.html). A [prior](methods-objective.html#def-prior) on `omega_bj_bj`, the log standard deviation, normal around $\log 0.3$ with standard deviation 0.3: ```{r background, eval = FALSE} @@ -169,7 +169,7 @@ sample in two wells. 36 - Ct is the log2 concentration in arbitrary units; a wel ### qPCR data -Column `lloq` holds the limit of each reading; an `NA` reading is censored there. Standard +Column `lloq` holds the limit of each reading; an `NA` reading is censored there, known only to lie below the limit. Standard deviation 0.5 cycles between samples, 0.25 between wells. ```{r qpcrdata} @@ -308,8 +308,8 @@ plotResiduals(fit) ### Random background -Standard deviation of the log2 background between gels, and per gel the mode with conditional -standard error: +Standard deviation of the log2 background between gels, and per gel the [mode](methods-sparsity-priors.html#def-mode) with [conditional +standard error](methods-nlme.html#def-conditional-standard-error): ```{r} fit$omega @@ -323,13 +323,13 @@ not depend on the modes. fit$fit$shrinkage ``` -Conditional draws against the estimated normal: +Conditional draws from the [posterior](methods-nlme.html#def-posterior) against the estimated normal: ```{r fig.height = 5} plotRandomEffects(fit$fit) ``` -Individual (IPRED) and population prediction (PRED): +Individual (IPRED) and population prediction (PRED), as in [Model diagnostics](guide-nlme.html#model-diagnostics): ```{r fig.height = 3.5} plot(fit$fit) + theme(legend.position = "right") + labs(color = "gel") diff --git a/vignettes/articles/guide-model.Rmd b/vignettes/articles/guide-model.Rmd index bdc25d79..117da5e3 100644 --- a/vignettes/articles/guide-model.Rmd +++ b/vignettes/articles/guide-model.Rmd @@ -14,28 +14,31 @@ source("results/stored.R") knitr::read_chunk("../../examples/oppeltNPJSystBiolAppl2018/model.R") ``` -A model in dMod2 is a chain of function objects, each returning output and derivatives: +A model in dMod2 is a [chain of function objects](methods-sensitivities.html#def-chain-gxp), each returning output and derivatives: | class | constructors | mapping | |---|---|---| -| `parfn` | `P()`, `Pexpl()`, `Pimpl()` | outer to inner parameters, or to a steady state | -| `prdfn` | `Xs()`, `Xf()` | parameters to trajectories, with (`Xs()`) or without sensitivities | -| `obsfn` | `Y()` | states to observables, observables to standard deviations | -| `objfn` | `normL2()`, `constraintL2()`, `datapointL2()`, `constraintStability()` | $-2 \log L$ | +| `parfn` | `P()`, `Pexpl()`, `Pimpl()` | outer to inner parameters, or to a [steady state](methods-steady-states.html#def-steady-state) | +| `prdfn` | `Xs()`, `Xf()` | parameters to trajectories, with (`Xs()`) or without [sensitivities](methods-sensitivities.html#def-sensitivity) | +| `obsfn` | `Y()` | states to observables, observables to standard deviations ([error model](methods-objective.html#def-error-model)) | +| `objfn` | `normL2()`, `constraintL2()`, `datapointL2()`, `constraintStability()` | [$-2 \log L$](methods-objective.html#def-minus-2-log-l) | `*` concatenates by the chain rule, $$\frac{\partial y}{\partial \theta} = \frac{\partial g}{\partial x}\,\frac{\partial x}{\partial p}\, \frac{\partial p}{\partial \theta},$$ -each factor exact, the middle one from the sensitivity equations; `+` adds objectives. +each factor exact, the middle one from the +[sensitivity equations](methods-sensitivities.html#forward-sensitivities); `+` adds +[objectives](methods-profiles.html#def-objective). `normL2(data, g*x*pSS*p, e)` is the objective. Inner parameters are the symbols of the equations, per condition; outer parameters are those of the fit. The guide uses the model of Oppelt et al. [@oppelt2018model], NFκB signaling in HepG2 cells after TNFα, from the project [`examples/oppeltNPJSystBiolAppl2018`](https://github.com/dModverse/dMod2/tree/master/examples/oppeltNPJSystBiolAppl2018). -This chapter follows `model.R`. Multistarts, profiles and other expensive results were computed +This chapter follows `model.R`. Multistarts, +[profiles](methods-profiles.html#def-profile) and other expensive results were computed once by the scripts of the project and are stored in `results/*.rds`; the chapters load them with `stored()`, which warns if a source script changed since. @@ -53,7 +56,7 @@ educts (of the products without net educts): $$\dot x_i = \frac{1}{V_i} \sum_r S_{ri}\, V_{c(r)}\, v_r(x, p),$$ -with $S_{ri}$ the stoichiometry and $V_{c(r)}$ the volume of the compartment of reaction $r$. +with $S_{ri}$ the [stoichiometry](methods-steady-states.html#def-stoichiometry) and $V_{c(r)}$ the volume of the compartment of reaction $r$. ```{r reactions, echo = FALSE} ``` @@ -114,14 +117,15 @@ estimated one. Rows with a value in `sigma` ignore the error model. ## Steady-state constraints -NFκB and IKK are conserved, so $f(x, p) = 0$ determines the resting state only with the totals: +NFκB and IKK are [conserved](methods-steady-states.html#conserved-quantities), so $f(x, p) = 0$ +determines the [resting state](methods-steady-states.html#def-resting-state) only with the totals: ```{r} conservedQuantities(reactions) ``` `Pimpl()` solves the steady state numerically, with the totals `totalNfk` and `totalIkk` as -parameters, `TNF` at 0, and exact derivatives of the root +parameters, `TNF` at 0, and exact derivatives of the [root](methods-steady-states.html#def-root) ([Methods > Steady states](methods-steady-states.html)). `steadyStates()` is the analytic alternative. @@ -143,9 +147,12 @@ exact sensitivities ```{r odemodel} ``` -The backend `"cppDE"` (default) integrates by BDF, `"Sundials"` uses CVODES, `"deSolve"` deSolve. -A step is accepted if -$\bigl(\tfrac1n \sum_i \varepsilon_i^2 / (\mathrm{atol} + \mathrm{rtol}\,|x_i|)^2\bigr)^{1/2} \le 1$: +The backend `"cppDE"` (default) integrates by +[BDF](https://dmodverse.github.io/cppDE/articles/methods-stepping.html), `"Sundials"` uses CVODES, +`"deSolve"` deSolve. A step is accepted if the error test holds +for the local error estimates $\varepsilon_i$, + +$$\Bigl(\frac1n \sum_i \frac{\varepsilon_i^2}{(\mathrm{atol} + \mathrm{rtol}\,|x_i|)^2}\Bigr)^{1/2} \le 1 :$$ | option | default | controls | |---|---|---| @@ -204,9 +211,10 @@ length(getParameters(prd)) ## Likelihood and prior -`normL2(data, prd, e)` returns $-2 \log L$ with gradient and Gauss-Newton Hessian -([Methods > Likelihood and prior](methods-objective.html)). `constraintL2()` adds a Gaussian prior -on the log scale, also the start distribution of [Optimization](guide-optimization.html): mean 0 +`normL2(data, prd, e)` returns $-2 \log L$ with gradient and +[Gauss-Newton Hessian](methods-sensitivities.html#gauss-newton-with-an-error-model) +([Methods > Likelihood and prior](methods-objective.html)). `constraintL2()` adds a Gaussian +[prior](methods-objective.html#def-prior) on the log scale, also the start distribution of [Optimization](guide-optimization.html): mean 0 and standard deviation 4 by default, narrower where the magnitude is known: | parameters | mean | sd | reason | @@ -218,8 +226,8 @@ and standard deviation 4 by default, narrower where the magnitude is known: | `trigger_iIkk` | $\log(1/240)$ | 2 | IKK recovers over hours | `pSS` also returns unstable roots (`controlsPTC = list(stability = FALSE)`); -`constraintStability()` is zero on a stable resting state and reaches 100 per eigenvalue at the -stability boundary, and needs `Pimpl(derivMode = "forward-forward")` +`constraintStability()` is zero on a stable resting state and reaches 100 per +eigenvalue at the stability boundary, and needs `Pimpl(derivMode = "forward-forward")` ([Methods > Steady states](methods-steady-states.html#stability)). ```{r objective} @@ -234,7 +242,8 @@ stability boundary, and needs `Pimpl(derivMode = "forward-forward")` invisible(stored("results/fits.rds", "fit.R")) ``` -The best fit of [Optimization](guide-optimization.html), with the gauge of +The best fit of [Optimization](guide-optimization.html), with the +[gauge](methods-symmetries.html#def-gauge) of [Symmetries](guide-symmetries.html): ```{r gauge, echo = FALSE} diff --git a/vignettes/articles/guide-nlme.Rmd b/vignettes/articles/guide-nlme.Rmd index a72785c3..c6f5522e 100644 --- a/vignettes/articles/guide-nlme.Rmd +++ b/vignettes/articles/guide-nlme.Rmd @@ -15,7 +15,7 @@ do.call(knitr::read_chunk, list(file.path("results", "guide-nlme.R"))) ``` A mixed-effects model writes each individual parameter as a population value plus a random -deviation and integrates the deviations out of the likelihood. Random effects are declared in the +deviation and integrates the deviations out of the [likelihood](methods-objective.html#def-likelihood). [Random effects](methods-nlme.html#def-random-effect) are declared in the `parfn`; `em()` fits the model. Example: theophylline, twelve subjects, one oral dose each. ```{r setup} @@ -61,28 +61,28 @@ The formula acts after the log transformation: $\log \mathrm{Cl}_i = \mathrm{Cl} Further forms: - `Cl ~ 1 + (1 | ID)`: random intercept per subject. -- `Cl ~ 1 + logWeight + (1 | ID)`: a covariate, fixed effect `Cl_logWeight` on a table column. +- `Cl ~ 1 + logWeight + (1 | ID)`: a covariate, [fixed effect](methods-nlme.html#def-fixed-effect) `Cl_logWeight` on a table column. - `Ka + Cl ~ 1 + (1 | p | ID)`: random effects of `Ka` and `Cl` correlated (same ID `p`). - `Cl ~ 1 + wt + (1 + dose | p | ID)`: a covariate and a random slope, correlated with the intercept. - `Cl ~ 1 + (1 | ID) + (1 | ID:OCC)`: variability between subjects and between occasions. -- `Cl ~ 1 + (1 | gr(ID, dist = spikeSlab()))`: spike-and-slab instead of normal random effects. +- `Cl ~ 1 + (1 | gr(ID, dist = spikeSlab()))`: [spike-and-slab](methods-nlme.html#def-spike-and-slab) instead of normal random effects. -Conditions of one group share the group random effects. The random effects of one ID form a block +Conditions of one [group](methods-nlme.html#def-group) share the group random effects. The random effects of one ID form a [block](methods-nlme.html#def-block) with full covariance; `omega__` are the entries of the Cholesky factor of the block, with the log of the diagonal. Spike-and-slab and Dirichlet-process random effects: [Sparse deviations](guide-sparse-deviations.html). ## Marginal likelihood -`em()` maximizes the likelihood of fixed effects, $\Omega$ and error parameters with the random +`em()` maximizes the marginal likelihood of fixed effects, $\Omega$ and [error parameters](methods-objective.html#def-error-parameters) with the random effects integrated out. It takes `normL2(data, g * x * p, errmodel = e)`, or `normT(..., df = 4)` for Student-t residuals, and builds the prior from `randomEffects(p)`. `method`: | method | use | reported $-2 \log L$ | |---|---|---| -| `"focei"` | default, fast, Laplace's approximation at the modes | Laplace | -| `"quadrature"` | skewed posteriors, few random effects per group | quadrature | +| `"focei"` | default, fast, Laplace's approximation at the [modes](methods-sparsity-priors.html#def-mode) | Laplace | +| `"quadrature"` | skewed [posteriors](methods-nlme.html#def-posterior), few random effects per group | quadrature | | `"laplaceEM"` | EM on the Laplace approximation | quadrature of level $K + 2$ | | `"saem"` | many random effects per group, non-Gaussian posteriors | quadrature of level $K + 2$ | @@ -121,7 +121,7 @@ summary(fit) `omega_*` are log standard deviations here. Shrinkage near 1 means the data of a subject hardly move the individual parameter. -`value` is $-2 \log L$; `valueNonmem` compares with the NONMEM `OBJ` (`NA` for `normT()`). The fit +`value` is [$-2 \log L$](methods-nlme.html#def-minus-2-log-l); `valueNonmem` compares with the NONMEM `OBJ` (`NA` for `normT()`). The fit holds `Omega`, `omega`, `random`, `etaModes`, `etaSE` and `shrinkage`. Methods: `coef()`, `vcov()`, `confint()` (Wald or `method = "profile"`), `logLik()`, `AIC()`, `BIC()`, `anova()`, `predict()`, `residuals()`, `simulate()` and the plots below. @@ -131,9 +131,9 @@ holds `Omega`, `omega`, `random`, `etaModes`, `etaSE` and `shrinkage`. Methods: | entry of `control` | default | controls | |---|---|---| | `sd` | `0.3` | start of standard deviations not in `init` | -| `innerControl` | `rinit = 1`, `rmax = 10`, `iterlim = 30`, `steptol = 1e-8`, `mtol = 1e-12` | trust region of the modes | +| `innerControl` | `rinit = 1`, `rmax = 10`, `iterlim = 30`, `steptol = 1e-8`, `mtol = 1e-12` | [trust region](methods-trust.html#def-trust-region) of the modes | | `trustControl` | `rinit = 1`, `rmax = 10`, `iterlim = 200`, `ftol = 1e-7`, `mtol = 1e-5` | trust region of population parameters | -| `derivMode` | `"forward-reverse"` | volume-term second derivatives, or `"forward-forward"` | +| `derivMode` | `"forward-reverse"` | [volume-term](methods-nlme.html#volume-term) second derivatives, or `"forward-forward"` | | `secondOrderCorrection` | `TRUE` | derivative of the volume term | `"forward-forward"` needs models built with `derivMode = "forward-forward"`. @@ -144,8 +144,8 @@ holds `Omega`, `omega`, `random`, `etaModes`, `etaSE` and `shrinkage`. Methods: ## Adaptive sparse-grid quadrature -`method = "quadrature"` starts from the FOCEI fit and integrates on a sparse grid around each group -mode; level $K$ is Laplace's approximation. A certificate flags groups whose posterior the grid +`method = "quadrature"` starts from the FOCEI fit and integrates on a [sparse grid](methods-nlme.html#def-sparse-grid) around each group +mode; [level](methods-nlme.html#def-level) $K$ is Laplace's approximation. A certificate flags groups whose posterior the grid does not resolve. [Methods > Adaptive sparse-grid quadrature](methods-nlme.html#adaptive-sparse-grid-quadrature). @@ -154,8 +154,8 @@ quadrature](methods-nlme.html#adaptive-sparse-grid-quadrature). | `tol` | `0.1` | allowed change of $-2 \log L$ by the next level, split over groups; `Inf` keeps stage levels | | `levels` | `K + 1` | stages; level `K + s` is exact for total degree `2 s + 1` | | `maxLevel` | `K + 8` | highest level | -| `tolDecrement` | `1e-4` | Newton decrement that ends a stage | -| `maxEcmPerStage` | `10` | rebuilds per stage | +| `tolDecrement` | `1e-4` | [Newton decrement](methods-nlme.html#def-newton-decrement) that ends a stage | +| `maxECMPerStage` | `10` | rebuilds per stage | | `cm1Control`, `maxCm1Iter` | `rinit = 1`, `ftol = mtol = 1e-8`; `30` | `trust()` settings and iterations of a step | | `pruneTol` | `Inf` | drop nodes with log weight this far below the largest | | `certificate` | `points = 256`, `seed = 1` | importance-sampling check, `FALSE` skips | @@ -166,8 +166,8 @@ The fit holds `stageTrace`, `etaCov` (posterior covariance per group) and `certi ## Laplace EM `method = "laplaceEM"`: expectation conditional maximization on the Laplace approximation, -reporting the quadrature of level $K + 2$, without certificate. `control$quadrature` takes `epsEcm` -(default `1e-5`), `maxEcm` (default 200) and `cm1Control`, `maxCm1Iter`, `pruneTol`, `maxLevel`. +reporting the quadrature of level $K + 2$, without certificate. `control$quadrature` takes `epsECM` +(default `1e-5`), `maxECM` (default 200) and `cm1Control`, `maxCm1Iter`, `pruneTol`, `maxLevel`. [Methods > Laplace EM](methods-nlme.html#laplace-em). ## Stochastic approximation EM (SAEM) @@ -231,7 +231,8 @@ distribution errors (NPDE) come from simulations. Both should be standard normal plotResiduals(fit, type = c("CWRES", "NPDE"), nsim = 200, seed = 1) ``` -Visual predictive check: +Visual predictive check, the 5th, 50th and 95th percentiles of the readings per time bin against +the prediction intervals of the same percentiles of data simulated from the fit: ```{r, fig.height = 3.5} plotVPC(fit, nsim = 200, bins = 8, seed = 1) diff --git a/vignettes/articles/guide-optimization.Rmd b/vignettes/articles/guide-optimization.Rmd index 6b56ac28..e8e7fcb1 100644 --- a/vignettes/articles/guide-optimization.Rmd +++ b/vignettes/articles/guide-optimization.Rmd @@ -17,9 +17,11 @@ knitr::read_chunk("../../examples/oppeltNPJSystBiolAppl2018/onefit.R") knitr::read_chunk("../../examples/oppeltNPJSystBiolAppl2018/plots.R") ``` -dMod2 [@kaschek2019dmod] minimizes $-2 \log L$ (with a prior, $-2 \log$ of the posterior) by the -trust-region method `trust()`, from many starts by `mstrust()`, here on the model of -[Setting up models](guide-model.html) with the gauge of [Symmetries](guide-symmetries.html). +dMod2 [@kaschek2019dmod] minimizes $-2 \log L$ (with a [prior](methods-objective.html#prior), +$-2 \log$ of the posterior) by the [trust-region method](methods-trust.html#trust-region-method) +`trust()`, from many starts by `mstrust()`, here on the model of +[Setting up models](guide-model.html) with the [gauge](methods-symmetries.html#def-gauge) of +[Symmetries](guide-symmetries.html). Derivations: [Methods > Trust-region optimization](methods-trust.html). ```{r setup, echo = FALSE} @@ -60,14 +62,17 @@ Derivations: [Methods > Trust-region optimization](methods-trust.html). ## Trust-region method -Each iteration minimizes a quadratic model inside a ball of radius $r$, first `rinit`; the ratio -of actual to predicted decrease decides on step and radius. A trial point where the objective fails -counts as rejected. `stepControl$nonmonotone` in $(0, 1)$ also accepts rising steps and returns the -best iterate. +Each iteration minimizes a [quadratic model](methods-trust.html#def-quadratic-model) inside a ball of +[radius](methods-trust.html#def-radius) $r$, first `rinit`; the +[ratio of actual to predicted decrease](methods-trust.html#radius-update) decides on step and radius. A trial +point where the objective fails counts as rejected. `stepControl$nonmonotone` in +$(0, 1)$ also accepts rising steps ([nonmonotone acceptance](methods-trust.html#nonmonotone-acceptance)) and +returns the best iterate. -`parlower` and `parupper` set bounds. `boundary = "reflective"` (default) keeps the iterates -strictly inside and lists bound parameters in `atBound`; `boundary = "clip"` removes them from the -subproblem and runs Gauss-Newton only, with `ftol` and `mtol`. +`parlower` and `parupper` set [bounds](methods-trust.html#bound-constraints). `boundary = "reflective"` +(default) keeps the iterates strictly inside and lists bound parameters in `atBound`; +`boundary = "clip"` removes them from the [subproblem](methods-trust.html#def-subproblem) and runs +[Gauss-Newton](methods-trust.html#gauss-newton-approximation) only, with `ftol` and `mtol`. ### Termination criteria @@ -94,15 +99,16 @@ as `tolControl`. | `hessianMethod` | model Hessian | the objective returns | |---|---|---| | `"gn"` | Gauss-Newton | value, gradient, Gauss-Newton Hessian | -| `"exact"` | exact (Newton) | value, gradient, exact Hessian | -| `"bfgs"` | damped BFGS update, positive definite | value, gradient | -| `"sr1"` | symmetric rank-one update, possibly indefinite | value, gradient | +| `"exact"` | exact ([Newton](methods-trust.html#exact-hessian)) | value, gradient, exact Hessian | +| `"bfgs"` | damped [BFGS update](methods-trust.html#bfgs-update), positive definite | value, gradient | +| `"sr1"` | [symmetric rank-one update](methods-trust.html#sr1-update), possibly indefinite | value, gradient | The default is the hybrid of Fides [@froehlich2022fides]: Gauss-Newton until the radius stayed the same for 20 iterations, then BFGS ([Methods > Hessian phases](methods-trust.html#hessian-phases)). -The sparse path, multiple shooting and `boundary = "clip"` run Gauss-Newton. With an error model the -Gauss-Newton Hessian can be indefinite +The [sparse path](methods-trust.html#sparse-hessians), [multiple shooting](methods-multiple-shooting.html#def-multiple-shooting) +and `boundary = "clip"` run Gauss-Newton. With an [error model](methods-objective.html#error-model) +the Gauss-Newton Hessian can be indefinite ([Methods > Gauss-Newton with an error model](methods-sensitivities.html#gauss-newton-with-an-error-model)). `"exact"` needs a chain built with `derivMode = "forward-forward"` or `"forward-reverse"` ([Sensitivities](guide-sensitivities.html)). @@ -110,15 +116,15 @@ Quasi-Newton settings, entries of `qnControl`: | entry | default | controls | |---|---|---| -| `hessianInit` | `"gn"` | seed: `"gn"`, `"identity"`, `"exact"`, or `"tracked"` (later phases) | +| `hessianInit` | `"gn"` | [seed](methods-trust.html#seed-and-memory): `"gn"`, `"identity"`, `"exact"`, or `"tracked"` (later phases) | | `hessianReseed` | `"never"` | `"stall"`: reseed instead of stopping on stagnation, up to 8 times | | `qnMemory` | `0` | `0` accumulates all updates; $m > 0$ rebuilds from the last $m$ pairs | -| `qnCautious` | `1e-8` | cautious test of BFGS; `0` turns it off | +| `qnCautious` | `1e-8` | [cautious test](methods-trust.html#def-cautious-test) of BFGS; `0` turns it off | | `qnRejected` | `TRUE` for `"sr1"` | SR1 also updates from rejected trial points | ### Hessian phases and reverse sweep -`phases` runs several sources in turn, each a list with `hessianMethod` and optionally `iterlim`, +`phases` runs several sources in turn ([Hessian phases](methods-trust.html#hessian-phases)), each a list with `hessianMethod` and optionally `iterlim`, `radiusStall`, `sweep`, `keepRadius`, `onStop` and `qnControl`. A phase hands over on a stop other than `"gradient"`, on `iterlim` or after `radiusStall` iterations at one radius; `switches` bounds the handovers. @@ -129,14 +135,16 @@ fit <- trust(obj, best, fixed = gauge, tolControl = tolerances, fit[c("phaseIterations", "evalBySource", "nSwitch", "stopReason")] ``` -`sweep = "reverse"` computes the gradient of a quasi-Newton phase by one backward sweep, for models +`sweep = "reverse"` computes the gradient of a quasi-Newton phase by one +[backward sweep](methods-sensitivities.html#reverse-sweep), for models built with `derivMode = c("forward", "reverse")`; a `"bfgs"` or `"sr1"` phase does so by default. ### Sparse Hessians -`sparse = TRUE` uses sparse Cholesky factors, plus a low-rank part, for many parameters that each -act on few conditions; it reaches the same fit as the dense path. `"auto"` (default) takes it from -100 parameters on where it costs fewer flops (`options(dMod2.sparseAuto = )`). +`sparse = TRUE` uses sparse Cholesky factors, plus a [low-rank part](methods-trust.html#def-low-rank-part), +for many parameters that each act on few conditions; it reaches the same fit as the dense path. +`"auto"` (default) takes it from 100 parameters on where it costs fewer flops +(`options(dMod2.sparseAuto = )`). ### Arguments and result @@ -176,7 +184,8 @@ fit[c("value", "converged", "iterations", "stopReason")] ## Multistart fitting -`mstrust()` fits from many starts; `as.parframe()` sorts the fits by value. `fit.R` draws 200 +`mstrust()` fits from many starts (multistart); `as.parframe()` sorts the fits by +value. `fit.R` draws 200 starts from the prior of [Setting up models](guide-model.html#likelihood-and-prior): ```{r multistart, eval = FALSE} @@ -212,7 +221,7 @@ c(fits = nrow(fits), converged = sum(fits$converged), best = min(fits$value), withinOne = sum(fits$value < min(fits$value) + 1)) ``` -Sorted values; each plateau is a local optimum: +Sorted values; each [plateau](methods-trust.html#def-plateau) is a local optimum: ```{r waterfall, fig.height = 3.5} ``` @@ -255,13 +264,15 @@ t(rbind(converged = tapply(opt$converged, method, sum), tapply(opt$value < top + 5, method, sum, na.rm = TRUE)))) ``` -The exact Hessian converges most often, scaled SR1 reaches the best plateaus most often, and +The exact Hessian converges most often, scaled SR1 +([structured secant updates](methods-trust.html#structured-secant-updates)) reaches the best plateaus most often, and Gauss-Newton followed by BFGS on the reverse gradient needs the least time per hit. Details: [Methods > Forward and reverse derivatives on the Oppelt fit](methods-trust.html#forward-and-reverse-derivatives-on-the-oppelt-fit). ## L1 penalties -`trustL1()` adds $\sum_i \lambda_i \lvert \theta_i - \mu_i \rvert$ for the parameters named in +`trustL1()` adds the L1 penalty $\sum_i \lambda_i \lvert \theta_i - \mu_i \rvert$ +for the parameters named in `mu`; a scan over `lambda` selects the parameters that differ from the reference. `one.sided`, `gate` and `fuse` vary the penalty ([Methods > L1 penalties](methods-trust.html#l1-penalties)). diff --git a/vignettes/articles/guide-petab.Rmd b/vignettes/articles/guide-petab.Rmd index d3e40043..d8552275 100644 --- a/vignettes/articles/guide-petab.Rmd +++ b/vignettes/articles/guide-petab.Rmd @@ -53,16 +53,18 @@ prd <- g * x * pSS * p ## PEtab export -`exportPEtab()` writes reactions as SBML, observables, errors, data, and the transformation `p` -with fixed values and values per condition. PEtab 2, the default, has no parameter scales: values -of parameters entering as `exp()` are written on linear scale, with a warning. The gauge of +`exportPEtab()` writes reactions as SBML, observables, errors, data, and the +[parameter transformation](methods-steady-states.html#def-parameter-transformation) `p` with fixed values and values per condition. PEtab 2, the default, has no parameter scales: values +of parameters entering as `exp()` are written on linear scale, with a warning. The [gauge](methods-symmetries.html#def-gauge) of [Symmetries](guide-symmetries.html) becomes fixed values. -- **State at rest.** `steadyState = pSS` gives a pre-equilibration before time 0, shared by both - conditions. One species per conserved total starts at the total (`NfkIkb`, `Ikk`), all others +- **State at rest.** `steadyState = pSS` gives a pre-equilibration, a + [steady state](methods-steady-states.html#def-steady-state) before time 0, shared by both + conditions. One species per + [conserved total](methods-steady-states.html#conserved-quantities) starts at the total (`NfkIkb`, `Ikk`), all others at 0. -- **Event.** `events = events` writes the event at time 0 as the `TNF` value of the condition. -- **Errors.** Imaging readouts get the error model, blots the data standard deviations as noise +- **Event.** `events = events` writes the [event](methods-sensitivities.html#def-event) at time 0 as the `TNF` value of the condition. +- **Errors.** Imaging readouts get the [error model](methods-objective.html#def-error-model), blots the data standard deviations as noise parameters per measurement. ```{r, include = FALSE} @@ -82,7 +84,7 @@ read.delim("results/petab/conditions_oppelt.tsv") ## PEtab import -`importPEtab()` builds `prdfn`, the `obsfn`s of observables and errors, the `parfn`, data and +`importPEtab()` builds `prdfn`, the [`obsfn`s](methods-objective.html#def-obsfn) of observables and errors, the `parfn`, data and `objfn`; a pre-equilibration becomes a `Pimpl()`. With `compile = FALSE`, `compile()` builds the sources. @@ -100,13 +102,14 @@ compile(g, x, pSS, p, e, petab$prd, petab$e, output = "oppelt_petab_guide", core ```{r petabcompare} ``` -The imported problem reproduces the data term of `model.R` at the best fit. `petab$bestfit` holds +The imported problem reproduces the [data term](methods-objective.html#data-term) of `model.R` at the best fit. `petab$bestfit` holds the nominal values on the problem scales, `petab$parlower` and `petab$parupper` the bounds. ## SBML models `exportSbml()` writes species with compartments, reactions, parameters and initial assignments; -concentration rates are multiplied by the compartment volume, `importSbml()` divides again. +concentration rates are multiplied by the +[compartment volume](methods-steady-states.html#def-compartment-volume), `importSbml()` divides again. `importSbml()` returns the equation list in `reactions`, parameter and initial values, observables, assignment rules and events: diff --git a/vignettes/articles/guide-prediction-uncertainty.Rmd b/vignettes/articles/guide-prediction-uncertainty.Rmd index a69ffea2..6cc5819f 100644 --- a/vignettes/articles/guide-prediction-uncertainty.Rmd +++ b/vignettes/articles/guide-prediction-uncertainty.Rmd @@ -18,7 +18,7 @@ inWords <- function(n) if (n %in% 1:12) c("one", "two", "three", "four", "five", "eight", "nine", "ten", "eleven", "twelve")[n] else format(n) ``` -The prediction profile likelihood [@kreutz2012likelihood] gives the confidence band of a +The [prediction profile likelihood](methods-profiles.html#def-prediction-profile-likelihood) [@kreutz2012likelihood] gives the confidence band of a prediction, here of unmeasured nuclear IκBα after TNFα [@oppelt2018model, Fig. 5] in the reduced model of [Profile likelihood](guide-profiles.html). Code: `prediction.R`. @@ -76,10 +76,10 @@ prdReduced <- gReduced * xReduced * pReduced ## Prediction profiles and validation data points -`datapointL2()` ties a parameter `v` to the prediction by a validation data point of small -standard deviation; the profile of `v` is the prediction profile, and the values within the -$\chi^2_1$ threshold form the confidence interval. `attrName = "data"` adds the validation term to -the data term, so `stop = "data"` and `confint(val.column = "data")` leave the prior out +`datapointL2()` ties a parameter `v` to the prediction by a [validation data point](methods-profiles.html#def-validation-data-point) of small +standard deviation; the [profile](methods-profiles.html#def-profile) of `v` is the prediction profile, and the values within the +$\chi^2_1$ threshold form the [confidence interval](methods-profiles.html#def-confidence-interval). `attrName = "data"` adds the validation term to +the [data term](methods-profiles.html#def-data-term), so `stop = "data"` and `confint(val.column = "data")` leave the [prior](methods-objective.html#prior) out ([Methods > Prediction profiles](methods-profiles.html#prediction-profiles)). ## Prediction band @@ -98,7 +98,7 @@ decades <- log10(range(band$value[band$value > 0])) `prediction.R` computes the profile at `r nrow(band)` times of the stimulated condition, from 2 minutes on; the results are loaded from `results/prediction.rds`. The prediction spans `r inWords(floor(diff(decades)))` orders of magnitude, so the validation point has standard -deviation $0.01\,\hat v(t)$. The profiles run on linear scale, since the resting state holds no +deviation $0.01\,\hat v(t)$. The profiles run on linear scale, since the [resting state](methods-steady-states.html#stability) holds no nuclear IκBα. ```{r predictionsetup, eval = FALSE} @@ -161,7 +161,7 @@ ggplot2::ggplot(course, ggplot2::aes(time, value)) + theme_dMod2() ``` -Units of total NFκB follow from the gauge of [Symmetries](guide-symmetries.html). +Units of total NFκB follow from the [gauge](methods-symmetries.html#gauge-and-reduction) of [Symmetries](guide-symmetries.html). ## All prediction profiles diff --git a/vignettes/articles/guide-profiles.Rmd b/vignettes/articles/guide-profiles.Rmd index 0e4ace08..fb57325e 100644 --- a/vignettes/articles/guide-profiles.Rmd +++ b/vignettes/articles/guide-profiles.Rmd @@ -18,9 +18,9 @@ knitr::read_chunk("../../examples/oppeltNPJSystBiolAppl2018/refit.R") knitr::read_chunk("../../examples/oppeltNPJSystBiolAppl2018/fundamental.R") ``` -The profile likelihood [@raue2009structural] shows how well the data constrain each parameter. +The [profile likelihood](methods-profiles.html#def-profile-likelihood) [@raue2009structural] shows how well the data constrain each parameter. This chapter profiles the full model at the best fit of [Optimization](guide-optimization.html), -tests the core model of the publication and fits a reduced model. +tests the core model of the publication and fits a [reduced model](methods-profiles.html#def-reduced-model). ```{r setup, echo = FALSE} ``` @@ -60,18 +60,17 @@ tests the core model of the publication and fits a reduced model. ## Profile likelihood and confidence intervals -The profile of a parameter is the data term along the path on which the other parameters minimize -the objective with that parameter fixed. Here the objective has a prior of standard deviation 20 +The profile of a parameter is the [data term](methods-profiles.html#def-data-term) along the path on which the other parameters minimize +the [objective](methods-profiles.html#def-objective) with that parameter fixed. Here the objective has a [prior](methods-objective.html#prior) of standard deviation 20 on the log scale at the best fit, so that the data term shapes the profiles. Data terms within -3.84, the 95 % quantile of $\chi^2_1$, of the minimum form the 95 % confidence interval +3.84, the 95 % quantile of $\chi^2_1$, of the minimum form the 95 % [confidence interval](methods-profiles.html#def-confidence-interval) ([Methods > Profile likelihood](methods-profiles.html)). `stepControl = list(stop = "data")` ends a profile there, `confint(val.column = "data")` reads the interval, `profileThreshold()` gives other levels. A profile open towards $-\infty$ means the process can be switched off, towards $+\infty$ that it can be instantaneous ([Methods > Shapes](methods-profiles.html#shapes)). -`method = "integrate"` (default) follows the constrained optimum as a curve, with -`algoControl = list(reoptimize = TRUE)` corrected by `trust()`; `method = "optimize"` refits at -every step. +`method = "integrate"` (default) follows the [constrained optimum](methods-profiles.html#def-constrained-optimum) as a curve +and corrects each step by a short fit with `trust()`; `method = "optimize"` refits at every step. | entry of `stepControl` | `"integrate"` | `"optimize"` | controls | |---|---|---|---| @@ -101,7 +100,7 @@ invisible(stored("results/fits.rds", "fit.R")) invisible(stored("results/profiles.rds", "profiles.R")) ``` -and profiles each side until the data term has risen by the threshold or the parameter has moved +and profiles each side until the data term has risen by the [threshold](methods-profiles.html#def-threshold) or the parameter has moved by 7. The profiles are loaded from `results/profiles.rds`: ```{r profiles, eval = FALSE} @@ -168,7 +167,7 @@ plotProfile(profiles, mode %in% c("data", "prior"), name %in% open, ncol = 4) + ## Parameter paths -`plotPaths()` shows how the other parameters compensate along a profile. Along `act_Ikb_Base`, +`plotPaths()` shows how the other parameters compensate along a profile ([parameter path](methods-profiles.html#def-parameter-path)). Along `act_Ikb_Base`, `eta_act_Ikb_Base_c_pNfkIkb` rises by the same amount: the data determine the product. Shown are the parameters that move by more than 1: @@ -190,7 +189,7 @@ for (par in c("act_Ikb_Base", "int_Nfk")) ## Predictions along a profile `plotArray()` predicts along one side of a profile, colored by the profiled parameter; `fixed` -adds the gauge. Along the upper side of `degrad_RnaA20`, `RnaA20` falls by two orders of magnitude +adds the [gauge](methods-symmetries.html#gauge-and-reduction). Along the upper side of `degrad_RnaA20`, `RnaA20` falls by two orders of magnitude while A20 stays nearly the same: ```{r, fig.height = 5} @@ -296,8 +295,8 @@ The core model with two delay steps, the separate factor and the scale `s_ipNFkB ```{r reducedobservables, eval = FALSE} ``` -As in the publication, all NFκB rests in the complex with IκBα and all IKK is inactive, a steady -state for every parameter value, so neither `Pimpl()` nor a stability term is needed: +As in the publication, all NFκB rests in the complex with IκBα and all IKK is inactive, a [steady +state](methods-steady-states.html#def-steady-state) for every parameter value, so neither `Pimpl()` nor a [stability](methods-steady-states.html#stability) term is needed: ```{r reducedmodel, eval = FALSE} ``` @@ -360,7 +359,7 @@ plateau <- fc$data[which.max(fc$constraint)] - fc$data[fc$constraint == 0][1] fcLower <- intervalsReduced$lower[intervalsReduced$name == "form_complex"] / log(10) ``` -All parameters are identifiable except `form_complex`, bounded below at +All parameters are [identifiable](methods-profiles.html#def-identifiable) except `form_complex`, bounded below at `r signif(fcLower, 2)` on the log10 scale and open above on a plateau `r round(plateau, 2)` above the optimum; the publication reports (-0.21, 3.03). The profiles of `degrad_A20`, `degrad_RnaA20` and `shuttle_RnaA20` have a second minimum inside the interval. The rate constants: @@ -395,7 +394,7 @@ atSecond <- sum(abs(fits$shuttle_RnaA20 - second$shuttle_RnaA20) < 0.1 & ``` Exchanging `degrad_A20` and `degrad_RnaA20` leaves every readout and the prior unchanged, a -discrete symmetry ([Symmetries > Discrete symmetries](guide-symmetries.html#discrete-symmetries)). +[discrete symmetry](https://dmodverse.github.io/symident/method/global.html) ([Symmetries > Discrete symmetries](guide-symmetries.html#discrete-symmetries)). Of the `r nrow(best)` best fits of the multistart, `r below` lie on the side `degrad_A20 < degrad_RnaA20` and `r nrow(best) - below` at the mirror image. The profile of `degrad_RnaA20` passes through the mirror image of the optimum, within @@ -411,8 +410,8 @@ also lie close to the fixed set. ## Profiles in the fundamental domain -The fundamental domain `degrad_A20 < degrad_RnaA20` holds the optimum and removes the swap. -`fundamental.R` fits the reduced model in the chart that +The [fundamental domain](https://dmodverse.github.io/symident/method/global.html) `degrad_A20 < degrad_RnaA20` holds the optimum and removes the swap. +`fundamental.R` fits the reduced model in the [chart](methods-symmetries.html#def-chart) that `symmetryReduction(branch = "degrad_A20 < degrad_RnaA20")` returns, with `define("degrad_RnaA20 <- degrad_A20 + delta_RnaA20")` before `insert("x <- exp(x)")`; the fixed set lies at `delta_RnaA20` $\to -\infty$. Only the parameter transformation is new: diff --git a/vignettes/articles/guide-remote-computing.Rmd b/vignettes/articles/guide-remote-computing.Rmd index 4b4fc09e..5cf3c28e 100644 --- a/vignettes/articles/guide-remote-computing.Rmd +++ b/vignettes/articles/guide-remote-computing.Rmd @@ -12,7 +12,8 @@ knitr::opts_knit$set(root.dir = .work) .outdir <- options(dMod2.outdir = NULL) ``` -Conditions of one evaluation run in threads, independent fits and profiles in processes. +Conditions of one evaluation run in threads, independent fits and +[profiles](methods-profiles.html#def-profile) in processes. `distributedComputing()` runs R code as tasks in detached processes, locally, over ssh or as a SLURM array job. Only the local job below runs at page build. @@ -255,7 +256,6 @@ sides <- expand.grid(par = names(best), side = c("left", "right"), stringsAsFact profilesJob <- distributedComputing( profile(obj, best, task$par, side = task$side, fixed = gauge, limits = c(lower = -7, upper = 7), stepControl = list(stop = "data"), - algoControl = list(reoptimize = TRUE), optControl = list(iterlim = 100, tolControl = tolerances)), tasks = sides, on = cluster, jobname = "oppelt_profiles", input = c("obj", "best", "gauge", "tolerances")) diff --git a/vignettes/articles/guide-sensitivities.Rmd b/vignettes/articles/guide-sensitivities.Rmd index ccba3991..1dda6701 100644 --- a/vignettes/articles/guide-sensitivities.Rmd +++ b/vignettes/articles/guide-sensitivities.Rmd @@ -16,8 +16,9 @@ source("results/stored.R") s <- stored("results/sensitivities.rds", "sensitivities.R") ``` -dMod2 computes derivatives of the objective exactly from the ODE sensitivities and the chain rule -through every function object. Code: `sensitivities.R`; details: +dMod2 computes derivatives of the [objective](methods-profiles.html#def-objective) exactly from the ODE +[sensitivities](methods-sensitivities.html#def-sensitivity) and the chain rule through every +[function object](methods-sensitivities.html#def-chain-gxp). Code: `sensitivities.R`; details: [Methods > Sensitivities and Hessians](methods-sensitivities.html). `derivMode` of `odemodel()`, `Y()`, `P()` and `Pimpl()` selects the derivatives a function @@ -28,25 +29,28 @@ call that asks for a derivative not built is an error. ## Forward sensitivities The default, `derivMode = "forward"`: `Xs()` integrates $\partial x / \partial \theta$ with the -states, the objective returns gradient and Gauss-Newton Hessian. `sensErrCon` in `optionsSens` -sets whether sensitivities enter the error test (default `TRUE`). +states, the objective returns gradient and +[Gauss-Newton Hessian](methods-sensitivities.html#gauss-newton-with-an-error-model). `sensErrCon` +in `optionsSens` sets whether sensitivities enter the +error test (default `TRUE`). ## Forward over forward `derivMode = "forward-forward"` in `odemodel()`, `Y()`, `P()` and `Pimpl()` builds second-order -sensitivities, and a call with `deriv2 = TRUE` returns the exact Hessian from them. The equation +sensitivities, and a call with `deriv2 = TRUE` returns the +[exact Hessian](methods-sensitivities.html#forward-over-forward) from them. The equation count grows with the square of the parameters (guide model: `r nrow(s$gradients)`); it suits small models such as those of [Nonlinear mixed-effects models](guide-nlme.html). ## Reverse sweep -One backward sweep of the adjoint system gives the gradient at a cost independent of the +One backward sweep of the [adjoint](methods-sensitivities.html#def-adjoint) system gives the gradient at a cost independent of the parameter count ([Methods > Reverse sweep](methods-sensitivities.html#reverse-sweep)). Build with -`derivMode = c("forward", "reverse")` (`Pimpl()` passes the sweep through the Jacobian of the -root), call with `sweep = "reverse"`. Both passes solve with `options` alone; solves with +`derivMode = c("forward", "reverse")` (`Pimpl()` passes the sweep through the +[Jacobian of the root](methods-steady-states.html#derivatives-of-the-root)), call with `sweep = "reverse"`. Both passes solve with `options` alone; solves with sensitivities use `optionsSens` merged over `options`. In -`trust()` the sweep is set per phase: +`trust()` the sweep is set per [phase](methods-trust.html#hessian-phases): ```{r, eval = FALSE} fit <- trust(obj, start, @@ -55,11 +59,11 @@ fit <- trust(obj, start, fit$phaseSweep ``` -Without `sweep`, `"bfgs"` and `"sr1"` phases sweep backwards if the objective allows it. +Without `sweep`, `"bfgs"` and `"sr1"` (quasi-Newton updates) phases sweep backwards if the objective allows it. Gauss-Newton needs forward sensitivities: a `"gn"` phase with `sweep = "reverse"` is an error. `"exact"` with `sweep = "reverse"` and `deriv2 = TRUE` uses forward over reverse. -The backward sweep follows the step grid of the value pass by default; on the cppDE backend +The backward sweep follows the step grid of the [value pass](methods-sensitivities.html#def-value-pass) by default; on the cppDE backend `optionsReverse` of `Xs()` sets the accuracy, see `cppDE::adjointControl()`: ```{r, eval = FALSE} @@ -82,8 +86,9 @@ Under `refine`, value and `chi2` include the change to the refined trajectory, a The exact Hessian without second-order sensitivities, one column per parameter ([Methods > Forward over reverse](methods-sensitivities.html#forward-over-reverse)). Build with `derivMode = c("forward", "reverse", "forward-reverse")`, call with -`sweep = "reverse", deriv2 = TRUE`. FOCEI in [Nonlinear mixed-effects models](guide-nlme.html) -uses it for directional second derivatives. +`sweep = "reverse", deriv2 = TRUE`. [FOCEI](methods-nlme.html#def-focei) in +[Nonlinear mixed-effects models](guide-nlme.html) uses it for +[directional second derivatives](methods-sensitivities.html#second-derivatives-along-directions). ## ODE backends @@ -91,7 +96,7 @@ uses it for directional second derivatives. | backend | solver | forward | fwd/fwd | reverse | fwd/rev | use | |---|---|---|---|---|---|---| -| `"cppDE"` (default) | C++: BDF/NDF, Adams, Rosenbrock, Tsitouras | duals | duals | discrete adjoint | yes | all models | +| `"cppDE"` (default) | C++: BDF/NDF, Adams, Rosenbrock, Tsitouras | duals | duals | [discrete adjoint](methods-sensitivities.html#def-discrete-adjoint) | yes | all models | | `"Sundials"` | CVODES, `cppDE::cvode()` | CVODES | no | CVODES ASA | no | first-order derivatives | | `"deSolve"` | `lsodes`, cOde | sens. equations | no | no | no | dMod models | diff --git a/vignettes/articles/guide-sparse-deviations.Rmd b/vignettes/articles/guide-sparse-deviations.Rmd index ea8d02e0..333c8eda 100644 --- a/vignettes/articles/guide-sparse-deviations.Rmd +++ b/vignettes/articles/guide-sparse-deviations.Rmd @@ -21,14 +21,15 @@ enumerate <- function(x) if (length(x) < 2) paste(x) else Oppelt et al. [@oppelt2018model] also measured the TNFα response of HepG2 cells under diclofenac (DCF). Which rate constants does DCF change? The publication selected differences by an L1 scan and -a likelihood ratio test [@steiert2016l1]. This chapter repeats the scan and answers the same -question with spike-and-slab random effects. Model: the reduced model of +a likelihood ratio test [@steiert2016l1]. This chapter repeats the +scan and answers the same question with [spike-and-slab](methods-nlme.html#def-spike-and-slab) random effects. Model: the reduced model of [Profile likelihood](guide-profiles.html); random effects and `em()`: [Nonlinear mixed-effects models](guide-nlme.html). `dcf.R` computed the fits; the chapter loads them. The second part lists the sparse random-effect distributions and what their fits report; -derivations: [Methods > Sparsity priors](methods-sparsity-priors.html). +derivations: [Methods > Sparsity priors](methods-sparsity-priors.html), the terms it uses in the +[Index](index-terms.html). ```{r setup, echo = FALSE} ``` @@ -68,7 +69,8 @@ TNFα-stimulated cells of the first blot scale, without (`TNF_none`) and with DC ``` With DCF an estimated rate constant $k$ becomes $\log k + \Delta_k$. `insert()` with -`x ~ 1 + (1 | gr(compound, dist = spikeSlab()))` writes each $\Delta_k$ as a random effect +`x ~ 1 + (1 | gr(compound, dist = spikeSlab()))` writes each $\Delta_k$ as a +[random effect](methods-nlme.html#def-random-effect) `eta__DCF`, 0 without compound; the L1 scan treats the same symbols as parameters. 24 differences, as in the publication: @@ -297,11 +299,13 @@ spike-and-slab distribution [@mitchell1988bayesian; @george1993variable] of a di $$p(\Delta_k) = (1 - \rho)\, \delta(\Delta_k) + \rho\, \mathcal{N}(\Delta_k;\, 0, \tau^2),$$ -with inclusion probability $\rho$ (`prob_compound`) and slab standard deviation $\tau$ -(`tau_compound`, log scale). `em()` estimates $\theta$, $\rho$ and $\tau$ from the likelihood with -the differences integrated out, a sum over subsets +with [inclusion probability](methods-sparsity-priors.html#def-inclusion-probability) $\rho$ (`prob_compound`) and slab standard deviation $\tau$ +(`tau_compound`, log scale). `em()` estimates $\theta$, $\rho$ and $\tau$ from the +marginal likelihood, the likelihood with the differences integrated out, a sum over +[subsets](methods-sparsity-priors.html#def-subset) ([Methods > Sparsity priors](methods-sparsity-priors.html#approximate-marginal)). -$p_0 = \Pr(\Delta_k = 0 \mid y)$ is the posterior spike probability. +$p_0 = \Pr(\Delta_k = 0 \mid y)$ is the posterior spike probability, one minus the inclusion probability +given the data. The candidates are the same 20 as in the L1 scan; with both partners of a product as candidates, neither would reach a probability of one half. `dcf.R` runs 1000 starts of `msem()` around the @@ -492,15 +496,106 @@ fit$random[, c("eta", "mode", "p0")] `p0` is the posterior probability that the reaction is absent. With a grouping, `k ~ 1 + (1 | gr(ID, dist = spikeSlab(spike = -Inf)))` switches the reaction off per group. `em(method = "focei")` and `em(method = "quadrature")` fit these random effects, also beside -normal ones of the same grouping; `"quadrature"` integrates to `tol` where `"focei"` takes the -Laplace approximation. With few candidates, most of them clearly present, an estimated `prob` +normal ones of the same grouping; `"quadrature"` integrates on a +[sparse grid](methods-nlme.html#adaptive-sparse-grid-quadrature) to `tol` where `"focei"` takes the +[Laplace approximation](methods-nlme.html#laplace-approximation). With few candidates, most of them clearly present, an estimated `prob` tends to 1; a fixed `prob` is the selection prior. Details: [Methods > Spike at a given value](methods-sparsity-priors.html#spike-at-a-given-value). +## Starts far from the data + +With a given `mean` or `spike`, `em()` sums over the subsets of candidates per group. The sum runs +in phases, each from the estimates and inner [modes](methods-sparsity-priors.html#def-mode) of the phase before; a burn-in may fit +the [fixed effects](methods-nlme.html#def-fixed-effect) first ([Methods > Phases and burn-in](methods-sparsity-priors.html#phases-and-burn-in)): + +| entry of `control$sparseFit` | values | default | +|---|---|---| +| `phases` | `"meanfield"`, `"ec"`, `"exact"` in the order they run; a character vector, or a named list with `maxECM` and `epsECM` per phase | all three; `maxECM = 200`, `epsECM = 1e-2`, in the last phase `1e-6` | +| `burnin` | `FALSE`, `TRUE` or `list(start = , iterlim = )`; `start` `"random"`, `"spike"`, `"slab"` or names of random effects | `FALSE`; `start = "random"`, `iterlim = 200` | +| `termBudget` | the most subsets of the exact sum; beyond it `"exact"` is skipped after `"ec"`, an error without | `4096` | + +`"meanfield"` ([mean field](methods-sparsity-priors.html#mean-field)) takes the inclusion of each candidate from the +Laplace integrals of a reference subset and of the subsets that differ from it in one candidate, +$K + 1$ integrals for $K$ candidates instead of $2^K$. `"ec"`, the +[expectation consistent approximation](methods-sparsity-priors.html#expectation-consistent-approximation-in-the-rate), +expands the data term as a Gaussian, at the first step with every candidate in the slab; from a start far from the data that expansion does not hold, and EC does not +converge. The burn-in fits the fixed effects in one [trust region](methods-trust.html#def-trust-region) with the +candidates of the start +subset in the slab, at the joint mode with the prior densities as penalty; the others stay at the +spike. A small example: two species, four candidate rates, the start of the initial values 40 and +10 times too high. + +```{r, include = FALSE} +options(dMod2.outdir = file.path(tempdir(), "guide-switching")) +dir.create(getOption("dMod2.outdir"), showWarnings = FALSE) +``` + +```{r switching, results = "hide"} +rates <- c("a0", "a1", "b0", "b1") +xSw <- Xs(odemodel(eqnvec(x = "a0 - a1*x", y = "b0 - b1*y"), modelname = "switch_x", compile = FALSE)) +gSw <- Y(eqnvec(x = "x", y = "y"), xSw, modelname = "switch_g", compile = FALSE) +trafoSw <- define(NULL, "p <- p", p = c("x", "y", rates)) |> + branch(table = data.frame(row.names = "C1", one = 1)) |> + insert("k <- exp(k)", k = rates) |> + insert(k ~ 0 + (1 | gr(dist = spikeSlab(prob = 0.5, tau = 1, mean = log(0.5), spike = -Inf))), k = rates) +pSw <- P(trafoSw, modelname = "switch_p", compile = FALSE) +compile(gSw, xSw, pSw, output = "switch") +# x is produced and degraded, y only degraded +times <- seq(0, 10, by = 0.5) +set.seed(2) +noisy <- function(n, v) data.frame(name = n, time = times, value = v + rnorm(length(times), 0, 0.05), + sigma = 0.05) +dataSw <- datalist(C1 = rbind(noisy("x", 2 - 1.5 * exp(-0.5 * times)), noisy("y", 2 * exp(-0.3 * times)))) +objSw <- normL2(dataSw, gSw * xSw * pSw) +far <- c(x = 20, y = 20) +``` + +EC alone fails at this start: + +```{r} +tryCatch(em(objSw, randomEffects(pSw), init = far, verbose = FALSE, + control = list(sparseFit = list(phases = "ec"))), + error = conditionMessage) +``` + +A burn-in from a random start subset, then the default phases: + +```{r} +set.seed(1) +fitSw <- em(objSw, randomEffects(pSw), init = far, verbose = FALSE, + control = list(sparseFit = list(burnin = TRUE))) +fitSw$burnin +fitSw$phases +fitSw$random[, c("eta", "mode", "p0")] +``` + +`fit$burnin` is the start subset, `fit$phases` has a row per phase: `value` is -2 log L of the +approximation of the phase (for the burn-in data plus prior at the mode), `failed` the subsets whose +inner search failed. An error names the phase. `msem()` draws a start subset per attempt and +repeats a failed start (`retry`); `multistart` lists the start subset in `subset`. Around a fitted +model, as for DCF above, the spike is that model and the start is near the data: no burn-in is +needed, and `spikeSlab()` with the default spike 0 takes the joint trust region of the next +section, which has no phases. + +## Hyperpriors + +With one group, as in the selection of reactions above, `prob` and `tau` rest on the few candidates of +the block: an estimated `prob` ([empirical Bayes](methods-sparsity-priors.html#def-empirical-bayes)) tends to 0 or 1, and an estimated `tau` +follows the modes. [Hyperpriors](methods-sparsity-priors.html#def-hyperprior) replace the estimates: + +```{r, eval = FALSE} +spikeSlab(prob = betaPrior(1, 1), tau = halfCauchyPrior(1), mean = log(0.5), spike = -Inf) +``` + +`betaPrior(1, 1)` integrates `prob` out, every number of candidates in the slab equally likely; +`fit$slab` reports the posterior mean of `prob` with a 95 % interval. A scale prior on `tau` takes the +posterior mode, with `integrate = TRUE` the phase `"exact"` integrates over `log tau`. With many groups +the estimates stay the default. Details: [Methods > Hyperpriors](methods-sparsity-priors.html#hyperpriors). + ## Fitting sparse random effects -`em(method = "focei")` integrates sparse random effects by the Laplace approximation at the joint -mode of a group, exactly where possible, and by expectation consistent (EC) approximation where the -data link a Dirichlet-process effect to another factor or the subset sum exceeds the budget. Fixed +`em(method = "focei")` integrates sparse random effects by the Laplace approximation at the +[joint mode](methods-sparsity-priors.html#joint-mode) of a group, exactly where possible, and by expectation consistent (EC) approximation where the +data link a [Dirichlet-process](methods-sparsity-priors.html#dirichlet-process-random-effects) effect to another factor or the subset sum exceeds the budget. Fixed effects and hyperparameters move in one trust region. `fit$coupling` is `"expectationConsistent"` if a group needed EC, else `NULL`. Methods: [Methods > Approximate marginal](methods-sparsity-priors.html#approximate-marginal), diff --git a/vignettes/articles/guide-symmetries.Rmd b/vignettes/articles/guide-symmetries.Rmd index 66a35cb6..1a0b7379 100644 --- a/vignettes/articles/guide-symmetries.Rmd +++ b/vignettes/articles/guide-symmetries.Rmd @@ -56,16 +56,17 @@ with identical observables in the model of [Setting up models](guide-model.html) ## Lie symmetries and detection -Each family is the orbit of a Lie symmetry. symident obtains the generators as the kernel of the -observability-identifiability matrix and proves scalings exactly +Each family is the [orbit](methods-symmetries.html#def-orbit) of a [Lie symmetry](methods-symmetries.html#def-lie-symmetry). symident obtains the +[generators](methods-symmetries.html#def-generator) as the [kernel](methods-steady-states.html#def-kernel) of the +[observability-identifiability matrix](methods-symmetries.html#def-oim) and proves [scalings](methods-symmetries.html#def-scaling) exactly ([Methods > Structural identifiability and Lie symmetries](methods-symmetries.html)). ## Detection settings -- `equilibrate = TRUE`: initial values are the steady state without TNFα. +- `equilibrate = TRUE`: initial values are the [steady state](methods-steady-states.html#def-steady-state) without TNFα. - `reduceCQ = TRUE`: symmetries act on the conserved totals, the parameters of `Pimpl()`. - `forcings = "TNF"`: TNFα is an input state, set by the event at time 0. -- `conditions`: a direction is non-identifiable only if it is so in both doses. +- `conditions`: a direction is [non-identifiable](methods-profiles.html#def-non-identifiable) only if it is so in both doses. The imaging readouts bleach, $y = \log(s x + o) - \tau t$. In the control the states are constant, so the bleaching rates are in no symmetry, and `symmetries.R` drops the bleaching terms. @@ -92,7 +93,7 @@ types <- vapply(symmetries$symmetries, `[[`, "", "type") ``` The rank is `r symmetries$rank` of `r symmetries$dim` coordinates, proven; the kernel is spanned -by `r inWords(length(types))` scalings, each proven over the rationals. The generators are one +by `r inWords(length(types))` scalings, each proven over the rationals ([level](methods-symmetries.html#def-level)). The generators are one basis; up to sums there are four kinds. - **Unobserved intermediates**, level against driven rate: receptor $X_1$, IκBα transcript $X_4$, @@ -105,7 +106,7 @@ basis; up to sums there are four kinds. ## Symmetry reduction `symmetryReduction()` returns in `$trafo` a transformation without the directions, for scalings -by fixing one coordinate per direction +by fixing one coordinate per direction, a [section](methods-symmetries.html#def-section) ([Methods > Gauge and reduction](methods-symmetries.html#gauge-and-reduction)). Loaded from `results/reduction.rds`: @@ -119,13 +120,13 @@ reduction ## Gauge fixing -`model.R` fixes one moved parameter per scaling at 1, 0 on log scale, the gauge: +`model.R` fixes one moved parameter per scaling at 1, 0 on log scale, the [gauge](methods-symmetries.html#def-gauge): ```{r gauge} ``` The `r inWords(length(gauge))` coordinates remove all `r inWords(length(types))` scalings if their -weight matrix is regular +[weight](methods-symmetries.html#def-weights) matrix is regular (invertible) ([Methods > Gauge and reduction](methods-symmetries.html#gauge-and-reduction)): ```{r} @@ -144,7 +145,7 @@ the A20 imaging scale. [Optimization](guide-optimization.html) fits the remainin ## Discrete symmetries -A discrete symmetry maps a parameter value to isolated other values with the same output. +A [discrete symmetry](https://dmodverse.github.io/symident/method/global.html) maps a parameter value to isolated other values with the same output. `symmetryDetection(mode = "global")` counts these values and reconstructs rational maps between them (requires msolve). `discrete.R` applies it to the reduced model of [Profile likelihood](guide-profiles.html#reduced-model), passed as `trafo`; loaded from @@ -165,14 +166,14 @@ swap <- discrete$discreteSymmetries[[1]] swap[c("map", "level", "stateMaps")] ``` -There are `r inWords(discrete$info$discrete$count)` values with the output of a generic one; the +There are `r inWords(discrete$info$discrete$count)` values with the output of a [generic](methods-symmetries.html#def-generic) one, the [fiber](https://dmodverse.github.io/symident/method/global.html); the map exchanges the degradation rates of the A20 transcript and of A20, `exact` means proven by the map of the states. The map moves no coordinate of the scalings and holds in the original coordinates as well. The publication does not name the swap and reports both rates with the same 95 % interval, $-5.97$ to $-3.32$ on log scale [@oppelt2018model, Table S7], the union of the two images. -`symmetryReduction(branch = )` gives a chart of the fundamental domain +`symmetryReduction(branch = )` gives a [chart](methods-symmetries.html#def-chart) of the [fundamental domain](https://dmodverse.github.io/symident/method/global.html) `degrad_A20 < degrad_RnaA20`: ```{r fundamental, eval = FALSE} diff --git a/vignettes/articles/index-terms.Rmd b/vignettes/articles/index-terms.Rmd new file mode 100644 index 00000000..f9c13228 --- /dev/null +++ b/vignettes/articles/index-terms.Rmd @@ -0,0 +1,275 @@ +--- +title: "Index" +--- + +Terms of the guide and the methods articles, each linked to the place where the text defines it. + +## Symbols + +- [$-2 \log L$](methods-objective.html#def-minus-2-log-l), Likelihood and prior +- [$-2 \log L$](methods-nlme.html#def-minus-2-log-l), Marginal likelihood of mixed-effects models +- [$\hat B^{+}$](methods-trust.html#def-b-hat-plus), Trust-region optimization +- [$\Omega$](methods-nlme.html#def-omega), Marginal likelihood of mixed-effects models + +## A + +- [adjoint](methods-sensitivities.html#def-adjoint), Sensitivities and Hessians + +## B + +- [balance](methods-steady-states.html#def-balance), Steady states +- [base point](methods-symmetries.html#def-base-point), Structural identifiability and Lie symmetries +- [basis](methods-steady-states.html#def-basis), Steady states +- [Bayes factor](methods-sparsity-priors.html#def-bayes-factor), Sparsity priors +- [beta-binomial](methods-sparsity-priors.html#def-beta-binomial), Sparsity priors +- [block](methods-nlme.html#def-block), Marginal likelihood of mixed-effects models + +## C + +- [cautious test](methods-trust.html#def-cautious-test), Trust-region optimization +- [cavity](methods-sparsity-priors.html#def-cavity), Sparsity priors +- [chain `g*x*p`](methods-sensitivities.html#def-chain-gxp), Sensitivities and Hessians +- [chart](methods-symmetries.html#def-chart), Structural identifiability and Lie symmetries +- [Checkpoints](methods-sensitivities.html#def-checkpoint), Sensitivities and Hessians +- [clustered lasso](methods-trust.html#def-clustered-lasso), Trust-region optimization +- [Collapsed indicator moves](methods-nlme.html#def-collapsed-move), Marginal likelihood of mixed-effects models +- [compartment volumes](methods-steady-states.html#def-compartment-volume), Steady states +- [condensing](methods-multiple-shooting.html#def-condensing), Multiple shooting +- [condition](dMod2.html#def-condition), Get started +- [conditional mode](methods-nlme.html#def-conditional-mode), Marginal likelihood of mixed-effects models +- [Conditional standard errors](methods-nlme.html#def-conditional-standard-error), Marginal likelihood of mixed-effects models +- [confidence interval](methods-profiles.html#def-confidence-interval), Profile likelihood +- [conservation class](methods-steady-states.html#def-conservation-class), Steady states +- [conservation laws](methods-steady-states.html#def-conservation-law), Steady states +- [conservation manifold](methods-steady-states.html#def-conservation-manifold), Steady states +- [conserved quantity](methods-steady-states.html#def-conserved-quantity), Steady states +- [constrained optimum](methods-profiles.html#def-constrained-optimum), Profile likelihood +- [continuity constraint](methods-multiple-shooting.html#def-continuity-constraint), Multiple shooting +- [cotangent](methods-sensitivities.html#def-cotangent), Sensitivities and Hessians +- [cut](methods-steady-states.html#def-cut), Steady states +- [cycle](methods-steady-states.html#def-cycle), Steady states + +## D + +- [damped](methods-trust.html#def-damping), Trust-region optimization +- [data term](methods-profiles.html#def-data-term), Profile likelihood +- [determined parameter](methods-objective.html#def-determined-parameter), Likelihood and prior +- [Dirichlet-process random effects](methods-nlme.html#def-dirichlet-process-random-effects), Marginal likelihood of mixed-effects models +- [*discrete adjoint*](methods-sensitivities.html#def-discrete-adjoint), Sensitivities and Hessians +- [dual numbers](methods-sensitivities.html#def-dual-number), Sensitivities and Hessians + +## E + +- [ECM](methods-nlme.html#def-ecm), Marginal likelihood of mixed-effects models +- [ECME](methods-nlme.html#def-ecme), Marginal likelihood of mixed-effects models +- [Empirical Bayes](methods-sparsity-priors.html#def-empirical-bayes), Sparsity priors +- [error model](methods-objective.html#def-error-model), Likelihood and prior +- [error parameters](methods-objective.html#def-error-parameters), Likelihood and prior +- [event](methods-sensitivities.html#def-event), Sensitivities and Hessians +- [expectation consistent (EC) approximation](methods-sparsity-priors.html#def-expectation-consistent-approximation), Sparsity priors + +## F + +- [filter](methods-multiple-shooting.html#def-filter), Multiple shooting +- [finite-sample threshold](methods-profiles.html#def-finite-sample-threshold), Profile likelihood +- [Fixed effects](methods-nlme.html#def-fixed-effect), Marginal likelihood of mixed-effects models +- [flux terms](methods-steady-states.html#def-flux-term), Steady states +- [FOCEI](methods-nlme.html#def-focei), Marginal likelihood of mixed-effects models +- [forcings](methods-steady-states.html#def-forcing), Steady states +- [forward mode](methods-sensitivities.html#def-forward-mode), Sensitivities and Hessians +- [Forward over forward](methods-sensitivities.html#def-forward-over-forward), Sensitivities and Hessians +- [Forward over reverse](methods-sensitivities.html#def-forward-over-reverse), Sensitivities and Hessians +- [forward sweep](methods-sensitivities.html#def-forward-sweep), Sensitivities and Hessians +- [free energy](methods-sparsity-priors.html#def-free-energy), Sparsity priors +- [frozen nodes](methods-nlme.html#def-frozen-nodes), Marginal likelihood of mixed-effects models +- [fused block](methods-trust.html#def-fused-block), Trust-region optimization + +## G + +- [gap](methods-multiple-shooting.html#def-gap), Multiple shooting +- [gauge](methods-profiles.html#def-gauge), Profile likelihood +- [gauge](methods-symmetries.html#def-gauge), Structural identifiability and Lie symmetries +- [general directions](methods-symmetries.html#def-general-direction), Structural identifiability and Lie symmetries +- [generalized Gauss-Newton](methods-multiple-shooting.html#def-generalized-gauss-newton), Multiple shooting +- [generator](methods-symmetries.html#def-generator), Structural identifiability and Lie symmetries +- [generic](methods-symmetries.html#def-generic), Structural identifiability and Lie symmetries +- [group](methods-nlme.html#def-group), Marginal likelihood of mixed-effects models + +## H + +- [hands over](methods-trust.html#def-handover), Trust-region optimization +- [hard case](methods-trust.html#def-hard-case), Trust-region optimization +- [hit](methods-multiple-shooting.html#def-hit), Multiple shooting +- [hit](methods-trust.html#def-hit), Trust-region optimization +- [hyperpriors](methods-sparsity-priors.html#def-hyperprior), Sparsity priors + +## I + +- [identifiable](methods-profiles.html#def-identifiable), Profile likelihood +- [inclusion probability](methods-nlme.html#def-inclusion-probability), Marginal likelihood of mixed-effects models +- [inclusion probability](methods-sparsity-priors.html#def-inclusion-probability), Sparsity priors +- [indicator](methods-nlme.html#def-indicator), Marginal likelihood of mixed-effects models +- [indicator](methods-sparsity-priors.html#def-indicator), Sparsity priors +- [inner parameters](dMod2.html#def-inner-parameters), Get started +- [integral curves](methods-symmetries.html#def-integral-curve), Structural identifiability and Lie symmetries +- [integration-based profile](methods-profiles.html#def-integration-based-profile), Profile likelihood +- [invariant](methods-symmetries.html#def-invariant), Structural identifiability and Lie symmetries + +## J + +- [Jacobian](methods-steady-states.html#def-jacobian), Steady states +- [joint mode](methods-sparsity-priors.html#def-joint-mode), Sparsity priors +- [joint region](methods-profiles.html#def-joint-region), Profile likelihood + +## K + +- [kernel](methods-steady-states.html#def-kernel), Steady states + +## L + +- [large residuals](methods-trust.html#def-large-residual), Trust-region optimization +- [Level](methods-nlme.html#def-level), Marginal likelihood of mixed-effects models +- [level](methods-symmetries.html#def-level), Structural identifiability and Lie symmetries +- [Lie order](methods-symmetries.html#def-lie-order), Structural identifiability and Lie symmetries +- [Lie symmetry](methods-symmetries.html#def-lie-symmetry), Structural identifiability and Lie symmetries +- [likelihood](methods-objective.html#def-likelihood), Likelihood and prior +- [low-rank part](methods-trust.html#def-low-rank-part), Trust-region optimization + +## M + +- [marginal score](methods-nlme.html#def-marginal-score), Marginal likelihood of mixed-effects models +- [maximum likelihood](methods-objective.html#def-maximum-likelihood), Likelihood and prior +- [mean field](methods-sparsity-priors.html#def-mean-field), Sparsity priors +- [mode](methods-sparsity-priors.html#def-mode), Sparsity priors +- [Multiple shooting](methods-multiple-shooting.html#def-multiple-shooting), Multiple shooting +- [multiplicity correction](methods-sparsity-priors.html#def-multiplicity-correction), Sparsity priors +- [multiplier](methods-sensitivities.html#def-multiplier), Sensitivities and Hessians +- [multiplier](methods-trust.html#def-multiplier), Trust-region optimization +- [mu-referenced](methods-nlme.html#def-mu-referencing), Marginal likelihood of mixed-effects models + +## N + +- [natural level function](methods-multiple-shooting.html#def-natural-level-function), Multiple shooting +- [Newton decrement](methods-nlme.html#def-newton-decrement), Marginal likelihood of mixed-effects models +- [nodes](methods-multiple-shooting.html#def-node), Multiple shooting +- [noise floor](methods-trust.html#def-noise-floor), Trust-region optimization +- [non-identifiable](methods-profiles.html#def-non-identifiable), Profile likelihood +- [nonmonotone acceptance](methods-trust.html#def-nonmonotone-acceptance), Trust-region optimization + +## O + +- [objective](methods-profiles.html#def-objective), Profile likelihood +- [objective function](dMod2.html#def-objfn), Get started +- [objective function](methods-objective.html#def-objective-function), Likelihood and prior +- [`objfn`](methods-objective.html#def-objfn), Likelihood and prior +- [observability-identifiability matrix](methods-symmetries.html#def-oim), Structural identifiability and Lie symmetries +- [observation function](dMod2.html#def-obsfn), Get started +- [`obsfn`](methods-objective.html#def-obsfn), Likelihood and prior +- [Occam term](methods-sparsity-priors.html#def-occam-term), Sparsity priors +- [one-parameter group](methods-symmetries.html#def-one-parameter-group), Structural identifiability and Lie symmetries +- [orbit](methods-symmetries.html#def-orbit), Structural identifiability and Lie symmetries +- [outer parameters](dMod2.html#def-outer-parameters), Get started + +## P + +- [parameter path](methods-profiles.html#def-parameter-path), Profile likelihood +- [parameter region](methods-profiles.html#def-parameter-region), Profile likelihood +- [parameter transformation](dMod2.html#def-parfn), Get started +- [parameter transformation](methods-steady-states.html#def-parameter-transformation), Steady states +- [Pareto shape](methods-nlme.html#def-pareto-shape), Marginal likelihood of mixed-effects models +- [path equation](methods-profiles.html#def-path-equation), Profile likelihood +- [phase](methods-trust.html#def-phase), Trust-region optimization +- [pivot](methods-steady-states.html#def-pivot), Steady states +- [plateau](methods-trust.html#def-plateau), Trust-region optimization +- [population parameters](methods-nlme.html#def-population-parameters), Marginal likelihood of mixed-effects models +- [posterior](methods-nlme.html#def-posterior), Marginal likelihood of mixed-effects models +- [practically non-identifiable](methods-profiles.html#def-practical-non-identifiability), Profile likelihood +- [prediction function](dMod2.html#def-prdfn), Get started +- [prediction profile likelihood](methods-profiles.html#def-prediction-profile-likelihood), Profile likelihood +- [predictions](methods-objective.html#def-prediction), Likelihood and prior +- [prior](methods-objective.html#def-prior), Likelihood and prior +- [prior term](methods-profiles.html#def-prior-term), Profile likelihood +- [profile](methods-profiles.html#def-profile), Profile likelihood +- [profile likelihood](methods-profiles.html#def-profile-likelihood), Profile likelihood +- [pseudo-transient continuation](methods-steady-states.html#def-pseudo-transient-continuation), Steady states + +## Q + +- [quadratic model](methods-trust.html#def-quadratic-model), Trust-region optimization + +## R + +- [radius](methods-trust.html#def-radius), Trust-region optimization +- [random effects](methods-nlme.html#def-random-effect), Marginal likelihood of mixed-effects models +- [Rao-Blackwellized](methods-nlme.html#def-rao-blackwellization), Marginal likelihood of mixed-effects models +- [reduced model](methods-profiles.html#def-reduced-model), Profile likelihood +- [regular](methods-steady-states.html#def-regular-root), Steady states +- [relative error](methods-objective.html#def-relative-error), Likelihood and prior +- [replacement synchronization](methods-multiple-shooting.html#def-replacement-synchronization), Multiple shooting +- [reseed](methods-trust.html#def-reseed), Trust-region optimization +- [residual](methods-sensitivities.html#def-residual), Sensitivities and Hessians +- [resting state](methods-steady-states.html#def-resting-state), Steady states +- [restoration](methods-multiple-shooting.html#def-restoration), Multiple shooting +- [reverse mode](methods-sensitivities.html#def-reverse-mode), Sensitivities and Hessians +- [reverse sweep](methods-sensitivities.html#def-reverse-sweep), Sensitivities and Hessians +- [right-hand side](methods-steady-states.html#def-right-hand-side), Steady states +- [root](methods-steady-states.html#def-root), Steady states +- [rugged](methods-multiple-shooting.html#def-rugged-objective), Multiple shooting + +## S + +- [saltation matrix](methods-sensitivities.html#def-saltation-matrix), Sensitivities and Hessians +- [scaled gap size](methods-multiple-shooting.html#def-scaled-gap-size), Multiple shooting +- [Scalings](methods-symmetries.html#def-scaling), Structural identifiability and Lie symmetries +- [second-order correction](methods-multiple-shooting.html#def-second-order-correction), Multiple shooting +- [section](methods-symmetries.html#def-section), Structural identifiability and Lie symmetries +- [secular equation](methods-trust.html#def-secular-equation), Trust-region optimization +- [seed](methods-sensitivities.html#def-seed), Sensitivities and Hessians +- [seed](methods-trust.html#def-seed), Trust-region optimization +- [segments](methods-multiple-shooting.html#def-segment), Multiple shooting +- [sensitivities](methods-sensitivities.html#def-sensitivity), Sensitivities and Hessians +- [sites](methods-sparsity-priors.html#def-site), Sparsity priors +- [slab](methods-sparsity-priors.html#def-slab), Sparsity priors +- [sloppy models](methods-trust.html#def-sloppy-model), Trust-region optimization +- [Smolyak](methods-nlme.html#def-smolyak), Marginal likelihood of mixed-effects models +- [sparse grid](methods-nlme.html#def-sparse-grid), Marginal likelihood of mixed-effects models +- [spike](methods-sparsity-priors.html#def-spike), Sparsity priors +- [spike-and-slab](methods-nlme.html#def-spike-and-slab), Marginal likelihood of mixed-effects models +- [Stagnation](methods-trust.html#def-stagnation), Trust-region optimization +- [steady state](methods-steady-states.html#def-steady-state), Steady states +- [Stochastic-approximation EM](methods-nlme.html#def-saem), Marginal likelihood of mixed-effects models +- [stoichiometric coefficients](methods-steady-states.html#def-stoichiometric-coefficient), Steady states +- [stoichiometry](methods-steady-states.html#def-stoichiometry), Steady states +- [structural parameters](methods-nlme.html#def-structural-parameters), Marginal likelihood of mixed-effects models +- [structurally non-identifiable](methods-profiles.html#def-structural-non-identifiability), Profile likelihood +- [structure](methods-sparsity-priors.html#def-structure), Sparsity priors +- [structured secant updates](methods-trust.html#def-structured-secant-update), Trust-region optimization +- [subproblem](methods-trust.html#def-subproblem), Trust-region optimization +- [subset](methods-sparsity-priors.html#def-subset), Sparsity priors +- [support](methods-symmetries.html#def-support), Structural identifiability and Lie symmetries +- [symmetry](methods-profiles.html#def-symmetry), Profile likelihood + +## T + +- [tangent](methods-sensitivities.html#def-tangent), Sensitivities and Hessians +- [threshold](methods-profiles.html#def-threshold), Profile likelihood +- [tilted distribution](methods-sparsity-priors.html#def-tilted-distribution), Sparsity priors +- [trust region](methods-trust.html#def-trust-region), Trust-region optimization + +## V + +- [validation data point](methods-profiles.html#def-validation-data-point), Profile likelihood +- [validation profile](methods-profiles.html#def-validation-profile), Profile likelihood +- [validation profiles](methods-objective.html#def-validation-profile), Likelihood and prior +- [value pass](methods-sensitivities.html#def-value-pass), Sensitivities and Hessians +- [volume term](methods-nlme.html#def-volume-term), Marginal likelihood of mixed-effects models + +## W + +- [weighted degree](methods-symmetries.html#def-weighted-degree), Structural identifiability and Lie symmetries +- [weights](methods-symmetries.html#def-weights), Structural identifiability and Lie symmetries + +## Z + +- [zero residual](methods-trust.html#def-zero-residual), Trust-region optimization + diff --git a/vignettes/articles/methods-multiple-shooting.Rmd b/vignettes/articles/methods-multiple-shooting.Rmd index 110a4d78..b5b805f3 100644 --- a/vignettes/articles/methods-multiple-shooting.Rmd +++ b/vignettes/articles/methods-multiple-shooting.Rmd @@ -23,9 +23,10 @@ inFraction <- function(x) if (round(1 / x) %in% 2:10) c("half", "a third", "a qu ``` Single shooting integrates from the initial state over the whole time axis. For oscillating or -spiking systems the objective is rugged: a parameter change shifts every later period, and a peak -moved by more than the peak width leaves the residuals without direction, so few starts reach the -narrow valleys. `trust()` offers multiple shooting instead ([trust region](methods-trust.html)). +spiking systems the objective is [rugged]{#def-rugged-objective}, with many local minima and +narrow valleys: a parameter change shifts every later period, and a peak moved by more than the +peak width leaves the residuals without direction, so few starts reach the narrow valleys. +`trust()` offers multiple shooting instead ([trust region](methods-trust.html)). ## Usage @@ -65,9 +66,12 @@ phases, `switches`, `hessianReseed`, `qnMemory`, `nonmonotone`, `boundary = "cli ## Segments and gaps -Multiple shooting [@bock1983recent; @baake1992fitting] cuts the time axis at nodes -$\tau_1 < \dots < \tau_M$ and integrates segment $j$ from node values $s_j$, the first from the -initial state of the parameter transformation. Continuity becomes the constraint +[Multiple shooting]{#def-multiple-shooting} [@bock1983recent; @baake1992fitting] cuts the time axis +at [nodes]{#def-node} $\tau_1 < \dots < \tau_M$ into [segments]{#def-segment} and integrates +segment $j$ from node values $s_j$, the first from the initial state of the parameter transformation. +The node values are fitted with the parameters. The [gap]{#def-gap} $c_j$ is the difference between +the end state of segment $j$ and the node value of the next segment, and the +[continuity constraint]{#def-continuity-constraint} demands every gap to be zero: $$c_j = x(\tau_{j+1};\, \tau_j, s_j, \theta) - s_{j+1} = 0 . \tag{1}$$ @@ -77,14 +81,17 @@ single-shooting objective. ## Condensed step -Bock's generalized Gauss-Newton method linearizes (1). With the end-state sensitivities +Bock's [generalized Gauss-Newton]{#def-generalized-gauss-newton} method, Gauss-Newton for least +squares with equality constraints, linearizes the residuals and the constraints (1) and takes the +step from the linear problem. With the end-state sensitivities $G_j = \partial x_j / \partial s_j$ and $P_j = \partial x_j / \partial \theta$, $$\Delta s_{j+1} = \alpha\, c_j + G_j\, \Delta s_j + P_j\, \Delta \theta , \tag{2}$$ and the recursion gives $\Delta s = \alpha z + S\, \Delta\theta$. Substituted into the linearized -residuals it leaves a Gauss-Newton model in $\Delta\theta$ alone (condensing), of single-shooting -size, so subproblem solver and bounds of `trust()` apply unchanged. The nodes follow the step by the +residuals it leaves a Gauss-Newton model in $\Delta\theta$ alone, of single-shooting size, so +subproblem solver and bounds of `trust()` apply unchanged. This elimination of the node steps is +[condensing]{#def-condensing}. The nodes follow the step by the linearization, not by simulation, so the gaps close only at convergence. The trust region bounds parameters and nodes together, @@ -95,7 +102,9 @@ with $D = \operatorname{diag}(\lvert v \rvert^{1/2})$ for the distances $v$ to t [Bound constraints](methods-trust.html#bound-constraints), the identity without bounds, since a region on $\theta$ alone leaves $S\, \Delta\theta$ unbounded, which is huge across a spike. $V$ is one over the state scale (`multipleShootingControl$scale`): data range for observed states, -simulation range otherwise, a decade for log10 node values. $\alpha = 1$ closes the linearized gaps +simulation range otherwise, a decade for log10 node values. The +[scaled gap size]{#def-scaled-gap-size} $h = \lVert V c \rVert$ is the Euclidean norm of the gaps in +units of the state scale. $\alpha = 1$ closes the linearized gaps (Bock's step); under an active region $\alpha \le 1$ is the share of the node part of the full step that the radius allows. A link of the condensing chain that would propagate a gap through expanding segments beyond a bound is dropped for the step. Other summands, a prior or a single-shooting @@ -103,9 +112,9 @@ segments beyond a bound is dropped for the step. Other summands, a prior or a si | control | effect | |---|---| -| `stepControl$acceptance = "filter"` (default) | filter of Fletcher and Leyffer [@fletcher2002nonlinear] on the objective function $\mathcal{J}(\theta)$, $-2 \log L$ or $-2 \log$ of the posterior, and the scaled gap size $h = \lVert V c \rVert$ | -| `stepControl$acceptance = "merit"` | $\ell_2$ exact penalty $\mathcal{J} + \mu h$ | -| `stepControl$soc` (on) | one second-order correction of a rejected step whose gaps did not close as predicted | +| `stepControl$acceptance = "filter"` (default) | [filter]{#def-filter} of Fletcher and Leyffer [@fletcher2002nonlinear] on the objective function $\ell(\theta)$, $-2 \log L$ or $-2 \log$ of the posterior, and the scaled gap size $h$: a trial point is accepted if it lowers $h$ or $\ell$ by a margin against the current point and every pair $(h, \ell)$ stored from earlier iterates | +| `stepControl$acceptance = "merit"` | exact penalty $\ell + \mu h$ | +| `stepControl$soc` (on) | one [second-order correction]{#def-second-order-correction} of a rejected step whose gaps did not close as predicted: the step repeated with the gaps at the trial point closed by the current linearization | | `tolControl$ctol` | `converged = TRUE` only for $h$ below it; stagnation, `rmin`, ten failed solves in a row, `iterlim`, and under `acceptance = "natural"` a zero full step or one failed solve end the run with `converged = FALSE` above it | | `hessianMethod = "gn"` | condensed Gauss-Newton blocks | | `hessianMethod = "bfgs"`, `"sr1"` | one quasi-Newton block per segment Lagrangian, from gradients alone, so usable with `sweep = "reverse"` | @@ -118,7 +127,7 @@ measure the fit. From a distant start the condensed step can be forced through a regime the data never show, such as a spike threshold. `stepControl$anneal` (on) therefore first minimizes -$$\mathcal{J} + w \lVert V c \rVert^2 \tag{4}$$ +$$\ell + w \lVert V c \rVert^2 \tag{4}$$ over parameters and nodes on the sparse Gauss-Newton matrix, $w$ rising tenfold per stage from one, then hands over to the exact method: precision annealing [@ye2015improved] with a fixed schedule. A @@ -147,7 +156,7 @@ parameters, cuts nothing, since no node removes it. |---|---| | `charts = c(phi = "angle")` | gap counted modulo $2\pi$ | | `charts` entry `"log10"` | node values of a positive state on the log scale | -| default | observed states at the data; others from a run with observed states reset to the data at each data time, replacement synchronization [@pecora1990synchronization] | +| default | observed states at the data; others from a run with observed states reset to the data at each data time, [replacement synchronization]{#def-replacement-synchronization} [@pecora1990synchronization] | | `init = "spline"` | smoothing spline, roughness by generalized cross-validation [@horbelt2002parameter] | | `init = "simulation"` | simulation at the start parameters | | list as `fit$multipleShooting$nodes` | given values, node times in `nodes` | @@ -164,7 +173,7 @@ the layout. ## Further step controls -`stepControl$acceptance = "natural"` selects Bock's natural level function +`stepControl$acceptance = "natural"` selects Bock's [natural level function]{#def-natural-level-function} [@peifer2007parameter]: the full Gauss-Newton step damped by a factor from a curvature estimate, cut back by a corrector, and accepted when the simplified step at the trial point (current Jacobians, trial residuals and gaps) has shrunk. The filter takes over where the damping finds no @@ -177,7 +186,7 @@ Off by default, since each helps on some problems and costs on others: | `stepControl$twoPhase` | fit parameters with nodes held at the start [@horbelt2002parameter], then lay out nodes at the result and release them; helps with noisy node values, as on spiking traces, at several times the cost elsewhere | | `stepControl$regularize` | fix condensed directions with singular value below that fraction of the largest [@peifer2007parameter] | | `multipleShootingControl$breaks` | nodes without continuity constraint [@voss2004nonlinear]; Gauss-Newton Hessian only | -| `stepControl$restore` | filter restoration, at most five times: close the linearized gaps, damped if needed, else put the nodes on the current trajectory; on noisy spike trains this makes the layout cut more segments and fewer starts succeed | +| `stepControl$restore` | filter [restoration]{#def-restoration}, steps that only reduce the gaps where the filter accepts no step, at most five times: close the linearized gaps, damped if needed, else put the nodes on the current trajectory; on noisy spike trains this makes the layout cut more segments and fewer starts succeed | ## FitzHugh-Nagumo oscillator @@ -195,7 +204,7 @@ Forty starts perturb the initial states by a standard deviation of 1.5 and $a$, ```{r fhnfits, eval = FALSE} ``` -A hit has a single-shooting objective within 0.1 of the best, evaluated anew because open gaps can +A [hit]{#def-hit} has a single-shooting objective within 0.1 of the best, evaluated anew because open gaps can report a data term below the optimum. ```{r, echo = FALSE} diff --git a/vignettes/articles/methods-nlme.Rmd b/vignettes/articles/methods-nlme.Rmd index 5d0db0c1..6cb68f50 100644 --- a/vignettes/articles/methods-nlme.Rmd +++ b/vignettes/articles/methods-nlme.Rmd @@ -14,7 +14,10 @@ knitr::opts_chunk$set(collapse = TRUE, comment = "#>", message = FALSE) ## Marginal likelihood -Group $i$ of $G$ has random effects $\eta_i \in \mathbb{R}^K$, inner parameters +A [group]{#def-group} is the unit that shares one draw of the random effects, for example a +subject or a gel, and holds one or several conditions. Group $i$ of $G$ has +[random effects]{#def-random-effect} $\eta_i \in \mathbb{R}^K$, the unobserved deviations of the +group from the population, integrated out of the likelihood, inner parameters $\phi_i = h(\theta, \eta_i)$ and the observation model $$\begin{aligned} @@ -22,28 +25,36 @@ y_{ij} &= g\bigl(x(t_{ij};\, \phi_i)\bigr) + \varepsilon_{ij}, \\ \varepsilon_{ij} &\sim \mathcal{N}\bigl(0, \sigma^2(\phi_i, t_{ij})\bigr), \qquad \eta_i \sim \mathcal{N}(0, \Omega), \end{aligned} \tag{1}$$ -with population parameters $\psi = (\theta, \Omega, \sigma)$, and +with [$\Omega$]{#def-omega} the covariance matrix of the random effects, +[population parameters]{#def-population-parameters} $\psi = (\theta, \Omega, \sigma)$, the +parameters `em()` estimates, and [structural parameters]{#def-structural-parameters} $\theta$, +those that are neither random effects nor parameters of $\Omega$ or the error model, fixed effects +included. The log marginal likelihood is -$$\ell(\psi) = \sum_{i=1}^G \log L_i(\psi), \qquad -L_i(\psi) = \int p(y_i \mid \eta_i, \psi)\, p(\eta_i \mid \Omega)\, \mathrm{d}\eta_i . \tag{2}$$ +$$\begin{aligned} +\log L(\psi) &= \sum_{i=1}^G \log L_i(\psi), \\ +L_i(\psi) &= \int p(y_i \mid \eta_i, \psi)\, p(\eta_i \mid \Omega)\, \mathrm{d}\eta_i . +\end{aligned} \tag{2}$$ -The integrand is `normL2(data, g * x * p, errmodel = e)`, with sensitivities in $\eta_i$ by the +`em()` minimizes and reports [$-2 \log L$]{#def-minus-2-log-l}; differences of +nested fits are likelihood-ratio statistics. The integrand is +`normL2(data, g * x * p, errmodel = e)`, with sensitivities in $\eta_i$ by the chain rule, plus the prior $\sum_i \eta_i^\top \Omega^{-1} \eta_i + G \log \lvert \Omega \rvert$ from `randomEffects(p)`. Conditions without a group add their $-2 \log L$ unchanged. `normT(..., df = 4)` gives Student-t residuals. ## EM algorithm -With the posterior $q_i(\eta_i) = p(\eta_i \mid y_i, \psi^{(t)})$, Jensen's inequality gives +With the [posterior]{#def-posterior} $q_i(\eta_i) = p(\eta_i \mid y_i, \psi^{(t)})$, the distribution +of the random effects of a group given the data, Jensen's inequality gives [@dempster1977maximum] -$$\log L_i(\psi) \ge \underbrace{\mathbb{E}_{q_i}\bigl[\log p(y_i, \eta_i \mid \psi)\bigr]}_{Q_i(\psi \mid \psi^{(t)})} -- \mathbb{E}_{q_i}\bigl[\log q_i(\eta_i)\bigr], \tag{3}$$ +$$\log L_i(\psi) \ge \underbrace{\mathbb{E}_{q_i}\bigl[\log p(y_i, \eta_i \mid \psi)\bigr]}_{Q_i(\psi \mid \psi^{(t)})} - \mathbb{E}_{q_i}\bigl[\log q_i(\eta_i)\bigr], \tag{3}$$ with equality at $\psi = \psi^{(t)}$. EM alternates forming $Q = \sum_i Q_i$ and maximizing it, -so $\ell$ never decreases; near the optimum it converges linearly at the fraction of missing -information. ECM [@meng1993maximum] splits the M-step into conditional steps, ECME -[@liu1994ecme] takes some of them on the likelihood itself: $\Omega$ in closed form, structural +so $\log L$ never decreases; near the optimum it converges linearly at the fraction of missing +information. [ECM]{#def-ecm} [@meng1993maximum] splits the M-step into conditional steps, each over +some parameters with the others held, [ECME]{#def-ecme} [@liu1994ecme] takes some of them on the likelihood itself: $\Omega$ in closed form, structural parameters by optimization. [Sparsity priors](methods-sparsity-priors.html#hyperparameters) minimizes $-2Q$ instead. The methods replace the posterior, which has no closed form, by: @@ -58,17 +69,23 @@ minimizes $-2Q$ instead. The methods replace the posterior, which has no closed ### Laplace approximation -With $\Phi_i(\eta) = -2 \log p(y_i \mid \eta, \psi) - 2 \log p(\eta \mid \Omega) - K \log(2\pi)$, -the prior without the constant of the normal density, mode $\hat\eta_i$ and the Gauss-Newton +With + +$$\Phi_i(\eta) = -2 \log p(y_i \mid \eta, \psi) - 2 \log p(\eta \mid \Omega) - K \log(2\pi),$$ + +the prior without the constant of the normal density, the +[conditional mode]{#def-conditional-mode} $\hat\eta_i$, which minimizes $\Phi_i$ and so maximizes +the posterior, and the Gauss-Newton curvature $H_i$ of $\Phi_i$ at $\hat\eta_i$, Laplace's approximation of (2) is $-2 \log L_i \approx \Phi_i(\hat\eta_i) + \log \lvert H_i/2 \rvert$, the constant canceling against -that of the Gaussian integral. FOCEI minimizes +that of the Gaussian integral. [FOCEI]{#def-focei}, first-order conditional estimation with +interaction, minimizes $$F(\psi) = \sum_i \Bigl[ \Phi_i(\hat\eta_i) + \log \lvert H_i/2 \rvert \Bigr] \tag{4}$$ plus the full $-2 \log L$ of the conditions without a group. $\log \lvert H_i/2 \rvert$ is the -volume term. $H_i$ includes the derivatives of $\sigma$ in $\eta$, the interaction of FOCEI -[@wang2007derivation; @pinheiro1995approximations]. Conditional standard errors of the modes are +[volume term]{#def-volume-term}, the log determinant of the curvature of the posterior. $H_i$ includes the derivatives of $\sigma$ in $\eta$, the interaction of FOCEI +[@wang2007derivation; @pinheiro1995approximations]. [Conditional standard errors]{#def-conditional-standard-error} of the modes are the square roots of the diagonal of $2 H_i^{-1}$. The error has either sign and order $1 / n_i$ for $n_i$ data points in the group, with a factor that grows with $K$. @@ -79,12 +96,13 @@ Each evaluation, in C++: - **Modes.** One trust region per group, Gauss-Newton with SR1 correction, started from the last modes moved to first order along the outer step, stopped at `innerControl$steptol`; eigenvalue floor $10^{-10} \operatorname{tr}(H_i)/K$; trial points of all groups in one batched prediction. -- **Gradient.** By the envelope theorem the mode shift drops out: - $\nabla_\psi F = \sum_i \nabla_\psi \Phi_i \big|_{\hat\eta_i} + \sum_i \mathrm{d} \log \lvert H_i - \rvert / \mathrm{d}\psi$, with a Newton correction for the gradient left by the inner search. -- **Model Hessian.** Gauss-Newton Schur complement $\sum_i [\Phi_i^{\psi\psi} - - \Phi_i^{\psi\eta} (\Phi_i^{\eta\eta})^{-1} \Phi_i^{\eta\psi}]$, plus the volume-term Hessian - with second-order sensitivities, plus SR1 from the last three accepted gradients. +- **Gradient.** By the envelope theorem the mode shift drops out, + $$\nabla_\psi F = \sum_i \nabla_\psi \Phi_i \big|_{\hat\eta_i} + \sum_i \frac{\mathrm{d} \log \lvert H_i \rvert}{\mathrm{d}\psi},$$ + with a Newton correction for the gradient left by the inner search. +- **Model Hessian.** Gauss-Newton Schur complement + $$\sum_i \bigl[\Phi_i^{\psi\psi} - \Phi_i^{\psi\eta} (\Phi_i^{\eta\eta})^{-1} \Phi_i^{\eta\psi}\bigr],$$ + plus the volume-term Hessian with second-order sensitivities, plus SR1 from the last three + accepted gradients. - **Stop.** Model gain below `trustControl$mtol` in the region `rmax`, or five rejected trials flat within `ftol`. - **Hessian source.** With several groupings the outer loop is `trust()`, and `trustControl` takes @@ -99,7 +117,9 @@ Each evaluation, in C++: One C++ kernel evaluates all groups at once: the modes, the local model of each group and the integral on it. At the mode, -$\Phi_i(\hat\eta_i + \delta) \approx \Phi_i(\hat\eta_i) + g_i^\top \delta + \tfrac12 \delta^\top H_i \delta$, + +$$\Phi_i(\hat\eta_i + \delta) \approx \Phi_i(\hat\eta_i) + g_i^\top \delta + \tfrac12 \delta^\top H_i \delta,$$ + $g_i$ the gradient the inner search leaves. The block $H_{NN}$ of the normal random effects is factored once; eliminating it gives the outer model, $\Phi_i^{\psi\psi} - \Phi_i^{\psi N} H_{NN}^{-1} \Phi_i^{N\psi}$, and the curvature $H_{LL} - H_{LN} H_{NN}^{-1} H_{NL}$ left on the other coordinates @@ -112,10 +132,12 @@ $\log \lvert H_{NN}/2 \rvert$ and $W_i = H_{NN}^{-1}$. For Gauss-Newton $H_i$, from second-order sensitivities, -$$\frac{\mathrm{d} \log \lvert H_i \rvert}{\mathrm{d} \psi_k} -= \operatorname{tr}\Bigl(H_i^{-1} \frac{\partial H_i}{\partial \psi_k}\Big|_\eta\Bigr) -+ \sum_l \operatorname{tr}\Bigl(H_i^{-1} \frac{\partial H_i}{\partial \eta_l}\Bigr) \frac{\mathrm{d} \hat\eta_l}{\mathrm{d} \psi_k}, -\qquad \frac{\mathrm{d}\hat\eta}{\mathrm{d}\psi} = -(\Phi_i^{\eta\eta})^{-1} \Phi_i^{\eta\psi}, \tag{5}$$ +$$\begin{aligned} +\frac{\mathrm{d} \log \lvert H_i \rvert}{\mathrm{d} \psi_k} +&= \operatorname{tr}\Bigl(H_i^{-1} \frac{\partial H_i}{\partial \psi_k}\Big|_\eta\Bigr) \\ +&\quad + \sum_l \operatorname{tr}\Bigl(H_i^{-1} \frac{\partial H_i}{\partial \eta_l}\Bigr) \frac{\mathrm{d} \hat\eta_l}{\mathrm{d} \psi_k}, \\ +\frac{\mathrm{d}\hat\eta}{\mathrm{d}\psi} &= -(\Phi_i^{\eta\eta})^{-1} \Phi_i^{\eta\psi}, +\end{aligned} \tag{5}$$ | `control` | volume term | |---|---| @@ -129,15 +151,19 @@ curvature of the volume term without third-order sensitivities, as `summary()` s ## Adaptive sparse-grid quadrature Laplace biases $\Omega$ for skewed posteriors, as for oral doses sampled near absorption. The -cubature $\int e^{-\Phi_i/2}\, \mathrm{d}\eta \approx \sum_b W_b\, e^{-\Phi_i(\eta_b)/2}$ removes -that error level by level. It combines the nested Genz-Keister rules [@genz1996fully], 1, 3, 9, 19 -and 35 points exact to degree 1, 5, 15, 29 and 51, by Smolyak's sparse grid -[@smolyak1963quadrature; @heiss2008likelihood], +cubature + +$$\int e^{-\Phi_i/2}\, \mathrm{d}\eta \approx \sum_b W_b\, e^{-\Phi_i(\eta_b)/2}$$ + +removes that error level by level. It combines the nested Genz-Keister rules [@genz1996fully], 1, 3, 9, 19 +and 35 points exact to degree 1, 5, 15, 29 and 51, by the [Smolyak]{#def-smolyak} [sparse grid]{#def-sparse-grid} +[@smolyak1963quadrature; @heiss2008likelihood], a sum of tensor products of one-dimensional rules +with far fewer nodes than the full tensor grid, $$A(L, K) = \sum_{\lvert \mathbf{i} \rvert \le L} \Delta^{i_1} \otimes \cdots \otimes \Delta^{i_K}, \tag{6}$$ -$\Delta^l$ the difference of the one-dimensional rules of levels $l$ and $l - 1$. Level $L$ is exact -for total degree $2(L - K) + 1$ against the Gaussian, with nodes polynomial in $K$ (for $K = 3$, +$\Delta^l$ the difference of the one-dimensional rules of levels $l$ and $l - 1$. [Level]{#def-level} $L$, the bound on the sum $\lvert \mathbf{i} \rvert$ of the one-dimensional +levels, is exact for total degree $2(L - K) + 1$ against the Gaussian, with nodes polynomial in $K$ (for $K = 3$, levels 3 to 7 have 1, 7, 19, 45, 117); level $K$ is the single Laplace node. The grid sits on the FOCEI Gaussian $\mathcal{N}(\hat\eta_i, 2 H_i^{-1})$ and moves with $\psi$ [@clausen2009maximum]. Negative weights make $\log L_i$ a signed log-sum-exp; a nonpositive sum, an unresolved posterior, @@ -160,40 +186,50 @@ move of the grid with $\psi$ is not differentiated. evaluated neighbors join the grid, their change is the estimate, and a group above the tolerance is capped. With no refinement the grid is that of (6); for $K = 20$ levels $K + 1$ to $K + 3$ have 41, 801 and 10041 nodes. -- **Step.** Trust region over all parameters on frozen nodes. For mu-referenced fixed effects, - $\phi_i = D_i \beta + \eta_i$, nodes are frozen in $\phi$, need no sensitivities and hold over - larger steps. -- **Stop.** A Newton step on the rebuilt nodes would gain less than `tolDecrement`, or +- **Step.** Trust region over all parameters on [frozen nodes]{#def-frozen-nodes}: nodes and + weights held while $\psi$ moves within the step, so the quadrature is a smooth function of $\psi$. + [Fixed effects]{#def-fixed-effect} are the coefficients of an effect formula, the same for all + groups. They are [mu-referenced]{#def-mu-referencing} where the formula sets + $\phi_i = D_i \beta + \eta_i$, $D_i$ the design row of the group, so a shift of $\beta$ acts as a + shift of $\eta_i$; there nodes are frozen in $\phi$, need no sensitivities and hold over larger + steps. +- **Stop.** The [Newton decrement]{#def-newton-decrement}, the decrease of $-2 \log L$ that a Newton + step on the rebuilt nodes would make by the quadratic model, is below `tolDecrement`, or $-2 \log L$ rose after a step on unchanged levels, so the step lies below what the levels resolve. Either way the fit is stationary at the levels reached, capped ones included; it returns the iterate of lowest $-2 \log L$ on the highest levels, and the stage trace records the levels, errors and caps per group. At the estimate, importance sampling ($t_5$ proposal at the mode, shifted lattice points) flags -groups whose two estimates differ by more than three standard errors plus the level error, or with Pareto shape -[@vehtari2024pareto] above 0.7. +groups whose two estimates differ by more than three standard errors plus the larger of the level +error and `tol` over the number of groups, or with [Pareto shape]{#def-pareto-shape} $\hat k$ +[@vehtari2024pareto] above 0.7, $\hat k$ the shape of a generalized Pareto distribution fitted to +the largest importance weights; above 0.7 the tail is so heavy that the estimate is unreliable. ## Laplace EM `method = "laplaceEM"` runs ECME: a trust-region run of at most `maxCm1Iter` (default 30) iterations of -the structural parameters on the likelihood over frozen nodes of level $K + 1$, then every block of $\Omega$ from $S = G^{-1} \sum_i M_i$ with the posterior +the structural parameters on the likelihood over frozen nodes of level $K + 1$, then every [block]{#def-block} of $\Omega$, the random effects of one ID with full covariance and +independent of the other blocks, from $S = G^{-1} \sum_i M_i$ with the posterior second moments $M_i = \hat\eta_i \hat\eta_i^\top + 2 H_i^{-1}$ (modes alone would shrink -$\Omega$). It stops when parameter change and extrapolated remaining distance are below `epsEcm` -(default `1e-5`), or after `maxEcm` (default 200) iterations. Settings come from `control$quadrature`. +$\Omega$). It stops when parameter change and extrapolated remaining distance are below `epsECM` +(default `1e-5`), or after `maxECM` (default 200) iterations. Settings come from `control$quadrature`. ## SAEM `method = "saem"` uses posterior draws, with no Gaussian assumption and equal cost for any $K$. -Stochastic-approximation EM [@delyon1999convergence] averages the sufficient statistics by a +[Stochastic-approximation EM]{#def-saem} (SAEM) [@delyon1999convergence] averages the sufficient statistics by a Robbins-Monro recursion [@robbins1951stochastic], -$$s_k = s_{k-1} + \gamma_k \bigl( S(y, \eta^{(k)}) - s_{k-1} \bigr), \qquad -\eta^{(k)} \sim q(\cdot \mid \psi^{(k-1)}), \qquad \psi^{(k)} = \hat\psi(s_k), \tag{7}$$ +$$\begin{aligned} +s_k &= s_{k-1} + \gamma_k \bigl( S(y, \eta^{(k)}) - s_{k-1} \bigr), \\ +\eta^{(k)} &\sim q(\cdot \mid \psi^{(k-1)}), \qquad \psi^{(k)} = \hat\psi(s_k), +\end{aligned} \tag{7}$$ -converging to a stationary point of $\ell$ [@delyon1999convergence; @kuhn2004coupling]. $\Omega$ +converging to a stationary point of $\log L$ [@delyon1999convergence; @kuhn2004coupling]. $\Omega$ follows from $\sum_i \eta_i \eta_i^\top$, mu-referenced fixed effects by generalized least squares, other structural parameters from an average of quadratic models at the draws, whose Newton -step has the marginal score as fixed point. +step has the [marginal score]{#def-marginal-score}, the gradient of $\log L(\psi)$, as fixed point. | phase | rule | |---|---| @@ -201,24 +237,26 @@ step has the marginal score as fixed point. | burn-in | $\gamma_k = 1$, variances shrink at most 5 % per iteration; ends when no parameter drifts over `window` | | averaging | $\gamma_k = k^{-0.7}$, $k$ counted from the end of burn-in, mean of iterates [@kushner2003stochastic]; ends when the expected Monte Carlo rise of $-2 \log L$ is below `mcTol` | -SAEM neither forms $\ell$ nor raises it in every iteration; `em()` reports the quadrature of level +SAEM neither forms $\log L$ nor raises it in every iteration; `em()` reports the quadrature of level $K + 2$ with standard errors from the quadrature Hessian. SAEM suits many random effects and skewed, heavy-tailed or multimodal posteriors [@kuhn2004coupling]. ### Spike-and-slab random effects -A spike-and-slab random effect $\eta_{ij} = z_{ij} v_{ij}$ has an indicator $z_{ij}$ with +A [spike-and-slab]{#def-spike-and-slab} random effect $\eta_{ij} = z_{ij} v_{ij}$ is 0 (spike) or +normal (slab) by an [indicator]{#def-indicator} $z_{ij}$ with $\Pr(z_{ij} = 1) = p$ and a slab value $v_{ij} \sim \mathcal{N}(0, \tau^2)$ [@mitchell1988bayesian; @george1993variable]. Per iteration, after the normal random effects: - **Local model.** Per group the quadratic model of the data term in the slab values, with the curvature clipped to be positive semidefinite, refreshed at the mean of the slab-only Gaussian. -- **Collapsed indicator moves.** Each indicator of a group once per sweep, in random order, all +- **[Collapsed indicator moves]{#def-collapsed-move}.** Each indicator of a group once per sweep, in random order, all groups at once. The other slab values of the group move with $v_{ij}$ along the regression of the local model, $v_o = b_o + x\,u_o$, so the state $b$ with $z_{ij} = 0$ and the line stay fixed. On this line the slab mass $I = \int f(x)\,dx$, $f$ the joint density of data and prior, is a Gauss-Hermite sum on the local Gaussian $\mathcal{N}(m, s^2)$ with the exact data - term at `nodes` (default 3) points, which gives the conditional inclusion probability with the slab value + term at `nodes` (default 3) points, which gives the conditional [inclusion probability]{#def-inclusion-probability} + $\Pr(z_{ij} = 1)$ given the data, with the slab value integrated out [@liu1994collapsed], $$\hat\pi_{ij} = \frac{I}{I + f_0}, \qquad f_0 = f \text{ at } z_{ij} = 0 . \tag{8}$$ @@ -231,7 +269,9 @@ $\Pr(z_{ij} = 1) = p$ and a slab value $v_{ij} \sim \mathcal{N}(0, \tau^2)$ the slab, scaled by the conditional standard deviations of the local model. - **A-step and M-steps.** $p$ and $\tau$ follow from Robbins-Monro averages of $\sum \hat\pi_{ij}$ and $\sum \hat\pi_{ij}\,\mathbb{E}(x^2 \mid z_{ij} = 1)$, the - Rao-Blackwellized statistics [@casella1996rao] of the sweep, in place of the drawn indicators. An + [Rao-Blackwellized]{#def-rao-blackwellization} statistics [@casella1996rao] of the sweep: + conditional expectations in place of the drawn indicators, with the same mean and smaller + variance. An effect the data do not inform has $\hat\pi_{ij} = p$ and second moment $\tau^2$ and leaves both unchanged; counts of drawn indicators would instead let $p$ wander to 1 in burn-in, where $\gamma_k = 1$. In burn-in the odds $p / (1 - p)$ and $\tau$ change by a factor in @@ -240,8 +280,11 @@ $\Pr(z_{ij} = 1) = p$ and a slab value $v_{ij} \sim \mathcal{N}(0, \tau^2)$ $p_0$ is one minus the mean of $\hat\pi_{ij}$ over the late sweeps, an effect selected where it is below 1/2. An `em` fit as `init` starts the chain at the selected values of that fit, the indicators set where they are not 0, which checks a FOCEI optimum by SAEM. $-2 \log L$ at the -estimate is that of `method = "focei"`; with Dirichlet-process random effects beside on more than -14 groups, or with `integral = "importance"`, it comes from sequential importance sampling over the +estimate is that of `method = "focei"`. +[Dirichlet-process random effects]{#def-dirichlet-process-random-effects} cluster the groups: the +groups of a cluster share one value, 0 for the population cluster and a normal draw for each other +cluster. With them beside on more than 14 groups, or with `integral = "importance"`, $-2 \log L$ +comes from sequential importance sampling over the partitions ([Sparsity priors](methods-sparsity-priors.html#importance-sampling)), each group summing over the subsets of the spike-and-slab effects that reach the group data. diff --git a/vignettes/articles/methods-objective.Rmd b/vignettes/articles/methods-objective.Rmd index 7a96d2c8..470db6f6 100644 --- a/vignettes/articles/methods-objective.Rmd +++ b/vignettes/articles/methods-objective.Rmd @@ -5,16 +5,23 @@ csl: ieee.csl link-citations: true --- -Without a prior, dMod2 estimates by maximum likelihood and minimizes $-2 \log L$. With a prior, -it minimizes $-2 \log$ of the posterior up to a constant, and the minimum is the maximum a -posteriori estimate [@kaschek2019dmod]. The methods articles call the minimized quantity the -objective function $\mathcal{J}(\theta)$, $-2 \log L$ or $-2 \log$ of the posterior. Guide: [Setting up models](guide-model.html#likelihood-and-prior); derivatives: +Without a prior, dMod2 estimates by [maximum likelihood]{#def-maximum-likelihood}: it chooses +the parameters $\theta$ that maximize the [likelihood]{#def-likelihood} $L(\theta)$, the +probability density of the observed data read as a function of $\theta$, and minimizes +[$-2 \log L$]{#def-minus-2-log-l}, minus twice the log-likelihood, (1). With a +[prior]{#def-prior}, a probability density $\pi(\theta)$ of the parameters before the data +([Prior](#prior)), it minimizes $-2 \log$ of the posterior up to a constant, and the minimum is the +maximum a posteriori estimate [@kaschek2019dmod]. The methods articles call the minimized quantity +the [objective function]{#def-objective-function} $\ell(\theta)$, $-2 \log L$ or $-2 \log$ +of the posterior; in dMod2 it is an [`objfn`]{#def-objfn}, a function object that returns value, +gradient and Hessian. Guide: [Setting up models](guide-model.html#likelihood-and-prior); derivatives: [Sensitivities and Hessians](methods-sensitivities.html). ## Data term `normL2()` computes twice the negative log-likelihood of independent Gaussian errors, for data -$y_j$, predictions $g_j(\theta)$ and standard deviations $\sigma_j(\theta)$: +$y_j$, [predictions]{#def-prediction} $g_j(\theta)$, the model values of the observables at the +measurement times from the chain `g*x*p` ([Setting up models](guide-model.html)), and standard deviations $\sigma_j(\theta)$: $$-2 \log L(\theta) = \sum_j \left( \frac{(y_j - g_j(\theta))^2}{\sigma_j(\theta)^2} + \log \sigma_j(\theta)^2 \right) + \text{const}. \tag{1}$$ @@ -24,9 +31,13 @@ term of (1) falls as $\sigma_j$ grows, the second rises. ## Error model -$\sigma_j$ comes from the data column `sigma` where set, otherwise from the error model, an -`obsfn` $\sigma = e(g, \theta)$ of prediction and parameters. A constant $\sigma$ on a log-scale -observable $y = \log(s\, x + o)$ is a relative error: to first order, $\sigma$ in $\log z$ is +$\sigma_j$ comes from the data column `sigma` where set, otherwise from the [error model]{#def-error-model} +$\sigma = e(g, \theta)$, a function of prediction and parameters. The error model is an +[`obsfn`]{#def-obsfn}, a function object from `Y()` that maps states to observables or, here, to +standard deviations. The parameters of $\theta$ that enter $e$ are the +[error parameters]{#def-error-parameters}; (1) estimates them with the model parameters. A constant +$\sigma$ on a log-scale observable $y = \log(s\, x + o)$ is a +[relative error]{#def-relative-error}, a standard deviation proportional to the value: to first order, $\sigma$ in $\log z$ is $\sigma z$ in $z$. ## Prior @@ -40,14 +51,17 @@ added to the data term by `+`; $\log s_k^2$ enters only where $s_k$ is a paramet estimated $s_k$ from growing, but (2) then has no minimum: $\theta_k = \mu_k$ with $s_k \to 0$ lowers it without limit, so an estimated $s_k$ needs a lower bound. On the log scale, a prior far wider than the data leaves determined parameters in place and keeps undetermined ones finite, so the minimum exists without -bounds. The Hessian of (2) is $2/s_k^2$ on the diagonal. +bounds. A [determined parameter]{#def-determined-parameter} has a profile likelihood with a +confidence interval of finite length ([Profiles](methods-profiles.html)); an undetermined one moves +to $\pm\infty$ at almost constant $-2 \log L$. The Hessian of (2) is $2/s_k^2$ on the diagonal. ## Further terms - `constraintStability()`: keeps the steady state of a `Pimpl()` stable ([Steady states](methods-steady-states.html#stability)). -- `datapointL2()`: a data point whose value is a parameter, for validation profiles - [@kreutz2012likelihood]. +- `datapointL2()`: a data point whose value is a parameter, for + [validation profiles]{#def-validation-profile}, profiles over the value of a hypothetical data + point that give a confidence interval of a prediction [@kreutz2012likelihood]. Each term is an `objfn`; a sum keeps the parts as attributes, so profiles and likelihood ratios read the data term alone. diff --git a/vignettes/articles/methods-profiles.Rmd b/vignettes/articles/methods-profiles.Rmd index 96156d10..bc1d600c 100644 --- a/vignettes/articles/methods-profiles.Rmd +++ b/vignettes/articles/methods-profiles.Rmd @@ -11,30 +11,50 @@ without a quadratic approximation [@raue2009structural; @kreutz2012likelihood]. ## Profile and threshold -The objective function $\mathcal{J}(\theta) = -2 \log L(\theta) - 2 \log \pi(\theta)$ is the data term plus the -prior $\pi$ ([Likelihood and prior](methods-objective.html)). Along the profile of $\theta_i$ the -other parameters minimize $\mathcal{J}$, +The [objective]{#def-objective} function $\ell(\theta) = -2 \log L(\theta) - 2 \log \pi(\theta)$ is the +[data term]{#def-data-term} $-2 \log L$ plus the [prior term]{#def-prior-term} $-2 \log \pi$ of the +prior $\pi$ ([Likelihood and prior](methods-objective.html)). `normL2()` returns the data term as +attribute `data`, `constraintL2()` the prior term as `prior`, and `profile()` keeps both as columns. +The [profile]{#def-profile} of $\theta_i$ is $\ell$ minimized over all other parameters as a +function of $\theta_i = c$. The minimizing values of the other parameters form the +[parameter path]{#def-parameter-path} $\hat\theta(c)$, -$$\hat\theta(c) = \operatorname*{arg\,min}_{\theta \,:\, \theta_i = c} \mathcal{J}(\theta) , \tag{1}$$ +$$\hat\theta(c) = \operatorname*{arg\,min}_{\theta \,:\, \theta_i = c}\, \ell(\theta) , \tag{1}$$ -and the profile likelihood is the data term along this path, +and the [profile likelihood]{#def-profile-likelihood} is the objective along this path, -$$\mathrm{PL}_i(c) = -2 \log L\bigl(\hat\theta(c)\bigr) . \tag{2}$$ +$$\mathrm{PL}_i(c) = \ell\bigl(\hat\theta(c)\bigr) . \tag{2}$$ + +A parameter that moves with $\theta_i$ along the path compensates the change of $\theta_i$ in the +predictions (`plotPaths()`). Without a prior, (2) is the minimum of $-2 \log L$ with $\theta_i = c$. By the likelihood ratio test, the rise $\mathrm{PL}_i(c) - \mathrm{PL}_i(\hat\theta_i)$ from the optimum $\hat\theta_i$ below -the $1 - \alpha$ quantile of $\chi^2_1$ (3.84 for 95 %) defines an asymptotic confidence interval, -invariant under reparameterization of $\theta_i$. Without a prior the optimum is the minimum of -(2); with a prior (2) may fall below the value at the optimum, and the rise is still measured from -there. `profileThreshold()` computes the threshold, `method = "F"` the finite-sample one for -estimated standard deviations. A prior wide against the data curvature keeps (1) finite where the +the [threshold]{#def-threshold}, the $1 - \alpha$ quantile of $\chi^2_1$ (3.84 for 95 %), defines an +asymptotic [confidence interval]{#def-confidence-interval}, the set of values $c$ compatible with the data, +invariant under reparameterization of $\theta_i$. The optimum is the minimum of (2). +`profileThreshold()` computes the threshold, `method = "F"` the +[finite-sample threshold]{#def-finite-sample-threshold} $n \log(1 + F_{1,\nu,1-\alpha}/\nu)$ with $n$ +data points and $\nu = n - p$ for $p$ estimated mean parameters, exact for Gaussian errors with one +estimated standard deviation. A prior wide against the data curvature keeps (1) finite where the data do not determine $\theta_i$ and changes (2) little where they do. -`profile()` stops on $\mathcal{J}$ by default; `stepControl = list(stop = "data")` ends a profile at the -threshold of (2), and `confint(val.column = "data")` reads the interval off (2). +`profile()` stops on (2) by default; `stepControl = list(stop = "data")` ends a profile at the +threshold of the data term $-2 \log L\bigl(\hat\theta(c)\bigr)$ along the path, and +`confint(val.column = "data")` reads the interval off that term. ## Shapes +A parameter is [identifiable]{#def-identifiable} when (2) exceeds the threshold on both sides, otherwise +[non-identifiable]{#def-non-identifiable}: [practically non-identifiable]{#def-practical-non-identifiability} +when the profile stays below the threshold on one side or both for the given data, +[structurally non-identifiable]{#def-structural-non-identifiability} when different parameter values give +the same prediction of every observable and the profile is flat +([Structural identifiability](methods-symmetries.html#structural-identifiability)). A +[symmetry]{#def-symmetry} is a transformation of the parameters that leaves every observable unchanged; a +[gauge]{#def-gauge} fixes coordinates so that each orbit of the symmetry meets the fixed values in one +point ([Gauge and reduction](methods-symmetries.html#gauge-and-reduction)). + | shape of (2) | meaning | |---|---| | above the threshold on both sides | finite interval | @@ -43,7 +63,8 @@ threshold of (2), and `confint(val.column = "data")` reads the interval off (2). On the log scale, a one-sided profile towards $-\infty$ means the reaction can be switched off, towards $+\infty$ that the process is in equilibrium on the time scale of the data, replaceable by a -large fixed value or the quasi-steady state. Both limits give a smaller model with the same fit +large fixed value or the quasi-steady state. Both limits give a +[reduced model]{#def-reduced-model}, the model with the parameter at the limit, with the same fit [@maiwald2016driving]. Each profile tests one limit with all other parameters free; several limits together need a likelihood ratio test of the reduced model. @@ -53,18 +74,22 @@ A profile is a sequence of constrained fits, each started from the last point. - `method = "optimize"` steps $\theta_i$ and refits the others with `trust()`, one converged fit per point. -- `method = "integrate"` follows the constrained optimum of the Lagrangian - $\mathcal{J}(\theta) + \lambda\,(\theta_i - c)$, where $\nabla \mathcal{J} + \lambda e_i = 0$ and $\theta_i = c$. - Differentiating in $c$ gives the path equation +- `method = "integrate"`, the [integration-based profile]{#def-integration-based-profile}, follows + the [constrained optimum]{#def-constrained-optimum} $\hat\theta(c)$ of (1), the stationary point of + the Lagrangian $\ell(\theta) + \lambda\,(\theta_i - c)$, where $\nabla \ell + \lambda e_i = 0$ and $\theta_i = c$. + Differentiating in $c$ gives the [path equation]{#def-path-equation}, the linear system for + $\mathrm{d}\theta/\mathrm{d}c$ that the profile follows in Euler steps, $$\begin{pmatrix} H & e_i \\ e_i^\top & 0 \end{pmatrix} \begin{pmatrix} \mathrm{d}\theta/\mathrm{d}c \\ \mathrm{d}\lambda/\mathrm{d}c \end{pmatrix} = \begin{pmatrix} 0 \\ 1 \end{pmatrix} \tag{3}$$ - with the Hessian $H$ of $\mathcal{J}$: one evaluation and one linear solve per step. The step solves (3) - with $-\gamma \nabla \mathcal{J}$ in place of the upper zero, which pulls it back to the constrained - optimum ($\gamma = 1$ by default, adapted to the size of the pull); with a Gauss-Newton $H$ the - path still drifts, and `algoControl = list(reoptimize = TRUE)` corrects each step by a short fit. + with the Hessian $H$ of $\ell$: one evaluation and one linear solve per step. The step solves (3) + with $-\gamma \nabla \ell$ in place of the upper zero, which pulls it back to the constrained + optimum ($\gamma = 1$ by default, adapted to the size of the pull). With a Gauss-Newton $H$ the + path still drifts, so each step is then corrected by a short fit of the other parameters with + `trust()`, at most `optControl$iterlim = 10` iterations; `algoControl = list(reoptimize = FALSE)` + leaves out the fit. Step control and stops: @@ -74,26 +99,34 @@ Step control and stops: | step doubles | mismatch below `0.3 * atol`, or below `0.3 * rtol` relative | | side ends | objective (or data term, `stop = "data"`) up by the threshold; `limits` relative to the optimum reached; `limit` steps | -A point of $\mathcal{J}$ below the start value is a better optimum: fit and profiles are then to be repeated +A point of $\ell$ below the start value is a better optimum: fit and profiles are then to be repeated from it. Where the curvature jumps, the step shrinks to `min` and stays on the profile. ## Prediction profiles -A prediction $z = g(t, \theta)$ has the profile likelihood +A prediction $z = g(t, \theta)$ has the [prediction profile likelihood]{#def-prediction-profile-likelihood}, +the objective minimized under the constraint $g(t, \theta) = z$, -$$\mathrm{PPL}(z) = -2 \log L\bigl(\hat\theta(z)\bigr) , \quad -\hat\theta(z) = \operatorname*{arg\,min}_{\theta \,:\, g(t, \theta) = z} \mathcal{J}(\theta) , \tag{4}$$ +$$\begin{aligned} +\mathrm{PPL}(z) &= \ell\bigl(\hat\theta(z)\bigr) , \\ +\hat\theta(z) &= \operatorname*{arg\,min}_{\theta \,:\, g(t, \theta) = z}\, \ell(\theta) , +\end{aligned} \tag{4}$$ -whose threshold gives a confidence interval of the prediction [@kreutz2012likelihood]; without a -prior it is the image of the parameter region at the $\chi^2_1$ threshold, not of the joint region. +whose threshold gives a confidence interval of the prediction [@kreutz2012likelihood], over several +$t$ a pointwise confidence band. Without a prior the interval is the image of the +[parameter region]{#def-parameter-region} at the $\chi^2_1$ threshold, the set of $\theta$ with +$-2 \log L$ less than 3.84 above the minimum, not of the [joint region]{#def-joint-region}, which uses +the $\chi^2_p$ quantile of all $p$ parameters at once and is larger. -A validation data point makes $z$ a parameter $v$, tied to the prediction by +A [validation data point]{#def-validation-data-point}, a hypothetical measurement $v$ of the prediction +with standard deviation $\sigma_v$, makes $z$ a parameter $v$, tied to the prediction by $$\left( \frac{g(t, \theta) - v}{\sigma_v} \right)^2 . \tag{5}$$ -The profile of $v$ is (4) for $\sigma_v \to 0$ and lies below (4) otherwise, so the interval of $v$ is -wider: for a quadratic (4) of half-width $w$ the half-width becomes $(w^2 + \Delta \sigma_v^2)^{1/2}$, +The [validation profile]{#def-validation-profile}, the profile of $v$, is (4) for $\sigma_v \to 0$ and +lies below (4) otherwise. The interval of $v$, the range of a new measurement compatible with model +and data, is therefore wider: for a quadratic (4) of half-width $w$ the half-width becomes $(w^2 + \Delta \sigma_v^2)^{1/2}$, $\Delta$ the threshold. `datapointL2()` builds (5) as an `objfn` from the evaluation of `normL2()`, which therefore predicts at $t$ (`times = t`). With `attrName = "data"`, (5) adds to the data term, so `stop = "data"` and `confint(val.column = "data")` include it. Where the model cannot follow $v$, diff --git a/vignettes/articles/methods-sensitivities.Rmd b/vignettes/articles/methods-sensitivities.Rmd index c3c8090e..2370df25 100644 --- a/vignettes/articles/methods-sensitivities.Rmd +++ b/vignettes/articles/methods-sensitivities.Rmd @@ -23,19 +23,24 @@ through every function object, without finite differences. Guide: ## Forward sensitivities -The sensitivities $S = \partial x / \partial \theta$ of $\dot x = f(x, \theta)$, -$x(t_0) = x_0(\theta)$, solve +The [sensitivities]{#def-sensitivity} $S = \partial x / \partial \theta$ of $\dot x = f(x, \theta)$, +$x(t_0) = x_0(\theta)$, the derivatives of the trajectory with respect to the parameters, solve $$\dot S = \frac{\partial f}{\partial x}\, S + \frac{\partial f}{\partial \theta}, \qquad S(t_0) = \frac{\partial x_0}{\partial \theta}, \tag{1}$$ -$n_x n_\theta$ further equations. cppDE evaluates $f$ on dual numbers, one tangent per parameter, -and steps states and tangents together. The step-size control includes the tangents (`sensErrCon`), +$n_x n_\theta$ further equations. cppDE evaluates $f$ on [dual numbers]{#def-dual-number}, numbers with a value part and derivative +parts whose arithmetic propagates first derivatives exactly by the chain rule, one +[tangent]{#def-tangent} (derivative part) per parameter. States and tangents step forward in time +together, the [forward sweep]{#def-forward-sweep} of [forward mode]{#def-forward-mode} +differentiation. The step-size control includes the tangents (`sensErrCon`), so the sensitivities are as accurate as the states -([forward sensitivities](https://dmodverse.github.io/cppDE/articles/methods-forward.html)). An event -passes the tangents through the saltation matrix of the jump +([forward sensitivities](https://dmodverse.github.io/cppDE/articles/methods-forward.html)). An [event]{#def-event}, a jump of the states at a time or on a condition, +passes the tangents through the [saltation matrix]{#def-saltation-matrix} of the jump, which maps +the sensitivities before the jump to those after it ([events](https://dmodverse.github.io/cppDE/articles/methods-events.html)). Every further function -object of `g*x*p` multiplies by the Jacobian of that object, e.g. $g_x S + g_\theta$ for +object of the [chain `g*x*p`]{#def-chain-gxp}, parameter transformation `p`, prediction `x` and +observation `g` ([Setting up models](guide-model.html)), multiplies by the Jacobian of that object, e.g. $g_x S + g_\theta$ for $y = g(x, \theta)$. ## Gradient and Hessian of the objective @@ -44,7 +49,8 @@ Each data point adds, up to a constant, $$\ell_j = r_j^2 + \log \sigma_j^2, \qquad r_j = \frac{g_j - y_j}{\sigma_j}, \tag{2}$$ -the summand of [the data term](methods-objective.html#data-term). For fixed $\sigma_j$ and +the summand of [the data term](methods-objective.html#data-term), with the [residual]{#def-residual} +$r_j$, the difference of prediction and data divided by the standard deviation. For fixed $\sigma_j$ and $J = \partial r / \partial \theta$, the gradient is $2 J^\top r$ and the Hessian $$\nabla^2 \sum_j r_j^2 = 2 J^\top J + 2 \sum_j r_j\, \nabla^2 r_j . \tag{3}$$ @@ -69,13 +75,16 @@ $2 (1 - r_j^2) / \sigma_j$. ## Forward over forward -Differentiating (1) again gives $n_x n_\theta (n_\theta + 1) / 2$ equations and the exact Hessian, +[Forward over forward]{#def-forward-over-forward} applies forward tangents to the forward +sensitivities. Differentiating (1) again gives $n_x n_\theta (n_\theta + 1) / 2$ equations and the exact Hessian, for small models. ## Reverse sweep -The gradient of the objective alone follows from one backward sweep with the multipliers -$\lambda(t)$, zero after the last measurement, and the terms $\ell_j$ of the data at the +The [adjoint]{#def-adjoint} or [multiplier]{#def-multiplier} $\lambda(t)$ is the sensitivity of +the objective to a change of the state at time $t$. The gradient of the objective alone follows +from one [reverse sweep]{#def-reverse-sweep}, backward in time from the data to the start, with +$\lambda$ zero after the last measurement and the terms $\ell_j$ of the data at the measurement times $t_j$, $$\begin{aligned} @@ -86,11 +95,14 @@ $$\begin{aligned} + \sum_j \frac{\partial \ell_j}{\partial \theta} . \end{aligned} \tag{5}$$ -cppDE uses the *discrete adjoint* of the -integrator steps, the exact derivative of the computed objective, with checkpoints of the forward -trajectory ([reverse mode](https://dmodverse.github.io/cppDE/articles/methods-reverse.html)). The -cost is a few times the value, independent of $n_\theta$. The value pass solves without -sensitivities, and the sweep uses the step grid of that pass. `Pimpl()` passes the sweep through +cppDE uses the [*discrete adjoint*]{#def-discrete-adjoint} of the +integrator steps, the [reverse mode]{#def-reverse-mode} applied to the steps instead of to the ODE +and the exact derivative of the computed objective. [Checkpoints]{#def-checkpoint} store the start +of every accepted forward step (state, time, step size, controller state), and the sweep applies +the transposed steps from these, last to first +([reverse mode](https://dmodverse.github.io/cppDE/articles/methods-reverse.html)). The +cost is a few times the value, independent of $n_\theta$. The [value pass]{#def-value-pass}, the forward +solve that computes the objective value, runs without sensitivities, and the sweep uses the step grid of that pass. `Pimpl()` passes the sweep through the Jacobian of the root ([Steady states](methods-steady-states.html#derivatives-of-the-root)). ### Accuracy of a reverse gradient @@ -109,7 +121,8 @@ a fixed `gradtol` does not keep the relative error small ([checking the sweep](https://dmodverse.github.io/cppDE/articles/methods-reverse-checks.html)). A refined sweep differentiates the trajectory with substeps, not the computed one. Under `refine` it -therefore returns, per seed, the first-order change of the seeded functional between the two: over +therefore returns, per [seed]{#def-seed}, the vector the sweep starts from in the observed values, +the first-order change of the seeded functional between the two: over the steps, the adjoint at the step end times the difference of the end states, plus the seeds times the difference of the observed values ([value correction](https://dmodverse.github.io/cppDE/articles/methods-reverse-checks.html#value-correction)). @@ -120,7 +133,8 @@ correction. ## Forward over reverse -Forward tangents, one per parameter, ride on the backward sweep, which returns one Hessian column +[Forward over reverse]{#def-forward-over-reverse} applies forward tangents, one per parameter, to +the backward sweep, which returns one Hessian column per tangent. Cost grows like a forward solve; the $n_\theta^2$ Hessian entries are accumulated, but no $n_x n_\theta^2$ second-order sensitivities are integrated or stored ([forward over reverse](https://dmodverse.github.io/cppDE/articles/methods-forward-reverse.html)). @@ -138,15 +152,20 @@ $$\sum_r w_r\, \nabla^2 z_r\, v_k + J^\top \dot w_k \tag{6}$$ for every $k$, $z_r$ prediction or sigma of row $r$, $J$ their Jacobian. With the gradient of the row loss as seed and $L_r J_r v_k$ as tangent derivative, $L_r$ the Hessian (4), the sweep gives -$\Phi_i^{\eta\eta}$, $\Phi_i^{\eta\psi}$ and the mode shift -$\mathrm{d}\hat\eta / \mathrm{d}\psi = -(\Phi_i^{\eta\eta})^{-1} \Phi_i^{\eta\psi}$. The trace +the second derivatives $\Phi_i^{\eta\eta}$ and $\Phi_i^{\eta\psi}$ of $\Phi_i$ in $\eta$ and in +$\eta$, $\psi$, and the mode shift + +$$\frac{\mathrm{d}\hat\eta}{\mathrm{d}\psi} = -(\Phi_i^{\eta\eta})^{-1} \Phi_i^{\eta\psi} .$$ + +The trace gradients are linear in $M$: seed $j$ is $2 L_r J_{r,j}$, with tangent derivative the derivative of $L_r$ contracted with $J_{r,j}$ and $J_{r,k}$. With $U_{jk}$ slice $k$ of the result for seed $j$, $$\nabla \operatorname{tr}(M H_i) = \sum_{j,k} M_{jk}\, U_{jk} \tag{7}$$ for every symmetric $M$: $K$ seeds for any number of matrices. Hessian rows and trace seeds go back -in one sweep, every cotangent with $K + 1$ blocks, the seed and the derivative of the seed along +in one sweep. Every [cotangent]{#def-cotangent}, the derivative of the output propagated back to an +intermediate quantity, has $K + 1$ blocks, the seed and the derivative of the seed along each tangent. Reference: `odemodel()`, `Xs()`, `Y()`, `P()`, `Pimpl()`, `normL2()` diff --git a/vignettes/articles/methods-sparsity-priors.Rmd b/vignettes/articles/methods-sparsity-priors.Rmd index 95128ad2..8bf5dff1 100644 --- a/vignettes/articles/methods-sparsity-priors.Rmd +++ b/vignettes/articles/methods-sparsity-priors.Rmd @@ -14,10 +14,12 @@ knitr::opts_chunk$set(collapse = TRUE, comment = "#>", message = FALSE) | distribution | deviation $\eta$ of a group | hyperparameters | |---|---|---| -| `spikeSlab()` | $0$ with probability $1 - \rho$, else $\mathcal{N}(0, \tau^2)$; `spike` and `mean` set other values, see [Spike at a given value](#spike-at-a-given-value) | `prob_`, `tau_` | +| `spikeSlab()` | $0$ with probability $1 - \rho$, else $\mathcal{N}(0, \tau^2)$; `spike` and `mean` set other values, see [Spike at a given value](#spike-at-a-given-value) | `prob_`, `tau_`, or priors on them ([Hyperpriors](#hyperpriors)) | | `dirichletProcess()` | value of the cluster of the group: $0$ for the population cluster, else one $\mathcal{N}(0, \tau^2)$ draw per cluster | `concentration_`, `tau_` | -The spike and slab decides for every group alone whether it deviates. The Dirichlet process also +The spike and slab decides for every group alone whether it deviates: the [spike]{#def-spike} puts +the deviation at one value, 0 by default, the [slab]{#def-slab} draws it from a normal distribution. +The Dirichlet process also groups the groups: the groups of one cluster share one deviation, so a fit tells which groups behave alike, not only which differ from the population value. @@ -31,7 +33,8 @@ random effects of a group split into normal coordinates $N$ and sparse ones $S$. ### Joint mode -`em()` first finds the joint mode $\hat\eta$, minimizing +The [mode]{#def-mode} of a group is the value of the random effects that maximizes data likelihood +times prior. `em()` first finds the [joint mode]{#def-joint-mode} $\hat\eta$, minimizing $$\begin{aligned} \Phi(\eta) = {} & \sum_i \Bigl[ D_i(\eta_i) + \eta_{iN}^\top \Omega^{-1} \eta_{iN} \Bigr] @@ -84,7 +87,7 @@ $$I = \int \prod_i \exp\Bigl( -\tfrac12\, \eta_{iS}^\top P_i\, \eta_{iS} + b_i^\ p(\eta_S)\, d\eta_S , \tag{5}$$ $p$ the sparse prior. Without sparse coordinates (4) is the -[FOCEI value](methods-nlme.html#focei). Every structure, a subset of spike coordinates or a +[FOCEI value](methods-nlme.html#focei). Every [structure]{#def-structure}, a subset of spike coordinates or a partition into clusters, is a Gaussian integral. Spike-and-slab priors factor over groups, the Dirichlet process couples the groups of a symbol, and off-diagonal entries of $P_i$ couple the coordinates of a group. @@ -108,7 +111,7 @@ and a hyperparameter derivative is the posterior expectation of the derivative o The prior [@mitchell1988bayesian; @george1993variable] is a point mass at 0 of weight $1 - \rho$ and a normal slab of weight $\rho$. With $V_F = (T_{FF} + \tau^{-2} \mathbb{1})^{-1}$ for the -subset $F$ of slab coordinates, +[subset]{#def-subset} $F$ of slab coordinates, $$Z = \sum_F \rho^{|F|} (1 - \rho)^{K - |F|}\, \frac{\lvert V_F \rvert^{1/2}}{\tau^{|F|}}\, @@ -123,7 +126,9 @@ $$\begin{aligned} \mathbb{E}\, \eta \eta^\top &= \sum_F \Pr(F \mid y) \bigl( V_F + \mu_F \mu_F^\top \bigr), \end{aligned} \tag{8}$$ -$\mu_F$, $V_F$ zero-filled outside $F$; the second moment is full within the factor. Summed over +$\mu_F$, $V_F$ zero-filled outside $F$; the second moment is full within the factor. $1 - p_{0k}$ is the +[inclusion probability]{#def-inclusion-probability} of coordinate $k$, the posterior probability of +the slab; `p0` reports $p_{0k}$. Summed over coordinates sharing them, $$\begin{aligned} @@ -152,14 +157,17 @@ A Dirichlet-process symbol integrates by a recursion over subsets of the groups Where no Dirichlet-process symbol joins two groups, the groups are integrated one by one, a group exactly where the data do not couple the factors of the group and the joint spike-and-slab sum stays within the budget. Where a Dirichlet-process symbol joins two groups, all groups are integrated -together, exactly where this holds for every group. Otherwise $I$ is the EC approximation -[@opper2005expectation], of the group, or of all groups where they are integrated together. With the coupling +together, exactly where this holds for every group. Otherwise $I$ is the +[expectation consistent (EC) approximation]{#def-expectation-consistent-approximation} +[@opper2005expectation], of the group, or of all groups where they are integrated together, which +replaces an intractable integral by two tractable ones whose means and variances agree. With the coupling $\mathcal{G}(\eta) = \prod_i \exp(-\tfrac12 \eta_i^\top P_i \eta_i + b_i^\top \eta_i)$ and the statistics $\phi(\eta) = (\eta_k, -\eta_k^2/2)_k$: -- $q \propto p\, e^{\lambda^\top \phi}$, every factor exact against a diagonal cavity $\lambda$; -- $r \propto \mathcal{G}\, e^{\gamma^\top \phi}$, the coupling exact under diagonal sites $\gamma$, - a Gaussian of precision $P_i + \operatorname{diag}(\gamma_t)$ per group. +- $q \propto p\, e^{\lambda^\top \phi}$, the [tilted distribution]{#def-tilted-distribution}: every + factor exact against a diagonal [cavity]{#def-cavity} $\lambda$, the Gaussian of all other factors; +- $r \propto \mathcal{G}\, e^{\gamma^\top \phi}$, the coupling exact under diagonal + [sites]{#def-site} $\gamma$, Gaussian factors in place of the exact prior factors, a Gaussian of precision $P_i + \operatorname{diag}(\gamma_t)$ per group. With $A_q(\lambda) = \log \int p\, e^{\lambda^\top \phi}$, $A_r(\gamma) = \log \int \mathcal{G}\, e^{\gamma^\top \phi}$ and the product of one-dimensional @@ -202,7 +210,7 @@ move with $\mathrm{d}\lambda^*$, starting the next inner loop near the solution. | loop | ends | |---|---| | inner | means within $10^{-10}$ standard deviations and variances within $10^{-10}$ relative; or within $10^{-4}$ when Newton no longer lowers $\Psi$ | -| outer | marginals of $r$ match the Gaussians of $\nu$ to $10^{-10}$; or within $10^{-4}$ when a fixed-point step no longer raises the free energy $F = A_q + A_r - A_s$ (rounding of an ill-conditioned Gaussian part) | +| outer | marginals of $r$ match the Gaussians of $\nu$ to $10^{-10}$; or within $10^{-4}$ when a fixed-point step no longer raises the [free energy]{#def-free-energy} $F = A_q + A_r - A_s$, the right side of (10) (rounding of an ill-conditioned Gaussian part) | | outer Newton step | accepted where it raises $F$ by the Armijo condition, the step halved down to a sixteenth; else the fixed-point step, which always raises $F$ | | failure | a failed evaluation; the trust region shortens the step | @@ -248,7 +256,7 @@ Every evaluation of the marginal is an E-step; the M-steps set the hyperparamete joint trust region. EM in general: [EM algorithm](methods-nlme.html#em-algorithm). The objective is $-2Q$, $Q$ the expected complete-data log-density. -With the indicator $z_{ik}$ (1 slab, 0 spike), the complete-data $-2 \log$ prior over groups $i$ and +With the [indicator]{#def-indicator} $z_{ik}$ (1 slab, 0 spike), the complete-data $-2 \log$ prior over groups $i$ and symbols $k$ is, up to terms free of $\rho$ and $\tau$, $$\begin{aligned} @@ -444,7 +452,8 @@ others, since the Ewens prior of a subset is that of the subset. This removes fl mode and integral. `fit$slab` lists the probabilities, concentrations and slab standard deviations, each with the -symbols, the estimate and whether it was fixed. +symbols, the estimate and whether it was fixed; with [hyperpriors]{#def-hyperprior}, priors on hyperparameters, also the 95 % interval and the prior +([Hyperpriors](#hyperpriors)). ## Selection of deviations @@ -458,8 +467,8 @@ condition for the right set fails for such correlations. It gives no probability one data set: [Sparse deviations > L1 scan](guide-sparse-deviations.html#l1-scan). The spike and slab separates decision and size: a deviation is 0 or from the slab, which shrinks -little, and (7) weighs every structure by the marginal likelihood, with $\rho$ and $\tau$ estimated -instead of scanned. Coupled coordinates the data cannot separate share the posterior, with +little, and (7) weighs every structure by the marginal likelihood, with $\rho$ and $\tau$ estimated, +given, or under a prior ([Hyperpriors](#hyperpriors)) instead of scanned. Coupled coordinates the data cannot separate share the posterior, with intermediate $p_0$. Both statements hold within the Laplace approximation of the data term. Groups that deviate alike are a second structure. The Dirichlet process @@ -610,23 +619,37 @@ $$p(\eta_k) = (1 - \rho)\, \delta_\alpha(\eta_k) + \rho\, \mathcal{N}(\eta_k;\, $\alpha$ and $\mu_0$ given. $\alpha = -\infty$ requires $\eta_k$ to enter the model only as a summand of an exponent $b^{(\cdots + \eta_k)}$ with a numeric base $b > 1$, read off the equations of the model; the spike is then the model at rate 0. The quadratic model of (7) cannot reach $-\infty$, so -every subset $F$ of slab coordinates of a group is a separate Laplace integral, at the inner mode +the sum over subsets of this section takes the data term of every subset itself. The same path +fits spike-and-slab random effects under a hyperprior ([Hyperpriors](#hyperpriors)) and every +spike-and-slab model with `method = "quadrature"`, the default spike 0 included. + +### Sum over subsets + +Every subset $F$ of slab coordinates of a group is a separate Laplace integral, at the inner mode $\hat\eta_F$ of -$$f_F(\eta_F) = -2 \log L(\eta_F,\, \eta_{\bar F} = \alpha) + \sum_{k \in F} \frac{(\eta_k - \mu_0)^2}{\tau^2} , -\qquad -2 \log Z_F = f_F(\hat\eta_F) + |F| \log \tau^2 + \log \bigl| \tfrac12 H_F \bigr| , \tag{42}$$ +$$\begin{aligned} +f_F(\eta_F) &= -2 \log L(\eta_F,\, \eta_{\bar F} = \alpha) + \sum_{k \in F} \frac{(\eta_k - \mu_0)^2}{\tau^2} , \\ +-2 \log Z_F &= f_F(\hat\eta_F) + |F| \log \tau^2 + \log \bigl| \tfrac12 H_F \bigr| , +\end{aligned} \tag{42}$$ -$H_F$ the Gauss-Newton Hessian, and $Z = \sum_F \rho^{|F|} (1 - \rho)^{K - |F|} Z_F$. With +$H_F$ the Hessian of $f_F$ the objective returns (Gauss-Newton without an error model of the +prediction), and $Z = \sum_F \rho^{|F|} (1 - \rho)^{K - |F|} Z_F$. With $\Pr(F \mid y)$ the term of $F$ over $Z$ and $C_F = 2 H_F^{-1}$, EM updates $$\rho \leftarrow \frac1K \sum_k (1 - p_{0k}), \qquad \tau^2 \leftarrow \frac{\sum_F \Pr(F \mid y) \sum_{k \in F} \bigl[ (\hat\eta_{Fk} - \mu_0)^2 + C_{F,kk} \bigr]} {\sum_F \Pr(F \mid y)\, |F|} , \tag{43}$$ -per block, and the fixed effects minimize $\sum_F \Pr(F \mid y)\, f_F$ jointly with one copy of -$\eta_F$ per subset; the log determinant of (42) enters the weights only. +per block, a random effect without data of the group entering both sums at the prior, with weight +$\rho$ and second moment $\tau^2$. The fixed effects minimize $\sum_F \Pr(F \mid y)\, f_F$ jointly with +one copy of $\eta_F$ per subset; the log determinant of (42) enters the weights only. Phase +`"exact"` sums over all subsets, up to `termBudget` of them over all groups; the other phases +approximate the sum. + +### Expectation consistent approximation in the rate -Beyond the budget a group takes EC (see [Expectation consistent +Phase `"ec"` integrates by EC (see [Expectation consistent approximation](#expectation-consistent-approximation)) in a coordinate in which the spike is 0: $u_k = b^{\eta_k}$ for $\alpha = -\infty$, with a log-normal slab $\ln u_k \sim \mathcal{N}(\mu_0 \ln b, (\tau \ln b)^2)$, and $u_k = \eta_k - \alpha$ else. The data term is a Gaussian @@ -634,29 +657,103 @@ in $u$, from one evaluation in $\eta$ at the expansion point $u^\circ$ and $$g_u = D\, g_\eta, \qquad H_u = D\, H_\eta\, D, \qquad D = \operatorname{diag}\bigl( 1 / (u^\circ_k \ln b) \bigr) , \tag{44}$$ -with no second-order term, since $H_\eta$ is Gauss-Newton. $u^\circ$ starts at the mode with every -coordinate in the slab and moves to the EC mean until it is stable. The sites update one at a time; -a site of negative precision is replaced by the one that matches the tilted mean at the cavity -variance. The fixed effects are fitted with the slab coordinates of inclusion probability above 1/2. +$D = 1$ for $u = \eta - \alpha$, with no second-order term, since $H_\eta$ is the expected Hessian +(Gauss-Newton without an error model of the prediction), positive semidefinite also with one. $u^\circ$ +starts at the mode with the coordinates of inclusion probability above 1/2 of the EM step before in +the slab, at the first step every coordinate, no lower than $b^{\mu_0 - 4\tau}$, and moves to the EC +mean until it is stable. The sites update one at a time, each by half the step to the matched +moments; a site of negative precision is replaced by the one that matches the tilted mean at the +cavity variance. The slab mass of a log-normal site is a Gauss-Hermite sum at the mode in +$\ln u$. The fixed effects take the slab coordinates of inclusion probability above 1/2. A single +expansion of the data term holds only near the data: from a start far from them, EC may not +converge. + +### Mean field + +Phase `"meanfield"` is a [mean field]{#def-mean-field} approximation: it approximates the posterior over the indicators $z_k = [k \in F]$ by independent +Bernoulli factors, one per coordinate. It takes $\log Z_F$ linear in $z$ around a reference subset +$R$, from the $K + 1$ Laplace integrals (42) of $R$ and of the subsets $R \triangle \{k\}$ that differ +from it in one coordinate: + +$$\log Z_F \approx \log Z_R + \sum_k (z_k - z^R_k)\, d_k , \qquad +d_k = \log Z_{R \cup \{k\}} - \log Z_{R \setminus \{k\}} , \tag{45}$$ + +$d_k$ the log Bayes factor of the slab of $k$ given the reference. A [Bayes factor]{#def-bayes-factor} is the ratio of the +marginal likelihoods of two models, each integrated over the prior of the model parameters; here +$Z_{R \cup \{k\}} / Z_{R \setminus \{k\}}$, coordinate $k$ in the slab, integrated over +$\mathcal{N}(\mu_0, \tau^2)$, against $k$ at the spike, the other coordinates as in $R$. It turns the prior +odds of the slab into the posterior odds, $\Pr(z_k = 1 \mid y) / \Pr(z_k = 0 \mid y) = e^{d_k}\, \rho / (1 - \rho)$, +and is below 1 where the gain in fit does not pay for the width of the slab. The sum over subsets then +factorizes, + +$$Z \approx Z_R\, e^{-\sum_k z^R_k d_k} \prod_k \bigl( 1 - \rho + \rho\, e^{d_k} \bigr) , \qquad +1 - p_{0k} = \frac{\rho\, e^{d_k}}{1 - \rho + \rho\, e^{d_k}} . \tag{46}$$ + +For a log-density linear in $z$ the variational mean-field solution, a product of Bernoulli factors, +is the posterior itself, so (46) is the mean field of the linear model (45). The approximation lies +in the terms (45) leaves out, the interactions of the coordinates: with $c_k = [z_k \ne z^R_k]$ the +coordinates on the other side of the reference, + +$$\begin{aligned} +\log Z_F &= \log Z_R + \sum_k c_k\, \delta_k + \sum_{k < l} c_k c_l\, \delta_{kl} + \dots , \\ +\delta_{kl} &= \log Z_{R \triangle \{k, l\}} - \log Z_{R \triangle \{k\}} - \log Z_{R \triangle \{l\}} + \log Z_R , +\end{aligned} \tag{47}$$ + +$\delta_k = \log Z_{R \triangle \{k\}} - \log Z_R$ the terms of (45). $\delta_{kl}$ vanishes where $k$ and $l$ +act on separate data or one does not change what the other explains; it is large for coordinates +that substitute for each other, such as two routes to the same effect, where mean field counts the +gain of each as if the other were absent. Mean field is then too confident in both together, EC +and the exact sum split the posterior between them. + +$R$ starts at the start subset of the burn-in, without one at every coordinate, and moves to +the coordinates with $1 - p_{0k} > \tfrac12$ until it stays or returns to an earlier reference; +every Laplace integral of the step is computed once and starts the inner search at the mode of the +same subset in the step before. A subset whose inner search fails has $Z_F = 0$. $\tau^2$ follows +(43) with $\Pr(F \mid y)$ replaced by the factors of (46), each coordinate at the mode of the subset +of $R$ and $R \triangle \{k\}$ that holds it; the fixed effects and $\Omega$ take $R$. + +Mean field and EC fail in opposite places. Mean field evaluates the data term of every subset it +uses exactly, at $K + 1$ inner searches per step against $2^K$ for the exact sum, and stays +defined far from the data, where a single quadratic model is poor; it misses the interactions +(47). EC holds the interactions of all coordinates in one Gaussian of the data term, at one +evaluation per relinearization, but that Gaussian holds only near the data. The default phases +run mean field, then EC, then the exact sum. + +### Phases and burn-in + +The phases run in the order of `phases`, default `c("meanfield", "ec", "exact")`, each EM until no +estimate changes by more than `epsECM`, from the estimates and the inner modes $\hat\eta_F$ of the +phase before. `"exact"` is the sum over all $F$; where the subsets exceed `termBudget` it is +skipped after `"ec"` and an error without it. A burn-in before them minimizes $f_F$ of one start +subset $F$ jointly in the fixed effects and $\eta_F$ by one trust region, without the log determinant +and with $\rho$, $\tau$ and $\Omega$ held; the coordinates outside $F$ stay at $\alpha$. $F$ holds each +slab coordinate with probability $\rho$ (`start = "random"`, under a beta prior the prior mean), none, +every one, or the given ones, and starts the first phase. + +### Normal random effects beside Normal random effects of the same grouping join every subset: $F$ holds them as well, with the prior $\mathcal{N}(0, \Omega)$ in (42) and $\log\lvert\Omega\rvert$ in the normalizer; $\Omega$ follows by EM from $\sum_F \Pr(F \mid y)\, (\hat\eta_F \hat\eta_F^\top + C_F)$ restricted to the normal coordinates, and in EC groups they enter the Gaussian exactly, without sites. +### SAEM + SAEM draws the indicators by the collapsed moves of [SAEM](methods-nlme.html#spike-and-slab-random-effects) with the spike at $\alpha$ and the slab mean $\mu_0$. At $\alpha = -\infty$ the line of a move holds the other slab values, and the move into the slab proposes from $\mathcal{N}(\hat x, 2 / f'')$, $\hat x$ the minimum of the data term plus slab prior in the coordinate by Newton steps on the model; the Metropolis-Hastings step on the exact posterior keeps the chain exact. -With `method = "quadrature"` every subset of weight above $10^{-8}$ of the largest is integrated on a -dimension-adaptive sparse grid [@smolyak1963quadrature; @gerstner2003dimension] around $\hat\eta_F$ -with precision $\tfrac12 H_F$, a subset of relative weight $w_F$ to the tolerance of the group over -$w_F$: nodes $\eta_i$ with signed weights $w_i$, +### Quadrature + +With `method = "quadrature"`, after the phases, every subset of weight above $10^{-8}$ of the largest +is integrated on a dimension-adaptive sparse grid [@smolyak1963quadrature; @gerstner2003dimension] +around $\hat\eta_F$ with precision $\tfrac12 H_F$, a subset of relative weight $w_F$ to the tolerance +of the group over $w_F$: nodes $\eta_i$ with signed weights $w_i$, $$Z_F \approx (2\pi\tau^2)^{-|F|/2} \sum_i w_i\, e^{-f_F(\eta_i)/2} , \qquad -\omega_i = \frac{w_i\, e^{-f_F(\eta_i)/2}}{\sum_j w_j\, e^{-f_F(\eta_j)/2}} , \tag{45}$$ +\omega_i = \frac{w_i\, e^{-f_F(\eta_i)/2}}{\sum_j w_j\, e^{-f_F(\eta_j)/2}} , \tag{48}$$ the grid refined in the direction of the largest error estimate until the estimated error of $-2 \log Z_F$ is below the tolerance. On these nodes, held fixed, $-2 \log L = -2 \log \sum_F @@ -665,4 +762,89 @@ $\rho$. `trust()` minimizes it, with the gradient $\sum_F \Pr(F \mid y) \sum_i \ f_F(\eta_i)$ by Fisher's identity and the Hessian by Louis' identity; then the modes and grids are rebuilt, until $-2 \log L$ decreases by less than `tolDecrement`. +## Hyperpriors + +With few groups, $\rho$ and $\tau$ of (43) rest on the $K$ deviations of a block. With $B_k$ the +Bayes factor of the slab of deviation $k$ ([Mean field](#mean-field)), the inclusion is $\pi_k = \rho B_k / (1 - \rho + \rho B_k)$, and +near $\rho = 1$ the update of (43) is + +$$\rho \leftarrow \frac1K \sum_k \pi_k(\rho) \approx 1 - (1 - \rho)\, \frac1K \sum_k \frac{1}{B_k} . \tag{49}$$ + +$\rho = 1$ attracts where $\frac1K \sum_k 1 / B_k < 1$: where the deviations on average cost no likelihood, +every one ends in the slab, and the prior odds $\rho / (1 - \rho)$ no longer charge for the number of +candidates. [Empirical Bayes]{#def-empirical-bayes}, which estimates hyperparameters by maximizing the +marginal likelihood of the same data, puts $\rho$ at 0 or 1 with positive probability for small +$K$ [@scott2010bayes]. For $\tau$, the [Occam term]{#def-occam-term} $|F| \log \tau^2 + \log |\tfrac12 H_F|$ of (42), the part of +$-2 \log Z_F$ that grows with the ratio of prior to posterior width and so charges a model for the +room the parameters had before the data, charges a deviation of posterior variance $V$ about +$\log(\tau^2 / V)$; (43) sets $\tau^2$ to the mean of +$(\hat\eta - \mu_0)^2 + V$ over the slab, so the slab follows the modes and the charge shrinks. A +hyperprior moves `spikeSlab()` of the default spike and slab mean to the sum over subsets of +[Spike at a given value](#spike-at-a-given-value). + +### Inclusion probability under a beta prior + +`spikeSlab(prob = betaPrior(a, b))` integrates $\rho$ out. A subset $F$ of $n$ of the $K$ deviations of a +block that reach data has the prior weight + +$$W(n) = \frac{B(a + n,\, b + K - n)}{B(a, b)} , \qquad W(n) = \frac{1}{(K + 1) \binom{K}{n}} \text{ for } a = b = 1 , \tag{50}$$ + +so that under Beta(1, 1) every number of deviations in the slab is equally likely, the +[multiplicity correction]{#def-multiplicity-correction} of [@scott2010bayes]: with more candidates, +each needs stronger evidence. A deviation without data leaves the sum unchanged, since the +[beta-binomial]{#def-beta-binomial} distribution of the slab count of $K$ indicators, $\rho$ integrated out, is the margin of that of more. $W$ depends on the count over all +groups of the block, so the sum over subsets no longer factorizes over the groups; with $T_g(n)$ the +sum of the terms of group $g$ with $n$ deviations in the slab, + +$$I = \sum_n W(n)\, (T_1 * T_2 * \cdots * T_G)(n) , \tag{51}$$ + +$*$ the convolution in $n$, $K_g + 1$ terms for the $K_g$ deviations of group $g$, and the weight of a +subset of group $g$ follows from the convolution of the other groups. + +| phase or method | with a beta prior | +|---|---| +| `"exact"` | (51) exactly | +| `"meanfield"` | (51) with the table $\{0: w_{0k},\, 1: w_{1k}\}$ of every deviation in place of $T_g$, $w_{0k}$ and $w_{1k}$ the log mass of spike and slab of (45) (0 on the side of the reference, $\delta_k$ on the other); exact for the linear model (45), the inclusion of $k$ the convolution of the other tables shifted by one | +| `"ec"` | the same with the tilted masses of spike and slab at the cavity; the sites take the prior probability $(a + \bar n_{-k}) / (a + b + K - 1)$, $\bar n_{-k}$ the expected number of the other deviations in the slab after the step before | +| SAEM | an indicator moves with $W$ of the count in place of $\rho^n (1 - \rho)^{K - n}$; deviations of one group | +| quadrature | the frozen nodes weigh their subsets by $W$; deviations of one group | + +`fit$slab` reports the posterior mean $(a + \bar n) / (a + b + K)$ and the 95 % interval of +$\mathrm{Beta}(a + \bar n,\, b + K - \bar n)$, $\bar n$ the expected number in the slab; the posterior of +$\rho$ is a mixture of beta distributions, of which this is the beta of the same mean count. + +### Slab width under a scale prior + +A scale prior on $\tau$, `halfCauchyPrior()` [@gelman2006prior; @polson2012half], `halfNormalPrior()` or +`invGammaPrior(shape, rate)` on $\tau^2$, makes the M-step of (43) the posterior mode: + +$$\hat\tau = \arg\min_\tau\; \bar n \log \tau^2 + \frac{S}{\tau^2} - 2 \log p(\tau) , \qquad +S = \textstyle\sum \Pr(\text{slab}) \bigl[ (\hat\eta - \mu_0)^2 + V \bigr] , \tag{52}$$ + +with $p$ the density in $\tau$, for the inverse gamma in $\tau^2$. The inverse gamma of shape $\kappa$ and +rate $\beta$ has the closed form $\hat\tau^2 = (S + 2\beta) / (\bar n + 2\kappa + 2)$; half-Cauchy and +half-normal take Newton steps in $\log \tau$, where (52) is convex, the slab term +$\bar n \log \tau^2 + S / \tau^2$ having the curvature $4 S / \tau^2$ in $\log \tau$. SAEM takes the same mode +from the averaged statistics of the chain, the quadrature adds $-2 \log p(\tau)$ with gradient and curvature on +the $\log \tau$ coordinate of the frozen nodes. `fit$value` holds $-2 \log p(\hat\tau)$ as well, +`fit$hyperprior` the term alone. + +With `integrate = TRUE` the phase `"exact"` integrates over $u = \log \tau$ instead, + +$$I = \int I(e^u)\, p(e^u)\, e^u \, du \approx \sqrt2\, s \sum_{i} w_i\, e^{x_i^2}\, I(e^{u_i})\, p(e^{u_i})\, e^{u_i} , +\qquad u_i = m + \sqrt2\, s\, x_i , \tag{53}$$ + +for the inverse gamma with $p(e^{2u})\, 2 e^{2u}$ in place of $p(e^u)\, e^u$; seven Gauss-Hermite nodes +$x_i$, weights $w_i$, every node an exact sum with the inner modes of the others as start. The +subsets of all nodes enter the M-step with their node weight, each with the slab width of the node, +and $m$, $s$ move to the posterior mean and standard deviation of $u$, the start $m = \log \tau$, +$s = 0.5$. The prior is part of the integral, so `fit$hyperprior` holds no term of that block. +Integrating costs seven exact sums per step; one block per fit, not with `method = "quadrature"`. + +| situation | `prob` | `tau` | +|---|---|---| +| many groups | estimated (`NULL`) | estimated (`NULL`) | +| one group or few, no prior knowledge | `betaPrior(1, 1)` | `halfCauchyPrior()` with the scale of a typical effect | +| a known effect size | `betaPrior(1, 1)` | given, with `mean` at that size, so that the slab means "acts" | + ## References diff --git a/vignettes/articles/methods-steady-states.Rmd b/vignettes/articles/methods-steady-states.Rmd index 67cb6208..4d3f0313 100644 --- a/vignettes/articles/methods-steady-states.Rmd +++ b/vignettes/articles/methods-steady-states.Rmd @@ -5,14 +5,19 @@ csl: ieee.csl link-citations: true --- -A model at rest before a stimulus starts from a root of the right-hand side. `Pimpl()` computes -it numerically, `steadyStates()` in closed form. Guide: +A [steady state]{#def-steady-state} is a state $x$ at which the +[right-hand side]{#def-right-hand-side} $f$ of the ODE $\dot x = f(x, p)$ of states $x$ and +parameters $p$ vanishes, a [root]{#def-root} of $f$. A model at rest before a stimulus starts from a +steady state. `Pimpl()` computes it numerically, `steadyStates()` in closed form. Guide: [Setting up models](guide-model.html#steady-state-constraints). ## Conserved quantities -With compartment volumes $V_i$, stoichiometric coefficients $S_{ri}$ of species $i$ in reaction -$r$, and rates $v_r$ in a frame of volume $V_{c(r)}$, the right-hand side is +With [compartment volumes]{#def-compartment-volume} $V_i$, the volume of the compartment that holds +species $i$, [stoichiometric coefficients]{#def-stoichiometric-coefficient} $S_{ri}$, the net number +of molecules of species $i$ that reaction $r$ produces, negative where it consumes them, the entries +of the [stoichiometry]{#def-stoichiometry} matrix $S$, and rates $v_r$ in a frame of volume +$V_{c(r)}$, the right-hand side is $$\dot x_i = f_i(x, p) = \frac{1}{V_i} \sum_r S_{ri}\, V_{c(r)}\, v_r(x, p). \tag{1}$$ @@ -20,20 +25,22 @@ Every $w$ with $S w = 0$ conserves the amount $$\sum_i w_i V_i x_i \tag{2}$$ -by (1); `conservedQuantities()` lists these amounts. Then $f(x, p) = 0$ does not determine $x$: -every conservation class, the states with given totals, has separate roots. +by (1), a [conserved quantity]{#def-conserved-quantity}; `conservedQuantities()` lists these +amounts. Then $f(x, p) = 0$ does not determine $x$: every +[conservation class]{#def-conservation-class}, the states with given totals, has separate roots. ## Pseudo-transient continuation -For an `eqnlist`, `Pimpl()` adds the conservation laws $C(p)\, x = T$ of the stoichiometry, totals -$T$ as parameters: +For an `eqnlist`, `Pimpl()` adds the [conservation laws]{#def-conservation-law} $C(p)\, x = T$ of the +stoichiometry, which set the conserved quantities to totals $T$ that enter as parameters: $$G(x, p) = \begin{pmatrix} f(x, p) \\ C(p)\, x - T \end{pmatrix} = 0 . \tag{3}$$ Equations given as an `eqnvec` or character vector have no stoichiometry and are solved as they are, so they have to determine $x$ themselves. With `flow = TRUE`, the default for an `eqnlist`, -pseudo-transient continuation solves (3) by implicit Euler steps of $\dot x = f(x, p)$ on the -conservation manifold, with a pseudo-time step that grows as the residual falls. It follows the flow +[pseudo-transient continuation]{#def-pseudo-transient-continuation} solves (3) by implicit Euler +steps of $\dot x = f(x, p)$ on the [conservation manifold]{#def-conservation-manifold}, the affine +subspace $C x = T$ that a trajectory never leaves, with a pseudo-time step that grows as the residual falls. It follows the flow far from the root and becomes Newton's method near it. Newton steps may also reach an unstable root, which the [stability test](#stability) catches. With `flow = FALSE`, the default otherwise, the equations need not be the right-hand side of an ODE: the solver takes damped Newton steps, @@ -52,16 +59,19 @@ From $G(x(p), p) = 0$ for all $p$, the implicit function theorem gives $$\frac{\partial G}{\partial x}\, \frac{\partial x}{\partial p} = -\frac{\partial G}{\partial p}, \tag{4}$$ -regular where $J = \partial f / \partial x$ restricted to the conservation manifold, -$N^\top J N$ for a basis $N$ of $\ker C$, is nonsingular; such a root is isolated in the -conservation class. Where the matrix is singular, `Pimpl()` takes the pseudo-inverse and warns. +solvable for $\partial x / \partial p$ at a regular root. A root is [regular]{#def-regular-root} where the [Jacobian]{#def-jacobian} +$J = \partial f / \partial x$ restricted to the conservation manifold, $N^\top J N$, is +nonsingular, with the columns of $N$ a [basis]{#def-basis} of the [kernel]{#def-kernel} $\ker C$, +the vectors $v$ with $C v = 0$, the directions within the conservation class. A regular root is +isolated in the conservation class. Where the matrix is singular, `Pimpl()` takes the pseudo-inverse and warns. Differentiating (4) again gives the second derivatives, `Pimpl(derivMode = "forward-forward")`, with the same matrix. A reverse sweep applies the transpose of the solution $\partial x / \partial p$ of (4) ([Sensitivities and Hessians](methods-sensitivities.html#reverse-sweep)). ## Stability -A root is a resting state only if every eigenvalue $\lambda_k$ of $J = \partial f / \partial x$ +A [resting state]{#def-resting-state} is a stable steady state, the state of the model before a +stimulus. A root is a resting state only if every eigenvalue $\lambda_k$ of $J = \partial f / \partial x$ on the conservation manifold has negative real part. At a root whose leading eigenvalue has real part above the larger of $10^{-8} s$, $s$ the largest eigenvalue modulus on the conservation manifold and $10^{-8} s$ the precision of the eigenvalues, and the stability tolerance @@ -74,11 +84,12 @@ the unstable root. `constraintStability()` adds a term that rises on a ramp below $\lambda_{tol}$, the sum of squares of the residuals -$$\rho_k = \sqrt{\kappa} \begin{cases} r_k^{3/2}, & r_k \le 1, \\ - 1 + \tfrac{3}{2}(r_k - 1), & r_k > 1, \end{cases} \qquad - r_k = \frac{\max\bigl(0,\ \mathrm{Re}\,\lambda_k - \lambda_0\bigr)}{\lambda_{tol} - \lambda_0}, +$$\begin{aligned} +\rho_k &= \sqrt{\kappa} \begin{cases} r_k^{3/2}, & r_k \le 1, \\ + 1 + \tfrac{3}{2}(r_k - 1), & r_k > 1, \end{cases} \\ +r_k &= \frac{\max\bigl(0,\ \mathrm{Re}\,\lambda_k - \lambda_0\bigr)}{\lambda_{tol} - \lambda_0}, \qquad \lambda_0 = \lambda_{tol} - \max(d, m s), - \tag{5}$$ +\end{aligned} \tag{5}$$ with weight $\kappa$ and the width $\max(d, m s)$ of the ramp: at least the absolute `width` $d$, default 0, and at least the `margin` $m$ relative to the scale, default $10^{-6}$, the precision of @@ -96,7 +107,10 @@ $$ $$ and $s = |\lambda_m|$, $\lambda_m$ the eigenvalue of largest modulus, has the derivative -$\mathrm{Re}(\bar\lambda_m\, \mathrm{d}\lambda_m / \mathrm{d}p) / s$ by (6), continuous except + +$$\frac{\mathrm{d}s}{\mathrm{d}p} = \frac{\mathrm{Re}(\bar\lambda_m\, \mathrm{d}\lambda_m / \mathrm{d}p)}{s}$$ + +by (6), continuous except where the eigenvalue of largest modulus changes. Eigenvalues that coincide within the error of the eigenvalues, as a defective double eigenvalue of a chain of states with equal rates, have no derivative each; each takes the mean $\mathrm{tr}(P\, \mathrm{d}J/\mathrm{d}p) / n_c$ over the @@ -107,10 +121,12 @@ complex pair, the derivatives of both diverge and the gradient of (5) has a kink The Gauss-Newton Hessian of (5), -$$2 \sum_{k \,:\, \mathrm{Re}\,\lambda_k > \lambda_0} - \frac{\mathrm{d} \rho_k}{\mathrm{d}p} \frac{\mathrm{d} \rho_k}{\mathrm{d}p}^{\mathsf T}, - \qquad \frac{\mathrm{d} \rho_k}{\mathrm{d}p} = \frac{3}{2} \sqrt{\kappa}\, \min(r_k, 1)^{1/2}\, - \frac{\mathrm{d} r_k}{\mathrm{d}p}, \tag{7}$$ +$$\begin{aligned} +&2 \sum_{k \,:\, \mathrm{Re}\,\lambda_k > \lambda_0} + \frac{\mathrm{d} \rho_k}{\mathrm{d}p} \frac{\mathrm{d} \rho_k}{\mathrm{d}p}^{\mathsf T}, \\ +&\frac{\mathrm{d} \rho_k}{\mathrm{d}p} = \frac{3}{2} \sqrt{\kappa}\, \min(r_k, 1)^{1/2}\, + \frac{\mathrm{d} r_k}{\mathrm{d}p}, +\end{aligned} \tag{7}$$ vanishes at the onset with the term and the gradient and is continuous at $r_k = 1$. Outside the ramp the term and (7) vanish, so the model of a trust-region step sees the boundary only from @@ -125,16 +141,20 @@ eigenvectors are the attribute `"eigenvalues"` of a call of the term. ## Analytical steady-state constraints `steadyStates()` solves $f(x, p) = 0$ in closed form [@rosenblatt2016customized; @kaschek2019dmod]. -The balances are taken in amounts, so that a quantity conserved across compartments is a dependent -balance. First, a state whose balance is linear in the state, with all terms of the state on one +The [balance]{#def-balance} of state $i$ is the equation $V_i\, \dot x_i = 0$ in amounts, a sum +of [flux terms]{#def-flux-term} $S_{ri} V_{c(r)} v_r$, so that a quantity conserved across +compartments is a dependent balance. First, a state whose balance is linear in the state, with all terms of the state on one side, is solved from that balance, influx over outflux rate, unless the rate constants of the -solution leave a cycle of the graph of states without a cut; the states of conserved quantities are +solution leave a [cycle]{#def-cycle} without a [cut]{#def-cut}. A cycle is a closed path of the graph of +states with an edge from each state to every state in the balance of that state; a cut is a state +on a cycle that stays a free parameter. The states of conserved quantities are left to the cuts. Then the cycles are cut, each at a state of a conserved quantity, which stays free, or at a state whose balance is solved for a rate constant common to the flux terms of one side. The cuts are ranked as by @rosenblatt2016customized: conserved quantities first, then sides whose flux terms occur in no other balance, fewer balances changed, fewer terms, more cycles through the state. Then each unknown, a state or a kinetic parameter, is solved from a combination -of balances such that the solution is a ratio of sums of positive terms. The solution is thus positive for positive +of balances such that the solution is a ratio of sums of positive terms; the unknown a balance is +solved for is the [pivot]{#def-pivot}. The solution is thus positive for positive parameters, also with `solveQuadratic = TRUE`, which takes the positive root of a balance quadratic in the state. A state whose balance is spent on a kinetic parameter stays free, as the parameter of the steady-state value of the state. States that are zero in every steady state are set to 0. A conserved quantity @@ -145,14 +165,15 @@ $k_0, \dots, k_m$ is a cut as well. The fluxes $v_j$ of the side get free ratios $r_{x,j} = v_j / v_0 > 0$, named `r__`; $k_0$ is solved, each $k_j$ follows from $r_{x,j}$ and $k_0$. The ratios are new parameters of the transformation. -The result, one equation per solved unknown, replaces identity entries of a parameter -transformation: +The result, one equation per solved unknown, replaces identity entries of a +[parameter transformation]{#def-parameter-transformation}, the map from outer to inner parameters +that `P()` builds: ```{r, eval = FALSE} steady <- steadyStates(reactions) parameters <- getParameters(reactions) -trafo <- repar(eqnvec(setNames(parameters, parameters)), "x <- y", - x = names(steady), y = steady) +trafo <- define(NULL, "x <- x", x = parameters) +trafo <- insert(trafo, "x <- y", x = names(steady), y = steady) p <- P(trafo) ``` @@ -161,7 +182,7 @@ p <- P(trafo) | `givenCQs` | conserved quantities, default from `customTotals()` or derived | | `neglect` | states and parameters never solved for | | `priority` | states solved first, parameters preferred as pivots | -| `forcings` | states held at zero as exogenous inputs | +| `forcings` | [forcings]{#def-forcing}, states given as external inputs, held at zero | | `solveQuadratic` | allow the positive root of a quadratic balance | | `file` | save the result with `saveRDS()` | diff --git a/vignettes/articles/methods-symmetries.Rmd b/vignettes/articles/methods-symmetries.Rmd index 076d5d7c..e48fd292 100644 --- a/vignettes/articles/methods-symmetries.Rmd +++ b/vignettes/articles/methods-symmetries.Rmd @@ -16,29 +16,37 @@ The model is $$\dot x = f(x, u(t), \theta), \qquad x(t_0) = x_0(\theta), \qquad y = g(x, \theta), \tag{1}$$ with states $x$, input $u$, observables $y$ and parameters $\theta \in \Theta \subseteq -\mathbb{R}^d$ of any kind, and prediction $y(t; \theta) = g(x(t), \theta)$. It is *locally -structurally identifiable* at $\theta$ if no nearby $\tilde\theta \ne \theta$ has the same +\mathbb{R}^d$ of any kind, and prediction $y(t; \theta) = g(x(t), \theta)$. It is *[locally +structurally identifiable]{#def-locally-structurally-identifiable}* at $\theta$ if no nearby $\tilde\theta \ne \theta$ has the same prediction. The property depends on the equations alone, as if every observable were measured exactly and continuously, and the answer is the same for every $\theta$ outside a set of measure -zero, for generic $\theta$. A +zero, the zero set of a nonzero polynomial: for [generic]{#def-generic} $\theta$. A structural non-identifiability makes the likelihood exactly flat along a curve, seen as a flat profile [@raue2009structural]. ## Lie symmetries -A *Lie symmetry* is a one-parameter group $\Phi_\varepsilon$ on $\Theta$ with -$y(t; \Phi_\varepsilon(\theta)) = y(t; \theta)$ for all $t$ and small $\varepsilon$. The orbits -are the integral curves of the *generator* - -$$X = \sum_{i=1}^d \xi_i(\theta)\, \frac{\partial}{\partial \theta_i}, \qquad -\xi(\theta) = \frac{\partial \Phi_\varepsilon(\theta)}{\partial \varepsilon}\Big|_{\varepsilon = 0}. -\tag{2}$$ - -An *invariant*, $X(I) = 0$, is constant on every orbit, and the prediction depends on $\theta$ only +A *[Lie symmetry]{#def-lie-symmetry}* is a [one-parameter group]{#def-one-parameter-group} +$\Phi_\varepsilon$ on $\Theta$, maps with $\Phi_0$ the identity and +$\Phi_a \circ \Phi_b = \Phi_{a + b}$, with +$y(t; \Phi_\varepsilon(\theta)) = y(t; \theta)$ for all $t$ and small $\varepsilon$. The +[orbit]{#def-orbit} of $\theta$, the curve $\varepsilon \mapsto \Phi_\varepsilon(\theta)$, is a +continuous family of parameter values with the same prediction. The orbits are the +[integral curves]{#def-integral-curve}, with tangent $\xi$ at every point, of the +*[generator]{#def-generator}* + +$$\begin{aligned} +X &= \sum_{i=1}^d \xi_i(\theta)\, \frac{\partial}{\partial \theta_i}, \\ +\xi(\theta) &= \frac{\partial \Phi_\varepsilon(\theta)}{\partial \varepsilon}\Big|_{\varepsilon = 0}. +\end{aligned} \tag{2}$$ + +The components $\xi_i$ are the rates of change of the coordinates along an orbit. An +*[invariant]{#def-invariant}*, a function $I(\theta)$ with $X(I) = 0$, is constant on every orbit, and the prediction depends on $\theta$ only through invariants. With $r$ generators that span all symmetries and are independent at generic $\theta$, the observables determine $d - r$ parameter combinations. -*Scalings*, $\xi_i(\theta) = w_i \theta_i$ with integer weights, are the most common symmetries of +*[Scalings]{#def-scaling}*, $\xi_i(\theta) = w_i \theta_i$ with integer +[weights]{#def-weights} $w_i$, multiply coordinate $i$ by $e^{w_i \varepsilon}$. They are the most common symmetries of reaction networks; on the log scale their orbits are straight lines. Two kinds occur in almost every signaling model: @@ -64,34 +72,46 @@ at $z_0$ are the time derivatives of the prediction at $t_0$, so an analytic pre $$y(t; \theta) = \sum_{k \ge 0} \frac{(t - t_0)^k}{k!}\, L_F^k g\bigl(z_0(\theta)\bigr). \tag{4}$$ -Collected up to order $N$ they form $\Psi_N(\theta)$, with the observability-identifiability matrix +Collected up to order $N$ they form $\Psi_N(\theta)$, with the +[observability-identifiability matrix]{#def-oim} (OIM) $$\mathrm{OIM}_N(\theta) = \frac{\partial \Psi_N(\theta)}{\partial \theta}. \tag{5}$$ +With free initial values among the parameters, one matrix tests both observability, the initial +states follow from the observables, and identifiability, the parameters do. + $\Psi_N$ is constant on every orbit, $\Psi_N(\Phi_\varepsilon(\theta)) = \Psi_N(\theta)$, and the derivative at $\varepsilon = 0$ is, by the chain rule and (2), -$$\frac{\mathrm{d}}{\mathrm{d}\varepsilon}\Psi_N\bigl(\Phi_\varepsilon(\theta)\bigr)\Big|_{\varepsilon = 0} -= \mathrm{OIM}_N(\theta)\, \xi(\theta) = 0. \tag{6}$$ +$$\begin{aligned} +\frac{\mathrm{d}}{\mathrm{d}\varepsilon}\Psi_N\bigl(\Phi_\varepsilon(\theta)\bigr)\Big|_{\varepsilon = 0} +&= \mathrm{OIM}_N(\theta)\, \xi(\theta) \\ +&= 0. +\end{aligned} \tag{6}$$ At generic $\theta$ and large enough $N$ the kernel of $\mathrm{OIM}_N$ consists exactly of the generators, $d - \operatorname{rank} \mathrm{OIM}_N$ counts them, and full rank means identifiable. For scalings, (6) reads $\mathrm{OIM}_N(\theta)\, \mathrm{diag}(\theta)\, w = 0$ for every $\theta$. With rational right-hand sides, observables and initial values it holds where every term -of every equation keeps the weighted degree, with weights on the states as well: a linear system in +of every equation has the [weighted degree]{#def-weighted-degree} of the left-hand side, the +degree of a monomial with each variable counted by the weight of that variable, with weights on the states as well: a linear system in the weights, whose integer solution lattice symident computes exactly. A scaling that holds only on an invariant set, such as a start at rest, fails this test. It is among the remaining kernel -vectors, the *general* directions, with closed forms from interpolation +vectors, the *[general directions]{#def-general-direction}*, generators that are no scaling, with +rational closed forms from interpolation ([symident method](https://dmodverse.github.io/symident/method.html)). -symident computes (5) exactly over finite fields $\mathbb{F}_p$ at a fixed base point and takes -the largest rank over several primes and a random point. The rank modulo $p$ at a point can only -fall below the generic value; the checks make a lower one unlikely but do not exclude it. symident -proves the order $N$ sufficient where it can. A direction is `"exact"` where the closed form is +symident computes (5) exactly over finite fields $\mathbb{F}_p$ at a fixed [base point]{#def-base-point}, the first primes 2, 3, 5, ... as parameter values, and +takes the largest rank over several primes and a random point. The rank modulo $p$ at a point can only +fall below the generic value; the checks make a lower one unlikely but do not exclude it. The +[Lie order]{#def-lie-order} $N$, the highest order in $\Psi_N$, is sufficient when no higher order +raises the rank of $\mathrm{OIM}_N$; symident proves this where it can. The +[level]{#def-level} of a direction is `"exact"` where the closed form is proven over the rationals, `"verified"` or `"checked"` where it is checked modulo a large prime at random points, with or without an error bound, and `"open"` without closed form; by default -(`reconstruct = FALSE`) a general direction is returned as the support. +(`reconstruct = FALSE`) a general direction is returned as the [support]{#def-support}, the coordinates with $\xi_i \not\equiv 0$ that the +generator moves. ### Steady-state starts, inputs and conditions @@ -112,15 +132,17 @@ a symmetry. Along every orbit the data term and the profiles of the data term are flat; a prior such as `constraintL2()` is not invariant and tilts them. The Hessian is flat in the generator directions at the optimum, in the Gauss-Newton approximation and for scalings on the log scale. So -symmetries are removed before the fit. A *gauge* fixes one coordinate per scaling; each orbit +symmetries are removed before the fit. A *[gauge]{#def-gauge}* fixes one coordinate per scaling; each orbit meets the fixed values in one point with the same prediction. With $W$ the weights of the scalings on the fixed coordinates, one row per generator, the gauge removes every scaling if $$\det W \ne 0 . \tag{7}$$ `symmetryReduction()` turns the generators into a parameter transformation: for scalings a -*section* fixing one coordinate per direction, for general directions invariants as new parameters -([reduction](https://dmodverse.github.io/symident/method.html#reduction-and-sections)). +*[section]{#def-section}*, a set that meets every orbit in one point, here by fixing one coordinate +per direction, for general directions a [chart]{#def-chart} on the set of orbits, invariants $q_k$ +as new parameters, returned only where valid on the domain declared by `positive` +([reduction](https://dmodverse.github.io/symident/method/reduction.html)). Reference: `symmetryDetection()`, `symmetryReduction()` diff --git a/vignettes/articles/methods-trust.Rmd b/vignettes/articles/methods-trust.Rmd index 01004bdd..6507378b 100644 --- a/vignettes/articles/methods-trust.Rmd +++ b/vignettes/articles/methods-trust.Rmd @@ -14,27 +14,30 @@ source("results/stored.R") knitr::read_chunk("../../examples/oppeltNPJSystBiolAppl2018/optimizers.R") ``` -`trust()` minimizes the objective function $\mathcal{J}(\theta)$, $-2 \log L$ or $-2 \log$ of the posterior, by a trust-region +`trust()` minimizes the objective function $\ell(\theta)$, $-2 \log L$ or $-2 \log$ of the posterior, by a trust-region method on the exact gradient [@kaschek2019dmod]. Arguments and usage: [Optimization](guide-optimization.html). ## Trust-region method -At the iterate $\theta_k$ with the gradient $b = \nabla \mathcal{J}(\theta_k)$ and a symmetric approximation $H$ of the Hessian, -`trust()` minimizes the quadratic model of the objective inside a ball, +At the iterate $\theta_k$ with the gradient $b = \nabla \ell(\theta_k)$ and a symmetric approximation $H$ of the Hessian, +`trust()` minimizes the [quadratic model]{#def-quadratic-model} $m(s)$ of the change of $\ell$ +along a step $s$, the second-order Taylor polynomial with $H$ in place of the Hessian, inside the +[trust region]{#def-trust-region}, a ball of [radius]{#def-radius} $r$, $$\min_{s} \; m(s) = b^\top s + \tfrac{1}{2}\, s^\top H s \quad \text{subject to} \quad \lVert s \rVert \le r . \tag{1}$$ -The ratio of actual to predicted decrease decides on the step and the radius $r$. Subproblem, +The ratio of actual to predicted decrease $-m(s)$ decides on the step and the radius $r$. Subproblem, radius, bounds and termination are the same for every source of $H$ and on the [sparse path](#sparse-hessians). ### Trust-region subproblem -`trust()` solves the subproblem (1) exactly, through the full eigendecomposition of $H$ -[@more1983computing]. The solution satisfies $(H + \nu I)\, s = -b$ with a multiplier $\nu \ge 0$ -that makes $H + \nu I$ positive semidefinite and vanishes unless the step reaches the boundary, +`trust()` solves the [subproblem]{#def-subproblem} (1), the minimization of the quadratic model over +the trust region, once per iteration and exactly, through the full eigendecomposition of $H$ +[@more1983computing]. The solution satisfies $(H + \nu I)\, s = -b$ with a [multiplier]{#def-multiplier} $\nu \ge 0$, +the Lagrange multiplier of the radius constraint, that makes $H + \nu I$ positive semidefinite and vanishes unless the step reaches the boundary, $\lVert s \rVert = r$. With $H = Q \Lambda Q^\top$, eigenvalues $\lambda_i$ and $\gamma = Q^\top b$, the step @@ -42,14 +45,16 @@ $$s(\nu) = -Q (\Lambda + \nu I)^{-1} \gamma \tag{2}$$ solves the subproblem when $\nu \ge \max(0, -\lambda_{\min})$ and either $\nu = 0$ with $\lVert s \rVert \le r$, or $\nu > 0$ with $\lVert s \rVert = r$. The second case is a root of the -secular equation +[secular equation]{#def-secular-equation}, which sets $\nu$ such that the step ends on the boundary, -$$\phi(\nu) = \frac{1}{r} - \frac{1}{\lVert s(\nu) \rVert} - = \frac{1}{r} - \Big( \sum_i \frac{\gamma_i^2}{(\lambda_i + \nu)^2} \Big)^{-1/2}, \tag{3}$$ +$$\begin{aligned} +\phi(\nu) &= \frac{1}{r} - \frac{1}{\lVert s(\nu) \rVert} \\ + &= \frac{1}{r} - \Big( \sum_i \frac{\gamma_i^2}{(\lambda_i + \nu)^2} \Big)^{-1/2}, +\end{aligned} \tag{3}$$ nearly linear for $\nu > -\lambda_{\min}$, solved by bisection on a bracket of $\nu$, every evaluation $O(n_\theta)$ in the eigenbasis. If $\gamma_i = 0$ for every eigenvector of -$\lambda_{\min} < 0$ and $\lVert s(-\lambda_{\min}) \rVert \le r$ (hard case), the solution is +$\lambda_{\min} < 0$ and $\lVert s(-\lambda_{\min}) \rVert \le r$ ([hard case]{#def-hard-case}), the solution is $s(-\lambda_{\min}) + \tau q_{\min}$ with $\lVert s \rVert = r$; otherwise it is the root of (3). Negative curvature is followed to the boundary. The eigendecomposition costs $O(n_\theta^3)$; sparse Hessians use the [sparse path](#sparse-hessians). @@ -58,7 +63,7 @@ followed to the boundary. The eigendecomposition costs $O(n_\theta^3)$; sparse H With the ratio of actual to predicted decrease -$$\rho_k = \frac{\mathcal{J}(\theta_k) - \mathcal{J}(\theta_k + s_k)}{-m_k(s_k)}, \tag{4}$$ +$$\rho_k = \frac{\ell(\theta_k) - \ell(\theta_k + s_k)}{-m_k(s_k)}, \tag{4}$$ the radius is updated with $r_{\max}$ = `rmax`: @@ -70,20 +75,24 @@ r_k, & \text{otherwise.} A step with $\rho_k < 1/4$ is rejected. The radius grows only when the step reached the boundary. Under `boundary = "clip"` the radius shrinks to $r_k/4$, grows at $\rho_k > 3/4$ after every step -that is not the Newton step, and a step that lowers $\mathcal{J}$ is accepted where the value or model test ends the run. +that is not the Newton step, and a step that lowers $\ell$ is accepted where the value or model test ends the run. The first radius is `rinit`. A trial point where the objective fails or is not finite counts as rejected; three in a row end the run (`"objfun"`). ### Nonmonotone acceptance -With `stepControl$nonmonotone` $= \eta \in (0, 1)$, the actual decrease is measured from a -weighted average of past values [@zhang2004nonmonotone], +With `stepControl$nonmonotone` $= \eta \in (0, 1)$, +[nonmonotone acceptance]{#def-nonmonotone-acceptance} measures the actual decrease from a +weighted average of past values [@zhang2004nonmonotone], so an accepted step may raise $\ell$, -$$Q_{k+1} = \eta Q_k + 1, \qquad C_{k+1} = \frac{\eta Q_k C_k + \mathcal{J}(\theta_{k+1})}{Q_{k+1}}, \tag{6}$$ +$$\begin{aligned} +Q_{k+1} &= \eta Q_k + 1, \\ +C_{k+1} &= \frac{\eta Q_k C_k + \ell(\theta_{k+1})}{Q_{k+1}}, +\end{aligned} \tag{6}$$ -updated at accepted steps, and $\rho_k = \bigl(C_k - \mathcal{J}(\theta_k + s_k)\bigr) / \bigl(-m_k(s_k)\bigr)$; +updated at accepted steps, and $\rho_k$ is (4) with $C_k$ in place of $\ell(\theta_k)$; $\eta = 0$ recovers (4). -The result is the best iterate visited; the termination tests read $\mathcal{J}$ itself. +The result is the best iterate visited; the termination tests read $\ell$ itself. ### Bound constraints @@ -110,17 +119,22 @@ can stop at a non-stationary point if $H$ is poor. A `"gradient"`, `"fvalue"` or that ends the run also needs the full Newton step of the scaled model (7) at the current iterate to predict a decrease of at most `mtol`, -$$\tfrac{1}{2}\, \hat b^\top \hat B^{+} \hat b - = \frac{1}{2} \sum_{\hat\lambda_i > 0} \frac{(\hat q_i^\top \hat b)^2}{\hat\lambda_i} \le \texttt{mtol} , \tag{8}$$ +$$\begin{aligned} +\tfrac{1}{2}\, \hat b^\top \hat B^{+} \hat b + &= \frac{1}{2} \sum_{\hat\lambda_i > 0} \frac{(\hat q_i^\top \hat b)^2}{\hat\lambda_i} \\ + &\le \texttt{mtol} , +\end{aligned} \tag{8}$$ -with the eigenpairs $(\hat\lambda_i, \hat q_i)$ of $\hat B$, eigenvalues inside the noise floor of -the eigendecomposition counted as zero. Along a direction of curvature $\lambda$ the gradient at a +with [$\hat B^{+}$]{#def-b-hat-plus} the inverse of $\hat B$ on the eigenvectors of positive +eigenvalues and zero on the others, the eigenpairs $(\hat\lambda_i, \hat q_i)$ of $\hat B$, and +eigenvalues inside the [noise floor]{#def-noise-floor} of the eigendecomposition, the rounding error +below which an eigenvalue is not resolved, counted as zero. Along a direction of curvature $\lambda$ the gradient at a distance $d$ from the minimum is $\lambda d$ and the value lies $\lambda d^2 / 2$ above it, so a small gradient along a flat direction does not mean a value close to the minimum; (8) bounds that excess. On the [sparse path](#sparse-hessians) the Cholesky factors give (8) where $\hat B$ is positive definite, the dense eigendecomposition of $\hat B$ elsewhere; `trustL1()` evaluates (8) on the model of the coordinates not held at a kink ([L1 penalties](#l1-penalties)). A run that fails -(8) goes on, within `iterlim`; `mtol = 0` drops the condition. Stagnation, five rejected steps in a +(8) goes on, within `iterlim`; `mtol = 0` drops the condition. [Stagnation]{#def-stagnation}, five rejected steps in a row that leave the value within `ftol`, ends the run, with `converged = TRUE` only where (8) holds: where the noise of the value exceeds the decrease a step predicts, a non-stationary point stagnates as well. While further phases follow, the @@ -144,7 +158,8 @@ second is small where residuals scatter around zero. A Gaussian prior adds twice the diagonal ([Likelihood and prior](methods-objective.html#prior)). With a parameter-dependent error model the matrix is $J^\top L J$, not necessarily semidefinite ([Sensitivities and Hessians](methods-sensitivities.html#gauss-newton-with-an-error-model)). With -large residuals the Gauss-Newton model can stop short of the minimum. +[large residuals]{#def-large-residual}, where the second term is not small, the Gauss-Newton model +can stop short of the minimum. ### Exact Hessian @@ -156,22 +171,27 @@ residuals and at a much higher cost per iteration. Both quasi-Newton updates use the secant pair -$$s_k = \theta_{k+1} - \theta_k, \qquad y_k = \nabla \mathcal{J}(\theta_{k+1}) - \nabla \mathcal{J}(\theta_k), \tag{9}$$ +$$\begin{aligned} +s_k &= \theta_{k+1} - \theta_k, \\ +y_k &= \nabla \ell(\theta_{k+1}) - \nabla \ell(\theta_k), +\end{aligned} \tag{9}$$ with the secant equation $B_{k+1} s_k = y_k$. BFGS keeps $B$ positive definite, which needs -$s^\top y > 0$; the pair is damped [@powell1978fast]: +$s^\top y > 0$; the pair is [damped]{#def-damping}, $y$ mixed with $B s$ [@powell1978fast]: -$$\vartheta = \begin{cases} +$$\begin{aligned} +\vartheta &= \begin{cases} 1, & s^\top y \ge 0.2\, s^\top B s, \\ \dfrac{0.8\, s^\top B s}{s^\top B s - s^\top y}, & \text{otherwise,} -\end{cases} -\qquad \tilde y = \vartheta y + (1 - \vartheta) B s , \tag{10}$$ +\end{cases} \\ +\tilde y &= \vartheta y + (1 - \vartheta) B s , +\end{aligned} \tag{10}$$ the update is $$B_{k+1} = B_k - \frac{B_k s\, s^\top B_k}{s^\top B_k s} + \frac{\tilde y\, \tilde y^\top}{s^\top \tilde y}. \tag{11}$$ -Then $s^\top \tilde y \ge 0.2\, s^\top B s > 0$. `qnCautious` skips pairs with +Then $s^\top \tilde y \ge 0.2\, s^\top B s > 0$. The [cautious test]{#def-cautious-test} `qnCautious` skips pairs with $s^\top y \le c \lVert s \rVert \lVert y \rVert$ (counted in `qnSkipped`). BFGS updates from accepted steps only. @@ -191,14 +211,16 @@ The data term of `normL2()` is a sum of row losses $\ell_i(m_i)$ in the predicti $m_i$ of a data point, $\ell_i = r_i^2$ in the simplest case. With the Jacobian $J$ of all $m_i$ and the derivatives $u_i = \partial \ell_i / \partial m_i$, the gradient is $J^\top u$ and the Hessian is the Gauss-Newton Hessian $G = J^\top L J$, $L$ the Hessian of the losses in $m$, which -the objective returns, plus $C = \sum_i u_i^\top \nabla^2 m_i$. The structured methods keep $G$ +the objective returns, plus $C = \sum_i u_i^\top \nabla^2 m_i$. The [structured secant updates]{#def-structured-secant-update} keep $G$ at every iterate and learn only $A \approx C$ from the steps. The secant of Dennis, Martínez and Tapia [@dennis1989convergence] is $(J_{k+1} - J_k)^\top u_{k+1}$ for the data term, of Gauss-Newton Hessian $G^{\rm LS}$; the other terms of a sum, such as a prior, take the secant of their gradient and Hessian: -$$B_k = G_k + A_k, \qquad -y^\#_k = y_k - J_k^\top (u_{k+1} - u_k) - \left(G_{k+1} - G^{\rm LS}_{k+1}\right) s_k , \tag{13}$$ +$$\begin{aligned} +B_k &= G_k + A_k, \\ +y^\#_k &= y_k - J_k^\top (u_{k+1} - u_k) - \left(G_{k+1} - G^{\rm LS}_{k+1}\right) s_k , +\end{aligned} \tag{13}$$ $s_k$ and $y_k$ from (9). For $\ell_i = r_i^2$, $u = 2 r$ and the data part is $2 (J_{k+1} - J_k)^\top r_{k+1}$, as in Fides [@froehlich2022fides]. It equals @@ -221,27 +243,33 @@ $$A_{k+1} = A_k + \frac{w\, w^\top}{w^\top s_k}, \qquad w = y^\#_k - A_k s_k, \t skipped when $\lvert w^\top s_k \rvert \le 10^{-8} \lVert s_k \rVert \lVert w \rVert$. $A$ stays indefinite where $C$ is, and rejected trial points update it under `qnRejected`. Both start at -$A_0 = 0$, so the first step is a Gauss-Newton step; a handover or a reseed starts there again. +$A_0 = 0$, so the first step is a Gauss-Newton step; a handover or a [reseed]{#def-reseed}, a restart of the update from a new seed, starts there again. A pair that leaves $A$ unchanged counts in `qnSkipped`. `qnScaling = "residual"` is the totally structured secant method of Huschens [@yabe1998quadratic]. With the residual norm $\rho = \lVert u \rVert$, which is $2 \lVert r \rVert$ -for $\ell_i = r_i^2$, and $\rho = \sqrt{\mathcal{J}}$ for an objective without data rows, +for $\ell_i = r_i^2$, and $\rho = \sqrt{\ell}$ for an objective without data rows, $$B_k = G_k + \rho_k A_k, \qquad z_k = \frac{\rho_{k+1}}{\rho_k}\, y^\#_k , \tag{16}$$ (14) or (15) act on $\rho_{k+1} A_k$ with $z_k$ in place of $y^\#_k$, and $A_{k+1}$ is the result divided by $\rho_{k+1}$. The correction vanishes with the residuals: convergence is -quadratic for a zero residual and superlinear otherwise. $\rho = 0$ leaves $A$ unchanged. +quadratic for a [zero residual]{#def-zero-residual}, an exact fit of the data at the minimum where +$C = 0$, and superlinear otherwise. $\rho = 0$ leaves $A$ unchanged. `"gnsbfgs"` is the hybrid Gauss-Newton structured BFGS method of Zhou and Chen [@zhou2010global]. After every accepted step, with $z_k$ from (16), -$$B_{k+1} = \begin{cases} -G_{k+1} + A_{k+1}, \quad A_{k+1} = \operatorname{BFGS}(A_k;\ s_k, z_k), - & z_k^\top s_k \ge \epsilon\, s_k^\top s_k , \\ -G_{k+1}, \quad A_{k+1} = A_k, & \text{otherwise,} -\end{cases} \tag{17}$$ +$$\begin{aligned} +B_{k+1} &= \begin{cases} +G_{k+1} + A_{k+1}, & z_k^\top s_k \ge \epsilon\, s_k^\top s_k , \\ +G_{k+1}, & \text{otherwise,} +\end{cases} \\ +A_{k+1} &= \begin{cases} +\operatorname{BFGS}(A_k;\ s_k, z_k), & z_k^\top s_k \ge \epsilon\, s_k^\top s_k , \\ +A_k, & \text{otherwise,} +\end{cases} +\end{aligned} \tag{17}$$ with $\epsilon$ = `qnHybridTol`, default $10^{-6}$ as in the paper, the undamped update (11) and $A_0 = 0$. The ratio $z^\top s / s^\top s$ tends to zero for a zero residual, where the run becomes @@ -258,16 +286,16 @@ branch, `hybridGN` counts the steps that chose it. ### Seed and memory -Far from the optimum $J^\top J$ is large and ill-conditioned; BFGS corrects a seed that is wrong +Far from the optimum $J^\top J$ is large and ill-conditioned; BFGS corrects a [seed]{#def-seed}, the matrix the update starts from, that is wrong by orders of magnitude only slowly, SR1 overwrites it. With `qnMemory` $= m > 0$ the approximation is rebuilt from $\gamma I$, $\gamma = y^\top y / s^\top y$ [@shanno1978matrix], and the last $m$ pairs, the curvature of L-BFGS [@nocedal2006numerical] as an explicit matrix. There is no -diagonal preconditioner: on the log scale the ill-conditioning of sloppy models lies along rotated -directions [@gutenkunst2007universally]. +diagonal preconditioner: on the log scale the ill-conditioning of [sloppy models]{#def-sloppy-model}, whose Hessian eigenvalues spread evenly +over many orders of magnitude, lies along rotated directions [@gutenkunst2007universally]. ### Hessian phases -A phase hands over to the next where a value, model, step or stagnation stop or the `iterlim` of the phase +A [phase]{#def-phase}, a part of the run with one source of $H$, [hands over]{#def-handover} to the next where a value, model, step or stagnation stop or the `iterlim` of the phase would end the run; `"gradient"` ends the run, and with `onStop = "end"` the value, model, step and stagnation stops end it as well. A phase with `radiusStall` $= n$ also hands over after $n$ consecutive iterations that leave the radius unchanged, an accepted step inside the region or one @@ -291,8 +319,8 @@ phase evaluates the gradient forward, so the switch costs no evaluation. Multipl ### Sparse Hessians -A sparse Hessian $H = S + U D U^\top$, $S$ sparse and $U$ of few columns $m$ with the diagonal -$D$, takes the same steps without the eigendecomposition. The root of (3) is found by Newton's +A sparse Hessian $H = S + U D U^\top$, $S$ sparse and the [low-rank part]{#def-low-rank-part} $U D U^\top$ of few columns $m$ in $U$ and the +diagonal $D$, dense curvature without a dense matrix, takes the same steps without the eigendecomposition. The root of (3) is found by Newton's method on $1/\lVert s(\nu) \rVert$, safeguarded by a bracket of $\nu$, to a relative $10^{-12}$: every iterate factorizes $S + \nu I$ by sparse Cholesky, with the ordering of one symbolic analysis per pattern, and adds $U D U^\top$ by the Woodbury identity through @@ -310,8 +338,10 @@ $m$ pairs (9), $m$ = `qnMemory` or 10 where that is 0, each damped by (10) again updates and skipped by the same tests as the dense update. In the compact representation [@byrd1994representations] -$$B = B_0 - W M^{-1} W^\top, \qquad W = (B_0 S,\ Y), \qquad -M = \begin{pmatrix} S^\top B_0 S & L \\ L^\top & -E \end{pmatrix}, \tag{18}$$ +$$\begin{aligned} +B &= B_0 - W M^{-1} W^\top, \qquad W = (B_0 S,\ Y), \\ +M &= \begin{pmatrix} S^\top B_0 S & L \\ L^\top & -E \end{pmatrix}, +\end{aligned} \tag{18}$$ $S$ and $Y$ hold the pairs as columns, $L$ the strict lower triangle of $S^\top Y$ and $E$ the diagonal. With $M = P \Theta P^\top$ the correction joins the low-rank part as the $2m$ columns of @@ -335,23 +365,24 @@ Gauss-Newton Hessian misses curvature that matters. `trustL1()` minimizes the objective plus an L1 penalty on some of the parameters [@tibshirani1996regression], -$$\mathcal{J}(\theta) + \sum_{i \in P} \lambda_i \lvert \theta_i - \mu_i \rvert , \tag{19}$$ +$$\ell(\theta) + \sum_{i \in P} \lambda_i \lvert \theta_i - \mu_i \rvert , \tag{19}$$ with penalized parameters $P$, references $\mu_i$ and strengths $\lambda_i$. `trustL1()` runs the trust region with the Gauss-Newton Hessian and two changes: a parameter on the kink is removed from -(1) while $\lvert \partial \mathcal{J} / \partial \theta_i \rvert \le \lambda_i$, and a step across the kink is +(1) while $\lvert \partial \ell / \partial \theta_i \rvert \le \lambda_i$, and a step across the kink is cut back onto $\mu_i$, so zero differences are exact. Further penalties are a one-sided one, $$\lambda_i \max(0,\, \mu_i - \theta_i) , \tag{20}$$ -which keeps a parameter on the kink while $0 \le \partial \mathcal{J} / \partial \theta_i \le \lambda_i$; a gate +which keeps a parameter on the kink while $0 \le \partial \ell / \partial \theta_i \le \lambda_i$; a gate $\lambda_i (\theta_i - \mu_i)$ with $\theta_i \ge \mu_i$, which keeps it there while -$\partial \mathcal{J} / \partial \theta_i \ge -\lambda_i$; and a fused block $B$, the clustered lasso +$\partial \ell / \partial \theta_i \ge -\lambda_i$; and a [fused block]{#def-fused-block} $B$, the [clustered lasso]{#def-clustered-lasso} [@hauber2023uncovering] in the L1 form (Hauber et al. favor the exponent 0.8), $$\lambda \sum_{p < q \in B} w_{pq}\, \lvert \theta_p - \theta_q \rvert , \tag{21}$$ -optionally with an anchor; equal parameters move as one until the data split them. +optionally with an anchor; it merges the parameters of $B$ into clusters of equal value, which move +as one until the data split them. ## Forward and reverse derivatives on the Oppelt fit @@ -401,7 +432,8 @@ summary <- do.call(rbind, lapply(split(opt, opt$method), function(d) data.frame( summary ``` -Medians over starts; a hit ends within 5 of the best value; `iterlim` counts the runs stopped by +Medians over starts; a [plateau]{#def-plateau} is a group of fits with one final value, a local +optimum; a [hit]{#def-hit} ends within 5 of the best value; `iterlim` counts the runs stopped by the iteration limit; `failed` counts runs without result, which the time limit of a task ended. The stops by method, with a stagnation that ends away from a stationary point of the model counted apart: diff --git a/vignettes/articles/migrating.Rmd b/vignettes/articles/migrating.Rmd index 79a4ee33..59bef9f1 100644 --- a/vignettes/articles/migrating.Rmd +++ b/vignettes/articles/migrating.Rmd @@ -12,14 +12,15 @@ What a dMod [@kaschek2019dmod] script has to change for dMod2. Function objects and algebra are the same: `Xs()`, `Xf()`, `Y()`, `P()`, `Pexpl()`, `Pimpl()`, `normL2()`, `constraintL2()`, `datapointL2()`, with `*` for concatenation, `+` for conditions or objective terms, and `normL2(data, g * x * p)`. `eqnlist()`, `addReaction()`, `define()`, -`insert()`, `branch()`, `repar()`, `trust()`, `mstrust()`, `profile()` and `plot*()` keep names +`insert()`, `branch()`, `trust()`, `mstrust()`, `profile()` and `plot*()` keep names and main arguments. dMod2 has `getSymbols()` and `replaceSymbols()`, so `library(cOde)` is not needed. ## Substitution syntax -`define()`, `insert()` and `repar()` take `"lhs <- rhs"`; `"lhs ~ rhs"` is an -error naming the new form. +`define()` and `insert()` take `"lhs <- rhs"`; `"lhs ~ rhs"` is an +error naming the new form. `repar()` is internal: `define()` sets an entry, `insert()` +replaces a symbol wherever it occurs. | dMod | dMod2 | |---|---| diff --git a/vignettes/articles/refs.bib b/vignettes/articles/refs.bib index f86bb8ed..e14952ad 100644 --- a/vignettes/articles/refs.bib +++ b/vignettes/articles/refs.bib @@ -662,3 +662,36 @@ @article{gerstner2003dimension year = {2003}, doi = {10.1007/s00607-003-0015-5} } + +@article{scott2010bayes, + title = {Bayes and Empirical-{{Bayes}} Multiplicity Adjustment in the Variable-Selection Problem}, + author = {Scott, James G. and Berger, James O.}, + date = {2010}, + journaltitle = {The Annals of Statistics}, + volume = {38}, + number = {5}, + pages = {2587--2619}, + doi = {10.1214/10-AOS792}, +} + +@article{gelman2006prior, + title = {Prior Distributions for Variance Parameters in Hierarchical Models}, + author = {Gelman, Andrew}, + date = {2006}, + journaltitle = {Bayesian Analysis}, + volume = {1}, + number = {3}, + pages = {515--534}, + doi = {10.1214/06-BA117A}, +} + +@article{polson2012half, + title = {On the Half-{{Cauchy}} Prior for a Global Scale Parameter}, + author = {Polson, Nicholas G. and Scott, James G.}, + date = {2012}, + journaltitle = {Bayesian Analysis}, + volume = {7}, + number = {4}, + pages = {887--902}, + doi = {10.1214/12-BA730}, +}