From 02c9b81ad260421e5260551b88c774427daaa61a Mon Sep 17 00:00:00 2001 From: Simon Beyer <64092903+simonbeyer1@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:08:45 +0100 Subject: [PATCH] feat(nlme): spikeSlab() with a given slab mean and spike, -Inf included, fitted by focei, quadrature and saem beside normal random effects; gr(dist = ) without a grouping; dimension-adaptive sparse grids in C++ for the quadrature of em(); symident >= 0.18.1; review of the whole package: compile() never unloads a shared object, SBML root events as two triggers, fitErrorModel() with the symbolic gradient, plotPairs() and getObservables() removed, checks in the C++ kernels; dMod2 0.17.0 Co-Authored-By: Claude Opus 5.5 --- DESCRIPTION | 4 +- NAMESPACE | 2 - NEWS.md | 56 +- R/EM.R | 123 +++- R/PEtabInterface.R | 85 +-- R/RcppExports.R | 32 + R/SBMLinterface.R | 117 +++- R/accessors.R | 20 +- R/alignment.R | 7 +- R/classes.R | 193 +++--- R/compile.R | 46 +- R/dataClass.R | 4 +- R/emResults.R | 35 +- R/eqnClass.R | 8 + R/eventClass.R | 1 + R/linalg.R | 2 +- R/multipleShooting.R | 26 +- R/nlmeDesign.R | 22 +- R/nlmeDiagnostics.R | 8 +- R/nlmeQuadrature.R | 189 +++--- R/nlmeSaem.R | 181 ++++-- R/nlmeSparse.R | 4 +- R/nlmeSpikeEC.R | 175 ++++++ R/nlmeSpikeSlab.R | 10 +- R/nlmeSpikeSubsets.R | 592 ++++++++++++++++++ R/normL2reverse.R | 10 +- R/objClass.R | 23 +- R/odeClass.R | 2 +- R/parClass.R | 15 +- R/parameters.R | 1 - R/plots.R | 75 +-- R/plotsEM.R | 5 +- R/prdClass.R | 12 +- R/prediction.R | 3 +- R/randomEffects.R | 67 +- R/reml.R | 25 +- R/remoteComputing.R | 15 +- R/reverse.R | 8 +- R/sanitize.R | 5 +- R/sparse.R | 4 +- R/statistics.R | 112 ++-- R/symbolics.R | 75 +++ R/symmetryDetection.R | 115 ++-- R/symmetryReduction.R | 35 +- R/trust.R | 34 +- R/trustShooting.R | 43 +- R/utils.R | 5 +- _pkgdown.yml | 2 - .../oppeltNPJSystBiolAppl2018/symmetries.R | 2 +- inst/WORDLIST | 255 +++++--- inst/code/dmodToSbml.py | 6 +- inst/examples/P.R | 1 + inst/examples/Xf.R | 9 + inst/examples/accessors.R | 15 + inst/examples/as.eventlist.R | 3 + inst/examples/customTotals.R | 9 + inst/examples/eqnvec.R | 2 + inst/examples/getLocalDLLs.R | 2 + inst/examples/normal.R | 8 + inst/examples/objlist.R | 8 + inst/examples/parlist.R | 1 + inst/examples/prdframe.R | 9 + inst/examples/res.R | 10 + inst/examples/write.eqnlist.R | 4 + man/P.Rd | 1 + man/Xd.Rd | 2 +- man/Xf.Rd | 11 + man/align.Rd | 3 +- man/as.data.frame.dMod.Rd | 11 + man/as.data.frame.eqnlist.Rd | 31 + man/as.eqnvec.Rd | 31 + man/as.eventlist.Rd | 5 + man/as.parframe.Rd | 38 ++ man/as.parvec.parframe.Rd | 38 ++ man/c.parvec.Rd | 36 ++ man/covariates.Rd | 30 + man/customTotals.Rd | 11 + man/discreteSymmetries.Rd | 58 +- man/em.Rd | 94 ++- man/eqnvec.Rd | 2 + man/exportSbml.Rd | 6 +- man/fitErrorModel.Rd | 6 +- man/format.eqnvec.Rd | 8 + man/getConditions.Rd | 17 + man/getEquations.Rd | 17 + man/getLocalDLLs.Rd | 4 + man/getObservables.Rd | 19 - man/getParameters.Rd | 17 + man/importSbml.Rd | 2 + man/load.parlist.Rd | 13 +- man/modelname.Rd | 17 + man/normal.Rd | 27 +- man/objframe.Rd | 12 + man/parlist.Rd | 1 + man/plotPairs.Rd | 21 - man/plotProfilesAndPaths.Rd | 5 + man/plus-.objlist.Rd | 10 + man/prdframe.Rd | 11 + man/prdlist.Rd | 11 + man/print.eqnlist.Rd | 31 + man/print.eqnvec.Rd | 8 + man/print.parfn.Rd | 12 + man/print.parvec.Rd | 36 ++ man/profileThreshold.Rd | 4 + man/randomEffects.Rd | 10 +- man/reconstControl.Rd | 6 +- man/res.Rd | 12 + man/sub-.parvec.Rd | 36 ++ man/summary.eqnvec.Rd | 8 + man/symmetryDetection.Rd | 14 +- man/symmetryReduction.Rd | 19 +- man/unique.parframe.Rd | 38 ++ man/vcov.em.Rd | 8 +- man/write.eqnlist.Rd | 6 + pkgdown/index.md | 12 +- src/Makevars | 3 +- src/Makevars.win | 3 +- src/RcppExports.cpp | 100 +++ src/adaptiveGrid.cpp | 372 +++++++++++ src/chain_kernel.cpp | 6 +- src/constraint_kernel.cpp | 2 +- src/focei_kernel.cpp | 4 +- src/normL2_kernel.cpp | 17 +- src/pimpl_kernel.cpp | 43 +- src/reach_kernel.cpp | 1 + src/trust_model.h | 10 +- src/trust_subproblem.h | 5 +- tests/testthat/_snaps/statsOutput.md | 18 +- tests/testthat/test-EMsparse.R | 10 +- tests/testthat/test-Pexpl.R | 2 +- tests/testthat/test-fn-composition-protocol.R | 31 + tests/testthat/test-loadDLL.R | 48 ++ tests/testthat/test-mstrust.R | 20 + tests/testthat/test-multipleShooting.R | 14 + tests/testthat/test-normL2.R | 6 +- tests/testthat/test-petab.R | 74 +++ tests/testthat/test-plots.R | 17 + tests/testthat/test-quadrature.R | 30 +- tests/testthat/test-randomEffects.R | 44 ++ tests/testthat/test-remote-libs.R | 6 + tests/testthat/test-spikeSlabSubsets.R | 256 ++++++++ tests/testthat/test-statsOutput.R | 31 +- tests/testthat/test-symmetry.R | 16 +- tests/testthat/test-trust.R | 17 + .../articles/guide-sparse-deviations.Rmd | 27 +- vignettes/articles/installation.Rmd | 2 +- .../articles/methods-multiple-shooting.Rmd | 6 +- vignettes/articles/methods-nlme.Rmd | 24 +- .../articles/methods-sparsity-priors.Rmd | 66 +- vignettes/articles/refs.bib | 11 + 150 files changed, 4222 insertions(+), 983 deletions(-) create mode 100644 R/nlmeSpikeEC.R create mode 100644 R/nlmeSpikeSubsets.R create mode 100644 inst/examples/Xf.R create mode 100644 inst/examples/accessors.R create mode 100644 inst/examples/as.eventlist.R create mode 100644 inst/examples/customTotals.R create mode 100644 inst/examples/getLocalDLLs.R create mode 100644 inst/examples/objlist.R create mode 100644 inst/examples/prdframe.R create mode 100644 inst/examples/res.R create mode 100644 inst/examples/write.eqnlist.R delete mode 100644 man/getObservables.Rd delete mode 100644 man/plotPairs.Rd create mode 100644 src/adaptiveGrid.cpp create mode 100644 tests/testthat/test-spikeSlabSubsets.R diff --git a/DESCRIPTION b/DESCRIPTION index 9e87eff3..d5ba7398 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Package: dMod2 Type: Package Title: Parameter Estimation in Dynamical Models -Version: 0.16.1 +Version: 0.17.0 Date: 2026-11-16 Authors@R: c( person("Simon", "Beyer", email = "simon.beyer@fdm.uni-freiburg.de", @@ -66,7 +66,7 @@ Suggests: ragg, rjson, yaml -SystemRequirements: C++17 compiler; Python (>= 3.9) with SymPy, NumPy and +SystemRequirements: C++17 compiler; Python (>= 3.10) with SymPy, NumPy and SciPy; the Python packages python-libsbml for SBML and PEtab, and symident for symmetryDetection() and symmetryReduction(). reticulate provides the Python packages on first use; symident is installed from PyPI. diff --git a/NAMESPACE b/NAMESPACE index 96c9a8ee..fb6951fe 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -240,7 +240,6 @@ export(getDerivs2) export(getEquations) export(getFluxes) export(getLocalDLLs) -export(getObservables) export(getParameters) export(getReactions) export(getSymbols) @@ -277,7 +276,6 @@ export(plotArray) export(plotCombined) export(plotData) export(plotFluxes) -export(plotPairs) export(plotPars) export(plotPaths) export(plotPathsMulti) diff --git a/NEWS.md b/NEWS.md index b0a5a05f..77a31f39 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,57 @@ +# dMod2 0.17.0 + +* Requires symident >= 0.18.1. The global analysis of symident stops on work limits instead of time + limits. `discreteSymmetries()` drops `timeout` and `budget` and takes `memory`, `experiments`, + `msolveEntries`, `msolveTerms`, `searchEntries` and `eliminationTerms`, also as `globalOptions` of + `symmetryDetection(mode = "global")`; `info$discrete` holds the certificate of the count + (`certificate$complete`), `countBound`, `countDomain`, `experiments`, `eliminated` and `relaxed`. + `timeout` is removed from `symmetryReduction()` and `reconstControl()`, and `discrete` from + `symmetryDetection()`: use `mode = "global"`. +* `spikeSlab()` takes the slab mean `mean` and the spike `spike`, both given, not estimated: + `(1 - prob) delta_spike + prob N(mean, tau^2)`. `spike = -Inf` under an exponential + transformation switches the parameter off; `em()` checks that the random effect is a summand in + the exponent of a numeric base greater than 1. Defaults keep the former distribution. +* `gr(dist = )` without a grouping column makes one group `all` of all conditions. With `0 +` the + random effect is the parameter itself, so that `k1 + k2 ~ 0 + (1 | gr(dist = spikeSlab(spike = + -Inf)))` selects reaction rates; placeholders, `x ~ ... , x = c("k1", "k2")`, share `prob` and + `tau` the same way. +* `em(method = "focei")` fits spike-and-slab random effects with `mean` or `spike` other than 0, + also beside normal random effects of the same grouping, by the sum over all subsets per group, + each a Laplace integral, with EM for the fixed effects, Omega and the hyperparameters + (`control$sparseFit$maxEcm`, `epsEcm`, `budget`). Groups beyond the budget take the expectation + consistent (EC) approximation in the rate coordinate, with a log-normal slab and the data term + expanded again at the EC mean (`control$sparseFit$ec`). `logLik(method = "importance")` refuses + these fits. +* `em(method = "quadrature")` fits spike-and-slab random effects with any `mean` and `spike`, also + beside normal ones: every subset of non-negligible weight on a sparse grid around the inner mode, + then `trust()` on -2 log L over the fixed nodes until the rebuilt grids gain less than + `control$quadrature$tolDecrement`. +* `em(method = "saem")` draws spike-and-slab random effects with a given `mean` and `spike`, `-Inf` + included, beside normal ones: a move into the slab from a spike at `-Inf` proposes from the + Laplace approximation of the coordinate by Newton steps on the model; -2 log L at the estimate is + the sum over subsets of `method = "focei"`. +* The quadrature of `em()` refines the sparse grids dimension-adaptively (Gerstner and Griebel 2003) + in C++: from the Smolyak grid of the stage and the grid of the last rebuild, only in the + directions in which the integrand departs from the Gaussian at the mode, with the change by the + evaluated neighbors as the error. `control$quadrature$maxNodes` counts the evaluated nodes. +* `fitErrorModel()` fits with the symbolic gradient of the error model and refuses a model without + one; the group column of `blather = TRUE` is `group`. +* `plotPairs()` and `getObservables()`, generics without methods, are removed. `plotProfilesAndPaths()` takes `maxvalue` and `threshold` like + `plotProfile()`. +* `compile(output = )` passes the suffixed name (`_2`, ...) of a shared object to the model names, + and `getLocalDLLs()` counts a shared object only below the working directory. Without `output`, + `compile()` skips a source whose shared object is loaded instead of unloading and rebuilding it. +* `*` of two functions whose conditions do not overlap is an error. `objfn * parfn` keeps the + prediction of the objective only where it composes with the parameter function. +* `confint()` compares the extrapolation of a profile with the span of the whole branch. + `mstrust()` passes `rinit`, `rmax` and `n` only to an optimizer that takes them. + `trust()` with multiple shooting counts the iterations of the first phase against `iterlim`. +* `distributedComputing(wait = TRUE)` polls ssh nodes and queues every 10 s. +* `exportSbml()` writes a root event as the trigger `root >= 0`, which fires when the root rises + through 0. `importSbml()` keeps a compartment that an event resizes as a symbol and returns the + start sizes in `compartmentInits`. Formulas of SBML and PEtab files evaluate with the + functions of `?cppDE::expressions` only. `importPEtab()` refuses an `estimate` other than 0 or 1. + # dMod2 0.16.1 * `derivMode` alone selects the derivatives a constructor builds: `odemodel()`, `Y()`, `P()`, @@ -347,7 +401,7 @@ * American spelling throughout: `trust(stepControl = list(regularize = ))` replaces `regularise`, the attribute `run` of the result of `mstrust()` names `optimizer` and `optimizerArgs` instead - of `optimiser` and `optimiserArgs`, and the sequential palette `"grey"` of [dMod_palettes()] is `"gray"`. + of `optimiser` and `optimiserArgs`, and the sequential palette `"grey"` of [dMod2_palettes()] is `"gray"`. * `wide2long()`, `%bmm%`, `rref()`, `nullZ()` and `submatrix()` are no longer exported, and `ggopen()` is removed. `as.data.frame()` of a prediction returns the long format of diff --git a/R/EM.R b/R/EM.R index c0598dd6..006584bf 100644 --- a/R/EM.R +++ b/R/EM.R @@ -26,11 +26,16 @@ #' several groupings; also for spike-and-slab and Dirichlet-process #' random effects (at most 14 groups).} #' \item{`"quadrature"`}{adaptive sparse-grid quadrature around the modes, -#' started from the FOCEI fit; section Quadrature.} +#' started from the FOCEI fit; section Quadrature. Also for spike-and-slab +#' random effects alone, per subset; section Sparse random effects.} #' \item{`"laplaceEM"`}{ECM on the Laplace approximation with the #' covariance-corrected update of `Omega`.} #' \item{`"saem"`}{stochastic-approximation EM, also for spike-and-slab and -#' Dirichlet-process random effects; section SAEM.} +#' Dirichlet-process random effects; section SAEM. With many structural +#' parameters and sparse random effects it does not find the optimum from +#' random starts reliably; start it from a `"focei"` fit, +#' `em(obj, random, fit, method = "saem")`, to check that fit without the +#' Laplace approximation.} #' } #' #' @param obj Objective of the data, [normL2()] or [normT()] of the model @@ -143,7 +148,9 @@ #' \item{`coupling`}{`"expectationConsistent"` where a group needed it, #' else `NULL`.} #' \item{`boundary`}{the hyperparameters set to 0, see `control`.} -#' \item{`etaModes`, `etaSE`, `shrinkage`}{} +#' \item{`etaModes`, `etaSE`, `shrinkage`}{the modes of the random effects per +#' group, their conditional standard errors, and per random effect +#' 1 - SD(modes) / SD from Omega.} #' \item{`certificate`}{with method `"quadrature"` per group the #' importance-sampling check at the estimate, section Quadrature.} #' } @@ -156,16 +163,22 @@ #' these frozen nodes. The nodes of the mu-referenced fixed effects are frozen #' in `phi = X beta + eta`. Entries of `control$quadrature`: #' \describe{ -#' \item{`tol`}{allowed change of -2 log L by the next level, default 0.1, -#' split over the groups; each group takes the lowest level from the current -#' stage of the group up within `tol / G` and never a lower one than before. -#' Where the next level exceeds `maxNodes`, the change from the level below -#' is the estimate. `Inf` keeps the levels of the stages.} +#' \item{`tol`}{allowed change of -2 log L by the next refinement, default +#' 0.1, split over the groups. Each group starts from the Smolyak grid of +#' the stage and the grid of the last rebuild, and refines it +#' dimension-adaptively (Gerstner and Griebel 2003): the forward neighbors +#' of the grid are evaluated, their change of -2 log L is the error, and the +#' neighbor of largest change joins the grid until the error is within +#' `tol / G`. A grid therefore refines only the directions in which the +#' integrand departs from the Gaussian at the mode. Where the next +#' refinement exceeds `maxNodes`, the evaluated neighbors join the grid and +#' their change is the estimate. `Inf` keeps the grids of the stages.} #' \item{`levels`}{the stages, default `K + 1` with `K` the number of random #' effects of a group; level `K + s` integrates polynomials of total #' degree `2 s + 1` exactly.} #' \item{`maxLevel`, `maxNodes`}{highest level, default `K + 8`, and the -#' largest node count of a level per group, default 1000. A group whose +#' largest number of evaluated nodes per group, default 1000; the level of +#' an adaptive grid is that of the smallest Smolyak grid holding it. A group whose #' error exceeds `tol / G` at the highest level within both is capped. #' Column `capped` of `stageTrace` counts the capped groups; attribute #' `"levels"` of `stageTrace` and the `certificate` list level, level error @@ -188,7 +201,8 @@ #' -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 -#' the fixed point at which it stops, default 1e-5, and the iteration limit.} +#' the fixed point at which it stops, default 1e-5, and the iteration limit, +#' default 200.} #' } #' @section SAEM: #' Metropolis draws of the random effects by random-walk and independence @@ -250,8 +264,9 @@ #' spike-and-slab ones on more than 14 groups, by importance sampling over the #' partitions, with `valueSE`. #' @section Sparse random effects: -#' With spike-and-slab or Dirichlet-process random effects the -#' parameters and hyperparameters move in one trust region. The integral of a +#' With spike-and-slab random effects of the default `spike = 0, mean = 0` or +#' Dirichlet-process random effects, `method = "focei"` moves the +#' parameters and hyperparameters in one trust region. The integral of a #' group is exact where the data couple none of the factors and the sum over #' the subsets of the spike-and-slab random effects of the group stays within a budget of #' nodes; else it is the expectation consistent (EC) approximation, and a @@ -261,8 +276,63 @@ #' \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.} #' } #' +#' Spike-and-slab random effects with `mean` or `spike` other than 0, 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: +#' `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 +#' the random table is the posterior probability of the spike. +#' +#' `method = "saem"` draws them by the moves of section SAEM: a spike at +#' `-Inf` leaves the other slab values as they are, and a move into the slab +#' proposes from the Laplace approximation of the coordinate given the others, +#' by Newton steps on the model. The reported -2 log L is the sum over subsets +#' of `method = "focei"` at the estimate; Dirichlet-process random effects +#' beside are refused. +#' +#' `method = "quadrature"` takes the same path for every model with +#' spike-and-slab random effects, the default `spike = 0` included, after EM on +#' the Laplace integrals to their fixed point. Every subset of Laplace weight +#' above 1e-8 of the largest is integrated on a dimension-adaptive sparse grid +#' around the inner mode as in section Quadrature; a group has +#' `control$quadrature$tol / G` (default 0.1 / G), a subset of relative weight +#' \eqn{w} the share \eqn{1 / w} of it, so that light subsets stay on the first +#' grid; the other subsets keep the Laplace value. Then every parameter, the +#' Cholesky parameters of Omega and the estimated `prob` and `tau` included, +#' 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`, +#' `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 +#' \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 +#' 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 +#' slab (40), `maxSweeps` (500) and `tolSweep` (1e-5, the change of the +#' marginal means in standard deviations), `maxRelinearize` (30) and +#' `tolRelinearize` (1e-4, relative). +#' #' @seealso [msem()], [randomEffects()], [insert()]; the guide chapters #' [Nonlinear mixed-effects models](https://dmodverse.github.io/dMod2/articles/guide-nlme.html) and #' [Sparse deviations](https://dmodverse.github.io/dMod2/articles/guide-sparse-deviations.html), the @@ -286,22 +356,24 @@ em <- function(obj, random, init = NULL, fixed = NULL, .withCores(cores, .emFit(design, start, fixed, method, control, verbose)) } -## Refuses entries of `control` and of the lists `sparseFit`, `quadrature`, `saem` and `innerControl` that -## em() does not read. +## Refuses entries of `control` and of the lists `sparseFit`, `sparseFit$ec`, `quadrature`, `saem` and +## `innerControl` that em() does not read. .checkEmControl <- function(control) { known <- list(control = c("sd", "inner", "innerControl", "trustControl", "secondOrderCorrection", "derivMode", "quadrature", "saem", "sparseFit", "boundary"), - sparseFit = c("maxOuter", "trustControl"), + sparseFit = c("maxOuter", "trustControl", "maxEcm", "epsEcm", "budget", "ec"), + ec = c("nodes", "maxSweeps", "tolSweep", "maxRelinearize", "tolRelinearize"), 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")) for (k in names(known)) { - x <- if (k == "control") control else control[[k]] + x <- if (k == "control") control else if (k == "ec") control$sparseFit$ec else control[[k]] bad <- .setdiff(names(x), known[[k]]) + where <- if (k == "control") "control" else if (k == "ec") "control$sparseFit$ec" else paste0("control$", k) if (length(bad)) - stop("em: unknown entries of `", if (k == "control") "control" else paste0("control$", k), "`: ", + stop("em: unknown entries of `", where, "`: ", paste(bad, collapse = ", "), ".", call. = FALSE) } inner <- control[["inner"]] @@ -505,7 +577,8 @@ msem <- function(obj, random, init = NULL, fixed = NULL, stop("em: -2 log L of the data is not finite at the start (", format(v), "); an error model of 0 or ", "below at a data point gives that.", call. = FALSE) fit <- .emFitMethod(design, start, fixed, method, control, verbose) - fit$control <- control + # the settings of the call, without the entries em() adds itself, so that em(control = fit$control) runs + fit$control <- control[.setdiff(names(control), c("sparse", "modes", "selected"))] fit$fixed <- fixed if (!boundary) return(fit) .emBoundary(design, fit, fixed, method, control, verbose) @@ -567,6 +640,20 @@ 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)) + 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 + .spikeBases(design) + if (method == "saem") return(.emResult(design, .fitSaemSparse(design, start, fixed, control, verbose), + method, fixed)) + if (!method %in% c("focei", "quadrature")) + stop("em: spikeSlab() with `mean` or `spike` other than 0 is fitted by method = \"focei\", \"quadrature\" ", + "or \"saem\".", call. = FALSE) + qc <- if (method == "quadrature") control$quadrature %||% list() + return(.emResult(design, .fitSpikeSubsets(design, start, fixed, control, verbose, quadrature = qc), method, + fixed)) + } if (method == "saem") return(.emResult(design, .fitSaemSparse(design, start, fixed, control, verbose), method, fixed)) if (method != "focei") diff --git a/R/PEtabInterface.R b/R/PEtabInterface.R index 79b22898..0d272faa 100644 --- a/R/PEtabInterface.R +++ b/R/PEtabInterface.R @@ -201,12 +201,16 @@ readPEtabTables <- function(yamlPath) { ids <- as.character(df$conditionId) names_ <- as.character(df$conditionName) - usable <- !is.na(names_) & nzchar(trimws(names_)) & - !names_ %in% ids[!ids %in% names_] & - !duplicated(names_) & !duplicated(names_, fromLast = TRUE) + usable <- !is.na(names_) & nzchar(trimws(names_)) + # a name shared with another key falls back to the id, until the keys are unique + repeat { + key <- ifelse(usable, names_, ids) + clash <- usable & key %in% key[duplicated(key)] + if (!any(clash)) break + usable[clash] <- FALSE + } if (!any(usable)) return(c(tables, list(conditionIds = NULL))) - key <- ifelse(usable, names_, ids) map <- setNames(ids, key) df$conditionId <- key @@ -555,6 +559,8 @@ readPEtabTables <- function(yamlPath) { out } + if (anyNA(df$estimate) || !all(df$estimate %in% c(0, 1))) + stop("parameters.tsv `estimate` must be 1 or 0 for every parameter.", call. = FALSE) pouter_idx <- which(df$estimate == 1) fixed_idx <- which(df$estimate == 0) @@ -995,7 +1001,7 @@ readPEtabTables <- function(yamlPath) { # Group by (simCondId, preeq); decide merge-vs-split per group. group_key <- paste(m$simulationConditionId, m$preequilibrationConditionId, - sep = "") + sep = "\001") for (gk in unique(group_key)) { ix <- which(group_key == gk) sc <- m$simulationConditionId[ix[1L]] @@ -1007,7 +1013,7 @@ readPEtabTables <- function(yamlPath) { consistent <- all(vapply(by_obs, function(rs) { length(unique(paste(m$observableParameters[rs], m$noiseParameters[rs], - sep = ""))) <= 1L + sep = "\001"))) <= 1L }, logical(1))) if (consistent) { @@ -1026,7 +1032,7 @@ readPEtabTables <- function(yamlPath) { } # ----- split: one sub-condition per distinct (obsPar, noisePar) tuple ----- - tuple_key <- paste(peq_lab[ix], obs_lab[ix], noi_lab[ix], sep = "") + tuple_key <- paste(peq_lab[ix], obs_lab[ix], noi_lab[ix], sep = "\001") keys_here <- unique(tuple_key) suffixes <- vapply(keys_here, function(k) { jx <- ix[tuple_key == k][1L] @@ -1110,14 +1116,13 @@ readPEtabTables <- function(yamlPath) { } -# Internal: evaluate a formula string to a finite constant in baseenv(), or +# Internal: evaluate a formula string to a finite constant in .formulaEnv(), or # NA_real_ when it is not numeric, not finite or has a free symbol. .petab_eval_constant <- function(formula) { if (is.na(formula) || !nzchar(formula)) return(NA_real_) num <- suppressWarnings(as.numeric(formula)) if (!is.na(num)) return(num) - v <- tryCatch(eval(parse(text = formula), envir = baseenv()), - error = function(e) NULL) + v <- tryCatch(eval(str2lang(formula), .formulaEnv()), error = function(e) NULL) if (is.numeric(v) && length(v) == 1L && is.finite(v)) v else NA_real_ } @@ -1128,12 +1133,7 @@ readPEtabTables <- function(yamlPath) { .petab_vanishes <- function(e, zero = character(0)) { if (is.null(e)) return(FALSE) syms <- setdiff(all.vars(e), "pi") - env <- new.env(parent = baseenv()) - env$piecewise <- function(...) { - a <- list(...); n <- length(a) - for (i in seq_len(n %/% 2L)) if (isTRUE(a[[2L * i]])) return(a[[2L * i - 1L]]) - if (n %% 2L) a[[n]] else 0 - } + env <- .formulaEnv() k <- seq_along(syms) for (probe in list(exp(sin(k)), exp(cos(k)))) { vals <- setNames(as.list(probe), syms) @@ -1590,6 +1590,7 @@ readPEtabTables <- function(yamlPath) { # place: other initial expressions (an amount species is conc * volume) still # reference it as an outer symbol. init <- vapply(extra, function(nm) { + if (nm %in% names(sbml$compartmentInits)) return(sbml$compartmentInits[[nm]]) if (nm %in% names(sbml$pars)) return(format(unname(sbml$pars[nm]), digits = 17)) vol <- r$compartments[[nm]]$volume @@ -2352,55 +2353,23 @@ print.petabproblem <- function(x, ...) { ## The exporter inverts `.petab_build_trafo` on `getEquations(p)`: scale wraps ## are stripped, then each LHS is classified (see .petab_classify_lhs). -# Internal: TRUE if `e` is the symbol `op_sym`, possibly in redundant -# parentheses as in `10^(K)`. -.petab_is_bare <- function(e, op_sym) { - if (is.symbol(e) && identical(e, op_sym)) return(TRUE) - if (is.call(e) && length(e) == 2L && - identical(e[[1L]], as.symbol("(")) && - .petab_is_bare(e[[2L]], op_sym)) return(TRUE) - FALSE +# Internal: the PEtab scale of a base of .wrapBase(): "log" for e, "log10" for 10, else NA. +.petab_base_scale <- function(b) { + if (is.na(b)) return(NA_character_) + if (b == exp(1)) return("log") + if (b == 10) return("log10") + NA_character_ } # Internal: scale encoded by `e` if it is a clean wrap of `op_sym`: # `exp(op)` -> "log", `10^(op)` or `exp10(op)` -> "log10", otherwise NA. -.petab_wrap_scale <- function(e, op_sym) { - if (!is.call(e)) return(NA_character_) - head <- e[[1L]] - if (length(e) == 2L && .petab_is_bare(e[[2L]], op_sym)) { - if (identical(head, as.symbol("exp"))) return("log") - if (identical(head, as.symbol("exp10"))) return("log10") - } - if (length(e) == 3L && identical(head, as.symbol("^")) && - is.numeric(e[[2L]]) && length(e[[2L]]) == 1L && e[[2L]] == 10 && - .petab_is_bare(e[[3L]], op_sym)) return("log10") - NA_character_ -} +.petab_wrap_scale <- function(e, op_sym) .petab_base_scale(.wrapBase(e, op_sym)) # Internal: parameter scale of each outer id read off the trafo: "log" if every # occurrence is a clean `exp(.)` wrap, "log10" for `10^(.)` / `exp10(.)`, else "lin". .petab_detect_scales <- function(eqs, ids) { - seen <- setNames(vector("list", length(ids)), ids) - walk <- function(e) { - if (is.call(e)) { - for (op in ids) { - sc <- .petab_wrap_scale(e, as.symbol(op)) - if (!is.na(sc)) { seen[[op]] <<- c(seen[[op]], sc); return(invisible()) } - } - for (i in seq_along(e)[-1L]) walk(e[[i]]) - } else if (is.symbol(e) && as.character(e) %in% ids) { - seen[[as.character(e)]] <<- c(seen[[as.character(e)]], "lin") - } - invisible() - } - for (eqv in eqs) for (rhs in as.character(unclass(eqv))) { - if (!is.na(suppressWarnings(as.numeric(rhs)))) next - walk(parse(text = rhs, keep.source = FALSE)[[1L]]) - } - vapply(ids, function(op) { - u <- unique(seen[[op]]) - if (length(u) == 1L) u else "lin" - }, character(1)) + sc <- vapply(.wrapBases(eqs, ids), .petab_base_scale, "") + setNames(ifelse(is.na(sc), "lin", sc), ids) } # Internal: SBML and PEtab math know no `exp10`; rewrite it as `10^(.)`. @@ -2707,7 +2676,7 @@ print.petabproblem <- function(x, ...) { if (length(miss)) stop("exportPEtab: the event on ", var, " depends on ", paste(miss, collapse = ", "), ", which is no parameter of the problem.", call. = FALSE) - num <- tryCatch(eval(str2lang(v), baseenv()), error = function(e) NULL) + num <- tryCatch(eval(str2lang(v), .formulaEnv()), error = function(e) NULL) if (is.numeric(num) && length(num) == 1L) format(num, digits = 17) else v }, "") cdf[[var]] <- NA_character_ diff --git a/R/RcppExports.R b/R/RcppExports.R index 4c37a629..234f3e23 100644 --- a/R/RcppExports.R +++ b/R/RcppExports.R @@ -1,6 +1,38 @@ # Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 +adaptiveGridNew <- function(K, level, start, maxLevel) { + .Call(`_dMod2_adaptiveGridNew`, K, level, start, maxLevel) +} + +adaptiveGridPending <- function(grid) { + .Call(`_dMod2_adaptiveGridPending`, grid) +} + +adaptiveGridAbsorb <- function(grid, z, logValues) { + invisible(.Call(`_dMod2_adaptiveGridAbsorb`, grid, z, logValues)) +} + +adaptiveGridRefine <- function(grid, maxNodes) { + .Call(`_dMod2_adaptiveGridRefine`, grid, maxNodes) +} + +adaptiveGridAccept <- function(grid) { + invisible(.Call(`_dMod2_adaptiveGridAccept`, grid)) +} + +adaptiveGridStatus <- function(grid) { + .Call(`_dMod2_adaptiveGridStatus`, grid) +} + +adaptiveGridNodes <- function(grid) { + .Call(`_dMod2_adaptiveGridNodes`, grid) +} + +adaptiveGridIndices <- function(grid) { + .Call(`_dMod2_adaptiveGridIndices`, grid) +} + alignmentPredictors <- function(conds, theta, S, threads = 1L) { .Call(`_dMod2_alignmentPredictors`, conds, theta, S, threads) } diff --git a/R/SBMLinterface.R b/R/SBMLinterface.R index 980d443e..2983d2d2 100644 --- a/R/SBMLinterface.R +++ b/R/SBMLinterface.R @@ -25,6 +25,8 @@ #' states when an event changes a compartment volume.} #' \item{`eventsSource`}{An [eventlist] or `NULL`, the event assignments #' of the SBML file only.} +#' \item{`compartmentInits`}{Named character, the size at the start of each +#' compartment an event assigns to; such a compartment keeps the id as volume.} #' \item{`renamed`}{Named character, the new ids of SBML ids that are no #' valid R or C++ names, named by the old ids.} #' } @@ -63,14 +65,14 @@ importSbml <- function(modelpath, keep = NULL) { # libsbml writes natural log as `ln(x)`, R and C expect `log(x)`. Every # formula passes through here; the leading boundary leaves `eln` intact. - .normalise_formula <- function(s) { + .normalizeFormula <- function(s) { if (length(s) == 0L) return(s) s <- stringr::str_replace_all(s, "\\*\\*", "^") s <- stringr::str_replace_all(s, "(^|[^A-Za-z0-9_.])ln\\(", "\\1log(") s } - v <- .normalise_formula(sbml[["v"]]) + v <- .normalizeFormula(sbml[["v"]]) states <- sbml[["stateNames"]] @@ -79,13 +81,24 @@ importSbml <- function(modelpath, keep = NULL) { compartmentOf <- character(0) comp_json <- sbml[["compartments"]] spc_json <- sbml[["speciesCompartments"]] + # A compartment an event assigns to keeps the id as volume, so the kinetic laws follow the event; + # the size at the start is in `compartmentInits`. + ev_targets <- unlist(lapply(sbml[["events"]], function(ev) + vapply(ev$assignments, function(a) a$variable, ""))) + compartmentInits <- character(0) if (!is.null(comp_json) && length(comp_json) > 0L) { for (c in comp_json) { # A unit-size compartment becomes the literal "1", keeping the compartment id out of # the kinetic laws; otherwise the id is a volume symbol the trafo can set. trivial <- !is.null(c$size) && is.numeric(c$size) && isTRUE(c$size == 1) + if (c$id %in% ev_targets) { + compartmentInits[[c$id]] <- if (!is.null(c$sizeAssignment)) .normalizeFormula(c$sizeAssignment) + else if (is.numeric(c$size)) format(c$size, digits = 17) else "1" + compartments[[c$id]] <- list(volume = c$id, rule = NULL) + next + } # An InitialAssignment on the compartment is the symbolic volume. - volume <- if (!is.null(c$sizeAssignment)) .normalise_formula(c$sizeAssignment) + volume <- if (!is.null(c$sizeAssignment)) .normalizeFormula(c$sizeAssignment) else if (trivial) "1" else c$id compartments[[c$id]] <- list(volume = volume, rule = NULL) } @@ -125,7 +138,7 @@ importSbml <- function(modelpath, keep = NULL) { amountStates <- intersect(unlist(sbml[["amountSpecies"]]), states) pars <- setNames(sbml[["p"]], sbml[["parameterNames"]]) - x0 <- setNames(.normalise_formula(sbml[["x0"]]), + x0 <- setNames(.normalizeFormula(sbml[["x0"]]), sbml[["stateNames"]]) # AssignmentRules `lhs := rhs` are inlined into rates and initials up to a @@ -136,21 +149,21 @@ importSbml <- function(modelpath, keep = NULL) { # RateRule is promoted to a state below instead. par_ia <- sbml[["parameterAssignments"]] for (nm in intersect(keep, names(par_ia))) { - v0 <- tryCatch(eval(parse(text = .normalise_formula(par_ia[[nm]])), baseenv()), + v0 <- tryCatch(eval(str2lang(.normalizeFormula(par_ia[[nm]])), .formulaEnv()), error = function(e) NULL) if (is.numeric(v0) && length(v0) == 1L && nm %in% names(pars)) pars[[nm]] <- v0 } ia_lhs <- setdiff(names(par_ia), c(names(rules), names(sbml[["rateRules"]]), keep)) if (length(ia_lhs)) { - ia_rhs <- .normalise_formula(unlist(par_ia[ia_lhs], use.names = FALSE)) + ia_rhs <- .normalizeFormula(unlist(par_ia[ia_lhs], use.names = FALSE)) if (length(states)) ia_rhs <- replaceSymbols(states, paste0("(", x0[states], ")"), ia_rhs) rules <- c(rules, setNames(as.list(ia_rhs), ia_lhs)) } if (length(rules)) { rule_lhs <- names(rules) - rule_rhs <- .normalise_formula(unlist(rules, use.names = FALSE)) + rule_rhs <- .normalizeFormula(unlist(rules, use.names = FALSE)) # Parenthesized so substitution into a sub-expression keeps precedence. rule_rhs <- paste0("(", rule_rhs, ")") max_iter <- length(rule_lhs) + 1L @@ -169,7 +182,7 @@ importSbml <- function(modelpath, keep = NULL) { rate_rules <- sbml[["rateRules"]] if (length(rate_rules)) { rr_lhs <- names(rate_rules) - rr_rhs <- .normalise_formula(unlist(rate_rules, use.names = FALSE)) + rr_rhs <- .normalizeFormula(unlist(rate_rules, use.names = FALSE)) # Inline assignment-rule LHSs into the rate-rule RHSs too, so a RateRule # that references a rule-defined symbol doesn't keep it as a free var. if (length(rules)) { @@ -187,7 +200,7 @@ importSbml <- function(modelpath, keep = NULL) { par_ia <- sbml[["parameterAssignments"]] init <- vapply(promote, function(nm) { ia <- par_ia[[nm]] - if (!is.null(ia) && nzchar(ia)) return(.normalise_formula(ia)) + if (!is.null(ia) && nzchar(ia)) return(.normalizeFormula(ia)) v0 <- suppressWarnings(as.numeric(pars[nm])) if (length(v0) != 1L || is.na(v0)) "0" else format(v0, digits = 17) }, character(1)) @@ -238,7 +251,8 @@ importSbml <- function(modelpath, keep = NULL) { # ---- events ---- # One "replace" row per eventAssignment. A `time >= T` trigger sets `time`, - # any other trigger becomes the root `lhs - (rhs)`. + # any other trigger becomes the root `lhs - (rhs)`, which cppDE fires at crossings in both + # directions; a pair `lhs >= rhs`, `lhs <= rhs` with the same assignments is one root event. events_json <- sbml[["events"]] events_df <- NULL events_src <- NULL @@ -248,6 +262,7 @@ importSbml <- function(modelpath, keep = NULL) { # compartment rescales are regenerated on the next import, so exporting # them would apply them twice. rows_src <- list() + down <- down_src <- logical(0) cmp_pat <- "^\\s*(.+?)\\s*(>=|>|<=|<|==|!=)\\s*(.+?)\\s*$" for (ev in events_json) { tt <- ev[["triggerTime"]] @@ -257,8 +272,10 @@ importSbml <- function(modelpath, keep = NULL) { else if (length(tt) && nzchar(tt)) as.character(tt) else NA root_val <- NA_character_ + falling <- FALSE if (is.na(time_val) && length(tf) && nzchar(tf)) { m <- regmatches(tf, regexec(cmp_pat, tf))[[1L]] + falling <- length(m) == 4L && m[3L] %in% c("<=", "<") root_val <- if (length(m) == 4L) paste0("(", m[2L], ") - (", m[4L], ")") else @@ -268,7 +285,7 @@ importSbml <- function(modelpath, keep = NULL) { # An event assignment to a compartment changes the compartment size while species # amounts stay put, so concentrations scale inversely. Emit the # rescale first, while the old volume is still in effect. - new_val <- .normalise_formula(a$formula) + new_val <- .normalizeFormula(a$formula) if (!is.null(compartmentOf) && a$variable %in% names(compartments)) { old_vol <- compartments[[a$variable]]$volume inside <- setdiff(names(compartmentOf)[compartmentOf == a$variable], @@ -281,6 +298,7 @@ importSbml <- function(modelpath, keep = NULL) { root = root_val, method = "replace", stringsAsFactors = FALSE) + down <- c(down, falling) } src_row <- data.frame( var = a$variable, @@ -292,11 +310,18 @@ importSbml <- function(modelpath, keep = NULL) { ) rows[[length(rows) + 1L]] <- src_row rows_src[[length(rows_src) + 1L]] <- src_row + down <- c(down, falling) + down_src <- c(down_src, falling) } } + # a falling row whose rising twin exists is the second half of one root event + paired <- function(df, falling) { + key <- do.call(paste, c(df[c("var", "value", "root")], sep = "\r")) + df[!(falling & key %in% key[!falling]), , drop = FALSE] + } if (length(rows)) { - events_df <- as.eventlist(do.call(rbind, rows)) - events_src <- as.eventlist(do.call(rbind, rows_src)) + events_df <- as.eventlist(paired(do.call(rbind, rows), down)) + events_src <- as.eventlist(paired(do.call(rbind, rows_src), down_src)) } } @@ -304,6 +329,7 @@ importSbml <- function(modelpath, keep = NULL) { observables = observables, assignmentRules = rules, events = events_df, eventsSource = events_src, + compartmentInits = compartmentInits, renamed = attr(sbml, "renamed") %||% character(0)) out } @@ -324,6 +350,40 @@ importSbml <- function(modelpath, keep = NULL) { "volatile", "wchar_t", "while", "xor", "std") +# Formulas of SBML and PEtab files are evaluated here: an environment on emptyenv() with the +# arithmetic, the comparisons and the functions of the expression language of cppDE, nothing else. +.formulaEnv <- local({ + env <- NULL + function() { + if (!is.null(env)) return(env) + e <- new.env(parent = emptyenv()) + base <- c("(", "+", "-", "*", "/", "^", "<", "<=", ">", ">=", "==", "!=", "&&", "||", "!", + "&", "|", "exp", "log", "log2", "log10", "sqrt", "sin", "cos", "tan", "asin", "acos", + "atan", "atan2", "sinh", "cosh", "tanh", "asinh", "acosh", "atanh", "abs", "min", "max", + "floor", "ceiling", "round", "trunc", "sign", "ifelse", "pi") + for (f in base) assign(f, get(f, envir = baseenv()), envir = e) + fns <- list( + ln = log, exp2 = function(x) 2^x, exp10 = function(x) 10^x, cbrt = function(x) sign(x) * abs(x)^(1/3), + pow = function(x, y) x^y, root = function(x, n) x^(1/n), ceil = ceiling, + cot = function(x) 1/tan(x), sec = function(x) 1/cos(x), csc = function(x) 1/sin(x), + acot = function(x) atan(1/x), asec = function(x) acos(1/x), acsc = function(x) asin(1/x), + coth = function(x) 1/tanh(x), sech = function(x) 1/cosh(x), csch = function(x) 1/sinh(x), + acoth = function(x) atanh(1/x), asech = function(x) acosh(1/x), acsch = function(x) asinh(1/x), + erf = function(x) 2 * stats::pnorm(x * sqrt(2)) - 1, erfc = function(x) 2 * stats::pnorm(-x * sqrt(2)), + Heaviside = function(x) as.numeric(x > 0), + piecewise = function(...) { + a <- list(...); n <- length(a) + for (i in seq_len(n %/% 2L)) if (isTRUE(as.logical(a[[2L * i]]))) return(a[[2L * i - 1L]]) + if (n %% 2L) a[[n]] else 0 + }) + list2env(fns, envir = e) + lockEnvironment(e, bindings = TRUE) + env <<- e + e + } +}) + + # Reserved in R, so a bare identifier of this name cannot be parsed. .R_RESERVED <- c("if", "else", "repeat", "while", "function", "for", "next", "break", "TRUE", "FALSE", "NULL", "Inf", "NaN", "NA", @@ -434,8 +494,10 @@ importSbml <- function(modelpath, keep = NULL) { #' @param filepath Path of the SBML file to write. #' @param modelID SBML model identifier. Defaults to `"dMod_export"`. #' @param events Object of class [eventlist] to emit as ``, or -#' `NULL`. Rows sharing a trigger become one ``. A compartment an event assigns to is written -#' as non-constant. Default `NULL`. +#' `NULL`. Rows sharing a trigger become one ``. A root event becomes two events with +#' the triggers `root >= 0` and `root <= 0`, initially true, so that the SBML model fires at +#' crossings in both directions and not at the start, as cppDE does. A compartment an event +#' assigns to is written as non-constant. Default `NULL`. #' @return `filepath`, invisibly. #' @seealso [importSbml()], [exportPEtab()] #' @inherit importSbml examples @@ -450,7 +512,8 @@ exportSbml <- function(eqnlist, parameters = NULL, inits = NULL, filepath, # parameter-only SBML document. if (length(eqnlist$states) > 0L && (is.null(eqnlist$compartments) || is.null(eqnlist$compartmentOf))) - stop("`eqnlist` must have populated compartments/compartmentOf. Use the updated constructor.") + stop("exportSbml: `eqnlist` has no compartments; assign them with assignCompartment().", + call. = FALSE) # Compartments: numeric size when the volume expression parses as numeric; # otherwise 1.0 and rely on the homonymous parameter for the symbolic value. @@ -509,7 +572,7 @@ exportSbml <- function(eqnlist, parameters = NULL, inits = NULL, filepath, } # Each row of the stoichiometric matrix becomes one reaction. The kinetic - # law is `rate * V_ref`, the α-bridge identity in the export direction. + # law is `rate * V_ref`, the inverse of the division by the volume on import. smatrix <- eqnlist$smatrix vref_vol <- .refVolumes(.refCompartments(smatrix, eqnlist$compartmentOf[eqnlist$states], eqnlist$reactionCompartment, eqnlist$description), @@ -548,20 +611,24 @@ exportSbml <- function(eqnlist, parameters = NULL, inits = NULL, filepath, event_list <- list() if (!is.null(events) && nrow(events)) { ev <- as.data.frame(events, stringsAsFactors = FALSE) - trig <- ifelse(is.na(ev$time), as.character(ev$root), - paste("time >=", ev$time)) + # an SBML trigger fires when it turns true: a root that cppDE fires on crossings in both + # directions becomes two triggers, true beforehand so that neither fires at the start + isRoot <- is.na(ev$time) + key <- ifelse(isRoot, as.character(ev$root), paste("time >=", ev$time)) # SBML assigns a value: an added or multiplied value becomes the formula on the old one formula <- function(var, value, method) switch(if (is.null(method) || is.na(method)) "replace" else as.character(method), replace = as.character(value), add = sprintf("%s + (%s)", var, value), multiply = sprintf("%s * (%s)", var, value), stop("exportSbml: event method ", method, " is not replace, add or multiply.", call. = FALSE)) - for (t in unique(trig)) { - rows <- ev[trig == t, , drop = FALSE] - event_list[[length(event_list) + 1L]] <- list( - trigger = t, - assignments = lapply(seq_len(nrow(rows)), function(i) - list(variable = rows$var[i], formula = formula(rows$var[i], rows$value[i], rows$method[i])))) + for (k in unique(key)) { + rows <- ev[key == k, , drop = FALSE] + assignments <- lapply(seq_len(nrow(rows)), function(i) + list(variable = rows$var[i], formula = formula(rows$var[i], rows$value[i], rows$method[i]))) + triggers <- if (isRoot[match(k, key)]) paste0("(", k, c(") >= 0", ") <= 0")) else k + for (t in triggers) + event_list[[length(event_list) + 1L]] <- list(trigger = t, initialValue = !identical(t, k), + assignments = assignments) } } diff --git a/R/accessors.R b/R/accessors.R index cd0e70fc..99054743 100644 --- a/R/accessors.R +++ b/R/accessors.R @@ -483,6 +483,7 @@ getDerivs2.objlist <- function(x, ...) { #' Default `NULL`. Used by the methods for `fn` and `prdlist`. #' @return Character vector of parameter names. For an `odemodel`, the states #' and parameters; for a `prdlist`, a list with one entry per condition. +#' @example inst/examples/accessors.R #' @export getParameters <- function(x, ..., conditions = NULL) { if (...length() > 0L) { @@ -545,7 +546,7 @@ getParameters.prdframe <- function(x, ..., conditions = NULL) { #' @rdname getParameters getParameters.prdlist <- function(x, ..., conditions = NULL) { - select <- 1:length(x) + select <- seq_along(x) if (!is.null(conditions)) select <- intersect(names(x), conditions) lapply(x[select], function(myx) getParameters(myx)) @@ -583,6 +584,7 @@ getParameters.eqnvec <- function(x, ..., conditions = NULL) { #' @param ... not used. #' @return Character vector of condition names, `NULL` for a function defined #' for every condition. +#' @example inst/examples/accessors.R #' @export getConditions <- function(x, ...) { UseMethod("getConditions", x) @@ -620,6 +622,7 @@ getConditions.fn <- function(x, ...) { #' @return Character vector of model names. The setter returns `x`. #' @seealso [compile()], [loadDLL()] #' +#' @example inst/examples/accessors.R #' @export modelname <- function(x = NULL, ..., conditions = NULL) { if (...length() > 0L) { @@ -653,7 +656,7 @@ modelname.objfn <- function(x = NULL, ..., conditions = NULL) { modelname.fn <- function(x = NULL, ..., conditions = NULL) { mappings <- attr(x, "mappings") - select <- 1:length(mappings) + select <- seq_along(mappings) if (!is.null(conditions)) select <- intersect(names(mappings), conditions) modelnames <- Reduce("union", lapply(mappings[select], function(m) attr(m, "modelname")) @@ -739,6 +742,7 @@ modelname.fn <- function(x = NULL, ..., conditions = NULL) { #' @return A list of `eqnvec` objects, one per condition. If `conditions` has #' length one, the `eqnvec` itself. For an `odemodel`, the `eqnvec` of the #' model. +#' @example inst/examples/accessors.R #' @export getEquations <- function(x, conditions = NULL) { @@ -781,15 +785,3 @@ getEquations.fn <- function(x, conditions = NULL) { } -#' Extract the Observables of an Object -#' -#' Generic without methods in dMod2; other packages can provide them. -#' -#' @param x object from which the observables are extracted. -#' @param ... not used. -#' @return The observables, as a character vector. -#' @export -getObservables <- function(x, ...) { - UseMethod("getObservables", x) -} - diff --git a/R/alignment.R b/R/alignment.R index 973c2eca..d64d7c54 100644 --- a/R/alignment.R +++ b/R/alignment.R @@ -1072,7 +1072,7 @@ print.alignmentmodel <- function(x, ...) { symbol = rows[[i]]$symbol, origin = origin[i], term = rows[[i]]$term, column = rows[[i]]$column, group = rows[[i]]$group, id = rows[[i]]$id, dist = rows[[i]]$dist, prob = rows[[i]]$prob, concentration = rows[[i]]$concentration, - tau = rows[[i]]$tau, + tau = rows[[i]]$tau, mean = rows[[i]]$mean %||% 0, spike = rows[[i]]$spike %||% 0, 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) { @@ -1158,7 +1158,8 @@ print.alignmentmodel <- function(x, ...) { #' `remlRounds` (the rounds of the restricted likelihood, 0 without), #' `seSource` (`"Hessian"`, or `"Gauss-Newton"` where the reported Hessian #' of a fit with random terms is not positive definite: then the -#' Gauss-Newton Schur complement of the expected information over the random effects), +#' Gauss-Newton Schur complement of the expected information over the random effects; +#' `"none"` where that fails too, without standard errors), #' `fit`, `objfn`, `omega`, `random` and `randomEffects` with random terms, #' and the `model`. `scaled` also has `scaled`, the value of the biological symbol at which the prediction meets #' the reading with the other symbols at the fit (`NaN` where none does), and @@ -1282,7 +1283,7 @@ align <- function(model, fits = 10L, cores = 1L, method = c("focei", "quadrature gn <- tryCatch(.alignmentGaussNewton(m, obj, re, best), error = function(e) NULL) H <- gn$hessian lowrank <- gn$lowrank - seSource <- "Gauss-Newton" + seSource <- if (is.null(H)) "none" else "Gauss-Newton" } # with REML the standard errors of the mean parameters at the estimated error parameters # (Lindstrom and Bates 1990): the inverse of their block of the information diff --git a/R/classes.R b/R/classes.R index cc3d80f4..b356204d 100644 --- a/R/classes.R +++ b/R/classes.R @@ -96,7 +96,7 @@ match.fnargs <- function(arglist, choices) { # NULL (one unnamed slot if none are), else those named `own`, and nothing when # the request names other conditions only. .resolveConditions <- function(conditions, own) { - overlap <- test_conditions(conditions, own) + overlap <- .testConditions(conditions, own) # union() would drop repeats, and a request may name the same condition more # than once (quadrature nodes, parameter-frame rows). if (is.null(overlap)) @@ -784,7 +784,8 @@ match.fnargs <- function(arglist, choices) { c1 <- attr(x1, "conditions"); c2 <- attr(x2, "conditions") overlap <- intersect(c1, c2) if (length(overlap) > 0) { - warning(paste("Condition", overlap, "existed and has been overwritten.")) + warning("Condition ", paste(overlap, collapse = ", "), " existed and has been overwritten.", + call. = FALSE) m1 <- m1[!c1 %in% overlap] c1 <- c1[!c1 %in% overlap] } @@ -885,13 +886,6 @@ match.fnargs <- function(arglist, choices) { } -.unionMappingAttr <- function(mappings) { - vals <- lapply(mappings, attr, "forcings") - vals <- vals[!vapply(vals, is.null, logical(1))] - if (!length(vals)) NULL else vals[[1]] -} - - ## General concatenation of functions ------------------------------------------ # The summands of an objective: the flat list `+` recorded, or the objective @@ -934,87 +928,79 @@ match.fnargs <- function(arglist, choices) { modelname.x2 <- attr(e2, "modelname") modelname12 <- union(modelname.x1, modelname.x2) - - # objfn + objfn - if (inherits(e1, "objfn") & inherits(e2, "objfn")) { - - outfn <- function(..., fixed = NULL, deriv = TRUE, deriv2 = FALSE, hessian = NULL, - conditions = conditions12, env = NULL, - cores = getOption("dMod2.cores", 1L), - sweep = "forward") { - - arglist <- list(...) - arglist <- arglist[match.fnargs(arglist, c("pars"))] - pars <- arglist[[1]] - # NULL asks for all conditions, as in normL2() - if (is.null(conditions)) conditions <- conditions12 - - # A term understands `sweep` only if it names it as a formal; one that - # does not runs forward, and under an exact request still returns the - # Hessian. Every wrapper in this package declares `sweep`. - .call <- function(f, conds, e) { - if (identical(sweep, "reverse") && "sweep" %in% names(formals(f))) - f(pars = pars, fixed = fixed, deriv = deriv, deriv2 = deriv2, - hessian = hessian, conditions = conds, env = e, cores = cores, - sweep = sweep) - else - f(pars = pars, fixed = fixed, deriv = deriv, deriv2 = deriv2, - hessian = if (identical(sweep, "reverse")) isTRUE(deriv2) - else hessian, - conditions = conds, env = e, cores = cores) - } - # a term without conditions once with the caller's env, any other on the term share of `conditions`, - # skipped where that is empty and it holds no unconditioned term; the second reuses the first env - .term <- function(f, own, e) { - if (is.null(own)) return(.call(f, NULL, env)) - mine <- .intersect(conditions, own) - if (length(mine) || isTRUE(attr(f, "unconditioned"))) .call(f, mine, e) - } - v1 <- .term(e1, conditions.x1, env) - v2 <- .term(e2, conditions.x2, attr(v1, "env") %||% env) - - # .sumobjlist adds an absent Hessian as zero, which is wrong when only - # one term has one and both values are finite. - .h <- function(v) !is.null(v) && !is.null(v$hessian) - .finite <- function(v) all(is.finite(v$value)) - if (!is.null(v1) && !is.null(v2) && xor(.h(v1), .h(v2)) && .finite(v1) && .finite(v2)) - stop("a summed objective got a Hessian from ", - if (.h(v1)) "the first" else "the second", " term and none from ", - if (.h(v1)) "the second" else "the first", - ". Adding them would drop that term's curvature silently.", - call. = FALSE) - - out <- v1 + v2 - attr(out, "env") <- attr(v1, "env") %||% attr(v2, "env") - return(out) + outfn <- function(..., fixed = NULL, deriv = TRUE, deriv2 = FALSE, hessian = NULL, + conditions = conditions12, env = NULL, + cores = getOption("dMod2.cores", 1L), + sweep = "forward") { + + arglist <- list(...) + arglist <- arglist[match.fnargs(arglist, c("pars"))] + pars <- arglist[[1]] + # NULL asks for all conditions, as in normL2() + if (is.null(conditions)) conditions <- conditions12 + + # A term understands `sweep` only if it names it as a formal; one that + # does not runs forward, and under an exact request still returns the + # Hessian. Every wrapper in this package declares `sweep`. + .call <- function(f, conds, e) { + if (identical(sweep, "reverse") && "sweep" %in% names(formals(f))) + f(pars = pars, fixed = fixed, deriv = deriv, deriv2 = deriv2, + hessian = hessian, conditions = conds, env = e, cores = cores, + sweep = sweep) + else + f(pars = pars, fixed = fixed, deriv = deriv, deriv2 = deriv2, + hessian = if (identical(sweep, "reverse")) isTRUE(deriv2) + else hessian, + conditions = conds, env = e, cores = cores) } - - class(outfn) <- c("objfn", "fn") - attr(outfn, "conditions") <- conditions12 - attr(outfn, "parameters") <- parameters12 - attr(outfn, "modelname") <- modelname12 - attr(outfn, "unconditioned") <- is.null(conditions.x1) || is.null(conditions.x2) || - isTRUE(attr(e1, "unconditioned")) || isTRUE(attr(e2, "unconditioned")) - attr(outfn, "compileInfo") <- .mergeCompileInfo(attr(e1, "compileInfo"), - attr(e2, "compileInfo")) - # Reconstruction handles, coalesced from either operand. - for (.a in c("prdfn", "data", "errfn", "timesD")) { - .v <- attr(e1, .a, exact = TRUE) - if (is.null(.v)) .v <- attr(e2, .a, exact = TRUE) - if (!is.null(.v)) attr(outfn, .a) <- .v + # a term without conditions once with the caller's env, any other on the term share of `conditions`, + # skipped where that is empty and it holds no unconditioned term; the second reuses the first env + .term <- function(f, own, e) { + if (is.null(own)) return(.call(f, NULL, env)) + mine <- .intersect(conditions, own) + if (length(mine) || isTRUE(attr(f, "unconditioned"))) .call(f, mine, e) } - # l2spec is CONCATENATED: every L2 term keeps separate data, prediction and - # error model, which is what reml() needs from a split objective. - attr(outfn, "l2spec") <- c(attr(e1, "l2spec", exact = TRUE), - attr(e2, "l2spec", exact = TRUE)) - # The summands themselves, flat however the sum was nested, so a caller - # can take a data term apart from the priors beside it. - attr(outfn, "terms") <- c(.objTerms(e1), .objTerms(e2)) - return(outfn) - + v1 <- .term(e1, conditions.x1, env) + v2 <- .term(e2, conditions.x2, attr(v1, "env") %||% env) + + # .sumobjlist adds an absent Hessian as zero, which is wrong when only + # one term has one and both values are finite. + .h <- function(v) !is.null(v) && !is.null(v$hessian) + .finite <- function(v) all(is.finite(v$value)) + if (!is.null(v1) && !is.null(v2) && xor(.h(v1), .h(v2)) && .finite(v1) && .finite(v2)) + stop("a summed objective got a Hessian from ", + if (.h(v1)) "the first" else "the second", " term and none from ", + if (.h(v1)) "the second" else "the first", + ". Adding them would drop that term's curvature silently.", + call. = FALSE) + + out <- v1 + v2 + attr(out, "env") <- attr(v1, "env") %||% attr(v2, "env") + return(out) } - + class(outfn) <- c("objfn", "fn") + attr(outfn, "conditions") <- conditions12 + attr(outfn, "parameters") <- parameters12 + attr(outfn, "modelname") <- modelname12 + attr(outfn, "unconditioned") <- is.null(conditions.x1) || is.null(conditions.x2) || + isTRUE(attr(e1, "unconditioned")) || isTRUE(attr(e2, "unconditioned")) + attr(outfn, "compileInfo") <- .mergeCompileInfo(attr(e1, "compileInfo"), + attr(e2, "compileInfo")) + # Reconstruction handles, coalesced from either operand. + for (.a in c("prdfn", "data", "errfn", "timesD")) { + .v <- attr(e1, .a, exact = TRUE) + if (is.null(.v)) .v <- attr(e2, .a, exact = TRUE) + if (!is.null(.v)) attr(outfn, .a) <- .v + } + # l2spec is CONCATENATED: every L2 term keeps separate data, prediction and + # error model, which is what reml() needs from a split objective. + attr(outfn, "l2spec") <- c(attr(e1, "l2spec", exact = TRUE), + attr(e2, "l2spec", exact = TRUE)) + # The summands themselves, flat however the sum was nested, so a caller + # can take a data term apart from the priors beside it. + attr(outfn, "terms") <- c(.objTerms(e1), .objTerms(e2)) + outfn } @@ -1139,7 +1125,6 @@ match.fnargs <- function(arglist, choices) { attr(outfn, "compileInfo") <- .mergeCompileInfo(attr(e1, "compileInfo"), attr(e2, "compileInfo")) attr(outfn, "conditions") <- own$conditions - attr(outfn, "forcings") <- .unionMappingAttr(own$mappings) # Keep "composed" only when a composed operand went in, so summary() keeps # the detail branch for a sum of leaves and drops it for a sum of chains. @@ -1169,7 +1154,8 @@ match.fnargs <- function(arglist, choices) { overlap <- names(e2)[names(e2) %in% names(e1)] if (length(overlap) > 0) { - warning(paste("Condition", overlap, "existed and has been overwritten.")) + warning("Condition ", paste(overlap, collapse = ", "), " existed and has been overwritten.", + call. = FALSE) e1 <- e1[!names(e1) %in% names(e2)] } @@ -1193,7 +1179,7 @@ match.fnargs <- function(arglist, choices) { return(out) } -out_conditions <- function(c1, c2) { +.outConditions <- function(c1, c2) { if (!is.null(c1)) return(c1) if (!is.null(c2)) return(c2) @@ -1201,7 +1187,7 @@ out_conditions <- function(c1, c2) { } -test_conditions <- function(c1, c2) { +.testConditions <- function(c1, c2) { if (is.null(c1)) return(NULL) if (is.null(c2)) return(NULL) .intersectU(c1, c2) @@ -1262,6 +1248,11 @@ test_conditions <- function(c1, c2) { !identical(conditions.p1, conditions.p2)) stop("Invalid composition of functions: the left-hand function is defined for condition ", conditions.p1, ", the right-hand one for condition ", conditions.p2, ".", call. = FALSE) + # two condition sets without a common condition -> every slot would be empty + if (!length(.intersect(conditions.p1, conditions.p2))) + stop("Invalid composition of functions: the left-hand function is defined for conditions ", + paste(conditions.p1, collapse = ", "), ", the right-hand one for ", + paste(conditions.p2, collapse = ", "), ", which share none.", call. = FALSE) } if (inherits(e1, "idfn")) return(e2) @@ -1274,7 +1265,7 @@ test_conditions <- function(c1, c2) { paste(class(e1), collapse = "/"), " * ", paste(class(e2), collapse = "/"), ".", call. = FALSE) - conditions.out <- out_conditions(conditions.p1, conditions.p2) + conditions.out <- .outConditions(conditions.p1, conditions.p2) st <- list2env(list(op = "*", kind = spec$out, p1 = e1, p2 = e2, p1kind = .fnKind(e1), p2kind = .fnKind(e2), @@ -1295,16 +1286,18 @@ test_conditions <- function(c1, c2) { .v <- attr(e1, .a, exact = TRUE) if (!is.null(.v)) attr(outfn, .a) <- .v } - # The reconstructed prediction has to live in the outer coordinates. + # The reconstructed prediction has to live in the outer coordinates. When + # it does not compose with e2 the handles are dropped: one in the inner + # coordinates would reconstruct another model. + .outer <- function(prd) tryCatch(prd * e2, error = function(e) NULL) .prd <- attr(e1, "prdfn", exact = TRUE) - if (!is.null(.prd)) - attr(outfn, "prdfn") <- tryCatch(.prd * e2, error = function(e) .prd) - .l2 <- attr(e1, "l2spec", exact = TRUE) - if (!is.null(.l2)) - attr(outfn, "l2spec") <- lapply(.l2, function(tm) { - tm$prdfn <- tryCatch(tm$prdfn * e2, error = function(e) tm$prdfn) - tm - }) + if (!is.null(.prd)) attr(outfn, "prdfn") <- .outer(.prd) + .l2 <- lapply(attr(e1, "l2spec", exact = TRUE), function(tm) { + tm$prdfn <- .outer(tm$prdfn) + tm + }) + if (length(.l2) && !any(vapply(.l2, function(tm) is.null(tm$prdfn), TRUE))) + attr(outfn, "l2spec") <- .l2 # The objective inside and the transformation, for controls(). Not # `terms`: the composition reads other parameters than the objective it # wraps. diff --git a/R/compile.R b/R/compile.R index 76c73d5b..cf547ccc 100644 --- a/R/compile.R +++ b/R/compile.R @@ -348,12 +348,26 @@ compile <- function(..., output = NULL, args = NULL, cores = detectFreeCores(), for (i in seq_along(info)) info[[i]]$srcfile <- normalizePath(info[[i]]$srcfile, "/") - ## Deduplicate by srcfile, keeping the first non-empty flags. + ## Deduplicate by srcfile, the first entry wins: compileInfo flags come + ## before those of the fallback discovery. ord <- order(vapply(info, function(e) e$srcfile, character(1))) info <- info[ord] keep <- !duplicated(vapply(info, function(e) e$srcfile, character(1))) info <- info[keep] + ## A loaded shared object is never unloaded: that nulls the native symbols the session resolved + ## from it. The generators give a new model a name no loaded object has, so a source whose own + ## shared object is loaded is the model already built and is skipped. + if (is.null(output)) { + root <- function(e) sub("\\.[^.]+$", "", basename(e$srcfile)) + built <- vapply(info, root, character(1)) %in% names(getLoadedDLLs()) + if (any(built)) + message("compile: already loaded, not rebuilt: ", + paste(vapply(info[built], root, character(1)), collapse = ", ")) + info <- info[!built] + if (!length(info)) return(invisible(TRUE)) + } + files <- vapply(info, function(e) e$srcfile, character(1)) ## Where the combined shared object goes. A bare name lands next to the @@ -459,12 +473,6 @@ compile <- function(..., output = NULL, args = NULL, cores = detectFreeCores(), .reportToolchain("C", cc_bin, base, "\\.c$") .reportToolchain("C++", cxx_bin, cxx_base, "\\.cpp$") - ## unload stale DLLs - loaded <- getLoadedDLLs() - for (i in seq_along(roots)) - if (roots[i] %in% names(loaded)) try(dyn.unload(loaded[[roots[i]]][["path"]]), silent = TRUE) - if (!is.null(outfile)) try(dyn.unload(outfile), silent = TRUE) - # A backend's compileArgs can repeat a flag the base already sets (-fopenmp). # Compile flags only: repeated -l on a link line can be load-bearing. .mergeFlags <- function(...) { @@ -579,7 +587,7 @@ compile <- function(..., output = NULL, args = NULL, cores = detectFreeCores(), else if (cores > 1 && length(info) > 1L) compile_on_cluster(info) else for (e in info) compile_one(e) - for (r in roots_full) .reloadDLL(paste0(r, so)) + for (r in roots_full) .loadNewDLL(paste0(r, so)) .clearSymbols() } else { ## Combined output: each source compiled to a .o, then one R CMD SHLIB link @@ -631,7 +639,7 @@ compile <- function(..., output = NULL, args = NULL, cores = detectFreeCores(), all_compile <- unique(unlist(lapply(info, function(e) strsplit(trimws(e$compileArgs %||% ""), "\\s+")[[1]]))) all_compile <- all_compile[nzchar(all_compile)] - output <- basename(sub(paste0("\\", so, "$"), "", output)) + output <- out_base ## Past the argument limit the objects go into a static archive in chunks, ## and SHLIB gets one anchor source plus the archive. The anchor is C++ when @@ -711,7 +719,6 @@ compile <- function(..., output = NULL, args = NULL, cores = detectFreeCores(), } out <- outfile - try(dyn.unload(out), silent = TRUE) if (file.exists(out)) unlink(out) ## Link through system2() pipes, not a `2>&1` token, which on Windows ## becomes the make override PKG_LIBS=2>&1. The compiler banner is dropped, @@ -732,7 +739,7 @@ compile <- function(..., output = NULL, args = NULL, cores = detectFreeCores(), if (!file.exists(out)) stop("R CMD SHLIB returned exit 0 but did not produce ", out, ":\n", paste(out_lines, collapse = "\n")) - .reloadDLL(out) + .loadNewDLL(out) .clearSymbols() ## cOde loads a deSolve leaf's entry points from the shared object the ## `modelname` names, which must now be the combined one. @@ -758,13 +765,12 @@ compile <- function(..., output = NULL, args = NULL, cores = detectFreeCores(), #' @return Character vector with the names of the loaded shared objects whose #' path lies in the working directory. #' @seealso [loadDLL()] +#' @example inst/examples/getLocalDLLs.R #' @export getLocalDLLs <- function() { - - all.dlls <- getLoadedDLLs() - is.local <- sapply(all.dlls, function(x) grepl(getwd(), unclass(x)$path, fixed = TRUE)) - names(is.local)[is.local] - + wd <- paste0(sub("/$", "", normalizePath(getwd(), winslash = "/")), "/") + paths <- .loadedDLLPaths() + names(paths)[startsWith(paths, wd)] } @@ -790,12 +796,10 @@ getLocalDLLs <- function() { } -## Loading an already loaded shared object is a no-op in R, so a rebuilt file is -## unloaded first. Entry points resolve by name, so this is safe for objects in use. -.reloadDLL <- function(path) { +## Loads a shared object unless the session holds it already; compile() never rebuilds a loaded one. +.loadNewDLL <- function(path) { p <- normalizePath(path, winslash = "/", mustWork = FALSE) - if (p %in% .loadedDLLPaths()) try(dyn.unload(p), silent = TRUE) - dyn.load(p) + if (!p %in% .loadedDLLPaths()) dyn.load(p) } diff --git a/R/dataClass.R b/R/dataClass.R index 18de8d17..e08c5f1f 100644 --- a/R/dataClass.R +++ b/R/dataClass.R @@ -192,7 +192,7 @@ plotData.datalist <- function(data, ..., scales = "free", legends <- list(if (all(frame$bloq == "no")) guides(shape = "none"), if (nlevels(frame$condition) == 1L) guides(color = "none")) - p <- ggplot(frame, aes(x = time, y = value, ymin = value - sigma, ymax = value + sigma, + p <- .ggplotDMod2(frame, aes(x = time, y = value, ymin = value - sigma, ymax = value + sigma, pch = bloq)) + layout + geom_point() + @@ -218,6 +218,7 @@ plot.datalist <- function(x, ..., scales = "free", #' @param x any R object #' @return a data frame #' @rdname as.data.frame.dMod +#' @example inst/examples/prdframe.R #' @export as.data.frame.datalist <- function(x, ...) { @@ -249,6 +250,7 @@ as.data.frame.datalist <- function(x, ...) { #' datalist, or the unique combinations of the non-standard columns of a data #' frame. #' @seealso [as.datalist()] +#' @example inst/examples/datalist.R #' @export covariates <- function(x, ...) { UseMethod("covariates", x) diff --git a/R/emResults.R b/R/emResults.R index 12f2e002..22a5e767 100644 --- a/R/emResults.R +++ b/R/emResults.R @@ -217,9 +217,11 @@ coef.em <- function(object, ...) object$argument #' @return The inverse of half the Hessian of the marginal -2 log L. A fit with #' spike-and-slab random effects has no Hessian; there it is the #' inverse of the empirical information `information` of the group scores, -#' see [em()], which needs more groups than parameters. A fit -#' with Dirichlet-process random effects, whose groups are not independent, -#' has neither: an error, as where the scores do not span every direction. +#' see [em()], which needs more groups than parameters. Fits with +#' Dirichlet-process random effects, whose groups are not independent, and +#' fits by the sum over subsets (`spikeSlab()` with `mean` or `spike` other +#' than 0, or `method = "quadrature"` with spike-and-slab random effects) +#' have neither: an error, as where the scores do not span every direction. #' @example inst/examples/emEstimates.R #' @export vcov.em <- function(object, ...) { @@ -230,8 +232,9 @@ vcov.em <- function(object, ...) { length(object$argument), " parameters, or the Hessian of the terms without random effects is ", "indefinite; confint(method = \"profile\") gives intervals.", call. = FALSE) if (is.null(H)) - stop("vcov: the fit has no Hessian of the marginal -2 log L and, with Dirichlet-process random effects, ", - "no empirical information; confint(method = \"profile\") gives intervals.", call. = FALSE) + stop("vcov: the fit has neither a Hessian of the marginal -2 log L nor an empirical information ", + "(Dirichlet-process random effects, or the sum over subsets of spike-and-slab random effects); ", + "confint(method = \"profile\") gives intervals.", call. = FALSE) if (is.null(object$hessian)) object$lowrank <- NULL object$hessian <- H vcov.trustfit(object, ...) @@ -352,6 +355,8 @@ logLik.em <- function(object, method = c("fit", "importance"), draws = 1000L, .. method <- match.arg(method) out <- structure(-object$value / 2, df = length(object$argument), nobs = object$nObs, class = "logLik") if (method == "fit") return(out) + if (any(vapply(object$design$blocks, function(b) b$dist == "spikeSlab" && (b$mean != 0 || b$spike != 0), TRUE))) + stop("logLik: method = \"importance\" takes spikeSlab() with `mean` and `spike` 0 only.", call. = FALSE) is <- .sparseImportance(object, draws) out[] <- -is$value / 2 structure(out, se = is$se / 2, ess = is$ess, approximation = -is$approximation / 2) @@ -397,12 +402,12 @@ predict.em <- function(object, times = NULL, type = c("all", "individual", "popu rows <- list() for (cn in conds) { d <- data[[cn]] - pi <- ipred[[cn]]; pp <- pred[[cn]] + ip <- ipred[[cn]]; pp <- pred[[cn]] si <- sigmaOf(ipred, cn); sp <- sigmaOf(pred, cn) - for (nm in intersect(unique(as.character(d$name)), colnames(pi))) { + for (nm in intersect(unique(as.character(d$name)), colnames(ip))) { dn <- d[d$name == nm, , drop = FALSE] - idx <- match(dn$time, pi[, "time"]) - grid_idx <- setdiff(seq_len(nrow(pi)), idx) + idx <- match(dn$time, ip[, "time"]) + grid_idx <- setdiff(seq_len(nrow(ip)), idx) # a recorded sigma wins over the error model, as in normL2() sig <- function(sm, i, given) { model <- if (!is.null(sm) && nm %in% colnames(sm)) as.numeric(sm[i, nm]) else NA_real_ @@ -411,12 +416,12 @@ predict.em <- function(object, times = NULL, type = c("all", "individual", "popu rows[[length(rows) + 1L]] <- data.frame( condition = cn, group = group[[cn]], time = dn$time, name = nm, observed = dn$value, sigma = sig(si, idx, dn$sigma), sigmaPRED = sig(sp, idx, dn$sigma), - IPRED = pi[idx, nm], PRED = pp[idx, nm], source = "obs", stringsAsFactors = FALSE) + IPRED = ip[idx, nm], PRED = pp[idx, nm], source = "obs", stringsAsFactors = FALSE) if (length(grid_idx)) rows[[length(rows) + 1L]] <- data.frame( - condition = cn, group = group[[cn]], time = pi[grid_idx, "time"], name = nm, + condition = cn, group = group[[cn]], time = ip[grid_idx, "time"], name = nm, observed = NA_real_, sigma = sig(si, grid_idx, NA_real_), - sigmaPRED = sig(sp, grid_idx, NA_real_), IPRED = pi[grid_idx, nm], + sigmaPRED = sig(sp, grid_idx, NA_real_), IPRED = ip[grid_idx, nm], PRED = pp[grid_idx, nm], source = "grid", stringsAsFactors = FALSE) } } @@ -623,7 +628,7 @@ anova.em <- function(object, ...) .anovaTable(c(list(object), list(...))) #' @example inst/examples/simulate.em.R #' @export simulate.em <- function(object, nsim = 1, seed = NULL, ...) { - if (!is.null(seed)) set.seed(seed) + .localSeed(seed) design <- object$design pars <- c(object$argument, object$fixed) lapply(seq_len(nsim), function(i) { @@ -680,7 +685,9 @@ simulate.em <- function(object, nsim = 1, seed = NULL, ...) { } next } - out[as.vector(E[, b$stems, drop = FALSE])] <- stats::rbinom(n, 1, value("prob")) * stats::rnorm(n, 0, value("tau")) + slab <- stats::rbinom(n, 1, value("prob")) == 1L + out[as.vector(E[, b$stems, drop = FALSE])] <- ifelse(slab, stats::rnorm(n, b$mean %||% 0, value("tau")), + b$spike %||% 0) } } out diff --git a/R/eqnClass.R b/R/eqnClass.R index cf56f279..7c8f4f18 100644 --- a/R/eqnClass.R +++ b/R/eqnClass.R @@ -280,6 +280,7 @@ conservedQuantities <- function(eqnlist) { #' the detected basis. #' @return The eqnlist with `$totals` updated. #' @seealso [conservedQuantities()] +#' @example inst/examples/customTotals.R #' @export customTotals <- function(eqnlist, totals) { if (is.null(totals) || (is.list(totals) && length(totals) == 0L)) { @@ -784,6 +785,7 @@ getFluxes <- function(eqnlist, type = c("conc", "amount")) { #' "Rate" (character) and one column per state, the columns of the #' stoichiometric matrix. The compartment layout is kept as attributes and #' read back by [as.eqnlist()]. `NULL` for an empty equation list. +#' @example inst/examples/eqnlist.R #' @export as.data.frame.eqnlist <- function(x, ...) { @@ -816,6 +818,7 @@ as.data.frame.eqnlist <- function(x, ...) { #' @return `NULL`, invisibly. Called for the file it writes. #' @seealso [as.data.frame.eqnlist()] #' +#' @example inst/examples/write.eqnlist.R #' @export #' @importFrom utils file.edit getParseData install.packages installed.packages read.csv str tail write.csv write.eqnlist <- function(eqnlist, ...) { @@ -944,6 +947,7 @@ subset.eqnlist <- function(x, ...) { #' @param ... not used. #' @return `x`, invisibly. #' +#' @example inst/examples/eqnlist.R #' @export print.eqnlist <- function(x, pander = FALSE, ...) { @@ -1042,6 +1046,7 @@ print.eqnlist <- function(x, pander = FALSE, ...) { #' @details For an `eqnlist`, the right-hand sides of the ODE are assembled #' from [getFluxes()]. #' @return Object of class [eqnvec]. +#' @example inst/examples/eqnlist.R #' @export as.eqnvec <- function(x, ...) { UseMethod("as.eqnvec", x) @@ -1196,6 +1201,7 @@ is.eqnvec <- function(x) inherits(x, "eqnvec") && length(names(x)) == length(x) #' @param x object of class [eqnvec], or a named parsable character vector. #' @param ... not used. #' @return Named character vector with spaces around `+`, `-`, `*` and `/`. +#' @example inst/examples/eqnvec.R #' @export format.eqnvec #' @export format.eqnvec <- function(x, ...) { @@ -1220,6 +1226,7 @@ format.eqnvec <- function(x, ...) { #' @return `x`, invisibly. #' #' @import stringr +#' @example inst/examples/eqnvec.R #' @export print.eqnvec <- function(x, width = 140, pander = FALSE, ...) { @@ -1260,6 +1267,7 @@ print.eqnvec <- function(x, width = 140, pander = FALSE, ...) { #' @param ... not used. #' @return `object`, invisibly. #' +#' @example inst/examples/eqnvec.R #' @export summary.eqnvec <- function(object, ...) { symbols <- vapply(object, function(eqn) paste(getSymbols(eqn), collapse = ", "), diff --git a/R/eventClass.R b/R/eventClass.R index 8ea32744..aab66279 100644 --- a/R/eventClass.R +++ b/R/eventClass.R @@ -90,6 +90,7 @@ print.eventlist <- function(x, ...) { #' @param ... not used. #' @return Object of class `eventlist`. #' @seealso [eventlist()] +#' @example inst/examples/as.eventlist.R #' @export as.eventlist <- function(x, ...) { UseMethod("as.eventlist", x) diff --git a/R/linalg.R b/R/linalg.R index 6297b524..9741fa34 100644 --- a/R/linalg.R +++ b/R/linalg.R @@ -75,7 +75,7 @@ ## submatrix -------------------------------------------- # M[rows, cols] that stays a matrix -.submatrix <- function(M, rows = 1:nrow(M), cols = 1:ncol(M)) { +.submatrix <- function(M, rows = seq_len(nrow(M)), cols = seq_len(ncol(M))) { M[rows, cols, drop = FALSE] } diff --git a/R/multipleShooting.R b/R/multipleShooting.R index ea07e867..ebdfcdf5 100644 --- a/R/multipleShooting.R +++ b/R/multipleShooting.R @@ -2,9 +2,6 @@ ## Segment j starts from node s_j, continuity c_j = phi(x_j(tau_{j+1})) - s_{j+1} ## in the chart phi. Nodes enter as inner initial states; nothing recompiles. -## Copyright (C) 2026 Simon Beyer - - # obj(pars, nodes, ...) returning the data term, the gaps and, per segment, the # blocks on (theta_loc, s_j) and the end state's chart value with the Jacobian. # Segment j holds the data and fixed-time events in [tau_j, tau_{j+1}). @@ -43,7 +40,7 @@ stop("multiple shooting: condition '", cn, "' has nodes before the start of the condition, t = ", tstart, ".", call. = FALSE) if (any(tau[-1L] >= tend)) - stop("multiple shooting: condition '", cn, "' has nodes at or after the last data point ", + stop("multiple shooting: condition '", cn, "' has nodes at or after the last data ", "point, t = ", tend, "; every segment needs time to run.", call. = FALSE) M <- length(tau) upper <- c(tau[-1L], tend) @@ -105,7 +102,6 @@ myfn } - ## ---- Setup helpers ----------------------------------------------------------- # The state names of a prediction function from Xs(): the equations of the ODE. @@ -188,7 +184,6 @@ invisible(NULL) } - ## ---- Charts ------------------------------------------------------------------ # State value from a node coordinate, with the derivative. @@ -213,7 +208,6 @@ list(value = setNames(s, names(charts)), deriv = setNames(d, names(charts))) } - ## ---- Inner parameters of the segments ---------------------------------------- # Inner parameters of the segments `which`: p's own for a condition's first @@ -302,7 +296,7 @@ "odemodel(..., includeTimeZero = FALSE).") else if (length(tt) && tt[length(tt)] < seg$end) paste0(" The solver stopped at t = ", tt[length(tt)], ".") - else " The backend extended the grid; fixed-time events need cppDE >= 0.10.2." + else " The backend added time points to the grid." msg <- paste0("multiple shooting: segment ", seg$j, " of condition '", seg$cond, "' should run on [", seg$start, ", ", seg$end, "], the solver returned [", if (length(tt)) tt[1L] else NA, ", ", @@ -320,13 +314,7 @@ segs <- spec$segs idx <- which(vapply(segs, function(s) is.null(spec$e.cond) || s$cond %in% spec$e.cond, TRUE)) if (!length(idx)) return(NULL) - split <- lapply(idx, function(k) { - pinner <- getParameters(obs[[k]]) - fixedinner <- pinner[union(attr(pinner, "fixed"), - intersect(names(pinner), names(fixed)))] - list(pars = as.parvec(pinner[setdiff(names(pinner), names(fixed))]), - fixed = as.parvec(fixedinner, deriv = FALSE, deriv2 = FALSE)) - }) + split <- lapply(idx, function(k) .errorModelArgs(obs[[k]], fixed)) conds <- vapply(segs[idx], `[[`, "", "cond") b <- .bundle(conds = conds, out = obs[idx], pars = lapply(split, `[[`, "pars"), @@ -414,7 +402,6 @@ out } - ## ---- Forward evaluation ------------------------------------------------------ .shootForward <- function(spec, cache, pars, nodes, fixed, deriv, hessian, cores, @@ -545,7 +532,6 @@ out } - ## ---- Reverse evaluation ------------------------------------------------------ ## One backward sweep per segment with 1 + n_x seeds, the data term and each end ## state; p's forward Jacobian maps the inner cotangents onto theta. @@ -656,7 +642,6 @@ out } - # An observed state's trajectory as a function of time: the replicate means # interpolated linearly, or with `smooth` a GCV smoothing spline (Horbelt, # Timmer and Voss 2002). @@ -885,7 +870,6 @@ setNames(as.list(names(eq)[hit]), trimws(eq[hit])) } - ## ---- From a normL2 objective ------------------------------------------------ # The pieces of normL2(multipleShootingControl = ): the chain split into @@ -1036,8 +1020,8 @@ } # Nodes just before fast changes of the data, where an observable's rate lies -# more than `k` robust deviations off the median rate, a twentieth of the median -# interval before the change. NULL when no condition shows one. +# more than `k` scaled median absolute deviations off the median rate, a twentieth +# of the median interval before the change. NULL when no condition shows one. .shootTransitionNodes <- function(data, x, times, k = 8, n = 10L) { base <- .shootAutoNodes(data, x, times, n) span <- .shootSpan(data, times, names(base)) diff --git a/R/nlmeDesign.R b/R/nlmeDesign.R index 0a5d038d..aadec11e 100644 --- a/R/nlmeDesign.R +++ b/R/nlmeDesign.R @@ -371,7 +371,8 @@ ## and the fixed hyperparameters, NA when estimated. .designBlock <- function(rows) { list(dist = rows$dist[1], prob = rows$prob[1], concentration = rows$concentration[1], - tau = rows$tau[1], stems = rows$stem, short = sub("^eta_", "", rows$stem)) + tau = rows$tau[1], mean = rows$mean[1] %||% 0, spike = rows$spike[1] %||% 0, stems = rows$stem, + short = sub("^eta_", "", rows$stem)) } ## Names of the hyperparameters of the blocks of one distribution, `hyper` named by `kinds` @@ -540,3 +541,22 @@ out[prob] <- stats::plogis(stats::qlogis(center[prob]) + noise[prob]) out } + +## Per spike-and-slab stem with spike -Inf the base b > 1 of the exponential b^(... + eta) in which +## the etas of the stem are summands, read off the equations of the model; an error where the etas +## enter otherwise, since the model at -Inf is then not the model at rate 0. +.spikeBases <- function(design) { + stems <- unlist(lapply(Filter(function(b) b$dist == "spikeSlab" && b$spike == -Inf, design$blocks), + `[[`, "stems")) + if (!length(stems)) return(numeric(0)) + leaves <- c(.fnLeaves(design$prdfn), if (!is.null(design$errfn)) .fnLeaves(design$errfn)) + eqs <- Filter(Negate(is.null), lapply(leaves, function(l) attr(l$kernel, "equations", exact = TRUE))) + vapply(setNames(nm = stems), function(st) { + etas <- unique(stats::na.omit(as.vector(design$etaNames[, st]))) + b <- unique(.wrapBases(eqs, etas, summand = TRUE)) + if (length(b) != 1L || is.na(b) || b <= 1) + stop("em: spikeSlab(spike = -Inf) needs ", st, " as a summand in the exponent of one numeric base ", + "greater than 1 in every condition, as after insert(trafo, \"x <- exp(x)\").", call. = FALSE) + b + }, 0) +} diff --git a/R/nlmeDiagnostics.R b/R/nlmeDiagnostics.R index 3789e4a8..001ce185 100644 --- a/R/nlmeDiagnostics.R +++ b/R/nlmeDiagnostics.R @@ -20,8 +20,8 @@ utils::globalVariables(c("lo", "mid", "hi", "percentile", "blq", "blqLo", "blqMi conds <- names(design$data) grids <- lapply(conds, function(cn) .emGrid(design, cn)) pars <- c(object$argument, object$fixed) - order <- .emObsRows(design) - data <- Map(function(d, o) d[o, , drop = FALSE], design$data, order) + rowsOf <- .emObsRows(design) + 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) @@ -51,12 +51,12 @@ utils::globalVariables(c("lo", "mid", "hi", "percentile", "blq", "blqLo", "blqMi ## The data rows in the order of predict() with their lower limit, -Inf for none. .emObsLimits <- function(design) { - order <- .emObsRows(design) + rowsOf <- .emObsRows(design) unlist(Map(function(d, o) { l <- d$lloq %||% rep(-Inf, nrow(d)) l[is.na(l)] <- -Inf l[o] - }, design$data, order), use.names = FALSE) + }, design$data, rowsOf), use.names = FALSE) } ## Normalized prediction distribution errors per data row (Comets et al. 2008), per unit of groups. diff --git a/R/nlmeQuadrature.R b/R/nlmeQuadrature.R index 79430ede..0a0a7fe0 100644 --- a/R/nlmeQuadrature.R +++ b/R/nlmeQuadrature.R @@ -18,27 +18,6 @@ .sparseGridCache[[key]] } -## The next level above `level` whose grid differs, NA above the largest one. -.nextLevel <- function(K, level) { - a <- .sparseGrid(K, level) - for (l in seq(level + 1L, length.out = 25L)) { - if (l - K + 1L > 26L) return(NA_integer_) - b <- .sparseGrid(K, l) - if (!identical(a$key, b$key) || !identical(a$logAbsW, b$logAbsW)) return(l) - } - NA_integer_ -} - -## The highest level below `level`, at least K, whose grid differs, NA if there is none. -.prevLevel <- function(K, level) { - a <- .sparseGrid(K, level) - for (l in rev(seq_len(level - K) + K - 1L)) { - b <- .sparseGrid(K, l) - if (!identical(a$key, b$key) || !identical(a$logAbsW, b$logAbsW)) return(l) - } - NA_integer_ -} - ## The node count of a level after pruning. .levelNodes <- function(K, level, pruneTol = Inf) { w <- .sparseGrid(K, level)$logAbsW @@ -60,6 +39,85 @@ } +## Dimension-adaptive sparse grids (src/adaptiveGrid.cpp) of several integrals in lock step, each from the Smolyak +## set of `level` and the index set `starts` until the error of -2 log I is within `tol`; `logf(which, z)` gives the +## log integrands of all integrals of a round in one call. Per integral grid, index set, level, error and cap. +.adaptiveGrids <- function(K, level, starts, logf, tol, maxNodes = Inf, maxLevel = Inf) { + n <- length(K) + tol <- rep_len(tol, n) + level <- rep_len(level, n) + maxLevel <- rep_len(maxLevel, n) + grids <- lapply(seq_len(n), function(i) + adaptiveGridNew(K[i], level[i], if (is.null(starts[[i]])) matrix(0L, 0, K[i]) else starts[[i]], + as.integer(min(maxLevel[i], .Machine$integer.max)))) + capped <- logical(n) + errorAt <- rep(NA_real_, n) + open <- seq_len(n) + while (length(open)) { + pend <- lapply(grids[open], adaptiveGridPending) + some <- which(vapply(pend, nrow, 0L) > 0L) + vals <- vector("list", length(open)) + if (length(some)) vals[some] <- logf(open[some], pend[some]) + # every open grid absorbs, so that waiting terms whose nodes are all known are computed as well + for (j in seq_along(open)) adaptiveGridAbsorb(grids[[open[j]]], pend[[j]], vals[[j]] %||% numeric(0)) + done <- logical(length(open)) + for (j in seq_along(open)) { + i <- open[j] + st <- adaptiveGridStatus(grids[[i]]) + error <- .gridError(st) + if (error <= tol[i]) { done[j] <- TRUE; next } + step <- adaptiveGridRefine(grids[[i]], maxNodes) + if (step == 1L) next + done[j] <- TRUE + capped[i] <- TRUE + # at the node budget the evaluated frontier joins the grid, the change by the frontier stays the error + if (step == 2L) { + adaptiveGridAccept(grids[[i]]) + errorAt[i] <- error + } + } + open <- open[!done] + } + lapply(seq_len(n), function(i) { + st <- adaptiveGridStatus(grids[[i]]) + ix <- adaptiveGridIndices(grids[[i]]) + # the old indices, the grid of the integral, start a later grid; the active ones only estimate the error + old <- ix[attr(ix, "old"), , drop = FALSE] + c(adaptiveGridNodes(grids[[i]]), list(indices = old, level = st$level, + error = if (!is.na(errorAt[i])) errorAt[i] else .gridError(st), + nodes = st$nodes, capped = capped[i])) + }) +} + +## The error of -2 log I of a grid status: twice the change of log I that the active terms make, as the +## change between two Smolyak levels, or without active terms the change from the grid below; Inf where +## the integral or the change leaves it without a sign. +.gridError <- function(st) { + # without an active term, as at maxLevel, the change from the grid without the outermost terms + if (!st$active) { + if (!(st$total > 0) || !(st$total - st$shell > 0)) return(Inf) + return(2 * abs(log(st$total / (st$total - st$shell)))) + } + if (!(st$total > 0) || !(st$total + st$change > 0)) return(Inf) + 2 * abs(log1p(st$change / st$total)) +} + +## The nodes of an adaptive grid `gr` around `mode` with posterior precision P = R'R, as +## .quadratureNodes() gives them: eta = mode + sqrt(2) R^-1 z and log weights +## log|w| + z'z + (K/2) log 2 - log|R|; nodes whose |w| lies `pruneTol` in log below the largest dropped. +.gridNodes <- function(gr, mode, precision, pruneTol = Inf) { + K <- length(mode) + R <- chol(precision) + z <- gr$z + eta <- t(sqrt(2) * backsolve(R, t(z))) + matrix(mode, nrow(z), K, byrow = TRUE) + colnames(eta) <- names(mode) + la <- log(abs(gr$weights)) + keep <- la >= max(la) - pruneTol + list(eta = eta[keep, , drop = FALSE], logW = ((K / 2) * log(2) - sum(log(diag(R))) + la + rowSums(z^2))[keep], + signs = sign(gr$weights)[keep], key = gr$key[keep]) +} + + ## Conditional modes and inner Hessians H_g (of the -2 log density, so the posterior precision ## is H_g / 2) of every group at `psi`, by the inner search of the group kernel. .innerModes <- function(design, psi, etaInit, fixed, meta, control = list()) { @@ -270,46 +328,8 @@ l } - # from `levels` up per group the lowest level whose error, the change of the group -2 log L to the next level - # within the budget, is at most tol / G, in lock step over the groups with the node values kept by key; a - # group above tol / G at the highest allowed level is capped - chooseLevels <- function(levels, capped, tol, nodesAt, psi) { - G <- length(levels) - error <- rep(NA_real_, G) - seen <- replicate(G, numeric(0), simplify = FALSE) - open <- seq_len(G) - while (length(open)) { - nxt <- vapply(open, function(i) .nextLevel(lay$K, levels[i]), 0L) - est <- vapply(nxt, allowed, TRUE) - up <- est & !is.na(nxt) & nxt <= maxLevel - ref <- ifelse(est, nxt, vapply(open, function(i) .prevLevel(lay$K, levels[i]), 0L)) - grids <- lapply(seq_along(open), function(j) - list(at = nodesAt(open[j], levels[open[j]]), ref = if (!is.na(ref[j])) nodesAt(open[j], ref[j]))) - need <- lapply(seq_along(open), function(j) { - gr <- grids[[j]] - eta <- rbind(gr$at$eta, gr$ref$eta) - key <- c(gr$at$key, gr$ref$key) - new <- !duplicated(key) & !(key %in% names(seen[[open[j]]])) - list(eta = eta[new, , drop = FALSE], key = key[new]) - }) - some <- which(vapply(need, function(n) length(n$key) > 0L, TRUE)) - vals <- if (length(some)) integrand(design$groups[open[some]], lapply(need[some], `[[`, "eta"), psi) - for (k in seq_along(some)) - seen[[open[some[k]]]] <- c(seen[[open[some[k]]]], setNames(vals[[k]], need[[some[k]]]$key)) - done <- logical(length(open)) - for (j in seq_along(open)) { - i <- open[j] - error[i] <- .levelError(grids[[j]], seen[[i]], lay$stems) - if (up[j] && error[i] > tol / G) { levels[i] <- nxt[j]; next } - done[j] <- TRUE - capped[i] <- !up[j] && !isTRUE(error[i] <= tol / G) - } - open <- open[!done] - } - list(levels = levels, error = error, capped = capped) - } - - # each group at the lowest level from `level` up within tol / G (chooseLevels()), never below the previous one + # each group on a dimension-adaptive grid (.adaptiveGrids()) from the Smolyak set of `level` and the index set + # of the last rebuild, refined until the error of the group -2 log L is within tol / G rebuild <- function(psi, level, tol = Inf, etaInit = state$modes) { psi <- c(psi, fixed[.setdiff(names(fixed), names(psi))]) im <- .innerModes(design, psi, etaInit, fixed, meta, control$innerControl %||% list()) @@ -319,23 +339,24 @@ state$stamp <- state$stamp + 1L state$memo <- NULL G <- length(design$groups) - levels <- pmax(rep(accepted(level), G), state$levels %||% 0L) - capped <- levels < as.integer(level) - error <- rep(NA_real_, G) - nodesAt <- function(i, l) .quadratureNodes(im$modes[i, ], im$H[[i]] / 2, l, pruneTol) - if (is.finite(tol)) { - chosen <- chooseLevels(levels, capped, tol, nodesAt, psi) - levels <- chosen$levels; error <- chosen$error; capped <- chosen$capped + Rs <- lapply(seq_len(G), function(i) chol(im$H[[i]] / 2)) + etaOf <- function(i, z) { + eta <- t(sqrt(2) * backsolve(Rs[[i]], t(z))) + matrix(im$modes[i, ], nrow(z), lay$K, byrow = TRUE) + `colnames<-`(eta, lay$stems) } - state$levels <- levels - state$levelError <- error - state$capped <- capped - state$nodes <- lapply(seq_len(G), function(i) nodesAt(i, levels[i])) + logf <- function(which, z) integrand(design$groups[which], Map(etaOf, which, z), psi) + grids <- .adaptiveGrids(rep(lay$K, G), accepted(level), state$indices %||% vector("list", G), logf, tol / G, + maxNodes, maxLevel) + state$indices <- lapply(grids, `[[`, "indices") + state$levels <- vapply(grids, `[[`, 0L, "level") + state$levelError <- vapply(grids, `[[`, 0, "error") + state$capped <- vapply(grids, `[[`, TRUE, "capped") | accepted(level) < as.integer(level) + state$nodes <- lapply(seq_len(G), function(i) .gridNodes(grids[[i]], im$modes[i, ], im$H[[i]] / 2, pruneTol)) invisible(state) } # the nodes of a rebuild, to return to without a new mode search - fields <- c("modes", "H", "psi0", "levels", "levelError", "capped", "nodes") + fields <- c("modes", "H", "psi0", "levels", "levelError", "capped", "nodes", "indices") snapshot <- function() mget(fields, envir = state) restore <- function(snap) { list2env(snap, envir = state) @@ -425,18 +446,6 @@ } -## The error of a group level, twice the change of log L to the reference level of `grid` on the node -## values `seen`: NA without a reference, Inf where a node sum is not resolved. -.levelError <- function(grid, seen, stems) { - if (is.null(grid$ref)) return(NA_real_) - at <- grid$at; rf <- grid$ref - la <- .nodeSum(at$logW + seen[at$key], at$signs, at$eta, stems) - lr <- .nodeSum(rf$logW + seen[rf$key], rf$signs, rf$eta, stems) - if (is.null(la) || is.null(lr)) return(Inf) - 2 * abs(lr$logL - la$logL) -} - - ## The predicted decrease of -2 log L of a Newton step, g' H^-1 g / 2. Where the Hessian is not ## positive definite, as where the variance of a random effect runs to 0, the directions without ## positive curvature add the linear decrease of a step of `rmax` along their gradient. @@ -613,17 +622,7 @@ list(eta = eta, logProposal = logProposal) }) logF <- q$integrand(design$groups, lapply(draws, `[[`, "eta"), c(psi, fixed)) - # the error of the levels against the next one where the levels were not chosen by tolerance levelError <- st$levelError - for (i in which(is.na(levelError))) { - up <- .nextLevel(K, st$levels[i]) - if (!q$allowed(up)) up <- .prevLevel(K, st$levels[i]) - if (is.na(up)) next - nodes <- .quadratureNodes(st$modes[i, ], st$H[[i]] / 2, up) - s <- .nodeSum(nodes$logW + q$integrand(design$groups[i], list(nodes$eta), c(psi, fixed))[[1]], - nodes$signs, nodes$eta, lay$stems) - levelError[i] <- if (is.null(s) || is.na(quad[i])) Inf else 2 * abs(s$logL - quad[i]) - } rows <- lapply(seq_along(design$groups), function(i) { lw <- logF[[i]] - draws[[i]]$logProposal mx <- max(lw) diff --git a/R/nlmeSaem.R b/R/nlmeSaem.R index 916fb868..3f96f4bc 100644 --- a/R/nlmeSaem.R +++ b/R/nlmeSaem.R @@ -261,12 +261,12 @@ sh <- shift(beta) S <- s2 - (crossprod(sh, s1) + crossprod(s1, sh) - crossprod(sh)) / G if (!is.null(minVar)) diag(S) <- pmax(diag(S), minVar) - chol <- .updateNormal(design, list(S), fixed) + cholPars <- .updateNormal(design, list(S), fixed) if (!length(free)) break - Omega <- tcrossprod(.choleskyFactor(lay, c(chol, fixed))) + Omega <- tcrossprod(.choleskyFactor(lay, c(cholPars, fixed))) beta[free] <- .glsFixedEffects(ref, s1, Omega, beta, free) } - list(beta = beta, chol = chol) + list(beta = beta, chol = cholPars) } full <- setNames(numeric(length(meta$pars_full_names)), meta$pars_full_names) @@ -319,8 +319,8 @@ Ic[free, free] <- Reduce(`+`, lapply(D, function(m) crossprod(m[, free, drop = FALSE], W %*% m[, free, drop = FALSE]))) sh <- shift(beta) S <- s2 - (crossprod(sh, s1) + crossprod(s1, sh) - crossprod(sh)) / G - chol <- .intersect(lay$cholPars, names(start)) - Ic[chol, chol] <- G / 2 * .choleskyDerivatives(lay, L, S)$hcc[chol, chol] + cp <- .intersect(lay$cholPars, names(start)) + Ic[cp, cp] <- G / 2 * .choleskyDerivatives(lay, L, S)$hcc[cp, cp] if (length(trustPars)) Ic[trustPars, trustPars] <- cm1Objective(full[trustPars])$hessian / 2 Ic } @@ -458,30 +458,31 @@ } ## The Gaussian of the slab values of group `g` in the subset `s`, the other coordinates at 0, on -## the quadratic model plus the slab prior: the mean (0 off `s`) and the upper factor R of the -## precision P, the covariance 2 `scale` P^-1. -.slabGaussian <- function(model, g, s, tau, scale) { +## the quadratic model plus the slab prior of mean `mu`: the mean (0 off `s`) and the upper factor R +## of the precision P, the covariance 2 `scale` P^-1. +.slabGaussian <- function(model, g, s, tau, scale, mu = 0 * tau) { mean <- numeric(length(s)) if (!any(s)) return(list(mean = mean, R = NULL, s = s, scale = scale)) H <- model$H[[g]] R <- chol(H[s, s, drop = FALSE] + diag(2 / tau[s]^2, sum(s))) - rhs <- drop(H %*% model$ref[g, ])[s] - model$grad[g, s] + rhs <- drop(H %*% model$ref[g, ])[s] - model$grad[g, s] + 2 * mu[s] / tau[s]^2 mean[s] <- backsolve(R, forwardsolve(t(R), rhs)) list(mean = mean, R = R, s = s, scale = scale) } ## Probabilists' Gauss-Hermite nodes and weights of order 3 or 5: sum w f(t) = E f(Z), Z ~ N(0, 1), ## exact for polynomials of degree 2 n - 1. -.hermiteNodes <- function(n) switch(as.character(n), - "3" = list(t = c(-sqrt(3), 0, sqrt(3)), w = c(1, 4, 1) / 6), - "5" = list(t = c(-2.856970013872806, -1.355626179974266, 0, 1.355626179974266, 2.856970013872806), - w = c(0.011257411327721, 0.222075922005613, 0.533333333333333, 0.222075922005613, 0.011257411327721)), - stop("em: `control$saem$nodes` is 3 or 5.", call. = FALSE)) - -## The collapsed move on indicator `j[g]` of every group g (NA: none), the slab value integrated -## out by Gauss-Hermite on the local Gaussian, an independence Metropolis-Hastings step on the exact -## posterior (methods-nlme, SAEM); `dataAt(V)` is -2 log p(y_g, eta_g) at V, `value` the current. -.slabCollapsed <- function(V, Z, value, dataAt, model, prob, tau, j, scale, gh) { +.hermiteNodes <- function(n) { + if (!n %in% c(3, 5)) stop("em: `control$saem$nodes` is 3 or 5.", call. = FALSE) + gh <- .gaussHermite(n) + list(t = sqrt(2) * gh$x, w = gh$w / sqrt(pi)) +} + +## The collapsed move on indicator `j[g]` of every group g (NA: none) with spike `spike` and slab N(`mu`, tau^2): +## 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) { G <- nrow(V); J <- ncol(V) go <- !is.na(j) base <- V; dir <- matrix(0, G, J); m <- sd <- rep(NA_real_, G) @@ -492,15 +493,23 @@ H <- model$H[[g]] S <- c(i, o) P <- H[S, S, drop = FALSE] + diag(2 / tau[S]^2, length(S)) - B <- if (length(o)) -solve(P[-1, -1, drop = FALSE], P[-1, 1]) else numeric(0) - if (Z[g, i]) { base[g, o] <- V[g, o] - B * V[g, i]; base[g, i] <- 0 } - dir[g, i] <- 1; dir[g, o] <- B - grad <- model$grad[g, ] + drop(H %*% (base[g, ] - model$ref[g, ])) + 2 * base[g, ] / tau^2 - s <- P[1, 1] + if (length(o)) sum(P[1, -1] * B) else 0 + B <- if (length(o) && is.finite(spike[i])) -solve(P[-1, -1, drop = FALSE], P[-1, 1]) else numeric(0) + xi <- if (Z[g, i]) V[g, i] else spike[i] + if (length(B)) base[g, o] <- V[g, o] - B * xi + base[g, i] <- 0 + dir[g, i] <- 1 + if (length(B)) dir[g, o] <- B + if (!is.null(override) && !is.na(override$m[g])) { m[g] <- override$m[g]; sd[g] <- override$sd[g]; next } + # coordinates at a spike of -Inf leave the quadratic model at the reference + dv <- base[g, ] - model$ref[g, ]; dv[!is.finite(dv)] <- 0 + dp <- base[g, ] - mu; dp[!is.finite(dp)] <- 0 + grad <- model$grad[g, ] + drop(H %*% dv) + 2 * dp / tau^2 + s <- P[1, 1] + if (length(B)) sum(P[1, -1] * B) else 0 if (!(s > 0)) stop("no curvature") - m[g] <- -(grad[i] + sum(B * grad[o])) / s + m[g] <- -(grad[i] + if (length(B)) sum(B * grad[o]) else 0) / s sd[g] <- sqrt(2 / s) }, error = function(e) go[g] <<- FALSE) + lineAt <- function(x) base + ifelse(dir == 0, 0, x * dir) out <- list(V = V, Z = Z, value = value, birth = rep(NA, G), ok = rep(FALSE, G), pinc = rep(NA_real_, G), slab2 = rep(NA_real_, G)) if (!any(go)) return(out) @@ -509,10 +518,12 @@ # coordinate of the group lp1 <- matrix(log(prob), G, J, byrow = TRUE); lp0 <- matrix(log1p(-prob), G, J, byrow = TRUE) sdSlab <- matrix(tau, G, J, byrow = TRUE) + muSlab <- matrix(mu, G, J, byrow = TRUE) + xOff <- ifelse(go, spike[ig[, 2]], 0) logF <- function(x, d, slab) { z <- Z; z[ig] <- slab - v <- base + ifelse(go, x, 0) * dir - out <- rowSums(ifelse(z, lp1 + stats::dnorm(v, 0, sdSlab, log = TRUE), lp0)) - d / 2 + v <- lineAt(ifelse(go, x, 0)) + out <- rowSums(ifelse(z, lp1 + stats::dnorm(v, muSlab, sdSlab, log = TRUE), lp0)) - d / 2 ifelse(go, out, NA_real_) } # the data term on the line at the columns of `x`, all in one evaluation; where that fails each @@ -520,16 +531,16 @@ at <- function(x) { x <- matrix(x, G) x[!go, ] <- 0 - one <- function(k) tryCatch(dataAt(base + x[, k] * dir), error = function(e) rep(Inf, G)) - d <- tryCatch(matrix(dataAt(lapply(seq_len(ncol(x)), function(k) base + x[, k] * dir)), G), + one <- function(k) tryCatch(dataAt(lineAt(x[, k])), error = function(e) rep(Inf, G)) + d <- tryCatch(matrix(dataAt(lapply(seq_len(ncol(x)), function(k) lineAt(x[, k]))), G), error = function(e) vapply(seq_len(ncol(x)), one, numeric(G))) matrix(ifelse(is.finite(d), d, Inf), G) } inSlab <- go & Z[ig] == 1 nodes <- outer(m, rep(1, length(gh$t))) + outer(sd, gh$t) - d <- at(cbind(0, nodes)) + d <- at(cbind(xOff, nodes)) d0 <- ifelse(inSlab, d[, 1], value) - lf0 <- logF(numeric(G), d0, FALSE) + lf0 <- logF(xOff, d0, FALSE) lw <- vapply(seq_along(gh$t), function(q) { x <- nodes[, q] log(gh$w[q]) + logF(x, d[, q + 1L], TRUE) - stats::dnorm(x, m, sd, log = TRUE) @@ -539,20 +550,21 @@ top <- apply(lw, 1, max) logI <- top + log(rowSums(exp(lw - top))) logI[!is.finite(top)] <- -Inf - m2 <- rowSums(exp(lw - top) * nodes^2) / rowSums(exp(lw - top)) + m2 <- rowSums(exp(lw - top) * (nodes - mu[ig[, 2]])^2) / rowSums(exp(lw - top)) pinc <- ifelse(is.finite(lf0), 1 / (1 + exp(lf0 - logI)), 1) pinc[!go] <- NA q1 <- 0.01 + 0.98 * pinc logW <- function(slab, x, lf) ifelse(slab, lf - log(q1) - stats::dnorm(x, m, sp, log = TRUE), lf - log1p(-q1)) cur <- logW(inSlab, V[ig], ifelse(inSlab, logF(V[ig], value, TRUE), lf0)) slabNew <- stats::runif(G) < q1 - xNew <- ifelse(slabNew, m + sp * stats::rnorm(G), 0) + xNew <- ifelse(slabNew, m + sp * stats::rnorm(G), xOff) dNew <- d0 if (any(go & slabNew)) dNew[go & slabNew] <- at(xNew)[go & slabNew, 1] new <- logW(slabNew, xNew, ifelse(slabNew, logF(xNew, dNew, TRUE), lf0)) ok <- go & is.finite(new) & (!is.finite(cur) | log(stats::runif(G)) < new - cur) + newV <- lineAt(ifelse(go, xNew, 0)) for (g in which(ok)) { - out$V[g, ] <- base[g, ] + xNew[g] * dir[g, ] + out$V[g, ] <- newV[g, ] out$Z[g, j[g]] <- slabNew[g] out$value[g] <- dNew[g] } @@ -566,13 +578,14 @@ ## 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) { +.slabWalk <- function(V, Z, value, dataAt, tau, step, sd, mu = 0 * tau) { G <- nrow(V) prop <- ifelse(Z, V + step * sd * matrix(stats::rnorm(length(V)), G), V) pv <- tryCatch(dataAt(prop), error = function(e) rep(Inf, G)) t2 <- matrix(rep(tau^2, each = G), G) + mm <- matrix(rep(mu, each = G), G) ok <- rowSums(Z) > 0 & is.finite(pv) & - log(stats::runif(G)) < (value - pv) / 2 - rowSums((prop^2 - V^2) / (2 * t2)) + log(stats::runif(G)) < (value - pv) / 2 - rowSums(ifelse(Z, ((prop - mm)^2 - (V - mm)^2) / (2 * t2), 0)) V[ok, ] <- prop[ok, ] value[ok] <- pv[ok] list(V = V, value = value, accept = ok) @@ -593,6 +606,15 @@ G <- nrow(Dp); K <- ncol(E) dpStems <- sl$stem[sl$dist == "dirichletProcess"] slabStems <- sl$stem[sl$dist == "spikeSlab"] + # the spike value and the slab mean of every spike-and-slab stem; other than 0 the final -2 log L is the + # sum over subsets of em(method = "focei") + 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) + 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) # -2 log L by importance sampling over the partitions where the exact sum beside spike-and-slab # random effects is too large or `integral` asks for it, else by the exact sum or EC importance <- length(dpStems) > 0L && (!length(slabStems) || G > 14L || identical(saem$integral, "importance")) @@ -646,15 +668,19 @@ for (st in sl$stem) chain$full[Dp[, st]] <- mode0[, st] Ds <- Dp[, slabStems, drop = FALSE] reach <- .reachOf(design)[, slabStems, drop = FALSE] - chain$full[Ds[!reach]] <- 0 - chain$incl <- if (is.null(selected0)) reach else reach & matrix(chain$full[Ds] != 0, G) + 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)) + chain$full[Ds[!reach]] <- spikeM[!reach] + chain$incl <- if (is.null(selected0)) reach else reach & matrix(chain$full[Ds] != spikeM, G) chain$slabRef <- matrix(chain$full[Ds], G, dimnames = dimnames(Ds)) # an estimated slab starts at least as wide as the largest of those modes: in a narrow slab a coordinate # without a deviation costs little, and tau and prob drift together to a slab of width 0 including all for (b in Filter(function(b) b$dist == "spikeSlab", design$blocks)) { tn <- unname(b$hyper["tau"]) if (tn %in% hypers && is.null(selected0)) - chain$hyper[[tn]] <- max(chain$hyper[[tn]], abs(chain$slabRef[, match(b$stems, slabStems)])) + chain$hyper[[tn]] <- max(chain$hyper[[tn]], abs(chain$slabRef[, match(b$stems, slabStems)] - + rep(meanS[match(b$stems, slabStems)], each = G))) } chain$slabStep <- rep(0.5, G) chain$eta <- mode0[, lay$stems, drop = FALSE] @@ -684,7 +710,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) + saem, gh, burnin, spikeS, meanS) chain <- slabs$chain moves <- slabs$moves } @@ -723,7 +749,30 @@ keep <- utils::tail(draws, length(late)) if (!length(keep)) keep <- list(list(dp = lapply(chain$state, .canonicalClusters), incl = chain$incl, pinc = chain$incl, v = matrix(chain$full[Ds], G, dimnames = dimnames(Ds)))) - picked <- .saemSelection(design, keep, chain$eta, dpStems, slabStems, reach, hyp) + picked <- .saemSelection(design, keep, chain$eta, dpStems, slabStems, reach, hyp, spikeS) + if (general) { + # -2 log L as em(method = "focei") defines it for a given spike or slab mean: the sum over subsets + lay2 <- .spikeLayout(design) + 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(), + .spikeOmega(design, c(chain$full, fixed))) + extra <- .extraObjective(design) + value <- sum(vapply(est, `[[`, 0, "m2logI")) + + 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]] + best <- e$parts[[which.max(vapply(e$parts, `[[`, 0, "weight"))]] + C <- matrix(0, ncol(En), ncol(En), dimnames = list(colnames(En), colnames(En))) + k <- match(best$on, En[g, ]) + C[k, k] <- best$cov + C + }) + 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)) + } # -2 log L as em(method = "focei") defines it, with the second derivatives the models provide reachAll <- .reachOf(design) units <- lapply(design$groups, function(g) @@ -799,7 +848,7 @@ ## 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) { + saem, gh, burnin, spikeS = 0 * hyp$tau[slabStems], meanS = 0 * hyp$tau[slabStems]) { G <- nrow(Ds) tauS <- hyp$tau[slabStems]; probS <- hyp$prob[slabStems] groupPars <- function() lapply(seq_len(G), function(g) { @@ -811,7 +860,7 @@ # the reference of the next model: the mean of the local Gaussian in the slab alone, within five slab # standard deviations for (g in seq_len(G)) chain$slabRef[g, ] <- tryCatch( - pmin(pmax(.slabGaussian(local, g, reach[g, ], tauS, 1)$mean, -5 * tauS), 5 * tauS), + pmin(pmax(.slabGaussian(local, g, reach[g, ], tauS, 1, meanS)$mean, meanS - 5 * tauS), meanS + 5 * tauS), error = function(e) chain$slabRef[g, ]) } chain$slabProp <- chain$slabProp %||% @@ -827,6 +876,33 @@ walkScale <- t(vapply(model$H, function(h) sqrt(2 / (pmax(diag(h), 0) + 2 / tauS^2)), numeric(ncol(Ds)))) if (ncol(Ds) == 1L) walkScale <- t(walkScale) incl <- chain$incl + # for a spike at -Inf the proposal of coordinate j[g] is the Laplace approximation of the coordinate given + # the others at V, by Newton steps on the model itself from the slab reference + newton <- function(V, j) { + minf <- !is.na(j) & !is.finite(spikeS[pmax(j, 1L)]) + if (!any(minf)) return(NULL) + x <- chain$slabRef[cbind(seq_len(G), pmax(j, 1L))] + curv <- rep(NA_real_, G) + base <- groupPars() + for (it in seq_len(3L)) { + pars <- lapply(seq_len(G), function(g) { + p <- base[[g]]; p[Ds[g, ]] <- V[g, ] + if (minf[g]) p[Ds[g, j[g]]] <- x[g] + p + }) + out <- tryCatch(.groupData(design, objs, pars), error = function(e) NULL) + if (is.null(out)) return(NULL) + for (g in which(minf)) { + nm <- Ds[g, j[g]]; k <- j[g] + gr <- out[[g]]$gradient[[nm]] + 2 * (x[g] - meanS[k]) / tauS[k]^2 + h <- as.matrix(out[[g]]$hessian)[nm, nm] + 2 / tauS[k]^2 + if (!is.finite(gr) || !(h > 0)) { minf[g] <- FALSE; next } + x[g] <- x[g] - max(min(gr / h, 2 * tauS[k]), -2 * tauS[k]) + curv[g] <- h + } + } + list(m = ifelse(minf, x, NA_real_), sd = ifelse(minf, sqrt(2 / curv), NA_real_)) + } tried <- c(birth = 0, death = 0); taken <- tried rbIncl <- rbSlab2 <- rbCount <- matrix(0, G, ncol(Ds)) for (s in seq_len(saem$nFlip)) { @@ -834,7 +910,8 @@ visit <- lapply(seq_len(G), function(g) { i <- which(reach[g, ]); i[sample.int(length(i))] }) 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) + fl <- .slabCollapsed(V, incl, value, blockAt, model, probS, tauS, j, saem$laplaceScale, gh, spikeS, meanS, + newton(V, j)) 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)) @@ -847,10 +924,10 @@ } # a coordinate whose collapsed step failed in every sweep enters with the draw chain$rbIncl <- ifelse(rbCount > 0, rbIncl / pmax(rbCount, 1), incl) - chain$rbSlab2 <- ifelse(rbCount > 0, rbSlab2 / pmax(rbCount, 1), incl * V^2) + chain$rbSlab2 <- ifelse(rbCount > 0, rbSlab2 / pmax(rbCount, 1), ifelse(incl, (V - rep(meanS, each = G))^2, 0)) walked <- numeric(G) for (s in seq_len(saem$nMcmc)) { - sw <- .slabWalk(V, incl, value, blockAt, tauS, chain$slabStep, walkScale) + sw <- .slabWalk(V, incl, value, blockAt, tauS, chain$slabStep, walkScale, meanS) V <- sw$V; value <- sw$value walked <- walked + sw$accept / saem$nMcmc } @@ -874,9 +951,9 @@ sh <- refs$shift(chain$beta) S <- chain$s2 - (crossprod(sh, chain$s1) + crossprod(chain$s1, sh) - crossprod(sh)) / G if (burnin) diag(S) <- pmax(diag(S), 0.95 * diag(tcrossprod(L))) - chol <- .updateNormal(design, list(S), fixed) - held <- .intersect(names(chol), names(outer)) - chain$full[held] <- chol[held] + cholPars <- .updateNormal(design, list(S), fixed) + held <- .intersect(names(cholPars), names(outer)) + chain$full[held] <- cholPars[held] if (!length(free)) break Omega <- tcrossprod(.choleskyFactor(design$normal, c(chain$full, fixed))) chain$beta[free] <- .glsFixedEffects(ref, chain$s1, Omega, chain$beta, free) @@ -936,7 +1013,7 @@ ## The selection from the late draws `keep`: per Dirichlet-process stem the most frequent partition with the ## cluster values averaged over the draws of that partition; per spike-and-slab coordinate the mean conditional inclusion ## probability, selected above 1/2 with the mean slab value. -.saemSelection <- function(design, keep, eta, dpStems, slabStems, reach, hyp) { +.saemSelection <- function(design, keep, eta, dpStems, slabStems, reach, hyp, spikeS = rep(0, length(slabStems))) { G <- nrow(design$etaNames) modes <- matrix(0, G, ncol(design$etaNames), dimnames = dimnames(design$etaNames)) modes[, design$normal$stems] <- eta @@ -953,10 +1030,10 @@ } if (length(slabStems)) { Z <- Reduce(`+`, lapply(keep, `[[`, "incl")) - V <- Reduce(`+`, lapply(keep, function(d) d$v * d$incl)) + V <- Reduce(`+`, lapply(keep, function(d) ifelse(d$incl, d$v, 0))) inclusion <- Reduce(`+`, lapply(keep, `[[`, "pinc")) / length(keep) selected <- inclusion > 0.5 - modes[, slabStems] <- ifelse(selected & Z > 0, V / pmax(Z, 1), 0) + modes[, slabStems] <- ifelse(selected & Z > 0, V / pmax(Z, 1), matrix(spikeS, G, length(slabStems), byrow = TRUE)) spike[, slabStems] <- ifelse(reach, 1 - inclusion, 1 - rep(hyp$prob[slabStems], each = G)) clusters[, slabStems] <- apply(selected, 2, function(s) ifelse(s, cumsum(s), 0)) } diff --git a/R/nlmeSparse.R b/R/nlmeSparse.R index e15acf5e..50468154 100644 --- a/R/nlmeSparse.R +++ b/R/nlmeSparse.R @@ -882,8 +882,8 @@ .empiricalInformation <- function(final, par) { if (is.null(final$scores) || anyNA(final$scores)) return(NULL) G <- nrow(final$scores) - centred <- sweep(final$scores, 2, colMeans(final$scores)) / 2 - I <- if (G > 1L) G / (G - 1) * crossprod(centred) else 0 * crossprod(centred) + centered <- sweep(final$scores, 2, colMeans(final$scores)) / 2 + I <- if (G > 1L) G / (G - 1) * crossprod(centered) else 0 * crossprod(centered) I[par, par] <- I[par, par] + final$freeHessian / 2 I } diff --git a/R/nlmeSpikeEC.R b/R/nlmeSpikeEC.R new file mode 100644 index 00000000..b99a7f47 --- /dev/null +++ b/R/nlmeSpikeEC.R @@ -0,0 +1,175 @@ +# Expectation consistent (EC) approximation of the integral of one group over spike-and-slab random effects with a +# given spike and slab mean, in the coordinate u in which the spike is 0 (methods article Sparsity priors, section +# Spike at a given value). + + +## Gauss-Hermite nodes and weights for the weight exp(-x^2), `n` nodes (Golub-Welsch). +.gaussHermite <- function(n) { + if (n == 1L) return(list(x = 0, w = sqrt(pi))) + J <- matrix(0, n, n) + off <- sqrt(seq_len(n - 1L) / 2) + J[cbind(seq_len(n - 1L), 2:n)] <- off + J[cbind(2:n, seq_len(n - 1L))] <- off + e <- eigen(J, symmetric = TRUE) + list(x = e$values, w = sqrt(pi) * e$vectors[1, ]^2) +} + +## The tilted distribution of one site, the Gaussian cavity N(u; mc, vc) times the slab part of the +## prior with weight `prob`: log of the slab mass, E[u], E[u^2] and E[(eta - mean)^2] under the slab; +## `lb` = log b for the log-normal slab of ln u = lb eta, NA for a normal slab in u = eta - spike. +.ecSlabMoments <- function(mc, vc, mean, tau, lb, spike, gh) { + if (is.na(lb)) { + # u = eta - spike, slab N(mean - spike, tau^2): the product of two Gaussians in closed form + ms <- mean - spike + v <- 1 / (1 / vc + 1 / tau^2) + m <- v * (mc / vc + ms / tau^2) + logZ <- stats::dnorm(mc, ms, sqrt(vc + tau^2), log = TRUE) + return(list(logZ = logZ, m1 = m, m2 = v + m^2, dev2 = v + (m + spike - mean)^2)) + } + # in w = ln u: log N(e^w; mc, vc) + log N(w; lb mean, (lb tau)^2), adaptive Gauss-Hermite at the mode + mw <- lb * mean; sw2 <- (lb * tau)^2 + h <- function(w) -(exp(w) - mc)^2 / (2 * vc) - (w - mw)^2 / (2 * sw2) + dh <- function(w) -(exp(w) - mc) * exp(w) / vc - (w - mw) / sw2 + d2h <- function(w) -(2 * exp(2 * w) - mc * exp(w)) / vc - 1 / sw2 + w <- if (mc > 0) min(log(mc), mw + 6 * sqrt(sw2)) else mw + for (i in seq_len(50L)) { + c2 <- d2h(w) + step <- if (c2 < 0) -dh(w) / c2 else sign(dh(w)) * sqrt(sw2) + step <- max(min(step, 2), -2) + w <- w + step + if (abs(step) < 1e-10) break + } + s <- 1 / sqrt(max(-d2h(w), 1e-12)) + nodes <- w + sqrt(2) * s * gh$x + lf <- h(nodes) + log(gh$w) + gh$x^2 + log(sqrt(2) * s) - 0.5 * log(2 * pi * vc) - 0.5 * log(2 * pi * sw2) + top <- max(lf) + q <- exp(lf - top) + Z <- sum(q) + u <- exp(nodes) + list(logZ = top + log(Z), m1 = sum(q * u) / Z, m2 = sum(q * u^2) / Z, + dev2 = sum(q * (nodes / lb - mean)^2) / Z) +} + +## 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. +.spikeECGroup <- function(design, objs, g, theta, fixed, etas, cand, nrm, pr, alpha, prob, lb, start, + control = list()) { + conds <- design$conditions[[g]] + J <- length(cand) + co <- c(cand, nrm) + N <- length(co) + mu <- pr$mu; tau <- pr$tau + lbc <- c(lb[cand], setNames(rep(NA_real_, length(nrm)), nrm)) + gh <- .gaussHermite(control$nodes %||% 40L) + # u = 0 is the spike of a slab coordinate, a normal coordinate is the eta itself + rate <- !is.na(lbc) + etaOf <- function(u) { + out <- u + alpha[co] + out[rate] <- log(u[rate]) / lbc[rate] + out + } + floorU <- c(ifelse(is.na(lb[cand]), -Inf, exp(lb[cand] * (mu[cand] - 4 * tau[cand]))), rep(-Inf, length(nrm))) + um <- ifelse(is.na(lbc), start[co] - alpha[co], exp(lbc * start[co])) + lam <- gam <- numeric(N) + # the normal prior: precision Omega^-1 in the Gaussian, the normalizer of the prior in the constant + P0 <- matrix(0, N, N) + if (length(nrm)) P0[J + seq_along(nrm), J + seq_along(nrm)] <- pr$Oinv + c0prior <- if (length(nrm)) -0.5 * pr$logdetO - length(nrm) / 2 * log(2 * pi) else 0 + relinearized <- FALSE + for (outer in seq_len(control$maxRelinearize %||% 30L)) { + um <- pmax(um, floorU) + eta <- setNames(etaOf(um), co) + out <- Reduce(`+`, .objEvalMany(objs[conds], rep(list(eta), length(conds)), deriv = TRUE, + fixed = c(theta, fixed, alpha[.setdiff(etas, co)]))) + if (!is.finite(out$value)) return(NULL) + D <- ifelse(rate, 1 / (um * lbc), 1) + gu <- D * out$gradient[co] + # Gauss-Newton in u: the residual Jacobian times D + Hu <- (D * as.matrix(out$hessian)[co, co]) * rep(D, each = N) + A <- Hu / 2 + P0 + a <- drop((Hu / 2) %*% um) - gu / 2 + c0 <- -out$value / 2 + sum(gu * um) / 2 - drop(um %*% Hu %*% um) / 4 + c0prior + if (outer == 1L) { + # sites from the prior moments of every slab coordinate + for (j in seq_len(J)) { + s <- .ecSlabMoments(0, 1e12, mu[cand[j]], tau[cand[j]], lb[cand[j]], alpha[cand[j]], gh) + m1 <- prob[cand[j]] * s$m1; m2 <- prob[cand[j]] * s$m2 + lam[j] <- 1 / max(m2 - m1^2, 1e-12); gam[j] <- m1 * lam[j] + } + } + ok <- FALSE + prevM <- prevV <- NULL + for (sweep in seq_len(control$maxSweeps %||% 500L)) { + Sigma <- tryCatch(chol2inv(chol(A + diag(lam, N))), error = function(e) NULL) + if (is.null(Sigma)) return(NULL) + m <- drop(Sigma %*% (a + gam)) + sd <- sqrt(diag(Sigma)) + # converged when the marginal means move by less than tolSweep standard deviations and the + # standard deviations by less than tolSweep relative + if (!is.null(prevM) && max(abs(m - prevM) / sd, abs(sd - prevV) / sd) < (control$tolSweep %||% 1e-5)) { + ok <- TRUE; break + } + prevM <- m; prevV <- sd + # one site at a time, each against the posterior after the update before + for (j in seq_len(J)) { + if (j > 1L) { + Sigma <- tryCatch(chol2inv(chol(A + diag(lam, N))), error = function(e) NULL) + if (is.null(Sigma)) return(NULL) + m <- drop(Sigma %*% (a + gam)) + } + v <- Sigma[j, j] + pc <- 1 / v - lam[j] + if (pc <= 0) next + vc <- 1 / pc + mc <- vc * (m[j] / v - gam[j]) + e <- cand[j] + s <- .ecSlabMoments(mc, vc, mu[[e]], tau[[e]], lb[[e]], alpha[[e]], gh) + lSpike <- log1p(-prob[[e]]) + stats::dnorm(0, mc, sqrt(vc), log = TRUE) + lSlab <- log(prob[[e]]) + s$logZ + top <- max(lSpike, lSlab) + logZj <- top + log(exp(lSpike - top) + exp(lSlab - top)) + pin <- exp(lSlab - logZj) + mt <- pin * s$m1 + vt <- max(pin * s$m2 - mt^2, 1e-14) + # a site of negative precision is replaced by the one that matches the tilted mean at the cavity variance + newLam <- max(1 / vt - 1 / vc, 0) + newGam <- mt * (1 / vc + newLam) - mc / vc + lam[j] <- 0.5 * lam[j] + 0.5 * newLam + gam[j] <- 0.5 * gam[j] + 0.5 * newGam + } + } + if (!ok) return(NULL) + 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) + for (j in seq_len(J)) { + v <- Sigma[j, j] + pc <- 1 / v - lam[j] + if (pc <= 0) return(NULL) + vc <- 1 / pc + mc <- vc * (m[j] / v - gam[j]) + e <- cand[j] + s <- .ecSlabMoments(mc, vc, mu[[e]], tau[[e]], lb[[e]], alpha[[e]], gh) + lSpike <- log1p(-prob[[e]]) + stats::dnorm(0, mc, sqrt(vc), log = TRUE) + lSlab <- log(prob[[e]]) + s$logZ + top <- max(lSpike, lSlab) + logZj <- top + log(exp(lSpike - top) + exp(lSlab - top)) + incl[j] <- exp(lSlab - 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] + logC[j] <- logZj - (-0.5 * log(vc * p) + 0.5 * r^2 / p - 0.5 * mc^2 / vc) + } + logI <- c0 + 0.5 * as.numeric(determinant(2 * pi * Sigma)$modulus) + 0.5 * sum((a + gam) * m) + sum(logC) + step <- max(abs(pmax(m, floorU) - um) / pmax(abs(um), 1e-8)) + um <- m + if (step < (control$tolRelinearize %||% 1e-4)) { relinearized <- TRUE; break } + } + if (!relinearized) return(NULL) + 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]) +} diff --git a/R/nlmeSpikeSlab.R b/R/nlmeSpikeSlab.R index 150e2dc6..e1de111a 100644 --- a/R/nlmeSpikeSlab.R +++ b/R/nlmeSpikeSlab.R @@ -1,4 +1,4 @@ -# Spike-and-slab random effects, 0 or from N(0, tau^2) with probability prob, and Dirichlet-process ones, a +# Spike-and-slab random effects of the default spike 0 and slab N(0, tau^2), and Dirichlet-process ones, a # partition of the groups under the Ewens prior with one N(0, tau^2) value per block but that of the population # value; derived in the methods article Sparsity priors. @@ -65,10 +65,10 @@ # the slab values of the group are integrated out: the Schur complement keeps the clusters keep <- seq_len(length(h) + length(new)) if (length(on)) { - drop <- setdiff(seq_len(d), keep) - Sinv <- solve(L2[drop, drop, drop = FALSE]) - h2 <- h2[keep] - drop(L2[keep, drop, drop = FALSE] %*% Sinv %*% h2[drop]) - L2 <- L2[keep, keep, drop = FALSE] - L2[keep, drop, drop = FALSE] %*% Sinv %*% L2[drop, keep, drop = FALSE] + out <- setdiff(seq_len(d), keep) + Sinv <- solve(L2[out, out, drop = FALSE]) + h2 <- h2[keep] - drop(L2[keep, out, drop = FALSE] %*% Sinv %*% h2[out]) + L2 <- L2[keep, keep, drop = FALSE] - L2[keep, out, drop = FALSE] %*% Sinv %*% L2[out, keep, drop = FALSE] lt <- lt[keep] cc <- value - logIntegral(L2, h2, lt) } diff --git a/R/nlmeSpikeSubsets.R b/R/nlmeSpikeSubsets.R new file mode 100644 index 00000000..711b9f6f --- /dev/null +++ b/R/nlmeSpikeSubsets.R @@ -0,0 +1,592 @@ +# Spike-and-slab random effects with a given slab mean and spike, -Inf included, beside normal ones: per +# group the sum over the subsets of slab etas, each a Laplace integral or a sparse-grid quadrature (methods +# article Sparsity priors, section Spike at a given value). + + +## 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. +.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) + })) +} + +## The prior of a group: slab means `mu` and standard deviations `tau` of the slab etas, and with normal +## random effects their etas `normal`, Omega^-1 `Oinv` and log|Omega| `logdetO`. +.spikePriorOf <- function(mu, tau, normal = character(0), Oinv = NULL, logdetO = 0) + list(mu = mu, tau = tau, normal = normal, Oinv = Oinv, logdetO = logdetO) + +## -2 log of the prior `pr` without the normalizer at the etas `p` (named, the slab etas of `p` in the +## slab), with gradient and Hessian in `p`. +.spikePriorTerm <- function(pr, p) { + n <- length(p) + gr <- setNames(numeric(n), names(p)) + H <- matrix(0, n, n, dimnames = list(names(p), names(p))) + s <- .intersect(names(p), names(pr$tau)) + d <- p[s] - pr$mu[s] + v <- sum((d / pr$tau[s])^2) + gr[s] <- 2 * d / pr$tau[s]^2 + if (length(s)) H[s, s] <- diag(2 / pr$tau[s]^2, length(s)) + if (length(pr$normal)) { + q <- pr$normal + Oq <- drop(pr$Oinv %*% p[q]) + v <- v + sum(p[q] * Oq) + gr[q] <- 2 * Oq + H[q, q] <- 2 * pr$Oinv + } + list(value = v, gradient = gr, hessian = H) +} + +## The normalizer of the prior over the etas `on`, -2 log of (2 pi)^(-d/2) |V|^(-1/2) without the 2 pi. +.spikePriorNorm <- function(pr, on) + sum(log(pr$tau[.intersect(on, names(pr$tau))]^2)) + if (length(pr$normal)) pr$logdetO else 0 + +## 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) { + conds <- design$conditions[[g]] + off <- .setdiff(etas, on) + base <- c(theta, fixed) + if (!length(on)) { + out <- Reduce(`+`, .objEvalMany(objs[conds], rep(list(c(base, start[off])), length(conds)), deriv = FALSE)) + if (!is.finite(out$value)) return(NULL) + return(list(m2logZ = out$value, mode = numeric(0), cov = matrix(0, 0, 0))) + } + fx <- c(base, start[off]) + objfun <- function(p, fixed = NULL, deriv = TRUE, ...) { + outs <- .objEvalMany(objs[conds], rep(list(p), length(conds)), deriv = deriv, fixed = fixed) + out <- Reduce(`+`, outs) + prior <- .spikePriorTerm(pr, p) + gr <- prior$gradient + if (!is.null(out$gradient)) gr <- gr + out$gradient[names(p)] + H <- prior$hessian + if (!is.null(out$hessian)) H <- H + as.matrix(out$hessian)[names(p), names(p)] + objlist(value = out$value + prior$value, gradient = gr, hessian = H) + } + fit <- tryCatch(.innerTrust(list(objfun = objfun, parinit = start[on], fixed = fx, rinit = 1, rmax = 10, + iterlim = 100L)), + error = function(e) NULL) + if (is.null(fit) || !is.finite(fit$value)) return(NULL) + at <- objfun(fit$argument, fixed = fx) + H <- (at$hessian + t(at$hessian)) / 2 + ch <- tryCatch(chol(H / 2), error = function(e) NULL) + if (is.null(ch)) return(NULL) + list(m2logZ = at$value + .spikePriorNorm(pr, on) + 2 * sum(log(diag(ch))), + mode = fit$argument, cov = chol2inv(ch), prec = H / 2) +} + +## The data -2 log L of group `g` at the parameter vectors `full`, one per node, in one call of the +## native chain (threads by option dMod2.cores only): values and, with `active`, gradients (nodes x +## active) and Gauss-Newton Hessians (nodes x active x active). +.spikeNodes <- function(design, g, full, active = character(0)) { + conds <- design$conditions[[g]] + B <- length(full) + grad <- length(active) > 0L + reqCond <- rep(conds, each = B) + reqFull <- rep(full, times = length(conds)) + rest <- .setdiff(names(full[[1L]]), active) + cores <- getOption("dMod2.cores", 1L) + kr <- .nodeChain(design, reqCond, reqFull, active, rest, grad, FALSE, cores) %||% + .nodeR(design, reqCond, reqFull, active, rest, grad, FALSE, cores) + node <- rep(seq_len(B), times = length(conds)) + Q <- length(active) + value <- numeric(B) + gr <- if (grad) matrix(0, B, Q, dimnames = list(NULL, active)) + he <- if (grad) array(0, c(B, Q, Q), dimnames = list(NULL, active, active)) + for (r in seq_along(node)) { + loc <- kr$local[[r]] + b <- node[r] + value[b] <- value[b] + loc$value + if (!grad) next + nm <- .intersect(active, names(loc$gradient)) + gr[b, nm] <- gr[b, nm] + loc$gradient[nm] + he[b, nm, nm] <- he[b, nm, nm] + as.matrix(loc$hessian)[nm, nm] + } + list(value = value, gradient = gr, hessian = he) +} + +## The subsets `rs` (from .spikeSubset()) of group `g` on adaptive sparse grids (.adaptiveGrids()), a subset of +## relative weight `w` to the tolerance tol / w, from the index sets `starts`: -2 log Z, nodes, signed posterior +## weights, index set, level and whether `tol` was met. +.spikeQuadrature <- function(design, g, theta, fixed, etas, rs, pr, alpha, w, starts, qc = list()) { + tol <- qc$tol + K <- vapply(rs, function(r) length(r$on), 0L) + fx <- lapply(rs, function(r) c(theta, fixed, alpha[.setdiff(etas, r$on)])) + names0 <- unique(c(names(theta), names(fixed), etas)) + Rs <- lapply(rs, function(r) chol(r$prec)) + etaOf <- function(i, z) { + eta <- t(sqrt(2) * backsolve(Rs[[i]], t(z))) + matrix(rs[[i]]$mode, nrow(z), K[i], byrow = TRUE) + `colnames<-`(eta, rs[[i]]$on) + } + logf <- function(which, z) { + etaList <- Map(etaOf, which, z) + full <- unlist(Map(function(i, eta) lapply(seq_len(nrow(eta)), function(b) c(fx[[i]], eta[b, ])[names0]), + which, etaList), recursive = FALSE) + data <- .spikeNodes(design, g, full)$value + owner <- rep(seq_along(which), vapply(etaList, nrow, 0L)) + Map(function(k, eta) { + prior <- vapply(seq_len(nrow(eta)), function(b) .spikePriorTerm(pr, eta[b, ])$value, 0) + -(data[owner == k] + prior) / 2 + }, seq_along(which), etaList) + } + wn <- w / sum(w) + grids <- .adaptiveGrids(K, K + 1L, starts, logf, tol / pmax(wn, 1e-6), qc$maxNodes %||% 1000L, + qc$maxLevel %||% (K + 8L)) + Map(function(r, gr) { + nd <- .gridNodes(gr, r$mode, r$prec) + lt <- nd$logW + gr$logValues[match(nd$key, gr$key)] + top <- max(lt) + sw <- nd$signs * exp(lt - top) + if (!all(is.finite(sw)) || sum(sw) <= 0) return(r) + r$m2logZ <- -2 * (top + log(sum(sw))) + .spikePriorNorm(pr, r$on) + length(r$on) * log(2 * pi) + r$nodes <- nd$eta + r$logW <- nd$logW + r$signs <- nd$signs + r$omega <- sw / sum(sw) + r$indices <- gr$indices + r$level <- gr$level + r$quadConverged <- !gr$capped + r + }, rs, grids) +} + +## All subsets of `n` items as logical rows. +.subsets <- function(n) { + if (!n) return(matrix(FALSE, 1L, 0L)) + 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) { + 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) { + slab <- unname(E[g, stems]) + nrm <- unname(E[g, nstems]) + etas <- c(slab, nrm) + mu <- setNames(lay$mean, slab) + # the spike of the slab etas, the normal ones are always integrated + alpha <- setNames(c(lay$spike, rep(0, length(nrm))), etas) + tauG <- setNames(hyp$tau[stems], slab) + probG <- setNames(hyp$prob[stems], slab) + pr <- .spikePriorOf(mu, tauG, nrm, omega$Oinv, omega$logdetO) + cand <- unname(E[g, stems[reach[g, stems]]]) + keyOf <- function(on) paste(on, collapse = ",") + startOf <- function(on) { + v <- alpha + v[nrm] <- 0 + v[on] <- warm[[g]][[keyOf(on)]] %||% c(mu, setNames(rep(0, length(nrm)), nrm))[on] + v + } + 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 + ec <- .spikeECGroup(design, objs, g, theta, fixed, etas, cand, nrm, pr, alpha, probG, + setNames(lbStem, slab), start, control) + if (is.null(ec)) + stop("em: the expectation consistent (EC) approximation of group ", g, " did not converge.", call. = FALSE) + on <- c(nrm, ec$on) + r <- .spikeSubset(design, objs, g, theta, fixed, etas, on, pr, startOf(on)) + if (is.null(r)) stop("em: the inner search of group ", g, " failed.", call. = FALSE) + r$on <- on + 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))) + } + S <- .subsets(length(cand)) + 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 + }) + parts <- Filter(Negate(is.null), parts) + if (!length(parts)) stop("em: no subset of the spike-and-slab random effects of group ", g, + " has a finite integral.", call. = FALSE) + lw <- vapply(parts, `[[`, 0, "logw") + sel <- which(lw >= max(lw) - log(1e8) & vapply(parts, function(p) length(p$on) > 0L, TRUE)) + if (!is.null(quadrature) && length(sel)) { + # the subsets of non-negligible Laplace weight by quadrature, the others keep the Laplace value + keys <- vapply(parts[sel], function(p) keyOf(p$on), "") + qs <- .spikeQuadrature(design, g, theta, fixed, etas, parts[sel], pr, alpha, + exp(lw[sel] - max(lw)), lapply(keys, function(k) gridWarm[[g]][[k]]), + modifyList(quadrature, list(tol = (quadrature$tol %||% 0.1) / length(design$groups)))) + for (k in seq_along(sel)) { + qs[[k]]$logw <- qs[[k]]$logw + (parts[[sel[k]]]$m2logZ - qs[[k]]$m2logZ) / 2 + parts[[sel[k]]] <- qs[[k]] + } + 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) + }) +} + +## 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. +.spikeNormalMoments <- function(est) { + lapply(est, function(e) { + q <- e$normal + if (!is.null(e$ec)) return(e$ec$normalMoment) + Reduce(`+`, lapply(e$parts, function(p) { + j <- match(q, p$on) + p$weight * (tcrossprod(p$mode[q]) + p$cov[j, j, drop = FALSE]) + })) + }) +} + +## Omega^-1 and log|Omega| from the Cholesky parameters in `pars`. +.spikeOmega <- function(design, pars) { + if (!design$normal$K) return(NULL) + L <- .choleskyFactor(design$normal, pars) + 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) { + 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) + 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]) + } + for (p in if (is.null(e$ec)) e$parts) { + on <- .intersect(p$on, own) + if (!length(on)) next + j <- match(on, p$on) + num <- num + p$weight * sum((p$mode[on] - e$mu[on])^2 + diag(p$cov)[j]) + den <- den + p$weight * length(on) + } + # an eta off the group data keeps the slab of the prior + blind <- .setdiff(own, e$cand) + 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) + } + hyp +} + +## 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. +.spikeM <- function(design, objs, est, extra, lay, hyp, omega) { + items <- list() + for (g in names(est)) { + e <- est[[g]] + pr <- .spikePriorOf(e$mu, setNames(hyp$tau[lay$stem], e$slab), e$normal, omega$Oinv, omega$logdetO) + for (p in e$parts) { + if (p$weight < 1e-8) next + k <- length(items) + 1L + copies <- if (length(p$on)) paste0(".s", k, ".", p$on) else character(0) + 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) + } + } + init <- unlist(lapply(items, function(it) setNames(it$mode, it$copies))) + objfun <- function(pars, fixed = NULL, deriv = TRUE, ...) { + th <- .setdiff(names(pars), names(init)) + n <- length(pars) + val <- 0 + gr <- setNames(numeric(n), names(pars)) + H <- matrix(0, n, n, dimnames = list(names(pars), names(pars))) + for (it in items) { + conds <- design$conditions[[it$g]] + local <- c(pars[th], setNames(pars[it$copies], it$on)) + outs <- .objEvalMany(objs[conds], rep(list(local), length(conds)), deriv = deriv, fixed = c(fixed, it$off)) + out <- Reduce(`+`, outs) + prior <- .spikePriorTerm(it$pr, local[it$on]) + val <- val + it$w * (out$value + prior$value) + if (!deriv) next + map <- setNames(c(th, it$copies), c(th, it$on)) + gl <- out$gradient[names(local)] + gl[it$on] <- gl[it$on] + prior$gradient[it$on] + gr[map[names(local)]] <- gr[map[names(local)]] + it$w * gl + Hl <- as.matrix(out$hessian)[names(local), names(local)] + if (length(it$on)) Hl[it$on, it$on] <- Hl[it$on, it$on] + prior$hessian[it$on, it$on] + idx <- map[names(local)] + H[idx, idx] <- H[idx, idx] + it$w * Hl + } + out <- objlist(value = val, gradient = gr, hessian = H) + if (!is.null(extra) && length(th)) { + ex <- extra(pars[th], fixed = fixed, deriv = deriv) + out$value <- out$value + ex$value + if (deriv) { + out$gradient[th] <- out$gradient[th] + ex$gradient[th] + out$hessian[th, th] <- out$hessian[th, th] + as.matrix(ex$hessian)[th, th] + } + } + out + } + list(objfun = objfun, init = init) +} + +## -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) { + nl <- design$normal + groups <- lapply(names(est), function(g) { + e <- est[[g]] + rows <- list(); logW <- numeric(0); signs <- numeric(0); subset <- list() + for (p in e$parts) { + if (p$weight < 1e-12) next + if (!is.null(p$nodes)) { + for (i in seq_len(nrow(p$nodes))) { + v <- e$alpha; v[p$on] <- p$nodes[i, p$on] + rows[[length(rows) + 1L]] <- v + subset[[length(subset) + 1L]] <- p$on + } + logW <- c(logW, p$logW); signs <- c(signs, p$signs) + next + } + v <- e$alpha; v[p$on] <- p$mode + rows[[length(rows) + 1L]] <- v + subset[[length(subset) + 1L]] <- p$on + d <- length(p$on) + logW <- c(logW, if (d) d / 2 * log(2 * pi) - 0.5 * as.numeric(determinant(p$prec)$modulus) else 0) + signs <- c(signs, 1) + } + list(g = g, eta = do.call(rbind, rows), logW = logW, signs = signs, subset = subset, e = e) + }) + probFree <- .intersect(lay$probName, hypers) + tauFree <- .intersect(lay$tauName, hypers) + cholFree <- names(omegaPars) + tn <- names(theta) + shift <- if (nl$K) .referenceShift(design) else list(pars = character(0)) + refAll <- .intersect(shift$pars, tn) + beta0 <- theta[refAll] + init <- c(theta, omegaPars, setNames(log(hyp$tau[lay$stem[match(tauFree, lay$tauName)]]), tauFree), + setNames(stats::qlogis(hyp$prob[lay$stem[match(probFree, lay$probName)]]), probFree)) + back <- function(arg) { + h <- hyp + for (n in tauFree) h$tau[lay$stem[lay$tauName == n]] <- exp(arg[[n]]) + for (n in probFree) h$prob[lay$stem[lay$probName == n]] <- stats::plogis(arg[[n]]) + list(theta = arg[tn], omegaPars = arg[cholFree], hyp = h) + } + objfun <- function(pars, deriv = TRUE, ...) { + all <- c(pars, fixed) + act <- names(pars) + Q <- length(act) + total <- 0 + gr <- setNames(numeric(Q), act) + H <- matrix(0, Q, Q, dimnames = list(act, act)) + h <- back(c(init[.setdiff(names(init), act)], pars))$hyp + L <- if (nl$K) .choleskyFactor(nl, all) + thA <- .intersect(tn, act) + refA <- .intersect(refAll, act) + dataA <- .setdiff(thA, refAll) + # the data see phi at the rebuild point: the referenced fixed effects at beta0, the etas frozen + base <- all[.intersect(names(all), c(tn, names(fixed)))] + base[refAll] <- beta0 + for (G in groups) { + e <- G$e + B <- nrow(G$eta) + full <- lapply(seq_len(B), function(b) c(base, G$eta[b, ])) + data <- .spikeNodes(design, G$g, full, if (deriv) dataA else character(0)) + logInt <- G$logW - data$value / 2 + g1 <- if (deriv) matrix(0, B, Q, dimnames = list(NULL, act)) + h1 <- if (deriv) array(0, c(B, Q, Q), dimnames = list(NULL, act, act)) + if (deriv && length(dataA)) { + g1[, dataA] <- -data$gradient[, dataA, drop = FALSE] / 2 + h1[, dataA, dataA] <- -data$hessian[, dataA, dataA, drop = FALSE] / 2 + } + if (nl$K) { + ch <- .intersect(cholFree, act) + etaN <- G$eta[, e$normal, drop = FALSE] + D <- if (length(refAll)) shift$D[[G$g]][, refAll, drop = FALSE] + if (length(refAll)) etaN <- etaN - matrix(drop(D %*% (all[refAll] - beta0)), B, nl$K, byrow = TRUE) + pa <- c(refA, ch) + pr <- .nodePrior(nl, L, etaN, D, refA, ch, deriv && length(pa) > 0L) + logInt <- logInt + pr$value + if (deriv && length(pa)) { + g1[, pa] <- g1[, pa] + pr$gradient[, pa, drop = FALSE] + h1[, pa, pa] <- h1[, pa, pa] + pr$hessian[, pa, pa, drop = FALSE] + } + } + inCand <- e$slab %in% e$cand + prob <- h$prob[lay$stem] + 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]] + logInt[b] <- logInt[b] + sum(-0.5 * log(2 * pi) - log(tau) - dev2 / 2) + + sum(ifelse(z, log(prob), log1p(-prob))[inCand]) + if (!deriv) next + for (n in .intersect(tauFree, act)) { + k <- lay$tauName[match(st, lay$stem)] == n + g1[b, n] <- g1[b, n] + sum(-1 + dev2[k]) + h1[b, n, n] <- h1[b, n, n] - 2 * sum(dev2[k]) + } + for (n in .intersect(probFree, act)) { + k <- lay$probName == n & inCand + r <- unname(prob[k]) + g1[b, n] <- g1[b, n] + sum(z[k] - r) + h1[b, n, n] <- h1[b, n, n] - sum(r * (1 - r)) + } + } + ns <- .nodeSum(logInt, G$signs, matrix(0, B, 1, dimnames = list(NULL, "z")), "z", g1, h1) + if (is.null(ns)) return(objlist(value = Inf, gradient = gr, hessian = H)) + total <- total - 2 * ns$logL + if (deriv) { gr <- gr + ns$gradient[act]; H <- H + ns$hessian[act, act] } + } + out <- objlist(value = total, gradient = gr, hessian = H) + if (!is.null(extra) && length(thA)) { + ex <- extra(pars[thA], fixed = fixed, deriv = deriv) + out$value <- out$value + ex$value + if (deriv) { + n <- names(ex$gradient) + out$gradient[n] <- out$gradient[n] + ex$gradient + out$hessian[n, n] <- out$hessian[n, n] + as.matrix(ex$hessian) + } + } + out + } + list(objfun = objfun, init = init, back = back) +} + +## 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. +.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))) + stop("em: spikeSlab() with `mean` or `spike` other than 0, or with method = \"quadrature\", is fitted ", + "beside normal random effects only.", call. = FALSE) + lay <- .spikeLayout(design) + objs <- .conditionObjectives(design) + extra <- .extraObjective(design) + hypers <- .intersect(c(lay$probName, lay$tauName), names(start)) + cholPars <- design$normal$cholPars + given <- c(start, fixed) + value <- function(col, name) setNames(ifelse(is.na(lay[[col]]), unname(given[lay[[name]]]), lay[[col]]), lay$stem) + st <- new.env() + 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 + bases <- .spikeBases(design) + 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))) + st$gridWarm <- lapply(est, function(e) setNames(lapply(e$parts, `[[`, "indices"), keyOf(e))) + est + } + record <- function(stage, k, value, delta) { + st$rows[[length(st$rows) + 1L]] <- data.frame(stage = stage, 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 + 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)] + } + 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 + } + stopReason <- if (conv) "converged" else "iterlim" + + # 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) + ev <- fr$objfun(fr$init) + dec <- .newtonDecrement(ev) + record("quadrature", 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, + iterlim = quadrature$maxCm1Iter %||% 30L))) + b <- fr$back(m$argument) + st$theta <- b$theta; st$omegaPars[] <- b$omegaPars; st$hyp <- b$hyp + } + } + + est <- eStep(quadrature) + theta <- st$theta; hyp <- st$hyp + total <- sum(vapply(est, `[[`, 0, "m2logI")) + 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)) + cov <- list() + for (gi in seq_along(design$groups)) { + e <- est[[gi]] + best <- e$parts[[which.max(vapply(e$parts, `[[`, 0, "weight"))]] + v <- e$alpha + v[best$on] <- best$mode + modes[gi, match(e$etas, E[gi, ])] <- v + sc <- match(e$slab, E[gi, ]) + clusters[gi, sc] <- as.numeric(e$slab %in% best$on) + spike[gi, sc] <- pmin(pmax(1 - e$inclusion, 0), 1) + C <- matrix(0, ncol(E), ncol(E), dimnames = list(colnames(E), colnames(E))) + k <- match(best$on, E[gi, ]) + C[k, k] <- best$cov + cov[[gi]] <- C + } + hyperValues <- c(setNames(hyp$prob[lay$stem], lay$probName), setNames(hyp$tau[lay$stem], lay$tauName)) + capped <- !unlist(lapply(est, function(e) lapply(e$parts, function(p) p$quadConverged %||% TRUE))) + if (!is.null(quadrature) && any(capped)) + warning("em: the quadrature of a subset reached maxLevel before tol.", call. = FALSE) + 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)) +} diff --git a/R/normL2reverse.R b/R/normL2reverse.R index 8f07fa38..7f265b2c 100644 --- a/R/normL2reverse.R +++ b/R/normL2reverse.R @@ -1,5 +1,4 @@ ## normL2 backwards -------------------------------------------------------- -## Copyright (C) 2026 Simon Beyer ## Values forward, the objective's derivative in them pulled back through the ## chain: one sweep instead of n_theta. Every data row seeds both prediction and @@ -33,14 +32,7 @@ cn_eval <- character(0) if (!is.null(errmodel)) { cn_eval <- if (is.null(e.cond)) conditions else .intersectU(conditions, e.cond) - fixed_names <- names(fixed) - split <- lapply(cn_eval, function(cn) { - pinner <- getParameters(prediction[[cn]]) - own <- attr(pinner, "fixed") - fixedinner <- pinner[c(own, .setdiffU(.intersectU(names(pinner), fixed_names), own))] - list(pars = as.parvec(pinner[.setdiffU(names(pinner), fixed_names)]), - fixed = as.parvec(fixedinner, deriv = FALSE, deriv2 = FALSE)) - }) + split <- lapply(cn_eval, function(cn) .errorModelArgs(prediction[[cn]], fixed)) err_pars <- lapply(split, `[[`, "pars") err_fixed <- lapply(split, `[[`, "fixed") eb <- .bundle(conds = cn_eval, diff --git a/R/objClass.R b/R/objClass.R index a5605500..09572244 100644 --- a/R/objClass.R +++ b/R/objClass.R @@ -67,13 +67,8 @@ evalConditionResidual <- function(dataI, predictionI, if (!is.null(errfn) && (is.null(eCondNames) || cn %in% eCondNames)) { if (is.null(cn)) stop("evalConditionResidual: `cn` must be supplied when `errfn` is set.") - pinner <- getParameters(predictionI) - # the `fixed` marker is empty without sensitivities, so the outer names count too - fixedinner <- pinner[union(attr(pinner, "fixed"), - intersect(names(pinner), names(fixed)))] - pinner <- as.parvec(pinner[setdiff(names(pinner), names(fixed))]) - fixedinner <- as.parvec(fixedinner, deriv = FALSE, deriv2 = FALSE) - err_cn <- errfn(out = predictionI, pars = pinner, fixed = fixedinner, + ea <- .errorModelArgs(predictionI, fixed) + err_cn <- errfn(out = predictionI, pars = ea$pars, fixed = ea$fixed, deriv = deriv, deriv2 = deriv2, conditions = cn)[[cn]] } @@ -462,16 +457,7 @@ normT <- function(data, x, errmodel = NULL, df, times = NULL, attrName = "data", attr(pr, "sigma", exact = TRUE)$frame) } else if (!is.null(errmodel)) { cn_eval <- if (is.null(e.cond)) conditions else intersect(conditions, e.cond) - split <- lapply(cn_eval, function(cn) { - pinner <- getParameters(prediction[[cn]]) - # The `fixed` marker is derived from the sensitivity rows, so it is - # empty under deriv = FALSE. Fall back to the outer fixed names, or - # the error model loses those parameters entirely. - fixedinner <- pinner[union(attr(pinner, "fixed"), - intersect(names(pinner), names(fixed)))] - list(pars = as.parvec(pinner[setdiff(names(pinner), names(fixed))]), - fixed = as.parvec(fixedinner, deriv = FALSE, deriv2 = FALSE)) - }) + split <- lapply(cn_eval, function(cn) .errorModelArgs(prediction[[cn]], fixed)) est <- .fnNode(errmodel) got <- if (!is.null(est) && length(cn_eval) > 1L) { b <- .bundle(conds = cn_eval, @@ -1346,6 +1332,7 @@ datapointL2 <- function(name, time, parameter, sigma = 1, #' each. #' @return An [objlist]. #' @aliases sumobjlist +#' @example inst/examples/objlist.R #' @export #' "+.objlist" <- function(e1, e2) { @@ -1571,6 +1558,7 @@ summary.objfn <- function(object, ...) { #' missing on the input. #' #' @seealso [objframe()], [normL2()] +#' @example inst/examples/res.R #' @export res <- function(data, out, err = NULL) { @@ -1733,6 +1721,7 @@ objlist <- function(value, gradient, hessian) { #' When `deriv2`/`deriv2.err` are supplied, the corresponding 3D arrays are #' attached as `"deriv2"` / `"deriv2.err"`. #' +#' @example inst/examples/res.R #' @export objframe <- function(mydata, deriv = NULL, deriv.err = NULL, deriv2 = NULL, deriv2.err = NULL) { diff --git a/R/odeClass.R b/R/odeClass.R index 227860a3..b7cfbb9c 100644 --- a/R/odeClass.R +++ b/R/odeClass.R @@ -217,7 +217,7 @@ odemodel <- function(f, derivMode = "forward", as.eventlist(events.func), stringsAsFactors = FALSE) } else { - events <- do.call(rbind, lapply(1:nrow(events.func), function(i) { + events <- do.call(rbind, lapply(seq_len(nrow(events.func)), function(i) { rbind( as.eventlist(events.sens[[i]]), as.eventlist(events.func[i,]), diff --git a/R/parClass.R b/R/parClass.R index 4b9e746e..b4699f4b 100644 --- a/R/parClass.R +++ b/R/parClass.R @@ -117,7 +117,7 @@ plot.parlist <- function(x, path = FALSE, ...) { end <- do.call(rbind, lapply(fits, `[[`, "argument")) frame <- data.frame(parameter = rep(colnames(start), each = nrow(start)), x = as.vector(start), y = as.vector(end), run = 1) - ggplot(frame, aes(x = x, y = y)) + geom_point() + facet_wrap(~parameter) + .ggplotDMod2(frame, aes(x = x, y = y)) + geom_point() + facet_wrap(~parameter) } # Iterates of every fit, one line per fit and one panel per parameter @@ -131,7 +131,7 @@ plot.parlist <- function(x, path = FALSE, ...) { iteration = rep(seq_len(nrow(iterates)), length(pars)), path = as.vector(iterates), idx = as.character(i)) }) - ggplot(do.call(rbind, steps), aes(x = iteration, y = path, color = idx)) + + .ggplotDMod2(do.call(rbind, steps), aes(x = iteration, y = path, color = idx)) + geom_line() + facet_wrap(~parameter) } @@ -218,6 +218,7 @@ c.parlist <- function(...) { #' attribute `"run"` of the parlist is kept. #' @seealso [parframe()], [as.parvec.parframe()], and [parlist()] for an #' example. +#' @example inst/examples/parlist.R #' @export as.parframe <- function(x, ...) { UseMethod("as.parframe", x) @@ -238,6 +239,7 @@ as.parframe <- function(x, ...) { #' and that fit did not converge. #' @seealso [as.parframe()], [parvec()] #' +#' @example inst/examples/parlist.R #' @export as.parvec.parframe <- function(x, index = 1, ...) { if (length(index) != 1L || is.na(index) || index < 1 || index > nrow(x)) @@ -515,7 +517,7 @@ plotValues.list <- function(x, ..., tol = 1, showSteps = FALSE, pseudoLog = FALS labels <- c("optimum", .profileLineLabels(threshold)[keep]) threshold <- c(0, threshold[keep]) - p <- ggplot(data, aes(x = par, y = delta, group = interaction(proflist, mode), + p <- .ggplotDMod2(data, aes(x = par, y = delta, group = interaction(proflist, mode), color = proflist, linetype = mode)) + facet_wrap(~name, scales = "free_x", ncol = ncol) + geom_hline(yintercept = threshold, lty = 2, color = "gray") + @@ -649,6 +651,7 @@ rbind.parframe <- function(..., deparse.level = 1) { #' @param ... Not used. Select rows first with [`subset()`][subset.parframe], as in #' `unique(subset(x, converged))`. #' @return The rows of `x` with distinct values, sorted by value. +#' @example inst/examples/parlist.R #' @export unique.parframe <- function(x, incomparables = FALSE, tol = 1, ...) { if (!nrow(x)) return(x) @@ -728,6 +731,7 @@ as.parvec.numeric <- function(x, names = NULL, deriv = NULL, deriv2 = NULL, ...) #' @param x object of class `parvec`. #' @param ... not used. #' @return `x`, invisibly. +#' @example inst/examples/parvec.R #' @export print.parvec <- function(x, ...) { @@ -765,6 +769,7 @@ print.parvec <- function(x, ...) { #' #' @return Object of class `parvec`. #' +#' @example inst/examples/parvec.R #' @export "[.parvec" <- function(x, ..., drop = FALSE) { @@ -829,6 +834,7 @@ print.parvec <- function(x, ...) { #' #' @return Object of class `parvec`. #' +#' @example inst/examples/parvec.R #' @export c.parvec <- function(...) { @@ -952,6 +958,7 @@ c.parvec <- function(...) { #' @param ... not used. #' @return `x`, invisibly. #' +#' @example inst/examples/P.R #' @export print.parfn <- function(x, ...) { @@ -980,7 +987,7 @@ summary.parfn <- function(object, ...) { if (!inherits(x, "composed")) { - output <- lapply(1:length(mappings), function(C) { + output <- lapply(seq_along(mappings), function(C) { list( equations = attr(mappings[[C]], "equations"), diff --git a/R/parameters.R b/R/parameters.R index 3f222d93..fc58d3f5 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -891,7 +891,6 @@ Pimpl <- function(trafo, parameters = NULL, forcings = NULL, condition = NULL, cons <- if (length(tn)) setNames(paste0("(", unlist(norm$totals), ") - ", tn), tn) else character(0) all_exprs <- c(unclass(norm$trafo[dependent]), cons) - n_eq <- length(all_exprs) parms_all <- intersect(norm$parms_all, getSymbols(all_exprs)) PEval <- suppressWarnings(cppDE::cppFUN( diff --git a/R/plots.R b/R/plots.R index 1975b6cd..b55554da 100644 --- a/R/plots.R +++ b/R/plots.R @@ -306,7 +306,8 @@ scale_fill_dMod2_div <- function(mid = 0, ..., direction = 1, palette = "okabe") } -ggplot <- function(...) ggplot2::ggplot(...) + scale_color_dMod2() + theme_dMod2() +# ggplot2::ggplot() with the dMod2 color scale and theme +.ggplotDMod2 <- function(...) ggplot2::ggplot(...) + scale_color_dMod2() + theme_dMod2() # Transformation of plotted values --------------------------------------- @@ -758,8 +759,7 @@ plotResiduals.default <- function(parframe, x, data, split = "condition", out <- as.data.frame(sums[, list(res = sum(res)), keyby = split]) colorBy <- as.name(split[min(2L, length(split))]) - p <- ggplot(out, aes(!!as.name(split[1]), res, color = !!colorBy, group = !!colorBy)) + - theme_dMod2() + + p <- .ggplotDMod2(out, aes(!!as.name(split[1]), res, color = !!colorBy, group = !!colorBy)) + geom_point() + geom_line() if (length(split) > 2L) p <- p + facet_wrap(split[-(1:2)]) @@ -782,23 +782,6 @@ plotResiduals.default <- function(parframe, x, data, split = "condition", plotTrace <- function(x, ...) UseMethod("plotTrace", x) - - -#' Pair Plot of Parameter Samples -#' -#' Generic for a corner plot of sampled parameters: scatter plots of pairs in -#' the lower triangle, marginal densities on the diagonal. dMod2 defines no -#' method for it; packages and extensions that return samples do. -#' -#' @param x Object holding parameter samples. -#' @param ... Method-specific arguments. -#' @return A `ggplot` object, as returned by the method. -#' @export -plotPairs <- function(x, ...) UseMethod("plotPairs", x) - - - - ## ---- profile / parameter-path plotting --------- #' Plot an Array of Trajectories Along the Profile of a Parameter #' @@ -972,6 +955,8 @@ plotPathsMulti <- function(profs, whichPar, nPars = 5, normalizePaths = FALSE) { #' absolute value of 1. Defaults to `FALSE`. #' @param modes Character vector, the contributions to the objective drawn in #' the profile plot besides the total. Defaults to `c("data", "prior")`. +#' @param maxvalue,threshold Cut-off of the objective difference and the +#' horizontal lines above the optimum, as in [plotProfile()]. #' @param ... Further arguments passed to [cowplot::plot_grid()]. #' #' @return A `ggplot` object, the grid of [cowplot::plot_grid()]. @@ -986,38 +971,39 @@ plotPathsMulti <- function(profs, whichPar, nPars = 5, normalizePaths = FALSE) { #' @export plotProfilesAndPaths <- function(profs, whichPar, nPars = 5, ncol = 3, normalizePaths = FALSE, - modes = c("data", "prior"), ...) { + modes = c("data", "prior"), maxvalue = 5, + threshold = .profileLines(), ...) { dots <- list(...) .require_ns("cowplot", "plotProfilesAndPaths()") # Save original obj.attributes before any subsetting drops them - orig_oa <- attr(profs, "obj.attributes") - filtered_oa <- if (!is.null(orig_oa)) intersect(orig_oa, modes) else NULL + origAttr <- attr(profs, "obj.attributes") + keptAttr <- if (!is.null(origAttr)) intersect(origAttr, modes) else NULL profs <- profs[profs$whichPar %in% whichPar, ] - cleanProfilePlot <- function(prof_sub) { + cleanProfilePlot <- function(profSub) { # Remove columns for unwanted modes, so plotProfile cannot plot them - cols_to_drop <- setdiff(orig_oa, modes) - prof_sub <- prof_sub[, !(colnames(prof_sub) %in% cols_to_drop), drop = FALSE] - attr(prof_sub, "obj.attributes") <- filtered_oa - p <- plotProfile(prof_sub) + dropCols <- setdiff(origAttr, modes) + profSub <- profSub[, !(colnames(profSub) %in% dropCols), drop = FALSE] + attr(profSub, "obj.attributes") <- keptAttr + p <- plotProfile(profSub, maxvalue = maxvalue) # the total and the requested contributions pdata <- attr(p, "data") pdata <- pdata[pdata$mode %in% c("total", modes), , drop = FALSE] - threshold <- c(1, 2.7, 3.84) - p_new <- ggplot(pdata, aes(x = par, y = delta, group = interaction(proflist, mode), - color = proflist, linetype = mode)) + + keep <- threshold != 0 + labels <- c("optimum", .profileLineLabels(threshold)[keep]) + lines <- c(0, threshold[keep]) + .ggplotDMod2(pdata, aes(x = par, y = delta, group = interaction(proflist, mode), + color = proflist, linetype = mode)) + facet_wrap(~name, scales = "free_x") + - geom_hline(yintercept = threshold, lty = 2, color = "gray") + + geom_hline(yintercept = lines, lty = 2, color = "gray") + geom_line() + geom_point(data = subset(pdata, is.zero)) + ylab(expression(paste("CL /", Delta * chi^2))) + - scale_y_continuous(breaks = c(1, 2.7, 3.84), - labels = c("68% / 1 ", "90% / 2.71", "95% / 3.84"), - limits = c(NA, 5)) + + scale_y_continuous(breaks = lines, labels = labels, limits = c(NA, maxvalue)) + xlab("parameter value") + labs(title = NULL, x = NULL, linetype = "contrib") + theme( @@ -1031,23 +1017,20 @@ plotProfilesAndPaths <- function(profs, whichPar, nPars = 5, ncol = 3, theme(legend.position = "none") } - stacked_list <- vector("list", length(whichPar)) + stacked <- vector("list", length(whichPar)) for (z in seq_along(whichPar)) { - prof_sub <- profs[profs$whichPar == whichPar[z], ] + profSub <- profs[profs$whichPar == whichPar[z], ] - p_prof_noleg <- cleanProfilePlot(prof_sub) + pProfile <- cleanProfilePlot(profSub) - p_paths <- plotPathsMulti(prof_sub, whichPar[z], nPars, normalizePaths = normalizePaths) + + pPaths <- plotPathsMulti(profSub, whichPar[z], nPars, normalizePaths = normalizePaths) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) - aligned_pair <- cowplot::align_plots(p_prof_noleg, p_paths, align = "v", axis = "tb") - stacked_list[[z]] <- cowplot::plot_grid(aligned_pair[[1]], aligned_pair[[2]], - ncol = 1, rel_heights = c(1, 0.7), align = "v", axis = "tb") + aligned <- cowplot::align_plots(pProfile, pPaths, align = "v", axis = "tb") + stacked[[z]] <- cowplot::plot_grid(aligned[[1]], aligned[[2]], ncol = 1, rel_heights = c(1, 0.7), + align = "v", axis = "tb") } - body <- do.call(cowplot::plot_grid, - c(list(plotlist = stacked_list, ncol = ncol), dots)) - - return(body) + do.call(cowplot::plot_grid, c(list(plotlist = stacked, ncol = ncol), dots)) } diff --git a/R/plotsEM.R b/R/plotsEM.R index f0a2906d..d5a3242f 100644 --- a/R/plotsEM.R +++ b/R/plotsEM.R @@ -1,4 +1,4 @@ -## NLME plotting and prediction methods for `em` fits. +## Plot methods for `em` fits. utils::globalVariables(c("IPRED", "PRED", "eta", "part", "xmin", "xmax", "ymin", "ymax", "inclusion", "label", "group", "estimate", "lower", "upper", "fit", "position", "width")) @@ -295,6 +295,9 @@ plotRandomEffects.em <- function(x, type = c("conditional", "modes", "inclusion" ## `draws` per group from the conditional mixture of 0 and a normal with the conditional variance; ## NULL for a fit without spike-and-slab random effects. .spikeSlabValues <- function(fit, type, draws) { + if (any(vapply(fit$design$blocks, function(b) b$dist == "spikeSlab" && (b$mean != 0 || b$spike != 0), TRUE))) + stop("plotRandomEffects: the mixture panels take spikeSlab() with `mean` and `spike` 0 only; ", + "fit$random holds p0 and the modes.", call. = FALSE) pri <- .spikeSlabPriors(fit) r <- fit$random if (is.null(pri) || is.null(r$p0)) return(NULL) diff --git a/R/prdClass.R b/R/prdClass.R index 3ad41214..bddcb4d2 100644 --- a/R/prdClass.R +++ b/R/prdClass.R @@ -169,7 +169,7 @@ plotCombined.prdlist <- function(prediction, data = NULL, ..., grid = facet_grid(rows = vars(name), cols = vars(condition), scales = scales), wrap_plain = facet_wrap(vars(name, condition), scales = scales)) - p <- ggplot(plotted, aes(!!!lapply(mapping, rlang::parse_expr))) + panels + p <- .ggplotDMod2(plotted, aes(!!!lapply(mapping, rlang::parse_expr))) + panels # a legend of one condition says nothing if (identical(mapping$color, "condition") && length(conditions) == 1L) p <- p + guides(color = "none") if (!is.null(errfn) && !is.null(prediction)) { @@ -206,10 +206,10 @@ plotPrediction.prdlist <- function(prediction, ..., errfn = NULL, frame$condition <- factor(frame$condition, .naturalLevels(frame$condition)) p <- if (facet == "wrap") { - ggplot(frame, aes(time, value, group = condition, color = condition)) + + .ggplotDMod2(frame, aes(time, value, group = condition, color = condition)) + facet_wrap(vars(name), scales = scales) } else { - ggplot(frame, aes(time, value)) + + .ggplotDMod2(frame, aes(time, value)) + facet_grid(rows = vars(name), cols = vars(condition), scales = scales) } band <- if (!is.null(errfn)) @@ -286,7 +286,7 @@ summary.prdfn <- function(object,...) { cat("Details:\n") if (!inherits(x, "composed")) { - output <- lapply(1:length(mappings), function(C) { + output <- lapply(seq_along(mappings), function(C) { list( equations = attr(mappings[[C]], "equations"), @@ -334,7 +334,7 @@ summary.obsfn <- function(object, ...) { cat("Details:\n") if (!inherits(x, "composed")) { - output <- lapply(1:length(mappings), function(C) { + output <- lapply(seq_along(mappings), function(C) { list( equations = attr(mappings[[C]], "equations"), @@ -521,6 +521,7 @@ obsfn <- function(X2Y, parameters = NULL, condition = NULL) { #' @return Object of class `prdframe`, a matrix with the attributes above. #' @seealso [getDerivs()], [getDerivs2()] #' +#' @example inst/examples/prdframe.R #' @export prdframe <- function(prediction = NULL, deriv = NULL, @@ -546,6 +547,7 @@ prdframe <- function(prediction = NULL, #' are named `"1"`, `"2"`, ... For `as.prdlist()`, not used. #' @return Object of class `prdlist`. #' @seealso [prdfn()], [plotCombined()] +#' @example inst/examples/prdframe.R #' @export prdlist <- function(...) { mylist <- .fillNames(list(...), "") diff --git a/R/prediction.R b/R/prediction.R index 47a40c72..da6819dd 100644 --- a/R/prediction.R +++ b/R/prediction.R @@ -1028,6 +1028,7 @@ Xs.cppDE <- function(odemodel, forcings = NULL, events = NULL, names = NULL, con #' changed with [controls()]. #' @inheritSection dModfn Calling a dMod function #' @seealso [Xs()], [controls()] +#' @example inst/examples/Xf.R #' @export Xf <- function(odemodel, ...) { UseMethod("Xf", odemodel) @@ -1197,7 +1198,7 @@ Xf.cppDE <- function(odemodel, forcings = NULL, events = NULL, condition = NULL, #' # Generate a data.frame and corresponding prediction function #' timesD <- seq(0, 2*pi, 0.5) #' mydata <- data.frame(name = "A", time = timesD, value = sin(timesD), -#' row.names = paste0("par", 1:length(timesD))) +#' row.names = paste0("par", seq_along(timesD))) #' x <- Xd(mydata) #' #' # Evaluate the prediction function at different time points diff --git a/R/randomEffects.R b/R/randomEffects.R index 0026bc59..8decba2b 100644 --- a/R/randomEffects.R +++ b/R/randomEffects.R @@ -24,7 +24,11 @@ #' `(1 | p | ID)` with an ID `p`: terms with the same ID and grouping are #' correlated across formulas, the columns of one term are correlated, other #' terms are independent. `gr(ID, dist = spikeSlab())` instead of `ID` sets -#' the distribution, see [normal()]. The random effect of a group is +#' the distribution, see [normal()]; `gr(dist = )` without a grouping +#' makes one group `all` of all conditions, so that with `0 +` the random +#' effect is the parameter itself, as in +#' `k1 + k2 ~ 0 + (1 | gr(dist = spikeSlab(spike = -Inf)))` for the +#' selection of reaction rates on the log scale. The random effect of a group is #' `eta__` for the intercept and #' `eta___` for a slope; a symbol with random terms #' in a second grouping gets the grouping name in the stem, `eta_cl_center_`.} @@ -38,8 +42,8 @@ #' @return An object of class `randomeffects`, a list with `terms` (one row #' per random effect column: `symbol`, `origin` (the formula), `term`, #' `column`, `group`, `id`, `dist`, the fixed hyperparameters `prob`, -#' `concentration` and `tau` (`NA` where estimated) and `stem`, the name -#' stem of the etas), +#' `concentration` and `tau` (`NA` where estimated), the given `mean` and +#' `spike` of spike-and-slab terms and `stem`, the name stem of the etas), #' `blocks` (groups of rows: the normal rows of a block are correlated, the #' rows of a spike-and-slab or Dirichlet-process block share the #' hyperparameters), `subjects` (the groups of each @@ -70,7 +74,8 @@ print.randomeffects <- function(x, ...) { r <- tm[x$blocks[[b]], , drop = FALSE] given <- function(v) if (is.na(v)) "estimated" else format(v) dist <- switch(r$dist[1], normal = "normal", - spikeSlab = sprintf("spikeSlab, prob %s, tau %s", given(r$prob[1]), given(r$tau[1])), + 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])), 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 = ", "))) @@ -89,11 +94,12 @@ print.randomeffects <- function(x, ...) { #' #' - `normal()`: multivariate normal with mean 0 and a covariance estimated #' per correlation block. The default. -#' - `spikeSlab()`: the deviation of a group is exactly 0 (spike) or drawn -#' from \eqn{N(0, \tau^2)}{N(0, tau^2)} (slab); every group deviates with -#' probability `prob`, independently. The spike-and-slab random effects of -#' a group are integrated jointly, see section Sparse random effects of -#' [em()]. +#' - `spikeSlab()`: the deviation of a group is exactly `spike` (spike) or +#' drawn from \eqn{N(\mu, \tau^2)}{N(mean, tau^2)} (slab); every group +#' deviates with probability `prob`, independently. The spike-and-slab +#' random effects of a group are integrated jointly, see section Sparse +#' random effects of [em()]. With `spike = -Inf` under an exponential +#' transformation, the spike switches the parameter off. #' - `dirichletProcess()`: per symbol, the deviations follow a Dirichlet #' process with base measure \eqn{N(0, \tau^2)}{N(0, tau^2)} and #' `concentration`, the fixed effect seated first at deviation 0: the @@ -112,6 +118,10 @@ print.randomeffects <- function(x, ...) { #' @param concentration Concentration of the Ewens prior, positive; `NULL` #' (default) estimates it. #' @param tau Standard deviation of the slab; `NULL` (default) estimates it. +#' @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 +#' of a numeric base greater than 1, as after `insert(trafo, "x <- exp(x)")`. #' @return An object of class `redist`. #' @seealso [randomEffects()], [insert()] #' @example inst/examples/normal.R @@ -120,11 +130,15 @@ normal <- function() .redist("normal") #' @export #' @rdname normal -spikeSlab <- function(prob = NULL, tau = NULL) { +spikeSlab <- function(prob = NULL, tau = NULL, mean = 0, spike = 0) { 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) - .redist("spikeSlab", prob = prob, tau = tau) + 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) } #' @export @@ -138,15 +152,16 @@ 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) +.redist <- function(dist, prob = NULL, concentration = NULL, tau = NULL, mean = 0, spike = 0) structure(list(dist = dist, prob = prob %||% NA_real_, concentration = concentration %||% NA_real_, - tau = tau %||% NA_real_), class = "redist") + tau = tau %||% NA_real_, mean = mean, spike = spike), class = "redist") #' @export print.redist <- function(x, ...) { arg <- function(v) if (is.na(v)) "NULL" else format(v) cat(switch(x$dist, normal = "normal()", - spikeSlab = sprintf("spikeSlab(prob = %s, tau = %s)", arg(x$prob), arg(x$tau)), + 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)), dirichletProcess = sprintf("dirichletProcess(concentration = %s, tau = %s)", arg(x$concentration), arg(x$tau))), "\n") invisible(x) @@ -221,7 +236,10 @@ print.redist <- function(x, ...) { origin = attr(f, "origin") %||% 1L)) } -## `expr | group`, `expr | id | group`; group a column, an interaction a:b or gr(group, dist = ). +## The group label of a random term without a grouping column, gr(dist = ): one group over all conditions. +.allGroup <- "all" + +## `expr | group`, `expr | id | group`; group a column, an interaction a:b, gr(group, dist = ) or gr(dist = ). .parseBar <- function(e, env) { id <- NA_character_ left <- e[[2]]; grp <- e[[3]] @@ -237,10 +255,15 @@ print.redist <- function(x, ...) { if (any(!nm %in% c("", "dist"))) stop("insert: gr() takes the grouping and `dist`, as in gr(ID, dist = spikeSlab()).", call. = FALSE) if ("dist" %in% nm) dist <- .evalDistribution(a[["dist"]], env) - grp <- a[[which(nm == "")[1]]] + grp <- if (any(nm == "")) a[[which(nm == "")[1]]] } + if (is.null(grp)) return(list(expr = stats::as.formula(call("~", left)), group = .allGroup, vars = character(0), + id = id, dist = dist)) vars <- all.vars(grp) - if (!length(vars)) stop("insert: a random term needs a grouping column.", call. = FALSE) + if (!length(vars)) stop("insert: a random term needs a grouping column, or gr(dist = ) for one group.", call. = FALSE) + if (identical(vars, .allGroup)) + stop("insert: the grouping `", .allGroup, "` is the label of gr(dist = ) without a grouping; rename the column.", + call. = FALSE) list(expr = stats::as.formula(call("~", left)), group = paste(vars, collapse = ":"), vars = vars, id = id, dist = dist) } @@ -294,9 +317,10 @@ print.redist <- function(x, ...) { random <- list() for (ti in seq_along(pf$random)) { rt <- pf$random[[ti]] - g <- do.call(paste, c(lapply(tree[rt$vars], as.character), sep = "_")) + g <- if (length(rt$vars)) do.call(paste, c(lapply(tree[rt$vars], as.character), sep = "_")) + else rep(.allGroup, nrow(tree)) # a condition with a missing grouping belongs to no group and keeps the fixed effects - none <- Reduce(`|`, lapply(tree[rt$vars], is.na)) + none <- Reduce(`|`, lapply(tree[rt$vars], is.na), rep(FALSE, nrow(tree))) g[none] <- NA_character_ .uniqueNames(g[!none], "groups of ", rt$group) Z <- stats::model.matrix(rt$expr, stats::model.frame(rt$expr, tree, na.action = stats::na.fail)) @@ -311,6 +335,7 @@ print.redist <- function(x, ...) { random[[length(random) + 1L]] <- list(symbol = sym, term = ti, column = zn[k], group = rt$group, 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, stem = stems[k], etas = ifelse(none, NA_character_, paste0(stems[k], "_", .effectName(g))), z = Z[, k], @@ -373,7 +398,7 @@ 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, - stem = r$stem, stringsAsFactors = FALSE) + mean = r$mean, spike = r$spike, stem = r$stem, stringsAsFactors = FALSE) terms <- rbind(terms, row) col <- setNames(rep(NA_character_, length(conds)), conds) col[rownames(tr)] <- r$etas @@ -409,7 +434,7 @@ 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), - stem = character(0)) + mean = numeric(0), spike = numeric(0), 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/reml.R b/R/reml.R index 6dc16d6b..92cec814 100644 --- a/R/reml.R +++ b/R/reml.R @@ -29,13 +29,9 @@ for (cn in conditions) { errout <- NULL if (!is.null(term$errfn)) { - pinner <- getParameters(prediction[[cn]]) - fixedinner <- pinner[attr(pinner, "fixed")] - errout <- term$errfn( - out = prediction[[cn]], - pars = as.parvec(pinner[setdiff(names(pinner), names(fixed))]), - fixed = as.parvec(fixedinner, deriv = FALSE, deriv2 = FALSE), - conditions = cn)[[cn]] + inner <- .errorModelArgs(prediction[[cn]], fixed) + errout <- term$errfn(out = prediction[[cn]], pars = inner$pars, fixed = inner$fixed, + conditions = cn)[[cn]] } frames <- c(frames, list(res(term$data[[cn]], prediction[[cn]], errout))) labels <- c(labels, if (length(spec) > 1L) paste0(t, ":", cn) else cn) @@ -48,6 +44,17 @@ } +# The inner parameters of a prediction as an error model takes them: `pars` without +# the outer `fixed`, and `fixed` those plus the ones the prediction marks fixed. The +# marker is empty without sensitivities, so the outer names always count. +.errorModelArgs <- function(prediction, fixed) { + pinner <- getParameters(prediction) + fixedinner <- pinner[.union(attr(pinner, "fixed"), .intersect(names(pinner), names(fixed)))] + list(pars = as.parvec(pinner[.setdiff(names(pinner), names(fixed))]), + fixed = as.parvec(fixedinner, deriv = FALSE, deriv2 = FALSE)) +} + + # The L2 terms of an objective. normL2() attaches one, "+" concatenates them. # The single prdfn/data/errfn handles are first-wins on composition, so they # only stand in when no term list is present. @@ -68,14 +75,14 @@ # Stack the per-row derivative blocks of every frame into one matrix over # `cols`, filling with zero where a term lacks a parameter. -.remlBlocks <- function(frames, which, cols) { +.remlBlocks <- function(frames, what, cols) { n <- vapply(frames, nrow, 0L) out <- matrix(0, sum(n), length(cols), dimnames = list(NULL, cols)) seen <- character(0) off <- 0L for (i in seq_along(frames)) { - d <- attr(frames[[i]], which) + d <- attr(frames[[i]], what) idx <- off + seq_len(n[i]) off <- off + n[i] if (is.null(d)) next diff --git a/R/remoteComputing.R b/R/remoteComputing.R index 6370426b..a698e54b 100644 --- a/R/remoteComputing.R +++ b/R/remoteComputing.R @@ -234,7 +234,7 @@ detectFreeCores <- function(machine = NULL) { ## machine had it, so the remote SUNDIALS must provide it too. lapack_check <- if (needsLapack) c( paste0("if [ -z \"$(Rscript -e '", cfgExpr(cfgFields("cvode_lapack_libs")), "')\" ]; then"), - " echo \"dMod: the model uses SUNDIALS' LAPACK dense solver, which the\" >&2", + " echo \"dMod2: the model uses SUNDIALS' LAPACK dense solver, which the\" >&2", " echo \" SUNDIALS of this machine lacks. Build one with\" >&2", " echo \" cppDE::installLibs() and reinstall cppDE here.\" >&2", " exit 1", @@ -344,7 +344,7 @@ detectFreeCores <- function(machine = NULL) { paste(c( "#!/bin/bash", - "# Generated by dMod: rebuilds the model shared object on this machine.", + "# Generated by dMod2: rebuilds the model shared object on this machine.", "# All path-valued compiler flags are resolved here, not on the submitting", "# machine, because the library trees differ.", "set -e", @@ -354,7 +354,7 @@ detectFreeCores <- function(machine = NULL) { "", "CPPDE_INC=$(Rscript -e 'cat(system.file(\"include\", package = \"cppDE\"))')", "if [ -z \"$CPPDE_INC\" ]; then", - " echo \"dMod: package 'cppDE' is not installed for the R on PATH here,\" >&2", + " echo \"dMod2: package 'cppDE' is not installed for the R on PATH here,\" >&2", " echo \" so the model sources cannot be rebuilt. Install it remotely\" >&2", " echo \" (remotes::install_github('dModverse/cppDE')) or submit with\" >&2", " echo \" compile = FALSE and link = FALSE.\" >&2", @@ -763,6 +763,13 @@ print.dMod2Target <- function(x, ...) { } .sleep <- function(seconds) Sys.sleep(seconds) +## Seconds between two polls of distributedComputing(wait = TRUE): 10 once ssh or the +## queue is asked, the default of wait(); 1 for a job on localhost only. +.pollInterval <- function(m) { + local <- !isTRUE(m$slurm) && all(vapply(m$hosts, .isLocalhost, NA)) + if (local) 1 else 10 +} + ## The results of the tasks joined: parlists by c(), parts of one msem() into one fit, data ## frames by rbind(), any other results as a list. Tasks without a result are left out with a warning. .combineResults <- function(out) { @@ -1242,7 +1249,7 @@ distributedComputing <- function(expr, tasks = NULL, on = localNode(), jobname = job <- .jobFunctions(m) if (!wait) return(job) - .waitTasks(m, 1) + .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)) diff --git a/R/reverse.R b/R/reverse.R index 5cf52b84..263cbd2d 100644 --- a/R/reverse.R +++ b/R/reverse.R @@ -1,5 +1,4 @@ ## Reverse-mode helpers ----------------------------------------------------- -## Copyright (C) 2026 Simon Beyer # A cotangent, `out` on the output matrix of the node and `pars` on the node parameters, optional and additive; # the trailing axis holds the cotangent and the directional derivatives, or K seeds, and `value` per seed the @@ -288,10 +287,9 @@ J <- attr(v, "deriv") # A missing Jacobian is an error, not a zero cotangent. if (is.null(J) || !is.matrix(J)) - stop("a transformation returned no Jacobian, so the backward pass has ", - "nothing to contract here. A preceding warning usually names the ", - "cause; Pimpl falls back to value only when the implicit ", - "function theorem cannot be applied at the current root.", + stop("a parameter transformation returned no Jacobian, which the reverse sweep ", + "needs. Pimpl() returns values only where the implicit function theorem ", + "does not apply at the root, see the preceding warning.", call. = FALSE) wv <- .pickCotangent(w, rownames(J)) u <- crossprod(J, wv) diff --git a/R/sanitize.R b/R/sanitize.R index 284d4409..4fe31d59 100644 --- a/R/sanitize.R +++ b/R/sanitize.R @@ -2,9 +2,8 @@ sanitizeConditions <- function(conditions) { - # The result names generated C sources and identifiers, so anything outside - # the C identifier alphabet has to go. `[[:punct:]]` is not enough: ICU counts - # `^` and `+` as symbols, and a non-ASCII condition name would survive it too. + # The result names generated C sources and identifiers: every run of + # characters outside the ASCII C identifier alphabet becomes one underscore. new <- str_replace_all(conditions, "[^A-Za-z0-9_]+", "_") return(new) diff --git a/R/sparse.R b/R/sparse.R index 82303cdf..006e8740 100644 --- a/R/sparse.R +++ b/R/sparse.R @@ -96,8 +96,8 @@ H <- .sparseOver(out$hessian, pnames) lr <- .lowrankOver(out$lowrank, pnames) if (is.null(lr)) return(list(hessian = H, lowrank = NULL)) - out <- setdiff(pnames, keep) - if (length(out) && any(lr$U[out, ] != 0)) return(list(hessian = .lowrankDense(H, lr), lowrank = NULL)) + outside <- setdiff(pnames, keep) + if (length(outside) && any(lr$U[outside, ] != 0)) return(list(hessian = .lowrankDense(H, lr), lowrank = NULL)) list(hessian = H, lowrank = .lowrankOver(lr, keep)) } diff --git a/R/statistics.R b/R/statistics.R index d79c6eb9..4d2e2c22 100644 --- a/R/statistics.R +++ b/R/statistics.R @@ -182,9 +182,9 @@ profile.objfn <- function(fitted, pars, whichPar, alpha = 0.05, stop("profile: whichPar must name or index parameters of pars.", call. = FALSE) # cores = c(pars = , conditions = ) splits the two axes; see mstrust(). - .cc <- .splitCores(cores, "pars") - coresConditions <- if (!is.null(.cc$conditions)) .sanitizeCores(.cc$conditions) - cores <- .sanitizeCores(min(length(whichPar), .cc$outer)) + cc <- .splitCores(cores, "pars") + coresConditions <- if (!is.null(cc$conditions)) .sanitizeCores(cc$conditions) + cores <- .sanitizeCores(min(length(whichPar), cc$outer)) folder <- "profiles-interRes" if (cautiousMode) dir.create(folder, showWarnings = FALSE) @@ -479,6 +479,9 @@ profile.function <- function(fitted, ...) profile.objfn(fitted, ...) #' #' @return A single number. #' @seealso [profile()][profile.objfn], [confint.parframe()] +#' @examples +#' profileThreshold(0.95) +#' profileThreshold(0.95, method = "F", n = 20, p = 3) #' @importFrom stats qf #' @export profileThreshold <- function(level = 0.95, method = c("chisq", "F"), @@ -545,7 +548,7 @@ confint.parframe <- function(object, parm = NULL, level = 0.95, ..., whichPar <- d[["whichPar"]][origin] # Define function to return constraint value where threshold is passed - get_xThreshold <- function(branch) { + crossing <- function(branch) { y <- branch[[val.column]] - d[[val.column]][origin] x <- branch[["constraint"]] @@ -557,24 +560,25 @@ confint.parframe <- function(object, parm = NULL, level = 0.95, ..., # If threshold exceeded, take closest points below and above threshold # and interpolate if (any(y > threshold)) { - i.above <- utils::head(which(y > threshold), 1) - i.below <- utils::tail(which(y < threshold), 1) - if (i.below > i.above) { + iAbove <- utils::head(which(y > threshold), 1) + iBelow <- utils::tail(which(y < threshold), 1) + if (iBelow > iAbove) { return(NA) } else { - slope <- (y[i.above] - y[i.below])/(x[i.above] - x[i.below]) - dy <- threshold - y[i.below] + slope <- (y[iAbove] - y[iBelow])/(x[iAbove] - x[iBelow]) + dy <- threshold - y[iBelow] dx <- dy/slope - x_threshold <- x[i.below] + dx - return(x_threshold) + xThreshold <- x[iBelow] + dx + return(xThreshold) } } - # If threshold not exceeded, - # take the last 20% of points (at least 3) an perform linear fit - n_last20 <- max(3, length(which(x - x[1] > 0.8 * (max(x) - x[1])))) - x <- tail(x, n_last20) - y <- tail(y, n_last20) + # Not reached: linear fit to the last 20 % of the points (at least 3), + # extrapolations beyond ten times the span of the whole branch are Inf + span <- max(x) - min(x) + nLast <- max(3, length(which(x - x[1] > 0.8 * (max(x) - x[1])))) + x <- tail(x, nLast) + y <- tail(y, nLast) slope <- sum((x - mean(x))*(y - mean(y)))/sum((x - mean(x))^2) # If slope < 0, return Inf @@ -584,28 +588,24 @@ confint.parframe <- function(object, parm = NULL, level = 0.95, ..., # Extrapolate until threshold is passed dy <- threshold - tail(y, 1) dx <- dy/slope - x_threshold <- tail(x, 1) + dx - - # Test if extrapolation takes the point of passage very far - # Set to Inf in that case - if (x_threshold > 10*(max(x) - min(x))) - x_threshold <- Inf - - return(x_threshold) + xThreshold <- tail(x, 1) + dx - - } + if (xThreshold > 10 * span) + xThreshold <- Inf + + return(xThreshold) + } # Right profiles right <- d[d[["constraint"]] >= 0,] right <- right[order(right[["constraint"]]), ] - upper <- d[[whichPar]][origin] + get_xThreshold(right) + upper <- d[[whichPar]][origin] + crossing(right) # Left profile left <- d[d[["constraint"]] <= 0,] left[["constraint"]] <- - left[["constraint"]] left <- left[order(left[["constraint"]]), ] - lower <- d[[whichPar]][origin] - get_xThreshold(left) + lower <- d[[whichPar]][origin] - crossing(left) data.frame(name = whichPar, @@ -874,9 +874,9 @@ mstrust <- function(objfun, center, rinit = .1, rmax = 10, fits = 20, cores = 1, # cores = c(fits = , conditions = ) splits the two axes. cppDE's batch runs # serially inside a fork, so an inner axis > 1 selects PSOCK. - .cc <- .splitCores(cores, "fits") - coresConditions <- if (!is.null(.cc$conditions)) .sanitizeCores(.cc$conditions) - cores <- .sanitizeCores(min(fits, .cc$outer)) + cc <- .splitCores(cores, "fits") + coresConditions <- if (!is.null(cc$conditions)) .sanitizeCores(cc$conditions) + cores <- .sanitizeCores(min(fits, cc$outer)) if (!is.null(coresConditions)) { oldCores <- options(dMod2.cores = coresConditions) on.exit(options(oldCores), add = TRUE) @@ -977,14 +977,15 @@ mstrust <- function(objfun, center, rinit = .1, rmax = 10, fits = 20, cores = 1, # Splits the named arguments of mstrust() by destination: the formals of the # optimizer, then those of the sampler, which must be disjoint, and every -# remaining name that is not mstrust()'s own goes to the objective. +# remaining name goes to the objective, except mstrust()'s own and rinit, rmax, n. .mstrustRoute <- function(given, optfun, samplefun, samplerName) { accepts <- function(f) intersect(setdiff(names(formals(f)), "..."), names(given)) toOptimizer <- accepts(optfun) toSampler <- accepts(samplefun) if (length(intersect(toOptimizer, toSampler))) stop("Argument names of the optimizer and ", samplerName, "() clash.") - toObjective <- setdiff(names(given), c(toOptimizer, toSampler, .mstrustOwn)) + toObjective <- setdiff(names(given), c(toOptimizer, toSampler, .mstrustOwn, + "rinit", "rmax", "n")) list(optimizer = given[toOptimizer], sampler = given[toSampler], objective = given[toObjective]) } @@ -1092,10 +1093,20 @@ msParframe <- function(pars, n = 20, seed = 12345, samplefun = stats::rnorm, #' @param folder The folder `//trial--/interRes` #' of the run, which holds one `fit-.Rda` per completed fit. #' -#' @return A parlist. +#' @return A parlist with one entry per file, in the order of the fit numbers. #' #' @seealso [mstrust()] #' +#' @examples +#' folder <- file.path(tempdir(), "interRes") +#' dir.create(folder, showWarnings = FALSE) +#' for (i in 1:3) +#' saveRDS(list(value = 10 / i, converged = TRUE, iterations = 5L, argument = c(a = i)), +#' file.path(folder, paste0("fit-", i, ".Rda"))) +#' fits <- load.parlist(folder) +#' as.parframe(fits) +#' unlink(folder, recursive = TRUE) +#' #' @export load.parlist <- function(folder) { files <- dir(folder, pattern = "\\.Rda$") @@ -1200,7 +1211,8 @@ reduceReplicates.data.frame <- function(data, select = "condition", datatrans = condition = do.call(paste, c(lapply(data[first, label, drop = FALSE], as.character), sep = "_")), data[first, extra, drop = FALSE]) - message("Dropped columns: ", paste(setdiff(names(data), names(out)), collapse = ", ")) + dropped <- setdiff(names(data), c(names(out), select)) + if (length(dropped)) message("Dropped columns: ", paste(dropped, collapse = ", ")) out } @@ -1230,8 +1242,8 @@ reduceReplicates.data.frame <- function(data, select = "condition", datatrans = #' @param factors Character vector, the columns of `data` whose value #' combinations define groups. The model is fitted separately per group. #' @param errorModel Character, the variance of a single measurement as an -#' expression in the mean `x` and the parameters. Default -#' `"exp(s0)+exp(srel)*x^2"`. +#' expression in the mean `x` and the parameters, built from the functions +#' [stats::deriv()] differentiates. Default `"exp(s0)+exp(srel)*x^2"`. #' @param par Named numeric vector of starting values for the parameters of #' `errorModel`. Default `c(s0 = 1, srel = 0.1)`. #' @param lower,upper Bounds on the parameters, named or in the order of @@ -1249,7 +1261,7 @@ reduceReplicates.data.frame <- function(data, select = "condition", datatrans = #' With `blather = TRUE`, a data frame with the columns of `data`, `sigma` #' replaced as above, one column per parameter of `errorModel` with the #' fitted value, the variance bands `cbLower68`, `cbUpper68`, `cbLower95` and -#' `cbUpper95`, the group label `condidnt` and the input `sigma` as +#' `cbUpper95`, the group label `group` and the input `sigma` as #' `sigmaLS`. The attribute `"errorModel"` holds `errorModel`. #' #' @seealso [reduceReplicates()] @@ -1273,6 +1285,15 @@ fitErrorModel <- function(data, factors, errorModel = "exp(s0)+exp(srel)*x^2", model <- str2expression(errorModel) callEnv <- parent.frame() variance <- function(p, x) eval(model[[length(model)]], c(as.list(p), list(x = x)), callEnv) + dmodel <- tryCatch(stats::deriv(model[[length(model)]], names(par)), error = function(e) + stop("fitErrorModel: errorModel has no symbolic derivative: ", conditionMessage(e), call. = FALSE)) + # the variance at every x and the n x length(par) Jacobian in the parameters + varianceJac <- function(p, x) { + v <- eval(dmodel, c(as.list(p), list(x = x)), callEnv) + J <- attr(v, "gradient") + list(v = rep_len(as.numeric(v), length(x)), + J = J[rep_len(seq_len(nrow(J)), length(x)), , drop = FALSE]) + } # A single factor column labels the groups as it is, several are pasted. label <- if (length(factors) == 1L) data[[factors]] else @@ -1291,7 +1312,14 @@ fitErrorModel <- function(data, factors, errorModel = "exp(s0)+exp(srel)*x^2", v <- variance(p, data$value[rows]) sum(dof[rows] * (log(v) + sampleSd[rows]^2 / v), na.rm = TRUE) } - best <- optimx::optimr(par, nll, method = "L-BFGS-B", + # rows without a sample variance drop out of the gradient as out of the value + grad <- function(p) { + m <- varianceJac(p, data$value[rows]) + w <- dof[rows] * (1 / m$v - sampleSd[rows]^2 / m$v^2) + w[is.na(dof[rows] * (log(m$v) + sampleSd[rows]^2 / m$v))] <- 0 + stats::setNames(as.numeric(crossprod(m$J, w)), names(par)) + } + best <- optimx::optimr(par, nll, grad, method = "L-BFGS-B", lower = bounds$lower, upper = bounds$upper, ...)$par estimates[rows, ] <- rep(best, each = length(rows)) single[rows] <- variance(best, data$value[rows]) @@ -1304,18 +1332,18 @@ fitErrorModel <- function(data, factors, errorModel = "exp(s0)+exp(srel)*x^2", result <- cbind(result, as.data.frame(estimates), cbLower68 = band(.683, FALSE), cbUpper68 = band(.683, TRUE), cbLower95 = band(.955, FALSE), cbUpper95 = band(.955, TRUE)) - result$condidnt <- label + result$group <- label result$sigmaLS <- data$sigma attr(result, "errorModel") <- errorModel if (plotting) { shown <- transform(result, observed = sampleSd^2, predicted = single) - print(ggplot(shown, aes(x = value)) + + print(ggplot2::ggplot(shown, aes(x = value)) + geom_point(aes(y = observed)) + geom_line(aes(y = predicted)) + geom_ribbon(aes(ymin = cbLower95, ymax = cbUpper95), alpha = 0.3) + geom_ribbon(aes(ymin = cbLower68, ymax = cbUpper68), alpha = 0.3) + - facet_wrap("condidnt", scales = "free") + + facet_wrap("group", scales = "free") + scale_y_log10() + ylab("variance") + theme_dMod2()) } diff --git a/R/symbolics.R b/R/symbolics.R index 5c157b69..7249ecb2 100644 --- a/R/symbolics.R +++ b/R/symbolics.R @@ -148,3 +148,78 @@ resolveRecurrence <- function (variables) { + + +## ---- exponential wraps ----------------------------------------------------------------------- + +## TRUE if `e` is the symbol `sym`, possibly in redundant parentheses. +.isBare <- function(e, sym) { + while (is.call(e) && length(e) == 2L && identical(e[[1L]], as.name("("))) e <- e[[2L]] + is.name(e) && identical(e, sym) +} + +## TRUE if `sym` occurs in `e` once, as a summand with sign + and coefficient 1: `sym`, `a + sym`, +## `(sym + a) - b`. +.isSummand <- function(e, sym) { + if (sum(all.names(e) == as.character(sym)) != 1L) return(FALSE) + repeat { + if (.isBare(e, sym)) return(TRUE) + if (!is.call(e)) return(FALSE) + head <- e[[1L]] + if (identical(head, as.name("(")) || (identical(head, as.name("+")) && length(e) == 2L)) { + e <- e[[2L]]; next + } + if (identical(head, as.name("+")) && length(e) == 3L) { + e <- if (as.character(sym) %in% all.names(e[[2L]])) e[[2L]] else e[[3L]]; next + } + if (identical(head, as.name("-")) && length(e) == 3L && as.character(sym) %in% all.names(e[[2L]])) { + e <- e[[2L]]; next + } + return(FALSE) + } +} + +## The base b of `e` when `e` is b^(...) with `sym` in the exponent: `exp()` (b = e), `exp10()`, +## a numeric literal `b^`; bare `sym` in the exponent, or with `summand` also as a summand. NA else. +.wrapBase <- function(e, sym, summand = FALSE) { + if (!is.call(e)) return(NA_real_) + head <- e[[1L]] + inside <- function(x) if (summand) .isSummand(x, sym) else .isBare(x, sym) + if (length(e) == 2L && inside(e[[2L]])) { + if (identical(head, as.name("exp"))) return(exp(1)) + if (identical(head, as.name("exp10"))) return(10) + } + if (length(e) == 3L && identical(head, as.name("^")) && is.numeric(e[[2L]]) && length(e[[2L]]) == 1L && + inside(e[[3L]])) return(e[[2L]]) + NA_real_ +} + +## Per symbol of `ids` the base b if every occurrence in the expressions `eqs` (character, or a list +## of them) is in a wrap b^(...) of one numeric base; NA for a linear or mixed occurrence, or none. +.wrapBases <- function(eqs, ids, summand = FALSE) { + seen <- setNames(vector("list", length(ids)), ids) + walk <- function(e, skip) { + if (is.name(e)) { + s <- as.character(e) + if (s %in% ids && !s %in% skip) seen[[s]] <<- c(seen[[s]], NA_real_) + return(invisible()) + } + if (!is.call(e)) return(invisible()) + for (s in .setdiff(.intersect(all.names(e), ids), skip)) { + b <- .wrapBase(e, as.name(s), summand) + if (is.na(b)) next + seen[[s]] <<- c(seen[[s]], b) + skip <- c(skip, s) + } + for (x in as.list(e)[-1L]) walk(x, skip) + invisible() + } + for (rhs in unlist(lapply(eqs, function(v) as.character(unclass(v))))) { + if (is.na(rhs) || !is.na(suppressWarnings(as.numeric(rhs)))) next + walk(str2lang(rhs), character(0)) + } + vapply(ids, function(s) { + u <- unique(seen[[s]]) + if (length(u) == 1L) u else NA_real_ + }, 0) +} diff --git a/R/symmetryDetection.R b/R/symmetryDetection.R index 9a9ecc7e..c991708a 100644 --- a/R/symmetryDetection.R +++ b/R/symmetryDetection.R @@ -79,10 +79,8 @@ #' (needs msolve, implies `reconstruct = TRUE`). A model the global analysis does not handle #' gets the reason in `info$discrete$unsupported` and a warning. #' @param globalOptions A list of arguments of the global analysis: `order`, `points`, -#' `timeout` and `budget` as in [discreteSymmetries()]. -#' @param discrete `FALSE` (default), `TRUE` or a list of arguments of -#' [discreteSymmetries()]: also search the discrete symmetries; `mode = "global"` does the -#' same through the detection. +#' `memory`, `experiments`, `msolveEntries`, `msolveTerms`, `searchEntries` and +#' `eliminationTerms` as in [discreteSymmetries()]. #' @param verbose Logical. Print the result. Defaults to `FALSE`. #' #' @return An object of class `symmetrydetection`: @@ -124,7 +122,7 @@ #' which the first is taken), `conditions`, `segments`, `coordinates`, #' `settings`, `elapsed` and `verification`.} #' \item{`gauge`}{the coordinates fixed under `gaugePreference`.} -#' \item{`discreteSymmetries`}{with `discrete`, see [discreteSymmetries()].} +#' \item{`discreteSymmetries`}{with `mode = "global"`, see [discreteSymmetries()].} #' \item{`call`}{the matched call.} #' } #' `print()` shows the verdict and the generators, `summary()` also the @@ -139,7 +137,9 @@ #' are `SYMIDENT_MSOLVE`, the path of the msolve executable (unset by #' default, msolve is then searched in the symident cache and on the #' `PATH`), and `SYMIDENT_CACHE`, the directory of that cache (by default -#' `~/.cache/symident` on Linux). The other switches are diagnostic, see the +#' `~/.cache/symident` on Linux). `SYMIDENT_MSOLVE_GB` sets the address space in GiB of +#' one call of msolve where `memory` of [discreteSymmetries()] is not given. The other +#' switches are diagnostic, see the #' symident documentation at . #' #' @seealso [symmetryReduction()], [reconstControl()]; the guide chapter @@ -160,7 +160,7 @@ symmetryDetection <- function(f, g, trafo = NULL, parameters = NULL, positive = TRUE, verify = TRUE, cores = 1, control = reconstControl(), scalingsOnly = FALSE, symEngine = c("modular", "symbolic"), mode = c("local", "global"), - globalOptions = NULL, discrete = FALSE, verbose = FALSE) { + globalOptions = NULL, verbose = FALSE) { symEngine <- match.arg(symEngine) mode <- match.arg(mode) if (missing(f) || is.null(f)) @@ -185,15 +185,14 @@ symmetryDetection <- function(f, g, trafo = NULL, parameters = NULL, spec$positive <- if (is.logical(positive)) isTRUE(positive) else as.list(as.character(positive)) spec$sym_engine <- symEngine spec$cores <- as.integer(max(1L, cores)) - spec$control <- setNames(lapply(unclass(control), function(x) - if (is.numeric(x) && is.infinite(x)) "Inf" else x), .symControlSnake(names(control))) + spec$control <- setNames(unclass(control), .symControlSnake(names(control))) if (mode == "global") { spec$mode <- "global" - if (length(globalOptions)) spec$global_options <- globalOptions + if (length(globalOptions)) + spec$global_options <- setNames(lapply(globalOptions, function(x) if (is.list(x)) x else .symCount(x)), + .symSnake(names(globalOptions))) } res <- .symFromPy(.symCall("detect_json", spec), match.call()) - if (!isFALSE(discrete)) - res <- do.call(discreteSymmetries, c(list(res, cores = cores), if (is.list(discrete)) discrete)) if (isTRUE(verbose)) print(res) invisible(res) } @@ -209,42 +208,66 @@ symmetryDetection <- function(f, g, trafo = NULL, parameters = NULL, #' \eqn{\sigma} of the coordinates, \eqn{\sigma} is reconstructed, checked on the output #' at random points (`"checked"`) and, where every state has a free initial value, #' proven by a map of the states (`"exact"`). A model with directions is reduced by -#' [symmetryReduction()] first and the reduced model is analyzed. +#' [symmetryReduction()] first and the reduced model is analyzed. The search stops on work +#' limits, never on a clock, so the result is the same on every machine; a count or proof +#' that reaches a limit ends without a result and names the limit in `limits` or in the +#' certificate. #' #' @param object A `symmetrydetection` result from [symmetryDetection()]. #' @param order Highest Taylor coefficient; `NULL` (default) twice the number of #' coordinates. #' @param points Number of random points of the count in the domain, or a list of #' points, each a named list of the coordinates. Defaults to 5. -#' @param timeout Seconds one call of msolve may take. Defaults to 600. -#' @param budget Seconds the reconstruction of the maps may take; past it, the counts -#' are reported without closed forms. Defaults to 300. #' @param cores Threads of msolve. Defaults to 1. +#' @param memory GiB of address space one call of msolve may take; past it the call +#' fails. `NULL` (default) keeps the value of symident (8). +#' @param experiments Count on several experiments with shared parameters and free +#' starts, which bounds the fiber of a model with free starts and no rational first +#' integral: `NULL` (default) where a short count of one experiment finds none, `TRUE` +#' first with the number of experiments from the rank criterion, a number `K` with `K` +#' experiments, `FALSE` never. +#' @param msolveEntries Nonzero entries of the F4 matrices one call of msolve may reduce. +#' @param msolveTerms Terms of the largest system given to msolve. +#' @param searchEntries Entries of the matrices over finite fields the exact count may +#' reduce. +#' @param eliminationTerms Terms of the largest polynomial of the elimination of the +#' states in the exact count. #' #' @return `object` with `discreteSymmetries`, per \eqn{\sigma} the `map` of the #' coordinates it changes (an [eqnvec]), `changes`, `level`, `preservesDomain` #' (`TRUE`, `FALSE`, or `NULL` with the `domainConditions` under which #' \eqn{\sigma(\theta)} lies in the domain) and `fixedSet`, the factors on which #' \eqn{\sigma} fixes \eqn{\theta}; and `info$discrete` with `order`, `count` (the -#' solutions over the algebraic closure at a random point modulo a prime), `counts` -#' per point (`complex`, `real`, `inDomain`, `undecided`), `closedForms`, `countFinal` -#' (every solution is the image of a proven \eqn{\sigma}), `fundamentalDomain` -#' (inequalities that keep one point of each orbit), `limits` and, for a model with -#' directions, `reduced`. +#' solutions over the algebraic closure at a random point modulo a prime), `countBound` +#' (the probability that a generic point has more, `NULL` where the count is exact or has +#' no bound), `countDomain` (the points of the fiber of a generic point inside the +#' domain, where that number is final), `counts` per point (`complex`, `real`, +#' `inDomain`, `undecided`), `closedForms`, `countFinal` (every solution is the image of +#' a proven \eqn{\sigma}), `fundamentalDomain` (inequalities that keep one point of each +#' orbit), `certificate` (what the result rests on, with `complete`: `"exact"`, +#' `"verified"`, `"axiom"`, `"no"` or `"open"`), `experiments` (the count on several +#' experiments, or why it does not apply), `limits` and, where they apply, `reduced` (for +#' a model with directions), `eliminated` (under `reduceCQ`, the species solved through +#' the totals), `relaxed` (the model with non-rational terms of the states as new states) +#' and `unsupported`. #' #' @details The search needs msolve; [symmetryDetection()] says where it is searched. +#' The defaults of `msolveEntries`, `msolveTerms`, `searchEntries` and `eliminationTerms` +#' (`NULL`) keep the values of symident. #' @references Godfrey, K. (1983). Compartmental Models and Their Application. #' Academic Press, London. #' @seealso [symmetryDetection()], [symmetryReduction()] #' @examplesIf requireNamespace("reticulate", quietly = TRUE) && reticulate::py_module_available("symident.install") && !is.null(tryCatch(reticulate::import("symident.install")$find_msolve()[[1]], error = function(e) NULL)) #' # two compartments, an input u into the first, the second observed #' f <- eqnvec(x1 = "-(k21 + k01)*x1 + k12*x2 + u", x2 = "k21*x1 - k12*x2") -#' res <- symmetryDetection(f, eqnvec(y = "x2"), knownInputs = "u", discrete = TRUE) +#' res <- symmetryDetection(f, eqnvec(y = "x2"), knownInputs = "u", mode = "global") #' res #' res$discreteSymmetries[[1]]$map #' res$info$discrete$fundamentalDomain #' @export -discreteSymmetries <- function(object, order = NULL, points = 5L, timeout = 600, budget = 300, cores = 1) { +discreteSymmetries <- function(object, order = NULL, points = 5L, cores = 1, memory = NULL, + experiments = NULL, msolveEntries = NULL, msolveTerms = NULL, + searchEntries = NULL, eliminationTerms = NULL) { if (!inherits(object, "symmetrydetection")) stop("discreteSymmetries(): `object` must be a symmetrydetection result.", call. = FALSE) api <- .symident("api") @@ -257,13 +280,14 @@ discreteSymmetries <- function(object, order = NULL, points = 5L, timeout = 600, known_inputs = spec$known_inputs %||% list(), fixed = spec$fixed %||% list(), parameters = spec$parameters %||% list(), regimes = spec$regimes) res <- api$Symmetries(raw, model) - env <- Sys.getenv() - env <- as.character(jsonlite::toJSON(as.list(env[grepl("^SYMIDENT_", names(env)) & nzchar(env)]), - auto_unbox = TRUE)) + env <- .symEnv() # the search fills the result it runs on search <- function() with(rj$`_context`(env), res$discrete( - order = if (!is.null(order)) as.integer(order), timeout = timeout, budget = budget, cores = as.integer(cores), - points = if (is.list(points)) points else as.integer(points))) + order = if (!is.null(order)) as.integer(order), cores = as.integer(cores), + points = if (is.list(points)) points else as.integer(points), memory = memory, + experiments = .symCount(experiments), msolve_entries = .symCount(msolveEntries), + msolve_terms = .symCount(msolveTerms), search_entries = .symCount(searchEntries), + elimination_terms = .symCount(eliminationTerms))) tryCatch(search(), symident.sym.msolve.MsolveMissingError = function(e) { if (!.offerMsolve()) stop("discreteSymmetries() needs msolve: confirm the msolve installation in an interactive session, ", @@ -309,8 +333,6 @@ discreteSymmetries <- function(object, order = NULL, points = 5L, timeout = 600, #' reconstruction under `equilibrate = TRUE`. Defaults to 3. #' @param homotopy Whether directions still open under `equilibrate = TRUE` are #' fitted along lines in parameter space as a last route. Defaults to `TRUE`. -#' @param timeout Time limit in seconds for the reconstruction. Directions not -#' finished in time are reported by their support. `Inf` (default) sets no limit. #' @param homotopyDegree Total degree bound of the entries the homotopy route fits. #' @param degreeCapMax Degree up to which an entry past `degreeCap` is probed again, #' the bound doubled each time. @@ -326,14 +348,13 @@ discreteSymmetries <- function(object, order = NULL, points = 5L, timeout = 600, #' @seealso [symmetryDetection()] #' @export #' @examples -#' reconstControl(degreeCap = 6L, timeout = 60) +#' reconstControl(degreeCap = 6L) reconstControl <- function(relevanceCap = 6L, relevanceCapDir = 24L, relevanceCapSparse = 30L, degreeCap = 4L, sampleSlack = 5L, probeRetries = 8L, laurentDegNum = 4L, laurentDegDen = 2L, laurentCandCap = 200000L, termCap = 60L, generalDegNum = 4L, generalDegDen = 3L, gapOrderCap = 8L, minSupportCandCap = 20000L, perPrimeCap = 120L, - perPrimeMinPrimes = 3L, homotopy = TRUE, timeout = Inf, - homotopyDegree = NULL, degreeCapMax = NULL, exactProof = NULL, + perPrimeMinPrimes = 3L, homotopy = TRUE, homotopyDegree = NULL, degreeCapMax = NULL, exactProof = NULL, exactWorkCap = NULL, seed = NULL) { stopifnot(relevanceCap >= 0L, relevanceCapDir >= 1L, relevanceCapSparse >= relevanceCap, degreeCap >= 0L, @@ -341,7 +362,7 @@ reconstControl <- function(relevanceCap = 6L, relevanceCapDir = 24L, relevanceCa laurentDegNum >= 1L, laurentDegDen >= 0L, laurentCandCap >= 1L, generalDegNum >= 1L, generalDegDen >= 1L, gapOrderCap >= 0L, minSupportCandCap >= 1L, perPrimeCap >= 1L, perPrimeMinPrimes >= 2L, - isTRUE(homotopy) || isFALSE(homotopy), is.numeric(timeout), timeout > 0, + isTRUE(homotopy) || isFALSE(homotopy), is.null(homotopyDegree) || homotopyDegree >= 1L, is.null(degreeCapMax) || degreeCapMax >= 0L, is.null(exactProof) || isTRUE(exactProof) || isFALSE(exactProof), @@ -361,7 +382,7 @@ reconstControl <- function(relevanceCap = 6L, relevanceCapDir = 24L, relevanceCa minSupportCandCap = as.integer(minSupportCandCap), perPrimeCap = as.integer(perPrimeCap), perPrimeMinPrimes = as.integer(perPrimeMinPrimes), homotopy = homotopy, - timeout = timeout, homotopyDegree = int(homotopyDegree), + homotopyDegree = int(homotopyDegree), degreeCapMax = int(degreeCapMax), exactProof = exactProof, exactWorkCap = if (is.null(exactWorkCap)) NULL else as.numeric(exactWorkCap), seed = int(seed)), @@ -371,7 +392,7 @@ reconstControl <- function(relevanceCap = 6L, relevanceCapDir = 24L, relevanceCa # ---- the interface to the Python package symident -------------------------------- -.symidentMin <- "0.17.0" +.symidentMin <- "0.18.1" .symidentReq <- paste0("symident>=", .symidentMin) # whether symident is installed in version .symidentMin or later @@ -398,6 +419,10 @@ reconstControl <- function(relevanceCap = 6L, relevanceCapDir = 24L, relevanceCa reticulate::import(paste0("symident.", module)) } +# a whole number as an integer where it fits, so that symident reads a count, not a float +.symCount <- function(x) + if (is.numeric(x) && length(x) == 1L && x == round(x) && abs(x) <= .Machine$integer.max) as.integer(x) else x + # camelCase to snake_case, the argument names of symident .symSnake <- function(x) tolower(gsub("([a-z0-9])([A-Z])", "\\1_\\2", x)) @@ -417,7 +442,8 @@ reconstControl <- function(relevanceCap = 6L, relevanceCapDir = 24L, relevanceCa "display", "factor", "pins", "new_parameters", "solved_domain", "trafo", "totals", "state_components", "input_change", "jets", "map", - "point", "section", "state_maps", "fiber_coordinates")) { + "point", "section", "state_maps", "fiber_coordinates", + "eliminated", "odes", "observables", "rest", "orders", "lift")) { if (!is.list(x)) return(x) nm <- names(x) for (i in seq_along(x)) @@ -434,17 +460,22 @@ reconstControl <- function(relevanceCap = 6L, relevanceCapDir = 24L, relevanceCa if (is.list(x) && !is.null(names(x))) lapply(x, entries) else entries(x) } +# the set SYMIDENT_* variables of the session as a JSON object, passed on every call since +# Python reads the environment once +.symEnv <- function() { + env <- Sys.getenv() + as.character(jsonlite::toJSON(as.list(env[grepl("^SYMIDENT_", names(env)) & nzchar(env)]), + auto_unbox = TRUE)) +} + # one call into symident: the arguments as JSON in, the result as JSON out, with the -# warnings raised and the JSON kept as attribute "json". The SYMIDENT_* environment -# travels with it, since Python reads the environment once +# warnings raised and the JSON kept as attribute "json" .symCall <- function(fun, ...) { si <- .symident() - env <- Sys.getenv() - env <- as.list(env[grepl("^SYMIDENT_", names(env)) & nzchar(env)]) args <- lapply(list(...), function(a) if (is.character(a) && length(a) == 1L) a else as.character(jsonlite::toJSON(a, auto_unbox = TRUE, null = "null", digits = NA, force = TRUE))) - args <- c(args, list(env = as.character(jsonlite::toJSON(env, auto_unbox = TRUE)))) + args <- c(args, list(env = .symEnv())) out <- tryCatch(do.call(si[[fun]], args), symident.sym.msolve.MsolveMissingError = function(e) { if (!.offerMsolve()) diff --git a/R/symmetryReduction.R b/R/symmetryReduction.R index 515279f2..451b0180 100644 --- a/R/symmetryReduction.R +++ b/R/symmetryReduction.R @@ -27,12 +27,8 @@ #' `TRUE`. #' @param alternatives Logical. Also return the charts of the other valid pins #' in `$alternatives`. Defaults to `FALSE`. -#' @param timeout Wall time in seconds for the section search of one block; a block not -#' solved in time keeps the invariants (`"invariant_only"`) and is named in `limits`. -#' `Inf` lets the search run to its end. Unlike `workCap`, it depends on the load of the -#' machine. Defaults to 600. #' @param branch With a discrete symmetry of `symmetryDetection(mode = "global")`: the side of -#' its fixed set as an inequality, e.g. `"k01 > k12"`, whose chart becomes the trafo: free values +#' the fixed set of the symmetry as an inequality, e.g. `"k01 > k12"`, whose chart becomes the trafo: free values #' in the positive orthant map one to one onto that side, chained with the section. Without it #' every branch is in `$alternatives`; `$discrete$branches` lists them with `injective`, `reach`, #' `unproven` and the `boundary`. Defaults to `NULL`. @@ -70,8 +66,7 @@ #' \item{`assumptions`}{what the reduction assumes: `domain` (the declared positive #' coordinates) and `starts` (the sides of switches declared at the start), with #' `errorBound`, the probability that a verified closed form is wrong.} -#' \item{`limits`}{the work budgets and time limits that stopped a section or -#' invariant search.} +#' \item{`limits`}{the work caps that stopped a section or invariant search.} #' \item{`checks`}{`pins` and `invariants`, whether every pin holds under the trafo #' and every invariant of a block maps to the matching new parameter over Q, `failed`, #' and with `check = TRUE` `loop`: the `directions` the reduced model has, the @@ -112,26 +107,24 @@ symmetryReduction <- function(object, fixed = NULL, positive = NULL, dPoly = 3L, dDarboux = 2L, dExp = 2L, separable = TRUE, reportZeroCompatibility = FALSE, alternatives = FALSE, - timeout = 600, allowOpen = TRUE, allowChecked = TRUE, + allowOpen = TRUE, allowChecked = TRUE, check = TRUE, workCap = 4000L, branch = NULL, ...) { if (!inherits(object, "symmetrydetection")) stop("symmetryReduction(): `object` must be a symmetrydetection result.", call. = FALSE) if (length(list(...))) warning("symmetryReduction(): unused argument(s) ignored.", call. = FALSE) chr <- function(x) if (is.null(x)) NULL else as.list(as.character(x)) - args <- list(fixed = chr(fixed), - positive = if (is.logical(positive)) isTRUE(positive) else chr(positive), - d_poly = as.integer(dPoly), d_darboux = as.integer(dDarboux), - d_exp = as.integer(dExp), separable = isTRUE(separable), - zero_compatibility = isTRUE(reportZeroCompatibility), - alternatives = isTRUE(alternatives), - timeout = if (is.infinite(timeout)) "Inf" else timeout, - allow_open = isTRUE(allowOpen), allow_checked = isTRUE(allowChecked), - check = isTRUE(check), - work_cap = as.integer(workCap)) - if (!is.null(branch)) args$branch <- as.character(branch) - if (is.null(fixed)) args$fixed <- NULL - if (is.null(positive)) args$positive <- NULL + # an argument left NULL is left out, so symident takes the value of the detection + args <- Filter(Negate(is.null), list( + fixed = chr(fixed), + positive = if (is.logical(positive)) isTRUE(positive) else chr(positive), + d_poly = as.integer(dPoly), d_darboux = as.integer(dDarboux), + d_exp = as.integer(dExp), separable = isTRUE(separable), + zero_compatibility = isTRUE(reportZeroCompatibility), + alternatives = isTRUE(alternatives), + allow_open = isTRUE(allowOpen), allow_checked = isTRUE(allowChecked), + check = isTRUE(check), work_cap = as.integer(workCap), + branch = if (!is.null(branch)) as.character(branch))) red <- .symRedFromPy(.symCall("reduce_json", .symRaw(object), args), match.call()) d <- object$info$discrete if (!is.null(object$discreteSymmetries) || !is.null(d)) diff --git a/R/trust.R b/R/trust.R index d593aa44..3b97924e 100644 --- a/R/trust.R +++ b/R/trust.R @@ -527,9 +527,10 @@ trust <- function(objfun, parinit, rinit = 0.1, rmax = 10, lbfgs <- all(vapply(ph$phases, function(p) p$hessianMethod %in% c("gn", "exact") || (p$hessianMethod == "bfgs" && identical(p$qnControl$hessianInit, "gn")), TRUE)) first <- NULL + start <- .reflectiveStart(parinit, parlower, parupper) if (identical(sparse, "auto")) { choice <- if (fromObjective && boundary == "reflective" && !length(.shootingTerms(objfun))) - .sparseChoice(objfun, parinit, dots) else list(sparse = FALSE) + .sparseChoice(objfun, start, dots) else list(sparse = FALSE) sparse <- choice$sparse first <- choice$first } @@ -559,11 +560,11 @@ trust <- function(objfun, parinit, rinit = 0.1, rmax = 10, # `want` (0 value, 1 gradient, 2 Gauss-Newton, 3 exact) becomes the objective's # own arguments here, where the formals of the objective are visible. The exact request is checked # up front, since a stop() inside fn reads as "parinit not feasible". - .fml <- names(formals(objfun)) - .wants_exact <- any(vapply(ph$phases, function(p) + fml <- names(formals(objfun)) + wantsExact <- any(vapply(ph$phases, function(p) identical(p$hessianMethod, "exact") || identical(p$qnControl$hessianInit, "exact"), TRUE)) - if (.wants_exact && !any(c("deriv2", "...") %in% .fml)) + if (wantsExact && !any(c("deriv2", "...") %in% fml)) stop("trust: hessianMethod or qnControl$hessianInit is \"exact\", but ", "this objective has no `deriv2` argument to ask an exact Hessian ", "with.", call. = FALSE) @@ -592,7 +593,7 @@ trust <- function(objfun, parinit, rinit = 0.1, rmax = 10, fn <- function(x, want = 2L, phase = 0L) { want <- as.integer(want) # the evaluation of the sparse choice at parinit is the first one of the kernel - if (!is.null(first) && want == 2L && identical(as.vector(x), as.vector(parinit))) { + if (!is.null(first) && want == 2L && identical(as.vector(x), as.vector(start))) { out <- first first <<- NULL return(.kernelHessian(out, pnames)) @@ -646,6 +647,29 @@ trust <- function(objfun, parinit, rinit = 0.1, rmax = 10, .trustFit(fit) } +# The point the reflective kernel starts from: parinit clipped to the bounds and pushed +# 100 eps inside them, bit for bit as push_interior() in src/trust_driver.h. Named bounds +# apply by name, an unnamed one to every parameter. +.reflectiveStart <- function(parinit, parlower, parupper) { + bound <- function(b, default) { + out <- rep(default, length(parinit)) + if (!length(b)) return(out) + if (is.null(names(b))) return(rep(as.numeric(b[[1L]]), length(parinit))) + m <- match(names(parinit), names(b)) + out[!is.na(m)] <- as.numeric(b[m[!is.na(m)]]) + out + } + lb <- bound(parlower, -Inf) + ub <- bound(parupper, Inf) + z <- pmin(pmax(as.numeric(parinit), lb), ub) + eps <- 100 * .Machine$double.eps * pmax(1, abs(z)) + narrow <- is.finite(lb) & is.finite(ub) & ub - lb <= 2 * eps + z <- ifelse(is.finite(ub) & ub - z < eps, ub - eps, z) + z <- ifelse(is.finite(lb) & z - lb < eps, lb + eps, z) + z[narrow] <- 0.5 * (lb[narrow] + ub[narrow]) + stats::setNames(z, names(parinit)) +} + # An objlist with the sparse Hessian over `pnames` as the kernel reads it, `kernel`: the upper # triangle in compressed columns and the low-rank part, list(p, i, x, U, d). A dense or missing # Hessian leaves it without, which the kernel takes as no Hessian. diff --git a/R/trustShooting.R b/R/trustShooting.R index 1dd6ea62..8b7a19ca 100644 --- a/R/trustShooting.R +++ b/R/trustShooting.R @@ -2,9 +2,6 @@ ## Bock's generalized Gauss-Newton method, condensed onto theta, on a trust region ## over parameters and nodes; acceptance by filter, l2 penalty or natural level. -## Copyright (C) 2026 Simon Beyer - - # trust() on an objective holding a normL2 with a multipleShootingControl. # Settings a shooting run cannot honor are refused. Every other summand enters # the condensed problem with a separate value, gradient and Gauss-Newton Hessian. @@ -61,7 +58,6 @@ K <- length(theta) lb <- .shootBound(parlower, tnames, -Inf) ub <- .shootBound(parupper, tnames, Inf) - ps <- rep(1, K) if (any(theta < lb | theta > ub)) { warning("trust: 'parinit' outside the bounds was clipped.", call. = FALSE) theta <- pmin(pmax(theta, lb), ub) @@ -152,7 +148,7 @@ thx <- function(th) setNames(c(th, numeric(Kx - K)), tx) lbx <- c(lb, rep(-Inf, Kx - K)) ubx <- c(ub, rep(Inf, Kx - K)) - psxOf <- function() c(ps, rep(1 / scale[spec$states], nBreak)) + psxOf <- function() c(rep(1, K), rep(1 / scale[spec$states], nBreak)) zeroBreaks <- function(gaps) { if (!nBreak) return(gaps) b <- bkOf()$brk @@ -172,10 +168,13 @@ # Horbelt, Timmer and Voss (2002): theta is fitted first with the nodes held, # then the nodes are laid out afresh and released. A failing phase is dropped. start0 <- NULL + # the iterations of the first phase count against iterlim + itPh1 <- 0L if (isTRUE(step$twoPhase)) { ph <- .shootPhaseOne(sobj, theta, nodes, fixed, cores, pv, lb, ub, rinit, rmax, iterlim) neval <- neval + ph$neval + itPh1 <- as.integer(ph$iterations) if (!is.null(ph$theta)) { nd <- tryCatch(initNodes(ph$theta), error = function(e) NULL) E1 <- if (!is.null(nd)) ev(ph$theta, nd, quiet = TRUE) @@ -353,7 +352,7 @@ if (isTRUE(step$anneal)) { evGN <- function(th, nd) ev(th, nd, hessian = TRUE, sw = "forward", quiet = TRUE) evV <- function(th, nd) ev(th, nd, quiet = TRUE, deriv = FALSE) - an <- .shootAnneal(evGN, spec, theta, nodes, tnames, ps, scale, pv, lb, ub, + an <- .shootAnneal(evGN, spec, theta, nodes, tnames, scale, pv, lb, ub, rinit, rmax, printIter, evV = evV, brk = bkOf()$brk) if (!is.null(an)) { theta <- an$theta; nodes <- an$nodes @@ -370,14 +369,14 @@ # Model Hessian per segment: the Gauss-Newton block, or a quasi-Newton one. # Kept by segment across a new layout; a segment that is new gets a seed. - seedBlocks <- function(E, which) { + seedBlocks <- function(E, ks) { if (qn$hessianInit == "gn") { Eg <- ev(theta, nodes, hessian = TRUE, sw = "forward") if (inherits(Eg, "error")) stop("trust: the Gauss-Newton seed failed: ", conditionMessage(Eg), call. = FALSE) neval <<- neval + 1L - lapply(which, function(k) .shootAlignMat(Eg$segments[[k]]$hess, E$segments[[k]]$vars)) - } else lapply(which, function(k) { + lapply(ks, function(k) .shootAlignMat(Eg$segments[[k]]$hess, E$segments[[k]]$vars)) + } else lapply(ks, function(k) { v <- E$segments[[k]]$vars Mc <- spec$segs[[k]]$M matrix(diag(ifelse(v %in% tnames, 1 / Mc, 1), length(v)), length(v), @@ -472,7 +471,7 @@ f <- E$value + PR$value h <- .shootViolation(E$gaps, scale) omega <- NA_real_ - for (iter in seq_len(iterlim)) { + for (iter in seq_len(iterlim - itPh1)) { if (is.null(C)) C <- condense(E) psx <- psxOf() opt <- .shootOptimality(thx(theta), C$g0, lbx, ubx, psx) @@ -568,7 +567,7 @@ # SR1 learns from rejected trials too, and needs their gradients trialDeriv <- hm != "gn" && isTRUE(qn$qnRejected) lastAccepted <- TRUE - if (acc != "natural") for (iter in seq_len(iterlim - itNat)) { + if (acc != "natural") for (iter in seq_len(iterlim - itPh1 - itNat)) { if (is.null(C)) C <- condense(E) psx <- psxOf() opt <- .shootOptimality(thx(theta), C$g0, lbx, ubx, psx) @@ -796,17 +795,17 @@ if (acc == "merit") msinfo$mu <- mu else if (acc == "filter") msinfo$filterSize <- nrow(filt) if (blather) msinfo$trace <- trace + # a loop over no iterations leaves `iter` empty list(argument = theta, value = f, gradient = setNames(as.numeric(C$g0[seq_len(K)]), tnames), hessian = C$H[seq_len(K), seq_len(K), drop = FALSE], - iterations = itNat + iter, neval = neval, + iterations = itPh1 + itNat + sum(iter), neval = neval, qnSkipped = qnSkipped, converged = converged, stopReason = stopReason, atBound = opt$atBound[seq_len(K)], multipleShooting = msinfo) } - # The first of two phases: theta alone by the trust region of trust(), on the # data term of the segments with every node held where it is, plus the other # summands. NULL for theta when the phase fails. @@ -841,7 +840,6 @@ iterations = r$iterations, neval = neval) } - ## ---- Condensing ---------------------------------------------------------------- ## Forwards through each condition's segments: S_{j+1} = A_k L_k and ## z_{j+1} = c_j + A_k zhat_k, with A_k the end-state Jacobian of segment k. @@ -972,7 +970,6 @@ out } - # Size of the gaps the linearized constraints leave after a step, # c_j + A_j d_j - Delta s_{j+1}, scaled per state, with A_j the full end-state # Jacobian: the exact linearization, also where condensing decoupled a link. @@ -1001,7 +998,6 @@ sqrt(s2) } - ## ---- Partitioned quasi-Newton ------------------------------------------------ ## Multipliers by lambda_{j-1} = grad_{s_j} m_j + G_j' lambda_j; segment j's pair ## is the local step of segment j and the change of the gradient of f_j + lambda_j' end_j. @@ -1051,7 +1047,6 @@ list(B = B, skipped = skipped) } - ## ---- Acceptance -------------------------------------------------------------- .shootViolation <- function(gaps, scale) { @@ -1073,7 +1068,6 @@ rbind(filt[keep, , drop = FALSE], c(h, f)) } - ## ---- Small helpers ------------------------------------------------------------- # The full generalized Gauss-Newton step (alpha = 1) on the pseudo-inverse, @@ -1269,14 +1263,13 @@ out } - ## ---- Annealing of the continuity --------------------------------------------- ## Precision annealing (Ye and Abarbanel): f + w ||V c||^2 over parameters and ## nodes, uncondensed and sparse, with w rising per stage before the exact method. # Gauss-Newton model of f + w ||V c||^2 in the scaled variables -# y = (ps * theta, s / scale), as a sparse matrix and a gradient. -.shootAnnealModel <- function(E, spec, tnames, ps, scale, w, PR, brk = NULL) { +# y = (theta, s / scale), as a sparse matrix and a gradient. +.shootAnnealModel <- function(E, spec, tnames, scale, w, PR, brk = NULL) { K <- length(tnames) states <- spec$states nx <- length(states) @@ -1291,7 +1284,7 @@ } } n <- off - dsc <- c(ps, rep(1 / scale[states], (n - K) / nx)) # y = dsc * x + dsc <- c(rep(1, K), rep(1 / scale[states], (n - K) / nx)) # y = dsc * x # blocks are collected and bound once, so assembly is linear in the segments blk <- vector("list", 2L * length(spec$segs) + 1L) nb <- 0L @@ -1375,7 +1368,7 @@ # Annealing stages, each minimizing f + w ||V c||^2 until a step gains less # than `ftol`, until the RMS gap per node is below `hnode`, w reaches `wmax`, or # the gaps stall. Returns the point the exact method starts from. -.shootAnneal <- function(evGN, spec, theta, nodes, tnames, ps, scale, pv, lb, ub, +.shootAnneal <- function(evGN, spec, theta, nodes, tnames, scale, pv, lb, ub, r, rmax, printIter = FALSE, w0 = 1, factor = 10, wmax = 1e10, hnode = 1e-3, itStage = 30L, ftol = 1e-3, evV = evGN, brk = NULL) { @@ -1411,7 +1404,7 @@ # a new weight is a new problem; the radius the last one ended on says # nothing about it r <- r0 - Mdl <- .shootAnnealModel(E, spec, tnames, ps, scale, w, PR, brk) + Mdl <- .shootAnnealModel(E, spec, tnames, scale, w, PR, brk) cont0 <- Mdl$cont for (it in seq_len(itStage)) { st <- .shootSparseTR(Mdl$H, Mdl$g, r) @@ -1450,7 +1443,7 @@ cat(sprintf("anneal w = %.0e F = %.8g gaps = %.3g r = %.3g %s\n", w, valT, sqrt(contT), r, if (rho >= 0.25) "accept" else "reject")) if (rho >= 0.25) { - MT <- .shootAnnealModel(ET, spec, tnames, ps, scale, w, PRT, brk) + MT <- .shootAnnealModel(ET, spec, tnames, scale, w, PRT, brk) dF <- Mdl$value - MT$value theta <- thetaT; nodes <- nodesT; E <- ET; PR <- PRT; Mdl <- MT if (rho > 0.75 && sqrt(sum(dy^2)) >= 0.9 * r) r <- min(2 * r, rmax) diff --git a/R/utils.R b/R/utils.R index 99c82cb4..992316ae 100644 --- a/R/utils.R +++ b/R/utils.R @@ -1,6 +1,5 @@ -# setdiff/intersect for character vectors that are already unique. base's -# versions coerce with as.vector() and run a unique() pass; on parameter-name -# vectors touched once per condition that is most of their cost. +# setdiff/intersect for character vectors that are already unique, without +# the as.vector() and unique() passes of base. .setdiffU <- function(a, b) a[match(a, b, 0L) == 0L] .intersectU <- function(a, b) a[match(a, b, 0L) > 0L] diff --git a/_pkgdown.yml b/_pkgdown.yml index 12efb0f5..d29f8831 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -300,7 +300,6 @@ reference: - plotArray - plotValues - plotPars - - plotPairs - plotResiduals - plotTrace @@ -385,6 +384,5 @@ reference: - getDerivs - getDerivs2 - getEquations - - getObservables - getParameters - attrs diff --git a/examples/oppeltNPJSystBiolAppl2018/symmetries.R b/examples/oppeltNPJSystBiolAppl2018/symmetries.R index 80a77d2e..9f9b8558 100644 --- a/examples/oppeltNPJSystBiolAppl2018/symmetries.R +++ b/examples/oppeltNPJSystBiolAppl2018/symmetries.R @@ -18,7 +18,7 @@ symmetries <- symmetryDetection(reactions, unbleached, events = events, forcings ## ---- reduction # a section of every orbit of the scalings -reduction <- symmetryReduction(symmetries, timeout = 120) +reduction <- symmetryReduction(symmetries) ## ---- symmetriessave dir.create("results", showWarnings = FALSE) diff --git a/inst/WORDLIST b/inst/WORDLIST index 30903f7c..33095897 100644 --- a/inst/WORDLIST +++ b/inst/WORDLIST @@ -1,64 +1,90 @@ +0k +1e +2K +2Q +2a +2b +2c +2m +3D +4D +A20 AAPS Aarons Adlung Aggeler AlyssaPetit +Armijo +BDF BLOQ BLQ BLoQ -BaF +BaF3 Bachmann Bergstrand -Bertozzi -Biomedicine -Biometrics +Bigl +Bigr +Bilevel Birkhäuser +Blackwellized BlotIt Boehm Brendel CFU -CIE +CIE2000 CMD CVODE CVODES CWRES +Cov +DOI DV Darboux Datalist Dimerization Dumitras ECM +ECME Epo EpoR Eqnlist Eventlist Ewens +F4 FOCE FOCEI Fehling -Fides +FitzHugh +Fk Forcings -Freiburg Fröhlich Fujita Funaki -Godfrey +GFP +Genz +Gerstner +GiB Gretz +Griebel Hager -Hessians +Hauber +HepG2 Holford Hopf Horbelt +Huh7 +Huschens IET IFN +IKK IPRED IRES -IRF +IRF9 IWRES Immunoblots -Isensee +IκBα JAK -JCB +JAK2 KLU Karlsson Kemmer @@ -66,181 +92,250 @@ Klingmueller Kok Kreutz Kurths -LOQ -Laske -Lehmann +L1 +L10 +L2 +L5 Leong Leyffer Lindstrom +Log2 +M3 MPI's Mader +Makevars +Martínez MathML Mavoglurant Mentré Modelname -Mol Monro Moré Multistart -NLME +Multistarts +Möbius +NDF +NFκB +NN NONMEM NPDE +Nagumo Nocedal +Nonmonotone O'Reilly -Observability -Observables +OIM Ogungbenro Okabe OpenMP +Oppelt PAGJA PCHIP -PDE PEtab PKPD PLOS -PLOSComputBiol PLoS PNAS -PRED +PPL PSOCK PWRES Peifer Pharmacodynamics +Pharmacokinetic Pharmacokinetics Phosphorylated Pigeolet Pimpl -Polychrome -Pos Pre Proteome PyPI +R2C README +Rao Raue Reparameterization -Reparametrization Rosenblatt +Rosenbrock Rtools +S1 +S3 +S5 +S7 +S8 +S9 SAEM SBML SBML's -SHP +SHP1 +SIGKILL +SIGTERM SLURM -SOCS +SOCS3 +SR1 +STAT1 +STAT2 +STAT5 +STAT5A +STAT5B Schur -Schwen +Smolyak +Smolyak's Sorensen Sorger +SuiteSparse Swameye SymPy -Syst TG +TNFα TSV +Tapia Teusel -Theophylline Timmer Tiwari Tsamandouras +Tsitouras +USP18 Voss -WD Wallin -Warfarin Wendling Wilk Woodbury +Xcode +YAML Zhang -actinomycin -adjoint +Zhou adjoints -al archiver +arg +atol backend's +bigl +bigr blotIt brms bwForCluster cOde camelCase -composable -coumarin +cdot +cdots +chi2 +circ +const cowplot cppDE cppDE's csv dMod +dMod2's data's databased datalist datalists deSolve decorrelated -deterministically -dichromatic +dephosphorylation +det +dfrac +diclofenac dimerization distributedComputing doi doxycycline +dx +e0264295 +e1010322 +e8955 educts +eigenbasis eigendecomposition +eigenpairs endosomes eqnlist eqnlists eqnvec -equilibrated -equilibration erythroid -et evaluable eventlist +feedbacks forcings -getter +frac +frac1K +ge ggplot +ggplot2 ggplots +globalizations hepatoma homotopy -integrators +i10 +iN +iS +ij +ik +immunoblots +infty interpolant -invariants isoform +jk jss +ker +kk knitr -libSBML +l2 +lVert +ldots +le +leftarrow libsbml -ligand -linearized +linearizes lloq -lme -loess +lme4 +log10 +log2 +lowerCamelCase +lvert +mRNA +mathbb +mathbf +mathcal +mathrm +mathsf mavoglurant md metanames -monomial -monomials +mis msolve mstrust +mtol multistart multistarts multistep nM +nabla +ni nleqslv -nlmixr +nlmixr2 +nlmixr2data +nonpositive +nonsingular +nucNFkB nucleocytoplasmic -nulled nullspace +numpy objfn objlist objlists -observability observableId -observables odemodel openxlsx +operatorname orthant +otimes outflux overexpressed overexpression -pAC +pIKK pM -pPDE +pNFκB parallelly parameterId parfn @@ -255,47 +350,67 @@ pharmacodynamics pharmacokinetic pharmacometrics phosphorylated -positionally +phosphorylates +pmatrix +posteriori +ppIKK +pq prdframe pre +preconditioner preequilibration -prothrombin +propto pseudoinverse purrr qPCR -quadratures +qquad +rVert +recompiles reimplemented -reimport reoptimizations reoptimized reoptimizes -reticulate +reparameterization +ri +rtol +rvert scaling's +scipy +setminus siRNA -spectrometry stabilise -stoichiometric subfolder -subproblem +subseteq substeps -summand summands +superlinear symengine symident symident's symmetryDetection symmetryReduction sympy -testthat +t5 +texttt +tfrac +tfrac12 +tfrac1n th -theophylline +thetaMax tibbles +tol toolchain trafo tsv uncompiled unconverged +underbrace unparsable -warfarin +v088 +v1 +v2 +valueSE +varepsilon +vartheta zstd α diff --git a/inst/code/dmodToSbml.py b/inst/code/dmodToSbml.py index da361301..6925f92c 100644 --- a/inst/code/dmodToSbml.py +++ b/inst/code/dmodToSbml.py @@ -122,13 +122,13 @@ def build_sbml(spec): kl.setMath(ast) # --- events --- - # One per trigger; `time` gives `time >= T`, otherwise the root - # expression is used as the trigger formula directly. + # One per trigger; `initialValue` true keeps a trigger that holds at + # the start from firing there. for e in spec.get("events", []): ev = model.createEvent() ev.setUseValuesFromTriggerTime(False) trig = ev.createTrigger() - trig.setInitialValue(False) + trig.setInitialValue(bool(e.get("initialValue", False))) trig.setPersistent(True) formula = e.get("trigger") ast = libsbml.parseL3Formula(_l3(formula)) diff --git a/inst/examples/P.R b/inst/examples/P.R index 5eebcc5f..07c6d780 100644 --- a/inst/examples/P.R +++ b/inst/examples/P.R @@ -4,6 +4,7 @@ trafo <- list( ctrl = eqnvec(k1 = "exp(log_k1)", k2 = "exp(log_k2)", A = "A0"), treat = eqnvec(k1 = "exp(log_k1 + log_fold)", k2 = "exp(log_k2)", A = "A0")) p <- P(trafo, compile = TRUE, modelname = "P_example", outdir = tempdir()) +print(p) getParameters(p) p(c(log_k1 = 0, log_k2 = -1, A0 = 2, log_fold = log(3))) } diff --git a/inst/examples/Xf.R b/inst/examples/Xf.R new file mode 100644 index 00000000..93cfc152 --- /dev/null +++ b/inst/examples/Xf.R @@ -0,0 +1,9 @@ +\donttest{ +f <- eqnvec(A = "-k1*A", B = "k1*A - k2*B") +model <- odemodel(f, modelname = "Xf_AB", outdir = tempdir()) + +## States alone, without sensitivities +x <- Xf(model) +pred <- x(seq(0, 10, 0.1), c(A = 1, B = 0, k1 = 0.5, k2 = 0.2)) +plot(pred) +} diff --git a/inst/examples/accessors.R b/inst/examples/accessors.R new file mode 100644 index 00000000..bf5b6314 --- /dev/null +++ b/inst/examples/accessors.R @@ -0,0 +1,15 @@ +## Accessors read the generated objects, no compiled code is needed +g <- Y(c(Aobs = "s*A"), states = "A", parameters = "s", compile = FALSE, + modelname = "accessors_obs", outdir = tempdir()) +p <- P(list(C1 = eqnvec(A = "A0", s = "s"), C2 = eqnvec(A = "2*A0", s = "s")), + compile = FALSE, modelname = "accessors_p", outdir = tempdir()) + +getParameters(g) +getParameters(p) +getConditions(p) +getEquations(p, conditions = "C2") + +modelname(g) +modelname(g, p) +modelname(p) <- "accessors_trafo" +modelname(p) diff --git a/inst/examples/as.eventlist.R b/inst/examples/as.eventlist.R new file mode 100644 index 00000000..f6784607 --- /dev/null +++ b/inst/examples/as.eventlist.R @@ -0,0 +1,3 @@ +events <- data.frame(var = c("A", "B"), time = c(5, 10), value = c(1, 0), + method = c("add", "replace")) +as.eventlist(events) diff --git a/inst/examples/customTotals.R b/inst/examples/customTotals.R new file mode 100644 index 00000000..2557a8bb --- /dev/null +++ b/inst/examples/customTotals.R @@ -0,0 +1,9 @@ +## A reversible conversion conserves A + B +el <- addReaction(eqnlist(), "A", "B", "k1*A") +el <- addReaction(el, "B", "A", "k2*B") +conservedQuantities(el) + +## Name the conserved quantity, then return to the detected basis +el <- customTotals(el, list(total = "A + B")) +el$totals +el <- customTotals(el, NULL) diff --git a/inst/examples/eqnvec.R b/inst/examples/eqnvec.R index df01f15f..1ce7190c 100644 --- a/inst/examples/eqnvec.R +++ b/inst/examples/eqnvec.R @@ -2,3 +2,5 @@ v <- eqnvec(y = "2*x + offset") print(v) is.eqnvec(v) +format(eqnvec(y = "2*x+offset")) +summary(v) diff --git a/inst/examples/getLocalDLLs.R b/inst/examples/getLocalDLLs.R new file mode 100644 index 00000000..fb538c02 --- /dev/null +++ b/inst/examples/getLocalDLLs.R @@ -0,0 +1,2 @@ +## Names of the loaded shared objects below the working directory +getLocalDLLs() diff --git a/inst/examples/normal.R b/inst/examples/normal.R index 5d3efb53..f4ccfade 100644 --- a/inst/examples/normal.R +++ b/inst/examples/normal.R @@ -2,6 +2,7 @@ normal() spikeSlab() spikeSlab(prob = 0.2, tau = 0.5) +spikeSlab(mean = log(0.5), spike = -Inf) dirichletProcess() dirichletProcess(concentration = 1) @@ -11,3 +12,10 @@ trafo <- branch(define(NULL, "x <- x", x = c("kp", "kd")), table = cov) trafo <- insert(trafo, "x <- exp(x)", x = c("kp", "kd")) trafo <- insert(trafo, x ~ 1 + (1 | gr(line, dist = dirichletProcess())), x = c("kp", "kd")) randomEffects(trafo) + +## reaction rates switched off by a spike at -Inf, one group of all conditions +sel <- branch(define(NULL, "x <- x", x = c("kp", "kd")), table = cov) +sel <- insert(sel, "x <- exp(x)", x = c("kp", "kd")) +sel <- insert(sel, x ~ 0 + (1 | gr(dist = spikeSlab(mean = log(0.5), spike = -Inf))), + x = c("kp", "kd")) +randomEffects(sel) diff --git a/inst/examples/objlist.R b/inst/examples/objlist.R new file mode 100644 index 00000000..6422cecf --- /dev/null +++ b/inst/examples/objlist.R @@ -0,0 +1,8 @@ +## Two priors on overlapping parameters +obj1 <- constraintL2(mu = c(a = 0, b = 0), sigma = 1) +obj2 <- constraintL2(mu = c(b = 1, c = 1), sigma = 1) + +## Gradients and Hessians are matched by parameter name +total <- obj1(c(a = 1, b = 2)) + obj2(c(b = 2, c = 3)) +total$value +total$gradient diff --git a/inst/examples/parlist.R b/inst/examples/parlist.R index ed712f47..e7ce2976 100644 --- a/inst/examples/parlist.R +++ b/inst/examples/parlist.R @@ -30,6 +30,7 @@ summary(out) ## Parameter frame and best fit parframe <- as.parframe(out) plotValues(parframe) +unique(parframe) bestfit <- as.parvec(parframe) plot((g*x)(times, bestfit), data) } diff --git a/inst/examples/prdframe.R b/inst/examples/prdframe.R new file mode 100644 index 00000000..b3a44a0e --- /dev/null +++ b/inst/examples/prdframe.R @@ -0,0 +1,9 @@ +## Prediction frames of a decay at two rates, without derivatives +times <- 0:4 +frame1 <- prdframe(cbind(time = times, A = exp(-times)), parameters = c(k = 1)) +frame2 <- prdframe(cbind(time = times, A = exp(-2 * times)), parameters = c(k = 2)) +frame1 + +## One frame per condition, in long format +pred <- prdlist(slow = frame1, fast = frame2) +as.data.frame(pred) diff --git a/inst/examples/res.R b/inst/examples/res.R new file mode 100644 index 00000000..3e71da8d --- /dev/null +++ b/inst/examples/res.R @@ -0,0 +1,10 @@ +## Prediction with the derivative of the observable y in the parameter k +times <- 0:2 +J <- array(-times * exp(-times), c(3, 1, 1), list(NULL, "y", "k")) +out <- prdframe(cbind(time = times, y = exp(-times)), deriv = J, parameters = c(k = 1)) + +data <- data.frame(time = times, name = "y", value = c(1.05, 0.35, 0.15), + sigma = 0.1, lloq = -Inf) +r <- res(data, out) +r +attr(r, "deriv") diff --git a/inst/examples/write.eqnlist.R b/inst/examples/write.eqnlist.R new file mode 100644 index 00000000..5728d4ba --- /dev/null +++ b/inst/examples/write.eqnlist.R @@ -0,0 +1,4 @@ +el <- addReaction(eqnlist(), "A", "B", "k1*A", description = "conversion") +file <- tempfile(fileext = ".csv") +write.eqnlist(el, file = file) +read.csv(file) diff --git a/man/P.Rd b/man/P.Rd index 3a2c5635..fa958938 100644 --- a/man/P.Rd +++ b/man/P.Rd @@ -141,6 +141,7 @@ trafo <- list( ctrl = eqnvec(k1 = "exp(log_k1)", k2 = "exp(log_k2)", A = "A0"), treat = eqnvec(k1 = "exp(log_k1 + log_fold)", k2 = "exp(log_k2)", A = "A0")) p <- P(trafo, compile = TRUE, modelname = "P_example", outdir = tempdir()) +print(p) getParameters(p) p(c(log_k1 = 0, log_k2 = -1, A0 = 2, log_fold = log(3))) } diff --git a/man/Xd.Rd b/man/Xd.Rd index 4e1d8476..f3958b9c 100644 --- a/man/Xd.Rd +++ b/man/Xd.Rd @@ -102,7 +102,7 @@ With \code{deriv = FALSE} it returns the value alone. # Generate a data.frame and corresponding prediction function timesD <- seq(0, 2*pi, 0.5) mydata <- data.frame(name = "A", time = timesD, value = sin(timesD), - row.names = paste0("par", 1:length(timesD))) + row.names = paste0("par", seq_along(timesD))) x <- Xd(mydata) # Evaluate the prediction function at different time points diff --git a/man/Xf.Rd b/man/Xf.Rd index 2a1b99b7..2db81961 100644 --- a/man/Xf.Rd +++ b/man/Xf.Rd @@ -127,6 +127,17 @@ saddle. With \code{deriv = FALSE} it returns the value alone. } +\examples{ +\donttest{ +f <- eqnvec(A = "-k1*A", B = "k1*A - k2*B") +model <- odemodel(f, modelname = "Xf_AB", outdir = tempdir()) + +## States alone, without sensitivities +x <- Xf(model) +pred <- x(seq(0, 10, 0.1), c(A = 1, B = 0, k1 = 0.5, k2 = 0.2)) +plot(pred) +} +} \seealso{ \code{\link[=Xs]{Xs()}}, \code{\link[=controls]{controls()}} } diff --git a/man/align.Rd b/man/align.Rd index 43256e1d..468bb705 100644 --- a/man/align.Rd +++ b/man/align.Rd @@ -69,7 +69,8 @@ with REML the maximum likelihood fits the rounds start from), \code{remlRounds} (the rounds of the restricted likelihood, 0 without), \code{seSource} (\code{"Hessian"}, or \code{"Gauss-Newton"} where the reported Hessian of a fit with random terms is not positive definite: then the -Gauss-Newton Schur complement of the expected information over the random effects), +Gauss-Newton Schur complement of the expected information over the random effects; +\code{"none"} where that fails too, without standard errors), \code{fit}, \code{objfn}, \code{omega}, \code{random} and \code{randomEffects} with random terms, and the \code{model}. \code{scaled} also has \code{scaled}, the value of the biological symbol at which the prediction meets the reading with the other symbols at the fit (\code{NaN} where none does), and diff --git a/man/as.data.frame.dMod.Rd b/man/as.data.frame.dMod.Rd index 939c89f6..a6f976c3 100644 --- a/man/as.data.frame.dMod.Rd +++ b/man/as.data.frame.dMod.Rd @@ -26,3 +26,14 @@ a data frame \description{ Coerce to a Data Frame } +\examples{ +## Prediction frames of a decay at two rates, without derivatives +times <- 0:4 +frame1 <- prdframe(cbind(time = times, A = exp(-times)), parameters = c(k = 1)) +frame2 <- prdframe(cbind(time = times, A = exp(-2 * times)), parameters = c(k = 2)) +frame1 + +## One frame per condition, in long format +pred <- prdlist(slow = frame1, fast = frame2) +as.data.frame(pred) +} diff --git a/man/as.data.frame.eqnlist.Rd b/man/as.data.frame.eqnlist.Rd index 3646eb8f..a3940e0a 100644 --- a/man/as.data.frame.eqnlist.Rd +++ b/man/as.data.frame.eqnlist.Rd @@ -20,3 +20,34 @@ read back by \code{\link[=as.eqnlist]{as.eqnlist()}}. \code{NULL} for an empty e \description{ Coerce Equation List into a Data Frame } +\examples{ +# Generate eqnlist from the constructor +S <- matrix(c(-1, 1, 1, -1), + nrow = 2, ncol = 2, + dimnames = list(NULL, c("A", "B"))) + +rates <- c("k1*A", "k2*B") +description <- c("forward", "backward") + +f <- eqnlist(smatrix = S, rates = rates, description = description) +print(f) + +# Convert to data.frame +fdata <- as.data.frame(f) +print(fdata) + +# Flat `volumes`: each distinct expression becomes a compartment c1, c2, ... +f <- as.eqnlist(fdata, volumes = c(A = "Vcyt", B = "Vnuc")) +print(f) +print(as.eqnvec(f)) +print(as.eqnvec(f, type = "amount")) + +# Named compartments with explicit state assignment +f2 <- eqnlist( + smatrix = S, rates = rates, description = description, + compartments = list(cyt = "Vcyt", nuc = "Vnuc"), + compartmentOf = c(A = "cyt", B = "nuc") +) +print(f2) +print(as.eqnvec(f2)) +} diff --git a/man/as.eqnvec.Rd b/man/as.eqnvec.Rd index a7283bc4..0520d189 100644 --- a/man/as.eqnvec.Rd +++ b/man/as.eqnvec.Rd @@ -31,3 +31,34 @@ Coerce to an Equation Vector For an \code{eqnlist}, the right-hand sides of the ODE are assembled from \code{\link[=getFluxes]{getFluxes()}}. } +\examples{ +# Generate eqnlist from the constructor +S <- matrix(c(-1, 1, 1, -1), + nrow = 2, ncol = 2, + dimnames = list(NULL, c("A", "B"))) + +rates <- c("k1*A", "k2*B") +description <- c("forward", "backward") + +f <- eqnlist(smatrix = S, rates = rates, description = description) +print(f) + +# Convert to data.frame +fdata <- as.data.frame(f) +print(fdata) + +# Flat `volumes`: each distinct expression becomes a compartment c1, c2, ... +f <- as.eqnlist(fdata, volumes = c(A = "Vcyt", B = "Vnuc")) +print(f) +print(as.eqnvec(f)) +print(as.eqnvec(f, type = "amount")) + +# Named compartments with explicit state assignment +f2 <- eqnlist( + smatrix = S, rates = rates, description = description, + compartments = list(cyt = "Vcyt", nuc = "Vnuc"), + compartmentOf = c(A = "cyt", B = "nuc") +) +print(f2) +print(as.eqnvec(f2)) +} diff --git a/man/as.eventlist.Rd b/man/as.eventlist.Rd index 96bdfaa5..b8e4ad9e 100644 --- a/man/as.eventlist.Rd +++ b/man/as.eventlist.Rd @@ -24,6 +24,11 @@ Object of class \code{eventlist}. \description{ Coerce to Eventlist } +\examples{ +events <- data.frame(var = c("A", "B"), time = c(5, 10), value = c(1, 0), + method = c("add", "replace")) +as.eventlist(events) +} \seealso{ \code{\link[=eventlist]{eventlist()}} } diff --git a/man/as.parframe.Rd b/man/as.parframe.Rd index 64dcaa01..89135f89 100644 --- a/man/as.parframe.Rd +++ b/man/as.parframe.Rd @@ -32,6 +32,44 @@ attribute \code{"run"} of the parlist is kept. \description{ Coerce to a Parameter Frame } +\examples{ +\donttest{ +## Observation of a regression curve +regfn <- c(y = "sin(a*time)") +g <- Y(regfn, parameters = "a", compile = TRUE, modelname = "parlist_obs", + outdir = tempdir()) +x <- Xt(condition = "C1") + +## Data +set.seed(1) +data <- datalist( + C1 = data.frame( + name = "y", + time = 1:5, + value = sin(1:5) + rnorm(5, 0, .1), + sigma = .1 + ) +) + +pars <- c(a = 1) +times <- seq(0, 5, .1) +plot((g*x)(times, pars), data) + +## Fits from random starts, stored in a parlist +obj <- normL2(data, g*x) +out <- as.parlist(lapply(1:5, function(i) { + trust(obj, pars + rnorm(length(pars), 0, 1), rinit = 1, rmax = 10) +})) +summary(out) + +## Parameter frame and best fit +parframe <- as.parframe(out) +plotValues(parframe) +unique(parframe) +bestfit <- as.parvec(parframe) +plot((g*x)(times, bestfit), data) +} +} \seealso{ \code{\link[=parframe]{parframe()}}, \code{\link[=as.parvec.parframe]{as.parvec.parframe()}}, and \code{\link[=parlist]{parlist()}} for an example. diff --git a/man/as.parvec.parframe.Rd b/man/as.parvec.parframe.Rd index 4fe8904f..61e4a064 100644 --- a/man/as.parvec.parframe.Rd +++ b/man/as.parvec.parframe.Rd @@ -27,6 +27,44 @@ and that fit did not converge. \description{ Select a Parameter Vector from a Parameter Frame } +\examples{ +\donttest{ +## Observation of a regression curve +regfn <- c(y = "sin(a*time)") +g <- Y(regfn, parameters = "a", compile = TRUE, modelname = "parlist_obs", + outdir = tempdir()) +x <- Xt(condition = "C1") + +## Data +set.seed(1) +data <- datalist( + C1 = data.frame( + name = "y", + time = 1:5, + value = sin(1:5) + rnorm(5, 0, .1), + sigma = .1 + ) +) + +pars <- c(a = 1) +times <- seq(0, 5, .1) +plot((g*x)(times, pars), data) + +## Fits from random starts, stored in a parlist +obj <- normL2(data, g*x) +out <- as.parlist(lapply(1:5, function(i) { + trust(obj, pars + rnorm(length(pars), 0, 1), rinit = 1, rmax = 10) +})) +summary(out) + +## Parameter frame and best fit +parframe <- as.parframe(out) +plotValues(parframe) +unique(parframe) +bestfit <- as.parvec(parframe) +plot((g*x)(times, bestfit), data) +} +} \seealso{ \code{\link[=as.parframe]{as.parframe()}}, \code{\link[=parvec]{parvec()}} } diff --git a/man/c.parvec.Rd b/man/c.parvec.Rd index 77fde860..62240a50 100644 --- a/man/c.parvec.Rd +++ b/man/c.parvec.Rd @@ -15,3 +15,39 @@ Object of class \code{parvec}. \description{ Concatenates \code{parvec} objects with their derivatives. } +\examples{ +## Parameter vector without derivatives +p <- as.parvec(c(a = 1, b = 2, c = 3)) +p + +## Jacobian and second derivatives +J <- matrix(c(1, 0, 0, + 0, 2, 0, + 0, 0, 3), + nrow = 3, byrow = TRUE, + dimnames = list(c("a", "b", "c"), c("x", "y", "z"))) + +H <- array(0, dim = c(3, 3, 3), + dimnames = list(c("a", "b", "c"), + c("x", "y", "z"), + c("x", "y", "z"))) +H["a", "x", "x"] <- 1 +H["b", "y", "y"] <- 2 +H["c", "z", "z"] <- 3 + +p2 <- as.parvec(c(a = 10, b = 20, c = 30), deriv = J, deriv2 = H) +p2 +getDerivs(p2) +getDerivs2(p2) + +## Subsetting keeps the matching derivatives +p_sub <- p2[c("a", "b")] +getDerivs(p_sub) + +## Concatenation +p3 <- as.parvec(c(d = 4, e = 5)) +c(p2, p3) + +## From numbers +parvec(a = 1, b = 2) +} diff --git a/man/covariates.Rd b/man/covariates.Rd index 1dcfb26e..eac25d5a 100644 --- a/man/covariates.Rd +++ b/man/covariates.Rd @@ -26,6 +26,36 @@ frame. \description{ Access the Covariates in the Data } +\examples{ +## Generate datalist from scratch +mydata1 <- data.frame(name = "A", + time = 0:5, + value = 0:5, + sigma = .1, + lloq = -0.5) + +mydata2 <- data.frame(name = "A", + time = 0:5, + value = sin(0:5), + sigma = .1) + +data <- datalist(C1 = mydata1, C2 = mydata2) +print(data) +plot(data) + +## Split one data.frame into conditions, keeping a covariate per condition +t <- seq(0, 2*pi, length.out = 20) +long <- data.frame(name = "A", time = c(t, t), sigma = 0.1, + amplitude = rep(c(1, 1.5), each = 20), + phase = rep(c("early", "late"), each = 20), + stage = rep(rep(c("upper", "lower"), each = 10), 2)) +long$value <- long$amplitude * sin(long$time) + +data <- as.datalist(long, splitBy = c("stage", "phase"), keepCovariates = "amplitude") +print(data) +plot(data) +print(covariates(data)) +} \seealso{ \code{\link[=as.datalist]{as.datalist()}} } diff --git a/man/customTotals.Rd b/man/customTotals.Rd index 42ed9a9d..64fd1b35 100644 --- a/man/customTotals.Rd +++ b/man/customTotals.Rd @@ -21,6 +21,17 @@ replace the detected basis, also as parameters of \code{\link[=Pimpl]{Pimpl()}}. expression must be linear in the states and conserved by the reactions, and together they must span as many quantities as \code{\link[=conservedQuantities]{conservedQuantities()}} finds. } +\examples{ +## A reversible conversion conserves A + B +el <- addReaction(eqnlist(), "A", "B", "k1*A") +el <- addReaction(el, "B", "A", "k2*B") +conservedQuantities(el) + +## Name the conserved quantity, then return to the detected basis +el <- customTotals(el, list(total = "A + B")) +el$totals +el <- customTotals(el, NULL) +} \seealso{ \code{\link[=conservedQuantities]{conservedQuantities()}} } diff --git a/man/discreteSymmetries.Rd b/man/discreteSymmetries.Rd index 2e532d57..d17277be 100644 --- a/man/discreteSymmetries.Rd +++ b/man/discreteSymmetries.Rd @@ -8,9 +8,13 @@ discreteSymmetries( object, order = NULL, points = 5L, - timeout = 600, - budget = 300, - cores = 1 + cores = 1, + memory = NULL, + experiments = NULL, + msolveEntries = NULL, + msolveTerms = NULL, + searchEntries = NULL, + eliminationTerms = NULL ) } \arguments{ @@ -22,12 +26,26 @@ coordinates.} \item{points}{Number of random points of the count in the domain, or a list of points, each a named list of the coordinates. Defaults to 5.} -\item{timeout}{Seconds one call of msolve may take. Defaults to 600.} +\item{cores}{Threads of msolve. Defaults to 1.} -\item{budget}{Seconds the reconstruction of the maps may take; past it, the counts -are reported without closed forms. Defaults to 300.} +\item{memory}{GiB of address space one call of msolve may take; past it the call +fails. \code{NULL} (default) keeps the value of symident (8).} -\item{cores}{Threads of msolve. Defaults to 1.} +\item{experiments}{Count on several experiments with shared parameters and free +starts, which bounds the fiber of a model with free starts and no rational first +integral: \code{NULL} (default) where a short count of one experiment finds none, \code{TRUE} +first with the number of experiments from the rank criterion, a number \code{K} with \code{K} +experiments, \code{FALSE} never.} + +\item{msolveEntries}{Nonzero entries of the F4 matrices one call of msolve may reduce.} + +\item{msolveTerms}{Terms of the largest system given to msolve.} + +\item{searchEntries}{Entries of the matrices over finite fields the exact count may +reduce.} + +\item{eliminationTerms}{Terms of the largest polynomial of the elimination of the +states in the exact count.} } \value{ \code{object} with \code{discreteSymmetries}, per \eqn{\sigma} the \code{map} of the @@ -35,11 +53,18 @@ coordinates it changes (an \link{eqnvec}), \code{changes}, \code{level}, \code{p (\code{TRUE}, \code{FALSE}, or \code{NULL} with the \code{domainConditions} under which \eqn{\sigma(\theta)} lies in the domain) and \code{fixedSet}, the factors on which \eqn{\sigma} fixes \eqn{\theta}; and \code{info$discrete} with \code{order}, \code{count} (the -solutions over the algebraic closure at a random point modulo a prime), \code{counts} -per point (\code{complex}, \code{real}, \code{inDomain}, \code{undecided}), \code{closedForms}, \code{countFinal} -(every solution is the image of a proven \eqn{\sigma}), \code{fundamentalDomain} -(inequalities that keep one point of each orbit), \code{limits} and, for a model with -directions, \code{reduced}. +solutions over the algebraic closure at a random point modulo a prime), \code{countBound} +(the probability that a generic point has more, \code{NULL} where the count is exact or has +no bound), \code{countDomain} (the points of the fiber of a generic point inside the +domain, where that number is final), \code{counts} per point (\code{complex}, \code{real}, +\code{inDomain}, \code{undecided}), \code{closedForms}, \code{countFinal} (every solution is the image of +a proven \eqn{\sigma}), \code{fundamentalDomain} (inequalities that keep one point of each +orbit), \code{certificate} (what the result rests on, with \code{complete}: \code{"exact"}, +\code{"verified"}, \code{"axiom"}, \code{"no"} or \code{"open"}), \code{experiments} (the count on several +experiments, or why it does not apply), \code{limits} and, where they apply, \code{reduced} (for +a model with directions), \code{eliminated} (under \code{reduceCQ}, the species solved through +the totals), \code{relaxed} (the model with non-rational terms of the states as new states) +and \code{unsupported}. } \description{ Searches the discrete symmetries of a \code{\link[=symmetryDetection]{symmetryDetection()}} result: other points @@ -51,16 +76,21 @@ may differ between regions. Where the other points are rational functions \eqn{\sigma} of the coordinates, \eqn{\sigma} is reconstructed, checked on the output at random points (\code{"checked"}) and, where every state has a free initial value, proven by a map of the states (\code{"exact"}). A model with directions is reduced by -\code{\link[=symmetryReduction]{symmetryReduction()}} first and the reduced model is analyzed. +\code{\link[=symmetryReduction]{symmetryReduction()}} first and the reduced model is analyzed. The search stops on work +limits, never on a clock, so the result is the same on every machine; a count or proof +that reaches a limit ends without a result and names the limit in \code{limits} or in the +certificate. } \details{ The search needs msolve; \code{\link[=symmetryDetection]{symmetryDetection()}} says where it is searched. +The defaults of \code{msolveEntries}, \code{msolveTerms}, \code{searchEntries} and \code{eliminationTerms} +(\code{NULL}) keep the values of symident. } \examples{ \dontshow{if (requireNamespace("reticulate", quietly = TRUE) && reticulate::py_module_available("symident.install") && !is.null(tryCatch(reticulate::import("symident.install")$find_msolve()[[1]], error = function(e) NULL))) withAutoprint(\{ # examplesIf} # two compartments, an input u into the first, the second observed f <- eqnvec(x1 = "-(k21 + k01)*x1 + k12*x2 + u", x2 = "k21*x1 - k12*x2") -res <- symmetryDetection(f, eqnvec(y = "x2"), knownInputs = "u", discrete = TRUE) +res <- symmetryDetection(f, eqnvec(y = "x2"), knownInputs = "u", mode = "global") res res$discreteSymmetries[[1]]$map res$info$discrete$fundamentalDomain diff --git a/man/em.Rd b/man/em.Rd index 4630d82f..feac7cea 100644 --- a/man/em.Rd +++ b/man/em.Rd @@ -137,7 +137,9 @@ importance sampling.} \item{\code{coupling}}{\code{"expectationConsistent"} where a group needed it, else \code{NULL}.} \item{\code{boundary}}{the hyperparameters set to 0, see \code{control}.} -\item{\code{etaModes}, \code{etaSE}, \code{shrinkage}}{} +\item{\code{etaModes}, \code{etaSE}, \code{shrinkage}}{the modes of the random effects per +group, their conditional standard errors, and per random effect +1 - SD(modes) / SD from Omega.} \item{\code{certificate}}{with method \code{"quadrature"} per group the importance-sampling check at the estimate, section Quadrature.} } @@ -166,11 +168,16 @@ exact derivative of the volume term. The default, and the method for several groupings; also for spike-and-slab and Dirichlet-process random effects (at most 14 groups).} \item{\code{"quadrature"}}{adaptive sparse-grid quadrature around the modes, -started from the FOCEI fit; section Quadrature.} +started from the FOCEI fit; section Quadrature. Also for spike-and-slab +random effects alone, per subset; section Sparse random effects.} \item{\code{"laplaceEM"}}{ECM on the Laplace approximation with the covariance-corrected update of \code{Omega}.} \item{\code{"saem"}}{stochastic-approximation EM, also for spike-and-slab and -Dirichlet-process random effects; section SAEM.} +Dirichlet-process random effects; section SAEM. With many structural +parameters and sparse random effects it does not find the optimum from +random starts reliably; start it from a \code{"focei"} fit, +\code{em(obj, random, fit, method = "saem")}, to check that fit without the +Laplace approximation.} } } \section{Quadrature}{ @@ -180,16 +187,22 @@ modes at the current parameters and one trust step over every parameter on these frozen nodes. The nodes of the mu-referenced fixed effects are frozen in \verb{phi = X beta + eta}. Entries of \code{control$quadrature}: \describe{ -\item{\code{tol}}{allowed change of -2 log L by the next level, default 0.1, -split over the groups; each group takes the lowest level from the current -stage of the group up within \code{tol / G} and never a lower one than before. -Where the next level exceeds \code{maxNodes}, the change from the level below -is the estimate. \code{Inf} keeps the levels of the stages.} +\item{\code{tol}}{allowed change of -2 log L by the next refinement, default +0.1, split over the groups. Each group starts from the Smolyak grid of +the stage and the grid of the last rebuild, and refines it +dimension-adaptively (Gerstner and Griebel 2003): the forward neighbors +of the grid are evaluated, their change of -2 log L is the error, and the +neighbor of largest change joins the grid until the error is within +\code{tol / G}. A grid therefore refines only the directions in which the +integrand departs from the Gaussian at the mode. Where the next +refinement exceeds \code{maxNodes}, the evaluated neighbors join the grid and +their change is the estimate. \code{Inf} keeps the grids of the stages.} \item{\code{levels}}{the stages, default \code{K + 1} with \code{K} the number of random effects of a group; level \code{K + s} integrates polynomials of total degree \verb{2 s + 1} exactly.} \item{\code{maxLevel}, \code{maxNodes}}{highest level, default \code{K + 8}, and the -largest node count of a level per group, default 1000. A group whose +largest number of evaluated nodes per group, default 1000; the level of +an adaptive grid is that of the smallest Smolyak grid holding it. A group whose error exceeds \code{tol / G} at the highest level within both is capped. Column \code{capped} of \code{stageTrace} counts the capped groups; attribute \code{"levels"} of \code{stageTrace} and the \code{certificate} list level, level error @@ -212,7 +225,8 @@ 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{\code{epsEcm}, \code{maxEcm}}{for \code{"laplaceEM"}: the extrapolated distance to -the fixed point at which it stops, default 1e-5, and the iteration limit.} +the fixed point at which it stops, default 1e-5, and the iteration limit, +default 200.} } } @@ -280,8 +294,9 @@ partitions, with \code{valueSE}. \section{Sparse random effects}{ -With spike-and-slab or Dirichlet-process random effects the -parameters and hyperparameters move in one trust region. The integral of a +With spike-and-slab random effects of the default \verb{spike = 0, mean = 0} or +Dirichlet-process random effects, \code{method = "focei"} moves the +parameters and hyperparameters in one trust region. The integral of a group is exact where the data couple none of the factors and the sum over the subsets of the spike-and-slab random effects of the group stays within a budget of nodes; else it is the expectation consistent (EC) approximation, and a @@ -291,7 +306,62 @@ trial point at which EC does not converge is a failed evaluation. Entries of \co \item{\code{trustControl}}{the \code{\link[=trust]{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 \code{control$innerControl} only \code{sqpIterlim} applies.} +\item{\code{maxEcm}, \code{epsEcm}, \code{budget}, \code{ec}}{of the sum over subsets, see below.} } + +Spike-and-slab random effects with \code{mean} or \code{spike} other than 0, see +\code{\link[=spikeSlab]{spikeSlab()}}, take a separate path of \code{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; \code{spike = -Inf} switches the +parameter off. The number of subsets summed over all groups is at most +\code{budget} (default 4096). The fixed effects and hyperparameters follow by EM: +\code{prob} is the mean inclusion probability, \code{tau^2} the mean squared deviation +from \code{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 +\code{maxEcm} iterations (default 200) or when no +estimate changes by more than \code{epsEcm} (default 1e-6). The \code{p0} column of +the random table is the posterior probability of the spike. + +\code{method = "saem"} draws them by the moves of section SAEM: a spike at +\code{-Inf} leaves the other slab values as they are, and a move into the slab +proposes from the Laplace approximation of the coordinate given the others, +by Newton steps on the model. The reported -2 log L is the sum over subsets +of \code{method = "focei"} at the estimate; Dirichlet-process random effects +beside are refused. + +\code{method = "quadrature"} takes the same path for every model with +spike-and-slab random effects, the default \code{spike = 0} included, after EM on +the Laplace integrals to their fixed point. Every subset of Laplace weight +above 1e-8 of the largest is integrated on a dimension-adaptive sparse grid +around the inner mode as in section Quadrature; a group has +\code{control$quadrature$tol / G} (default 0.1 / G), a subset of relative weight +\eqn{w} the share \eqn{1 / w} of it, so that light subsets stay on the first +grid; the other subsets keep the Laplace value. Then every parameter, the +Cholesky parameters of Omega and the estimated \code{prob} and \code{tau} included, +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 \code{tolDecrement} +(\code{stopReason} \code{"decrement"}). Of \code{control$quadrature} this path reads \code{tol}, +\code{maxLevel} and \code{maxNodes} (per subset), \code{tolDecrement}, \code{maxEcmPerStage}, +\code{cm1Control} and \code{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 +\eqn{b^\eta}{b^eta} for \code{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 +exactly, without sites. These groups take the subset of +inclusion probability above 1/2 for the fixed effects. Entries of +\code{control$sparseFit$ec}: \code{nodes} of the Gauss-Hermite rule of the log-normal +slab (40), \code{maxSweeps} (500) and \code{tolSweep} (1e-5, the change of the +marginal means in standard deviations), \code{maxRelinearize} (30) and +\code{tolRelinearize} (1e-4, relative). } \examples{ diff --git a/man/eqnvec.Rd b/man/eqnvec.Rd index 33698652..a3da5540 100644 --- a/man/eqnvec.Rd +++ b/man/eqnvec.Rd @@ -28,6 +28,8 @@ v <- eqnvec(y = "2*x + offset") print(v) is.eqnvec(v) +format(eqnvec(y = "2*x+offset")) +summary(v) } \seealso{ \link{eqnlist} diff --git a/man/exportSbml.Rd b/man/exportSbml.Rd index a0cac974..b3365ed5 100644 --- a/man/exportSbml.Rd +++ b/man/exportSbml.Rd @@ -33,8 +33,10 @@ formulas. Missing states default to 0. Default \code{NULL}.} \item{modelID}{SBML model identifier. Defaults to \code{"dMod_export"}.} \item{events}{Object of class \link{eventlist} to emit as \verb{}, or -\code{NULL}. Rows sharing a trigger become one \verb{}. A compartment an event assigns to is written -as non-constant. Default \code{NULL}.} +\code{NULL}. Rows sharing a trigger become one \verb{}. A root event becomes two events with +the triggers \code{root >= 0} and \code{root <= 0}, initially true, so that the SBML model fires at +crossings in both directions and not at the start, as cppDE does. A compartment an event +assigns to is written as non-constant. Default \code{NULL}.} } \value{ \code{filepath}, invisibly. diff --git a/man/fitErrorModel.Rd b/man/fitErrorModel.Rd index d0378b89..22a81ab2 100644 --- a/man/fitErrorModel.Rd +++ b/man/fitErrorModel.Rd @@ -25,8 +25,8 @@ fitErrorModel( combinations define groups. The model is fitted separately per group.} \item{errorModel}{Character, the variance of a single measurement as an -expression in the mean \code{x} and the parameters. Default -\code{"exp(s0)+exp(srel)*x^2"}.} +expression in the mean \code{x} and the parameters, built from the functions +\code{\link[stats:deriv]{stats::deriv()}} differentiates. Default \code{"exp(s0)+exp(srel)*x^2"}.} \item{par}{Named numeric vector of starting values for the parameters of \code{errorModel}. Default \code{c(s0 = 1, srel = 0.1)}.} @@ -50,7 +50,7 @@ the fitted model gives. With \code{blather = TRUE}, a data frame with the columns of \code{data}, \code{sigma} replaced as above, one column per parameter of \code{errorModel} with the fitted value, the variance bands \code{cbLower68}, \code{cbUpper68}, \code{cbLower95} and -\code{cbUpper95}, the group label \code{condidnt} and the input \code{sigma} as +\code{cbUpper95}, the group label \code{group} and the input \code{sigma} as \code{sigmaLS}. The attribute \code{"errorModel"} holds \code{errorModel}. } \description{ diff --git a/man/format.eqnvec.Rd b/man/format.eqnvec.Rd index 27eee653..cf0f8750 100644 --- a/man/format.eqnvec.Rd +++ b/man/format.eqnvec.Rd @@ -17,3 +17,11 @@ Named character vector with spaces around \code{+}, \code{-}, \code{*} and \code \description{ Format Equation Vector with Spaces } +\examples{ +v <- eqnvec(y = "2*x + offset") +print(v) +is.eqnvec(v) + +format(eqnvec(y = "2*x+offset")) +summary(v) +} diff --git a/man/getConditions.Rd b/man/getConditions.Rd index 43e799fd..c3ab04d0 100644 --- a/man/getConditions.Rd +++ b/man/getConditions.Rd @@ -24,3 +24,20 @@ for every condition. \description{ Extract the Conditions of an Object } +\examples{ +## Accessors read the generated objects, no compiled code is needed +g <- Y(c(Aobs = "s*A"), states = "A", parameters = "s", compile = FALSE, + modelname = "accessors_obs", outdir = tempdir()) +p <- P(list(C1 = eqnvec(A = "A0", s = "s"), C2 = eqnvec(A = "2*A0", s = "s")), + compile = FALSE, modelname = "accessors_p", outdir = tempdir()) + +getParameters(g) +getParameters(p) +getConditions(p) +getEquations(p, conditions = "C2") + +modelname(g) +modelname(g, p) +modelname(p) <- "accessors_trafo" +modelname(p) +} diff --git a/man/getEquations.Rd b/man/getEquations.Rd index 5a87a159..9a28e8e7 100644 --- a/man/getEquations.Rd +++ b/man/getEquations.Rd @@ -26,3 +26,20 @@ model. \description{ Extract the Equations of an Object } +\examples{ +## Accessors read the generated objects, no compiled code is needed +g <- Y(c(Aobs = "s*A"), states = "A", parameters = "s", compile = FALSE, + modelname = "accessors_obs", outdir = tempdir()) +p <- P(list(C1 = eqnvec(A = "A0", s = "s"), C2 = eqnvec(A = "2*A0", s = "s")), + compile = FALSE, modelname = "accessors_p", outdir = tempdir()) + +getParameters(g) +getParameters(p) +getConditions(p) +getEquations(p, conditions = "C2") + +modelname(g) +modelname(g, p) +modelname(p) <- "accessors_trafo" +modelname(p) +} diff --git a/man/getLocalDLLs.Rd b/man/getLocalDLLs.Rd index 353d56c1..8e4a5792 100644 --- a/man/getLocalDLLs.Rd +++ b/man/getLocalDLLs.Rd @@ -14,6 +14,10 @@ path lies in the working directory. Only the working directory is searched, not \code{getOption("dMod2.outdir")} or the directories the objects were generated in. } +\examples{ +## Names of the loaded shared objects below the working directory +getLocalDLLs() +} \seealso{ \code{\link[=loadDLL]{loadDLL()}} } diff --git a/man/getObservables.Rd b/man/getObservables.Rd deleted file mode 100644 index 220206ac..00000000 --- a/man/getObservables.Rd +++ /dev/null @@ -1,19 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/accessors.R -\name{getObservables} -\alias{getObservables} -\title{Extract the Observables of an Object} -\usage{ -getObservables(x, ...) -} -\arguments{ -\item{x}{object from which the observables are extracted.} - -\item{...}{not used.} -} -\value{ -The observables, as a character vector. -} -\description{ -Generic without methods in dMod2; other packages can provide them. -} diff --git a/man/getParameters.Rd b/man/getParameters.Rd index 4eb6c56c..e9687596 100644 --- a/man/getParameters.Rd +++ b/man/getParameters.Rd @@ -45,3 +45,20 @@ and parameters; for a \code{prdlist}, a list with one entry per condition. \description{ Extract the Parameters of an Object } +\examples{ +## Accessors read the generated objects, no compiled code is needed +g <- Y(c(Aobs = "s*A"), states = "A", parameters = "s", compile = FALSE, + modelname = "accessors_obs", outdir = tempdir()) +p <- P(list(C1 = eqnvec(A = "A0", s = "s"), C2 = eqnvec(A = "2*A0", s = "s")), + compile = FALSE, modelname = "accessors_p", outdir = tempdir()) + +getParameters(g) +getParameters(p) +getConditions(p) +getEquations(p, conditions = "C2") + +modelname(g) +modelname(g, p) +modelname(p) <- "accessors_trafo" +modelname(p) +} diff --git a/man/importSbml.Rd b/man/importSbml.Rd index a8a235fa..356098d2 100644 --- a/man/importSbml.Rd +++ b/man/importSbml.Rd @@ -29,6 +29,8 @@ name, already substituted into rates, initial values and observables.} states when an event changes a compartment volume.} \item{\code{eventsSource}}{An \link{eventlist} or \code{NULL}, the event assignments of the SBML file only.} +\item{\code{compartmentInits}}{Named character, the size at the start of each +compartment an event assigns to; such a compartment keeps the id as volume.} \item{\code{renamed}}{Named character, the new ids of SBML ids that are no valid R or C++ names, named by the old ids.} } diff --git a/man/load.parlist.Rd b/man/load.parlist.Rd index ac692b10..ecff5174 100644 --- a/man/load.parlist.Rd +++ b/man/load.parlist.Rd @@ -11,11 +11,22 @@ load.parlist(folder) of the run, which holds one \verb{fit-.Rda} per completed fit.} } \value{ -A parlist. +A parlist with one entry per file, in the order of the fit numbers. } \description{ Reads the per-fit files that \code{\link[=mstrust]{mstrust()}} writes with \code{output = TRUE}, for example after an aborted run. +} +\examples{ +folder <- file.path(tempdir(), "interRes") +dir.create(folder, showWarnings = FALSE) +for (i in 1:3) + saveRDS(list(value = 10 / i, converged = TRUE, iterations = 5L, argument = c(a = i)), + file.path(folder, paste0("fit-", i, ".Rda"))) +fits <- load.parlist(folder) +as.parframe(fits) +unlink(folder, recursive = TRUE) + } \seealso{ \code{\link[=mstrust]{mstrust()}} diff --git a/man/modelname.Rd b/man/modelname.Rd index ec02491f..51873a6a 100644 --- a/man/modelname.Rd +++ b/man/modelname.Rd @@ -46,6 +46,23 @@ The model name is the base name of the generated sources and shared objects of a function such as a prediction function, parameter transformation or objective function. } +\examples{ +## Accessors read the generated objects, no compiled code is needed +g <- Y(c(Aobs = "s*A"), states = "A", parameters = "s", compile = FALSE, + modelname = "accessors_obs", outdir = tempdir()) +p <- P(list(C1 = eqnvec(A = "A0", s = "s"), C2 = eqnvec(A = "2*A0", s = "s")), + compile = FALSE, modelname = "accessors_p", outdir = tempdir()) + +getParameters(g) +getParameters(p) +getConditions(p) +getEquations(p, conditions = "C2") + +modelname(g) +modelname(g, p) +modelname(p) <- "accessors_trafo" +modelname(p) +} \seealso{ \code{\link[=compile]{compile()}}, \code{\link[=loadDLL]{loadDLL()}} } diff --git a/man/normal.Rd b/man/normal.Rd index 6f204d7e..85eccb19 100644 --- a/man/normal.Rd +++ b/man/normal.Rd @@ -8,7 +8,7 @@ \usage{ normal() -spikeSlab(prob = NULL, tau = NULL) +spikeSlab(prob = NULL, tau = NULL, mean = 0, spike = 0) dirichletProcess(concentration = NULL, tau = NULL) } @@ -18,6 +18,12 @@ dirichletProcess(concentration = NULL, tau = NULL) \item{tau}{Standard deviation of the slab; \code{NULL} (default) estimates it.} +\item{mean}{Mean of the slab, one finite number, not estimated.} + +\item{spike}{Value of the spike, one finite number or \code{-Inf}, not +estimated. \code{-Inf} needs the random effect as a summand in the exponent +of a numeric base greater than 1, as after \code{insert(trafo, "x <- exp(x)")}.} + \item{concentration}{Concentration of the Ewens prior, positive; \code{NULL} (default) estimates it.} } @@ -32,11 +38,12 @@ estimated by \code{\link[=em]{em()}} unless given. \itemize{ \item \code{normal()}: multivariate normal with mean 0 and a covariance estimated per correlation block. The default. -\item \code{spikeSlab()}: the deviation of a group is exactly 0 (spike) or drawn -from \eqn{N(0, \tau^2)}{N(0, tau^2)} (slab); every group deviates with -probability \code{prob}, independently. The spike-and-slab random effects of -a group are integrated jointly, see section Sparse random effects of -\code{\link[=em]{em()}}. +\item \code{spikeSlab()}: the deviation of a group is exactly \code{spike} (spike) or +drawn from \eqn{N(\mu, \tau^2)}{N(mean, tau^2)} (slab); every group +deviates with probability \code{prob}, independently. The spike-and-slab +random effects of a group are integrated jointly, see section Sparse +random effects of \code{\link[=em]{em()}}. With \code{spike = -Inf} under an exponential +transformation, the spike switches the parameter off. \item \code{dirichletProcess()}: per symbol, the deviations follow a Dirichlet process with base measure \eqn{N(0, \tau^2)}{N(0, tau^2)} and \code{concentration}, the fixed effect seated first at deviation 0: the @@ -56,6 +63,7 @@ the clusters of any number of groups. normal() spikeSlab() spikeSlab(prob = 0.2, tau = 0.5) +spikeSlab(mean = log(0.5), spike = -Inf) dirichletProcess() dirichletProcess(concentration = 1) @@ -65,6 +73,13 @@ trafo <- branch(define(NULL, "x <- x", x = c("kp", "kd")), table = cov) trafo <- insert(trafo, "x <- exp(x)", x = c("kp", "kd")) trafo <- insert(trafo, x ~ 1 + (1 | gr(line, dist = dirichletProcess())), x = c("kp", "kd")) randomEffects(trafo) + +## reaction rates switched off by a spike at -Inf, one group of all conditions +sel <- branch(define(NULL, "x <- x", x = c("kp", "kd")), table = cov) +sel <- insert(sel, "x <- exp(x)", x = c("kp", "kd")) +sel <- insert(sel, x ~ 0 + (1 | gr(dist = spikeSlab(mean = log(0.5), spike = -Inf))), + x = c("kp", "kd")) +randomEffects(sel) } \seealso{ \code{\link[=randomEffects]{randomEffects()}}, \code{\link[=insert]{insert()}} diff --git a/man/objframe.Rd b/man/objframe.Rd index 8ab5f467..791b3640 100644 --- a/man/objframe.Rd +++ b/man/objframe.Rd @@ -37,3 +37,15 @@ attached as \code{"deriv2"} / \code{"deriv2.err"}. An objective frame stores residuals and their derivatives with respect to parameters, as \code{\link[=res]{res()}} returns them. } +\examples{ +## Prediction with the derivative of the observable y in the parameter k +times <- 0:2 +J <- array(-times * exp(-times), c(3, 1, 1), list(NULL, "y", "k")) +out <- prdframe(cbind(time = times, y = exp(-times)), deriv = J, parameters = c(k = 1)) + +data <- data.frame(time = times, name = "y", value = c(1.05, 0.35, 0.15), + sigma = 0.1, lloq = -Inf) +r <- res(data, out) +r +attr(r, "deriv") +} diff --git a/man/parlist.Rd b/man/parlist.Rd index 57933104..a36ce94a 100644 --- a/man/parlist.Rd +++ b/man/parlist.Rd @@ -69,6 +69,7 @@ summary(out) ## Parameter frame and best fit parframe <- as.parframe(out) plotValues(parframe) +unique(parframe) bestfit <- as.parvec(parframe) plot((g*x)(times, bestfit), data) } diff --git a/man/plotPairs.Rd b/man/plotPairs.Rd deleted file mode 100644 index a6d0f921..00000000 --- a/man/plotPairs.Rd +++ /dev/null @@ -1,21 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/plots.R -\name{plotPairs} -\alias{plotPairs} -\title{Pair Plot of Parameter Samples} -\usage{ -plotPairs(x, ...) -} -\arguments{ -\item{x}{Object holding parameter samples.} - -\item{...}{Method-specific arguments.} -} -\value{ -A \code{ggplot} object, as returned by the method. -} -\description{ -Generic for a corner plot of sampled parameters: scatter plots of pairs in -the lower triangle, marginal densities on the diagonal. dMod2 defines no -method for it; packages and extensions that return samples do. -} diff --git a/man/plotProfilesAndPaths.Rd b/man/plotProfilesAndPaths.Rd index 79a726ea..62abc178 100644 --- a/man/plotProfilesAndPaths.Rd +++ b/man/plotProfilesAndPaths.Rd @@ -11,6 +11,8 @@ plotProfilesAndPaths( ncol = 3, normalizePaths = FALSE, modes = c("data", "prior"), + maxvalue = 5, + threshold = .profileLines(), ... ) } @@ -30,6 +32,9 @@ absolute value of 1. Defaults to \code{FALSE}.} \item{modes}{Character vector, the contributions to the objective drawn in the profile plot besides the total. Defaults to \code{c("data", "prior")}.} +\item{maxvalue, threshold}{Cut-off of the objective difference and the +horizontal lines above the optimum, as in \code{\link[=plotProfile]{plotProfile()}}.} + \item{...}{Further arguments passed to \code{\link[cowplot:plot_grid]{cowplot::plot_grid()}}.} } \value{ diff --git a/man/plus-.objlist.Rd b/man/plus-.objlist.Rd index a0096162..074fd3ac 100644 --- a/man/plus-.objlist.Rd +++ b/man/plus-.objlist.Rd @@ -24,3 +24,13 @@ out. Numeric attributes are added, an absent one counting as zero. The \code{attrName} gives one attribute \code{chi2}, several give \verb{chi2_} each. } +\examples{ +## Two priors on overlapping parameters +obj1 <- constraintL2(mu = c(a = 0, b = 0), sigma = 1) +obj2 <- constraintL2(mu = c(b = 1, c = 1), sigma = 1) + +## Gradients and Hessians are matched by parameter name +total <- obj1(c(a = 1, b = 2)) + obj2(c(b = 2, c = 3)) +total$value +total$gradient +} diff --git a/man/prdframe.Rd b/man/prdframe.Rd index 8cd94651..7da5db85 100644 --- a/man/prdframe.Rd +++ b/man/prdframe.Rd @@ -34,6 +34,17 @@ Prediction lists (\link{prdlist}) returned by \code{\link[=Xs]{Xs()}}, \code{\li of prediction frames. A custom prediction function (see \code{P2X} in \code{\link[=prdfn]{prdfn()}}) returns one. } +\examples{ +## Prediction frames of a decay at two rates, without derivatives +times <- 0:4 +frame1 <- prdframe(cbind(time = times, A = exp(-times)), parameters = c(k = 1)) +frame2 <- prdframe(cbind(time = times, A = exp(-2 * times)), parameters = c(k = 2)) +frame1 + +## One frame per condition, in long format +pred <- prdlist(slow = frame1, fast = frame2) +as.data.frame(pred) +} \seealso{ \code{\link[=getDerivs]{getDerivs()}}, \code{\link[=getDerivs2]{getDerivs2()}} } diff --git a/man/prdlist.Rd b/man/prdlist.Rd index 34e58a3f..142dba25 100644 --- a/man/prdlist.Rd +++ b/man/prdlist.Rd @@ -28,6 +28,17 @@ Object of class \code{prdlist}. A prediction list holds model predictions, one \link{prdframe} per condition or parameter set. Prediction functions return prediction lists. } +\examples{ +## Prediction frames of a decay at two rates, without derivatives +times <- 0:4 +frame1 <- prdframe(cbind(time = times, A = exp(-times)), parameters = c(k = 1)) +frame2 <- prdframe(cbind(time = times, A = exp(-2 * times)), parameters = c(k = 2)) +frame1 + +## One frame per condition, in long format +pred <- prdlist(slow = frame1, fast = frame2) +as.data.frame(pred) +} \seealso{ \code{\link[=prdfn]{prdfn()}}, \code{\link[=plotCombined]{plotCombined()}} } diff --git a/man/print.eqnlist.Rd b/man/print.eqnlist.Rd index a3a81f6d..3affbf94 100644 --- a/man/print.eqnlist.Rd +++ b/man/print.eqnlist.Rd @@ -19,3 +19,34 @@ \description{ Print or Pander Equation List } +\examples{ +# Generate eqnlist from the constructor +S <- matrix(c(-1, 1, 1, -1), + nrow = 2, ncol = 2, + dimnames = list(NULL, c("A", "B"))) + +rates <- c("k1*A", "k2*B") +description <- c("forward", "backward") + +f <- eqnlist(smatrix = S, rates = rates, description = description) +print(f) + +# Convert to data.frame +fdata <- as.data.frame(f) +print(fdata) + +# Flat `volumes`: each distinct expression becomes a compartment c1, c2, ... +f <- as.eqnlist(fdata, volumes = c(A = "Vcyt", B = "Vnuc")) +print(f) +print(as.eqnvec(f)) +print(as.eqnvec(f, type = "amount")) + +# Named compartments with explicit state assignment +f2 <- eqnlist( + smatrix = S, rates = rates, description = description, + compartments = list(cyt = "Vcyt", nuc = "Vnuc"), + compartmentOf = c(A = "cyt", B = "nuc") +) +print(f2) +print(as.eqnvec(f2)) +} diff --git a/man/print.eqnvec.Rd b/man/print.eqnvec.Rd index 46c75351..420b2198 100644 --- a/man/print.eqnvec.Rd +++ b/man/print.eqnvec.Rd @@ -21,3 +21,11 @@ \description{ Print Equation Vector } +\examples{ +v <- eqnvec(y = "2*x + offset") +print(v) +is.eqnvec(v) + +format(eqnvec(y = "2*x+offset")) +summary(v) +} diff --git a/man/print.parfn.Rd b/man/print.parfn.Rd index 9f9186fa..47cc336e 100644 --- a/man/print.parfn.Rd +++ b/man/print.parfn.Rd @@ -17,3 +17,15 @@ \description{ Print Parameter Transformations } +\examples{ +\donttest{ +## One transformation per condition, all compiled into one shared object +trafo <- list( + ctrl = eqnvec(k1 = "exp(log_k1)", k2 = "exp(log_k2)", A = "A0"), + treat = eqnvec(k1 = "exp(log_k1 + log_fold)", k2 = "exp(log_k2)", A = "A0")) +p <- P(trafo, compile = TRUE, modelname = "P_example", outdir = tempdir()) +print(p) +getParameters(p) +p(c(log_k1 = 0, log_k2 = -1, A0 = 2, log_fold = log(3))) +} +} diff --git a/man/print.parvec.Rd b/man/print.parvec.Rd index 0373315c..666b6761 100644 --- a/man/print.parvec.Rd +++ b/man/print.parvec.Rd @@ -18,3 +18,39 @@ Prints a parameter vector with information about derivatives and fixed parameters. } +\examples{ +## Parameter vector without derivatives +p <- as.parvec(c(a = 1, b = 2, c = 3)) +p + +## Jacobian and second derivatives +J <- matrix(c(1, 0, 0, + 0, 2, 0, + 0, 0, 3), + nrow = 3, byrow = TRUE, + dimnames = list(c("a", "b", "c"), c("x", "y", "z"))) + +H <- array(0, dim = c(3, 3, 3), + dimnames = list(c("a", "b", "c"), + c("x", "y", "z"), + c("x", "y", "z"))) +H["a", "x", "x"] <- 1 +H["b", "y", "y"] <- 2 +H["c", "z", "z"] <- 3 + +p2 <- as.parvec(c(a = 10, b = 20, c = 30), deriv = J, deriv2 = H) +p2 +getDerivs(p2) +getDerivs2(p2) + +## Subsetting keeps the matching derivatives +p_sub <- p2[c("a", "b")] +getDerivs(p_sub) + +## Concatenation +p3 <- as.parvec(c(d = 4, e = 5)) +c(p2, p3) + +## From numbers +parvec(a = 1, b = 2) +} diff --git a/man/profileThreshold.Rd b/man/profileThreshold.Rd index b4ed3469..82429d88 100644 --- a/man/profileThreshold.Rd +++ b/man/profileThreshold.Rd @@ -27,6 +27,10 @@ finite-sample threshold \eqn{n\log(1 + F_{1,\nu,1-\alpha}/\nu)}, \eqn{\nu = n - p}, exact for Gaussian errors with a single sigma profiled out and the generalization of the classical t interval. } +\examples{ +profileThreshold(0.95) +profileThreshold(0.95, method = "F", n = 20, p = 3) +} \seealso{ \link[=profile.objfn]{profile()}, \code{\link[=confint.parframe]{confint.parframe()}} } diff --git a/man/randomEffects.Rd b/man/randomEffects.Rd index 7fe71182..c0f20b91 100644 --- a/man/randomEffects.Rd +++ b/man/randomEffects.Rd @@ -21,8 +21,8 @@ formulas, or a parameter function \code{\link[=P]{P()}} built from one.} An object of class \code{randomeffects}, a list with \code{terms} (one row per random effect column: \code{symbol}, \code{origin} (the formula), \code{term}, \code{column}, \code{group}, \code{id}, \code{dist}, the fixed hyperparameters \code{prob}, -\code{concentration} and \code{tau} (\code{NA} where estimated) and \code{stem}, the name -stem of the etas), +\code{concentration} and \code{tau} (\code{NA} where estimated), the given \code{mean} and +\code{spike} of spike-and-slab terms and \code{stem}, the name stem of the etas), \code{blocks} (groups of rows: the normal rows of a block are correlated, the rows of a spike-and-slab or Dirichlet-process block share the hyperparameters), \code{subjects} (the groups of each @@ -56,7 +56,11 @@ other columns are \verb{cl_} (\code{cl_wt}, \code{cl_log_wt}).} \code{(1 | p | ID)} with an ID \code{p}: terms with the same ID and grouping are correlated across formulas, the columns of one term are correlated, other terms are independent. \code{gr(ID, dist = spikeSlab())} instead of \code{ID} sets -the distribution, see \code{\link[=normal]{normal()}}. The random effect of a group is +the distribution, see \code{\link[=normal]{normal()}}; \code{gr(dist = )} without a grouping +makes one group \code{all} of all conditions, so that with \verb{0 +} the random +effect is the parameter itself, as in +\code{k1 + k2 ~ 0 + (1 | gr(dist = spikeSlab(spike = -Inf)))} for the +selection of reaction rates on the log scale. The random effect of a group is \verb{eta__} for the intercept and \verb{eta___} for a slope; a symbol with random terms in a second grouping gets the grouping name in the stem, \verb{eta_cl_center_}.} diff --git a/man/reconstControl.Rd b/man/reconstControl.Rd index 05aa3a8d..9ca4b9ba 100644 --- a/man/reconstControl.Rd +++ b/man/reconstControl.Rd @@ -22,7 +22,6 @@ reconstControl( perPrimeCap = 120L, perPrimeMinPrimes = 3L, homotopy = TRUE, - timeout = Inf, homotopyDegree = NULL, degreeCapMax = NULL, exactProof = NULL, @@ -75,9 +74,6 @@ reconstruction under \code{equilibrate = TRUE}. Defaults to 3.} \item{homotopy}{Whether directions still open under \code{equilibrate = TRUE} are fitted along lines in parameter space as a last route. Defaults to \code{TRUE}.} -\item{timeout}{Time limit in seconds for the reconstruction. Directions not -finished in time are reported by their support. \code{Inf} (default) sets no limit.} - \item{homotopyDegree}{Total degree bound of the entries the homotopy route fits.} \item{degreeCapMax}{Degree up to which an entry past \code{degreeCap} is probed again, @@ -105,7 +101,7 @@ default to \code{NULL}, which keeps the value of symident (4, 8, \code{TRUE}, 50 0). } \examples{ -reconstControl(degreeCap = 6L, timeout = 60) +reconstControl(degreeCap = 6L) } \seealso{ \code{\link[=symmetryDetection]{symmetryDetection()}} diff --git a/man/res.Rd b/man/res.Rd index 4f5ba82b..4a73712a 100644 --- a/man/res.Rd +++ b/man/res.Rd @@ -33,6 +33,18 @@ Matches data to the prediction by time and name and computes the residuals and their derivatives. Values below \code{lloq} are set to \code{lloq}. } +\examples{ +## Prediction with the derivative of the observable y in the parameter k +times <- 0:2 +J <- array(-times * exp(-times), c(3, 1, 1), list(NULL, "y", "k")) +out <- prdframe(cbind(time = times, y = exp(-times)), deriv = J, parameters = c(k = 1)) + +data <- data.frame(time = times, name = "y", value = c(1.05, 0.35, 0.15), + sigma = 0.1, lloq = -Inf) +r <- res(data, out) +r +attr(r, "deriv") +} \seealso{ \code{\link[=objframe]{objframe()}}, \code{\link[=normL2]{normL2()}} } diff --git a/man/sub-.parvec.Rd b/man/sub-.parvec.Rd index ff93ca97..9ad13db5 100644 --- a/man/sub-.parvec.Rd +++ b/man/sub-.parvec.Rd @@ -20,3 +20,39 @@ Object of class \code{parvec}. \description{ Subsets a \code{parvec} together with the derivatives. } +\examples{ +## Parameter vector without derivatives +p <- as.parvec(c(a = 1, b = 2, c = 3)) +p + +## Jacobian and second derivatives +J <- matrix(c(1, 0, 0, + 0, 2, 0, + 0, 0, 3), + nrow = 3, byrow = TRUE, + dimnames = list(c("a", "b", "c"), c("x", "y", "z"))) + +H <- array(0, dim = c(3, 3, 3), + dimnames = list(c("a", "b", "c"), + c("x", "y", "z"), + c("x", "y", "z"))) +H["a", "x", "x"] <- 1 +H["b", "y", "y"] <- 2 +H["c", "z", "z"] <- 3 + +p2 <- as.parvec(c(a = 10, b = 20, c = 30), deriv = J, deriv2 = H) +p2 +getDerivs(p2) +getDerivs2(p2) + +## Subsetting keeps the matching derivatives +p_sub <- p2[c("a", "b")] +getDerivs(p_sub) + +## Concatenation +p3 <- as.parvec(c(d = 4, e = 5)) +c(p2, p3) + +## From numbers +parvec(a = 1, b = 2) +} diff --git a/man/summary.eqnvec.Rd b/man/summary.eqnvec.Rd index 220dd6fc..89a2160f 100644 --- a/man/summary.eqnvec.Rd +++ b/man/summary.eqnvec.Rd @@ -17,3 +17,11 @@ \description{ Prints, for each equation, the symbols it depends on. } +\examples{ +v <- eqnvec(y = "2*x + offset") +print(v) +is.eqnvec(v) + +format(eqnvec(y = "2*x+offset")) +summary(v) +} diff --git a/man/symmetryDetection.Rd b/man/symmetryDetection.Rd index fc407e32..d7f7c8fb 100644 --- a/man/symmetryDetection.Rd +++ b/man/symmetryDetection.Rd @@ -29,7 +29,6 @@ symmetryDetection( symEngine = c("modular", "symbolic"), mode = c("local", "global"), globalOptions = NULL, - discrete = FALSE, verbose = FALSE ) } @@ -124,11 +123,8 @@ output of a generic one and reconstructs the maps between them, as \code{\link[= gets the reason in \code{info$discrete$unsupported} and a warning.} \item{globalOptions}{A list of arguments of the global analysis: \code{order}, \code{points}, -\code{timeout} and \code{budget} as in \code{\link[=discreteSymmetries]{discreteSymmetries()}}.} - -\item{discrete}{\code{FALSE} (default), \code{TRUE} or a list of arguments of -\code{\link[=discreteSymmetries]{discreteSymmetries()}}: also search the discrete symmetries; \code{mode = "global"} does the -same through the detection.} +\code{memory}, \code{experiments}, \code{msolveEntries}, \code{msolveTerms}, \code{searchEntries} and +\code{eliminationTerms} as in \code{\link[=discreteSymmetries]{discreteSymmetries()}}.} \item{verbose}{Logical. Print the result. Defaults to \code{FALSE}.} } @@ -172,7 +168,7 @@ routes), \code{branches} (resting states with several roots modulo a prime, of which the first is taken), \code{conditions}, \code{segments}, \code{coordinates}, \code{settings}, \code{elapsed} and \code{verification}.} \item{\code{gauge}}{the coordinates fixed under \code{gaugePreference}.} -\item{\code{discreteSymmetries}}{with \code{discrete}, see \code{\link[=discreteSymmetries]{discreteSymmetries()}}.} +\item{\code{discreteSymmetries}}{with \code{mode = "global"}, see \code{\link[=discreteSymmetries]{discreteSymmetries()}}.} \item{\code{call}}{the matched call.} } \code{print()} shows the verdict and the generators, \code{summary()} also the @@ -201,7 +197,9 @@ The environment variables a user may need are \code{SYMIDENT_MSOLVE}, the path of the msolve executable (unset by default, msolve is then searched in the symident cache and on the \code{PATH}), and \code{SYMIDENT_CACHE}, the directory of that cache (by default -\verb{~/.cache/symident} on Linux). The other switches are diagnostic, see the +\verb{~/.cache/symident} on Linux). \code{SYMIDENT_MSOLVE_GB} sets the address space in GiB of +one call of msolve where \code{memory} of \code{\link[=discreteSymmetries]{discreteSymmetries()}} is not given. The other +switches are diagnostic, see the symident documentation at \url{https://dmodverse.github.io/symident/}. } \examples{ diff --git a/man/symmetryReduction.Rd b/man/symmetryReduction.Rd index 8bbe5067..f5c0e0a9 100644 --- a/man/symmetryReduction.Rd +++ b/man/symmetryReduction.Rd @@ -14,7 +14,6 @@ symmetryReduction( separable = TRUE, reportZeroCompatibility = FALSE, alternatives = FALSE, - timeout = 600, allowOpen = TRUE, allowChecked = TRUE, check = TRUE, @@ -49,11 +48,6 @@ drive to 0. Defaults to \code{FALSE}.} \item{alternatives}{Logical. Also return the charts of the other valid pins in \verb{$alternatives}. Defaults to \code{FALSE}.} -\item{timeout}{Wall time in seconds for the section search of one block; a block not -solved in time keeps the invariants (\code{"invariant_only"}) and is named in \code{limits}. -\code{Inf} lets the search run to its end. Unlike \code{workCap}, it depends on the load of the -machine. Defaults to 600.} - \item{allowOpen}{Logical. Reduce the directions with a closed form and leave those of level \code{"open"} in place with a warning; \code{FALSE} makes such a direction an error. A direction of level \code{"verified"}, and a section claim left unproven, give a warning. @@ -67,15 +61,15 @@ failed, with a warning; \code{FALSE} makes either an error. Defaults to \code{TR and record in \code{checks$loop} whether exactly the remaining directions are left. Defaults to \code{TRUE}; large models may turn it off.} +\item{workCap}{Number of candidate sections the search of one block may try; +reaching it is an entry in \code{limits}. Defaults to 4000.} + \item{branch}{With a discrete symmetry of \code{symmetryDetection(mode = "global")}: the side of -its fixed set as an inequality, e.g. \code{"k01 > k12"}, whose chart becomes the trafo: free values +the fixed set of the symmetry as an inequality, e.g. \code{"k01 > k12"}, whose chart becomes the trafo: free values in the positive orthant map one to one onto that side, chained with the section. Without it -every branch is in \code{$alternatives}; \code{$discrete$branches} lists them with \code{injective}, \code{reach}, +every branch is in \verb{$alternatives}; \verb{$discrete$branches} lists them with \code{injective}, \code{reach}, \code{unproven} and the \code{boundary}. Defaults to \code{NULL}.} -\item{workCap}{Number of candidate sections the search of one block may try; -reaching it is an entry in \code{limits}. Defaults to 4000.} - \item{...}{Not used.} } \value{ @@ -99,8 +93,7 @@ under \code{unproven}).} \item{\code{assumptions}}{what the reduction assumes: \code{domain} (the declared positive coordinates) and \code{starts} (the sides of switches declared at the start), with \code{errorBound}, the probability that a verified closed form is wrong.} -\item{\code{limits}}{the work budgets and time limits that stopped a section or -invariant search.} +\item{\code{limits}}{the work caps that stopped a section or invariant search.} \item{\code{checks}}{\code{pins} and \code{invariants}, whether every pin holds under the trafo and every invariant of a block maps to the matching new parameter over Q, \code{failed}, and with \code{check = TRUE} \code{loop}: the \code{directions} the reduced model has, the diff --git a/man/unique.parframe.Rd b/man/unique.parframe.Rd index 224387af..c764e367 100644 --- a/man/unique.parframe.Rd +++ b/man/unique.parframe.Rd @@ -23,3 +23,41 @@ The rows of \code{x} with distinct values, sorted by value. \description{ Keeps one row per distinct objective value. } +\examples{ +\donttest{ +## Observation of a regression curve +regfn <- c(y = "sin(a*time)") +g <- Y(regfn, parameters = "a", compile = TRUE, modelname = "parlist_obs", + outdir = tempdir()) +x <- Xt(condition = "C1") + +## Data +set.seed(1) +data <- datalist( + C1 = data.frame( + name = "y", + time = 1:5, + value = sin(1:5) + rnorm(5, 0, .1), + sigma = .1 + ) +) + +pars <- c(a = 1) +times <- seq(0, 5, .1) +plot((g*x)(times, pars), data) + +## Fits from random starts, stored in a parlist +obj <- normL2(data, g*x) +out <- as.parlist(lapply(1:5, function(i) { + trust(obj, pars + rnorm(length(pars), 0, 1), rinit = 1, rmax = 10) +})) +summary(out) + +## Parameter frame and best fit +parframe <- as.parframe(out) +plotValues(parframe) +unique(parframe) +bestfit <- as.parvec(parframe) +plot((g*x)(times, bestfit), data) +} +} diff --git a/man/vcov.em.Rd b/man/vcov.em.Rd index 193c728d..0bd2f73b 100644 --- a/man/vcov.em.Rd +++ b/man/vcov.em.Rd @@ -15,9 +15,11 @@ The inverse of half the Hessian of the marginal -2 log L. A fit with spike-and-slab random effects has no Hessian; there it is the inverse of the empirical information \code{information} of the group scores, -see \code{\link[=em]{em()}}, which needs more groups than parameters. A fit -with Dirichlet-process random effects, whose groups are not independent, -has neither: an error, as where the scores do not span every direction. +see \code{\link[=em]{em()}}, which needs more groups than parameters. Fits with +Dirichlet-process random effects, whose groups are not independent, and +fits by the sum over subsets (\code{spikeSlab()} with \code{mean} or \code{spike} other +than 0, or \code{method = "quadrature"} with spike-and-slab random effects) +have neither: an error, as where the scores do not span every direction. } \description{ Covariance of the estimates of a mixed-effects fit diff --git a/man/write.eqnlist.Rd b/man/write.eqnlist.Rd index 35f73389..fe66e9a7 100644 --- a/man/write.eqnlist.Rd +++ b/man/write.eqnlist.Rd @@ -19,6 +19,12 @@ write.eqnlist(eqnlist, ...) Compartments and reaction frames are not written; a warning is issued if the equation list has any. } +\examples{ +el <- addReaction(eqnlist(), "A", "B", "k1*A", description = "conversion") +file <- tempfile(fileext = ".csv") +write.eqnlist(el, file = file) +read.csv(file) +} \seealso{ \code{\link[=as.data.frame.eqnlist]{as.data.frame.eqnlist()}} } diff --git a/pkgdown/index.md b/pkgdown/index.md index 558c54a2..e64fa7ca 100644 --- a/pkgdown/index.md +++ b/pkgdown/index.md @@ -16,15 +16,9 @@ remotes::install_github("dModverse/dMod2") - [Guide](articles/guide-model.html): the NFκB project of Oppelt et al. (2018), chapter by chapter, from the setup of the model to fits, profiles and prediction bands, then mixed effects, sparse deviations, alignment, PEtab and remote computing. -- [Methods](articles/index.html): the derivations behind the guide. -- [Examples](articles/index.html): projects with data, scripts and saved results. +- [Methods](articles/index.html#methods): the derivations behind the guide. +- [Examples](articles/index.html#examples-signaling-models): projects with data, scripts and saved results. - [Reference](reference/index.html): every exported function. The ODE backend is [cppDE](https://dmodverse.github.io/cppDE/), structural identifiability runs in -the Python package [symident](https://github.com/dModverse/symident). - -## Citation - -There is no publication for dMod2 yet. The paper below describes the predecessor [dMod](https://github.com/JetiLab/dMod) and is the reference for the modeling framework: - -Kaschek D, Mader W, Fehling-Kaschek M, Rosenblatt M, Timmer J (2019). Dynamic Modeling, Parameter Estimation, and Uncertainty Analysis in R. *Journal of Statistical Software*, 88(10), 1-32. [doi:10.18637/jss.v088.i10](https://doi.org/10.18637/jss.v088.i10) +the Python package [symident](https://dmodverse.github.io/symident/). diff --git a/src/Makevars b/src/Makevars index 72b13c81..ab884f26 100644 --- a/src/Makevars +++ b/src/Makevars @@ -8,5 +8,6 @@ normL2_kernel.o constraint_kernel.o residual_kernel.o chain_kernel.o: residual_k trust_kernel.o trustL1_kernel.o trust_step.o: trust_driver.h trust_subproblem.h trust_kernel.o trust_step.o: trust_qn.h trust_kernel.o: trust_model.h -focei_kernel.o: nlme_kernel.h trust_model.h trust_driver.h +focei_kernel.o: nlme_kernel.h trust_model.h trust_driver.h trust_subproblem.h nlme_kernel.o: nlme_kernel.h residual_kernel.h trust_subproblem.h +pimpl_kernel.o manifold_kernel.o chain_kernel.o: pimpl_kernel.h diff --git a/src/Makevars.win b/src/Makevars.win index 72b13c81..ab884f26 100644 --- a/src/Makevars.win +++ b/src/Makevars.win @@ -8,5 +8,6 @@ normL2_kernel.o constraint_kernel.o residual_kernel.o chain_kernel.o: residual_k trust_kernel.o trustL1_kernel.o trust_step.o: trust_driver.h trust_subproblem.h trust_kernel.o trust_step.o: trust_qn.h trust_kernel.o: trust_model.h -focei_kernel.o: nlme_kernel.h trust_model.h trust_driver.h +focei_kernel.o: nlme_kernel.h trust_model.h trust_driver.h trust_subproblem.h nlme_kernel.o: nlme_kernel.h residual_kernel.h trust_subproblem.h +pimpl_kernel.o manifold_kernel.o chain_kernel.o: pimpl_kernel.h diff --git a/src/RcppExports.cpp b/src/RcppExports.cpp index d8a42ce4..d8415689 100644 --- a/src/RcppExports.cpp +++ b/src/RcppExports.cpp @@ -10,6 +10,98 @@ Rcpp::Rostream& Rcpp::Rcout = Rcpp::Rcpp_cout_get(); Rcpp::Rostream& Rcpp::Rcerr = Rcpp::Rcpp_cerr_get(); #endif +// adaptiveGridNew +SEXP adaptiveGridNew(int K, int level, IntegerMatrix start, int maxLevel); +RcppExport SEXP _dMod2_adaptiveGridNew(SEXP KSEXP, SEXP levelSEXP, SEXP startSEXP, SEXP maxLevelSEXP) { +BEGIN_RCPP + Rcpp::RObject rcpp_result_gen; + Rcpp::RNGScope rcpp_rngScope_gen; + Rcpp::traits::input_parameter< int >::type K(KSEXP); + Rcpp::traits::input_parameter< int >::type level(levelSEXP); + Rcpp::traits::input_parameter< IntegerMatrix >::type start(startSEXP); + Rcpp::traits::input_parameter< int >::type maxLevel(maxLevelSEXP); + rcpp_result_gen = Rcpp::wrap(adaptiveGridNew(K, level, start, maxLevel)); + return rcpp_result_gen; +END_RCPP +} +// adaptiveGridPending +NumericMatrix adaptiveGridPending(SEXP grid); +RcppExport SEXP _dMod2_adaptiveGridPending(SEXP gridSEXP) { +BEGIN_RCPP + Rcpp::RObject rcpp_result_gen; + Rcpp::RNGScope rcpp_rngScope_gen; + Rcpp::traits::input_parameter< SEXP >::type grid(gridSEXP); + rcpp_result_gen = Rcpp::wrap(adaptiveGridPending(grid)); + return rcpp_result_gen; +END_RCPP +} +// adaptiveGridAbsorb +void adaptiveGridAbsorb(SEXP grid, NumericMatrix z, NumericVector logValues); +RcppExport SEXP _dMod2_adaptiveGridAbsorb(SEXP gridSEXP, SEXP zSEXP, SEXP logValuesSEXP) { +BEGIN_RCPP + Rcpp::RNGScope rcpp_rngScope_gen; + Rcpp::traits::input_parameter< SEXP >::type grid(gridSEXP); + Rcpp::traits::input_parameter< NumericMatrix >::type z(zSEXP); + Rcpp::traits::input_parameter< NumericVector >::type logValues(logValuesSEXP); + adaptiveGridAbsorb(grid, z, logValues); + return R_NilValue; +END_RCPP +} +// adaptiveGridRefine +int adaptiveGridRefine(SEXP grid, double maxNodes); +RcppExport SEXP _dMod2_adaptiveGridRefine(SEXP gridSEXP, SEXP maxNodesSEXP) { +BEGIN_RCPP + Rcpp::RObject rcpp_result_gen; + Rcpp::RNGScope rcpp_rngScope_gen; + Rcpp::traits::input_parameter< SEXP >::type grid(gridSEXP); + Rcpp::traits::input_parameter< double >::type maxNodes(maxNodesSEXP); + rcpp_result_gen = Rcpp::wrap(adaptiveGridRefine(grid, maxNodes)); + return rcpp_result_gen; +END_RCPP +} +// adaptiveGridAccept +void adaptiveGridAccept(SEXP grid); +RcppExport SEXP _dMod2_adaptiveGridAccept(SEXP gridSEXP) { +BEGIN_RCPP + Rcpp::RNGScope rcpp_rngScope_gen; + Rcpp::traits::input_parameter< SEXP >::type grid(gridSEXP); + adaptiveGridAccept(grid); + return R_NilValue; +END_RCPP +} +// adaptiveGridStatus +List adaptiveGridStatus(SEXP grid); +RcppExport SEXP _dMod2_adaptiveGridStatus(SEXP gridSEXP) { +BEGIN_RCPP + Rcpp::RObject rcpp_result_gen; + Rcpp::RNGScope rcpp_rngScope_gen; + Rcpp::traits::input_parameter< SEXP >::type grid(gridSEXP); + rcpp_result_gen = Rcpp::wrap(adaptiveGridStatus(grid)); + return rcpp_result_gen; +END_RCPP +} +// adaptiveGridNodes +List adaptiveGridNodes(SEXP grid); +RcppExport SEXP _dMod2_adaptiveGridNodes(SEXP gridSEXP) { +BEGIN_RCPP + Rcpp::RObject rcpp_result_gen; + Rcpp::RNGScope rcpp_rngScope_gen; + Rcpp::traits::input_parameter< SEXP >::type grid(gridSEXP); + rcpp_result_gen = Rcpp::wrap(adaptiveGridNodes(grid)); + return rcpp_result_gen; +END_RCPP +} +// adaptiveGridIndices +IntegerMatrix adaptiveGridIndices(SEXP grid); +RcppExport SEXP _dMod2_adaptiveGridIndices(SEXP gridSEXP) { +BEGIN_RCPP + Rcpp::RObject rcpp_result_gen; + Rcpp::RNGScope rcpp_rngScope_gen; + Rcpp::traits::input_parameter< SEXP >::type grid(gridSEXP); + rcpp_result_gen = Rcpp::wrap(adaptiveGridIndices(grid)); + return rcpp_result_gen; +END_RCPP +} // alignmentPredictors NumericMatrix alignmentPredictors(List conds, List theta, int S, int threads); RcppExport SEXP _dMod2_alignmentPredictors(SEXP condsSEXP, SEXP thetaSEXP, SEXP SSEXP, SEXP threadsSEXP) { @@ -710,6 +802,14 @@ END_RCPP } static const R_CallMethodDef CallEntries[] = { + {"_dMod2_adaptiveGridNew", (DL_FUNC) &_dMod2_adaptiveGridNew, 4}, + {"_dMod2_adaptiveGridPending", (DL_FUNC) &_dMod2_adaptiveGridPending, 1}, + {"_dMod2_adaptiveGridAbsorb", (DL_FUNC) &_dMod2_adaptiveGridAbsorb, 3}, + {"_dMod2_adaptiveGridRefine", (DL_FUNC) &_dMod2_adaptiveGridRefine, 2}, + {"_dMod2_adaptiveGridAccept", (DL_FUNC) &_dMod2_adaptiveGridAccept, 1}, + {"_dMod2_adaptiveGridStatus", (DL_FUNC) &_dMod2_adaptiveGridStatus, 1}, + {"_dMod2_adaptiveGridNodes", (DL_FUNC) &_dMod2_adaptiveGridNodes, 1}, + {"_dMod2_adaptiveGridIndices", (DL_FUNC) &_dMod2_adaptiveGridIndices, 1}, {"_dMod2_alignmentPredictors", (DL_FUNC) &_dMod2_alignmentPredictors, 4}, {"_dMod2_alignmentForwardBlocks", (DL_FUNC) &_dMod2_alignmentForwardBlocks, 5}, {"_dMod2_alignmentVjpBlocks", (DL_FUNC) &_dMod2_alignmentVjpBlocks, 9}, diff --git a/src/adaptiveGrid.cpp b/src/adaptiveGrid.cpp new file mode 100644 index 00000000..8afa2269 --- /dev/null +++ b/src/adaptiveGrid.cpp @@ -0,0 +1,372 @@ +// Dimension-adaptive sparse-grid quadrature (Gerstner and Griebel 2003) on the nested Genz-Keister rules +// of quadrature.cpp: the old indices of a downward closed set make the grid, the active ones the error. +// Terms sum w exp(l(z) - l(0) + z'z), the ratio of the integrand exp(l) to the Gaussian at the mode. + +#include + +#include +#include +#include +#include +#include +#include + +using namespace Rcpp; + +namespace { + +// Genz-Keister rules for the standard normal weight, as in quadrature.cpp: nodes x >= 0 and weights. +const std::vector> GK_X = { + {0}, + {0, 1.7320508075688772}, + {0, 0.74109534999454085, 1.7320508075688772, 2.8612795760570582, 4.1849560176727323}, + {0, 0.74109534999454085, 1.230423634027306, 1.7320508075688772, 2.5960831150492023, + 2.8612795760570582, 3.2053337944991944, 4.1849560176727323, 5.1870160399136562, + 6.3633944943363696}, + {0, 0.24899229757996061, 0.74109534999454085, 1.230423634027306, 1.7320508075688772, + 2.2336260616769414, 2.5960831150492023, 2.8612795760570582, 3.2053337944991944, + 3.6353185190372783, 4.1849560176727323, 4.7364330859522967, 5.1870160399136562, + 5.6981777684881099, 6.3633944943363696, 7.1221067008046166, 7.9807717985905606, + 9.0169397898903032}}; +const std::vector> GK_W = { + {1}, + {0.66666666666666663, 0.16666666666666666}, + {0.25396825396825395, 0.27007432957793787, 0.094850948509485097, 0.0079963254708935328, + 9.4269457556517484e-05}, + {0.30346719985420589, 0.20832499164960888, 0.061151730125247675, 0.064096054686807583, + 0.018085234254798452, -0.0063372247933737354, 0.0028848804365067511, 6.012336945984782e-05, + 6.094808731468983e-07, 8.6296846022298859e-10}, + {0.00051489450806878432, 0.19176011588804442, 0.14807083115521599, 0.092364726716986312, + 0.045273685465150516, 0.015673473751851151, 0.0031554462691875639, 0.0023113452403522102, + 0.00081895392750226486, 0.00027524214116785158, 3.5729348198975102e-05, + 2.7342206801187829e-06, 2.4676421345798077e-07, 2.1394194479561105e-08, + 4.6011760348656186e-10, 3.097222357606316e-12, 5.4500412650636897e-15, + 1.0541326582333341e-18}}; +const int N_RULES = 5; +// The smallest Smolyak level of quadrature.cpp at which each rule enters one coordinate. +const int FIRST_LEVEL[N_RULES] = {1, 2, 4, 9, 16}; + +// one rule index r in 0..4 per coordinate (1, 3, 9, 19, 35 nodes), the term the tensor product of D_r +typedef std::vector Index; +typedef std::vector Key; + +// Difference rule D_r on z = x / sqrt(2) with weights sqrt(pi) (w_r - w_{r-1}). +void diffRule(int r, std::vector& z, std::vector& w) { + z.clear(); w.clear(); + const double s2 = std::sqrt(2.0), sp = std::sqrt(M_PI); + const std::vector& x = GK_X[r]; + for (int sgn = -1; sgn <= 1; sgn += 2) { + for (std::size_t j = 0; j < x.size(); ++j) { + if (j == 0 && sgn < 0) continue; + double wp = 0.0; + if (r > 0) for (std::size_t k = 0; k < GK_X[r - 1].size(); ++k) if (GK_X[r - 1][k] == x[j]) wp = GK_W[r - 1][k]; + double d = GK_W[r][j] - wp; + if (d == 0.0) continue; + z.push_back(sgn * x[j] / s2); + w.push_back(sp * d); + } + } +} + +struct Term { + double delta = 0.0; + bool computed = false; + bool old = false; +}; + +class AdaptiveGrid { + public: + int K; + std::vector> dz, dw; + std::map terms; + std::map, double>> values; // node -> (z, log value) + std::vector waiting; // proposed, not yet computed + double l0 = NA_REAL; + int maxLevel; // no index of a higher level + + AdaptiveGrid(int K_, int maxLevel_) : K(K_), dz(N_RULES), dw(N_RULES), maxLevel(maxLevel_) { + for (int r = 0; r < N_RULES; ++r) diffRule(r, dz[r], dw[r]); + } + + static Key keyOf(const std::vector& z) { + Key k(z.size()); + for (std::size_t i = 0; i < z.size(); ++i) k[i] = std::llround(z[i] * 1e12); + return k; + } + + // calls f(z, w) for every node of the tensor term of `i` + template void eachNode(const Index& i, F f) const { + std::vector pos(K, 0); + std::vector z(K); + while (true) { + double w = 1.0; + for (int d = 0; d < K; ++d) { z[d] = dz[i[d]][pos[d]]; w *= dw[i[d]][pos[d]]; } + f(z, w); + int d = K - 1; + while (d >= 0) { + if (++pos[d] < static_cast(dz[i[d]].size())) break; + pos[d] = 0; + --d; + } + if (d < 0) break; + } + } + + void add(const Index& i) { + if (terms.count(i)) return; + terms[i] = Term(); + waiting.push_back(i); + } + + static int levelOf(const Index& i) { + int lv = 0; + for (int r : i) lv += FIRST_LEVEL[r]; + return lv; + } + + // forward neighbors of `i` not yet in the set whose backward neighbors are all old become active; + // above maxLevel they estimate the error but never become old + bool addNeighbors(const Index& i) { + bool added = false; + for (int k = 0; k < K; ++k) { + if (i[k] + 1 >= N_RULES) continue; + Index j = i; ++j[k]; + if (terms.count(j)) continue; + bool allOld = true; + for (int d = 0; d < K && allOld; ++d) { + if (j[d] == 0) continue; + Index b = j; --b[d]; + auto it = terms.find(b); + allOld = it != terms.end() && it->second.old; + } + if (allOld) { add(j); added = true; } + } + return added; + } + + // the indices of `closed` old, their forward neighbors whose backward neighbors are all old active + void start(const std::set& closed) { + for (const Index& i : closed) { add(i); terms[i].old = true; } + for (const Index& i : closed) addNeighbors(i); + } + + // nodes of the waiting terms without a value + NumericMatrix pending() const { + std::set need; + std::vector> out; + for (const Index& i : waiting) eachNode(i, [&](const std::vector& z, double) { + Key k = keyOf(z); + if (values.count(k) || need.count(k)) return; + need.insert(k); + out.push_back(z); + }); + NumericMatrix m(out.size(), K); + for (std::size_t b = 0; b < out.size(); ++b) for (int d = 0; d < K; ++d) m(b, d) = out[b][d]; + return m; + } + + // log values of the nodes of pending(), in that order; the waiting terms are then computed + void absorb(const NumericMatrix& z, const NumericVector& lv) { + if (z.ncol() != K || lv.size() != z.nrow()) + Rcpp::stop("adaptive grid: absorb() needs a K-column node matrix and one log value per row."); + for (int b = 0; b < z.nrow(); ++b) { + std::vector zb(K); + double zz = 0.0; + for (int d = 0; d < K; ++d) { zb[d] = z(b, d); zz += zb[d] * zb[d]; } + values[keyOf(zb)] = std::make_pair(zb, lv[b]); + if (zz == 0.0) l0 = lv[b]; + } + if (ISNAN(l0)) Rcpp::stop("adaptive grid: the node at the mode has no value."); + for (const Index& i : waiting) { + double s = 0.0; + eachNode(i, [&](const std::vector& zn, double w) { + auto it = values.find(keyOf(zn)); + if (it == values.end()) Rcpp::stop("adaptive grid: a pending node has no value."); + double zz = 0.0; + for (double v : zn) zz += v * v; + s += w * std::exp(it->second.second - l0 + zz); + }); + terms[i].delta = s; + terms[i].computed = true; + } + waiting.clear(); + } + + // the number of evaluated nodes after the forward neighbors of `i` wait + int prospective(const Index& i) const { + std::set extra; + for (int k = 0; k < K; ++k) { + if (i[k] + 1 >= N_RULES) continue; + Index j = i; ++j[k]; + if (terms.count(j)) continue; + eachNode(j, [&](const std::vector& z, double) { + Key key = keyOf(z); + if (!values.count(key)) extra.insert(key); + }); + } + return static_cast(values.size() + extra.size()); + } + + // the active terms become old, the integral their last refinement: at a budget the change they + // make stays the error estimate + void accept() { + for (auto& kv : terms) if (kv.second.computed) kv.second.old = true; + } + + // the active term of largest |delta| becomes old and the forward neighbors whose backward neighbors + // are all old wait: 1; 0 where no active term up to maxLevel is left, 2 where the evaluated nodes + // would exceed `maxNodes` + int refine(double maxNodes) { + std::vector> act; + for (const auto& kv : terms) + if (kv.second.computed && !kv.second.old && levelOf(kv.first) <= maxLevel) + act.push_back({std::fabs(kv.second.delta), kv.first}); + std::sort(act.begin(), act.end(), [](const std::pair& a, const std::pair& b) { + return a.first > b.first; + }); + // the old set grows by the largest active term even where it has no forward neighbor left + if (act.empty()) return 0; + if (prospective(act.front().second) > maxNodes) return 2; + for (const auto& a : act) { + terms[a.second].old = true; + if (addNeighbors(a.second)) return 1; + } + return 1; + } + + // the integral of the old terms, the change by the active ones, their number, and the shell: the + // terms of the old maximal indices, the change from the grid below where no active term is left + List status() const { + double total = 0.0, error = 0.0, shell = 0.0; + int level = 0, active = 0; + for (const auto& kv : terms) { + if (!kv.second.computed) continue; + if (!kv.second.old) { error += kv.second.delta; ++active; continue; } + total += kv.second.delta; + level = std::max(level, levelOf(kv.first)); + bool maximal = true; + for (int d = 0; d < K && maximal; ++d) { + if (kv.first[d] + 1 >= N_RULES) continue; + Index j = kv.first; ++j[d]; + auto it = terms.find(j); + if (it != terms.end() && it->second.old) maximal = false; + } + if (maximal) shell += kv.second.delta; + } + return List::create(_["total"] = total, _["error"] = std::fabs(error), _["change"] = error, _["shell"] = shell, + _["active"] = active, _["l0"] = l0, + _["nodes"] = static_cast(values.size()), _["level"] = level); + } + + // the combined grid of the old terms: nodes, signed weights for exp(-z'z) and log values + List grid() const { + std::map, double>> acc; + for (const auto& kv : terms) { + if (!kv.second.computed || !kv.second.old) continue; + eachNode(kv.first, [&](const std::vector& z, double w) { + Key k = keyOf(z); + auto it = acc.find(k); + if (it == acc.end()) acc[k] = std::make_pair(z, w); + else it->second.second += w; + }); + } + std::vector, double>>*> kept; + for (const auto& kv : acc) if (kv.second.second != 0.0) kept.push_back(&kv); + int B = kept.size(); + NumericMatrix z(B, K); + NumericVector w(B), lv(B); + CharacterVector key(B); + for (int b = 0; b < B; ++b) { + const auto& e = *kept[b]; + std::string s; + for (int d = 0; d < K; ++d) { + z(b, d) = e.second.first[d]; + s += std::to_string(e.first[d]) + (d + 1 < K ? " " : ""); + } + w[b] = e.second.second; + lv[b] = values.at(e.first).second; + key[b] = s; + } + return List::create(_["z"] = z, _["weights"] = w, _["logValues"] = lv, _["key"] = key); + } + + // the index set as rows, with attributes "delta" (the terms) and "old" + IntegerMatrix indices() const { + IntegerMatrix m(terms.size(), K); + NumericVector delta(terms.size()); + LogicalVector old(terms.size()); + int b = 0; + for (const auto& kv : terms) { + for (int d = 0; d < K; ++d) m(b, d) = kv.first[d]; + delta[b] = kv.second.delta; + old[b] = kv.second.old; + ++b; + } + m.attr("delta") = delta; + m.attr("old") = old; + return m; + } +}; + +} // namespace + + +// A grid of dimension K over the downward closure of the Smolyak set of `level` (every index with +// sum of FIRST_LEVEL at most `level`, the grid of sparseGridGK(K, level)) and the rule-index rows of +// `start`, such as the index set of an earlier grid; no index above `maxLevel` is added later. +// [[Rcpp::export]] +SEXP adaptiveGridNew(int K, int level, IntegerMatrix start, int maxLevel) { + if (K < 1) Rcpp::stop("adaptiveGridNew: K must be >= 1."); + if (start.nrow() > 0 && start.ncol() != K) Rcpp::stop("adaptiveGridNew: `start` needs K columns."); + XPtr g(new AdaptiveGrid(K, std::max(maxLevel, level)), true); + std::vector seeds; + for (int b = 0; b < start.nrow(); ++b) { + Index i(K); + for (int d = 0; d < K; ++d) i[d] = std::min(std::max(start(b, d), 0), N_RULES - 1); + seeds.push_back(i); + } + // the Smolyak set, enumerated within the remaining level so that no other index is visited + Index cur(K, 0); + std::function smolyak = [&](int d, int budget) { + if (d == K) { seeds.push_back(cur); return; } + for (int r = 0; r < N_RULES && FIRST_LEVEL[r] + (K - d - 1) <= budget; ++r) { + cur[d] = r; + smolyak(d + 1, budget - FIRST_LEVEL[r]); + } + cur[d] = 0; + }; + smolyak(0, std::max(level, K)); + // downward closure + std::set closed; + std::vector stack(seeds.begin(), seeds.end()); + while (!stack.empty()) { + Index top = stack.back(); stack.pop_back(); + if (!closed.insert(top).second) continue; + for (int d = 0; d < K; ++d) if (top[d] > 0) { Index j = top; --j[d]; stack.push_back(j); } + } + g->start(closed); + return g; +} + +// [[Rcpp::export]] +NumericMatrix adaptiveGridPending(SEXP grid) { return XPtr(grid)->pending(); } + +// [[Rcpp::export]] +void adaptiveGridAbsorb(SEXP grid, NumericMatrix z, NumericVector logValues) { + XPtr(grid)->absorb(z, logValues); +} + +// [[Rcpp::export]] +int adaptiveGridRefine(SEXP grid, double maxNodes) { return XPtr(grid)->refine(maxNodes); } + +// [[Rcpp::export]] +void adaptiveGridAccept(SEXP grid) { XPtr(grid)->accept(); } + +// [[Rcpp::export]] +List adaptiveGridStatus(SEXP grid) { return XPtr(grid)->status(); } + +// [[Rcpp::export]] +List adaptiveGridNodes(SEXP grid) { return XPtr(grid)->grid(); } + +// [[Rcpp::export]] +IntegerMatrix adaptiveGridIndices(SEXP grid) { return XPtr(grid)->indices(); } diff --git a/src/chain_kernel.cpp b/src/chain_kernel.cpp index 9f525288..cff14523 100644 --- a/src/chain_kernel.cpp +++ b/src/chain_kernel.cpp @@ -763,9 +763,9 @@ SEXP chain_data(List plan, List pre, List raw, bool deriv, bool deriv2, bool bui seeds_on ? sp.data() + off : nullptr, seeds_on ? ss.data() + off : nullptr); } if (want_rows && nd > 0) { - const int nb = hasDs ? 2 : 1; - rowJ[c].assign((std::size_t) nb * n * nd, 0.0); - rowU[c].assign((std::size_t) nb * n, 0.0); + const int blocks = hasDs ? 2 : 1; + rowJ[c].assign((std::size_t) blocks * n * nd, 0.0); + rowU[c].assign((std::size_t) blocks * n, 0.0); std::copy(dpred.begin(), dpred.end(), rowJ[c].begin()); std::copy(sp.begin(), sp.end(), rowU[c].begin()); if (hasDs) { diff --git a/src/constraint_kernel.cpp b/src/constraint_kernel.cpp index 4db167cd..c716c218 100644 --- a/src/constraint_kernel.cpp +++ b/src/constraint_kernel.cpp @@ -141,7 +141,7 @@ List constraintL2_scalar_kernel( std::vector allp_names; std::vector allp_vals; if (dP_opt.isNotNull()) { - // pars are theta-named; we need inner-par values via allp lookup + // pars are named by theta; the inner parameter values come from the allp lookup NumericVector p = pars; CharacterVector pn = p.names(); for (int i = 0; i < p.size(); ++i) { diff --git a/src/focei_kernel.cpp b/src/focei_kernel.cpp index 5979084f..516300bd 100644 --- a/src/focei_kernel.cpp +++ b/src/focei_kernel.cpp @@ -79,8 +79,8 @@ static List add_correction(Function& correction_cb, const CharacterVector& outer } // Moves the modes in `eta` (N x K) to first order along the step, eta += S_i step, the columns of -// S_i at the outer positions in its attribute "idx" where it has one; a subject whose move exceeds -// `radius`, the region the inner search starts with, keeps its modes. +// S_i at the outer positions in the attribute "idx" of S_i where present; a subject whose move +// exceeds `radius`, the region the inner search starts with, keeps the current modes. static void shift_modes(NumericMatrix& eta, const List& shift, const std::vector& step, double radius) { const int N = eta.nrow(), K = eta.ncol(), n = step.size(); if (shift.size() != N) return; diff --git a/src/normL2_kernel.cpp b/src/normL2_kernel.cpp index 41dd19ab..780a689e 100644 --- a/src/normL2_kernel.cpp +++ b/src/normL2_kernel.cpp @@ -215,10 +215,11 @@ CondInputs gather_one_condition( IntegerVector d2_dim = d2_attr.attr("dim"); if (d2_dim.size() == 4) { const int D0 = d2_dim[0], D1 = d2_dim[1], D2 = d2_dim[2]; + if (n_pred_par > 0 && (D0 != Dp0 || D1 != Dp1 || D2 != n_pred_par || d2_dim[3] != n_pred_par)) + throw std::runtime_error("normL2_kernel: deriv2 of the prediction does not match deriv."); const std::size_t N2 = (std::size_t) n_par_local * (std::size_t) n_par_local; C.d2pred.assign((std::size_t) n_data * N2, 0.0); - // R d2 attr col-major: [time, obs, par1, par2] - // We assume dimnames(d2)[[3]] == dimnames(d2)[[4]] == the prediction's parameters. + // col-major [time, obs, par1, par2]; dimnames 3 and 4 are the parameters of deriv for (int j = 0; j < n_data; ++j) { const int i = perm[j]; const int ti = t_idx[i] - 1; @@ -244,10 +245,17 @@ CondInputs gather_one_condition( if (!ed_sexp.isNULL()) { NumericVector ed_attr(ed_sexp); IntegerVector ed_dim = ed_attr.attr("dim"); + if (ed_dim.size() < 2) + throw std::runtime_error("normL2_kernel: deriv of the error model has no dimensions."); const int Ed0 = ed_dim[0]; const int Ed1 = ed_dim[1]; CharacterVector err_par_names = par_axis_names(ed_attr); const int n_err_par = err_par_names.size(); + if ((R_xlen_t) Ed0 * Ed1 * n_err_par > ed_attr.size()) + throw std::runtime_error("normL2_kernel: deriv of the error model is shorter than the dimensions."); + for (int i = 0; i < n_data; ++i) + if (sigma_is_na[i] && (t_idx_err[i] > Ed0 || o_idx_err_d[i] > Ed1)) + throw std::runtime_error("normL2_kernel: data point outside the error model derivatives."); std::vector err_to_local(n_err_par, -1); for (int q = 0; q < n_err_par; ++q) { std::string nm = as(err_par_names[q]); @@ -285,8 +293,9 @@ CondInputs gather_one_condition( IntegerVector ed2_dim = ed2_attr.attr("dim"); if (ed2_dim.size() == 4) { const int E0 = ed2_dim[0], E1 = ed2_dim[1], E2 = ed2_dim[2]; - // Assumes dimnames(deriv2)[[3]] == dimnames(deriv2)[[4]] == - // err_par_names, so the err_to_local mapping above applies. + if (n_err_par > 0 && (E0 != Ed0 || E1 != Ed1 || E2 != n_err_par || ed2_dim[3] != n_err_par)) + throw std::runtime_error("normL2_kernel: deriv2 of the error model does not match deriv."); + // dimnames 3 and 4 are err_par_names, so the err_to_local mapping above applies const std::size_t N2 = (std::size_t) n_par_local * (std::size_t) n_par_local; C.d2sigma.assign((std::size_t) n_data * N2, 0.0); diff --git a/src/pimpl_kernel.cpp b/src/pimpl_kernel.cpp index b2c2d995..0368849a 100644 --- a/src/pimpl_kernel.cpp +++ b/src/pimpl_kernel.cpp @@ -28,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -338,6 +339,10 @@ bool spectrum(const State& s, const std::vector& pv, const std::vector& vectors, std::string& error) { using cd = std::complex; const int n = s.nDep, np = s.nPar, m = s.nEq, k = s.k, nd = n + np, q = n - k; + if ((int) pv.size() != np || (int) x.size() != n) { + error = "parameters or state of the wrong length"; + return false; + } if (s.ad2 == nullptr) { error = "the stability of the steady state needs the second derivatives of the steady state, Pimpl(deriv2 = TRUE)"; return false; @@ -392,15 +397,15 @@ bool spectrum(const State& s, const std::vector& pv, const std::vector M, int d, bool vectors, std::vector& wr, std::vector& wi, + auto eigen = [](std::vector M, int d, bool withVectors, std::vector& wr, std::vector& wi, std::vector& vl, std::vector& vr) { wr.assign(d, 0.0); wi.assign(d, 0.0); - vl.assign(vectors ? (std::size_t) d * d : 1, 0.0); - vr.assign(vectors ? (std::size_t) d * d : 1, 0.0); + vl.assign(withVectors ? (std::size_t) d * d : 1, 0.0); + vr.assign(withVectors ? (std::size_t) d * d : 1, 0.0); if (d == 0) return true; - const char* job = vectors ? "V" : "N"; - int dd = d, ldv = vectors ? d : 1, lwork = -1, info = 0; + const char* job = withVectors ? "V" : "N"; + int dd = d, ldv = withVectors ? d : 1, lwork = -1, info = 0; double wq = 0; F77_CALL(dgeev)(job, job, &dd, M.data(), &dd, wr.data(), wi.data(), vl.data(), &ldv, vr.data(), &ldv, &wq, &lwork, &info FCONE FCONE); @@ -509,9 +514,9 @@ bool spectrum(const State& s, const std::vector& pv, const std::vector P((std::size_t) n * n, 0.0); for (int j = 0; j < n; ++j) for (int c = 0; c < mJ; ++c) { - cd y = std::conj(Z[j + (std::size_t) n * c]); - for (int b = 0; b < r2; ++b) y += X[c + (std::size_t) mJ * b] * std::conj(Z[j + (std::size_t) n * (mJ + b)]); - for (int i = 0; i < n; ++i) P[i + (std::size_t) n * j] += Z[i + (std::size_t) n * c] * y; + cd zc = std::conj(Z[j + (std::size_t) n * c]); + for (int b = 0; b < r2; ++b) zc += X[c + (std::size_t) mJ * b] * std::conj(Z[j + (std::size_t) n * (mJ + b)]); + for (int i = 0; i < n; ++i) P[i + (std::size_t) n * j] += Z[i + (std::size_t) n * c] * zc; } double umax = 0.0; for (int i = 0; i < n; ++i) umax = std::max(umax, std::abs(Z[i])); @@ -687,6 +692,11 @@ bool roots(const std::vector& req, std::vector& out, int threads, std::vector& warnings) { const int N = req.size(); out.assign(N, Root()); + for (const Request& q : req) + if ((int) q.pv.size() != q.st->nPar || (int) q.guess.size() != q.st->nDep) { + error = "Pimpl: parameters or start of the wrong length"; + return false; + } // per request: a memory entry, the task of another request, or a new task std::vector task(N, -1); std::vector keys(N); @@ -719,8 +729,10 @@ bool roots(const std::vector& req, std::vector& out, int threads, for (int i = 0; i < N; ++i) if (task[i] >= 0) order[task[i]] = std::max(order[task[i]], req[i].order); std::vector res(tasks.size()); const int T = tasks.size(); - int nt = std::max(1, std::min(threads, T)); + // the requested team, not cut to the tasks, so that libgomp keeps the threads and cppDE their scratch + int nt = T > 1 ? std::max(1, threads) : 1; #ifdef _OPENMP + nt = std::min(nt, omp_get_num_procs()); if (omp_in_parallel()) nt = 1; #pragma omp parallel for schedule(dynamic) num_threads(nt) if (nt > 1) #endif @@ -808,16 +820,14 @@ DL_FUNC fnOf(SEXP x) { // the dependent state `inDep` and the parameters it reads `inPar` (0-based), and `flow`. // [[Rcpp::export]] SEXP pimpl_state(List spec) { - State* s = new State(); + std::unique_ptr s(new State()); s->val = reinterpret_cast(fnOf(spec["val"])); s->ad = reinterpret_cast(fnOf(spec["ad"])); s->ad2 = reinterpret_cast(fnOf(spec["ad2"])); s->influx = reinterpret_cast(fnOf(spec["influx"])); s->ptc = reinterpret_cast(fnOf(spec["ptc"])); - if (s->val == nullptr || s->ad == nullptr || s->ptc == nullptr) { - delete s; + if (s->val == nullptr || s->ad == nullptr || s->ptc == nullptr) stop("Pimpl: the compiled system or cppDE's solver is not available"); - } s->nDep = as(spec["nDep"]); s->nPar = as(spec["nPar"]); s->k = as(spec["nTotals"]); @@ -826,7 +836,11 @@ SEXP pimpl_state(List spec) { s->inPar = as>(spec["inPar"]); s->depNames = as>(spec["depNames"]); s->flow = as(spec["flow"]); - SEXP xp = PROTECT(R_MakeExternalPtr(s, R_NilValue, R_NilValue)); + if (s->nDep < 0 || s->nPar < 0 || s->k < 0 || (int) s->depNames.size() != s->nDep) + stop("Pimpl: inconsistent sizes of the native state"); + for (int j : s->inDep) if (j < 0 || j >= s->nDep) stop("Pimpl: influx state index out of range"); + for (int j : s->inPar) if (j < 0 || j >= s->nPar) stop("Pimpl: influx parameter index out of range"); + SEXP xp = PROTECT(R_MakeExternalPtr(s.release(), R_NilValue, R_NilValue)); R_RegisterCFinalizerEx(xp, finalizeState, TRUE); UNPROTECT(1); return xp; @@ -850,6 +864,7 @@ void pimpl_controls(SEXP xp, bool keepRoot, List ctrl) { c.seed = dmod::pimpl::num(ctrl, "seed", c.seed); if (ctrl.containsElementNamed("startRange")) { NumericVector r = ctrl["startRange"]; + if (r.size() != 2) stop("Pimpl: startRange must have length 2"); c.lo = r[0]; c.hi = r[1]; } diff --git a/src/reach_kernel.cpp b/src/reach_kernel.cpp index 832f7a5b..1c7a66c8 100644 --- a/src/reach_kernel.cpp +++ b/src/reach_kernel.cpp @@ -13,6 +13,7 @@ using namespace Rcpp; // [[Rcpp::export]] LogicalVector graph_reach(CharacterVector from, CharacterVector to, CharacterVector sources, CharacterVector sinks) { + if (from.size() != to.size()) stop("graph_reach: `from` and `to` differ in length"); std::unordered_map id; auto number = [&](SEXP s) { auto it = id.emplace(CHAR(s), (int) id.size()); diff --git a/src/trust_model.h b/src/trust_model.h index 12116d9b..ffc64a8a 100644 --- a/src/trust_model.h +++ b/src/trust_model.h @@ -95,7 +95,7 @@ struct SparseModel { CHM_FR Q = nullptr; // LDL' of an indefinite Bhat_S + lambda I, analyzed where needed CHM_FR F = nullptr; // the factor of the last factorization std::vector pat_p, pat_i, diag; // pattern of the last analysis, diagonal positions - std::vector map; // entry k of S to its position in A + std::vector map; // entry k of S to the position in A std::vector V, E; // the low-rank part of Bhat: V diag(E) V' // at the last factorization: lambda, Z = (Bhat_S + lambda I)^-1 V, Kinv = (diag(1/E) + V'Z)^-1 double lam_f = std::numeric_limits::quiet_NaN(); @@ -142,7 +142,7 @@ struct SparseModel { Rcpp::stop("trust(sparse = TRUE) takes Hessians of the objective; a quasi-Newton phase is dense"); } - // A, with its symbolic analysis, for the pattern of `h`; the map of the entries of S into A. + // A and the symbolic analysis of A for the pattern of `h`; the map of the entries of S into A. void pattern(const Hess& h) { if (A && h.p == pat_p && h.i == pat_i) return; pat_p = h.p; pat_i = h.i; @@ -238,7 +238,7 @@ struct SparseModel { M_cholmod_free_dense(&B, &c); } - // The LDL' factor of Bhat_S + lambda I and its number of negative pivots; -1 for a zero one. + // The LDL' factor of Bhat_S + lambda I and the number of negative pivots; -1 for a zero pivot. int factorLDL(double lambda) { if (!Q) { const int super = c.supernodal, ll = c.final_ll; @@ -409,8 +409,8 @@ struct SparseModel { for (int i = 0; i < K; ++i) q += s[i] * w[i]; lam = lam + (ns - r) / r * ns * ns / q; } - // a bracket that closes before the root resolves is the hard case to rounding: the step at its - // upper end lies inside the region + // a bracket that closes before the root resolves is the hard case to rounding: the step at the + // upper end of the bracket lies inside the region if (!done) step(lam_in > 0.0 ? lam_in : hi); std::copy(s.begin(), s.end(), s_out); const double ns = norm(s); diff --git a/src/trust_subproblem.h b/src/trust_subproblem.h index 39dcb4e7..9b3e9e91 100644 --- a/src/trust_subproblem.h +++ b/src/trust_subproblem.h @@ -225,9 +225,8 @@ inline void trust_sub(int K, const double* g, } else if (f_dn >= 0.0) { root = beta_dn; } else { - // Bisection. fred is monotone increasing, so this converges robustly - // to within ~50 iterations even when beta_dn / beta_up span many - // orders of magnitude. + // Bisection: fred is monotone increasing, so the bracket holds the root + // also when beta_dn and beta_up span many orders of magnitude. double a = beta_dn, b = beta_up; for (int it = 0; it < 100; ++it) { double mid = 0.5 * (a + b); diff --git a/tests/testthat/_snaps/statsOutput.md b/tests/testthat/_snaps/statsOutput.md index 224b2743..2a826b37 100644 --- a/tests/testthat/_snaps/statsOutput.md +++ b/tests/testthat/_snaps/statsOutput.md @@ -107,15 +107,15 @@ 26 2 1.8230 0.13200 5 z ctrl -6.824 -3.653 3.084e-02 1.439e-01 31 3 16.9500 1.22000 5 z ctrl -6.824 -3.653 2.635e+00 1.229e+01 36 4 207.1000 14.91000 5 z ctrl -6.824 -3.653 3.932e+02 1.834e+03 - cbLower95 cbUpper95 condidnt sigmaLS - 1 1.830e-03 4.556e-02 y 0.05032 - 6 3.958e-03 9.853e-02 y 0.10030 - 11 1.511e-01 3.761e+00 y 0.48350 - 16 2.044e+01 5.089e+02 y 5.57400 - 21 2.254e-04 5.611e-03 z 0.02000 - 26 9.970e-03 2.482e-01 z 0.07783 - 31 8.516e-01 2.120e+01 z 1.52400 - 36 1.271e+02 3.164e+03 z 15.48000 + cbLower95 cbUpper95 group sigmaLS + 1 1.830e-03 4.556e-02 y 0.05032 + 6 3.958e-03 9.853e-02 y 0.10030 + 11 1.511e-01 3.761e+00 y 0.48350 + 16 2.044e+01 5.089e+02 y 5.57400 + 21 2.254e-04 5.611e-03 z 0.02000 + 26 9.970e-03 2.482e-01 z 0.07783 + 31 8.516e-01 2.120e+01 z 1.52400 + 36 1.271e+02 3.164e+03 z 15.48000 # steadyStates refuses named givenCQs and returns lhs = rhs as a named vector diff --git a/tests/testthat/test-EMsparse.R b/tests/testthat/test-EMsparse.R index 0e9166f8..38699eef 100644 --- a/tests/testthat/test-EMsparse.R +++ b/tests/testthat/test-EMsparse.R @@ -12,8 +12,8 @@ r } -# A decay model y = A exp(-k dose) per condition, five groups with two conditions each, and the -# linear model y = a + b dose on the same design with a known sigma. +# A nonlinear and a linear model per condition, five groups with two conditions each, the linear +# one with a known sigma. .sparse <- local({ cache <- NULL function() { @@ -58,7 +58,7 @@ modelname = "sp_glin", derivMode = .dm) pls <- P(linear(spikeSlab()), method = "explicit", compile = FALSE, modelname = "sp_linslab", derivMode = .dm) pld <- P(linear(dirichletProcess()), method = "explicit", compile = FALSE, modelname = "sp_lindp", derivMode = .dm) - # a second observable z = b + c that only the first two groups measure + # a second observable that only some groups measure gz <- Y(c(y = "a + b * dose", z = "b + c"), f = NULL, parameters = c("a", "b", "c", "dose"), compile = FALSE, modelname = "sp_gz", derivMode = .dm) reachP <- function(dist, name) { @@ -68,8 +68,8 @@ modelname = name, derivMode = .dm) } pz <- list(spikeSlab = reachP(spikeSlab(), "sp_zslab"), dirichletProcess = reachP(dirichletProcess(), "sp_zdp")) - # a state X that a stimulus u drives from 0, u = 0 in the groups L1 and L2, read with a drift w - # that only a state at 0 multiplies + # a state driven by a stimulus that is off in some groups, with a parameter that only a state at + # 0 multiplies tabu <- cbind(tab, u = ifelse(tab$ID %in% c("L1", "L2"), 0, 1)) xu <- Xs(odemodel(eqnvec(X = "s * u - dg * X", W = "w * X - dg * W"), modelname = "sp_xu", compile = FALSE, derivMode = .dm)) diff --git a/tests/testthat/test-Pexpl.R b/tests/testthat/test-Pexpl.R index 263ed4ff..e90f5020 100644 --- a/tests/testthat/test-Pexpl.R +++ b/tests/testthat/test-Pexpl.R @@ -89,7 +89,7 @@ test_that("Pexpl log trafo maps theta -> exp(theta) with Jacobian diag(exp(theta pv <- inner$C1 expect_equal(as.numeric(pv), c(1.5, 0.3)) - # J[i, j] = d (inner_i) / d (outer_j). Diagonal entries are exp(theta) = p. + # J[i, j] = d (inner_i) / d (outer_j) J <- attr(pv, "deriv") expect_equal(unname(diag(J)), c(1.5, 0.3)) expect_equal(J[upper.tri(J)], rep(0, sum(upper.tri(J)))) diff --git a/tests/testthat/test-fn-composition-protocol.R b/tests/testthat/test-fn-composition-protocol.R index 83777e75..2d52373c 100644 --- a/tests/testthat/test-fn-composition-protocol.R +++ b/tests/testthat/test-fn-composition-protocol.R @@ -203,6 +203,16 @@ test_that("functions for single conditions compose only for the same condition", expect_s3_class(gA * dMod2:::.fnWithConditions(fx$xfn, "A"), "prdfn") }) +test_that("condition sets without a common condition do not compose", { + skip_if_not_installed("cppDE") + skip_on_cran() + + fx <- fx_decay_compiled() + gAB <- dMod2:::.fnWithConditions(fx$gfn, c("A", "B")) + expect_error(gAB * dMod2:::.fnWithConditions(fx$xfn, c("C", "D")), "share none") + expect_s3_class(gAB * dMod2:::.fnWithConditions(fx$xfn, c("B", "C")), "prdfn") +}) + ## ---- Objective composition ---------------------------------------------- @@ -229,6 +239,27 @@ test_that("objfn * parfn keeps parameters, modelname and the NLME handles", { }) +test_that("objfn * parfn drops the prediction handles that do not compose", { + skip_if_not_installed("cppDE") + skip_on_cran() + + fx <- fx_decay_compiled() + mc <- fx_decay_multicond_compiled() + d <- fx_decay_data() + + rep <- normL2(d, fx$prd_id) * fx$pfn_log + expect_s3_class(attr(rep, "prdfn", exact = TRUE), "prdfn") + expect_length(attr(rep, "l2spec", exact = TRUE), 1L) + + # A prediction over several conditions does not compose with a + # single-condition transformation, so no handle stays in inner coordinates. + rep <- normL2(d, mc$prd) * fx$pfn_log + expect_s3_class(rep, "objfn") + expect_null(attr(rep, "prdfn", exact = TRUE)) + expect_null(attr(rep, "l2spec", exact = TRUE)) +}) + + test_that("deriv2 and cores survive a sum of objectives", { skip_if_not_installed("cppDE") skip_on_cran() diff --git a/tests/testthat/test-loadDLL.R b/tests/testthat/test-loadDLL.R index 5cbd9e7c..e163ee21 100644 --- a/tests/testthat/test-loadDLL.R +++ b/tests/testthat/test-loadDLL.R @@ -149,6 +149,41 @@ test_that("compiling into a loaded output name yields a fresh library", { }) +test_that("a suffixed output name reaches the modelname", { + dir <- file.path(tempdir(), "dmod_suffix") + dir.create(dir, showWarnings = FALSE, recursive = TRUE) + oldwd <- setwd(dir); on.exit(setwd(oldwd), add = TRUE) + + build <- function(nm) { + p <- P(eqnvec(a = "exp(la)"), condition = "C1", compile = FALSE, modelname = nm) + suppressMessages(compile(p, output = "sfx_all", cores = 1)) + p + } + + p1 <- build("sfx_one") + expect_equal(modelname(p1), "sfx_all") + expect_warning(p2 <- build("sfx_two"), "already loaded") + expect_equal(modelname(p2), "sfx_all_2") + expect_true(any(grepl("sfx_all_2", dMod2:::.dllFiles(list(p2)), fixed = TRUE))) + expect_equal(as.numeric(p2(c(la = 0))[["C1"]]["a"]), 1) +}) + + +test_that("getLocalDLLs matches the working directory as a path prefix", { + dir <- file.path(tempdir(), "dmod_local") + dir.create(dir, showWarnings = FALSE, recursive = TRUE) + oldwd <- setwd(dir); on.exit(setwd(oldwd), add = TRUE) + wd <- normalizePath(dir, winslash = "/") + + local_mocked_bindings( + .loadedDLLPaths = function() c(inside = file.path(wd, "a.so"), + below = file.path(wd, "sub", "b.so"), + sibling = paste0(wd, "2/c.so")), + .package = "dMod2") + expect_setequal(getLocalDLLs(), c("inside", "below")) +}) + + test_that("a multi-condition trafo compiled alone is named by the modelname", { fx <- fx_loaddll() oldwd <- setwd(fx$dir); on.exit(setwd(oldwd), add = TRUE) @@ -164,3 +199,16 @@ test_that("a multi-condition trafo compiled alone is named by the modelname", { expect_named(pred, c("a", "b")) expect_equal(unname(pred$b[, "yB"]), 2 * unname(pred$a[, "yB"])) }) + +test_that("compile() without output skips a source whose shared object is loaded", { + dir <- file.path(tempdir(), "dmod_keep") + dir.create(dir, showWarnings = FALSE, recursive = TRUE) + oldwd <- setwd(dir); on.exit(setwd(oldwd), add = TRUE) + + p <- P(eqnvec(a = "exp(la)"), condition = "C1", compile = FALSE, modelname = "keep_one") + suppressMessages(compile(p, cores = 1)) + path <- getLoadedDLLs()[["keep_one"]][["path"]] + expect_message(compile(p, cores = 1), "not rebuilt: keep_one") + expect_identical(getLoadedDLLs()[["keep_one"]][["path"]], path) + expect_equal(as.numeric(p(c(la = 0))[["C1"]]["a"]), 1) +}) diff --git a/tests/testthat/test-mstrust.R b/tests/testthat/test-mstrust.R index 819b07a2..be239a85 100644 --- a/tests/testthat/test-mstrust.R +++ b/tests/testthat/test-mstrust.R @@ -601,3 +601,23 @@ test_that("load.parlist reads the fits in the order of their numbers", { file.path(d, paste0("fit-", i, ".Rda"))) expect_equal(vapply(load.parlist(d), function(f) f$value, 1), 1:11) }) + +test_that("confint extrapolates a flat branch against the span of the whole branch", { + x <- seq(-10, 10, by = 1) + pr <- parframe(data.frame(value = 0.1 * abs(x), constraint = x, whichPar = "a", a = 1 + x), + parameters = "a", metanames = c("value", "constraint", "whichPar")) + ci <- confint(pr, val.column = "value") + dx <- (qchisq(0.95, 1) - 1) / 0.1 + 10 + expect_equal(unname(unlist(ci[1, c("lower", "upper")])), 1 + c(-1, 1) * dx) +}) + +test_that("mstrust keeps rinit, rmax and n from the objective when the optimizer lacks them", { + obj <- function(pars, ...) { + if (length(list(...))) stop("unexpected arguments: ", toString(names(list(...)))) + list(value = sum(pars^2)) + } + opt <- function(objfun, parinit, ...) + list(value = objfun(parinit, ...)$value, argument = parinit, converged = TRUE, iterations = 0L) + fits <- mstrust(obj, c(a = 0, b = 0), fits = 2, sd = 1, cores = 1, optmethod = opt) + expect_false(any(vapply(fits, function(f) !is.null(f$error), TRUE))) +}) diff --git a/tests/testthat/test-multipleShooting.R b/tests/testthat/test-multipleShooting.R index 27e8aaaa..8e22005e 100644 --- a/tests/testthat/test-multipleShooting.R +++ b/tests/testthat/test-multipleShooting.R @@ -510,6 +510,20 @@ test_that("the handover from the natural level function keeps the total iterlim" expect_false(fit$converged) }) +test_that("the iterations of the first phase count against iterlim", { + mo <- .ms_models() + obj <- normL2(mo$data, mo$g * mo$x * mo$p, multipleShootingControl = TRUE) + start <- mo$truth + c(0.8, -0.6, 0.4, -0.3, 0.3) + out <- utils::capture.output(fit <- trust(obj, start, iterlim = 4, blather = TRUE, printIter = TRUE, + stepControl = list(twoPhase = TRUE, anneal = FALSE))) + ph1 <- as.integer(sub(".* ([0-9]+) iterations.*", "\\1", grep("^phase 1", out, value = TRUE))) + expect_length(ph1, 1L) + expect_gt(ph1, 0L) + expect_gte(fit$iterations, ph1 + length(fit$multipleShooting$trace)) + expect_lte(length(fit$multipleShooting$trace), 4L - ph1) + expect_lte(fit$iterations, 4L) +}) + test_that("a value stop waits for the Newton step to predict no decrease", { mo <- .ms_models() obj0 <- normL2(mo$data, mo$g * mo$x * mo$p) diff --git a/tests/testthat/test-normL2.R b/tests/testthat/test-normL2.R index 089dea62..cd4cc7ca 100644 --- a/tests/testthat/test-normL2.R +++ b/tests/testthat/test-normL2.R @@ -7,7 +7,7 @@ skip_if_no_compile <- function() { } -# Error-model chains (sigma = sigma_y, sigma = srel * y) and a second-condition +# Error-model chains (absolute and relative) and a second-condition # trafo on the shared decay fixture, in one shared object built on first use. # The trafos pass the error parameters through, so normL2's errmodel call sees them. .nl2_fx <- local({ @@ -638,8 +638,8 @@ test_that("an error parameter outside the prediction's derivatives has a gradien }) -# A prediction y = a_i at times i and an error model exp(ls) (1 + 0.1 y^2), both with their -# exact second derivatives, written out so the objectives' Hessians need no compiled model. +# A prediction and an error model with exact second derivatives written out, so the Hessians of +# the objectives need no compiled model. .nl2_handmade <- function() { P2X <- function(times, pars, fixed = NULL, deriv = TRUE, deriv2 = FALSE) { p <- c(unclass(pars), unclass(fixed)); an <- paste0("a", 0:3) diff --git a/tests/testthat/test-petab.R b/tests/testthat/test-petab.R index 1528adf1..7114baec 100644 --- a/tests/testthat/test-petab.R +++ b/tests/testthat/test-petab.R @@ -1140,3 +1140,77 @@ test_that("SBML roundtrip preserves symbolic volumes, reaction frames and amount function(e) eval(parse(text = e), as.list(pars)), numeric(1)) expect_equal(value(g), value(f)) }) + + +test_that(".petab_parse_parameters refuses a parameter without estimate", { + df <- data.frame(parameterId = c("a", "b"), parameterScale = "lin", lowerBound = 0, + upperBound = 10, nominalValue = 1, estimate = c(1L, NA), + stringsAsFactors = FALSE) + expect_error(dMod2:::.petab_parse_parameters(df), "estimate") +}) + + +test_that("condition names that collide with a fallback id keep the keys unique", { + tables <- list( + conditions = data.frame(conditionId = c("a", "b"), conditionName = c("b", NA), + stringsAsFactors = FALSE), + measurements = data.frame(simulationConditionId = c("a", "b"), stringsAsFactors = FALSE)) + out <- dMod2:::.petab_use_condition_names(tables) + expect_false(anyDuplicated(out$conditions$conditionId) > 0) + expect_identical(out$conditions$conditionId, c("a", "b")) + expect_identical(out$measurements$simulationConditionId, c("a", "b")) +}) + + +test_that("formulas of model files evaluate with the math functions only", { + expect_equal(dMod2:::.petab_eval_constant("pow(2, 3) + piecewise(1, 2 > 1, 0) + ln(exp(1))"), 10) + f <- tempfile() + expect_true(is.na(dMod2:::.petab_eval_constant(sprintf('file.create("%s")', f)))) + expect_false(file.exists(f)) +}) + + +test_that("exportSbml writes a root event as two triggers and importSbml joins them again", { + withr::local_dir(tempdir()) + if (!.libsbml_works()) skip("libsbml virtualenv not available") + + reactions <- addReaction(eqnlist(), "A", "B", "k1*A", "fwd", compartment = "compartment") + events <- eventlist(var = "B", time = NA, value = 0, root = "A - 0.5", method = "replace") + out_xml <- file.path(tempdir(), "root_export.xml") + exportSbml(reactions, parameters = c(k1 = 0.8, compartment = 1), inits = c(A = 1, B = 0), + filepath = out_xml, modelID = "root_export", events = events) + xml_text <- gsub("\\s+", " ", paste(readLines(out_xml, warn = FALSE), collapse = " ")) + trig <- regmatches(xml_text, gregexpr("", xml_text))[[1]] + expect_length(trig, 2L) + expect_true(any(grepl("", trig)) && any(grepl("", trig))) + expect_true(all(grepl('initialValue="true"', trig))) + + ev <- importSbml(out_xml)$eventsSource + expect_equal(nrow(ev), 1L) + expect_true(grepl("A", ev$root)) +}) + + +test_that("importSbml keeps the symbol of a compartment an event resizes", { + if (!.libsbml_works()) skip("libsbml virtualenv not available") + + f <- tempfile(fileext = ".xml") + writeLines(c( + '', + '', + '', + '', + '', + '', + '', + '', + ' k c A ', + '', + '', + ' time 1 ', + ' 2 ', + ''), f) + m <- importSbml(f) + expect_equal(m$reactions$compartments$c$volume, "c") + expect_equal(unname(m$compartmentInits["c"]), "1") +}) diff --git a/tests/testthat/test-plots.R b/tests/testthat/test-plots.R index d11bba1b..643ad14b 100644 --- a/tests/testthat/test-plots.R +++ b/tests/testthat/test-plots.R @@ -151,6 +151,23 @@ test_that("plotProfilesAndPaths draws the total besides the contributions", { expect_true("total" %in% panels[[1]]$data$mode) }) +test_that("plotProfilesAndPaths draws the thresholds and the cut-off it is given", { + skip_if_not_installed("cowplot") + pars <- c(a = 1, b = 0.5) + profs <- profile(constraintL2(mu = pars, sigma = 0.1), pars, whichPar = "a", + limits = c(-1, 1), cores = 1) + panels <- list() + local_mocked_bindings(align_plots = function(...) { + if (!length(panels)) panels <<- list(...) + list(...) + }, .package = "cowplot") + plotProfilesAndPaths(profs, "a", nPars = 2, threshold = c(F = 4.5), maxvalue = 8) + y <- panels[[1]]$scales$get_scales("y") + expect_equal(unname(y$breaks), c(0, 4.5)) + expect_identical(y$labels, c("optimum", "F")) + expect_equal(y$limits, c(NA, 8)) +}) + test_that("the parlist overlay of plotProfile draws parameters only", { pars <- c(a = 1, b = 0.5) profs <- profile(constraintL2(mu = pars, sigma = 0.1), pars, whichPar = c("a", "b"), diff --git a/tests/testthat/test-quadrature.R b/tests/testthat/test-quadrature.R index 9d68a4e5..c9b2d1ea 100644 --- a/tests/testthat/test-quadrature.R +++ b/tests/testthat/test-quadrature.R @@ -54,7 +54,7 @@ test_that("the nodes integrate a normal of the posterior precision exactly", { }) -# A one-eta model y = exp(mu + eta) per group, observed once per condition. +# A model with one random effect per group, observed once per condition. .quad_models <- local({ cache <- NULL function() { @@ -71,7 +71,7 @@ test_that("the nodes integrate a normal of the posterior precision exactly", { tr <- branch(define(NULL, "intercept <- exp(mu)"), table = tab) tr <- insert(tr, mu ~ 1 + (1 | ID)) p <- P(tr, method = "explicit", compile = FALSE, modelname = "quad_p", derivMode = "forward-forward") - # a group covariate on mu and the parameter s of an error model sigma = exp(s) + # a group covariate and an error model with a free parameter tw <- branch(define(NULL, "x <- x", x = c("intercept", "s")), table = tab) tw <- insert(tw, "intercept <- exp(mu)") tw <- insert(tw, mu ~ w + (1 | ID)) @@ -273,3 +273,29 @@ test_that("the Newton decrement of a singular Hessian counts the flat directions ev <- list(gradient = c(1, 1e-3), hessian = diag(c(2, 0))) expect_equal(dMod2:::.newtonDecrement(ev, rmax = 10), 1 / 4 + 1e-2) }) + +test_that("an adaptive grid without refinement is the Smolyak grid of the level", { + for (K in 1:3) for (level in K:(K + 4)) { + ref <- sparseGridGK(K, level) + g <- adaptiveGridNew(K, level, matrix(0L, 0, K), 100L) + z <- adaptiveGridPending(g) + adaptiveGridAbsorb(g, z, rep(0, nrow(z))) + gr <- adaptiveGridNodes(g) + o1 <- do.call(order, as.data.frame(round(ref$nodes, 10))) + o2 <- do.call(order, as.data.frame(round(gr$z, 10))) + expect_equal(gr$z[o2, , drop = FALSE], ref$nodes[o1, , drop = FALSE], tolerance = 1e-12) + expect_equal(gr$weights[o2], ref$weights[o1], tolerance = 1e-12) + } +}) + +test_that("an adaptive grid refines the direction in which the integrand is not Gaussian", { + logf <- function(z) -rowSums(z^2) + 0.3 * z[, 1]^3 - 0.1 * z[, 1]^4 + exact <- integrate(function(x) exp(-x^2 + 0.3 * x^3 - 0.1 * x^4), -Inf, Inf)$value * sqrt(pi) + r <- .adaptiveGrids(2L, 2L, list(NULL), function(which, z) lapply(z, logf), 1e-8)[[1]] + est <- sum(r$weights * exp(r$logValues + rowSums(r$z^2))) + expect_equal(est, exact, tolerance = 1e-7) + expect_false(r$capped) + # a direction in which the integrand is Gaussian is not refined + expect_lte(max(r$indices[, 2]), 1L) + expect_lt(nrow(r$z), nrow(sparseGridGK(2L, 12L)$nodes)) +}) diff --git a/tests/testthat/test-randomEffects.R b/tests/testthat/test-randomEffects.R index 16122c8d..73ecb44b 100644 --- a/tests/testthat/test-randomEffects.R +++ b/tests/testthat/test-randomEffects.R @@ -89,3 +89,47 @@ test_that("a cluster term shares the concentration and tau over the symbols of t expect_length(re$blocks, 1L) expect_true(all(is.na(re$terms$concentration))) }) + +test_that("spikeSlab() takes a slab mean and a spike, -Inf included", { + d <- spikeSlab(prob = 0.3, mean = -1, spike = -Inf) + expect_equal(d[c("mean", "spike")], list(mean = -1, spike = -Inf)) + expect_equal(spikeSlab()[c("mean", "spike")], list(mean = 0, spike = 0)) + expect_output(print(d), "spikeSlab\\(prob = 0.3, tau = NULL, mean = -1, spike = -Inf\\)") + expect_error(spikeSlab(mean = Inf), "finite") + expect_error(spikeSlab(mean = c(0, 1)), "finite") + expect_error(spikeSlab(spike = Inf), "-Inf") + expect_error(spikeSlab(spike = NA_real_), "-Inf") + re <- randomEffects(insert(.tr(), v ~ 1 + (1 | gr(ID, dist = spikeSlab(mean = 2, spike = -Inf))))) + expect_equal(re$terms[c("mean", "spike")], data.frame(mean = 2, spike = -Inf)) + expect_output(print(re), "mean 2, spike -Inf") + expect_equal(randomEffects(insert(.tr(), v ~ 1 + (1 | ID)))$terms[c("mean", "spike")], + data.frame(mean = 0, spike = 0)) +}) + +test_that("gr() without a grouping puts all conditions in one group", { + tr <- insert(.tr(), ka + cl ~ 0 + (1 | gr(dist = spikeSlab(spike = -Inf)))) + expect_equal(as.character(tr$C2[c("ka", "cl")]), c("(eta_ka_all)", "(eta_cl_all)")) + re <- randomEffects(tr) + expect_equal(re$subjects$all, list(all = c("C1", "C2", "C3"))) + expect_equal(unique(re$terms$group), "all") + expect_length(re$fixed, 0) + # one spike-and-slab block, so the symbols share prob and tau + expect_equal(lapply(re$blocks, function(b) re$terms$stem[b]), list(c("eta_ka", "eta_cl"))) + spikeParams <- c("ka", "cl") + expect_identical(insert(.tr(), x ~ 0 + (1 | gr(dist = spikeSlab(spike = -Inf))), x = spikeParams), tr) + cov <- .cov; names(cov)[1] <- "all" + expect_error(insert(branch(define(NULL, "x <- x", x = "cl"), table = cov), cl ~ 1 + (1 | all)), + "rename the column") +}) + +test_that("the base of an exponential is read off the equations", { + eqs <- list(c(a = "exp(x1)", b = "10^(x2)", c = "exp10(x3) + 2.3^x4", d = "6^(k + x5 - z)"), + c(a = "exp(x1)", e = "x6 * exp(x6)", f = "exp(2 * x7)", g = "kb^x8", h = "2^(k - x9)")) + ids <- paste0("x", 1:9) + expect_equal(dMod2:::.wrapBases(eqs, ids), + setNames(c(exp(1), 10, 10, 2.3, NA, NA, NA, NA, NA), ids)) + expect_equal(dMod2:::.wrapBases(eqs, ids, summand = TRUE), + setNames(c(exp(1), 10, 10, 2.3, 6, NA, NA, NA, NA), ids)) + expect_equal(dMod2:::.petab_detect_scales(eqs, ids[1:4]), + c(x1 = "log", x2 = "log10", x3 = "log10", x4 = "lin")) +}) diff --git a/tests/testthat/test-remote-libs.R b/tests/testthat/test-remote-libs.R index d0ea3117..c7f5792a 100644 --- a/tests/testthat/test-remote-libs.R +++ b/tests/testthat/test-remote-libs.R @@ -505,3 +505,9 @@ test_that("a failing task returns the error, a running job keeps the name, and t job$purge(local = TRUE) expect_length(list.files("."), 0L) }) + +test_that("distributedComputing(wait = TRUE) polls ssh nodes and queues every 10 s", { + expect_identical(dMod2:::.pollInterval(list(hosts = "localhost", slurm = FALSE)), 1) + expect_identical(dMod2:::.pollInterval(list(hosts = c("localhost", "h1"), slurm = FALSE)), 10) + expect_identical(dMod2:::.pollInterval(list(hosts = "h1", slurm = TRUE)), 10) +}) diff --git a/tests/testthat/test-spikeSlabSubsets.R b/tests/testthat/test-spikeSlabSubsets.R new file mode 100644 index 00000000..b63c0776 --- /dev/null +++ b/tests/testthat/test-spikeSlabSubsets.R @@ -0,0 +1,256 @@ +# Spike-and-slab random effects with a spike at -Inf: selection of reaction rates by em(). + +.spkDir <- file.path(tempdir(), "spikeSubsets") +dir.create(.spkDir, showWarnings = FALSE) +.spk <- withr::with_dir(.spkDir, { + times <- seq(0, 10, by = 0.5) + decay <- function(x0, k0, k) k0 / k + (x0 - k0 / k) * exp(-k * times) + set.seed(1) + noisy <- function(v) data.frame(name = "x", time = times, value = v + rnorm(length(times), 0, 0.05), sigma = 0.05) + # data with and without the production term, one condition or several + one <- datalist(C1 = noisy(decay(1, 0, 0.5))) + two <- datalist(A = noisy(decay(1, 1, 0.5)), B = noisy(decay(1, 0, 0.5))) + counts <- datalist(C1 = data.frame(name = "x", time = times, sigma = NA, + value = rpois(length(times), 100 * exp(-0.5 * times)))) + shift <- datalist(A = noisy(decay(1, 1, 0.5)), B = noisy(decay(1, 1.6, 0.5))) + ids <- paste0("i", 1:6) + k1i <- 0.5 * exp(c(0.2, -0.15, 0.1, -0.2, 0.15, -0.1)) + individuals <- function(k0) do.call(datalist, setNames(lapply(1:6, function(i) noisy(decay(1, k0[i], k1i[i]))), ids)) + mixed <- individuals(rep(1:0, each = 3)) + pure <- individuals(rep(0, 6)) + + ff <- "forward-forward" + x <- Xs(odemodel(eqnvec(x = "k0 - k1*x"), modelname = "spk_x", compile = FALSE)) + g <- Y(eqnvec(x = "x"), x, modelname = "spk_g", compile = FALSE) + err <- Y(c(x = "sqrt(x)"), g, attachInput = FALSE, modelname = "spk_err", compile = FALSE) + xFF <- Xs(odemodel(eqnvec(x = "k0 - k1*x"), modelname = "spk_xff", derivMode = ff, compile = FALSE)) + gFF <- Y(eqnvec(x = "x"), xFF, modelname = "spk_gff", derivMode = ff, compile = FALSE) + base <- function(rows) insert(branch(define(NULL, "p <- p", p = c("x", "k0", "k1")), + table = data.frame(row.names = rows, ID = rows)), + "k <- exp(k)", k = c("k0", "k1")) + slab <- function(...) spikeSlab(tau = 1, spike = -Inf, ...) + sel <- insert(base("C1"), k ~ 0 + (1 | gr(dist = slab(prob = 0.5, mean = log(0.5)))), k = c("k0", "k1")) + selProb <- insert(base("C1"), k ~ 0 + (1 | gr(dist = slab(mean = log(0.5)))), k = c("k0", "k1")) + grp <- insert(base(c("A", "B")), k0 ~ 1 + (1 | gr(ID, dist = slab(prob = 0.5)))) + def <- insert(base(c("A", "B")), k0 ~ 1 + (1 | gr(ID, dist = spikeSlab(prob = 0.5, tau = 1)))) + mix <- insert(base(ids), k1 ~ 1 + (1 | ID), k0 ~ 0 + (1 | gr(ID, dist = slab(prob = 0.5)))) + mixOff <- insert(base(ids), k1 ~ 1 + (1 | ID), k0 ~ 0 + (1 | gr(ID, dist = slab(prob = 1e-6)))) + norm <- insert(branch(define(NULL, "p <- p", p = c("x", "k0", "k1")), + table = data.frame(row.names = ids, ID = ids)), "k0 <- 0") + norm <- insert(insert(norm, "k <- exp(k)", k = "k1"), k1 ~ 1 + (1 | ID)) + linear <- insert(branch(define(NULL, "p <- p", p = c("x", "k0", "k1")), + table = data.frame(row.names = "C1", one = 1)), + k0 ~ 0 + (1 | gr(dist = spikeSlab(spike = -Inf)))) + pSel <- P(sel, modelname = "spk_psel", compile = FALSE) + pProb <- P(selProb, modelname = "spk_pprob", compile = FALSE) + pGrp <- P(grp, modelname = "spk_pgrp", compile = FALSE) + pDef <- P(def, modelname = "spk_pdef", compile = FALSE) + pDefFF <- P(def, modelname = "spk_pdefff", derivMode = ff, compile = FALSE) + pMix <- P(mix, modelname = "spk_pmix", derivMode = ff, compile = FALSE) + pMixOff <- P(mixOff, modelname = "spk_pmixoff", derivMode = ff, compile = FALSE) + pNorm <- P(norm, modelname = "spk_pnorm", derivMode = ff, compile = FALSE) + pLin <- P(linear, modelname = "spk_plin", compile = FALSE) + # two independent species with four candidate rates in one group + ks <- c("a0", "a1", "b0", "b1") + x2 <- Xs(odemodel(eqnvec(x = "a0 - a1*x", y = "b0 - b1*y"), modelname = "spk_x2", compile = FALSE)) + g2 <- Y(eqnvec(x = "x", y = "y"), x2, modelname = "spk_g2", compile = FALSE) + ec <- insert(branch(define(NULL, "p <- p", p = c("x", "y", ks)), table = data.frame(row.names = "C1", one = 1)), + "k <- exp(k)", k = ks) + ec <- insert(ec, k ~ 0 + (1 | gr(dist = slab(prob = 0.5, mean = log(0.5)))), k = ks) + pEC <- P(ec, modelname = "spk_pec", compile = FALSE) + compile(g, x, err, xFF, gFF, pSel, pProb, pGrp, pDef, pDefFF, pMix, pMixOff, pNorm, pLin, g2, x2, pEC, + output = "spk_all", cores = test_cores()) + list(one = one, two = two, counts = counts, shift = shift, mixed = mixed, pure = pure, x = x, g = g, err = err, + xFF = xFF, gFF = gFF, pSel = pSel, pProb = pProb, pGrp = pGrp, pDef = pDef, pDefFF = pDefFF, pMix = pMix, + pMixOff = pMixOff, pNorm = pNorm, pLin = pLin, x2 = x2, g2 = g2, pEC = pEC, dir = .spkDir) +}) + +.spkFit <- function(data, p, ..., errmodel = NULL, method = "focei") { + withr::local_dir(.spk$dir) + obj <- normL2(data, .spk$g * .spk$x * p, errmodel = errmodel) + list(fit = em(obj, randomEffects(p), method = method, verbose = FALSE, ...), obj = obj) +} + +# fits that several tests share, each computed once +.spkFits <- new.env() +.spkShared <- function(key, expr) { + if (is.null(.spkFits[[key]])) .spkFits[[key]] <- expr + .spkFits[[key]] +} +.spkCounts <- function(method) .spkShared(paste0("counts_", method), + .spkFit(.spk$counts, .spk$pSel, init = c(x = 100), errmodel = .spk$err, method = method)) +.spkMixed <- function(method) .spkShared(paste0("mixed_", method), withr::with_dir(.spk$dir, { + set.seed(1) + em(normL2(.spk$mixed, .spk$gFF * .spk$xFF * .spk$pMix), randomEffects(.spk$pMix), + init = c(x = 1, k1 = log(0.5), omega_k1_k1 = log(0.2)), method = method, verbose = FALSE) +})) + +test_that("a production term the data do not need is switched off, the decay rate stays", { + r <- .spkFit(.spk$one, .spk$pSel, init = c(x = 1)) + fit <- r$fit + expect_true(fit$converged) + p0 <- setNames(fit$random$p0, fit$random$eta) + expect_gt(p0[["k0"]], 0.99) + expect_lt(p0[["k1"]], 1e-6) + expect_equal(fit$random$mode[fit$random$eta == "k0"], -Inf) + expect_equal(exp(fit$random$mode[fit$random$eta == "k1"]), 0.5, tolerance = 0.1) + expect_equal(unname(fit$argument["x"]), 1, tolerance = 0.05) + + # p0 from the Laplace integrals of the subsets of non-negligible weight, by trust() on objective plus prior + withr::local_dir(.spk$dir) + modes <- setNames(fit$random$mode, fit$random$parameter) + tau <- 1 + m2logZ <- function(on) { + prior <- constraintL2(setNames(rep(log(0.5), length(on)), on), sigma = tau) + off <- setdiff(names(modes), on) + start <- modes[on] + start[!is.finite(start)] <- log(0.5) + tr <- trust(r$obj + prior, start, fixed = c(fit$argument["x"], setNames(rep(-Inf, length(off)), off)), + hessianMethod = "gn") + tr$value + length(on) * log(tau^2) + as.numeric(determinant(tr$hessian / 2)$modulus) + } + z1 <- m2logZ("eta_k1_all") + z2 <- m2logZ(c("eta_k0_all", "eta_k1_all")) + expect_equal(p0[["k0"]], 1 / (1 + exp(-(z2 - z1) / 2)), tolerance = 1e-4) +}) + +test_that("with counts and an error model of the prediction the production term is switched off as well", { + fit <- .spkCounts("focei")$fit + expect_true(fit$converged) + p0 <- setNames(fit$random$p0, fit$random$eta) + expect_gt(p0[["k0"]], 0.7) + expect_lt(p0[["k1"]], 1e-6) + expect_equal(exp(fit$random$mode[fit$random$eta == "k1"]), 0.5, tolerance = 0.15) + expect_equal(unname(fit$argument["x"]), 100, tolerance = 0.1) +}) + +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")) + 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))) +}) + +test_that("quadrature takes the default spike at 0 as well, near the Laplace sum", { + init <- c(x = 1, k0 = 0, k1 = log(0.5)) + quad <- .spkFit(.spk$shift, .spk$pDef, init = init, method = "quadrature")$fit + withr::local_dir(.spk$dir) + laplace <- suppressMessages(em(normL2(.spk$shift, .spk$gFF * .spk$xFF * .spk$pDefFF), + randomEffects(.spk$pDefFF), init = init, verbose = FALSE)) + expect_true(quad$converged) + expect_equal(quad$random$p0, laplace$random$p0, tolerance = 0.05) + expect_equal(quad$value, laplace$value, tolerance = 0.01) +}) + +test_that("normal random effects beside a spike at -Inf: focei and quadrature select the same", { + fl <- .spkMixed("focei") + fq <- .spkMixed("quadrature") + for (f in list(fl, fq)) { + expect_true(f$converged) + p0 <- setNames(f$random$p0[f$random$eta == "k0"], f$random$group[f$random$eta == "k0"]) + expect_true(all(p0[c("i1", "i2", "i3")] < 0.05)) + expect_true(all(p0[c("i4", "i5", "i6")] > 0.5)) + expect_equal(exp(unname(f$argument["k1"])), 0.5, tolerance = 0.15) + } + expect_equal(fq$value, fl$value, tolerance = 0.01) +}) + +test_that("SAEM with a spike at -Inf beside normal random effects agrees with quadrature", { + fq <- .spkMixed("quadrature") + fs <- .spkMixed("saem") + expect_true(fs$converged) + k0 <- fs$random$eta == "k0" + expect_equal(fs$random$p0[k0], fq$random$p0[k0], tolerance = 0.05) + expect_equal(fs$random$mode[k0][4:6], rep(-Inf, 3)) + expect_equal(fs$argument[c("x", "k1")], fq$argument[c("x", "k1")], tolerance = 0.03) + expect_equal(exp(fs$argument[["omega_k1_k1"]]), exp(fq$argument[["omega_k1_k1"]]), tolerance = 0.2) +}) + +test_that("SAEM switches a production term off without groups", { + set.seed(2) + fit <- .spkFit(.spk$one, .spk$pSel, init = c(x = 1), method = "saem")$fit + p0 <- setNames(fit$random$p0, fit$random$eta) + expect_gt(p0[["k0"]], 0.9) + expect_lt(p0[["k1"]], 0.01) + expect_equal(exp(fit$random$mode[fit$random$eta == "k1"]), 0.5, tolerance = 0.1) +}) + +test_that("with prob near 0 and no production the subset quadrature is the quadrature of the normal model", { + withr::local_dir(.spk$dir) + init <- c(x = 1, k1 = log(0.5), omega_k1_k1 = log(0.2)) + ref <- suppressMessages(em(normL2(.spk$pure, .spk$gFF * .spk$xFF * .spk$pNorm), randomEffects(.spk$pNorm), + init = init, method = "quadrature", verbose = FALSE)) + sub <- em(normL2(.spk$pure, .spk$gFF * .spk$xFF * .spk$pMixOff), randomEffects(.spk$pMixOff), init = init, + method = "quadrature", verbose = FALSE) + # the weight of the spikes enters -2 log L + expect_equal(sub$value + 2 * 6 * log1p(-1e-6), ref$value, tolerance = 1e-3) + expect_equal(sub$argument[names(init)], ref$argument[names(init)], tolerance = 1e-3) +}) + +test_that("an estimated prob is the mean inclusion probability", { + fit <- .spkFit(.spk$one, .spk$pProb, init = c(x = 1))$fit + expect_true(fit$converged) + expect_equal(unname(fit$argument["prob_all"]), mean(1 - fit$random$p0), tolerance = 1e-4) +}) + +test_that("a spike per group switches the production term off in the group without production", { + fit <- .spkFit(.spk$two, .spk$pGrp, init = c(x = 1, k0 = 0, k1 = log(0.5)))$fit + p0 <- setNames(fit$random$p0, fit$random$group) + expect_lt(p0[["A"]], 0.1) + expect_gt(p0[["B"]], 0.9) + expect_equal(exp(unname(fit$argument["k0"])), 1, tolerance = 0.2) +}) + +test_that("a spike at -Inf needs an exponential, and laplaceEM refuses it", { + withr::local_dir(.spk$dir) + objLin <- normL2(.spk$one, .spk$g * .spk$x * .spk$pLin) + expect_error(em(objLin, randomEffects(.spk$pLin), init = c(x = 1, k1 = 0.5)), + "summand in the exponent") + obj <- normL2(.spk$one, .spk$g * .spk$x * .spk$pSel) + expect_error(em(obj, randomEffects(.spk$pSel), init = c(x = 0.5), method = "laplaceEM"), "method = \"focei\"") +}) + +test_that("EC beyond the budget agrees with the sum over all subsets", { + withr::local_dir(.spk$dir) + 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) + data <- datalist(C1 = rbind(noisy("x", 2 - 1.5 * exp(-0.5 * times)), noisy("y", 2 * exp(-0.3 * times)))) + 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))) + 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) +}) diff --git a/tests/testthat/test-statsOutput.R b/tests/testthat/test-statsOutput.R index 49de68d1..e2bf73f5 100644 --- a/tests/testthat/test-statsOutput.R +++ b/tests/testthat/test-statsOutput.R @@ -60,7 +60,7 @@ test_that("mstrust routes the arguments to the optimizer, the sampler and the ob fits <- mstrust(obj, c(a = 0, b = 0), fits = 2, optmethod = myopt, samplefun = mysample, spread = 0.5, iterlim = 7, scale = 10) expect_identical(seen$iterlim, 7) - expect_identical(sort(seen$dots), c("rinit", "rmax", "scale")) + expect_identical(seen$dots, "scale") expect_equal(fits[[1]]$parinit, c(a = 0.5, b = 1)) expect_equal(fits[[2]]$value, 12.5) run <- attr(fits, "run") @@ -114,6 +114,13 @@ test_that("reduceReplicates gives mean, standard error and the stable columns", expect_snapshot(pinFrame(suppressMessages(reduceReplicates(d[, -7])))) }) +test_that("reduceReplicates reports dropped columns only when there are some", { + d <- replicateData()[, c("name", "time", "value", "condition", "dose")] + expect_no_message(reduceReplicates(d)) + expect_no_message(reduceReplicates(d, select = c("condition", "dose"))) + expect_message(reduceReplicates(replicateData()), "Dropped columns: batch") +}) + test_that("reduceReplicates checks the input", { d <- replicateData() expect_error(reduceReplicates(d[, -1]), @@ -148,11 +155,11 @@ test_that("fitErrorModel fits per group and returns the standard error", { full <- fitErrorModel(red, factors = "name", par = c(s0 = -4, srel = -3), blather = TRUE) expect_identical(names(full), c(names(red), "s0", "srel", "cbLower68", "cbUpper68", - "cbLower95", "cbUpper95", "condidnt", "sigmaLS")) + "cbLower95", "cbUpper95", "group", "sigmaLS")) expect_identical(attr(full, "errorModel"), "exp(s0)+exp(srel)*x^2") expect_identical(full$sigma, out$sigma) expect_identical(full$sigmaLS, red$sigma) - expect_type(full$condidnt, "character") + expect_type(full$group, "character") expect_snapshot(print(roundNumeric(full))) # bounds, named or positional; two factors give one group per combination @@ -164,7 +171,23 @@ test_that("fitErrorModel fits per group and returns the standard error", { expect_equal(pos$srel, bnd$srel) two <- fitErrorModel(red, factors = c("name", "condition"), par = c(s0 = -4, srel = -3), blather = TRUE) - expect_identical(unique(as.character(two$condidnt)), c("y ctrl", "z ctrl")) + expect_identical(unique(as.character(two$group)), c("y ctrl", "z ctrl")) +}) + +test_that("fitErrorModel optimizes with the symbolic gradient of the error model", { + skip_if_not_installed("optimx") + skip_if_not_installed("numDeriv") + red <- errorModelData() + full <- fitErrorModel(red, factors = "name", par = c(s0 = -4, srel = -3), blather = TRUE) + rows <- red$name == "y" + nll <- function(p) { + v <- exp(p[1]) + exp(p[2]) * red$value[rows]^2 + sum((red$n[rows] - 1) * (log(v) + red$n[rows] * red$sigma[rows]^2 / v)) + } + best <- unname(unlist(full[which(rows)[1], c("s0", "srel")])) + expect_lt(max(abs(numDeriv::grad(nll, best))), 1e-3) + expect_error(fitErrorModel(red, factors = "name", errorModel = "pmax(exp(s0), x)", + par = c(s0 = -4)), "no symbolic derivative") }) test_that("fitErrorModel plots the variances of the replicates", { diff --git a/tests/testthat/test-symmetry.R b/tests/testthat/test-symmetry.R index 10684546..5b8411ac 100644 --- a/tests/testthat/test-symmetry.R +++ b/tests/testthat/test-symmetry.R @@ -2,9 +2,9 @@ # the objects. The analysis itself is tested in symident. test_that("argument names go to snake_case and field names back to camelCase", { - expect_identical(dMod2:::.symSnake(c("relevanceCapDir", "laurentDegNum", "timeout", + expect_identical(dMod2:::.symSnake(c("relevanceCapDir", "laurentDegNum", "msolveEntries", "perprimeMinPrimes", "stackedMin")), - c("relevance_cap_dir", "laurent_deg_num", "timeout", + c("relevance_cap_dir", "laurent_deg_num", "msolve_entries", "perprime_min_primes", "stacked_min")) expect_identical(dMod2:::.symCamel(c("lie_order_used", "rank", "gauge_suggestion")), c("lieOrderUsed", "rank", "gaugeSuggestion")) @@ -18,6 +18,9 @@ test_that("argument names go to snake_case and field names back to camelCase", { expect_identical(names(y$symmetries[[1]]$completeGenerator), "k_on") expect_identical(names(y$symmetries[[1]]$generator), "k_off") expect_identical(names(y$symmetries[[1]]$stateComponents), "x_c1") + z <- dMod2:::.symCamelFields(list(count_bound = 0.1, eliminated = list(x_c1 = "T_1 - x_c2"))) + expect_identical(names(z), c("countBound", "eliminated")) + expect_identical(names(z$eliminated), "x_c1") }) test_that("reconstControl() passes homotopy to symident as a flag", { @@ -177,7 +180,7 @@ test_that("scalings only, the gauge and the control settings", { expect_identical(r$identifiable, NA) expect_true(all(vapply(r$symmetries, `[[`, "", "type") == "scaling")) r <- symmetryDetection(f_ab, eqnvec(y = "s*A"), gaugePreference = NULL, - control = reconstControl(degreeCap = 3L, timeout = 100), + control = reconstControl(degreeCap = 3L), verbose = FALSE) expect_length(r$gauge, 1L) expect_identical(r$info$settings$degreeCap, 3L) @@ -233,7 +236,8 @@ test_that("discrete symmetries with a known input, kept by the reduction, and of skip_if(inherits(try(reticulate::import("symident.sym.msolve")$`_msolve_binary`(), silent = TRUE), "try-error"), "msolve not available") f <- eqnvec(x1 = "-(k21 + k01)*x1 + k12*x2 + u", x2 = "k21*x1 - k12*x2") - r <- symmetryDetection(f, eqnvec(y = "x2"), knownInputs = "u", discrete = list(points = 2)) + r <- symmetryDetection(f, eqnvec(y = "x2"), knownInputs = "u", mode = "global", + globalOptions = list(points = 2, msolveTerms = 1e5)) expect_true(r$identifiable) expect_length(r$discreteSymmetries, 1L) s <- r$discreteSymmetries[[1]] @@ -244,13 +248,15 @@ test_that("discrete symmetries with a known input, kept by the reduction, and of expect_identical(r$info$discrete$fundamentalDomain, "k01 < k12") expect_identical(nrow(r$info$discrete$counts), 2L) expect_true(r$info$discrete$countFinal) + expect_true(r$info$discrete$certificate$complete %in% c("exact", "verified", "axiom")) red <- symmetryReduction(r) expect_length(red$discrete$symmetries, 1L) expect_identical(red$discrete$fundamentalDomain, "k01 < k12") expect_output(print(r), "fundamental domain: k01 < k12") # a model with a scaling is reduced first, the maps in the reduced coordinates g <- eqnvec(m = "ktx - dm*m", p = "ktl*m - dp*p") - r2 <- discreteSymmetries(symmetryDetection(g, eqnvec(y = "p"), reconstruct = TRUE), points = 2) + r2 <- discreteSymmetries(symmetryDetection(g, eqnvec(y = "p"), reconstruct = TRUE), points = 2, + memory = 4, msolveEntries = 4e8) expect_false(r2$identifiable) expect_s3_class(r2$info$discrete$reduced$trafo, "eqnvec") expect_setequal(r2$discreteSymmetries[[1]]$changes, c("m", "dm", "dp")) diff --git a/tests/testthat/test-trust.R b/tests/testthat/test-trust.R index d513089c..8a125328 100644 --- a/tests/testthat/test-trust.R +++ b/tests/testthat/test-trust.R @@ -983,6 +983,23 @@ test_that("a phase hands over after radiusStall iterations at an unchanged radiu } } +test_that("the sparse choice evaluates the reflective start, which the kernel then reuses", { + target <- c(a = 1, b = -2, c = 3) + seen <- list() + obj <- function(p, ..., hessian = TRUE) { + seen[[length(seen) + 1L]] <<- p + H <- diag(2, length(p)) + dimnames(H) <- list(names(p), names(p)) + if (identical(hessian, "sparse")) H <- Matrix::Matrix(H, sparse = TRUE) + list(value = sum((p - target)^2), gradient = 2 * (p - target), hessian = H) + } + fit <- withr::with_options(list(dMod2.sparseAuto = list(parameters = 0, fill = 1)), + trust(obj, c(a = 0, b = 0, c = 0), parlower = c(a = 0), iterlim = 50)) + expect_true(fit$converged) + expect_gt(seen[[1]][["a"]], 0) + expect_gt(max(abs(seen[[2]] - seen[[1]])), 1e-8) +}) + # The damped BFGS update of the kernel with the cautious test. .bfgs_r <- function(B, s, y, cautious = 1e-8) { if (!(sum(s * y) > cautious * sqrt(sum(s^2) * sum(y^2)))) return(B) diff --git a/vignettes/articles/guide-sparse-deviations.Rmd b/vignettes/articles/guide-sparse-deviations.Rmd index 8c8e2264..ea8d02e0 100644 --- a/vignettes/articles/guide-sparse-deviations.Rmd +++ b/vignettes/articles/guide-sparse-deviations.Rmd @@ -380,7 +380,7 @@ if (all(ssSet %in% publicationDCF$rate)) { `r ssText` The 20 differences are exchangeable under the model: the nonzero ones against the slab density $\rho\, \mathcal{N}(0, \tau^2)$ (line), the count at 0 against the expected $20 (1 - \rho)$ (bar). With `r length(ssSet)` nonzero differences the figure shows gross departures -from the slab, an outlier or separate clusters, but is no test of its shape: +from the slab, an outlier or separate clusters, but is no test of the slab shape: ```{r, fig.width = 8, fig.height = 3} rho <- dcfSS$argument[["prob_compound"]] @@ -466,13 +466,36 @@ exactly zero unless the data need them: | distribution | a deviation $\eta$ of a group | hyperparameters | |---|---|---| -| `spikeSlab()` | $0$ with probability $1 - \rho$, else $\mathcal{N}(0, \tau^2)$ | `prob_`, `tau_` | +| `spikeSlab()` | `spike` with probability $1 - \rho$, else $\mathcal{N}(\mu, \tau^2)$; `spike` and $\mu$ (`mean`) default to 0 | `prob_`, `tau_` | | `dirichletProcess()` | cluster value: $0$ for the population cluster, else one $\mathcal{N}(0, \tau^2)$ draw | `concentration_`, `tau_` | Hyperparameters are shared by the symbols of a term (`_1`, `_2`, ... for several terms of one grouping) and estimated unless given, as in `spikeSlab(tau = 0.5)`. Normal and sparse random effects of one grouping combine; `em(method = "focei")` fits all. +## Switching parameters off + +With `spike = -Inf` on a parameter in an exponential, `insert(trafo, "k <- exp(k)")`, the spike +is the rate 0: the reaction is absent. `gr(dist = )` without a grouping makes one group `all` of +all conditions, so that with `0 +` the random effect is the parameter itself and the fit selects +reactions. For a model `g * x` with data `data` and the rates `k0`, `k1` in the parameter +transformation `trafo`: + +```{r, eval = FALSE} +trafo <- insert(trafo, "k <- exp(k)", k = c("k0", "k1")) +trafo <- insert(trafo, k ~ 0 + (1 | gr(dist = spikeSlab(prob = 0.5, tau = 1, mean = log(0.5), spike = -Inf))), + k = c("k0", "k1")) +fit <- em(normL2(data, g * x * P(trafo)), randomEffects(P(trafo)), init = c(x = 1)) +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` +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). + ## Fitting sparse random effects `em(method = "focei")` integrates sparse random effects by the Laplace approximation at the joint diff --git a/vignettes/articles/installation.Rmd b/vignettes/articles/installation.Rmd index 049e9410..820e913b 100644 --- a/vignettes/articles/installation.Rmd +++ b/vignettes/articles/installation.Rmd @@ -59,7 +59,7 @@ libsbml in a separate Python process, whose interpreter `DMOD_LIBSBML_PYTHON` se ## symident and msolve On first use of `symmetryDetection()` or `symmetryReduction()`, dMod2 installs -[symident](https://github.com/dModverse/symident) from PyPI into the session Python. On failure +[symident](https://dmodverse.github.io/symident/) from PyPI into the session Python. On failure the error names the interpreter; `pip install -U symident` with that interpreter installs it. Coupled steady states in a steady-state start need [msolve](https://msolve.lip6.fr/). diff --git a/vignettes/articles/methods-multiple-shooting.Rmd b/vignettes/articles/methods-multiple-shooting.Rmd index 35afe7a0..110a4d78 100644 --- a/vignettes/articles/methods-multiple-shooting.Rmd +++ b/vignettes/articles/methods-multiple-shooting.Rmd @@ -130,13 +130,13 @@ whole stage no longer closes the gaps. It needs forward sensitivities. `multipleShootingControl$nodes = "auto"` (default) starts from ten segments per condition, or one per half oscillation of the data if more, and halves a segment where -- the spectral radius of $G_j$ exceeds `growth` (10), the expansion of the linearized flow in +- the spectral radius of $G_j$ exceeds `growth` (default 10), the expansion of the linearized flow in the coordinates of the nodes; -- the RMS of the weighted residuals exceeds `misfit` (3) and twice the condition median; +- the RMS of the weighted residuals exceeds `misfit` (default 3) and twice the condition median; - or the solve fails. Cuts happen before the first step and at every iterate, never below half the finest data spacing, -and keep `minPoints` (states plus one) data points per half, so no node fits a segment alone. +and keep `minPoints` (default: states plus one) data points per half, so no node fits a segment alone. Over a period an oscillator has growth near one; what grows is the phase sensitivity to the frequency, linearly in the periods, until the segment fits the data a period off. One segment per half oscillation, diff --git a/vignettes/articles/methods-nlme.Rmd b/vignettes/articles/methods-nlme.Rmd index 28015ce2..5d0db0c1 100644 --- a/vignettes/articles/methods-nlme.Rmd +++ b/vignettes/articles/methods-nlme.Rmd @@ -148,12 +148,18 @@ move of the grid with $\psi$ is not differentiated. `method = "quadrature"` starts from the converged FOCEI fit and alternates: -- **Rebuild.** Grids at the current $\psi$, at the lowest level (never falling) whose error is at - most `tol` over the number of groups. The error of level $l$ is estimated by - $2\lvert \log L_i^{(l+1)} - \log L_i^{(l)} \rvert$. A level of more than `maxNodes` nodes per - group (default 1000) is never evaluated; there the estimate is the change from level $l - 1$, - and a group above the tolerance is capped at $l$. For $K = 20$ levels $K + 1$ to $K + 3$ have 41, - 801 and 10041 nodes, so the default budget ends at $K + 2$. +- **Rebuild.** Grids at the current $\psi$, refined dimension-adaptively [@gerstner2003dimension] + from the union of the grid of the stage level and the grid of the last rebuild, so a grid never + shrinks. The grid is a + downward closed set of multi-indices $\mathbf{i}$, the sum (6) over it; the forward + neighbors that keep the set downward closed are evaluated, and their sum, the change of $\log L_i$ they would make, + estimates the error $2 \lvert \log L_i^{+} - \log L_i \rvert$. While it exceeds `tol` over the + number of groups, the neighbor of largest term joins the set and the neighbors of that index are evaluated, + so the grid grows only in the directions in which $e^{-\Phi_i/2}$ departs from the Gaussian. + Refinements beyond `maxNodes` evaluated nodes per group (default 1000) are not made; there the + 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. @@ -169,11 +175,11 @@ groups whose two estimates differ by more than three standard errors plus the le ## Laplace EM -`method = "laplaceEM"` runs ECME: a trust-region run of at most `maxCm1Iter` (30) iterations of +`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 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` (200) iterations. Settings come from `control$quadrature`. +(default `1e-5`), or after `maxEcm` (default 200) iterations. Settings come from `control$quadrature`. ## SAEM @@ -212,7 +218,7 @@ $\Pr(z_{ij} = 1) = p$ and a slab value $v_{ij} \sim \mathcal{N}(0, \tau^2)$ 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` (3) points, which gives the conditional inclusion probability with the slab value + term at `nodes` (default 3) points, which gives the conditional inclusion probability 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}$$ diff --git a/vignettes/articles/methods-sparsity-priors.Rmd b/vignettes/articles/methods-sparsity-priors.Rmd index a4bf9895..95128ad2 100644 --- a/vignettes/articles/methods-sparsity-priors.Rmd +++ b/vignettes/articles/methods-sparsity-priors.Rmd @@ -14,7 +14,7 @@ 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)$ | `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_` | | `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 @@ -601,4 +601,68 @@ $$\texttt{valueSE} = \frac{2\, \operatorname{sd}(\zeta)}{\sqrt{M}\, \bar\zeta} . The symbols of a group are seated together on the full $P_i$. `control$saem$particles` sets $M$ (500). An SAEM fit has no gradient, Hessian or empirical information. +## Spike at a given value + +`spikeSlab(mean = , spike = )` generalizes the prior of [Spike and slab](#spike-and-slab) to + +$$p(\eta_k) = (1 - \rho)\, \delta_\alpha(\eta_k) + \rho\, \mathcal{N}(\eta_k;\, \mu_0, \tau^2) , \tag{41}$$ + +$\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 +$\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}$$ + +$H_F$ the Gauss-Newton Hessian, 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. + +Beyond the budget a group takes 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 +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. + +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 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$, + +$$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}$$ + +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 +\rho^{|F|} (1 - \rho)^{K - |F|} Z_F$ is a smooth function of the fixed effects, $\Omega$, $\tau$ and +$\rho$. `trust()` minimizes it, with the gradient $\sum_F \Pr(F \mid y) \sum_i \omega_i\, \nabla +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`. + ## References diff --git a/vignettes/articles/refs.bib b/vignettes/articles/refs.bib index 8e7e4a0c..f86bb8ed 100644 --- a/vignettes/articles/refs.bib +++ b/vignettes/articles/refs.bib @@ -651,3 +651,14 @@ @book{pitman2006combinatorial location = {Berlin, Heidelberg}, doi = {10.1007/b11601500}, } + +@article{gerstner2003dimension, + title = {Dimension-Adaptive Tensor-Product Quadrature}, + author = {Gerstner, Thomas and Griebel, Michael}, + journal = {Computing}, + volume = {71}, + number = {1}, + pages = {65--87}, + year = {2003}, + doi = {10.1007/s00607-003-0015-5} +}