diff --git a/.github/workflows/R-CMD-check.yaml b/.github/workflows/R-CMD-check.yaml index c5c1fd45..e3e86dfb 100644 --- a/.github/workflows/R-CMD-check.yaml +++ b/.github/workflows/R-CMD-check.yaml @@ -1,14 +1,33 @@ # Workflow derived from https://github.com/r-lib/actions/tree/v2/examples # Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help +# Runs on push to master and on every pull request; docs-only changes run no check. on: push: branches: [main, master] + paths-ignore: + - 'vignettes/articles/**' + - 'examples/**' + - 'dev/**' + - 'bench/**' + - '**.md' + - '_pkgdown.yml' + - 'pkgdown/**' pull_request: - # the other devel branches are not push-triggered: a full matrix run on every - # commit of a port in progress is not worth the minutes. Dispatch one when - # a layer is ready to be judged. + paths-ignore: + - 'vignettes/articles/**' + - 'examples/**' + - 'dev/**' + - 'bench/**' + - '**.md' + - '_pkgdown.yml' + - 'pkgdown/**' workflow_dispatch: +# a new push cancels the outdated run of the same branch or pull request +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + name: R-CMD-check permissions: read-all @@ -27,12 +46,10 @@ jobs: - {os: windows-latest, r: 'release'} - {os: ubuntu-latest, r: 'devel', http-user-agent: 'release'} - {os: ubuntu-latest, r: 'release'} + # no oldrel-1: DESCRIPTION requires R >= 4.5.0 env: - # cppDE is a private repo in the same org and GITHUB_TOKEN is scoped to - # this repo alone, so pak cannot resolve the Remote with it. DMODVERSE_PAT - # grants Contents:read on dModverse/cppDE. The fallback keeps outside - # forks running as far as they can get. + # cppDE is a private repo in the same org: DMODVERSE_PAT reads it for the Remote GITHUB_PAT: ${{ secrets.DMODVERSE_PAT || secrets.GITHUB_TOKEN }} R_KEEP_PKG_SOURCE: yes # skip_on_cran() guards 13 test files; our own jobs opt in. @@ -80,16 +97,10 @@ jobs: - uses: r-lib/actions/check-r-package@v2 with: - # --as-cran dropped: dMod depends on cppDE via Remotes (GitHub-only), - # so CRAN-submission feasibility checks would always WARN. - # --ignore-vignettes: the vignettes ship pre-rendered as static PDFs - # and are not rebuilt here; --no-build-vignettes alone leaves a - # "Directory 'inst/doc' does not exist" WARNING that --ignore-vignettes - # silences cleanly. - args: 'c("--no-manual", "--ignore-vignettes")' + # without --as-cran: cppDE is a GitHub Remote, not on CRAN + args: 'c("--no-manual")' upload-snapshots: true - build_args: 'c("--no-manual","--no-build-vignettes","--compact-vignettes=gs+qpdf")' - error-on: '"warning"' + build_args: 'c("--no-manual","--compact-vignettes=gs+qpdf")' # Fedora is not a hosted runner, hence a container with the distro's own R: # gcc, FlexiBLAS and the hardening flags differ from Ubuntu's. No RSPM binaries @@ -137,7 +148,6 @@ jobs: - uses: r-lib/actions/check-r-package@v2 with: - args: 'c("--no-manual", "--ignore-vignettes")' + args: 'c("--no-manual")' upload-snapshots: true - build_args: 'c("--no-manual","--no-build-vignettes","--compact-vignettes=gs+qpdf")' - error-on: '"warning"' + build_args: 'c("--no-manual","--compact-vignettes=gs+qpdf")' diff --git a/DESCRIPTION b/DESCRIPTION index 736a7a19..e54966da 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Package: dMod2 Type: Package Title: Parameter Estimation in Dynamical Models -Version: 0.15.10 +Version: 0.16.0 Date: 2026-11-16 Authors@R: c( person("Simon", "Beyer", email = "simon.beyer@fdm.uni-freiburg.de", diff --git a/NAMESPACE b/NAMESPACE index 446b6b50..96c9a8ee 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -93,6 +93,8 @@ S3method(plotCombined,em) S3method(plotCombined,prdlist) S3method(plotData,data.frame) S3method(plotData,datalist) +S3method(plotPars,em) +S3method(plotPars,list) S3method(plotPars,parframe) S3method(plotPars,parlist) S3method(plotPrediction,prdlist) @@ -207,14 +209,14 @@ export(coordTransform) export(covariates) export(customTotals) export(dMod2Jobs) -export(dMod_colors) -export(dMod_colors_cb) -export(dMod_divergent) -export(dMod_divergent_cb) -export(dMod_gradient) -export(dMod_gradient_cb) -export(dMod_palette) -export(dMod_palettes) +export(dMod2_colors) +export(dMod2_colors_cb) +export(dMod2_divergent) +export(dMod2_divergent_cb) +export(dMod2_gradient) +export(dMod2_gradient_cb) +export(dMod2_palette) +export(dMod2_palettes) export(datalist) export(datapointL2) export(define) @@ -303,12 +305,12 @@ export(repar) export(replaceSymbols) export(res) export(resolveRecurrence) -export(scale_color_dMod) -export(scale_color_dMod_c) -export(scale_color_dMod_div) -export(scale_fill_dMod) -export(scale_fill_dMod_c) -export(scale_fill_dMod_div) +export(scale_color_dMod2) +export(scale_color_dMod2_c) +export(scale_color_dMod2_div) +export(scale_fill_dMod2) +export(scale_fill_dMod2_c) +export(scale_fill_dMod2_div) export(setCompartmentVolume) export(slurmCluster) export(slurmTemplate) @@ -318,7 +320,7 @@ export(steadyStates) export(subset.eqnlist) export(symmetryDetection) export(symmetryReduction) -export(theme_dMod) +export(theme_dMod2) export(trust) export(trustL1) export(write.eqnlist) diff --git a/NEWS.md b/NEWS.md index 8e494322..c695733e 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,166 @@ +# dMod2 0.16.0 + +* The plotting theme and color helpers are named after the package: `theme_dMod2()`, + `scale_color_dMod2()`, `scale_fill_dMod2()` (with `_c` and `_div`), `dMod2_colors`, + `dMod2_colors_cb`, `dMod2_palette()`, `dMod2_palettes()`, `dMod2_gradient()`, + `dMod2_divergent()` and their `_cb` forms; the `dMod` names are gone. `theme_dMod2()` draws the + axis ticks outside the panel. +* `trust()` runs the hybrid method of Fides (Fröhlich and Sorger 2022) by default: Gauss-Newton, + then BFGS once the trust radius stayed the same for 20 iterations. The BFGS matrix starts from the + Gauss-Newton Hessian at the start and is updated along the Gauss-Newton steps, and the radius is + kept at the switch. `hessianMethod = "gn"` keeps plain Gauss-Newton. The sparse path, multiple + shooting and `boundary = "clip"` run Gauss-Newton. `mstrust()` and `profile()` follow the + default; `em()` and FOCEI keep Gauss-Newton. +* New settings of `trust()` phases: `keepRadius` starts a phase at the radius of the handover, and + `onStop = "end"` ends the run on a value, model, step or stagnation stop instead of handing over. + `qnControl$hessianInit = "tracked"` starts a later BFGS phase from a BFGS matrix updated over the + whole run. +* `trust()` with multiple shooting: a stop on stagnation, value, predicted decrease or gradient + reports `converged = TRUE` only where the full step of the condensed model predicts a decrease of + at most `mtol`, as in single shooting. +* `trust()` with multiple shooting: after the natural level function hands over to the filter, + `iterlim` bounds both parts together and `iterations` counts both. +* A phase of `trust()` takes `radiusStall`, the number of consecutive iterations at an unchanged + trust radius after which it hands over to the next phase, the switch of the hybrid method of + Fides (Fröhlich and Sorger). +* `trust(sparse = TRUE)` runs a BFGS phase with `qnControl$hessianInit = "gn"` as limited-memory + BFGS: the sparse Hessian of the objective at the start of the phase, shifted by a multiple of the + identity where it is not positive definite, plus the compact correction + of Byrd, Nocedal and Schnabel from the last `qnMemory` pairs, 10 where it is 0, as a low-rank + part of the model. `sparse = "auto"` takes the sparse path only where every phase takes the + Hessian of the objective. +* `em()` with random effects over several groupings passes every argument of `trust()` in + `control$trustControl` to the outer search, `hessianMethod`, `phases`, `switches` and + `qnControl` included, and reports `phaseIterations`. FOCEI of one grouping reads `rinit`, + `rmax`, `iterlim`, `ftol` and `mtol`; flat `ftol`, `mtol`, `gtol` and `xtol` join `tolControl`. + Other entries of `control$trustControl` are an error. +* `em()` and `msem()` take `control$inner = "sqp"` for FOCEI and for spike-and-slab and + Dirichlet-process random effects. The outer search first runs on inexact modes: + `innerControl$sqpIterlim` inner iterations (default 2) from the modes predicted along + d eta / d theta, with value and gradient corrected to first order, to the square roots of `ftol` + and `mtol`. It then continues on converged modes, so estimates, value, gradient and Hessian are + those of the nested search. `"nested"` stays the default. Fits report `innerIterations` and, with + `"sqp"`, `sqpIterations`. +* `em()` and `msem()` refuse unknown entries of `control$quadrature`, `control$saem` and + `control$innerControl`, as of `control` and `control$sparseFit`. `innerControl` takes `rinit`, + `rmax`, `iterlim`, `steptol`, `mtol`, `eigenFloorRelative` and `sqpIterlim`. +* `trust()`, `trustL1()` and `mstrust()` no longer name the control list of a flat tolerance or + quasi-Newton setting such as `gtol`; like any other argument they do not take, it reaches the + objective. +* `symmetryDetection()`, `symmetryReduction()` and `discreteSymmetries()` need symident 0.17.0. +* `trust()` takes the structured quasi-Newton Hessians `hessianMethod = "sbfgs"` and `"ssr1"` + (Dennis, Martínez and Tapia), the Gauss-Newton Hessian of the objective at every iterate plus a + correction learned by a BFGS or an SR1 update, and the hybrids `"gnsbfgs"` and `"gnssr1"` (Zhou and + Chen), which choose at every accepted step between the Gauss-Newton Hessian alone, or plus the + residual norm times the identity with `qnControl$qnHybridShift = TRUE`, and the structured + model. The structured secant is that of Dennis, Martínez and Tapia, `(J+ - J)'u+` + from the Jacobian `J` of the predictions and sigmas at the data and the derivatives `u` of the + value in them, generalized to the error models and censored data of `normL2()`; the other terms + of a sum, such as a prior, enter with the gradient and Hessian they return. Objectives asked for + `hessian = "structured"` return these data rows in an entry `structure` of the objlist, which + `+` stacks; an objective without them gets the secant of gradient and Gauss-Newton Hessian. + The BFGS update of `"sbfgs"` is undamped and restores the secant also where the Gauss-Newton + Hessian of the new iterate plus the correction is indefinite along the step. + `qnControl$qnScaling = "residual"` scales the correction with the residual norm `|u|` + (Huschens), `qnControl$qnHybridTol` sets the switch of the hybrids. The methods run + inside `phases` and through `mstrust()`; the result reports `hybridGN`, and `evalBySource` names + the four new sources. `trustL1()` refuses `hessianMethod`. +* `distributedComputing()` refuses a job whose name a job submitted from another working directory + still holds in the folder of a remote node, until that job is purged. +* `terminate()` of a `dMod2Job` on SSH nodes or the local machine sends SIGKILL to the tasks that + still run 5 seconds after SIGTERM. +* `trust()` and `trustL1()` end on a convergence stop that the Newton decrease held back where the + run then ends on the radius without an accepted step that changes the value by `ftol` or more, + with `converged = TRUE`. On an objective with noise above `mtol`, such as a FOCEI marginal, the + runs end on that convergence stop at the optimum. +* `trust()` and `trustL1()` end on `"stagnation"` with `converged = TRUE` only where the full Newton + step of the model predicts a decrease of at most `mtol`, or where a convergence stop was held + back since the last step that changed the value by `ftol` or more. +* `constraintStability()` takes `width`, the least width of the ramp in the units of the rates, + default `0`, and `margin`, the least width relative to the largest eigenvalue modulus, default + `1e-6`, which replaces the control `stabilityMargin` of `Pimpl()`. A wide ramp shows the + boundary to the model of a trust-region step before the step crosses it. +* The gradient of `constraintStability()` is exact on a defective double eigenvalue, such as that of + a chain of states with equal rates: eigenvalues that coincide within the precision of the + eigenvalues take the mean of their derivatives, the trace of the spectral projector times the + derivative of the Jacobian. The eigenvalues of a Jacobian with large entries are matched within a + precision relative to the norm of the Jacobian. +* With spike-and-slab or Dirichlet-process random effects the marginal is the value at the exact + modes to first order: the value depends on the modes at first order, and the gradient the inner + search leaves at them is removed by one Newton step on the exact inner Hessian. Value and + gradient do not depend on the outer tolerances. +* The modes of spike-and-slab and Dirichlet-process random effects are found by the C++ group + kernel of FOCEI, all groups in one batched prediction per step, and end where the Gauss-Newton + step is below `1e-8`; `control$sparseFit$trustControl` sets the outer search only. +* `em(method = "saem")` and `msem(method = "saem")` fit spike-and-slab random effects, also beside + normal and Dirichlet-process ones: per-indicator birth and death moves from the local Gaussian + model of the data, the other slab values of the group following along the regression of that + model, and a joint random walk on the slab values; `prob` and `tau` follow in closed form, an + estimated `tau` starts at least at the largest group mode under the slab alone. + `control$saem$nFlip` sets the indicator sweeps per iteration; the acceptance rates of births, + deaths and random-walk steps are columns of `stageTrace`. -2 log L is that of `method = "focei"` + at the estimate, with the inclusion probabilities from the late draws. With many spike-and-slab + effects per group the chain can settle with every effect in the slab and `prob` near 1. +* `logLik(fit, method = "importance")` estimates the marginal log-likelihood of a fit with + spike-and-slab random effects at the estimates by importance sampling on the model, with standard + error and effective sample size per group. +* `em(method = "quadrature")` returns the best iterate of the outer loop, not the last. +* `control$quadrature$maxNodes` (default 1000): a level with more nodes per group is never + evaluated. There the level error is estimated by the change from the level below, and a group + above `tol / G` is capped. +* `converged` of a quadrature fit means stationary at the levels reached: the Newton decrement is + below `tolDecrement` (`stopReason` `"decrement"`), or -2 log L rose after a step on unchanged + levels (`"resolution"`). A small decrement relative to the summed level error does not end the + fit. Capped groups are listed in column `capped` of `stageTrace` and `certificate`, and in + attribute `"levels"` of `stageTrace`. +* `plotRandomEffects()` draws spike-and-slab random effects: `type = "inclusion"` gives a heatmap of + the probability of a deviation per group and effect; `"conditional"` and `"modes"` show draws from + the conditional mixture against the prior spike and slab. +* `plotTrace()` draws the hyperparameters of sparse random effects recorded in the trace. +* `plotPars()` takes an `em` fit or a list of them: estimates with Wald intervals, fits side by side. +* `residuals(type = "NPDE")` and `plotResiduals()` work for fits with sparse random effects only. +* Objective functions take `hessian = "expected"`: `normL2()` then returns the expected (Fisher) + information of the likelihood in place of the Gauss-Newton Hessian, `2 / sigma^2` in the + prediction and `4 / sigma^2` in sigma per data point (Student-t: `2 (nu + 1)` and `4 nu` over + `(nu + 3) sigma^2`), positive semidefinite also where an error model depends on the parameters. + `$information` of spike-and-slab fits takes it for the terms without random effects. +* The documentation of `em()` describes `$information` of spike-and-slab fits as an empirical + information, positive semidefinite, not a Hessian. +* `steadyStates()` follows the procedure of Rosenblatt et al. (2016): the cycles of the graph of + states are cut first, at a state of a conserved quantity or at a state whose balance is solved for + a rate constant of one flux side, and the remaining states and rate constants are solved from + balances in amounts. A quantity conserved across compartments is recognized, and networks whose + cycles defeated the greedy choice of unknowns are solved. Where no cycle forces a cut, the result + solves for states rather than rate constants and can differ in form from earlier versions. +* `steadyStates()` solves a state from the balance of that state before cutting cycles, where the + solution is a ratio of positive sums and every cycle keeps a cut; the states of conserved + quantities are left to the cuts. +* `steadyStates()` cuts a flux side whose terms have separate rate constants when no other cut gives + a solution: the fluxes of the side keep free ratios `r__`, new parameters of the + transformation, and one rate constant of the side is solved. +* `em(method = "saem")` with spike-and-slab random effects draws each indicator with the slab value + integrated out (Gauss-Hermite on the local model, exact model at the nodes, independence + Metropolis-Hastings) and takes `prob` and `tau` from Rao-Blackwellized statistics; the chain no + longer settles with every effect in the slab and `prob` near 1. `p0` is the mean conditional + spike probability of the late sweeps. New `control$saem$nodes`. +* `em(method = "saem")` with Dirichlet-process random effects beside spike-and-slab ones takes any + number of groups: -2 log L by sequential importance sampling over the partitions with `valueSE` + beyond 14 groups, or with `control$saem$integral = "importance"`. +* An `em` fit as `init` of `em(method = "saem")` with sparse random effects starts the chain at the + selected effects of that fit. +* `em(method = "saem")` with sparse random effects reports `innerModes`, the modes of the + approximate marginal at the estimates, and `logLik(method = "importance")` starts from them, or + from `etaModes` in a fit without them. +* A BFGS phase of `trust()` seeded from an indefinite Hessian (`hessianInit = "gn"` or `"exact"`, or + a handover from Gauss-Newton) starts from the absolute values of the Hessian eigenvalues. +* `c()` of a parvec names an unnamed operand by the argument name, `c(p, z = 1)`. +* `plotValues(pseudoLog = TRUE)` labels every tick as a power of ten where all are, and every tick + as a plain number otherwise. +* `discreteSymmetries()` handles models with several conditions and events. +* `symmetryDetection(mode = "global")` reads a reduction with one trafo per condition, keeps the + parameter names in the section and the state maps of a discrete symmetry, and prints the + coordinates the section pins. + # dMod2 0.15.10 * `constraintStability(pSS, p, weight)` penalizes instability only. With `s` the largest eigenvalue @@ -37,7 +200,7 @@ `discreteSymmetries()`. A model the global analysis does not handle gets the reason in `info$discrete$unsupported`. Needs symident 0.15.0. * `symmetryReduction()` limits the section search of each block to `timeout = 600` seconds by - default (`Inf` lets it run to its end), and `allowOpen` and `allowChecked` default to `TRUE`: an + default (`Inf` lets the search run to the end), and `allowOpen` and `allowChecked` default to `TRUE`: an open or checked direction gives a warning, as in symident 0.15.0. * `symmetryReduction(branch = )` takes the chart of one side of the fixed set of a discrete symmetry as the trafo; without it the branch charts are in `$alternatives`. Needs symident 0.15.0. diff --git a/R/EM.R b/R/EM.R index 30618e4c..ef78e70b 100644 --- a/R/EM.R +++ b/R/EM.R @@ -23,14 +23,14 @@ #' \describe{ #' \item{`"focei"`}{Laplace approximation at the conditional modes with the #' exact derivative of the volume term. The default, and the method for -#' spike-and-slab and Dirichlet-process random effects (at most 14 -#' groups) and for several groupings.} +#' 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.} #' \item{`"laplaceEM"`}{ECM on the Laplace approximation with the #' covariance-corrected update of `Omega`.} -#' \item{`"saem"`}{stochastic-approximation EM, also for Dirichlet-process -#' random effects; section SAEM.} +#' \item{`"saem"`}{stochastic-approximation EM, also for spike-and-slab and +#' Dirichlet-process random effects; section SAEM.} #' } #' #' @param obj Objective of the data, [normL2()] or [normT()] of the model @@ -57,10 +57,30 @@ #' \describe{ #' \item{`sd`}{start of the standard deviations of the random effects, #' default 0.3.} -#' \item{`innerControl`}{the trust region of the modes; it stops where the -#' Newton step is below `steptol`, default 1e-8.} +#' \item{`inner`}{`"nested"` (default) solves the modes at every +#' evaluation of the outer search; `"sqp"` takes `sqpIterlim` iterations of +#' the inner search from the modes predicted along d eta / d theta, with +#' value and gradient corrected to first order for the eta gradient left +#' over, until the outer search stops, and then goes on nested from there, +#' so that the estimates are those of the nested search. Applies to FOCEI +#' and to spike-and-slab and Dirichlet-process random effects.} +#' \item{`innerControl`}{the trust region of the modes: `rinit` and `rmax`, +#' the initial and largest radius (default 1 and 10); `iterlim`, default +#' 30 and over several groupings 100; `steptol`, default 1e-8, the Newton +#' step at which it stops; `mtol`, default 1e-12, the predicted change of +#' -2 log L, relative to -2 log L, at which a step on the boundary of the +#' region stops it; `eigenFloorRelative`, default 1e-10, the floor of the +#' eigenvalues of the inner Hessian relative to their mean (one grouping); +#' `sqpIterlim`, default 2, the inner iterations per evaluation with +#' `inner = "sqp"`. With spike-and-slab and Dirichlet-process random +#' effects only `sqpIterlim` applies. Other entries are an error.} #' \item{`trustControl`}{the outer trust region; it stops where the -#' predicted change of -2 log L is below `mtol`, default 1e-5.} +#' predicted change of -2 log L is below `mtol`, default 1e-5. Takes +#' `ftol`, `mtol`, `gtol` and `xtol` flat or in `tolControl`. With random +#' effects over several groupings the outer search is [trust()], and +#' every argument of [trust()] passes, `hessianMethod`, `phases` and +#' `qnControl` included; FOCEI of one grouping reads `rinit`, `rmax`, +#' `iterlim`, `ftol` and `mtol`. Other entries are an error.} #' \item{`secondOrderCorrection`}{the derivative of the volume term, #' default `TRUE`.} #' \item{`derivMode`}{how FOCEI gets the second derivatives of the volume @@ -76,7 +96,7 @@ #' estimates; where -2 log L rises by at most `boundary`, that fit is #' returned and names the hyperparameter in `boundary`.} #' \item{`quadrature`, `saem`, `sparseFit`}{lists of the sections -#' Quadrature, SAEM and Sparse random effects.} +#' Quadrature, SAEM and Sparse random effects; other entries are an error.} #' } #' @param cores Number of cores over the groups and conditions inside the #' fit; with 1 (default) no threads are started. @@ -95,9 +115,20 @@ #' \item{`information`}{with spike-and-slab random effects the #' empirical information that gives the standard errors: `G / (G - 1)` #' times the sum of the outer products of the centered scores of the `G` -#' groups, plus half the Hessian of the conditions without random -#' effects.} -#' \item{`converged`, `iterations`}{} +#' groups, of rank at most `G - 1`, plus half the curvature of the terms +#' without random effects (conditions outside every group, priors) by +#' their expected information (`hessian = "expected"`, see [dModfn]), +#' positive semidefinite. It is not the Hessian of the marginal -2 log L +#' and is singular where the scores and those terms span fewer directions +#' than there are parameters. [vcov()][vcov.em] inverts it where it is +#' positive definite.} +#' \item{`converged`, `iterations`}{the convergence of the outer search +#' and the iterations; with several groupings also `phaseIterations` of +#' [trust()].} +#' \item{`innerIterations`, `sqpIterations`}{with FOCEI and sparse random +#' effects the iterations of the inner searches summed over the groups and +#' evaluations, and with `control$inner = "sqp"` the outer iterations on +#' inexact modes.} #' \item{`Omega`, `omega`}{the covariance of the normal random effects, #' their standard deviations and correlations with standard errors.} #' \item{`random`}{per group the modes with conditional standard errors; @@ -128,17 +159,27 @@ #' \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. -#' `Inf` keeps the -#' levels of the stages.} +#' Where the next level exceeds `maxNodes`, the change from the level below +#' is the estimate. `Inf` keeps the levels 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`}{highest level, default `K + 8`.} +#' \item{`maxLevel`, `maxNodes`}{highest level, default `K + 8`, and the +#' largest node count of a level per group, default 1000. 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 +#' and cap per group.} #' \item{`tolDecrement`}{a stage ends when a Newton step on the rebuilt -#' nodes would lower -2 log L by less than this, default 1e-4, or than the -#' nodes resolve.} +#' nodes would lower -2 log L by less than this, default 1e-4 +#' (`stopReason` `"decrement"`), or when -2 log L rose after a step on nodes +#' of unchanged levels, so the step lies below what the levels resolve +#' (`"resolution"`). `converged` means stationary at the levels reached, +#' capped ones included; the fit returns the iterate of lowest -2 log L on +#' the highest levels.} #' \item{`maxEcmPerStage`, `cm1Control`, `maxCm1Iter`}{rebuilds per stage -#' (default 10), [trust()] settings and iterations of a step (default 30).} +#' (default 10, `stopReason` `"iterlim"` where they run out), [trust()] +#' settings and iterations of a step (default 30).} #' \item{`pruneTol`}{nodes whose weight lies this much in log below the #' largest are dropped, default `Inf`.} #' \item{`certificate`}{`FALSE`, or a list of `points` (default 256) and @@ -159,23 +200,55 @@ #' \item{`nBurnin`, `nEM`}{at most that many burn-in and averaging #' iterations, default 200 and 300.} #' \item{`nMcmc`, `nLaplace`}{random-walk and independence steps per -#' iteration, default 3 each.} +#' iteration, default 3 each; `nLaplace` with normal random effects alone.} #' \item{`laplaceEvery`, `laplaceScale`}{iterations between refreshes of the -#' modes, default 5, and the factor of the proposal covariance, default -#' 1.5.} +#' modes, default 5, with normal random effects alone, and the factor of the +#' proposal covariance, default 1.5, also of the slab value of an indicator +#' move.} #' \item{`window`, `mcTol`}{the burn-in ends when no parameter has a #' significant slope over the last `window` iterations (default 25), the #' averaging when the expected rise of -2 log L from the Monte Carlo error #' is below `mcTol` (default 0.05).} -#' \item{`particles`}{with Dirichlet-process random effects the particles of -#' the sequential importance sampling of -2 log L, default 500.} +#' \item{`particles`}{the particles of the sequential importance sampling +#' of -2 log L with Dirichlet-process random effects, default 500.} #' \item{`cm1Control`}{[trust()] settings of the Newton steps of the other #' parameters, default one iteration per SAEM iteration.} +#' \item{`nFlip`}{with spike-and-slab random effects the sweeps over the +#' indicators per iteration, default 1.} +#' \item{`nodes`}{Gauss-Hermite nodes of the slab mass of an indicator, 3 +#' (default) or 5.} +#' \item{`integral`}{`"importance"` takes -2 log L by importance sampling +#' over the partitions also where Dirichlet-process random effects beside +#' spike-and-slab ones allow the exact sum.} #' } -#' With Dirichlet-process random effects a Gibbs sweep draws the clusters of -#' the groups (Neal 2000, algorithm 8), the averaging runs `nEM` iterations, -#' and the reported clusters are the most frequent partition of the late -#' draws. +#' With normal random effects alone, -2 log L at the estimate is the +#' quadrature of level `K + 2`, and `maxLevel`, `maxNodes` and `pruneTol` of +#' `control$quadrature` apply to it. +#' With spike-and-slab or Dirichlet-process random effects the averaging runs +#' `nEM` iterations. A sweep of Metropolis-Hastings moves visits every +#' indicator of a group once, in random order and for all groups at once, +#' with the slab value integrated out: the other slab values of the group +#' follow along the regression of the local quadratic model of the data, the +#' slab mass on that line is a Gauss-Hermite sum with the exact model at the +#' nodes, and the proposal draws the indicator from the resulting conditional +#' inclusion probability and the slab value from the local Gaussian; the +#' independence Metropolis-Hastings step keeps the posterior exact. `nMcmc` +#' random-walk steps move the slab values of every group jointly. `prob` and +#' `tau` follow in closed form from the averaged conditional inclusion +#' probabilities and slab second moments of the sweeps, not from the drawn +#' indicators; an estimated `tau` starts at least at the largest group mode +#' under the slab alone. An `em` fit as `init` starts the chain at the +#' selected random effects of that fit instead, the way to check a FOCEI +#' optimum by SAEM. The acceptance rates of births, deaths and random-walk +#' steps per iteration are columns of `stageTrace`. A Gibbs sweep draws +#' the clusters of the Dirichlet-process random effects (Neal 2000, +#' algorithm 8). The reported clusters are the most frequent partition of +#' the late draws, a spike-and-slab random effect is selected where the mean +#' conditional inclusion probability of the late sweeps is above 1/2, `p0` +#' one minus that mean. -2 log L is that of `method = "focei"` at the +#' estimate; with Dirichlet-process random effects alone, or beside +#' 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 @@ -185,8 +258,9 @@ #' trial point at which EC does not converge is a failed evaluation. Entries of `control$sparseFit`: #' \describe{ #' \item{`maxOuter`}{iterations of the trust region, default 200.} -#' \item{`trustControl`}{the [trust()] settings; `ftol`, `mtol` and `gtol` -#' of the `tolControl` there also end the search of the modes (else 1e-10).} +#' \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.} #' } #' #' @seealso [msem()], [randomEffects()], [insert()]; the guide chapters @@ -208,21 +282,34 @@ em <- function(obj, random, init = NULL, fixed = NULL, design <- .emDesign(obj, random) start <- .emStart(design, init, fixed, sd = control$sd %||% 0.3) control$modes <- cont$modes + control$selected <- cont$selected .withCores(cores, .emFit(design, start, fixed, method, control, verbose)) } -## Refuses entries of `control` and of `control$sparseFit` that em() does not read. +## Refuses entries of `control` and of the lists `sparseFit`, `quadrature`, `saem` and `innerControl` that +## em() does not read. .checkEmControl <- function(control) { - known <- list(control = c("sd", "innerControl", "trustControl", "secondOrderCorrection", "derivMode", "quadrature", - "saem", "sparseFit", "boundary"), - sparseFit = c("maxOuter", "trustControl")) + known <- list(control = c("sd", "inner", "innerControl", "trustControl", "secondOrderCorrection", "derivMode", + "quadrature", "saem", "sparseFit", "boundary"), + sparseFit = c("maxOuter", "trustControl"), + 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]] bad <- .setdiff(names(x), known[[k]]) if (length(bad)) - stop("em: unknown ", if (k == "control") "entries of `control`: " else "entries of `control$sparseFit`: ", + stop("em: unknown entries of `", if (k == "control") "control" else paste0("control$", k), "`: ", paste(bad, collapse = ", "), ".", call. = FALSE) } + inner <- control[["inner"]] + if (!is.null(inner) && !(length(inner) == 1L && inner %in% c("nested", "sqp"))) + stop("em: `control$inner` is \"nested\" or \"sqp\".", call. = FALSE) + sq <- control$innerControl$sqpIterlim + if (!is.null(sq) && !(is.numeric(sq) && length(sq) == 1L && is.finite(sq) && sq >= 1 && sq == round(sq))) + stop("em: `control$innerControl$sqpIterlim` is one whole number of at least 1.", call. = FALSE) dm <- control$derivMode if (!is.null(dm) && !(length(dm) == 1L && dm %in% c("forward-reverse", "forward-forward"))) stop("em: `control$derivMode` is \"forward-reverse\" or \"forward-forward\".", call. = FALSE) @@ -298,6 +385,7 @@ msem <- function(obj, random, init = NULL, fixed = NULL, design <- .emDesign(obj, random) center <- .emStart(design, init, fixed, sd = control$sd %||% 0.3) control$modes <- cont$modes + control$selected <- cont$selected sd <- .perturbSd(sd, center) # every start and every seed is drawn here, so set.seed() reproduces a run whatever `cores`; # an inner axis above 1 runs the fits in PSOCK workers, as mstrust() @@ -405,7 +493,7 @@ msem <- function(obj, random, init = NULL, fixed = NULL, } fixed <- c(fixed, init$fixed[.setdiff(names(init$fixed), names(fixed))]) list(random = random, init = init$argument[.setdiff(names(init$argument), names(fixed))], fixed = fixed, - modes = init$innerModes) + modes = init$innerModes, selected = init$etaModes) } ## One fit of `design` from `start` by `method`, with `control`; -2 log L of the data at the @@ -479,11 +567,11 @@ 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))) { - if (method == "saem") return(.emResult(design, .fitSaemDirichlet(design, start, fixed, control, verbose), + if (method == "saem") return(.emResult(design, .fitSaemSparse(design, start, fixed, control, verbose), method, fixed)) if (method != "focei") stop("em: spike-and-slab and Dirichlet-process random effects are fitted by method = \"focei\" ", - "(Dirichlet-process ones also by \"saem\").", call. = FALSE) + "or \"saem\".", call. = FALSE) return(.emResult(design, .fitSparse(design, start, fixed, control, verbose), method, fixed)) } joint <- design$objfn + .normalPrior(design) @@ -505,6 +593,8 @@ msem <- function(obj, random, init = NULL, fixed = NULL, ## trust() for an inner step of an EM loop, whose iteration limit is part of the loop: that one ## warning is muffled, others pass. -.innerTrust <- function(args) +.innerTrust <- function(args) { + if (is.null(args$phases) && is.null(args$hessianMethod)) args$hessianMethod <- "gn" withCallingHandlers(suppressMessages(do.call(trust, args)), warning = function(w) if (grepl("Maximum number of iterations", conditionMessage(w), fixed = TRUE)) invokeRestart("muffleWarning")) +} diff --git a/R/PEtabInterface.R b/R/PEtabInterface.R index 2b60bf3e..77ed6d76 100644 --- a/R/PEtabInterface.R +++ b/R/PEtabInterface.R @@ -586,10 +586,9 @@ readPEtabTables <- function(yamlPath) { .petab_ss_time <- 1e10 -# Internal: one record list(id, dist, pars, lower, upper, scale, ...) per prior, or -# NULL; v2 `priorDistribution` columns win over v1's. A `parameterScale*` prior -# is on the optimized parameter; a plain one is on the linear parameter, and -# `scale` is the scale of the optimized parameter it is evaluated through. +# One record list(id, dist, pars, lower, upper, scale, ...) per prior, or NULL; v2 `priorDistribution` +# columns win over v1's. A `parameterScale*` prior is on the optimized parameter, a plain one on the +# linear parameter, evaluated through `scale`, the scale of the optimized parameter. .petab_parse_priors <- function(df, scales) { pick <- function(a, b) @@ -721,12 +720,9 @@ readPEtabTables <- function(yamlPath) { } -# Internal: the prior term of a PEtab objective on the -2 log scale, reported in -# `attr(, "prior")`. A prior on the optimized parameter of a family with a dMod -# constructor goes through it; the others and the truncation constant, which -# leaves gradient and Hessian alone, are here. A prior on the linear parameter of -# a log or log10 parameter is the prior density at the back-transformed value, without -# a Jacobian term, as in other PEtab tools. +# The prior term of a PEtab objective on the -2 log scale, in `attr(, "prior")`: a family with a dMod +# constructor through it, the others and the truncation constant here. A prior on the linear value of a +# log or log10 parameter is the density at the back-transformed value without a Jacobian, as in PEtab tools. .petab_prior_objective <- function(specs) { one <- function(sp) { diff --git a/R/RcppExports.R b/R/RcppExports.R index 0b01d86e..4c37a629 100644 --- a/R/RcppExports.R +++ b/R/RcppExports.R @@ -29,8 +29,8 @@ chain_params <- function(plan, values, deriv, deriv2, threads, tangents) { .Call(`_dMod2_chain_params`, plan, values, deriv, deriv2, threads, tangents) } -chain_data <- function(plan, pre, raw, deriv, deriv2, build_hessian, local, threads, bloq_mode, t_df, want_seed, sparse = FALSE) { - .Call(`_dMod2_chain_data`, plan, pre, raw, deriv, deriv2, build_hessian, local, threads, bloq_mode, t_df, want_seed, sparse) +chain_data <- function(plan, pre, raw, deriv, deriv2, build_hessian, local, threads, bloq_mode, t_df, want_seed, sparse = FALSE, want_rows = FALSE) { + .Call(`_dMod2_chain_data`, plan, pre, raw, deriv, deriv2, build_hessian, local, threads, bloq_mode, t_df, want_seed, sparse, want_rows) } chain_frames <- function(plan, pre, raw, deriv2, threads) { @@ -61,24 +61,24 @@ datapointL2_kernel <- function(pouter, fixed_opt, prdf, dpred_attr_opt, d2pred_a .Call(`_dMod2_datapointL2_kernel`, pouter, fixed_opt, prdf, dpred_attr_opt, d2pred_attr_opt, obs_name, t, sigma, value_par, deriv, build_hessian) } -focei_inner_trust <- function(model_cb, err_cb, pars_full, eta_warmstart, subject_meta, Omega_inv_mat, Omega_log_det, fixed, control, predict_cb = NULL) { - .Call(`_dMod2_focei_inner_trust`, model_cb, err_cb, pars_full, eta_warmstart, subject_meta, Omega_inv_mat, Omega_log_det, fixed, control, predict_cb) +focei_run <- function(model_cb, err_cb, joint_cb, init, subject_meta, fixed, control, correction_mode = "none", correction_cb = NULL, predict_cb = NULL, eta_init = NULL) { + .Call(`_dMod2_focei_run`, model_cb, err_cb, joint_cb, init, subject_meta, fixed, control, correction_mode, correction_cb, predict_cb, eta_init) } -focei_run <- function(model_cb, err_cb, joint_cb, init, subject_meta, fixed, control, correction_mode = "none", correction_cb = NULL, predict_cb = NULL) { - .Call(`_dMod2_focei_run`, model_cb, err_cb, joint_cb, init, subject_meta, fixed, control, correction_mode, correction_cb, predict_cb) -} - -focei_run_sparse <- function(trial, complete, init, N, K, outer_ctrl, inner_rinit) { - .Call(`_dMod2_focei_run_sparse`, trial, complete, init, N, K, outer_ctrl, inner_rinit) +focei_run_sparse <- function(trial, complete, init, N, K, outer_ctrl, inner_rinit, eta_init = NULL) { + .Call(`_dMod2_focei_run_sparse`, trial, complete, init, N, K, outer_ctrl, inner_rinit, eta_init) } release_heap <- function() { invisible(.Call(`_dMod2_release_heap`)) } -normL2_kernel <- function(prediction, err_list_opt, meta_list, par_names_global, deriv2_requested, threads, bloq_mode = "M3", build_hessian = TRUE, want_seed = FALSE, local_blocks = FALSE, t_df = 0) { - .Call(`_dMod2_normL2_kernel`, prediction, err_list_opt, meta_list, par_names_global, deriv2_requested, threads, bloq_mode, build_hessian, want_seed, local_blocks, t_df) +nlme_group_kernel <- function(model_cb, err_cb, pars_full, eta_warmstart, subject_meta, Omega_inv_mat, Omega_log_det, fixed, control, predict_cb = NULL) { + .Call(`_dMod2_nlme_group_kernel`, model_cb, err_cb, pars_full, eta_warmstart, subject_meta, Omega_inv_mat, Omega_log_det, fixed, control, predict_cb) +} + +normL2_kernel <- function(prediction, err_list_opt, meta_list, par_names_global, deriv2_requested, threads, bloq_mode = "M3", build_hessian = TRUE, want_seed = FALSE, local_blocks = FALSE, t_df = 0, expected = FALSE, want_rows = FALSE) { + .Call(`_dMod2_normL2_kernel`, prediction, err_list_opt, meta_list, par_names_global, deriv2_requested, threads, bloq_mode, build_hessian, want_seed, local_blocks, t_df, expected, want_rows) } parvec_attach <- function(out, deriv, deriv2) { @@ -137,8 +137,8 @@ trustL1_impl <- function(objfun, parinit, mu, lambda, one_sided, rinit, rmax, pa .Call(`_dMod2_trustL1_impl`, objfun, parinit, mu, lambda, one_sided, rinit, rmax, parscale, iterlim, ftol, mtol, gtol, xtol, rmin, thetamax, boundary, minimize, blather, parupper, parlower, printIter, traceFile, gate, fuse) } -trust_impl <- function(objfun, parinit, rinit, rmax, parscale, iterlim, ftol, mtol, gtol, xtol, rmin, thetamax, boundary, phaseMethod, phaseIterlim, phaseReverse, phaseInit, phaseReseed, phaseMemory, phaseCautious, phaseRejected, switches = 0L, nonmonotone = 0.0, sparse = FALSE, minimize = TRUE, blather = FALSE, parupper = NULL, parlower = NULL, printIter = FALSE, traceFile = NULL) { - .Call(`_dMod2_trust_impl`, objfun, parinit, rinit, rmax, parscale, iterlim, ftol, mtol, gtol, xtol, rmin, thetamax, boundary, phaseMethod, phaseIterlim, phaseReverse, phaseInit, phaseReseed, phaseMemory, phaseCautious, phaseRejected, switches, nonmonotone, sparse, minimize, blather, parupper, parlower, printIter, traceFile) +trust_impl <- function(objfun, parinit, rinit, rmax, parscale, iterlim, ftol, mtol, gtol, xtol, rmin, thetamax, boundary, phaseMethod, phaseIterlim, phaseRadiusStall, phaseReverse, phaseKeepRadius, phaseStopEnds, phaseInit, phaseReseed, phaseMemory, phaseCautious, phaseRejected, phaseScaled, phaseHybridTol, phaseHybridShift, switches = 0L, nonmonotone = 0.0, sparse = FALSE, minimize = TRUE, blather = FALSE, parupper = NULL, parlower = NULL, printIter = FALSE, traceFile = NULL) { + .Call(`_dMod2_trust_impl`, objfun, parinit, rinit, rmax, parscale, iterlim, ftol, mtol, gtol, xtol, rmin, thetamax, boundary, phaseMethod, phaseIterlim, phaseRadiusStall, phaseReverse, phaseKeepRadius, phaseStopEnds, phaseInit, phaseReseed, phaseMemory, phaseCautious, phaseRejected, phaseScaled, phaseHybridTol, phaseHybridShift, switches, nonmonotone, sparse, minimize, blather, parupper, parlower, printIter, traceFile) } sparse_factor_cost <- function(p, i, n) { diff --git a/R/alignment.R b/R/alignment.R index 204c7f0a..973c2eca 100644 --- a/R/alignment.R +++ b/R/alignment.R @@ -397,11 +397,9 @@ print.alignmentmodel <- function(x, ...) { local } -## Outputs (prediction, sigma) of the readings `rows` with first and second derivatives in the -## parameters the rows depend on: the compiled derivatives in the predictors times their -## coefficients, per pair of symbols over the parameters of their predictors only. `local` is -## the description of the rows by .alignmentLocal(); the values alone come from the sparse -## coefficients without it. +## Prediction and sigma of the readings `rows` with first and second derivatives in the parameters they +## depend on, from the compiled derivatives in the predictors times their coefficients; `local` describes the +## rows (.alignmentLocal()), without it the values alone come from the sparse coefficients. .alignmentEval <- function(m, rows, pars, deriv = TRUE, deriv2 = FALSE, local = NULL) { sym <- m$symbols$symbol n <- length(rows) @@ -594,10 +592,9 @@ print.alignmentmodel <- function(x, ...) { ## ---- objective -------------------------------------------------------------------- -## Prediction and error model of the readings of one condition. The model sits in `shared`, an -## environment common to all conditions, which serialize() writes once. One evaluation gives -## both outputs: the prediction frame holds the frame of the error model, which the error model -## returns when it is asked at the same parameters, split the same way, for no higher derivatives. +## Prediction and error model of the readings of one condition, the model in `shared`, an environment of all +## conditions that serialize() writes once. The prediction frame holds the error-model frame, which the error +## model returns when asked at the same parameters, split the same way, for no higher derivatives. .alignmentOutputs <- function(shared, rows, condition, times, pars, fixed, deriv, deriv2) { m <- shared$m local <- shared$local[[condition]] @@ -899,10 +896,9 @@ print.alignmentmodel <- function(x, ...) { }) } -## The vjps of output `o` (1 prediction, 2 sigma) of many conditions, per condition [free x K]: -## one evaluation at all their rows where the times of every condition are the condition rows, shared by the -## two outputs of a sweep as in .alignmentVjp(), else one by one. With `seeds` every column is a -## first-order seed. +## The vjps of output `o` (1 prediction, 2 sigma) of many conditions, [free x K] each: one evaluation at all +## rows where the times of a condition are the condition rows, shared by both outputs as in .alignmentVjp(), else one by +## one. With `seeds` every column is a first-order seed. .alignmentVjpMany <- function(shared, times, parsList, fixedList, cotangentList, o, cores, seeds = FALSE, conditions = NULL) { conds <- .alignmentRowConditions(shared, times, conditions) @@ -965,12 +961,9 @@ print.alignmentmodel <- function(x, ...) { out } -## The condition of every reading: the experiment of the reading, the combination of the columns of the fixed -## parts of the scaling formulas, within the connected component of the reading of the groups of the random -## terms, in parts of few biological values, so the Hessian is sparse over them and every condition -## depends on few parameters. -## The name joins the parts that are set and not repeated, "absolute" for a reading without -## any, where these names tell the conditions apart. +## The condition of every reading: the experiment, the columns of the fixed parts of the scaling formulas and +## the component of the random-term groups, cut so that each condition depends on few parameters. The name +## joins the parts set and not repeated, "absolute" for a reading without any. .alignmentConditions <- function(m) { scaling <- m$symbols$symbol[m$symbols$role == "scaling"] cols <- unique(unlist(lapply(scaling, function(s) m$design[[s]]$columns))) @@ -1210,7 +1203,7 @@ align <- function(model, fits = 10L, cores = 1L, method = c("focei", "quadrature stop("align: no start value for ", paste(names(st)[is.na(st)], collapse = ", "), ", whose symbols never reach the readings on their scale; give `init`.", call. = FALSE) if (!is.null(re)) { - ctrl <- list(sd = 1, trustControl = c(list(iterlim = iterlim), tc), innerControl = tc[c("ftol", "mtol")], + ctrl <- list(sd = 1, trustControl = c(list(iterlim = iterlim), tc), innerControl = tc["mtol"], quadrature = list(cm1Control = list(tolControl = tc)), sparseFit = list(maxOuter = iterlim, trustControl = list(tolControl = tc))) best <- if (fits > 1L) msem(obj, re, st, method = method, control = ctrl, fits = fits, cores = cores, sd = sd) @@ -1500,10 +1493,9 @@ align <- function(model, fits = 10L, cores = 1L, method = c("focei", "quadrature } -## Start values: biological intercepts where the symbol is the median reading, or the median -## positive one where the scale of the symbol does not reach that, the other intercepts where their symbol -## is 1, the rest 0. The coefficients of the first scaling symbol then start where the predictor -## is per experiment the median of the predictors that meet the relative readings. +## Start values: biological intercepts at the median reading (the median positive one where the scale cannot +## reach it), other intercepts where their symbol is 1, the rest 0; the coefficients of the first scaling +## symbol where the predictor per experiment is the median of those meeting the relative readings. .alignmentStart <- function(m, free) { y <- m$y[is.finite(m$y)] st <- setNames(numeric(length(free)), free) @@ -1623,7 +1615,7 @@ plotAligned <- function(x, ...) { ggplot2::geom_errorbar(ggplot2::aes(ymin = .data$value - .data$sigma, ymax = .data$value + .data$sigma), width = 0) + ggplot2::labs(x = xv, y = "aligned value", color = NULL) + - scale_color_dMod(guide = if (length(grp)) "legend" else "none") + theme_dMod() + scale_color_dMod2(guide = if (length(grp)) "legend" else "none") + theme_dMod2() } #' @rdname plotValues @@ -1646,9 +1638,9 @@ plotScaled <- function(x, ...) { } ggplot2::ggplot(s, ggplot2::aes(x = .data[[xv]], y = .data$scaled)) + ggplot2::geom_point(alpha = 0.6) + - ggplot2::geom_point(data = bio, ggplot2::aes(x = .data[[xv]], y = .data$value), color = dMod_colors[2]) + + ggplot2::geom_point(data = bio, ggplot2::aes(x = .data[[xv]], y = .data$value), color = dMod2_colors[2]) + ggplot2::labs(x = xv, y = "reading on the scale of the values") + - theme_dMod() + theme_dMod2() } #' @rdname plotAligned @@ -1659,14 +1651,13 @@ plotResiduals.alignment <- function(parframe, ...) { ggplot2::ggplot(s, ggplot2::aes(x = .data$prediction, y = .data$residual)) + ggplot2::geom_point() + ggplot2::geom_hline(yintercept = 0, linetype = 2) + ggplot2::labs(x = "prediction", y = "standardized residual") + - theme_dMod() + theme_dMod2() } -## The variances x' V x of linear combinations of the estimates, the rows x of a matrix with -## parameter columns, V the inverse of half the Hessian of -2 log L, the sparse H plus the low-rank -## part `lowrank`: by a sparse Cholesky solve and Woodbury for a sparse Hessian, else by -## eigendecomposition. Inf along the null space of a singular one. +## The variances x' V x of the rows x of a matrix over the parameters, V the inverse of half the Hessian of +## -2 log L plus `lowrank`: sparse Cholesky and Woodbury for a sparse Hessian, else the eigendecomposition; +## Inf along the null space of a singular one. .alignmentVariance <- function(H, free, lowrank = NULL) { if (is.null(H) || !length(free)) return(NULL) H <- H[free, free, drop = FALSE] / 2 diff --git a/R/chain.R b/R/chain.R index daabe6e0..299bb5b3 100644 --- a/R/chain.R +++ b/R/chain.R @@ -1,8 +1,6 @@ ## ---- Native chain --------------------------------------------------------------------------- -## normL2(data, g * x * p, errmodel = e) evaluated per condition in C++: the transformations by -## their own compiled functions, the batch solve of the model, the observables, the error model -## and the data term (src/chain_kernel.cpp). A plan per signature holds the indices; whatever it -## does not cover takes the R path, as does everything under options(dMod2.evaluation = "R"). +## normL2(data, g * x * p, errmodel = e) per condition in C++ (src/chain_kernel.cpp), a plan per signature +## holding the indices; what it does not cover, and all under options(dMod2.evaluation = "R"), takes the R path. ## Whether objectives, FOCEI and the quadrature evaluate in C++: getOption("dMod2.evaluation"), ## "C++" (the default) or "R". @@ -13,11 +11,9 @@ identical(ev, "C++") } -## A stage of the transformation for the parfn kernel `k` on the names `prev` before it: -## list(kind, fn, vjp, inNames, fnout, through, guessNames, state, order), a compiled function -## (kind 0) or a steady state (kind 1) whose native `state` solves the roots, with derivatives of -## order `order`. With `vjp` the vector-Jacobian product of the sweeps (`"_vjp_ad"`) or of the -## adjoint (`"_vjp"`). NULL where the kernel cannot take part. +## A stage for the parfn kernel `k` on the names `prev` before it: a compiled function (kind 0) or a steady +## state (kind 1) with derivatives of order `order`, and with `vjp` the vector-Jacobian product of the sweeps +## (`"_vjp_ad"`) or of the adjoint (`"_vjp"`). NULL where the kernel cannot take part. .chainStage <- function(k, prev, cond, deriv2, order, vjp = NULL) { addr <- function(name) tryCatch(getNativeSymbolInfo(name)$address, error = function(e) NULL) if (isTRUE(attr(k, "pexpl", exact = TRUE))) { @@ -43,10 +39,9 @@ order = as.integer(order)) } -## The stages of the parfn kernels `kernels`, in the order they apply, from the outer names -## `outer`: their indices into the vector before each, with the passed entries reduced to what a -## later stage or the names `needed` read; `o` the outer names the first one reads, `final` the -## names after the last. NULL where a kernel cannot take part. +## The stages of `kernels` in the order they apply from the outer names `outer`, passing only what a later +## stage or `needed` reads; `o` the outer names the first reads, `final` the names after the last. NULL where +## a kernel cannot take part. .chainStages <- function(kernels, outer, needed, cond, deriv2, order, vjp = NULL) { st <- vector("list", length(kernels)) prev <- outer @@ -72,14 +67,9 @@ list(stages = st, o = o, final = prev) } -## The plan for the objective of `spec` (an entry of attr(obj, "l2spec")) on `conds`: per -## condition the free outer names `free[[i]]`, the fixed ones `fixedNames` behind them, and the -## positions of the condition directions among `global`. With `times`, a list per condition, the plan of the -## prediction and error model on these times, without the data. With `tangents` the plan of the -## sweeps of forward over reverse instead: the solve on `times` along that many tangents of the -## free names, the data rows, and the backward solve with `seeds` seeds. With `adjoint` the plan of -## the adjoint gradient: values forward keeping the checkpoints, the backward solve of first order -## and the raw `_vjp` entries. NULL where a piece cannot take part. +## The plan of the objective `spec` (of attr(obj, "l2spec")) on `conds` with free names `free[[i]]`, then +## `fixedNames`; with `times` the prediction and error model on them, with `tangents` the sweeps of forward over +## reverse, with `adjoint` the adjoint gradient. NULL where a piece cannot take part. .chainPlan <- function(spec, conds, free, fixedNames, global, deriv, deriv2 = FALSE, times = NULL, tangents = 0L, seeds = 0L, adjoint = FALSE) { prd <- spec$prdfn @@ -245,21 +235,21 @@ } ## The data term of `plan` at `values`, the outer values per condition or one vector for all, in -## the order of the plan, with `sparse` the Hessian as the slots of chain_data(); NULL where the -## chain fails, for the R path to report it. -.chainEval <- function(plan, values, deriv, deriv2, hessian, local, cores, bloq, df, sparse = FALSE) { +## the order of the plan, with `sparse` the Hessian as the slots of chain_data() and with `rows` the +## data rows; NULL where the chain fails, for the R path to report it. +.chainEval <- function(plan, values, deriv, deriv2, hessian, local, cores, bloq, df, sparse = FALSE, + rows = FALSE) { pre <- .chainParams(plan, values, deriv, deriv2, cores) raw <- if (!is.null(pre)) .chainSolveRun(plan, pre$args, cores) if (is.null(raw)) return(NULL) chain_data(plan, pre, raw, deriv, deriv2, hessian, local, as.integer(cores), bloq, if (is.finite(df)) df else 0, - FALSE, sparse) + FALSE, sparse, rows) } -## The data term of `ctx` per request in C++: request j on condition `conds[j]`, which may repeat, -## at the free values `parsList[[j]]` and fixed values `fixedList[[j]]` (NULL for none, the same -## names in every request), with value, chi2 and, with `deriv`, gradient and Hessian in the names of -## the free values; NULL where the chain does not cover the model or fails, for the R path. +## The data term of `ctx` in C++ per request j on condition `conds[j]` at `parsList[[j]]`, fixed values +## `fixedList[[j]]`: value, chi2 and with `deriv` gradient and Hessian in the free names; NULL where the chain +## does not cover the model or fails. .chainLocal <- function(ctx, conds, parsList, fixedList, deriv, deriv2, cores, bloq, df) { if (is.null(ctx) || !.evalCpp() || !length(conds)) return(NULL) fixedList <- fixedList %||% rep(list(NULL), length(conds)) diff --git a/R/classes.R b/R/classes.R index 0913b7f9..cc3d80f4 100644 --- a/R/classes.R +++ b/R/classes.R @@ -963,10 +963,8 @@ match.fnargs <- function(arglist, choices) { else hessian, conditions = conds, env = e, cores = cores) } - # A term without conditions is evaluated once with the caller's env, any - # other on the term share of `conditions` and skipped when that is empty, - # unless it holds an unconditioned term. The second term reuses the env - # the first returned. + # 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) @@ -1046,6 +1044,10 @@ match.fnargs <- function(arglist, choices) { # An absent gradient or Hessian stays absent. out <- lapply(unclass(x2), function(x) if (is.null(x) || is.list(x)) x else x1 * x) if (!is.null(x2$lowrank)) out$lowrank$d <- x1 * x2$lowrank$d + if (!is.null(x2$structure)) { + out$structure$seeds <- x1 * x2$structure$seeds + out$structure$hessian <- x1 * x2$structure$hessian + } numericAttrs <- names(Filter(is.numeric, attributes(x2))) attributes(out) <- attributes(x2) for (n in numericAttrs) attr(out, n) <- x1 * attr(x2, n) diff --git a/R/constraintStability.R b/R/constraintStability.R index 0e2dd634..44a13234 100644 --- a/R/constraintStability.R +++ b/R/constraintStability.R @@ -7,15 +7,17 @@ #' \eqn{\sqrt{w}\, r^{3/2}} for \eqn{r \le 1} and #' \eqn{\sqrt{w}\, (1 + 3 (r - 1) / 2)} beyond, with #' \eqn{r = \max(0, \mathrm{Re}\,\lambda - \lambda_0) / (\lambda_{tol} - \lambda_0)}. -#' With \eqn{s} the largest eigenvalue modulus there, \eqn{\lambda_{tol}} the -#' `stabilityTol` and \eqn{m} the `stabilityMargin` of the `controlsPTC` of -#' `pSS`, the ramp begins at \eqn{\lambda_0 = \lambda_{tol} - m s}. The term is -#' zero on a steady state whose leading real part lies more than \eqn{m s} -#' below \eqn{\lambda_{tol}}, reaches the weight \eqn{w} for each eigenvalue, both of -#' a complex pair, whose real part reaches \eqn{\lambda_{tol}}, and grows -#' quadratically beyond. Value, gradient and Gauss-Newton Hessian are -#' continuous. Steady states that agree in the parameters, resting states and -#' start values they read count once. The gradient is exact. +#' With \eqn{\lambda_{tol}} the `stabilityTol` of the `controlsPTC` of `pSS`, +#' the ramp begins at \eqn{\lambda_0 = \lambda_{tol} - \max(d, m s)}, with +#' \eqn{d} the `width`, \eqn{m} the `margin` and \eqn{s} the largest +#' eigenvalue modulus on the manifold. The term is zero on a steady state +#' whose leading real part lies below \eqn{\lambda_0}, reaches the weight +#' \eqn{w} for each eigenvalue, both of a complex pair, whose real part +#' reaches \eqn{\lambda_{tol}}, and grows quadratically beyond. Value, +#' gradient and Gauss-Newton Hessian are continuous. Steady states that agree in the parameters, resting states and +#' start values they read count once. The gradient is exact; eigenvalues that +#' coincide within the precision of the eigenvalues take the mean of their +#' derivatives, exact where they stay equal. #' #' @details The term is an assumption of the model, that the system rests where #' the steady state is taken, not data: [profile()] with `stop = "data"` and @@ -40,6 +42,13 @@ #' @param weight \eqn{w}, the value of the term where the real part of an #' eigenvalue reaches the stability tolerance, in units of \eqn{-2 \log L}. #' Default 100. +#' @param width \eqn{d}, the least width of the ramp in the units of the rates, +#' default `0`. A ramp wide against the change of the real parts over a step +#' shows the boundary to the model of a trust-region step before the step +#' crosses it; a resting state whose slowest mode decays faster than +#' `width` is not affected. +#' @param margin \eqn{m}, the least width of the ramp relative to the largest +#' eigenvalue modulus, the precision of the eigenvalues; default `1e-6`. #' @param attrName Name of the attribute that holds the value of the term, #' default `"stability"`. #' @return An objfn of the parameters of `p`, or of `pSS` without `p`, to add to @@ -47,12 +56,17 @@ #' @seealso [Pimpl()], [constraintL2()] #' @example inst/examples/constraintStability.R #' @export -constraintStability <- function(pSS, p = NULL, weight = 100, attrName = "stability") { +constraintStability <- function(pSS, p = NULL, weight = 100, width = 0, margin = 1e-6, + attrName = "stability") { kernels <- attr(pSS, "mappings") if (!length(kernels) || !all(vapply(kernels, function(k) is.function(attr(k, "spectrum")), TRUE))) stop("constraintStability: `pSS` is a parfn of Pimpl().", call. = FALSE) if (!(is.numeric(weight) && length(weight) == 1L && weight > 0)) stop("constraintStability: `weight` is a positive number.", call. = FALSE) + if (!(is.numeric(margin) && length(margin) == 1L && margin > 0)) + stop("constraintStability: `margin` is a positive number.", call. = FALSE) + if (!(is.numeric(width) && length(width) == 1L && width >= 0)) + stop("constraintStability: `width` is a number of at least 0.", call. = FALSE) inputs <- getParameters(pSS) # the parameters of p that enter the inputs of the steady state parameters <- if (is.null(p)) inputs else { @@ -71,9 +85,7 @@ constraintStability <- function(pSS, p = NULL, weight = 100, attrName = "stabili args <- list(...) pars <- args[[match.fnargs(args, "pars")]] free <- names(pars) - tol <- attr(kernels[[1]], "stabilityTol")() - lamTol <- tol[["stabilityTol"]] - margin <- tol[["stabilityMargin"]] + lamTol <- attr(kernels[[1]], "stabilityTol")() if (is.null(p)) { inner <- list(c(unclass(pars), unclass(fixed))) jac <- list(matrix(diag(1, length(free)), length(free), dimnames = list(free, free))) @@ -98,7 +110,7 @@ constraintStability <- function(pSS, p = NULL, weight = 100, attrName = "stabili }, "") rows <- list() for (i in which(!duplicated(keys))) { - sp <- attr(kernels[[at[[i]]]], "spectrum")(inner[[i]], lamTol, margin) + sp <- attr(kernels[[at[[i]]]], "spectrum")(inner[[i]], lamTol - width, margin) if (!length(sp$active)) next J <- jac[[i]] cols <- intersect(free, colnames(J)) @@ -109,14 +121,17 @@ constraintStability <- function(pSS, p = NULL, weight = 100, attrName = "stabili if (length(on) && length(cols)) g[cols] <- drop(v[on] %*% J[on, cols, drop = FALSE]) g } - # the ramp ends at the tolerance and is `margin` times the largest eigenvalue modulus wide - ds <- chain(sp$scaleGrad) - span <- margin * sp$scale + # the ramp ends at the tolerance and is `width` or `margin` times the largest eigenvalue + # modulus wide, whichever is wider + relative <- margin * sp$scale >= width + span <- if (relative) margin * sp$scale else width + dspan <- if (relative) margin * chain(sp$scaleGrad) else 0 lam0 <- lamTol - span for (k in seq_along(sp$active)) { re <- sp$re[sp$active[k]] + if (re <= lam0) next r <- (re - lam0) / span - dr <- (chain(sp$grad[k, ]) + (1 - r) * margin * ds) / span + dr <- (chain(sp$grad[k, ]) + (1 - r) * dspan) / span # residual sqrt(w) r^(3/2) up to the tolerance, then linear with the same slope rho <- sqrt(weight) * if (r <= 1) r^1.5 else 1 + 1.5 * (r - 1) drho <- sqrt(weight) * 1.5 * sqrt(min(r, 1)) * dr diff --git a/R/emResults.R b/R/emResults.R index 3b5b9aee..2bacb067 100644 --- a/R/emResults.R +++ b/R/emResults.R @@ -15,7 +15,9 @@ }, 0)) out <- list(argument = fit$argument, value = fit$value, gradient = fit$gradient, hessian = fit$hessian, lowrank = fit$lowrank, information = fit$information, converged = fit$converged, - iterations = fit$iterations, trustIterations = fit$trustIterations, + iterations = fit$iterations, innerIterations = fit$innerIterations, sqpIterations = fit$sqpIterations, + trustIterations = fit$trustIterations, + phaseIterations = fit$phaseIterations, stopReason = fit$stopReason, failures = fit$failures, method = method, fixed = fixed, nObs = nObs, valueNonmem = if (!is.finite(design$df)) fit$value - nDensity * log(2 * pi) else NA_real_, @@ -223,9 +225,10 @@ coef.em <- function(object, ...) object$argument vcov.em <- function(object, ...) { H <- .emCurvature(object) if (is.null(H) && !is.null(object$information)) - stop("vcov: the scores of the ", length(object$design$groups), " groups do not span every ", - "direction of the ", length(object$argument), " parameters; confint(method = \"profile\") gives ", - "intervals.", call. = FALSE) + stop("vcov: the empirical information is not positive definite: the scores of the ", + length(unique(object$random$group)), " groups do not span every direction of the ", + 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) @@ -330,15 +333,28 @@ print.summary.em <- function(x, digits = 4, ...) { #' Log-likelihood of a mixed-effects fit #' #' @param object An `em` object, see [em()]. +#' @param method `"fit"` (default) the marginal log-likelihood of the fit; +#' `"importance"` the marginal log-likelihood at the estimates by importance +#' sampling on the model, for spike-and-slab random effects of one grouping +#' (normal ones beside). The proposal is the mixture of the approximation of +#' the fit with widened spreads; the fit must contain the design. +#' @param draws Draws per group for `method = "importance"`, default 1000. #' @param ... Ignored. #' @return The marginal log-likelihood, `-value / 2`, of class `logLik` with #' the number of estimated parameters as `df` and the number of -#' observations as `nobs`, so [stats::AIC()] and [stats::BIC()] apply. +#' observations as `nobs`, so [stats::AIC()] and [stats::BIC()] apply. With +#' `method = "importance"` the attributes `se` (standard error), `ess` +#' (effective sample size per group) and `approximation` (the log-likelihood +#' of the approximation of the fit at the estimates). #' @example inst/examples/emEstimates.R #' @export -logLik.em <- function(object, ...) { - structure(-object$value / 2, df = length(object$argument), nobs = object$nObs, - class = "logLik") +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) + is <- .sparseImportance(object, draws) + out[] <- -is$value / 2 + structure(out, se = is$se / 2, ess = is$ess, approximation = -is$approximation / 2) } diff --git a/R/nlmeDesign.R b/R/nlmeDesign.R index d4b42231..0a5d038d 100644 --- a/R/nlmeDesign.R +++ b/R/nlmeDesign.R @@ -49,10 +49,9 @@ class = "emdesign") } -## Per group, whether each sparse eta reaches the data of the group conditions, along the dependencies -## of the parameter transformations, steady states, the ODE with events and the observables or -## the error model to a measured name; the normal etas count as reaching. A piece without -## equations counts as passing everything on, so that an eta is marked only where no path exists. +## Per group whether each sparse eta reaches the data of the group, along the transformations, steady states, +## the ODE with events, observables and error model to a measured name; normal etas reach. A piece without +## equations passes everything on, so that an eta is marked only where no path exists. .etaReach <- function(design) { E <- design$etaNames sparse <- vapply(colnames(E), function(st) any(vapply(design$blocks, function(b) @@ -68,12 +67,9 @@ reach } -## Which of `etas` reach the data of condition `cn`: a graph of named nodes in layers, the outer -## parameters, the outputs of every transformation, the states, the observables and the error -## model, searched in C++ (graph_reach) from every eta to the measured names. Every expression is -## read with the names that are 0 in this condition set to 0 (.zeroOut()): a state that starts at 0, -## whose right-hand side vanishes with the other zeros and that no event moves stays 0 and passes -## nothing on. A piece without equations, such as a function written by hand, reaches all. +## Which of `etas` reach the data of condition `cn`, by a search in C++ (graph_reach) over the layered names +## with the names that are 0 in the condition set to 0 (.zeroOut()), so that a state held at 0 passes nothing +## on. A piece without equations, such as a function written by hand, reaches all. .reachData <- function(design, cn, etas) { every <- setNames(rep(TRUE, length(etas)), etas) lv <- .fnLeaves(design$prdfn, cn) @@ -226,11 +222,9 @@ setNames(graph_reach(as.character(unlist(from)), as.character(unlist(to)), node(0L, etas), sinks), etas) } -## The roots of a steady state (environment `env` of Pimpl()) each input moves: the states whose -## equation holds the input, then every state whose equation holds a moved state and every state of -## a conservation row with the input or a moved state. The other states solve a subsystem that holds -## neither the input nor a moved state; where it lacks full structural column rank, the input moves -## every root. Inputs in `zeros` are 0. +## The roots of a steady state (`env` of Pimpl()) each input moves: the states whose equation or conservation +## row holds it or a moved state; where the rest lacks full structural column rank, every root. Inputs in +## `zeros` are 0. .pimplDepends <- function(env, zeros) { dep <- env$dependent rows <- env$all_exprs diff --git a/R/nlmeDiagnostics.R b/R/nlmeDiagnostics.R index cd5651ce..3789e4a8 100644 --- a/R/nlmeDiagnostics.R +++ b/R/nlmeDiagnostics.R @@ -65,8 +65,9 @@ utils::globalVariables(c("lo", "mid", "hi", "percentile", "blq", "blqLo", "blqMi sims <- .simulatedRows(object, nsim) y <- pr$observed lloq <- .emObsLimits(design) - pars <- c(object$argument, .etaVector(object)) - units <- lapply(.volumeUnits(design, c(pars, object$fixed), object$fixed), `[[`, "conditions") + # the conditions of a group, or of a component of several groupings, share the random effects + units <- if (is.null(design$groupings)) unname(design$conditions[design$groups]) + else lapply(design$components, `[[`, "conditions") units <- c(units, as.list(.setdiff(names(design$data), unlist(units)))) out <- rep(NA_real_, length(y)) for (u in units) { @@ -247,22 +248,22 @@ plotVPC.em <- function(x, nsim = 200L, bins = 8L, pc = FALSE, logScale = FALSE, p <- ggplot2::ggplot(shown, ggplot2::aes(x = time, group = percentile)) + ggplot2::geom_ribbon(ggplot2::aes(ymin = lo, ymax = hi, fill = percentile == "50%"), alpha = 0.3) + ggplot2::geom_line(ggplot2::aes(y = mid), linetype = "dashed", color = "gray40") + - ggplot2::geom_line(ggplot2::aes(y = observed), color = dMod_colors[2], linewidth = 0.8, na.rm = TRUE) + - ggplot2::geom_point(ggplot2::aes(y = observed), color = dMod_colors[2], na.rm = TRUE) + - ggplot2::scale_fill_manual(values = c(`TRUE` = dMod_colors[1], `FALSE` = dMod_colors[3]), guide = "none") + + ggplot2::geom_line(ggplot2::aes(y = observed), color = dMod2_colors[2], linewidth = 0.8, na.rm = TRUE) + + ggplot2::geom_point(ggplot2::aes(y = observed), color = dMod2_colors[2], na.rm = TRUE) + + ggplot2::scale_fill_manual(values = c(`TRUE` = dMod2_colors[1], `FALSE` = dMod2_colors[3]), guide = "none") + facet + ggplot2::labs(x = "Time", y = if (pc) "Prediction-corrected value" else "Value", title = sprintf("%sVPC, %d simulations: 5, 50, 95%% of the data and their 95%% intervals", if (pc) "Prediction-corrected " else "", nsim)) + - theme_dMod(base_size = 11) + theme_dMod2(base_size = 11) attr(p, "vpc") <- table if (!any(is.finite(lloq))) return(p) bt <- table[table$percentile == "50%" & table$limited, , drop = FALSE] blq <- ggplot2::ggplot(bt, ggplot2::aes(x = time)) + - ggplot2::geom_ribbon(ggplot2::aes(ymin = blqLo, ymax = blqHi), fill = dMod_colors[3], alpha = 0.3) + + ggplot2::geom_ribbon(ggplot2::aes(ymin = blqLo, ymax = blqHi), fill = dMod2_colors[3], alpha = 0.3) + ggplot2::geom_line(ggplot2::aes(y = blqMid), linetype = "dashed", color = "gray40") + - ggplot2::geom_line(ggplot2::aes(y = blq), color = dMod_colors[2], linewidth = 0.8) + - ggplot2::geom_point(ggplot2::aes(y = blq), color = dMod_colors[2]) + - facet + ggplot2::labs(x = "Time", y = "Fraction censored") + theme_dMod(base_size = 11) + ggplot2::geom_line(ggplot2::aes(y = blq), color = dMod2_colors[2], linewidth = 0.8) + + ggplot2::geom_point(ggplot2::aes(y = blq), color = dMod2_colors[2]) + + facet + ggplot2::labs(x = "Time", y = "Fraction censored") + theme_dMod2(base_size = 11) out <- if (requireNamespace("cowplot", quietly = TRUE)) cowplot::plot_grid(p, blq, ncol = 1, rel_heights = c(2, 1)) else list(vpc = p, blq = blq) attr(out, "vpc") <- table @@ -301,12 +302,12 @@ plotVPC.em <- function(x, nsim = 200L, bins = 8L, pc = FALSE, logScale = FALSE, plots <- lapply(split(long, factor(long$covariate, cols)), function(d) { p <- ggplot2::ggplot(d, ggplot2::aes(y = mode)) + ggplot2::geom_hline(yintercept = 0, linetype = "dashed", color = "gray50") p <- if (d$numeric[1]) p + ggplot2::geom_point(ggplot2::aes(x = x), alpha = 0.7) + - ggplot2::geom_smooth(ggplot2::aes(x = x), method = "loess", formula = y ~ x, se = FALSE, color = dMod_colors[2], + ggplot2::geom_smooth(ggplot2::aes(x = x), method = "loess", formula = y ~ x, se = FALSE, color = dMod2_colors[2], linewidth = 0.7) else p + ggplot2::geom_boxplot(ggplot2::aes(x = value), outlier.shape = NA) + ggplot2::geom_jitter(ggplot2::aes(x = value), width = 0.15, height = 0, alpha = 0.5) p + ggplot2::facet_wrap(~ eta, scales = "free_y", nrow = 1) + - ggplot2::labs(x = d$covariate[1], y = "mode of the random effect") + theme_dMod(base_size = 11) + ggplot2::labs(x = d$covariate[1], y = "mode of the random effect") + theme_dMod2(base_size = 11) }) if (length(plots) == 1L) return(plots[[1]]) if (requireNamespace("cowplot", quietly = TRUE)) cowplot::plot_grid(plotlist = plots, ncol = 1) else plots diff --git a/R/nlmeFocei.R b/R/nlmeFocei.R index ec71ebae..df786c35 100644 --- a/R/nlmeFocei.R +++ b/R/nlmeFocei.R @@ -3,10 +3,9 @@ # exact derivative of the volume term; the guide chapter Nonlinear mixed-effects models has the derivation. -## Derivatives up to order 4 of the -2 log likelihood of a row in the row prediction p and sigma s, -## normal or Student-t with df degrees of freedom, M3 below the limit: [n, 5, 5], entry -## [, i + 1, j + 1] = d^(i+j) / dp^i ds^j, the value itself left at 0. Normal rows above the -## limit in closed form, the others from the Taylor series in (dp, ds). +## Derivatives up to order 4 of the row -2 log likelihood in prediction p and sigma s, normal or Student-t, +## M3 below the limit: [n, 5, 5] with [, i + 1, j + 1] = d^(i+j) / dp^i ds^j and the value left at 0; normal +## rows above the limit in closed form, the others from the Taylor series in (dp, ds). .rowLossDerivs <- function(p, s, y, censored, df = Inf) { if (is.finite(df)) return(.rowLossTaylor(p, s, y, censored, df)) out <- .rowLossNormal(p, s, y) @@ -178,10 +177,11 @@ ## Kernel description of the groups: per group the etas and condition blocks, the layout of -## the outer and full parameter vectors and the Cholesky layout. -.foceiMeta <- function(design, start, fixed) { +## the outer and full parameter vectors and the Cholesky layout. The etas are those of `stems`; with +## `reach` (groups x stems) a group has those it marks as coordinates, the others rest at 0. +.foceiMeta <- function(design, start, fixed, stems = design$normal$stems, reach = NULL) { lay <- design$normal - E <- design$etaNames[, lay$stems, drop = FALSE] + E <- design$etaNames[, stems, drop = FALSE] outer <- names(start) %||% character(0) full <- c(outer, as.vector(E)) probe <- setNames(numeric(length(full)), full) @@ -195,14 +195,17 @@ meta <- lapply(groups, function(g) { blocks <- lapply(design$conditions[[g]], function(cn) .conditionBlock(design, cn, probe, fixed, frames[[cn]])) used <- unique(unlist(lapply(blocks, `[[`, "parameters"))) - absent <- .setdiff(E[g, ], used) + on <- if (is.null(reach)) rep(TRUE, ncol(E)) else reach[g, stems] + absent <- .setdiff(E[g, on], used) if (length(absent)) stop("em: the random effects ", paste(absent, collapse = ", "), " of group ", g, " enter none of the conditions of that group.", call. = FALSE) - list(eta_idx_in_pars = match(E[g, ], full), eta_names = unname(E[g, ]), - blocks = lapply(blocks, function(b) { b$parameters <- NULL; b })) + out <- list(eta_idx_in_pars = match(E[g, on], full), eta_names = unname(E[g, on]), + blocks = lapply(blocks, function(b) { b$parameters <- NULL; b })) + if (!all(on)) out$coords <- which(on) + out }) - list(subjects = groups, conditions = names(design$data), K = lay$K, + list(subjects = groups, conditions = names(design$data), K = ncol(E), eta_idx_global = matrix(match(E, full), nrow(E)), eta_names = lapply(groups, function(g) unname(E[g, ])), outer_names = outer, outer_idx_in_full = match(outer, full), other_etas_init = setNames(rep(0, length(E)), as.vector(E)), pars_full_names = full, @@ -600,9 +603,8 @@ if (.foceiSparseChoice(design, joint, start, fixed, control$sparse %||% "auto")) return(.fitFoceiSparse(design, joint, start, fixed, control)) ic <- modifyList(list(rinit = 1, rmax = 10, iterlim = 30, steptol = 1e-8, mtol = 1e-12, - eigen_floor_relative = 1e-10), control$innerControl %||% list()) - oc <- modifyList(list(rinit = 1, rmax = 10, iterlim = 200, ftol = 1e-7, mtol = 1e-5), - control$trustControl %||% list()) + eigenFloorRelative = 1e-10), control$innerControl %||% list()) + oc <- .foceiOuterControl(control$trustControl, oneGrouping = TRUE) cores <- getOption("dMod2.cores", 1L) meta <- .foceiMeta(design, start, fixed) .requireM3(design, meta, "FOCEI") @@ -614,10 +616,11 @@ # gradient, and d eta*/d theta, which starts the modes of the next trial to first order learn <- .outerSecant(outer) last <- NULL - volume <- function(full_pars, joint_hessian, H_inv_list, data_gradient) { + # the volume derivatives contract dH with the weights of the integrator, the Schur complement takes H_NN^-1 + volume <- function(full_pars, joint_hessian, H_inv_list, weight_list, data_gradient) { ff <- mode == "forward-forward" - vol <- if (ff) .foceiVolume(design, full_pars, fixed, outer, H_inv_list, hessian = TRUE, cores = cores) - else .volumeReverse(design, full_pars, fixed, outer, H_inv_list, cores = cores) + vol <- if (ff) .foceiVolume(design, full_pars, fixed, outer, weight_list, hessian = TRUE, cores = cores) + else .volumeReverse(design, full_pars, fixed, outer, weight_list, cores = cores) curvature <- if (ff) vol$hessian[outer, outer] else 0 if (ff) last <<- list(full = full_pars, hessian = vol$hessian) base <- .gnSchur(joint_hessian, outer, meta$eta_names, H_inv_list) + curvature @@ -625,14 +628,16 @@ list(gradient = vol$gradient, hessian = curvature + learn$dense(), eta_shift = vol$etaShift) } failure <- new.env(parent = emptyenv()) - fit <- tryCatch(focei_run(model_cb = design$prdfn, err_cb = .errorModel(design), joint_cb = joint, - init = start, subject_meta = meta, fixed = fixed, - control = list(inner = ic, outer = oc), - correction_mode = if (correction) "eager" else "none", - correction_cb = if (correction) volume else NULL, - predict_cb = .guardPredictor(.batchPredictor(design), failure)), - error = function(e) stop(conditionMessage(e), if (!is.null(failure$message)) - paste0("; the last prediction that failed: ", failure$message), call. = FALSE)) + run <- function(inner, start, warm, settings, newton) tryCatch( + focei_run(model_cb = design$prdfn, err_cb = .errorModel(design), joint_cb = joint, + init = start, subject_meta = meta, fixed = fixed, + control = list(inner = inner, outer = settings, newtonValue = newton), + correction_mode = if (correction) "eager" else "none", + correction_cb = if (correction) volume else NULL, + predict_cb = .guardPredictor(.batchPredictor(design), failure), eta_init = warm), + error = function(e) stop(conditionMessage(e), if (!is.null(failure$message)) + paste0("; the last prediction that failed: ", failure$message), call. = FALSE)) + fit <- .sqpThenNested(run, .sqpInner(control, ic), ic, start, oc) E <- design$etaNames[, design$normal$stems, drop = FALSE] etaModes <- fit$etaModes @@ -652,13 +657,75 @@ # the volume Hessian of the last correction where the fit ends on the correction point vol <- if (!is.null(last) && identical(names(last$full), names(full)) && identical(unname(unclass(last$full)), unname(full))) last$hessian - else .foceiVolume(design, full, fixed, outer, fit$H_inv, hessian = TRUE, cores = cores)$hessian + else .foceiVolume(design, full, fixed, outer, fit$weight, hessian = TRUE, cores = cores)$hessian hessian <- hessian + vol[on, on] } list(argument = fit$argument, value = fit$value, gradient = fit$gradient, hessian = hessian, etaModes = etaModes, etaCov = setNames(lapply(fit$H_inv, function(H) 2 * H), design$groups), - converged = isTRUE(fit$converged), iterations = fit$iterations, trace = fit$trace, - derivMode = mode, hessianExact = exact) + converged = isTRUE(fit$converged), iterations = fit$iterations, innerIterations = fit$innerIterations, + sqpIterations = fit$sqpIterations, trace = fit$trace, derivMode = mode, hessianExact = exact) +} + +## The inner settings of the inexact phase of control$inner = "sqp", `ic` with iterlim +## `ic$sqpIterlim` (default 2); NULL with control$inner "nested". +.sqpInner <- function(control, ic) { + if (!identical(control[["inner"]], "sqp")) return(NULL) + modifyList(ic, list(iterlim = as.integer(ic$sqpIterlim %||% 2L))) +} + +## An outer search by `run(inner, start, warm, settings, newton)` with settings `oc`: with `sqp` first on the +## inexact modes of `sqp` to the tolerances of .sqpTolerance(), then from there on the modes of `ic`, so the result is that +## of the nested search; the iterations add up, `sqpIterations` those of the first. +.sqpThenNested <- function(run, sqp, ic, start, oc) { + if (is.null(sqp) || oc$iterlim <= 0) { + fit <- run(ic, start, NULL, oc, FALSE) + fit$innerIterations <- as.integer(fit$innerIterations) + return(fit) + } + first <- run(sqp, start, NULL, .sqpTolerance(oc), TRUE) + fit <- run(ic, first$argument, first$etaModes, modifyList(oc, list(iterlim = oc$iterlim - first$iterations)), + FALSE) + fit$iterations <- first$iterations + fit$iterations + fit$sqpIterations <- first$iterations + fit$innerIterations <- as.integer(first$innerIterations + fit$innerIterations) + if (!is.null(first$trace)) fit$trace <- Map(c, first$trace, lapply(fit$trace, `[`, -1L)) + fit +} + +## The outer tolerances of the search on inexact modes, the square roots of ftol and mtol of `oc`, flat +## or in `tolControl`: the value there is off by the modes, and the nested search ends the fit. +.sqpTolerance <- function(oc) { + loose <- function(x) lapply(x[.intersect(names(x), c("ftol", "mtol"))], sqrt) + oc <- modifyList(oc, loose(oc)) + if (!is.null(oc$tolControl)) oc$tolControl <- modifyList(oc$tolControl, loose(oc$tolControl)) + oc +} + +## The outer trust settings of FOCEI from `control$trustControl`. Flat ftol, mtol, gtol and xtol join +## `tolControl`. Over several groupings the outer search is trust(), and every other argument of +## trust() passes; one grouping runs a separate outer loop, which reads rinit, rmax and iterlim. +.foceiOuterControl <- function(tc, oneGrouping) { + tc <- tc %||% list() + nms <- names(tc) + if (length(tc) && (is.null(nms) || !all(nzchar(nms)))) + stop("em: all entries of control$trustControl must be named.", call. = FALSE) + flat <- c("ftol", "mtol", "gtol", "xtol") + rest <- tc[.setdiff(nms, c(flat, "tolControl"))] + tol <- modifyList(list(ftol = 1e-7, mtol = 1e-5), c(tc$tolControl %||% list(), tc[.intersect(nms, flat)])) + if ("sparse" %in% names(rest)) + stop("em: sparse is an argument of em(), not an entry of control$trustControl.", call. = FALSE) + if (oneGrouping) { + bad <- .setdiff(names(rest), c("rinit", "rmax", "iterlim")) + if (length(bad)) + stop("em: control$trustControl: ", paste(bad, collapse = ", "), " reach trust() with random ", + "effects over several groupings only. FOCEI of one grouping runs a separate outer trust ", + "region on rinit, rmax, iterlim, ftol and mtol.", call. = FALSE) + return(c(modifyList(list(rinit = 1, rmax = 10, iterlim = 200L), rest), tol)) + } + out <- .trustControl(list(rinit = 1, rmax = 10, iterlim = 200L), rest, label = "em: control$trustControl") + if (is.null(out$phases) && is.null(out$hessianMethod)) out$hessianMethod <- "gn" + out$tolControl <- tol + out } ## How FOCEI gets the second derivatives: `control$derivMode`, forward over reverse by default; @@ -719,10 +786,9 @@ S } -## The SR1 correction of an outer model from the steps s between the points `add()` is called at -## and the curvature the model at the newer point misses along them, y - B s with y the change of -## the full outer gradient and `times(x)` = B x; the last `memory` pairs from zero in their order, -## as U diag(d) U' (`factors()`) or a matrix (`dense()`). A pair with |r's| <= 1e-8 |r| |s| is skipped. +## The SR1 correction of an outer model from the steps s between the points of `add()` and r = y - B s, y the +## change of the outer gradient and `times(x)` = B x: the last `memory` pairs as U diag(d) U' (`factors()`) or +## a matrix (`dense()`); a pair with |r's| <= 1e-8 |r| |s| is skipped. .outerSecant <- function(outer, memory = 2L) { S <- M <- matrix(0, length(outer), 0) last <- NULL @@ -842,9 +908,8 @@ ## groups or low-rank, with the SR1 correction. .fitFoceiSparse <- function(design, joint, start, fixed = NULL, control = list()) { ic <- modifyList(list(rinit = 1, rmax = 10, iterlim = 30, steptol = 1e-8, mtol = 1e-12, - eigen_floor_relative = 1e-10), control$innerControl %||% list()) - oc <- modifyList(list(rinit = 1, rmax = 10, iterlim = 200, ftol = 1e-7, mtol = 1e-5), - control$trustControl %||% list()) + eigenFloorRelative = 1e-10), control$innerControl %||% list()) + oc <- .foceiOuterControl(control$trustControl, oneGrouping = TRUE) cores <- getOption("dMod2.cores", 1L) meta <- .foceiMeta(design, start, fixed) .requireM3(design, meta, "FOCEI") @@ -859,17 +924,22 @@ mode <- .secondOrderMode(design, joint, start, fixed, control) correction <- mode != "none" - # the modes and the value at theta, the inner trust started from `warm` - modesAt <- function(theta, warm) { + # the modes and the value at theta, the inner trust of the settings `settings` started from `warm`; + # with `newton` the value at the exact modes to second order in the eta gradient the inner trust leaves + modesAt <- function(theta, warm, settings = ic, newton = FALSE) { L <- .choleskyFactor(lay, c(theta, fixed)) full <- setNames(numeric(length(meta$pars_full_names)), meta$pars_full_names) full[outer] <- theta - inner <- focei_inner_trust(design$prdfn, errfn, full, warm, meta, chol2inv(t(L)), - 2 * sum(log(diag(L))), fixed, control = ic, predict_cb = predictor) + inner <- nlme_group_kernel(design$prdfn, errfn, full, warm, meta, chol2inv(t(L)), + 2 * sum(log(diag(L))), fixed, control = settings, predict_cb = predictor) full[etas] <- as.vector(inner$eta_modes) jt <- joint(pars = full, fixed = fixed, deriv = TRUE, hessian = "sparse", conditions = meta$conditions) - list(theta = theta, full = full, inner = inner, joint = jt, - value = jt$value + sum(inner$log_det_H) - N * K * log(2)) + decrement <- if (newton) sum(vapply(seq_len(N), function(g) { + r <- jt$gradient[E[g, ]] + sum(r * (inner$H_inv[[g]] %*% r)) + }, 0)) else 0 + list(theta = theta, full = full, inner = inner, joint = jt, iterations = inner$iterations, + value = jt$value + sum(inner$term) + inner$constant - decrement / 2) } # the gradient and the sparse Hessian of the outer objective, and d eta*/d theta per group derivativesAt <- function(ev, deriv2 = FALSE) { @@ -894,12 +964,12 @@ # forward over reverse: the exact volume gradient on the Gauss-Newton Schur model, whose # curvature the SR1 correction learns if (mode == "forward-reverse" && !deriv2) { - vol <- .volumeReverse(design, ev$full, fixed, outer, ev$inner$H_inv, cores = cores, local = TRUE) + vol <- .volumeReverse(design, ev$full, fixed, outer, ev$inner$weight, cores = cores, local = TRUE) ev$gradient <- ev$gradient + vol$gradient[outer] ev$shift <- vol$etaShift return(ev) } - vol <- .foceiVolume(design, ev$full, fixed, outer, ev$inner$H_inv, hessian = "sparse", cores = cores) + vol <- .foceiVolume(design, ev$full, fixed, outer, ev$inner$weight, hessian = "sparse", cores = cores) ev$gradient <- ev$gradient + vol$gradient[outer] ev$hessian <- Matrix::forceSymmetric(ev$hessian + vol$hessian) ev$lowrank <- .lowrankJoin(ev$lowrank, vol$lowrank) @@ -910,8 +980,8 @@ # the derivatives with the SR1 correction of the outer model as part of the low-rank part and # the mode shifts over the outer positions of their columns learn <- .outerSecant(outer) - trial <- function(theta, warm) { - ev <- modesAt(setNames(as.numeric(theta), outer), warm) + trial <- function(theta, warm, settings = ic, newton = FALSE) { + ev <- modesAt(setNames(as.numeric(theta), outer), warm, settings, newton) ev$eta_modes <- ev$inner$eta_modes ev } @@ -928,7 +998,12 @@ if (length(S)) structure(matrix(as.numeric(S), nrow(S)), idx = match(colnames(S), outer))) ev } - res <- focei_run_sparse(trial, complete, setNames(as.numeric(start), outer), N, K, oc, ic$rinit) + run <- function(inner, start, warm, settings, newton) { + res <- focei_run_sparse(function(theta, warm) trial(theta, warm, inner, newton), complete, + setNames(as.numeric(start), outer), N, K, settings, ic$rinit, warm) + c(res, list(etaModes = res$keep$inner$eta_modes)) + } + res <- .sqpThenNested(run, .sqpInner(control, ic), ic, start, oc) cur <- res$keep converged <- res$converged it <- res$iterations @@ -946,7 +1021,8 @@ dimnames(etaModes) <- list(design$groups, lay$stems) list(argument = cur$theta, value = cur$value, gradient = setNames(cur$gradient, outer), hessian = final$hessian, lowrank = final$lowrank, etaModes = etaModes, etaCov = setNames(lapply(cur$inner$H_inv, function(H) 2 * H), design$groups), - converged = converged, iterations = it, trace = trace, derivMode = mode, hessianExact = exact) + converged = converged, iterations = it, innerIterations = res$innerIterations, + sqpIterations = res$sqpIterations, trace = trace, derivMode = mode, hessianExact = exact) } @@ -967,6 +1043,12 @@ ic <- modifyList(list(rinit = 1, rmax = 10, iterlim = 100L, mtol = 1e-12, steptol = 1e-8), control$innerControl %||% list()) warm <- setNames(numeric(length(etas)), etas) + # the inner settings and, on inexact modes (control$inner = "sqp"), the modes predicted along d eta*/d theta + # from the last evaluation; `innerIterations` counts the evaluated inner steps + inner <- ic + newton <- FALSE + predict <- NULL + innerIterations <- 0L # the objectives per condition of the R evaluation, built where the chain does not cover the model delayedAssign("objs", .conditionObjectives(design)) # The modes of all components in lock step (focei_units_lockstep()): per round one batched @@ -974,33 +1056,13 @@ # the component data and the normal prior of the component etas, e' P e / 2, accepted by a separate ratio. modes <- function(theta) { held <- c(theta, fixed) + if (!is.null(predict)) warm <<- predict$modes + drop(predict$shift %*% (theta - predict$theta)) P <- lapply(.volumeUnits(design, c(theta, fixed, warm), fixed), function(u) { m <- as.matrix(u$P); storage.mode(m) <- "double"; m }) - # the data terms of the components `idx` at the etas `etas`, summed per component in C++ where - # the model allows it; NULL for a component whose prediction fails, the others evaluated apart - dataUnits <- function(idx, etas) { - cs <- unlist(lapply(units[idx], `[[`, "conditions"), use.names = FALSE) - owner <- rep(seq_along(idx), vapply(units[idx], function(u) length(u$conditions), 0L)) - parsL <- lapply(owner, function(j) setNames(etas[[j]], units[[idx[j]]]$eta)) - loc <- tryCatch(.chainLocal(design$chain, cs, parsL, rep(list(held), length(cs)), TRUE, FALSE, - getOption("dMod2.cores", 1L), design$bloq, design$df), error = function(e) NULL) - d <- if (!is.null(loc)) chain_unit_sums(loc, owner - 1L, lapply(units[idx], `[[`, "eta")) - else tryCatch({ - m <- .objEvalMany(objs[cs], parsL, deriv = TRUE, fixed = held) - lapply(seq_along(idx), function(j) { - eta <- units[[idx[j]]]$eta - mine <- m[owner == j] - list(value = sum(vapply(mine, `[[`, 0, "value")), - gradient = Reduce(`+`, lapply(mine, function(x) .named(x$gradient, eta))), - hessian = Reduce(`+`, lapply(mine, function(x) .namedHessian(x$hessian, eta)))) - }) - }, error = function(e) NULL) - if (is.null(d)) return(if (length(idx) == 1L) list(NULL) - else lapply(seq_along(idx), function(j) dataUnits(idx[j], etas[j])[[1L]])) - lapply(d, function(x) if (is.finite(x$value)) x) - } - w <- focei_units_lockstep(dataUnits, lapply(units, function(u) unname(warm[u$eta])), P, ic) + w <- focei_units_lockstep(.unitData(design, units, objs, held), lapply(units, function(u) unname(warm[u$eta])), + P, inner) + innerIterations <<- innerIterations + sum(attr(w, "iterations")) for (i in seq_along(units)) warm[units[[i]]$eta] <<- w[[i]] warm } @@ -1017,6 +1079,13 @@ Hinv <- lapply(units, function(u) .scaledSolve(block(u))) logdet <- sum(vapply(units, function(u) as.numeric(determinant(block(u) / 2)$modulus), 0)) cores <- getOption("dMod2.cores", 1L) + decrement <- 0 + if (newton) { + corrected <- .inexactModes(gn, Hinv, units, etas, outer) + decrement <- corrected$decrement + gn$gradient <- corrected$gradient + predict <<- list(theta = theta, modes = full[etas], shift = corrected$shift) + } schur <- function(h) { ee <- .intersect(etas, rownames(h)) h[outer, outer, drop = FALSE] - @@ -1026,8 +1095,8 @@ jp <- sparseH(joint(pars = full, fixed = fixed, deriv = TRUE, deriv2 = TRUE, hessian = curvature)) jh <- jp$hessian lowrank <- jp$lowrank - vol <- .foceiVolume(design, full, fixed, outer, Hinv, hessian = if (!volumeHessian) FALSE else curvature %||% TRUE, - cores = cores) + vol <- .foceiVolume(design, full, fixed, outer, Hinv, cores = cores, + hessian = if (!volumeHessian) FALSE else curvature %||% TRUE) H <- schur(jh) if (volumeHessian) { H <- H + vol$hessian[outer, outer] @@ -1057,17 +1126,21 @@ } } if (sparse) H <- Matrix::forceSymmetric(Matrix::Matrix(H, sparse = TRUE)) - out <- objlist(value = gn$value + logdet, gradient = gn$gradient[outer] + volGradient, hessian = H) + out <- objlist(value = gn$value + logdet - decrement / 2, gradient = gn$gradient[outer] + volGradient, hessian = H) out$lowrank <- .lowrankOver(lowrank, outer) attr(out, "Hinv") <- Hinv out } - oc <- modifyList(list(rinit = 1, rmax = 10, iterlim = 200L, ftol = 1e-7, mtol = 1e-5), control$trustControl %||% list()) - args <- list(objfun = outerObjective, parinit = start, rinit = oc$rinit, rmax = oc$rmax, iterlim = oc$iterlim, - tolControl = oc[.intersect(names(oc), c("ftol", "mtol", "gtol"))], - sparse = sparse) - # iterlim 0 evaluates the marginal at the start, which is no failure to converge - fit <- if (oc$iterlim > 0) do.call(trust, args) else .innerTrust(args) + # one outer search; the modes of the last evaluation stay in `warm`, so `etaStart` is not needed + run <- function(innerSettings, from, etaStart, settings, newtonValue) { + inner <<- innerSettings + newton <<- newtonValue + predict <<- NULL + args <- c(list(objfun = outerObjective, parinit = from), settings, list(sparse = sparse)) + # iterlim 0 evaluates the marginal at the start, which is no failure to converge + if (settings$iterlim > 0) do.call(trust, args) else .innerTrust(args) + } + fit <- .sqpThenNested(run, .sqpInner(control, ic), ic, start, .foceiOuterControl(control$trustControl, oneGrouping = FALSE)) final <- outerObjective(fit$argument, volumeHessian = TRUE) cov <- unlist(lapply(seq_along(units), function(i) { V <- 2 * attr(final, "Hinv")[[i]] @@ -1077,10 +1150,57 @@ list(argument = fit$argument[outer], value = final$value, gradient = final$gradient, hessian = final$hessian, lowrank = final$lowrank, etas = warm, etaCovUnits = cov, units = units, converged = isTRUE(fit$converged), iterations = fit$iterations, stopReason = fit$stopReason, + phaseIterations = fit$phaseIterations, innerIterations = innerIterations, sqpIterations = fit$sqpIterations, derivMode = mode, hessianExact = mode == "forward-forward" || .jointDeriv2(joint, c(fit$argument[outer], warm), fixed)) } +## The data terms of the components `idx` at the etas `etas`, the other parameters at `held`, summed per +## component in C++ where the model allows it; NULL for a component whose prediction fails. +.unitData <- function(design, units, objs, held) { + dataUnits <- function(idx, etas) { + cs <- unlist(lapply(units[idx], `[[`, "conditions"), use.names = FALSE) + owner <- rep(seq_along(idx), vapply(units[idx], function(u) length(u$conditions), 0L)) + parsL <- lapply(owner, function(j) setNames(etas[[j]], units[[idx[j]]]$eta)) + loc <- tryCatch(.chainLocal(design$chain, cs, parsL, rep(list(held), length(cs)), TRUE, FALSE, + getOption("dMod2.cores", 1L), design$bloq, design$df), error = function(e) NULL) + d <- if (!is.null(loc)) chain_unit_sums(loc, owner - 1L, lapply(units[idx], `[[`, "eta")) + else tryCatch({ + m <- .objEvalMany(objs[cs], parsL, deriv = TRUE, fixed = held) + lapply(seq_along(idx), function(j) { + eta <- units[[idx[j]]]$eta + mine <- m[owner == j] + list(value = sum(vapply(mine, `[[`, 0, "value")), + gradient = Reduce(`+`, lapply(mine, function(x) .named(x$gradient, eta))), + hessian = Reduce(`+`, lapply(mine, function(x) .namedHessian(x$hessian, eta)))) + }) + }, error = function(e) NULL) + if (!is.null(d)) return(lapply(d, function(x) if (is.finite(x$value)) x)) + if (length(idx) == 1L) return(list(NULL)) + # the components one by one, so that the others keep their value + lapply(seq_along(idx), function(j) dataUnits(idx[j], etas[j])[[1L]]) + } + dataUnits +} + +## Value and gradient on inexact modes at the exact modes to first order in the eta gradient r the inner search +## leaves, f - r' H_ee^-1 r / 2 and g_o - H_oe H_ee^-1 r, and d eta*/d theta = -H_ee^-1 H_eo, which predicts the +## modes of the next evaluation. +.inexactModes <- function(gn, Hinv, units, etas, outer) { + shift <- matrix(0, length(etas), length(outer), dimnames = list(etas, outer)) + decrement <- 0 + gradient <- gn$gradient + for (i in seq_along(units)) { + e <- units[[i]]$eta + Hoe <- as.matrix(gn$hessian[outer, e, drop = FALSE]) + d <- drop(Hinv[[i]] %*% gradient[e]) + decrement <- decrement + sum(gradient[e] * d) + gradient[outer] <- gradient[outer] - drop(Hoe %*% d) + shift[e, ] <- -Hinv[[i]] %*% t(Hoe) + } + list(decrement = decrement, gradient = gradient, shift = shift) +} + ## A gradient restricted to `names`, 0 where absent. .named <- function(g, names) { out <- setNames(numeric(length(names)), names); h <- .intersect(names, names(g)); out[h] <- g[h]; out } diff --git a/R/nlmePrior.R b/R/nlmePrior.R index b867d921..4f12b943 100644 --- a/R/nlmePrior.R +++ b/R/nlmePrior.R @@ -125,7 +125,7 @@ hessian = cd$hcc[free, free, drop = FALSE]) } if (!length(free)) return(chol) - fit <- trust(expected, chol[free], rinit = 1, rmax = 10, iterlim = 100) + fit <- trust(expected, chol[free], rinit = 1, rmax = 10, iterlim = 100, hessianMethod = "gn") chol[free] <- fit$argument chol } diff --git a/R/nlmeQuadrature.R b/R/nlmeQuadrature.R index db7e3ed0..79430ede 100644 --- a/R/nlmeQuadrature.R +++ b/R/nlmeQuadrature.R @@ -29,6 +29,22 @@ 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 + sum(w >= max(w) - pruneTol) +} + ## Nodes eta = mode + sqrt(2) R^-1 z and log weights w exp(z'z) 2^(K/2) / |R| around the mode ## with posterior precision P = R'R, exact for a Gaussian posterior; nodes whose |w| lies ## `pruneTol` in log below the largest are dropped. @@ -45,7 +61,7 @@ ## 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 trust of the FOCEI kernel. +## 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()) { lay <- design$normal E <- design$etaNames[, lay$stems, drop = FALSE] @@ -54,8 +70,8 @@ full[as.vector(E)] <- as.vector(etaInit) L <- .choleskyFactor(lay, psi) ic <- modifyList(list(rinit = 1, rmax = 10, iterlim = 30, steptol = 1e-8, mtol = 1e-12, - eigen_floor_relative = 1e-10), control) - fr <- focei_inner_trust(model_cb = design$prdfn, err_cb = .errorModel(design), pars_full = full, + eigenFloorRelative = 1e-10), control) + fr <- nlme_group_kernel(model_cb = design$prdfn, err_cb = .errorModel(design), pars_full = full, eta_warmstart = etaInit, subject_meta = meta, Omega_inv_mat = chol2inv(t(L)), Omega_log_det = 2 * sum(log(diag(L))), fixed = fixed, control = ic, predict_cb = .guardPredictor(.batchPredictor(design))) @@ -228,6 +244,8 @@ .requireM3(design, meta, "Quadrature") cores <- getOption("dMod2.cores", 1L) maxLevel <- control$maxLevel %||% (lay$K + 8L) + maxNodes <- control$maxNodes %||% 1000L + pruneTol <- control$pruneTol %||% Inf shift <- .referenceShift(design) state <- new.env() state$modes <- matrix(0, nrow(E), lay$K, dimnames = dimnames(E)) @@ -242,8 +260,56 @@ data, etas) } - # each group at the lowest level from `level` up, never below the previous one, whose next - # level changes the group -2 log L by at most tol / G + # a level within the node budget; it is evaluated, and the tolerance raises a group to it up to + # maxLevel + allowed <- function(l) !is.na(l) && .levelNodes(lay$K, l, pruneTol) <= maxNodes + # the highest level within the budget up to `level`, at least K + accepted <- function(level) { + l <- as.integer(level) + while (l > lay$K && !allowed(l)) l <- l - 1L + 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 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()) @@ -253,47 +319,31 @@ state$stamp <- state$stamp + 1L state$memo <- NULL G <- length(design$groups) - levels <- pmax(rep(as.integer(level), G), state$levels %||% 0L) + 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, control$pruneTol %||% Inf) + nodesAt <- function(i, l) .quadratureNodes(im$modes[i, ], im$H[[i]] / 2, l, pruneTol) if (is.finite(tol)) { - # lock step over the groups, the node values kept by key - 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) - grids <- lapply(seq_along(open), function(j) - list(at = nodesAt(open[j], levels[open[j]]), - up = if (!is.na(nxt[j])) nodesAt(open[j], nxt[j]))) - need <- lapply(seq_along(open), function(j) { - gr <- grids[[j]] - eta <- rbind(gr$at$eta, gr$up$eta) - key <- c(gr$at$key, gr$up$key) - new <- !duplicated(key) & !(key %in% names(seen[[open[j]]])) - list(eta = eta[new, , drop = FALSE], key = key[new]) - }) - vals <- integrand(design$groups[open], lapply(need, `[[`, "eta"), psi) - for (j in seq_along(open)) seen[[open[j]]] <- c(seen[[open[j]]], setNames(vals[[j]], need[[j]]$key)) - done <- logical(length(open)) - for (j in seq_along(open)) { - i <- open[j] - at <- grids[[j]]$at; up <- grids[[j]]$up - la <- .nodeSum(at$logW + seen[[i]][at$key], at$signs, at$eta, lay$stems) - lu <- if (!is.null(up)) .nodeSum(up$logW + seen[[i]][up$key], up$signs, up$eta, lay$stems) - e <- if (is.null(la) || is.null(lu)) Inf else 2 * abs(lu$logL - la$logL) - error[i] <- e - if (e <= tol / G || is.na(nxt[j]) || nxt[j] > maxLevel) done[j] <- TRUE - else levels[i] <- nxt[j] - } - open <- open[!done] - } + chosen <- chooseLevels(levels, capped, tol, nodesAt, psi) + levels <- chosen$levels; error <- chosen$error; capped <- chosen$capped } state$levels <- levels state$levelError <- error + state$capped <- capped state$nodes <- lapply(seq_len(G), function(i) nodesAt(i, levels[i])) invisible(state) } + # the nodes of a rebuild, to return to without a new mode search + fields <- c("modes", "H", "psi0", "levels", "levelError", "capped", "nodes") + snapshot <- function() mget(fields, envir = state) + restore <- function(snap) { + list2env(snap, envir = state) + state$stamp <- state$stamp + 1L + state$memo <- NULL + invisible(state) + } + # the data term at the frozen nodes, recomputed only when a parameter it depends on changes or # more derivatives are asked for dataTerm <- function(base, dataActive, grad, deriv2) { @@ -370,7 +420,20 @@ } class(value) <- c("objfn", "fn") attr(value, "parameters") <- names(start) - list(value = value, rebuild = rebuild, integrand = integrand, state = state) + list(value = value, rebuild = rebuild, integrand = integrand, state = state, allowed = allowed, + snapshot = snapshot, restore = restore) +} + + +## 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) } @@ -394,25 +457,33 @@ ## The final evaluation over every parameter on the nodes at `psi`, with the exact Hessian where ## the chain has second derivatives, and the conditional covariance of the etas, M - m m' per group. +## The stage trace holds the levels per group as attribute "levels". .quadratureResult <- function(design, q, psi, fixed, iterations, converged, trace, - exact = .hasDeriv2(q, psi, fixed)) { + exact = .hasDeriv2(q, psi, fixed), stopReason = NULL) { out <- q$value(psi, fixed = fixed, deriv2 = exact) cov <- Map(function(M, m) M - tcrossprod(m), attr(out, "moments"), attr(out, "means")) + if (!is.null(trace)) attr(trace, "levels") <- .levelTable(design, q$state) list(argument = psi, value = out$value, gradient = out$gradient, hessian = out$hessian, etaModes = q$state$modes, etaCov = setNames(cov, design$groups), - converged = converged, iterations = iterations, stageTrace = trace) + converged = converged, iterations = iterations, stopReason = stopReason, stageTrace = trace) } +## Per group the level, node count, estimated level error and whether the level is capped. +.levelTable <- function(design, st) + data.frame(group = design$groups, level = st$levels, nodes = vapply(st$nodes, function(n) nrow(n$eta), 0L), + levelError = st$levelError, capped = st$capped %||% FALSE) + -## ECM by quadrature from `start`: per stage of `levels`, the nodes rebuilt at the current -## parameters and one trust over every parameter on them, until a Newton step on the rebuilt -## nodes would lower -2 log L by less than `tolDecrement`, or by less than the last step raised it. +## ECM by quadrature from `start`: per stage the nodes rebuilt at the current parameters and one +## trust over every parameter on them, until the stop "decrement" or "resolution" of em(); the fit +## returns the best iterate. .fitQuadrature <- function(design, start, fixed, control = list(), verbose = FALSE, etaInit = NULL) { lay <- design$normal qc <- control$quadrature %||% list() levels <- qc$levels %||% (lay$K + 1L) tol <- qc$tol %||% 0.1 + nIt <- qc$maxEcmPerStage %||% 10L q <- .quadratureObjective(design, start, fixed, modifyList(control, qc)) if (!is.null(etaInit)) q$state$modes <- etaInit psi <- start @@ -421,45 +492,44 @@ step <- .trustControl(list(rinit = 1, rmax = 10, hessianMethod = if (exact) "exact" else "gn", tolControl = list(ftol = 1e-8, mtol = 1e-8)), qc$cm1Control, label = "cm1Control") - rows <- list(); dec <- Inf; ended <- FALSE + rows <- list(); best <- NULL; reason <- "iterlim" for (level in levels) { - prev <- NULL; best <- NULL; ended <- FALSE - for (it in seq_len(qc$maxEcmPerStage %||% 10L)) { + prev <- NULL; reason <- "iterlim" + for (it in seq_len(nIt)) { if (it > 1L || level != levels[1]) q$rebuild(psi, level, tol) ev <- q$value(psi, fixed = fixed, deriv2 = exact) dec <- .newtonDecrement(ev) - # what the nodes resolve: the change of -2 log L by the next level, summed over the groups - resolution <- sum(q$state$levelError[is.finite(q$state$levelError)]) - at <- list(psi = psi, value = ev$value, levels = q$state$levels) - # -2 log L rose since the last iterate, on nodes of the same levels, by more than the Newton - # decrement here: the change is below what these nodes resolve, the stage ends at the best iterate. - unresolved <- !is.null(prev) && identical(prev$levels, at$levels) && at$value - prev$value > dec + st <- q$state + at <- list(psi = psi, value = ev$value, levels = st$levels, snapshot = q$snapshot()) + # values on higher levels supersede those on lower ones if (is.null(best) || !identical(best$levels, at$levels) || at$value < best$value) best <- at + last <- at rows[[length(rows) + 1L]] <- data.frame(level = level, ecmIter = it, OFV = ev$value, decrement = dec, - resolution = resolution, maxLevel = max(q$state$levels), - nodes = sum(vapply(q$state$nodes, function(n) nrow(n$eta), 0L)), + resolution = sum(st$levelError[is.finite(st$levelError)]), + maxLevel = max(st$levels), capped = sum(st$capped), + nodes = sum(vapply(st$nodes, function(n) nrow(n$eta), 0L)), maxSoftmax = max(attr(ev, "diagnostics")$maxWeight), nEffMin = min(attr(ev, "diagnostics")$nEff)) - if (verbose) message(sprintf("em(quadrature) level %d ecm %d: -2 log L %.6f, decrement %.2e, resolution %.2e", - level, it, ev$value, dec, resolution)) - if (dec < max(qc$tolDecrement %||% 1e-4, resolution)) { ended <- TRUE; break } - if (unresolved) { - ended <- TRUE - if (!identical(best$psi, psi)) { psi <- best$psi; q$rebuild(psi, level, tol) } - break + if (verbose) message(sprintf("em(quadrature) level %d ecm %d: -2 log L %.6f, decrement %.2e, capped groups %d", + level, it, ev$value, dec, sum(st$capped))) + if (dec < (qc$tolDecrement %||% 1e-4)) { reason <- "decrement"; break } + # the frozen nodes predicted a decrease the rebuilt ones do not show: the step is below + # what these levels resolve + if (!is.null(prev) && identical(prev$levels, at$levels) && at$value > prev$value) { + reason <- "resolution"; break } + if (it == nIt) break prev <- at cm <- .innerTrust(modifyList(step, list(objfun = q$value, parinit = psi, fixed = fixed, iterlim = qc$maxCm1Iter %||% 30L))) psi <- cm$argument } } - converged <- ended - if (!converged) q$rebuild(psi, levels[length(levels)], tol) - fit <- .quadratureResult(design, q, psi, fixed, length(rows), converged, - do.call(rbind, rows), exact) + if (!identical(best, last)) q$restore(best$snapshot) + fit <- .quadratureResult(design, q, best$psi, fixed, length(rows), reason != "iterlim", + do.call(rbind, rows), exact, reason) if (!isFALSE(qc$certificate)) - fit$certificate <- .quadratureCertificate(design, q, psi, fixed, qc$certificate %||% list(), tol) + fit$certificate <- .quadratureCertificate(design, q, best$psi, fixed, qc$certificate %||% list(), tol) fit } @@ -547,6 +617,7 @@ 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]], @@ -561,7 +632,7 @@ se <- stats::sd(perShift) / sqrt(shifts) / est data.frame(group = design$groups[i], level = st$levels[i], quadrature = -2 * quad[i], importance = -2 * (mx + log(est)), se = 2 * se, khat = .paretoShape(lw), - levelError = levelError[i]) + levelError = levelError[i], capped = isTRUE(st$capped[i])) }) out <- do.call(rbind, rows) allowed <- pmax(if (is.finite(tol)) tol / nrow(out) else 0, out$levelError, na.rm = TRUE) diff --git a/R/nlmeSaem.R b/R/nlmeSaem.R index 5e2f7cd5..916fb868 100644 --- a/R/nlmeSaem.R +++ b/R/nlmeSaem.R @@ -17,9 +17,9 @@ else stats::pnorm(-w[censored], log.p = TRUE)) } -## -2 log p(y_g, eta_g) of every group at the rows of `eta`, the value of the FOCEI kernel per -## group: the data term of every condition in one evaluation without derivatives, in C++ where the -## model allows it, else from the predictions and the row losses in R. +## -2 log p(y_g, eta_g) of every group at the rows of `eta`, as the FOCEI kernel per group, all +## conditions in one evaluation without derivatives; with `full` a list of parameter vectors, one +## column per vector. .groupDensity <- function(design, meta, fixed, cores = 1L) { errfn <- .errorModel(design) node <- .fnNode(errfn) @@ -28,19 +28,18 @@ conditions <- vapply(blocks, function(b) as.character(b$condition), "") times <- lapply(blocks, `[[`, "times") etaNames <- lapply(meta$fast_meta, `[[`, "eta_names") - dataTerm <- function(parsList) { - d <- .chainLocal(design$chain, conditions, parsList, rep(list(fixed), length(parsList)), FALSE, FALSE, cores, - design$bloq, design$df) + G <- length(etaNames) + dataTerm <- function(parsList, n) { + d <- .chainLocal(design$chain, rep(conditions, n), parsList, rep(list(fixed), length(parsList)), FALSE, FALSE, + cores, design$bloq, design$df) if (is.null(d)) return(NULL) v <- vapply(d, function(x) as.numeric(x$value), 0) - vapply(seq_along(etaNames), function(g) sum(v[group == g]), 0) + matrix(rowsum(v, rep(group, n) + G * rep(seq_len(n) - 1L, each = length(group)), reorder = TRUE), G, n) } - function(full, eta, Oinv, logDet) { + one <- function(full, eta) { parsList <- lapply(seq_along(blocks), function(j) { p <- full; p[etaNames[[group[j]]]] <- eta[group[j], ]; p }) - value <- dataTerm(parsList) - if (!is.null(value)) return(value + rowSums((eta %*% Oinv) * eta) + logDet) preds <- .predictMany(design$prdfn, times = times, parsList = parsList, conditions = conditions, fixed = fixed, deriv = FALSE, cores = cores) inner <- lapply(preds, function(q) attr(q, "parameters")) @@ -49,7 +48,7 @@ fixed = vector("list", length(preds))), FALSE, FALSE, NULL, cores) else lapply(seq_along(preds), function(j) errfn(out = preds[[j]], pars = inner[[j]], conditions = conditions[j])[[1L]])) - value <- numeric(length(etaNames)) + value <- numeric(G) for (j in seq_along(blocks)) { b <- blocks[[j]] err <- errs[[j]] %||% .dataSigmaErrfn(design$data)(out = preds[[j]], conditions = conditions[j])[[1L]] @@ -59,7 +58,17 @@ s[recorded] <- b$sigma_data[recorded] value[group[j]] <- value[group[j]] + .rowLoss(p, s, b$y_data, seq_along(p) > b$n_aloq, design$df) } - value + rowSums((eta %*% Oinv) * eta) + logDet + value + } + function(full, eta, Oinv, logDet) { + many <- is.list(full) + sets <- if (many) full else list(full) + parsList <- unlist(lapply(sets, function(f) lapply(seq_along(blocks), function(j) { + p <- f; p[etaNames[[group[j]]]] <- eta[group[j], ]; p + })), recursive = FALSE) + value <- dataTerm(parsList, length(sets)) %||% vapply(sets, one, numeric(G), eta = eta) + value <- matrix(value, G) + rowSums((eta %*% Oinv) * eta) + logDet + if (many) value else value[, 1] } } @@ -221,23 +230,13 @@ .fitSaem <- function(design, start, fixed, control = list(), verbose = FALSE) { lay <- design$normal - sc <- control$saem %||% list() - maxBurnin <- sc$nBurnin %||% 200L - maxAveraging <- sc$nEM %||% 300L - nMcmc <- sc$nMcmc %||% 3L - nLaplace <- sc$nLaplace %||% 3L - laplaceEvery <- sc$laplaceEvery %||% 5L - laplaceScale <- sc$laplaceScale %||% 1.5 - window <- sc$window %||% 25L - mcTol <- sc$mcTol %||% 0.05 + saem <- .saemSettings(control) cores <- getOption("dMod2.cores", 1L) E <- design$etaNames[, lay$stems, drop = FALSE] G <- nrow(E); K <- ncol(E) meta <- .foceiMeta(design, start, fixed) .requireM3(design, meta, "SAEM") quad <- modifyList(control, control$quadrature %||% list()) - cm1 <- .trustControl(list(rinit = 1, rmax = 10, iterlim = 1, tolControl = list(ftol = 1e-6, mtol = 1e-6)), - sc$cm1Control, label = "cm1Control") # phi = eta + D_g beta held while beta moves, for the random intercepts with X constant in the # groups: GLS for those of .muReference(), the trust step for those whose symbol also enters @@ -247,18 +246,14 @@ groupedDesign$data <- design$data[grouped] ref <- .muReference(groupedDesign) gls <- names(.muReference(design)) - refPars <- unlist(lapply(unname(ref), `[[`, "pars")) + refs <- .referenceMatrices(design, ref, E) + refPars <- refs$refPars + D <- refs$D + shift <- refs$shift free <- .intersect(unlist(lapply(unname(ref[gls]), `[[`, "pars")), names(start)) structural <- .setdiff(names(start), lay$cholPars) trustPars <- .setdiff(structural, free) partial <- .intersect(trustPars, refPars) - D <- lapply(design$groups, function(g) { - m <- matrix(0, K, length(refPars), dimnames = list(lay$stems, refPars)) - for (e in ref) m[e$stem, e$pars] <- e$X[g, ] - m - }) - shift <- function(beta) matrix(vapply(D, function(m) drop(m %*% beta[refPars]), numeric(K)), G, K, - byrow = TRUE, dimnames = dimnames(E)) # Omega and the GLS beta that maximize the expected prior given the averages s1 of phi_g and # s2 of phi_g phi_g' / G; the diagonal of S at least `minVar` while annealing mStep <- function(s1, s2, beta, minVar = NULL) { @@ -333,7 +328,7 @@ beta <- c(start, fixed)[refPars] step <- rep(0.4, G) modePhi <- im$modes + shift(beta) - factors <- .proposalFactors(im$H, laplaceScale) + factors <- .proposalFactors(im$H, saem$laplaceScale) s1 <- s2 <- phi <- NULL psi <- start history <- matrix(NA_real_, 0, length(start), dimnames = list(NULL, names(start))) @@ -341,24 +336,24 @@ rows <- list() burnin <- TRUE; burnEnd <- NA_integer_; stationary <- FALSE info <- NULL; mcGap <- NA_real_; q <- NULL; model <- NULL - for (k in seq_len(maxBurnin + maxAveraging)) { + for (k in seq_len(saem$nBurnin + saem$nEM)) { gamma <- if (burnin) 1 else (k - burnEnd)^-0.7 L <- .choleskyFactor(lay, c(full, fixed)) Oinv <- chol2inv(t(L)); logDet <- 2 * sum(log(diag(L))) target <- function(e) density(full, e, Oinv, logDet) # a state where the model fails takes any proposal it can evaluate value <- tryCatch(target(eta), error = function(e) rep(Inf, G)) - rw <- .metropolisGroups(target, eta, value, nMcmc, step = step) + rw <- .metropolisGroups(target, eta, value, saem$nMcmc, step = step) eta <- rw$eta - if (nLaplace > 0L) { + if (saem$nLaplace > 0L) { # where the modes cannot be refreshed the previous proposal stays, MH is exact either way - im <- if (k > 1L && (k - 1L) %% laplaceEvery == 0L) + im <- if (k > 1L && (k - 1L) %% saem$laplaceEvery == 0L) tryCatch(.innerModes(design, c(full[names(start)], fixed), eta, fixed, meta), error = function(e) NULL) if (!is.null(im)) { modePhi <- im$modes + shift(beta) - factors <- .proposalFactors(im$H, laplaceScale) + factors <- .proposalFactors(im$H, saem$laplaceScale) } - lap <- .metropolisGroups(target, eta, rw$value, nLaplace, modes = modePhi - shift(beta), chol = factors) + lap <- .metropolisGroups(target, eta, rw$value, saem$nLaplace, modes = modePhi - shift(beta), chol = factors) eta <- lap$eta } if (burnin) step <- pmin(pmax(step * exp(0.3 * (rw$accept - 0.4)), 0.02), 5) @@ -377,7 +372,7 @@ # model of the complete-data objective # where the complete-data objective fails at the draws, the trust parameters keep their values if (length(trustPars) && burnin) { - cm <- tryCatch(.innerTrust(modifyList(cm1, list(objfun = cm1Objective, parinit = full[trustPars]))), + cm <- tryCatch(.innerTrust(modifyList(saem$cm1, list(objfun = cm1Objective, parinit = full[trustPars]))), error = function(e) NULL) if (!is.null(cm)) full[trustPars] <- cm$argument } @@ -400,9 +395,8 @@ history <- rbind(history, psi) if (burnin) { - stationary <- k >= window && - all(abs(.slopeStatistics(utils::tail(history, window))) < 2) - if (stationary || k >= maxBurnin) { + stationary <- k >= saem$window && all(abs(.slopeStatistics(utils::tail(history, saem$window))) < 2) + if (stationary || k >= saem$nBurnin) { burnin <- FALSE; burnEnd <- k q <- .quadratureObjective(design, psi, fixed, quad) q$state$modes <- eta @@ -419,9 +413,9 @@ if (length(trustPars)) draw[trustPars] <- one$trust targets <- rbind(targets, draw) n <- k - burnEnd - Ic <- if (n >= 2L * window && n %% 10L == 0L) tryCatch(completeInformation(), error = function(e) NULL) + Ic <- if (n >= 2L * saem$window && n %% 10L == 0L) tryCatch(completeInformation(), error = function(e) NULL) if (!is.null(Ic)) - mcGap <- .monteCarloGap(info, Ic, .batchMeansCov(targets[-seq_len(window), , drop = FALSE])) + mcGap <- .monteCarloGap(info, Ic, .batchMeansCov(targets[-seq_len(saem$window), , drop = FALSE])) } rows[[k]] <- data.frame(iter = k, phase = if (is.na(burnEnd) || k <= burnEnd) "burnin" else "averaging", gamma = gamma, deltaPsi = max(abs(psi - prev)), @@ -429,62 +423,200 @@ accept = mean(rw$accept), mcGap = mcGap) if (verbose && k %% 50L == 0L) message(sprintf("em(saem) iteration %d, %s", k, rows[[k]]$phase)) - if (!is.na(mcGap) && mcGap <= mcTol) break + if (!is.na(mcGap) && mcGap <= saem$mcTol) break } trace <- do.call(rbind, rows) - if (!is.na(burnEnd) && nrow(history) > burnEnd + window) - psi <- colMeans(history[(burnEnd + window + 1L):nrow(history), , drop = FALSE]) + if (!is.na(burnEnd) && nrow(history) > burnEnd + saem$window) + psi <- colMeans(history[(burnEnd + saem$window + 1L):nrow(history), , drop = FALSE]) q <- q %||% .quadratureObjective(design, psi, fixed, quad) q$state$modes <- eta q$rebuild(psi, K + 2L) - converged <- stationary && !is.na(mcGap) && mcGap <= mcTol + converged <- stationary && !is.na(mcGap) && mcGap <= saem$mcTol .quadratureResult(design, q, psi, fixed, nrow(trace), converged, trace) } -## SAEM with Dirichlet-process random effects, normal ones beside them: Metropolis and Gibbs draws, -## Robbins-Monro statistics with closed-form M-steps, the structural parameters on the averaged -## quadratic model; -2 log L by importance sampling, the clusters the most frequent late partition. -.fitSaemDirichlet <- function(design, start, fixed, control = list(), verbose = FALSE) { +## ---- spike-and-slab random effects --------------------------------------------------------- + +## The quadratic model of the data -2 log L of every group in the spike-and-slab coordinates `at` +## (G x J names) at the values `ref`: exact gradient and the curvature of the objective at `pars` +## with `at` set to `ref`. +.slabModel <- function(design, objs, pars, at, ref) { + G <- nrow(at) + out <- .groupData(design, objs, lapply(seq_len(G), function(g) { p <- pars[[g]]; p[at[g, ]] <- ref[g, ]; p })) + grad <- t(vapply(seq_len(G), function(g) .named(out[[g]]$gradient, at[g, ]), numeric(ncol(at)))) + if (ncol(at) == 1L) grad <- t(grad) + if (any(!is.finite(grad))) return(NULL) + H <- lapply(seq_len(G), function(g) .namedHessian(out[[g]]$hessian, at[g, ])) + if (any(!is.finite(unlist(H)))) return(NULL) + # the curvature with negative eigenvalues set to 0, so every subset has a Gaussian + H <- lapply(H, function(h) { + e <- eigen((h + t(h)) / 2, symmetric = TRUE) + structure(e$vectors %*% (t(e$vectors) * pmax(e$values, 0)), dimnames = dimnames(h)) + }) + list(ref = ref, grad = grad, H = H) +} + +## 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) { + 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] + 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) { + G <- nrow(V); J <- ncol(V) + go <- !is.na(j) + base <- V; dir <- matrix(0, G, J); m <- sd <- rep(NA_real_, G) + # a group whose local model has no Gaussian along the line does not move + for (g in which(go)) tryCatch({ + i <- j[g] + o <- which(Z[g, ] & seq_len(J) != i) + 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 + if (!(s > 0)) stop("no curvature") + m[g] <- -(grad[i] + sum(B * grad[o])) / s + sd[g] <- sqrt(2 / s) + }, error = function(e) go[g] <<- FALSE) + 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) + ig <- cbind(seq_len(G), ifelse(go, j, 1L)) + # log p(y, eta) of a group on the line at x from the data term d, with the prior of every + # coordinate of the group + lp1 <- matrix(log(prob), G, J, byrow = TRUE); lp0 <- matrix(log1p(-prob), G, J, byrow = TRUE) + sdSlab <- matrix(tau, G, J, byrow = TRUE) + 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 + ifelse(go, out, NA_real_) + } + # the data term on the line at the columns of `x`, all in one evaluation; where that fails each + # column alone, a failed column Inf + 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), + 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)) + d0 <- ifelse(inSlab, d[, 1], value) + lf0 <- logF(numeric(G), 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) + }, numeric(G)) + sp <- sd * sqrt(scale) + lw <- matrix(lw, G) + 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)) + 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) + 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) + for (g in which(ok)) { + out$V[g, ] <- base[g, ] + xNew[g] * dir[g, ] + out$Z[g, j[g]] <- slabNew[g] + out$value[g] <- dNew[g] + } + # a proposed change of the indicator: TRUE a birth, FALSE a death + out$birth <- ifelse(go & slabNew != inSlab, slabNew, NA) + out$ok <- ok + out$pinc <- pinc + out$slab2 <- ifelse(go, pinc * ifelse(is.finite(m2), m2, 0), NA) + out +} + +## A random-walk Metropolis step on all slab values of every group where the indicator is set, of +## size `step` per group times `sd` per coordinate; the acceptance per group. +.slabWalk <- function(V, Z, value, dataAt, tau, step, sd) { + 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) + ok <- rowSums(Z) > 0 & is.finite(pv) & + log(stats::runif(G)) < (value - pv) / 2 - rowSums((prop^2 - V^2) / (2 * t2)) + V[ok, ] <- prop[ok, ] + value[ok] <- pv[ok] + list(V = V, value = value, accept = ok) +} + + +## SAEM with spike-and-slab and Dirichlet-process random effects, normal ones beside them; the +## estimate is the mean of the late iterates, the selected effects and clusters come from the late +## draws. +.fitSaemSparse <- function(design, start, fixed, control = list(), verbose = FALSE) { lay <- design$normal sl <- .sparseLayout(design) - if (any(sl$dist != "dirichletProcess")) - stop("em: method = \"saem\" takes normal and Dirichlet-process random effects.", call. = FALSE) - sc <- control$saem %||% list() - maxBurnin <- sc$nBurnin %||% 200L - maxAveraging <- sc$nEM %||% 300L - nMcmc <- sc$nMcmc %||% 3L - window <- sc$window %||% 25L + saem <- .saemSettings(control) + gh <- .hermiteNodes(saem$nodes) cores <- getOption("dMod2.cores", 1L) E <- design$etaNames[, lay$stems, drop = FALSE] Dp <- design$etaNames[, sl$stem, drop = FALSE] G <- nrow(Dp); K <- ncol(E) + dpStems <- sl$stem[sl$dist == "dirichletProcess"] + slabStems <- sl$stem[sl$dist == "spikeSlab"] + # -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")) hypers <- .intersect(.sparseHypers(sl), names(start)) + off <- .intersect(attr(.extraObjective(design), "parameters"), c(.sparseHypers(sl), as.vector(design$etaNames))) + if (length(off)) + stop("em: with spike-and-slab or Dirichlet-process random effects the terms beside the data ", + "take the fixed effects only; ", paste(off, collapse = ", "), " are hyperparameters or random effects.", + call. = FALSE) outer <- start[.setdiff(names(start), hypers)] meta <- .foceiMeta(design, c(outer, setNames(numeric(length(Dp)), as.vector(Dp))), fixed) .requireM3(design, meta, "SAEM") - full <- setNames(numeric(length(meta$pars_full_names)), meta$pars_full_names) - full[names(outer)] <- outer - hyper <- start[hypers] + chain <- list(full = setNames(numeric(length(meta$pars_full_names)), meta$pars_full_names), hyper = start[hypers]) + chain$full[names(outer)] <- outer # phi = eta + D_g beta held while the mu-referenced fixed effects move, those by GLS where their # symbol enters no condition outside the groups; the other structural parameters by trust ref <- .muReference(design) free <- .intersect(unlist(lapply(unname(ref), `[[`, "pars")), names(outer)) - refPars <- unlist(lapply(unname(ref), `[[`, "pars")) - D <- lapply(design$groups, function(g) { - m <- matrix(0, K, length(refPars), dimnames = list(lay$stems, refPars)) - for (e in ref) m[e$stem, e$pars] <- e$X[g, ] - m - }) - shift <- function(beta) matrix(vapply(D, function(m) drop(m %*% beta[refPars]), numeric(K)), G, K, - byrow = TRUE, dimnames = dimnames(E)) + refs <- .referenceMatrices(design, ref, E) structural <- .setdiff(names(outer), c(lay$cholPars, free)) density <- .groupDensity(design, meta, fixed, cores) objPars <- attr(design$objfn, "parameters") - cm1 <- .trustControl(list(rinit = 1, rmax = 10, iterlim = 1, tolControl = list(ftol = 1e-6, mtol = 1e-6)), - sc$cm1Control, label = "cm1Control") - # the complete-data -2 log L of the structural parameters at the drawn etas - cm1Objective <- function(theta, ...) { + # the complete-data -2 log L of the structural parameters at the parameters `full` and the drawn etas `eta` + completeData <- function(full, eta) function(theta, ...) { p <- full; p[structural] <- theta p[as.vector(E)] <- as.vector(eta) active <- .intersect(structural, objPars) @@ -494,106 +626,80 @@ hessian = .namedHessian(out$hessian, structural)) } - # every group starts in a separate cluster at the group mode under the slab alone, so the sampler - # merges clusters rather than finding deviations by draws from the slab + # every group starts in the slab and in a separate cluster at the group mode under the slab + # alone, so the sampler removes deviations rather than finding them by draws from the slab; a + # fit as init gives the start instead: the selected values, 0 in the spike, clusters by value objs <- .conditionObjectives(design) prior <- if (K) .normalPrior(design) - start0 <- matrix(0, G, ncol(design$etaNames), dimnames = dimnames(design$etaNames)) - mode0 <- .sparseModes(design, objs, prior, c(outer, fixed), .stemHypers(sl, c(hyper, fixed)), start0, - list(iterlim = 300L)) - state <- lapply(setNames(nm = sl$stem), function(st) list(z = seq_len(G), v = unname(mode0[, st]))) - for (st in sl$stem) full[Dp[, st]] <- mode0[, st] - eta <- mode0[, lay$stems, drop = FALSE] - step <- rep(0.4, G) - valueStep <- setNames(rep(0.3, nrow(sl)), sl$stem) - beta <- c(outer, fixed)[refPars] - s1 <- s2 <- NULL - stats <- NULL - blocks <- Filter(function(b) b$dist == "dirichletProcess", design$blocks) - psiOf <- function() c(full[names(outer)], hyper)[names(start)] + En <- design$etaNames + fitsDesign <- function(m) is.matrix(m) && all(rownames(En) %in% rownames(m)) && all(colnames(En) %in% colnames(m)) + selected0 <- if (fitsDesign(control$selected)) control$selected[rownames(En), colnames(En), drop = FALSE] + start0 <- if (fitsDesign(control$modes)) control$modes[rownames(En), colnames(En), drop = FALSE] + else matrix(0, G, ncol(En), dimnames = dimnames(En)) + mode0 <- .sparseModes(design, c(outer, fixed), .stemHypers(sl, c(chain$hyper, fixed)), start0, list(iterlim = 300L)) + if (!is.null(selected0)) mode0[, sl$stem] <- selected0[, sl$stem] + chain$state <- lapply(setNames(nm = dpStems), function(st) { + if (is.null(selected0)) return(list(z = seq_len(G), v = unname(mode0[, st]))) + v <- unique(mode0[mode0[, st] != 0, st]) + list(z = match(mode0[, st], v, nomatch = 0L), v = unname(v)) + }) + 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) + 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$slabStep <- rep(0.5, G) + chain$eta <- mode0[, lay$stems, drop = FALSE] + chain$step <- rep(0.4, G) + chain$valueStep <- setNames(rep(0.3, length(dpStems)), dpStems) + chain$beta <- c(outer, fixed)[refs$refPars] + blocks <- Filter(function(b) b$dist != "normal", design$blocks) + psiOf <- function() c(chain$full[names(outer)], chain$hyper)[names(start)] history <- matrix(NA_real_, 0, length(start), dimnames = list(NULL, names(start))) draws <- list() rows <- list() - burnin <- TRUE; burnEnd <- NA_integer_; stationary <- FALSE; model <- NULL - for (k in seq_len(maxBurnin + maxAveraging)) { + burnin <- TRUE; burnEnd <- NA_integer_; stationary <- FALSE + for (k in seq_len(saem$nBurnin + saem$nEM)) { gamma <- if (burnin) 1 else (k - burnEnd)^-0.7 - L <- if (K) .choleskyFactor(lay, c(full, fixed)) + L <- if (K) .choleskyFactor(lay, c(chain$full, fixed)) Oinv <- if (K) chol2inv(t(L)) else matrix(0, 0, 0) logDet <- if (K) 2 * sum(log(diag(L))) else 0 - hyp <- .stemHypers(sl, c(hyper, fixed)) + hyp <- .stemHypers(sl, c(chain$hyper, fixed)) accept <- NA_real_ + moves <- c(birth = NA_real_, death = NA_real_, walk = NA_real_) if (K) { - rw <- .metropolisGroups(function(e) density(full, e, Oinv, logDet), eta, - tryCatch(density(full, eta, Oinv, logDet), error = function(e) rep(Inf, nrow(eta))), - nMcmc, step = step) - eta <- rw$eta - accept <- mean(rw$accept) - if (burnin) step <- pmin(pmax(step * exp(0.3 * (rw$accept - 0.4)), 0.02), 5) + walk <- .saemNormalWalk(density, chain$full, chain$eta, Oinv, logDet, saem$nMcmc, chain$step, burnin) + chain$eta <- walk$eta + chain$step <- walk$step + accept <- walk$accept } - for (st in sl$stem) { - at <- Dp[, st] - dataAt <- function(v) { f <- full; f[at] <- v; density(f, eta, Oinv, logDet) } - state[[st]] <- .dpGibbs(state[[st]], dataAt, hyp$concentration[[st]], hyp$tau[[st]]) - mv <- .dpValues(state[[st]], dataAt, hyp$tau[[st]], valueStep[[st]]) - state[[st]] <- mv$s - if (burnin && !is.na(mv$accept)) - valueStep[[st]] <- min(max(valueStep[[st]] * exp(0.3 * (mv$accept - 0.4)), 0.01), 5) - full[at] <- c(0, state[[st]]$v)[state[[st]]$z + 1L] - } - - # A-step and M-steps: Omega and the GLS fixed effects on the averages of phi, then per block - # the slab sd and the concentration - if (K) { - phi <- eta + shift(beta) - s1 <- if (is.null(s1)) phi else s1 + gamma * (phi - s1) - s2 <- if (is.null(s2)) crossprod(phi) / G else s2 + gamma * (crossprod(phi) / G - s2) - for (it in 1:3) { - sh <- shift(beta) - S <- s2 - (crossprod(sh, s1) + crossprod(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)) - full[held] <- chol[held] - if (!length(free)) break - beta[free] <- .glsFixedEffects(ref, s1, tcrossprod(.choleskyFactor(lay, c(full, fixed))), beta, free) - } - full[free] <- beta[free] - eta <- phi - shift(beta) - } - cur <- vapply(blocks, function(b) c(free = sum(vapply(b$stems, function(st) length(state[[st]]$v), 0)), - slab2 = sum(vapply(b$stems, function(st) sum(state[[st]]$v^2), 0))), - numeric(2)) - stats <- if (is.null(stats)) cur else stats + gamma * (cur - stats) - # while annealing the slab and the concentration change by a factor of at most 0.95 to 1.25 - # per iteration, so one sweep cannot drive them to a limit - bound <- function(new, old) if (burnin) min(max(new, 0.95 * old), 1.25 * old) else new - for (j in seq_along(blocks)) { - b <- blocks[[j]] - tn <- b$hyper[["tau"]]; cn <- b$hyper[["concentration"]] - if (tn %in% hypers && stats["free", j] > 1e-8) - hyper[[tn]] <- bound(sqrt(stats["slab2", j] / stats["free", j]), hyper[[tn]]) - if (cn %in% hypers) - hyper[[cn]] <- bound(.ewensConcentration(stats["free", j], rep(G, length(b$stems))), hyper[[cn]]) - } - # where the complete-data objective fails at the draws, the structural parameters keep their values - if (length(structural) && burnin) { - cm <- tryCatch(.innerTrust(modifyList(cm1, list(objfun = cm1Objective, parinit = full[structural]))), - error = function(e) NULL) - if (!is.null(cm)) full[structural] <- cm$argument - } - out <- if (length(structural) && !burnin) tryCatch(cm1Objective(full[structural]), error = function(e) NULL) - if (!is.null(out)) { - model <- .averageQuadratic(if (gamma < 1) model, out, full[structural], gamma) - full[structural] <- .quadraticStep(model, full[structural]) + 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) + chain <- slabs$chain + moves <- slabs$moves } + if (K) chain <- .saemNormalStep(chain, design, ref, free, refs, outer, fixed, L, gamma, burnin) + chain <- .saemHyperStep(chain, blocks, slabStems, reach, hypers, G, gamma, burnin) + chain <- .saemStructuralStep(chain, completeData(chain$full, chain$eta), structural, saem$cm1, gamma, burnin) prev <- if (nrow(history)) history[nrow(history), ] else psiOf() psi <- psiOf() history <- rbind(history, psi) - if (!burnin) draws[[length(draws) + 1L]] <- lapply(state, .canonicalClusters) - + if (!burnin) draws[[length(draws) + 1L]] <- list(dp = lapply(chain$state, .canonicalClusters), incl = chain$incl, + pinc = if (length(slabStems)) chain$rbIncl, + v = matrix(chain$full[Ds], G, dimnames = dimnames(Ds))) if (burnin) { - stationary <- k >= window && all(abs(.slopeStatistics(utils::tail(history, window))) < 2) - if (stationary || k >= maxBurnin) { + stationary <- k >= saem$window && all(abs(.slopeStatistics(utils::tail(history, saem$window))) < 2) + if (stationary || k >= saem$nBurnin) { burnin <- FALSE; burnEnd <- k if (verbose) message(sprintf("em(saem) burn-in ends at iteration %d", k)) } @@ -601,38 +707,258 @@ rows[[k]] <- data.frame(iter = k, phase = if (is.na(burnEnd) || k <= burnEnd) "burnin" else "averaging", gamma = gamma, deltaPsi = if (length(psi)) max(abs(psi - prev)) else 0, deltaStruct = if (length(structural)) max(abs(psi[structural] - prev[structural])) else 0, - accept = accept, clusters = sum(vapply(state, function(s) length(s$v), 0))) + accept = accept, clusters = sum(vapply(chain$state, function(s) length(s$v), 0)), + included = sum(chain$incl), acceptBirth = moves[["birth"]], acceptDeath = moves[["death"]], + acceptWalk = moves[["walk"]]) if (verbose && k %% 50L == 0L) message(sprintf("em(saem) iteration %d, %s", k, rows[[k]]$phase)) - if (!burnin && k - burnEnd >= maxAveraging) break + if (!burnin && k - burnEnd >= saem$nEM) break } trace <- do.call(rbind, rows) - late <- if (!is.na(burnEnd) && nrow(history) > burnEnd + window) (burnEnd + window + 1L):nrow(history) + late <- if (!is.na(burnEnd) && nrow(history) > burnEnd + saem$window) (burnEnd + saem$window + 1L):nrow(history) else seq_len(nrow(history)) psi <- colMeans(history[late, , drop = FALSE]) - full[names(outer)] <- psi[names(outer)] - hyper[] <- psi[hypers] + chain$full[names(outer)] <- psi[names(outer)] + chain$hyper[] <- psi[hypers] - # the most frequent partition of every stem in the late draws, the cluster values averaged over - # the draws with that partition, and the share of draws at the population value per group 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) + # -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) + list(eta = unname(design$etaNames[g, reachAll[g, ]]), conditions = design$conditions[[g]])) + derivMode <- .secondOrderMode(design, design$objfn, chain$full[names(outer)], fixed, + control[.setdiff(names(control), "secondOrderCorrection")], units = units) + integral <- if (importance) list(integral = "importance", particles = saem$particles) + r <- .sparseMarginal(design, objs, prior, c(chain$full[names(outer)], fixed), .stemHypers(sl, c(chain$hyper, fixed)), + as.character(.intersect(names(outer), names(start))), character(0), fixed, picked$modes, + grad = FALSE, control = c(integral, list(iterlim = 300L, derivMode = derivMode))) + modes <- picked$modes + modes[, lay$stems] <- r$modes[, lay$stems] + list(argument = psi, value = r$value, valueSE = if (importance) r$valueSE, gradient = NULL, hessian = NULL, + etaModes = modes, innerModes = r$modes, etaCov = setNames(r$cov, design$groups), clusters = picked$clusters, + spike = picked$spike, converged = stationary, iterations = nrow(trace), stageTrace = trace) +} + +## The settings of SAEM, `control$saem` with the defaults, and in `cm1` the trust settings of the Newton steps +## of the parameters outside the closed-form M-steps. +.saemSettings <- function(control) { + sc <- control$saem %||% list() + list(nBurnin = sc$nBurnin %||% 200L, nEM = sc$nEM %||% 300L, nMcmc = sc$nMcmc %||% 3L, + nLaplace = sc$nLaplace %||% 3L, laplaceEvery = sc$laplaceEvery %||% 5L, + laplaceScale = sc$laplaceScale %||% 1.5, window = sc$window %||% 25L, mcTol = sc$mcTol %||% 0.05, + nFlip = sc$nFlip %||% 1L, nodes = sc$nodes %||% 3L, particles = sc$particles %||% 500L, + integral = sc$integral, + cm1 = .trustControl(list(rinit = 1, rmax = 10, iterlim = 1, tolControl = list(ftol = 1e-6, mtol = 1e-6)), + sc$cm1Control, label = "cm1Control")) +} + +## The mu-referenced fixed effects `ref` on the etas `E`: their names, per group the matrix D_g, and +## shift(beta), the G x K matrix of the shifts D_g beta. +.referenceMatrices <- function(design, ref, E) { + refPars <- unlist(lapply(unname(ref), `[[`, "pars")) + K <- ncol(E) + D <- lapply(design$groups, function(g) { + m <- matrix(0, K, length(refPars), dimnames = list(colnames(E), refPars)) + for (e in ref) m[e$stem, e$pars] <- e$X[g, ] + m + }) + shift <- function(beta) matrix(vapply(D, function(m) drop(m %*% beta[refPars]), numeric(K)), nrow(E), K, + byrow = TRUE, dimnames = dimnames(E)) + list(refPars = refPars, D = D, shift = shift) +} + +## Random-walk Metropolis steps on the normal etas of all groups, the step sizes adapted while annealing. +.saemNormalWalk <- function(density, full, eta, Oinv, logDet, n, step, burnin) { + current <- tryCatch(density(full, eta, Oinv, logDet), error = function(e) rep(Inf, nrow(eta))) + rw <- .metropolisGroups(function(e) density(full, e, Oinv, logDet), eta, current, n, step = step) + if (burnin) step <- pmin(pmax(step * exp(0.3 * (rw$accept - 0.4)), 0.02), 5) + list(eta = rw$eta, accept = mean(rw$accept), step = step) +} + +## Per Dirichlet-process stem a Gibbs sweep over the clusters and random-walk steps on the cluster values, the +## step sizes adapted while annealing; `chain$full` takes the values of the drawn clusters. +.saemClusterSweep <- function(chain, Dp, stems, density, Oinv, logDet, hyp, burnin) { + full <- chain$full + for (st in stems) { + at <- Dp[, st] + dataAt <- function(v) { f <- full; f[at] <- v; density(f, chain$eta, Oinv, logDet) } + chain$state[[st]] <- .dpGibbs(chain$state[[st]], dataAt, hyp$concentration[[st]], hyp$tau[[st]]) + mv <- .dpValues(chain$state[[st]], dataAt, hyp$tau[[st]], chain$valueStep[[st]]) + chain$state[[st]] <- mv$s + if (burnin && !is.na(mv$accept)) + chain$valueStep[[st]] <- min(max(chain$valueStep[[st]] * exp(0.3 * (mv$accept - 0.4)), 0.01), 5) + full[at] <- c(0, chain$state[[st]]$v)[chain$state[[st]]$z + 1L] + } + chain$full <- full + chain +} + +## The indicators and slab values against proposals from the local models, which stay where they cannot be +## 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) { + G <- nrow(Ds) + tauS <- hyp$tau[slabStems]; probS <- hyp$prob[slabStems] + groupPars <- function() lapply(seq_len(G), function(g) { + p <- chain$full; p[names(fixed)] <- fixed; p[E[g, ]] <- chain$eta[g, ]; p + }) + local <- tryCatch(.slabModel(design, objs, groupPars(), Ds, chain$slabRef), error = function(e) NULL) + if (!is.null(local)) { + chain$slabProp <- local + # 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), + error = function(e) chain$slabRef[g, ]) + } + chain$slabProp <- chain$slabProp %||% + list(ref = 0 * chain$slabRef, grad = 0 * chain$slabRef, H = rep(list(diag(0, ncol(Ds))), G)) + model <- chain$slabProp + V <- matrix(chain$full[Ds], G) + blockAt <- function(x) { + set <- function(v) { f <- chain$full; f[Ds] <- v; f } + density(if (is.list(x)) lapply(x, set) else set(x), chain$eta, Oinv, logDet) + } + value <- tryCatch(blockAt(V), error = function(e) rep(Inf, G)) + # the conditional standard deviations of the local model, the scales of the random walk + 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 + tried <- c(birth = 0, death = 0); taken <- tried + rbIncl <- rbSlab2 <- rbCount <- matrix(0, G, ncol(Ds)) + for (s in seq_len(saem$nFlip)) { + # every indicator of a group once, in random order, one round over all groups per indicator + 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) + 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)) + done <- which(!is.na(fl$pinc)) + at <- cbind(done, j[done]) + rbIncl[at] <- rbIncl[at] + fl$pinc[done] + rbSlab2[at] <- rbSlab2[at] + fl$slab2[done] + rbCount[at] <- rbCount[at] + 1 + } + } + # 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) + walked <- numeric(G) + for (s in seq_len(saem$nMcmc)) { + sw <- .slabWalk(V, incl, value, blockAt, tauS, chain$slabStep, walkScale) + V <- sw$V; value <- sw$value + walked <- walked + sw$accept / saem$nMcmc + } + moves <- c(taken / tried, walk = sum(walked) / max(sum(rowSums(incl) > 0), 1)) + chain$full[Ds] <- V + chain$incl <- incl + if (burnin) + chain$slabStep <- ifelse(rowSums(incl) > 0, pmin(pmax(chain$slabStep * exp(0.3 * (walked - 0.25)), 0.01), 5), + chain$slabStep) + list(chain = chain, moves = moves) +} + +## The A-step on phi = eta + D beta and the M-steps of Omega and the GLS fixed effects on the averages of phi; +## while annealing the diagonal of S stays at least 0.95 of the current variances. +.saemNormalStep <- function(chain, design, ref, free, refs, outer, fixed, L, gamma, burnin) { + G <- nrow(chain$eta) + phi <- chain$eta + refs$shift(chain$beta) + chain$s1 <- if (is.null(chain$s1)) phi else chain$s1 + gamma * (phi - chain$s1) + chain$s2 <- if (is.null(chain$s2)) crossprod(phi) / G else chain$s2 + gamma * (crossprod(phi) / G - chain$s2) + for (it in 1:3) { + 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] + if (!length(free)) break + Omega <- tcrossprod(.choleskyFactor(design$normal, c(chain$full, fixed))) + chain$beta[free] <- .glsFixedEffects(ref, chain$s1, Omega, chain$beta, free) + } + chain$full[free] <- chain$beta[free] + chain$eta <- phi - refs$shift(chain$beta) + chain +} + +## The averaged statistics of every sparse block (free coordinates, groups, slab second moments) and the M-steps +## of the slab sd, the concentration and the probability of a deviation; while annealing each changes by a +## factor of 0.95 to 1.25 at most per iteration, so that one sweep cannot drive it to a limit. +.saemHyperStep <- function(chain, blocks, slabStems, reach, hypers, G, gamma, burnin) { + current <- vapply(blocks, function(b) { + if (b$dist == "dirichletProcess") + return(c(free = sum(vapply(b$stems, function(st) length(chain$state[[st]]$v), 0)), groups = 0, + slab2 = sum(vapply(b$stems, function(st) sum(chain$state[[st]]$v^2), 0)))) + j <- match(b$stems, slabStems) + c(free = sum(chain$rbIncl[, j][reach[, j]]), groups = sum(reach[, j]), slab2 = sum(chain$rbSlab2[, j][reach[, j]])) + }, numeric(3)) + chain$blockStats <- if (is.null(chain$blockStats)) current else chain$blockStats + gamma * (current - chain$blockStats) + averaged <- chain$blockStats + bound <- function(new, old) if (burnin) min(max(new, 0.95 * old), 1.25 * old) else new + odds <- function(p) p / (1 - p) + for (j in seq_along(blocks)) { + b <- blocks[[j]] + tn <- unname(b$hyper["tau"]); cn <- unname(b$hyper["concentration"]); pn <- unname(b$hyper["prob"]) + if (tn %in% hypers && averaged["free", j] > 1e-8) + chain$hyper[[tn]] <- bound(sqrt(averaged["slab2", j] / averaged["free", j]), chain$hyper[[tn]]) + if (cn %in% hypers) + chain$hyper[[cn]] <- bound(.ewensConcentration(averaged["free", j], rep(G, length(b$stems))), chain$hyper[[cn]]) + if (pn %in% hypers && averaged["groups", j] > 0) { + o <- bound(odds(min(max(averaged["free", j] / averaged["groups", j], 1e-8), 1 - 1e-8)), odds(chain$hyper[[pn]])) + chain$hyper[[pn]] <- o / (1 + o) + } + } + chain +} + +## The structural parameters: a trust step on the complete-data objective at the draws while annealing, then the +## step on the averaged quadratic model; where the objective fails at the draws they keep their values. +.saemStructuralStep <- function(chain, objective, structural, cm1, gamma, burnin) { + if (!length(structural)) return(chain) + if (burnin) { + cm <- tryCatch(.innerTrust(modifyList(cm1, list(objfun = objective, parinit = chain$full[structural]))), + error = function(e) NULL) + if (!is.null(cm)) chain$full[structural] <- cm$argument + return(chain) + } + out <- tryCatch(objective(chain$full[structural]), error = function(e) NULL) + if (is.null(out)) return(chain) + chain$model <- .averageQuadratic(if (gamma < 1) chain$model, out, chain$full[structural], gamma) + chain$full[structural] <- .quadraticStep(chain$model, chain$full[structural]) + chain +} + +## 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) { + G <- nrow(design$etaNames) modes <- matrix(0, G, ncol(design$etaNames), dimnames = dimnames(design$etaNames)) - modes[, lay$stems] <- eta + modes[, design$normal$stems] <- eta clusters <- spike <- matrix(NA_real_, G, ncol(design$etaNames), dimnames = dimnames(design$etaNames)) - for (st in sl$stem) { - keys <- vapply(keep, function(d) paste(d[[st]]$z, collapse = " "), "") + for (st in dpStems) { + keys <- vapply(keep, function(d) paste(d$dp[[st]]$z, collapse = " "), "") top <- names(which.max(table(keys))) - with <- keep[keys == top] - z <- with[[1]][[st]]$z - values <- colMeans(do.call(rbind, lapply(with, function(d) d[[st]]$v)) %||% matrix(0, 1, 0)) + same <- keep[keys == top] + z <- same[[1]]$dp[[st]]$z + values <- colMeans(do.call(rbind, lapply(same, function(d) d$dp[[st]]$v)) %||% matrix(0, 1, 0)) modes[, st] <- c(0, values)[z + 1L] clusters[, st] <- z - spike[, st] <- colMeans(do.call(rbind, lapply(keep, function(d) d[[st]]$z == 0L))) + spike[, st] <- colMeans(do.call(rbind, lapply(keep, function(d) d$dp[[st]]$z == 0L))) } - r <- .sparseMarginal(design, objs, prior, c(full[names(outer)], fixed), .stemHypers(sl, c(hyper, fixed)), - as.character(.intersect(names(outer), names(start))), character(0), fixed, modes, grad = TRUE, - control = list(integral = "importance", particles = sc$particles %||% 500L, iterlim = 300L)) - modes[, lay$stems] <- r$modes[, lay$stems] - list(argument = psi, value = r$value, valueSE = r$valueSE, gradient = NULL, hessian = NULL, - etaModes = modes, etaCov = setNames(r$cov, design$groups), clusters = clusters, spike = spike, - converged = stationary, iterations = nrow(trace), stageTrace = trace) + if (length(slabStems)) { + Z <- Reduce(`+`, lapply(keep, `[[`, "incl")) + V <- Reduce(`+`, lapply(keep, function(d) d$v * d$incl)) + inclusion <- Reduce(`+`, lapply(keep, `[[`, "pinc")) / length(keep) + selected <- inclusion > 0.5 + modes[, slabStems] <- ifelse(selected & Z > 0, V / pmax(Z, 1), 0) + 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)) + } + list(modes = modes, clusters = clusters, spike = spike) } diff --git a/R/nlmeSparse.R b/R/nlmeSparse.R index 1d34a235..e15acf5e 100644 --- a/R/nlmeSparse.R +++ b/R/nlmeSparse.R @@ -74,105 +74,79 @@ ## ---- inner mode -------------------------------------------------------------------- -## The mode of the etas at `theta`, group by group, since the etas of a group enter only the group -## conditions: data -2 log L, normal prior and the slab alone, eta^2 / tau^2, per spike-and-slab -## eta, by trust. The model is differentiated in the etas of the group that reach the group data -## only, the others rest at 0; the Hessian is Gauss-Newton with a BFGS correction from the points -## that lowered the value, which adds the curvature of the residuals. A group starts from the lowest of `start` and the modes in -## `control$optima`, the optima found at earlier points, since the inner problem may have several. -## The tolerances of the outer trust region, which bound the error the solver leaves, end the search. -## With `control$phi` the value of every group at the group mode is attribute "phi". -.sparseModes <- function(design, objs, prior, theta, hyp, start, control = list()) { +## The modes of the etas at `theta` by the group kernel, the slab alone per sparse eta, etas off the group data +## at 0, each group from the lowest of `start` and `control$optima`; attributes "iterations", the inner +## iterations summed over the groups, and with `control$phi` "phi", the inner values. +.sparseModes <- function(design, theta, hyp, start, control = list()) { lay <- .sparseLayout(design) E <- design$etaNames - names <- as.vector(E) - slab <- .slabPrecision(E, lay, hyp) - modes <- matrix(as.vector(start), nrow(E), dimnames = dimnames(E)) + K <- ncol(E) reach <- .reachOf(design) - modes[!reach] <- 0 - given <- as.list(control$trustControl$tolControl) - tol <- utils::modifyList(list(ftol = 1e-10, mtol = 1e-10), - given[.intersect(c("ftol", "mtol", "gtol"), names(given))]) - phis <- setNames(rep(NA_real_, nrow(E)), rownames(E)) - for (i in seq_len(nrow(E))) { - en <- E[i, reach[i, ]] - if (!length(en)) next - conds <- design$conditions[[i]] - sl <- slab[.intersect(names(slab), en)] - # the value alone - phi <- function(eta) { - full <- c(theta, setNames(as.vector(modes), names)) - full[en] <- as.numeric(eta) - v <- sum(vapply(.objEvalMany(objs[conds], rep(list(full[en]), length(conds)), deriv = FALSE, - fixed = full[.setdiff(names(full), en)]), `[[`, 0, "value")) - if (!is.null(prior)) v <- v + prior(pars = full, deriv = FALSE)$value - if (length(sl)) v <- v + sum(sl * full[names(sl)]^2) / 2 - v - } - known <- control$optima[[i]] - if (length(known)) { - starts <- rbind(modes[i, reach[i, ]], known[, reach[i, ], drop = FALSE]) - modes[i, reach[i, ]] <- starts[which.min(vapply(seq_len(nrow(starts)), function(r) phi(starts[r, ]), 0)), ] - } - best <- Inf; bestAt <- bestGrad <- correction <- NULL - objective <- function(eta, ...) { - full <- c(theta, setNames(as.vector(modes), names)) - full[en] <- as.numeric(eta) - out <- Reduce(`+`, .objEvalMany(objs[conds], rep(list(full[en]), length(conds)), - fixed = full[.setdiff(names(full), en)])) - v <- out$value - gr <- out$gradient[en] - he <- out$hessian[en, en, drop = FALSE] - if (!is.null(prior)) { - pr <- prior(pars = full, deriv = TRUE) - nn <- .intersect(en, names(pr$gradient)) - v <- v + pr$value - gr[nn] <- gr[nn] + pr$gradient[nn] - he[nn, nn] <- he[nn, nn] + pr$hessian[nn, nn] - } - if (length(sl)) { - es <- full[names(sl)] - v <- v + sum(sl * es^2) / 2 - gr[names(sl)] <- gr[names(sl)] + sl * es - he[cbind(names(sl), names(sl))] <- he[cbind(names(sl), names(sl))] + sl - } - if (is.null(correction)) correction <<- 0 * he - # a correction from an earlier point that leaves the model at this one indefinite is dropped - if (any(correction != 0) && min(eigen(he + correction, symmetric = TRUE, only.values = TRUE)$values) <= 0) - correction <<- 0 * he - if (v < best) { - if (!is.null(bestAt)) correction <<- .secantCorrection(he, correction, eta - bestAt, gr - bestGrad) - best <<- v; bestAt <<- eta; bestGrad <<- gr - } - list(value = v, gradient = gr, hessian = he + correction) + isL <- colnames(E) %in% lay$stem + meta <- control$meta %||% .foceiMeta(design, theta, NULL, colnames(E), reach) + Pm <- matrix(0, K, K) + ld <- 0 + if (any(!isL)) { + L <- .choleskyFactor(design$normal, theta) + Pm[!isL, !isL] <- chol2inv(t(L)) + ld <- 2 * sum(log(diag(L))) + } + diag(Pm)[isL] <- 1 / hyp$tau[colnames(E)[isL]]^2 + predictor <- .guardPredictor(.batchPredictor(design)) + full <- setNames(numeric(length(meta$pars_full_names)), meta$pars_full_names) + full[names(theta)] <- theta + iterations <- 0L + run <- function(warm, iterlim) { + warm <- matrix(as.vector(warm), nrow(E)) + warm[!reach] <- 0 + k <- nlme_group_kernel(design$prdfn, .errorModel(design), full, warm, meta, Pm, ld, NULL, + list(iterlim = iterlim), predict_cb = predictor) + iterations <<- iterations + sum(k$iterations) + list(modes = matrix(as.vector(k$eta_modes), nrow(E), dimnames = dimnames(E)), phi = as.numeric(k$value)) + } + # the starts: per group the row of `start` or of an earlier optimum with the lowest value + start <- matrix(as.vector(start), nrow(E), dimnames = dimnames(E)) + depth <- max(0L, vapply(control$optima, function(o) if (is.null(o)) 0L else nrow(o), 0L)) + if (depth) { + low <- run(start, 0L)$phi + for (r in seq_len(depth)) { + cand <- start + for (i in seq_len(nrow(E))) if (!is.null(control$optima[[i]]) && nrow(control$optima[[i]]) >= r) + cand[i, ] <- control$optima[[i]][r, ] + phi <- run(cand, 0L)$phi + lower <- phi < low + start[lower, ] <- cand[lower, ] + low[lower] <- phi[lower] } - args <- list(objfun = objective, parinit = setNames(modes[i, reach[i, ]], en), rinit = 1, rmax = 10, - iterlim = control$iterlim %||% 100L, tolControl = tol) - fit <- do.call(trust, c(args, list(sparse = FALSE))) - modes[i, reach[i, ]] <- fit$argument[en] - if (isTRUE(control$phi)) phis[i] <- phi(fit$argument[en]) } - if (isTRUE(control$phi)) attr(modes, "phi") <- phis + best <- run(start, control$iterlim %||% 100L) + modes <- best$modes + modes[!reach] <- 0 + if (isTRUE(control$phi)) attr(modes, "phi") <- setNames(best$phi, rownames(E)) + attr(modes, "iterations") <- iterations modes } ## The lowest inner minimum per group at `theta` from the modes `warm`, from 0 and from `spread` ## starts around `warm`, each eta moved by `scale` times a deterministic pseudo-normal number: the ## inner problem of a group may have several minima, and every search keeps to the one it starts in. -.exploreModes <- function(design, objs, prior, theta, hyp, warm, control, scale, spread = 2L) { +.exploreModes <- function(design, theta, hyp, warm, control, scale, spread = 2L) { ctl <- utils::modifyList(control, list(phi = TRUE, optima = NULL)) - best <- .sparseModes(design, objs, prior, theta, hyp, warm, ctl) + best <- .sparseModes(design, theta, hyp, warm, ctl) low <- attr(best, "phi") + iterations <- attr(best, "iterations") n <- length(warm) for (k in 0:spread) { z <- if (k == 0L) 0 else stats::qnorm(pmin(pmax(((sin(seq_len(n) * k * 12.9898 + 78.233) * 43758.5453) %% 1), 0.01), 0.99)) start <- if (k == 0L) 0 * warm else warm + scale * matrix(z, nrow(warm)) - m <- .sparseModes(design, objs, prior, theta, hyp, start, ctl) + m <- .sparseModes(design, theta, hyp, start, ctl) + iterations <- iterations + attr(m, "iterations") lower <- !is.na(attr(m, "phi")) & (is.na(low) | attr(m, "phi") < low - 1e-6) best[lower, ] <- m[lower, ] low[lower] <- attr(m, "phi")[lower] } attr(best, "phi") <- NULL + attr(best, "iterations") <- iterations best } @@ -224,15 +198,9 @@ coupled = any(vapply(P, function(Pi) any(Pi[!within] != 0), TRUE))) } -## The integral over the sparse coordinates, I = int exp(-eta' P_i eta / 2 + b_i' eta) prod p(eta) -## per group (src/sparse_kernel.cpp), group by group where no Dirichlet-process stem joins groups: -## exact where P couples no two factors and the joint spike-and-slab sum of a group stays within -## `budget` nodes, else by the expectation consistent (EC) approximation from the sites `sites` -## where given (`ec` marks those groups). Only the coordinates of `reach` whose row of P and entry -## of b are not all 0 enter, the others keep their prior. NULL where the integral does not -## converge. log I, the moments E eta and Cov eta that the derivatives of log I in b and P are, the -## derivatives in the hyperparameters `hypers`, also per group, the reported values, clusters and -## spike probabilities and the M-step statistics. +## I = int exp(-eta' P_i eta / 2 + b_i' eta) prod p(eta) per group (src/sparse_kernel.cpp): exact within `budget` +## nodes where P couples no factors, else by EC from `sites` (`ec` marks those groups); log I, moments, hyper +## derivatives, values, clusters, spike and M-step statistics, NULL where it does not converge. .sparseIntegral <- function(P, b, lay, hyp, hypers, sites = NULL, reach = NULL, budget = .slabBudget) { G <- nrow(b); K <- ncol(b); stems <- colnames(b) r <- match(stems, lay$stem) @@ -273,14 +241,16 @@ sweeps = sp$outer) } -## The integral of Dirichlet-process stems by sequential importance sampling -## (.dirichletImportance), with the standard error of log I; the moments and derivatives of the -## mean-field result are not formed, they stay 0 or NA. +## The integral of Dirichlet-process stems, spike-and-slab ones beside them, by sequential +## importance sampling (.dirichletImportance), with the standard error of log I; the moments and +## derivatives of the mean-field result are not formed, they stay 0 or NA. .importanceField <- function(P, m, lay, hyp, hypers, particles) { G <- nrow(m); K <- ncol(m); stems <- colnames(m) - if (!all(lay$dist[match(stems, lay$stem)] == "dirichletProcess")) - stop("em: importance sampling integrates Dirichlet-process random effects only.", call. = FALSE) - is <- .dirichletImportance(P, m, hyp$concentration[stems], hyp$tau[stems], particles) + dist <- lay$dist[match(stems, lay$stem)] + if (!any(dist == "dirichletProcess")) + stop("em: importance sampling integrates Dirichlet-process random effects.", call. = FALSE) + is <- .dirichletImportance(P, m, hyp$concentration[stems], hyp$tau[stems], particles, + slab = dist == "spikeSlab", prob = hyp$prob[stems]) none <- matrix(NA_real_, G, K, dimnames = dimnames(m)) list(logI = is$logI, se = is$se, dm = 0 * m, dP = lapply(P, function(x) 0 * x), dhyper = setNames(numeric(length(hypers)), hypers), mean = none, @@ -291,283 +261,386 @@ ## ---- marginal ------------------------------------------------------------------------------ -## The approximate marginal -2 log L at `theta`: the normal etas on the quadratic model of the joint -## mode, the sparse coordinates on the Schur complement in natural parameters, P = S / 2 and -## b = (S mode - g) / 2, integrated by .sparseIntegral(); the exact gradient in `active` and -## `hypers`, a model Hessian, the moments and the selected clusters. An eta that does not reach -## the data of the group rests at 0 with the prior. With -## `scores`, the gradient split into the rows of the groups and that of the conditions without -## random effects, with their Hessian. +## The approximate marginal -2 log L at `theta`: the sparse etas integrated on the Schur complement S at the +## joint mode, P = S / 2 and b = (S mode - g) / 2; the exact gradient in `active` and `hypers`, a model Hessian, +## the moments and clusters, with `scores` the gradient per group. Etas off the group data keep the prior. .sparseMarginal <- function(design, objs, prior, theta, hyp, active, hypers, fixed, warm, grad = TRUE, control = list(), scores = FALSE) { + modes <- .sparseModes(design, theta, hyp, warm, control) + innerIterations <- attr(modes, "iterations") + attr(modes, "iterations") <- NULL + at <- .sparsePoint(design, theta, modes, identical(control$derivMode, "forward-reverse")) + terms <- .sparseTerms(design, objs, prior, at, fixed, grad) + curv <- .sparseCurvature(design, at, active, fixed) + blocks <- .sparseBlocks(at, curv, terms, fixed) + importance <- identical(control$integral, "importance") + integral <- if (importance) .sparseImportanceIntegral(at, blocks, hyp, hypers, control$particles %||% 500L) + else .sparseIntegral(lapply(blocks$schur, `/`, 2), blocks$b, at$lay, hyp, hypers, control$sites, + at$reach[, at$sparseCols, drop = FALSE]) + if (is.null(integral)) return(list(infeasible = TRUE, innerIterations = innerIterations)) + out <- .sparseMoments(at, terms, curv, blocks, integral, innerIterations) + if (!grad || importance) return(out) + + d <- .sparseGroupDerivatives(design, at, terms, curv, blocks, integral, active, fixed) + model <- .sparseModelHessian(at, blocks, integral, d) + slabPrecision <- .slabPrecision(at$E, at$lay, hyp) + diagonal <- cbind(names(slabPrecision), names(slabPrecision)) + d$etaHessian[diagonal] <- d$etaHessian[diagonal] + slabPrecision + out$value <- out$value + .modeCorrection(at, terms, d, slabPrecision) + outer <- .sparseOuterDerivatives(at, terms, blocks, integral, d, hyp, hypers, active, fixed, scores) + out$modeShift <- outer$modeShift + out$gradient <- outer$gradient + out$hessian <- model %||% outer$schur + if (scores) + out[c("scores", "freeGradient", "freeHessian")] <- + list(outer$byGroup, d$freeGradient, .freeInformation(design, objs, terms, at, active, fixed, d$freeHessian)) + out +} + +## The point of .sparseMarginal(): the layout, the normal and sparse columns of the etas, the modes and the +## full parameter vector. +.sparsePoint <- function(design, theta, modes, forwardReverse) { lay <- .sparseLayout(design) - nl <- design$normal E <- design$etaNames - G <- nrow(E); K <- ncol(E) - isL <- colnames(E) %in% lay$stem - iN <- which(!isL); iL <- which(isL) - reach <- .reachOf(design) - modes <- .sparseModes(design, objs, prior, theta, hyp, warm, control) - full <- c(theta, setNames(as.vector(modes), as.vector(E))) - # forward over reverse: the data Hessians Gauss-Newton, the exact rows and the derivatives of the - # curvature from sweeps along the etas, also for the value alone - fr <- identical(control$derivMode, "forward-reverse") - at <- .groupData(design, objs, rep(list(full), G), deriv = TRUE, deriv2 = grad && !fr) - pr <- if (!is.null(prior)) prior(pars = full, fixed = fixed, deriv = TRUE) + isSparse <- colnames(E) %in% lay$stem + list(lay = lay, normal = design$normal, E = E, G = nrow(E), K = ncol(E), normalCols = which(!isSparse), + sparseCols = which(isSparse), reach = .reachOf(design), modes = modes, + full = c(theta, setNames(as.vector(modes), as.vector(E))), forwardReverse = forwardReverse) +} + +## The data terms of the groups, the normal prior, the terms without random effects (free conditions, +## priors, constraints) and the data gradient in the etas, 0 off the group data. Under forward over reverse +## the data Hessians are Gauss-Newton. +.sparseTerms <- function(design, objs, prior, at, fixed, grad) { + deriv2 <- grad && !at$forwardReverse + groups <- .groupData(design, objs, rep(list(at$full), at$G), deriv = TRUE, deriv2 = deriv2) + normalPrior <- if (!is.null(prior)) prior(pars = at$full, fixed = fixed, deriv = TRUE) free <- if (length(design$freeConditions)) - .objEvalMany(objs[design$freeConditions], rep(list(full), length(design$freeConditions)), - deriv = TRUE, deriv2 = grad && !fr) - # the terms of the objective besides the data, priors and constraints, enter as the free conditions + .objEvalMany(objs[design$freeConditions], rep(list(at$full), length(design$freeConditions)), + deriv = TRUE, deriv2 = deriv2) extra <- .extraObjective(design) - if (!is.null(extra)) free <- c(free, list(extra(pars = full, fixed = fixed, deriv = TRUE, deriv2 = grad && !fr))) - A <- active - units <- lapply(seq_len(G), function(i) - list(eta = unname(E[i, reach[i, ]]), conditions = design$conditions[[design$groups[i]]])) - if (fr) { - fw <- .sweepForward(design, full, fixed, units) - # the curvature of a group on all etas of the group, 0 in those that do not reach the group data - cu <- .unitCurvature(design, fw, units) - curv <- lapply(seq_len(G), function(i) { - H <- matrix(0, K, K) - H[reach[i, ], reach[i, ]] <- cu[[i]] + if (!is.null(extra)) free <- c(free, list(extra(pars = at$full, fixed = fixed, deriv = TRUE, deriv2 = deriv2))) + etaGradient <- matrix(t(vapply(seq_len(at$G), function(i) groups[[i]]$gradient[at$E[i, ]], numeric(at$K))), at$G, + dimnames = dimnames(at$E)) + etaGradient[!at$reach] <- 0 + list(groups = groups, prior = normalPrior, free = free, extra = extra, etaGradient = etaGradient) +} + +## The data curvature H of every group on all etas of the group, 0 in those off the group data: from forward +## sweeps under forward over reverse, else Gauss-Newton with the derivatives dA in `active` and dE in the etas. +.sparseCurvature <- function(design, at, active, fixed) { + units <- lapply(seq_len(at$G), function(i) + list(eta = unname(at$E[i, at$reach[i, ]]), conditions = design$conditions[[design$groups[i]]])) + if (at$forwardReverse) { + forward <- .sweepForward(design, at$full, fixed, units) + perUnit <- .unitCurvature(design, forward, units) + groups <- lapply(seq_len(at$G), function(i) { + H <- matrix(0, at$K, at$K) + H[at$reach[i, ], at$reach[i, ]] <- perUnit[[i]] list(H = H) }) - } else { - conds <- unlist(design$conditions, use.names = FALSE) - times <- lapply(conds, function(cn) .emGrid(design, cn)) - preds <- setNames(.predictMany(design$prdfn, times = times, parsList = rep(list(full), length(conds)), - conditions = conds, fixed = fixed, deriv = TRUE, deriv2 = TRUE), conds) - curv <- lapply(seq_len(G), function(i) .gnCurvature(design, design$groups[i], preds, E[i, ], A, fixed)) - } - gr <- matrix(t(vapply(seq_len(G), function(i) at[[i]]$gradient[E[i, ]], numeric(K))), G, - dimnames = dimnames(E)) - gr[!reach] <- 0 - - # the normal etas: H_NN of every group with the prior precision 2 Omega^-1; the sparse block - # of `Hs` is the Schur complement of `Hs`, the curvature left once the normal etas are integrated out - cd <- if (length(iN)) .choleskyDerivatives(nl, .choleskyFactor(nl, c(full, fixed))) - HN <- lapply(curv, function(cv) if (length(iN)) cv$H[iN, iN, drop = FALSE] + 2 * cd$Oinv) - volume <- sum(vapply(HN, function(H) if (is.null(H)) 0 else as.numeric(determinant(H / 2)$modulus), 0)) - # the sparse block of every group: the curvature S, the Schur complement of the normal block; - # the data term on it is exp(-eta' P eta / 2 + b' eta) up to the constant mode' S mode / 2 - g' mode - S <- lapply(seq_len(G), function(i) { - H <- curv[[i]]$H - s <- H[iL, iL, drop = FALSE] - if (length(iN)) s <- s - H[iL, iN, drop = FALSE] %*% solve(HN[[i]], H[iN, iL, drop = FALSE]) + return(list(groups = groups, units = units, forward = forward)) + } + conds <- unlist(design$conditions, use.names = FALSE) + times <- lapply(conds, function(cn) .emGrid(design, cn)) + preds <- setNames(.predictMany(design$prdfn, times = times, parsList = rep(list(at$full), length(conds)), + conditions = conds, fixed = fixed, deriv = TRUE, deriv2 = TRUE), conds) + groups <- lapply(seq_len(at$G), function(i) .gnCurvature(design, design$groups[i], preds, at$E[i, ], active, fixed)) + list(groups = groups, units = units) +} + +## A G x (sparse etas) matrix from `f(i)`, the row of group i. +.bySparse <- function(at, f) { + n <- length(at$sparseCols) + matrix(vapply(seq_len(at$G), f, numeric(n)), at$G, n, byrow = TRUE, + dimnames = list(rownames(at$E), colnames(at$E)[at$sparseCols])) +} + +## Per group the normal block H_NN plus the prior precision 2 Omega^-1 with the volume sum log|H_NN / 2|, and the +## sparse block: S, the Schur complement of the normal block, and b, the data term on it being +## exp(-eta' P eta / 2 + b' eta) up to `offset`, mode' S mode / 2 - g' mode. +.sparseBlocks <- function(at, curv, terms, fixed) { + normal <- at$normalCols; sparse <- at$sparseCols + cholesky <- if (length(normal)) .choleskyDerivatives(at$normal, .choleskyFactor(at$normal, c(at$full, fixed))) + normalHessian <- lapply(curv$groups, function(cv) if (length(normal)) cv$H[normal, normal, drop = FALSE] + 2 * cholesky$Oinv) + volume <- sum(vapply(normalHessian, function(H) if (is.null(H)) 0 else as.numeric(determinant(H / 2)$modulus), 0)) + schur <- lapply(seq_len(at$G), function(i) { + H <- curv$groups[[i]]$H + s <- H[sparse, sparse, drop = FALSE] + if (length(normal)) s <- s - H[sparse, normal, drop = FALSE] %*% solve(normalHessian[[i]], H[normal, sparse, drop = FALSE]) (s + t(s)) / 2 }) - KL <- length(iL) - bySparse <- function(f) matrix(vapply(seq_len(G), f, numeric(KL)), G, KL, byrow = TRUE, - dimnames = list(rownames(E), colnames(E)[iL])) - gL <- gr[, iL, drop = FALSE] - mL <- modes[, iL, drop = FALSE] - bL <- bySparse(function(i) drop(S[[i]] %*% mL[i, ] - gL[i, ]) / 2) - offset <- sum(vapply(seq_len(G), function(i) sum(mL[i, ] * (S[[i]] %*% mL[i, ])) / 2 - sum(gL[i, ] * mL[i, ]), 0)) - importance <- identical(control$integral, "importance") - sp <- if (importance) { - # in center form, m = mode - S^-1 g, log I of the natural form is that of the center form plus m' P m / 2 - mc <- mL - bySparse(function(i) { - a <- reach[i, iL] - out <- numeric(KL) - out[a] <- solve(S[[i]][a, a, drop = FALSE], gL[i, a]) - out - }) - is <- .importanceField(lapply(S, `/`, 2), mc, lay, hyp, hypers, control$particles %||% 500L) - is$logI <- is$logI + sum(vapply(seq_len(G), function(i) sum(mc[i, ] * (S[[i]] %*% mc[i, ])) / 4, 0)) - is - } else .sparseIntegral(lapply(S, `/`, 2), bL, lay, hyp, hypers, control$sites, reach[, iL, drop = FALSE]) - if (is.null(sp)) return(list(infeasible = TRUE)) - value <- sum(vapply(at, `[[`, 0, "value")) + (pr$value %||% 0) + volume - 2 * sp$logI + offset + - sum(vapply(free, `[[`, 0, "value")) - selected <- modes - selected[, iL] <- ifelse(is.na(sp$values), modes[, iL], sp$values) + sparseGradient <- terms$etaGradient[, sparse, drop = FALSE] + sparseModes <- at$modes[, sparse, drop = FALSE] + b <- .bySparse(at, function(i) drop(schur[[i]] %*% sparseModes[i, ] - sparseGradient[i, ]) / 2) + offset <- sum(vapply(seq_len(at$G), function(i) + sum(sparseModes[i, ] * (schur[[i]] %*% sparseModes[i, ])) / 2 - sum(sparseGradient[i, ] * sparseModes[i, ]), 0)) + list(cholesky = cholesky, normalHessian = normalHessian, volume = volume, schur = schur, b = b, offset = offset, + sparseGradient = sparseGradient, sparseModes = sparseModes) +} + +## The sparse integral by importance sampling in center form, m = mode - S^-1 g: log I of the natural form is +## that of the center form plus m' P m / 2. +.sparseImportanceIntegral <- function(at, blocks, hyp, hypers, particles) { + sparse <- at$sparseCols + center <- blocks$sparseModes - .bySparse(at, function(i) { + on <- at$reach[i, sparse] + out <- numeric(length(sparse)) + out[on] <- solve(blocks$schur[[i]][on, on, drop = FALSE], blocks$sparseGradient[i, on]) + out + }) + sampled <- .importanceField(lapply(blocks$schur, `/`, 2), center, at$lay, hyp, hypers, particles) + sampled$logI <- sampled$logI + sum(vapply(seq_len(at$G), function(i) + sum(center[i, ] * (blocks$schur[[i]] %*% center[i, ])) / 4, 0)) + sampled +} + +## The value, the selected values, clusters and spike probabilities, and the posterior moments of the etas; +## the normal etas given the sparse ones are normal with a mean linear in them. +.sparseMoments <- function(at, terms, curv, blocks, integral, innerIterations) { + G <- at$G; K <- at$K; E <- at$E + normal <- at$normalCols; sparse <- at$sparseCols + value <- sum(vapply(terms$groups, `[[`, 0, "value")) + (terms$prior$value %||% 0) + blocks$volume - + 2 * integral$logI + blocks$offset + sum(vapply(terms$free, `[[`, 0, "value")) + selected <- at$modes + selected[, sparse] <- ifelse(is.na(integral$values), at$modes[, sparse], integral$values) clusters <- spike <- matrix(NA_real_, G, K, dimnames = dimnames(E)) - clusters[, iL] <- sp$clusters; spike[, iL] <- sp$spike - mean <- matrix(0, G, K, dimnames = dimnames(E)) - mean[, iL] <- sp$mean - # the normal etas given the sparse ones are normal with a mean linear in them - cov <- lapply(seq_len(G), function(i) { + clusters[, sparse] <- integral$clusters; spike[, sparse] <- integral$spike + etaMean <- matrix(0, G, K, dimnames = dimnames(E)) + etaMean[, sparse] <- integral$mean + etaCov <- lapply(seq_len(G), function(i) { V <- matrix(0, K, K, dimnames = list(colnames(E), colnames(E))) - V[iL, iL] <- sp$cov[[i]] - if (length(iN)) { - B <- solve(HN[[i]], curv[[i]]$H[iN, iL, drop = FALSE]) - VS <- V[iL, iL, drop = FALSE] + V[sparse, sparse] <- integral$cov[[i]] + if (length(normal)) { + B <- solve(blocks$normalHessian[[i]], curv$groups[[i]]$H[normal, sparse, drop = FALSE]) + VS <- V[sparse, sparse, drop = FALSE] VS[is.na(VS)] <- 0 - V[iN, iN] <- 2 * solve(HN[[i]]) + B %*% VS %*% t(B) - V[iN, iL] <- -B %*% VS - V[iL, iN] <- t(V[iN, iL, drop = FALSE]) + V[normal, normal] <- 2 * solve(blocks$normalHessian[[i]]) + B %*% VS %*% t(B) + V[normal, sparse] <- -B %*% VS + V[sparse, normal] <- t(V[normal, sparse, drop = FALSE]) } V }) - var <- matrix(vapply(cov, diag, numeric(K)), G, K, byrow = TRUE, dimnames = dimnames(E)) - out <- list(value = value, modes = modes, mean = mean, var = var, cov = cov, slab = sp$slab, - selected = selected, clusters = clusters, spike = spike, valueSE = 2 * (sp$se %||% 0), - coupling = sp$coupling, sites = sp$sites, reach = reach) - if (!grad || importance) return(out) + etaVar <- matrix(vapply(etaCov, diag, numeric(K)), G, K, byrow = TRUE, dimnames = dimnames(E)) + list(value = value, modes = at$modes, innerIterations = innerIterations, mean = etaMean, var = etaVar, + cov = etaCov, slab = integral$slab, selected = selected, clusters = clusters, spike = spike, + valueSE = 2 * (integral$se %||% 0), coupling = integral$coupling, sites = integral$sites, reach = at$reach, + local = list(P = lapply(blocks$schur, `/`, 2), b = blocks$b)) +} - # derivatives of the value in g, S and the mode on the sparse block, from the moments of the - # integral at the fixed point, delta = E eta - mode and Cov eta, then through the Schur - # complement on the cross and normal blocks of H - delta <- sp$mean - mL - Q <- length(A) - own <- matrix(0, G, Q, dimnames = list(rownames(E), A)) - names <- as.vector(t(E)) - dEta <- setNames(numeric(G * K), names) - Hex <- matrix(0, G * K, G * K, dimnames = list(names, names)) - Hcross <- matrix(0, G * K, Q, dimnames = list(names, A)) - # the blocks of the model Hessian: under forward over reverse those of the Gauss-Newton Hessian, as - # the parameter block is, so that the Schur complement is positive semidefinite; the exact rows - # enter the gradient and the mode shift - HexM <- Hex; HcrossM <- Hcross - schur <- matrix(0, Q, Q, dimnames = list(A, A)) - # per group the matrices the derivatives of the curvature are contracted with: MHi on all etas, - # H_NN^-1 on the normal ones - contraction <- lapply(seq_len(G), function(i) { - MHi <- matrix(0, K, K, dimnames = list(E[i, ], E[i, ])) - MHi[iL, iL] <- (tcrossprod(delta[i, ]) + sp$cov[[i]]) / 2 - Hi <- NULL - if (length(iN)) { - Hi <- solve(HN[[i]]) - B <- curv[[i]]$H[iL, iN, drop = FALSE] %*% Hi - Ms <- MHi[iL, iL, drop = FALSE] - MHi[iL, iN] <- -Ms %*% B - MHi[iN, iL] <- t(MHi[iL, iN, drop = FALSE]) - MHi[iN, iN] <- crossprod(B, Ms %*% B) +## Per group the matrices the derivatives of the curvature are contracted with: `weight` on all etas, from +## delta = E eta - mode and Cov eta of the integral, and `normalInverse`, H_NN^-1, on the normal ones. +.curvatureContractions <- function(at, curv, blocks, integral, delta) { + normal <- at$normalCols; sparse <- at$sparseCols + lapply(seq_len(at$G), function(i) { + weight <- matrix(0, at$K, at$K, dimnames = list(at$E[i, ], at$E[i, ])) + weight[sparse, sparse] <- (tcrossprod(delta[i, ]) + integral$cov[[i]]) / 2 + normalInverse <- NULL + if (length(normal)) { + normalInverse <- solve(blocks$normalHessian[[i]]) + B <- curv$groups[[i]]$H[sparse, normal, drop = FALSE] %*% normalInverse + Ms <- weight[sparse, sparse, drop = FALSE] + weight[sparse, normal] <- -Ms %*% B + weight[normal, sparse] <- t(weight[sparse, normal, drop = FALSE]) + weight[normal, normal] <- crossprod(B, Ms %*% B) } - list(MHi = MHi, Hi = Hi) + list(weight = weight, normalInverse = normalInverse) }) - # forward over reverse: the exact eta rows of the data Hessian and the trace gradients - sw <- if (fr) .sweepUnits(design, full, fixed, units, fw = fw, Ms = lapply(seq_len(G), function(i) { - ct <- contraction[[i]] - M2 <- 0 * ct$MHi - if (!is.null(ct$Hi)) M2[iN, iN] <- ct$Hi - list(ct$MHi[reach[i, ], reach[i, ], drop = FALSE], M2[reach[i, ], reach[i, ], drop = FALSE]) - })) - pick <- function(v, nm) { out <- setNames(numeric(length(nm)), nm); h <- .intersect(nm, names(v)); out[h] <- v[h]; out } +} + +## For group i the exact rows of the data Hessian at the group etas `en` and in `an`, and the traces +## tr(weight dH) and tr(H_NN^-1 dH_NN) along `active` and the etas: from the sweeps `sweep` under forward over +## reverse, else from the curvature derivatives `cv`. +.groupTraces <- function(at, term, cv, contraction, sweep, en, an, active) { + if (at$forwardReverse) { + rowsAt <- function(cols) { + out <- matrix(0, at$K, length(cols), dimnames = list(en, cols)) + h <- .intersect(cols, colnames(sweep$rows)) + out[rownames(sweep$rows), h] <- sweep$rows[, h] + out + } + pick <- function(v, nm) { out <- setNames(numeric(length(nm)), nm); h <- .intersect(nm, names(v)); out[h] <- v[h]; out } + return(list(exactE = rowsAt(en), exactA = rowsAt(an), + dMA = pick(sweep$traces[[1]], active), dME = pick(sweep$traces[[1]], en), + dHA = pick(sweep$traces[[2]], active), dHE = pick(sweep$traces[[2]], en))) + } + normal <- at$normalCols + weight <- contraction$weight + out <- list(exactE = term$hessian[en, en, drop = FALSE], exactA = term$hessian[en, an, drop = FALSE], + dMA = vapply(seq_along(active), function(q) sum(weight * cv$dA[, , q]), 0), + dME = vapply(seq_len(at$K), function(j) sum(weight * cv$dE[, , j]), 0)) + if (length(normal)) { + out$dHA <- vapply(seq_along(active), function(q) sum(contraction$normalInverse * cv$dA[normal, normal, q]), 0) + out$dHE <- vapply(seq_len(at$K), function(j) sum(contraction$normalInverse * cv$dE[normal, normal, j]), 0) + } + out +} + +## The derivatives of the value at fixed modes: the explicit gradient in `active` per group, the gradient in +## the etas, the exact eta and cross blocks of the Hessian, the model ones (Gauss-Newton under forward over +## reverse, so that the Schur complement is positive semidefinite), and the block of `active`. +.sparseGroupDerivatives <- function(design, at, terms, curv, blocks, integral, active, fixed) { + G <- at$G; K <- at$K; E <- at$E + normal <- at$normalCols; sparse <- at$sparseCols + nl <- at$normal + delta <- integral$mean - blocks$sparseModes + nActive <- length(active) + etaOrder <- as.vector(t(E)) + groupGradient <- matrix(0, G, nActive, dimnames = list(rownames(E), active)) + etaGradient <- setNames(numeric(G * K), etaOrder) + etaHessian <- matrix(0, G * K, G * K, dimnames = list(etaOrder, etaOrder)) + crossHessian <- matrix(0, G * K, nActive, dimnames = list(etaOrder, active)) + etaModel <- etaHessian; crossModel <- crossHessian + activeHessian <- matrix(0, nActive, nActive, dimnames = list(active, active)) + contraction <- .curvatureContractions(at, curv, blocks, integral, delta) + sweeps <- if (at$forwardReverse) + .sweepUnits(design, at$full, fixed, curv$units, fw = curv$forward, Ms = lapply(seq_len(G), function(i) { + ct <- contraction[[i]] + M2 <- 0 * ct$weight + if (!is.null(ct$normalInverse)) M2[normal, normal] <- ct$normalInverse + list(ct$weight[at$reach[i, ], at$reach[i, ], drop = FALSE], M2[at$reach[i, ], at$reach[i, ], drop = FALSE]) + })) for (i in seq_len(G)) { en <- E[i, ] - o <- at[[i]] - hh <- o$hessian - an <- .intersect(A, names(o$gradient)) - cv <- curv[[i]] - Mgi <- Meta <- numeric(K) - Mgi[iL] <- delta[i, ] - Meta[iL] <- -drop(S[[i]] %*% delta[i, ]) - gL[i, ] - MHi <- contraction[[i]]$MHi - Hi <- contraction[[i]]$Hi - # the exact rows of the group's data Hessian at the group etas, and tr(M dH) along A and the etas - if (fr) { - rowsAt <- function(cols) { - out <- matrix(0, K, length(cols), dimnames = list(en, cols)) - h <- .intersect(cols, colnames(sw[[i]]$rows)) - out[rownames(sw[[i]]$rows), h] <- sw[[i]]$rows[, h] - out - } - exactE <- rowsAt(en); exactA <- rowsAt(an) - dMA <- pick(sw[[i]]$traces[[1]], A); dME <- pick(sw[[i]]$traces[[1]], en) - dHA <- pick(sw[[i]]$traces[[2]], A); dHE <- pick(sw[[i]]$traces[[2]], en) - } else { - exactE <- hh[en, en, drop = FALSE]; exactA <- hh[en, an, drop = FALSE] - dMA <- vapply(seq_len(Q), function(q) sum(MHi * cv$dA[, , q]), 0) - dME <- vapply(seq_len(K), function(j) sum(MHi * cv$dE[, , j]), 0) - if (length(iN)) { - dHA <- vapply(seq_len(Q), function(q) sum(Hi * cv$dA[iN, iN, q]), 0) - dHE <- vapply(seq_len(K), function(j) sum(Hi * cv$dE[iN, iN, j]), 0) - } + term <- terms$groups[[i]] + hh <- term$hessian + an <- .intersect(active, names(term$gradient)) + modeWeight <- shiftWeight <- numeric(K) + modeWeight[sparse] <- delta[i, ] + shiftWeight[sparse] <- -drop(blocks$schur[[i]] %*% delta[i, ]) - blocks$sparseGradient[i, ] + tr <- .groupTraces(at, term, curv$groups[[i]], contraction[[i]], sweeps[[i]], en, an, active) + groupGradient[i, an] <- groupGradient[i, an] + term$gradient[an] + drop(modeWeight %*% tr$exactA) + + tr$dMA[match(an, active)] + etaGradient[en] <- term$gradient[en] + drop(modeWeight %*% tr$exactE) + tr$dME + shiftWeight + if (length(normal)) { + # d log|H_NN| along the parameters, the Cholesky entries and the etas; the prior precision in H_NN + # also enters the Schur complement + groupGradient[i, ] <- groupGradient[i, ] + tr$dHA + etaGradient[en] <- etaGradient[en] + tr$dHE + ch <- .intersect(active, nl$cholPars) + MN <- contraction[[i]]$normalInverse + contraction[[i]]$weight[normal, normal, drop = FALSE] + groupGradient[i, ch] <- groupGradient[i, ch] + + vapply(ch, function(cp) 2 * sum(MN * blocks$cholesky$dOinv[[match(cp, nl$cholPars)]]), 0) } - own[i, an] <- own[i, an] + o$gradient[an] + drop(Mgi %*% exactA) + dMA[match(an, A)] - dEta[en] <- o$gradient[en] + drop(Mgi %*% exactE) + dME + Meta - if (length(iN)) { - # d log|H_NN| along the parameters, the Cholesky entries and the etas; the prior precision - # in H_NN also enters the Schur complement - own[i, ] <- own[i, ] + dHA - dEta[en] <- dEta[en] + dHE - ch <- .intersect(A, nl$cholPars) - MN <- Hi + MHi[iN, iN, drop = FALSE] - own[i, ch] <- own[i, ch] + vapply(ch, function(cp) 2 * sum(MN * cd$dOinv[[match(cp, nl$cholPars)]]), 0) - } - Hex[en, en] <- exactE - Hcross[en, an] <- exactA - HexM[en, en] <- if (fr) hh[en, en] else exactE - HcrossM[en, an] <- if (fr) hh[en, an] else exactA - schur[an, an] <- schur[an, an] + hh[an, an] + etaHessian[en, en] <- tr$exactE + crossHessian[en, an] <- tr$exactA + etaModel[en, en] <- if (at$forwardReverse) hh[en, en] else tr$exactE + crossModel[en, an] <- if (at$forwardReverse) hh[en, an] else tr$exactA + activeHessian[an, an] <- activeHessian[an, an] + hh[an, an] } - explicit <- colSums(own) + explicit <- colSums(groupGradient) + pr <- terms$prior if (!is.null(pr)) { - pa <- .intersect(A, names(pr$gradient)); pe <- .intersect(names, names(pr$gradient)) + pa <- .intersect(active, names(pr$gradient)); pe <- .intersect(etaOrder, names(pr$gradient)) explicit[pa] <- explicit[pa] + pr$gradient[pa] - dEta[pe] <- dEta[pe] + pr$gradient[pe] - Hex[pe, pe] <- Hex[pe, pe] + pr$hessian[pe, pe] - Hcross[pe, pa] <- Hcross[pe, pa] + pr$hessian[pe, pa] - HexM[pe, pe] <- HexM[pe, pe] + pr$hessian[pe, pe] - HcrossM[pe, pa] <- HcrossM[pe, pa] + pr$hessian[pe, pa] - schur[pa, pa] <- schur[pa, pa] + pr$hessian[pa, pa] - } - freeGradient <- setNames(numeric(Q), A) - freeHessian <- matrix(0, Q, Q, dimnames = list(A, A)) - for (o in free) { - an <- .intersect(A, names(o$gradient)) + etaGradient[pe] <- etaGradient[pe] + pr$gradient[pe] + etaHessian[pe, pe] <- etaHessian[pe, pe] + pr$hessian[pe, pe] + crossHessian[pe, pa] <- crossHessian[pe, pa] + pr$hessian[pe, pa] + etaModel[pe, pe] <- etaModel[pe, pe] + pr$hessian[pe, pe] + crossModel[pe, pa] <- crossModel[pe, pa] + pr$hessian[pe, pa] + activeHessian[pa, pa] <- activeHessian[pa, pa] + pr$hessian[pa, pa] + } + freeGradient <- setNames(numeric(nActive), active) + freeHessian <- matrix(0, nActive, nActive, dimnames = list(active, active)) + for (o in terms$free) { + an <- .intersect(active, names(o$gradient)) freeGradient[an] <- freeGradient[an] + o$gradient[an] freeHessian[an, an] <- freeHessian[an, an] + o$hessian[an, an] } - explicit <- explicit + freeGradient - schur <- schur + freeHessian + list(groupGradient = groupGradient, explicit = explicit + freeGradient, etaGradient = etaGradient, + etaHessian = etaHessian, crossHessian = crossHessian, etaModel = etaModel, crossModel = crossModel, + activeHessian = activeHessian + freeHessian, freeGradient = freeGradient, freeHessian = freeHessian, + etaOrder = etaOrder, + onData = etaOrder[as.vector(t(at$reach))]) +} - # the model Hessian: the Schur complement over all etas, the sparse etas with the effective prior - # curvature of the integral, the sites of EC or per factor 2 C^-1 - S of the - # posterior covariance C; with normal etas alone it is the Gauss-Newton Schur complement - posterior <- HexM - factors <- .sparseFactors(lapply(S, `/`, 2), colnames(E)[iL], lay)$factors - for (i in seq_len(G)) { - en <- E[i, iL] - if (isTRUE(sp$ec[i])) { - posterior[en, en] <- posterior[en, en] + diag(2 * pmax(sp$sites$Lam[i, ], 0), KL) +## The model Hessian: the Schur complement over all etas, the sparse etas with the effective prior curvature +## of the integral, the sites of EC or per factor 2 C^-1 - S of the posterior covariance C; NULL without active +## parameters or where the solve fails. +.sparseModelHessian <- function(at, blocks, integral, d) { + posterior <- d$etaModel + factors <- .sparseFactors(lapply(blocks$schur, `/`, 2), colnames(at$E)[at$sparseCols], at$lay)$factors + for (i in seq_len(at$G)) { + en <- at$E[i, at$sparseCols] + if (isTRUE(integral$ec[i])) { + posterior[en, en] <- posterior[en, en] + diag(2 * pmax(integral$sites$Lam[i, ], 0), length(at$sparseCols)) next } - V <- sp$cov[[i]] + V <- integral$cov[[i]] if (anyNA(V)) next for (f in factors) { e <- eigen(V[f, f, drop = FALSE], symmetric = TRUE) inv <- e$vectors %*% (t(e$vectors) / pmax(e$values, 1e-12 * max(1, e$values))) - posterior[en[f], en[f]] <- posterior[en[f], en[f]] + 2 * inv - S[[i]][f, f, drop = FALSE] + posterior[en[f], en[f]] <- posterior[en[f], en[f]] + 2 * inv - blocks$schur[[i]][f, f, drop = FALSE] } } - on <- names[as.vector(t(reach))] - model <- if (Q) tryCatch(schur - crossprod(HcrossM[on, , drop = FALSE], - solve(posterior[on, on, drop = FALSE], HcrossM[on, , drop = FALSE])), - error = function(e) NULL) + on <- d$onData + if (ncol(d$crossModel)) + tryCatch(d$activeHessian - crossprod(d$crossModel[on, , drop = FALSE], + solve(posterior[on, on, drop = FALSE], d$crossModel[on, , drop = FALSE])), + error = function(e) NULL) +} - slabPrec <- .slabPrecision(E, lay, hyp) - Hex[cbind(names(slabPrec), names(slabPrec))] <- Hex[cbind(names(slabPrec), names(slabPrec))] + slabPrec +## The change of the value to the exact modes, to first order: the value depends on the modes by the eta +## gradient, and the inner search leaves a gradient at them that a Newton step on the eta Hessian removes. +.modeCorrection <- function(at, terms, d, slabPrecision) { + inner <- setNames(numeric(length(d$etaOrder)), d$etaOrder) + for (i in seq_len(at$G)) inner[at$E[i, ]] <- terms$etaGradient[i, ] + pr <- terms$prior + if (!is.null(pr)) { + pe <- .intersect(d$etaOrder, names(pr$gradient)) + inner[pe] <- inner[pe] + pr$gradient[pe] + } + inner[names(slabPrecision)] <- inner[names(slabPrecision)] + slabPrecision * at$full[names(slabPrecision)] + on <- d$onData + tryCatch(-sum(d$etaGradient[on] * solve(d$etaHessian[on, on, drop = FALSE], inner[on])), error = function(e) 0) +} - # the shift of the mode: every eta moves with the parameters; the curvature of the mode is block - # diagonal by groups, so the shift of a group is separate - td <- .tauDerivative(modes, E, lay, hyp) - gradient <- explicit - hyperGrad <- -2 * sp$dhyper +## The total gradient with the shift of the modes along the parameters, block diagonal by groups, the Schur +## complement of the active block, and with `scores` the gradient per group. +.sparseOuterDerivatives <- function(at, terms, blocks, integral, d, hyp, hypers, active, fixed, scores) { + G <- at$G; K <- at$K + nActive <- length(active) + tauDeriv <- .tauDerivative(at$modes, at$E, at$lay, hyp) + gradient <- d$explicit + hyperGradient <- -2 * integral$dhyper byGroup <- if (scores) { - hg <- sp$hyperGroups %||% matrix(NA_real_, G, length(hypers), dimnames = list(NULL, hypers)) - cbind(own, -2 * hg[, hypers, drop = FALSE]) + hg <- integral$hyperGroups %||% matrix(NA_real_, G, length(hypers), dimnames = list(NULL, hypers)) + cbind(d$groupGradient, -2 * hg[, hypers, drop = FALSE]) } - if (scores && !is.null(pr)) byGroup[, A] <- byGroup[, A] + .priorGroups(nl, E, full, fixed, cd, A) - out$modeShift <- matrix(0, length(names), Q, dimnames = list(names, A)) + if (scores && !is.null(terms$prior)) + byGroup[, active] <- byGroup[, active] + .priorGroups(at$normal, at$E, at$full, fixed, blocks$cholesky, active) + modeShift <- matrix(0, length(d$etaOrder), nActive, dimnames = list(d$etaOrder, active)) owner <- outer(seq_len(G), rep(seq_len(G), each = K), `==`) * 1 - if (Q) { - shift <- solve(Hex, Hcross) - out$modeShift <- -shift - gradient <- gradient - drop(dEta %*% shift) - if (scores) byGroup[, A] <- byGroup[, A] - owner %*% (dEta * shift) - schur <- schur - crossprod(Hcross, shift) + schur <- d$activeHessian + if (nActive) { + shift <- solve(d$etaHessian, d$crossHessian) + modeShift <- -shift + gradient <- gradient - drop(d$etaGradient %*% shift) + if (scores) byGroup[, active] <- byGroup[, active] - owner %*% (d$etaGradient * shift) + schur <- schur - crossprod(d$crossHessian, shift) } for (h in hypers) { - v <- dEta * drop(solve(Hex, ifelse(!is.na(td$hyper) & td$hyper == h, td$d, 0))) - hyperGrad[h] <- hyperGrad[h] - sum(v) + v <- d$etaGradient * drop(solve(d$etaHessian, ifelse(!is.na(tauDeriv$hyper) & tauDeriv$hyper == h, tauDeriv$d, 0))) + hyperGradient[h] <- hyperGradient[h] - sum(v) if (scores) byGroup[, h] <- byGroup[, h] - drop(owner %*% v) } - out$gradient <- c(gradient, hyperGrad) - out$hessian <- model %||% schur - if (scores) out[c("scores", "freeGradient", "freeHessian")] <- list(byGroup, freeGradient, freeHessian) - out + list(modeShift = modeShift, gradient = c(gradient, hyperGradient), schur = schur, byGroup = byGroup) +} + +## The expected information in `active` of the terms without random effects, by which they enter the +## information; `freeHessian` gives the layout. +.freeInformation <- function(design, objs, terms, at, active, fixed, freeHessian) { + info <- 0 * freeHessian + extra <- terms$extra + free <- c(lapply(design$freeConditions, function(cn) + objs[[cn]](at$full, fixed = fixed, deriv = TRUE, hessian = "expected")), + if (!is.null(extra)) list(extra(pars = at$full, fixed = fixed, deriv = TRUE, hessian = "expected"))) + for (o in free) { + an <- .intersect(active, rownames(o$hessian)) + info[an, an] <- info[an, an] + o$hessian[an, an] + } + info } ## The gradient of the normal prior of every group, eta' Omega^-1 eta + log|Omega|, in the @@ -635,12 +708,20 @@ hyper <- start[hypers] par <- start[structural] lc <- control$sparseFit %||% list() - lc$derivMode <- .secondOrderMode(design, design$objfn, par, fixed, control[.setdiff(names(control), "secondOrderCorrection")], - units = lapply(design$groups, function(g) - list(eta = unname(E[g, reach[g, ]]), conditions = design$conditions[[g]]))) + units <- lapply(design$groups, function(g) list(eta = unname(E[g, reach[g, ]]), conditions = design$conditions[[g]])) + lc$derivMode <- .secondOrderMode(design, design$objfn, par, fixed, + control[.setdiff(names(control), "secondOrderCorrection")], units = units) + lc$meta <- .foceiMeta(design, c(par, fixed), NULL, colnames(E), reach) maxOuter <- lc$maxOuter %||% 200L jointControl <- .trustControl(list(rinit = 1, rmax = 10, tolControl = list(ftol = 1e-10, mtol = 1e-5)), lc$trustControl, label = "trustControl") + # control$inner = "sqp": the modes by sqpIterlim inner iterations from the predicted modes, without the earlier + # optima as starts, until the trust region stops at the tolerances of .sqpTolerance(); then on nested + nested <- lc + inexact <- identical(control[["inner"]], "sqp") + if (inexact) lc$iterlim <- as.integer(control$innerControl$sqpIterlim %||% 2L) + runControl <- if (inexact) .sqpTolerance(jointControl) else jointControl + innerIterations <- 0L # the inner start at p: the last modes moved by their first-order shift along the parameters predicted <- function(p) { if (is.null(shift)) return(warm) @@ -659,7 +740,8 @@ on.exit(release_heap(), add = TRUE) r <- .sparseMarginal(design, objs, prior, c(p, fixed), .stemHypers(lay, c(hyper, fixed)), names(p), hypers, fixed, predicted(p), grad = grad, scores = scores, - control = modifyList(lc, list(sites = sites, optima = optima))) + control = modifyList(lc, list(sites = sites, optima = if (!inexact) optima))) + innerIterations <<- innerIterations + r$innerIterations if (isTRUE(r$infeasible)) return(r) if (commit) accept(p, r) r @@ -671,22 +753,24 @@ hy <- .stemHypers(lay, c(hyper, fixed)) st <- lay$stem[lay$dist %in% c("spikeSlab", "dirichletProcess")] scale[, st] <- rep(hy$tau[st], each = nrow(E)) - found <- .exploreModes(design, objs, prior, c(p, fixed), hy, warm, lc, scale * .reachOf(design)) + found <- .exploreModes(design, c(p, fixed), hy, warm, nested, scale * .reachOf(design)) + innerIterations <<- innerIterations + attr(found, "iterations") optima <<- .modeOptima(optima, found) explored <<- steps() } accept <- function(p, r) { warm <<- r$modes warmAt <<- p - optima <<- .modeOptima(optima, r$modes) + if (!inexact) optima <<- .modeOptima(optima, r$modes) if (!is.na(explored) && steps() - explored >= 25L) explore(p) if (!is.null(r$modeShift)) shift <<- r$modeShift if (!is.null(r$sites)) sites <<- r$sites } rows <- list() - record <- function(phase, value, dpar) - rows[[length(rows) + 1L]] <<- data.frame(iter = length(rows) + 1L, phase = phase, OFV = value, - deltaPar = dpar, t(hyper)) + record <- function(phase, value, dpar) { + row <- data.frame(iter = length(rows) + 1L, phase = phase, OFV = value, deltaPar = dpar, t(hyper)) + rows[[length(rows) + 1L]] <<- row + } # the iterations are the recorded steps; the start of every trust run is recorded without one steps <- function() sum(vapply(rows, function(r) !is.na(r$deltaPar), TRUE)) # the objective in the structural parameters and the unbounded hyperparameters; the model Hessian @@ -727,15 +811,15 @@ } # one run of the trust region from the current point: the trust result, NULL with a warning on # an error - jointRun <- function(rinit = jointControl$rinit) { + jointRun <- function(rinit = runControl$rinit) { x0 <- c(par, .hyperToFree(kind, hyper)) best <<- Inf; bestAt <<- bestGrad <<- correction <<- NULL - jt <- tryCatch(.innerTrust(modifyList(jointControl, list(objfun = jointObjective, parinit = x0, rinit = rinit, - iterlim = max(maxOuter - steps(), 1L)))), - error = function(e) { - warning("em: the trust region stopped: ", conditionMessage(e), call. = FALSE) - NULL - }) + settings <- modifyList(runControl, list(objfun = jointObjective, parinit = x0, rinit = rinit, + iterlim = max(maxOuter - steps(), 1L))) + jt <- tryCatch(.innerTrust(settings), error = function(e) { + warning("em: the trust region stopped: ", conditionMessage(e), call. = FALSE) + NULL + }) hyper <<- .hyperFromFree(kind, x0[hypers]) if (is.list(jt)) { par <<- jt$argument[names(par)] @@ -747,42 +831,61 @@ if (length(par) + length(hyper) > 0L) explore(par) # a run that stops short starts again with a fresh correction while the runs lower -2 log L estimated <- length(par) + length(hyper) > 0L - conv <- !estimated - stopReason <- if (estimated) "iterlim" else NA_character_ - last <- Inf - mtol <- jointControl$tolControl$mtol %||% 1e-5 - while (estimated && steps() < maxOuter) { - jt <- jointRun() - if (is.null(jt)) { conv <- FALSE; stopReason <- "error"; break } - conv <- isTRUE(jt$converged) - stopReason <- jt$stopReason %||% NA_character_ - if (conv || !(jt$value < last - mtol)) break - last <- jt$value + runs <- list(jt = list(), converged = !estimated, stopReason = if (estimated) "iterlim" else NA_character_) + if (estimated) runs <- .sparseRuns(jointRun, steps, maxOuter, runControl$tolControl$mtol %||% 1e-5, runs) + sqpIterations <- NULL + if (inexact) { + # the nested search from the estimates and modes of the inexact one + inexact <- FALSE + lc <- nested + runControl <- jointControl + if (estimated && !is.null(runs$jt)) { + sqpIterations <- steps() + runs <- .sparseRuns(jointRun, steps, maxOuter, jointControl$tolControl$mtol %||% 1e-5, runs) + } } + conv <- runs$converged + stopReason <- runs$stopReason explored <- NA_integer_ final <- marginal(par, scores = TRUE) if (isTRUE(final$infeasible) || !is.finite(final$value %||% NA_real_)) stop("em: the integral over the sparse random effects has no finite value at the last point of the ", "fit, or the expectation consistent (EC) approximation did not converge there; a start nearer ", - "the optimum may avoid it.", - call. = FALSE) + "the optimum may avoid it.", call. = FALSE) coupled <- final$coupling - # the model Hessian approximates the curvature of the integral by Gauss-Newton, so the fit has none; with - # independent groups the empirical information is G / (G - 1) times the sum of the outer products - # of their centered scores of log L, the conditions without random effects add half their Hessian - information <- if (!is.null(final$scores) && !anyNA(final$scores)) { - 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) - I[names(par), names(par)] <- I[names(par), names(par)] + final$freeHessian / 2 - I - } list(argument = c(par, hyper), value = final$value, gradient = final$gradient, - hessian = NULL, information = information, etaModes = final$selected, + hessian = NULL, information = .empiricalInformation(final, names(par)), etaModes = final$selected, etaCov = setNames(final$cov, design$groups), clusters = final$clusters, spike = final$spike, converged = conv, iterations = steps(), stopReason = stopReason, failures = failures, stageTrace = do.call(rbind, rows), coupling = coupled, - innerModes = final$modes) + innerModes = final$modes, innerIterations = innerIterations, sqpIterations = sqpIterations) +} + +## Runs of the trust region by `run()` while each lowers -2 log L by more than `mtol`, up to `maxOuter` steps: +## the last run with convergence and stop reason, `previous` where none starts, `jt` NULL after an error. +.sparseRuns <- function(run, steps, maxOuter, mtol, previous) { + out <- previous + last <- Inf + while (steps() < maxOuter) { + jt <- run() + if (is.null(jt)) return(list(jt = NULL, converged = FALSE, stopReason = "error")) + out <- list(jt = jt, converged = isTRUE(jt$converged), stopReason = jt$stopReason %||% NA_character_) + if (out$converged || !(jt$value < last - mtol)) break + last <- jt$value + } + out +} + +## The empirical information of a sparse fit from the scores of `final`: the model Hessian approximates the +## curvature of the integral by Gauss-Newton, so with independent groups it is G / (G - 1) times the sum of the +## outer products of the centered scores, plus half the Hessian of the conditions without random effects. +.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) + I[par, par] <- I[par, par] + final$freeHessian / 2 + I } @@ -878,10 +981,9 @@ pmax(ifelse(abs(d) > 1e-8 & slope * d > 0, slope / d, info), 1e-8) } -## M-steps from the posterior moments `r` over the coordinates that reach their data: -## tau^2 = E[sum of squared slab values] / E[slab blocks], -## prob = E[slab etas] / groups, and the concentration c with E[slab blocks] = sum_i c / (c + i) -## over the groups of every stem. +## M-steps from the posterior moments `r` over the coordinates that reach their data: tau^2 = E[sum of squared +## slab values] / E[slab blocks], prob = E[slab etas] / groups, and the concentration c with +## E[slab blocks] = sum_i c / (c + i) over the groups of every stem. .updateSparse <- function(lay, r, current) { for (h in names(current)) { rows <- r$slab[lay$stem[lay$probName %in% h | lay$concentrationName %in% h | lay$tauName %in% h], , @@ -915,3 +1017,118 @@ } exp(lt) } + + +## ---- importance sampling on the model ------------------------------------------------ + +## -2 log L of a spike-and-slab fit by importance sampling on the model, `draws` per group from the +## mixture of the approximation with spreads widened by `widen`: value, standard error, effective +## sample size per group and the value of the approximation at the same point. +.sparseImportance <- function(object, draws = 1000L, widen = 1.5, chunk = 250L) { + design <- object$design + if (is.null(design)) + stop("logLik: the fit has no design; method = \"importance\" evaluates the model.", call. = FALSE) + lay <- .sparseLayout(design) + if (!is.null(design$groupings) || is.null(lay) || any(lay$dist != "spikeSlab")) + stop("logLik: method = \"importance\" takes spike-and-slab random effects of one grouping, normal ones beside.", + call. = FALSE) + fixed <- object$fixed + hypers <- .intersect(.sparseHypers(lay), names(object$argument)) + par <- object$argument[.setdiff(names(object$argument), hypers)] + theta <- c(par, fixed) + hyp <- .stemHypers(lay, c(object$argument, fixed)) + objs <- .conditionObjectives(design) + prior <- if (design$normal$K) .normalPrior(design) + E <- design$etaNames + # the inner modes of the approximation at the estimates, of a fit without them the modes of the changes + warm <- object$innerModes %||% object$etaModes %||% matrix(0, nrow(E), ncol(E), dimnames = dimnames(E)) + reach <- .reachOf(design) + dm <- .secondOrderMode(design, design$objfn, par, fixed, list(), units = lapply(design$groups, function(g) + list(eta = unname(E[g, reach[g, ]]), conditions = design$conditions[[g]]))) + r <- .sparseMarginal(design, objs, prior, theta, hyp, names(par), hypers, fixed, warm, grad = FALSE, + control = list(derivMode = dm)) + if (isTRUE(r$infeasible)) stop("logLik: the approximation has no value at the estimates.", call. = FALSE) + G <- nrow(E) + isL <- colnames(E) %in% lay$stem + full <- c(theta, setNames(as.vector(r$modes), as.vector(E))) + if (design$normal$K) { + Lc <- .choleskyFactor(design$normal, theta) + Omega <- Lc %*% t(Lc) + } + dmvn <- function(X, m, S) { + R <- chol(S) + Z <- backsolve(R, t(X) - m, transpose = TRUE) + -colSums(Z^2) / 2 - sum(log(diag(R))) - nrow(R) * log(2 * pi) / 2 + } + groups <- lapply(seq_len(G), function(i) { + on <- r$reach[i, ] + jL <- which(isL & on); jN <- which(!isL & on) + X <- matrix(0, draws, ncol(E)) + lq <- lp <- numeric(draws) + # the subset by the spike probabilities, the slab values of it jointly from the local model + # exp(-eta' P eta / 2 + b' eta) of the data times the slab prior + if (length(jL)) { + kL <- match(jL, which(isL)) + st <- colnames(E)[jL] + tau <- hyp$tau[st]; prob <- hyp$prob[st] + p0 <- pmin(pmax(r$spike[i, jL], 0.01), 0.99) + P <- r$local$P[[i]][kL, kL, drop = FALSE] + bb <- r$local$b[i, kL] + Z <- matrix(stats::runif(draws * length(jL)) > rep(p0, each = draws), draws) + for (k in seq_len(draws)) { + z <- Z[k, ] + lq[k] <- sum(ifelse(z, log(1 - p0), log(p0))) + lp[k] <- sum(ifelse(z, log(prob), log(1 - prob))) + if (!any(z)) next + Lam <- P[z, z, drop = FALSE] + diag(1 / tau[z]^2, sum(z)) + R <- chol(Lam / widen^2) + mu <- backsolve(chol(Lam), backsolve(chol(Lam), bb[z], transpose = TRUE)) + x <- mu + backsolve(R, stats::rnorm(sum(z))) + X[k, jL[z]] <- x + u <- R %*% (x - mu) + lq[k] <- lq[k] + sum(log(diag(R))) - sum(z) * log(2 * pi) / 2 - sum(u^2) / 2 + lp[k] <- lp[k] + sum(stats::dnorm(x, 0, tau[z], log = TRUE)) + } + } + if (length(jN)) { + S <- widen^2 * r$cov[[i]][jN, jN, drop = FALSE] + m <- r$modes[i, jN] + Xn <- matrix(stats::rnorm(draws * length(jN)), draws) %*% chol(S) + rep(m, each = draws) + X[, jN] <- Xn + lq <- lq + dmvn(Xn, m, S) + on <- match(colnames(E)[jN], design$normal$stems) + lp <- lp + dmvn(Xn, rep(0, length(jN)), Omega[on, on, drop = FALSE]) + } + list(X = X, lw = lp - lq) + }) + # the data -2 log L of every group at the draws, in chunks of draws over all groups + conds <- lapply(seq_len(G), function(i) design$conditions[[design$groups[i]]]) + data <- matrix(0, G, draws) + for (start in seq(1L, draws, by = chunk)) { + ks <- start:min(draws, start + chunk - 1L) + jobs <- do.call(rbind, lapply(seq_len(G), function(i) + expand.grid(group = i, draw = ks, cond = conds[[i]], stringsAsFactors = FALSE))) + pars <- lapply(seq_len(nrow(jobs)), function(q) { + p <- full + p[E[jobs$group[q], ]] <- groups[[jobs$group[q]]]$X[jobs$draw[q], ] + p + }) + v <- vapply(.objEvalMany(objs[jobs$cond], pars, deriv = FALSE), `[[`, 0, "value") + agg <- tapply(v, list(jobs$group, jobs$draw), sum) + data[as.integer(rownames(agg)), as.integer(colnames(agg))] <- agg + } + terms <- vapply(seq_len(G), function(i) { + lw <- groups[[i]]$lw - data[i, ] / 2 + mx <- max(lw) + w <- exp(lw - mx) + c(value = -2 * (mx + log(mean(w))), se = 2 * stats::sd(w) / (sqrt(draws) * mean(w)), + ess = sum(w)^2 / sum(w^2)) + }, numeric(3)) + free <- if (length(design$freeConditions)) + sum(vapply(.objEvalMany(objs[design$freeConditions], rep(list(full), length(design$freeConditions)), + deriv = FALSE), `[[`, 0, "value")) + extra <- .extraObjective(design) + beside <- (free %||% 0) + if (!is.null(extra)) extra(pars = full, fixed = fixed, deriv = FALSE)$value else 0 + list(value = sum(terms["value", ]) + beside, se = sqrt(sum(terms["se", ]^2)), + ess = setNames(terms["ess", ], rownames(E)), approximation = r$value) +} diff --git a/R/nlmeSpikeSlab.R b/R/nlmeSpikeSlab.R index 3fe35b9e..150e2dc6 100644 --- a/R/nlmeSpikeSlab.R +++ b/R/nlmeSpikeSlab.R @@ -1,7 +1,6 @@ -# Spike-and-slab random effects, each 0 or from N(0, tau^2) with probability prob, and -# Dirichlet-process random effects, a partition of the groups under the Ewens prior with one -# N(0, tau^2) value per block but that of the population value; the methods article Sparsity -# priors derives both. +# Spike-and-slab random effects, 0 or from N(0, tau^2) with probability prob, 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. ## The most nodes the joint sum over the subsets of the spike-and-slab coordinates of a group @@ -10,10 +9,13 @@ .slabBudget <- 2^24 ## log I of the Dirichlet-process stems on the expansion (precision P[[g]], center m[g, ]) by -## sequential importance sampling over the seating of the groups, each by prior times predictive; -## the product of the normalizers is unbiased for I, the standard error of log I beside it. -.dirichletImportance <- function(P, m, concentration, tau, particles = 500L) { +## sequential importance sampling over the seatings, with the standard error of log I; the stems of +## `slab` are spike-and-slab ones, summed over subsets, at most `budget` seatings and subsets. +.dirichletImportance <- function(P, m, concentration, tau, particles = 500L, slab = NULL, prob = NULL, + budget = 4096L) { G <- nrow(m); K <- ncol(m) + slab <- slab %||% rep(FALSE, K) + dpIdx <- which(!slab) # log of the integral over the free values with precision Lam (data and prior), linear term h logIntegral <- function(Lam, h, logTau) { if (!length(h)) return(0) @@ -22,38 +24,61 @@ } logZ <- numeric(particles) for (pt in seq_len(particles)) { - sizes <- rep(list(1L), K) + sizes <- rep(list(1L), length(dpIdx)) stemOf <- integer(0); clusterOf <- integer(0) Lam <- matrix(0, 0, 0); h <- numeric(0); logTau <- numeric(0); c0 <- 0; current <- 0 for (g in seq_len(G)) { - choices <- as.matrix(expand.grid(lapply(sizes, function(n) seq_len(length(n) + 1L)))) Pg <- P[[g]]; mg <- m[g, ] - states <- vector("list", nrow(choices)) - logw <- numeric(nrow(choices)) - for (r in seq_len(nrow(choices))) { - ch <- choices[r, ] + open <- which(slab & rowSums(abs(Pg)) > 0) + seats <- if (length(dpIdx)) as.matrix(expand.grid(lapply(sizes, function(n) seq_len(length(n) + 1L)))) + else matrix(0L, 1, 0) + subsets <- if (length(open)) as.matrix(expand.grid(rep(list(c(FALSE, TRUE)), length(open)))) + else matrix(FALSE, 1, 0) + if (nrow(seats) * nrow(subsets) > budget) + stop("em: importance sampling sums over at most ", budget, " seatings and spike-and-slab subsets of ", + "a group.", call. = FALSE) + combos <- expand.grid(seat = seq_len(nrow(seats)), subset = seq_len(nrow(subsets))) + states <- vector("list", nrow(combos)) + logw <- numeric(nrow(combos)) + for (r in seq_len(nrow(combos))) { + ch <- seats[combos$seat[r], ] + on <- open[as.logical(subsets[combos$subset[r], ])] new <- which(ch > lengths(sizes)) - d <- length(h) + length(new) + nNew <- length(new) + length(on) + d <- length(h) + nNew A <- matrix(0, K, d) - sOf <- c(stemOf, new); cOf <- c(clusterOf, ch[new]) - for (s in seq_len(K)) if (ch[s] > 1L) A[s, which(sOf == s & cOf == ch[s])] <- 1 + sOf <- c(stemOf, dpIdx[new]); cOf <- c(clusterOf, ch[new]) + for (s in seq_along(dpIdx)) if (ch[s] > 1L) A[dpIdx[s], which(sOf == dpIdx[s] & cOf == ch[s])] <- 1 + for (k in seq_along(on)) A[on[k], length(h) + length(new) + k] <- 1 L2 <- matrix(0, d, d); L2[seq_along(h), seq_along(h)] <- Lam - lt <- c(logTau, log(tau[new])) - diag(L2)[length(h) + seq_along(new)] <- 1 / tau[new]^2 + lt <- c(logTau, log(tau[dpIdx[new]]), log(tau[on])) + diag(L2)[length(h) + seq_len(nNew)] <- 1 / exp(2 * lt[length(h) + seq_len(nNew)]) L2 <- L2 + crossprod(A, Pg %*% A) - h2 <- c(h, numeric(length(new))) + drop(crossprod(A, Pg %*% mg)) + h2 <- c(h, numeric(nNew)) + drop(crossprod(A, Pg %*% mg)) cc <- c0 - sum(mg * (Pg %*% mg)) / 2 - prior <- sum(vapply(seq_len(K), function(s) - log(if (ch[s] > length(sizes[[s]])) concentration[s] else sizes[[s]][ch[s]]) - log(g + concentration[s]), 0)) + prior <- sum(vapply(seq_along(dpIdx), function(s) { + a <- concentration[dpIdx[s]] + log(if (ch[s] > length(sizes[[s]])) a else sizes[[s]][ch[s]]) - log(g + a) + }, 0)) + sum(ifelse(open %in% on, log(prob[open]), log1p(-prob[open]))) value <- cc + logIntegral(L2, h2, lt) logw[r] <- prior + value - current + # 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] + lt <- lt[keep] + cc <- value - logIntegral(L2, h2, lt) + } states[[r]] <- list(Lam = L2, h = h2, logTau = lt, c0 = cc, value = value, stemOf = sOf, clusterOf = cOf) } mx <- max(logw) logZ[pt] <- logZ[pt] + mx + log(sum(exp(logw - mx))) pick <- sample.int(length(logw), 1L, prob = exp(logw - mx)) - st <- states[[pick]]; ch <- choices[pick, ] - for (s in seq_len(K)) { + st <- states[[pick]]; ch <- seats[combos$seat[pick], ] + for (s in seq_along(dpIdx)) { if (ch[s] > length(sizes[[s]])) sizes[[s]] <- c(sizes[[s]], 1L) else sizes[[s]][ch[s]] <- sizes[[s]][ch[s]] + 1L } Lam <- st$Lam; h <- st$h; logTau <- st$logTau; c0 <- st$c0; current <- st$value diff --git a/R/nlmeSweeps.R b/R/nlmeSweeps.R index e87222c9..6305f35a 100644 --- a/R/nlmeSweeps.R +++ b/R/nlmeSweeps.R @@ -1,14 +1,11 @@ -# Second-order information of the mixed-effects objectives by forward over reverse: one forward -# pass along the etas, several backward sweeps with seeds on the predicted values and sigmas of -# the data rows. The etas of different units never meet in a condition, so the k-th eta of -# every unit shares one tangent. +# Second-order information of the mixed-effects objectives by forward over reverse: one forward pass along the +# etas, backward sweeps seeded on the predictions and sigmas of the data rows. Etas of different units never +# meet in a condition, so the k-th eta of every unit shares one tangent. -## The forward pass along the colored eta directions of `units`, then a direction per parameter -## in `along`: per condition of `conds` the prediction and error-model values with their tangents -## and tapes, and per data row the prediction p, sigma s and their derivatives pd, sd along the -## directions. Through the native chain where it covers the model (`native`, for a backward sweep -## with `blocks` seed blocks), then without values and tapes. +## The forward pass along the colored eta directions of `units` and one per parameter in `along`: per condition +## the values with tangents and tapes, per data row p, s and their derivatives pd, sd; through the native chain +## where it covers the model (`native`, for `blocks` seed blocks), then without values and tapes. .sweepForward <- function(design, full, fixed, units, cores = 1L, along = character(0), conds = unique(unlist(lapply(units, `[[`, "conditions"), use.names = FALSE)), blocks = 1L, chain = TRUE) { @@ -51,10 +48,9 @@ preds = preds, errs = errs, rows = unname(rows)) } -## The forward pass along the k-th tangent of the native full pass `fw` on the conditions `conds`, -## for a backward sweep with `blocks` seed blocks: the parameter stages along that tangent anew, -## the solution and the k-th tangent taken from `fw` without a solve. NULL where `fw` did not run -## natively. +## The forward pass along the k-th tangent of the native pass `fw` on `conds`, for `blocks` seed blocks: the +## parameter stages anew, the solution and the k-th tangent from `fw` without a solve; NULL where `fw` did not +## run natively. .sweepSlice <- function(design, full, fixed, fw, k, conds, blocks, cores) { nat <- fw$native if (is.null(nat)) return(NULL) @@ -110,11 +106,9 @@ rows } -## The backward sweep of a forward pass `fw` with the seeds `seeds`, per condition a list of -## `pred` and `sigma`, [rows, blocks (K + 1)], or these stacked over the conditions with `n` the -## rows per condition: per block a seed and the seed derivatives along the K tangents. Per condition -## the cotangent of the parameters it reaches, [parameters, blocks (K + 1)]: per block J' w and the -## sum over rows of w Hess(f) v_k plus J' wdot_k. +## The backward sweep of `fw` with `seeds` per condition, `pred` and `sigma` of [rows, blocks (K + 1)] (or +## stacked, `n` rows per condition), each block a seed and the seed derivatives along the K tangents: per condition +## the cotangent [parameters, blocks], per block J' w and the row sum of w Hess(f) v_k plus J' wdot_k. .sweepBackward <- function(fw, seeds, cores = 1L, blocks = 1L) { stacked <- is.matrix(seeds$pred) if (!is.null(fw$native)) { @@ -251,14 +245,9 @@ } -## Per unit of `units` (with `eta` and `conditions`) by forward over reverse: `rows`, the exact -## eta rows of the Hessian of the data term, and `traces`, the gradients grad tr(M H_u) of the -## matrices in `Ms[[u]]`, H_u the Gauss-Newton Hessian of the data term in the unit's etas. All as -## named over `reach`, the parameters the unit's conditions reach. Either one backward sweep along -## all tangents with a seed block for the rows and one per eta direction for the traces -## (`narrow = FALSE`), or per direction k a forward pass along it alone and a backward sweep with a -## seed for row k and one per M (.sweepNarrow()), whose stores have two columns in place of K + 1; -## NULL takes the narrow one where there are matrices M and few of them. +## Per unit by forward over reverse `rows`, the exact eta rows of the data Hessian, and `traces`, grad tr(M H_u) +## of the matrices `Ms[[u]]` with H_u the Gauss-Newton Hessian in the unit etas: one sweep along all tangents +## (`narrow = FALSE`) or one per direction (.sweepNarrow()); NULL takes the narrow one for few matrices M. .sweepUnits <- function(design, full, fixed, units, Ms = NULL, cores = 1L, fw = NULL, narrow = NULL) { Ke <- max(1L, vapply(units, function(u) length(u$eta), 0L)) nM <- max(0L, lengths(Ms)) @@ -274,10 +263,9 @@ l_ <- function(i, j) lr[, i + 1L, j + 1L] if (narrow) return(.sweepNarrow(design, full, fixed, units, Ms, cores, fw, r, l_, unitOf)) Ku <- rep(vapply(units, function(u) length(u$eta), 0L)[unitOf[fw$conds]], r$n) - # block 1, the data Hessian along every tangent: seed the loss gradient, the derivative - # L (pd, sd); block j + 1, for grad tr(M H_u) = sum_jk M_jk U_jk with symmetric M: seed - # 2 L J_j, and along tangent k the seeds of J_j' dL J_k, so that U has the derivatives - # through J and through L + # block 1, the data Hessian along every tangent: seed the loss gradient, derivative L (pd, sd); block j + 1, + # grad tr(M H_u) = sum_jk M_jk U_jk for symmetric M: seed 2 L J_j and along tangent k J_j' dL J_k, so that U + # has the derivatives through J and through L a <- r$pd; b <- r$sd sp <- ss <- matrix(0, length(r$p), B * (K + 1L)) sp[, 1L] <- l_(1, 0); sp[, 1L + seq_len(K)] <- l_(2, 0) * a + l_(1, 1) * b @@ -316,12 +304,9 @@ }) } -## The rows and trace gradients of .sweepUnits() direction by direction. Along eta_k, from a -## forward pass along it alone over the conditions whose unit has a k-th eta: row k of the Hessian -## from the loss gradient seeded with the loss derivative L J_k along the tangent, and with M symmetric -## sum_j M_jk U_jk from the seed 2 L J M_k with, along the tangent, J M_k' dL J_k. The rows `r` and -## loss derivatives `l_` are those of the full pass `fw`; a matrix M that is 0 in every unit has no -## seed. +## The rows and trace gradients of .sweepUnits() per direction eta_k from a forward pass along it alone: row k +## from the loss gradient seeded with L J_k, sum_j M_jk U_jk from the seed 2 L J M_k with J M_k' dL J_k along the +## tangent. `r` and `l_` are those of `fw`; a matrix M that is 0 in every unit has no seed. .sweepNarrow <- function(design, full, fixed, units, Ms, cores, fw, r, l_, unitOf) { nM <- max(lengths(Ms)) Msym <- lapply(Ms, function(ml) lapply(ml, function(Mm) (Mm + t(Mm)) / 2)) @@ -410,13 +395,9 @@ } -## The volume term sum_u log|H_u| of FOCEI by forward over reverse: the gradient in `outer` and -## the mode shift d eta*/d theta = -H_ee^-1 H_eA per unit, H_u^-1 from `H_inv_list`, from the -## eta rows of the joint Hessian and the trace gradient at M = H_u^-1 (`.sweepUnits()`). With -## `curvature` also the volume Hessian from dH_u/dtheta, the trace gradients at the unit matrices: -## -tr(H^-1 D_a H H^-1 D_b H) + tr(H^-1 d2P_ab), without the terms of the curvature of the -## prediction in the etas. With `local` the shift and the Hessian of a unit have the columns of the -## parameters it depends on only. +## The volume term sum_u log|H_u| of FOCEI by forward over reverse (.sweepUnits()): the gradient in `outer`, the +## shift -H_ee^-1 H_eA per unit and with `curvature` the Hessian -tr(H^-1 D_a H H^-1 D_b H) + tr(H^-1 d2P_ab); +## with `local` the shift and Hessian of a unit only in the parameters it depends on. .volumeReverse <- function(design, full, fixed, outer, H_inv_list, cores = 1L, local = FALSE, curvature = FALSE) { units <- .volumeUnits(design, full, fixed) diff --git a/R/normL2reverse.R b/R/normL2reverse.R index eedb40e9..8f07fa38 100644 --- a/R/normL2reverse.R +++ b/R/normL2reverse.R @@ -144,10 +144,9 @@ out } -# The seed as one cotangent per condition aligned with `prediction`, direct and -# through the error model, whose forward tape `err_tape` covers the conditions at -# positions `err_idx`. Rows follow the kernel's ALOQ-then-BLOQ order; fixed-sigma -# rows get no sigma seed. +# The seed as one cotangent per condition of `prediction`, direct and through the error model, whose tape +# `err_tape` covers the conditions at `err_idx`; rows in the ALOQ-then-BLOQ order of the kernel, fixed-sigma +# rows without a sigma seed. .normL2SeedCt <- function(meta_list, prediction, err_list, kr, err_tape, err_idx = NULL, env = NULL, cores = 1L, K = 1L) { n <- length(meta_list) diff --git a/R/objClass.R b/R/objClass.R index 8278f253..a5605500 100644 --- a/R/objClass.R +++ b/R/objClass.R @@ -34,7 +34,6 @@ as.objlist <- function(p) { #' @param dataI `data.frame` of one condition of a [datalist], with columns #' `name`, `time`, `value` and `sigma`. #' @param predictionI [prdframe] of that condition. -#' @param pars Named numeric parameter vector. #' @param errfn Optional [obsfn], the error model. Default `NULL`. #' @param fixed Optional named numeric vector of fixed parameters, passed to #' `errfn`. Default `NULL`. @@ -54,7 +53,7 @@ as.objlist <- function(p) { #' @seealso [normL2()] #' @keywords internal #' @export -evalConditionResidual <- function(dataI, predictionI, pars, +evalConditionResidual <- function(dataI, predictionI, errfn = NULL, fixed = NULL, cn = NULL, @@ -131,15 +130,48 @@ evalConditionResidual <- function(dataI, predictionI, pars, } out } -# Resolve deriv -> hessian -> deriv2. `hessian = NULL` means TRUE forward, FALSE -# backwards, TRUE under deriv2. A contradicting explicit value (deriv2 with -# hessian = FALSE, or hessian backwards without deriv2) warns and takes the cheaper. +# The data rows `st` of an objlist (see objlist()) over the parameters `pnames`, zero for a +# parameter they lack; unnamed columns are taken as `pnames`. +.structureOver <- function(st, pnames) { + if (is.null(st)) return(NULL) + J <- st$jacobian + H <- st$hessian + if (!is.null(colnames(J)) && !identical(colnames(J), pnames)) { + Z <- matrix(0, nrow(J), length(pnames), dimnames = list(NULL, pnames)) + hit <- .intersect(pnames, colnames(J)) + Z[, hit] <- J[, hit, drop = FALSE] + J <- Z + } + if (!is.null(rownames(H)) && !identical(rownames(H), pnames)) { + Z <- matrix(0, length(pnames), length(pnames), dimnames = list(pnames, pnames)) + hit <- .intersect(pnames, rownames(H)) + Z[hit, hit] <- H[hit, hit] + H <- Z + } + list(jacobian = J, seeds = st$seeds, hessian = H) +} + +# The data rows of two terms of a sum over the parameters `pars`: the rows stacked, the +# Gauss-Newton Hessians of the data terms added. +.structureBind <- function(s1, s2, pars) { + if (is.null(s1)) return(.structureOver(s2, pars)) + if (is.null(s2)) return(.structureOver(s1, pars)) + a <- .structureOver(s1, pars) + b <- .structureOver(s2, pars) + list(jacobian = rbind(a$jacobian, b$jacobian), seeds = c(a$seeds, b$seeds), hessian = a$hessian + b$hessian) +} + +# Resolve deriv -> hessian -> deriv2: `hessian = NULL` is TRUE forward or under deriv2, FALSE +# backwards; a contradicting explicit value warns and takes the cheaper. "structured" is the +# Gauss-Newton Hessian with the data rows of the term, see objlist(). .resolveCurvature <- function(deriv, deriv2, hessian, sweep) { reverse <- identical(sweep, "reverse") asked <- !is.null(hessian) sparse <- identical(hessian, "sparse") + expected <- identical(hessian, "expected") + structured <- identical(hessian, "structured") deriv2 <- isTRUE(deriv2) - want <- if (asked) isTRUE(hessian) || sparse else (deriv2 || !reverse) + want <- if (asked) isTRUE(hessian) || sparse || expected || structured else (deriv2 || !reverse) if (deriv2 && asked && !want) { warning("'hessian = FALSE' overrides 'deriv2 = TRUE'; no Hessian is built.", @@ -155,7 +187,8 @@ evalConditionResidual <- function(dataI, predictionI, pars, want <- FALSE } want <- isTRUE(deriv) && want - list(hessian = want, deriv2 = deriv2 && want, sparse = sparse && want) + list(hessian = want, deriv2 = deriv2 && want, sparse = sparse && want, expected = expected && want && !deriv2, + structured = structured && want && !deriv2) } @@ -318,13 +351,13 @@ normT <- function(data, x, errmodel = NULL, df, times = NULL, attrName = "data", # the plans of the native chain (.chainContext()) .chain <- .chainContext(list(prdfn = x, errfn = errmodel, data = data, timesD = timesD)) .chainObjective <- function(pars, fixed, conditions, deriv, deriv2, hessian, cores, parsList = NULL, - sparse = FALSE) { + sparse = FALSE, rows = FALSE) { free <- if (is.null(parsList)) rep(list(names(pars)), length(conditions)) else lapply(parsList, names) plan <- .chainLookup(.chain, conditions, free, names(fixed), if (is.null(parsList)) names(pars), deriv, deriv2) if (is.null(plan)) return(NULL) values <- if (is.null(parsList)) list(c(unclass(pars), unclass(fixed))) else lapply(parsList, function(p) c(unclass(p), unclass(fixed))) - .chainEval(plan, values, deriv, deriv2, hessian, !is.null(parsList), cores, optBLOQ, df, sparse) + .chainEval(plan, values, deriv, deriv2, hessian, !is.null(parsList), cores, optBLOQ, df, sparse, rows) } # Controls of the objective, changed later by controls<-. trust() lays out the @@ -352,6 +385,8 @@ normT <- function(data, x, errmodel = NULL, df, times = NULL, attrName = "data", hessian <- cv$hessian deriv2 <- cv$deriv2 sparse <- cv$sparse + expected <- cv$expected + structured <- cv$structured if (identical(sweep, "reverse")) { if (!is.null(.prediction)) stop("normL2: a handed-in prediction is a forward-mode shortcut and ", @@ -389,15 +424,18 @@ normT <- function(data, x, errmodel = NULL, df, times = NULL, attrName = "data", # the native chain where the pieces of the chain allow it, the R path below otherwise; the predictions # are computed when the environment is asked for them - if (is.null(.prediction) && !.local && .evalCpp() && + if (is.null(.prediction) && !.local && !expected && .evalCpp() && !exists("prediction", envir = env, inherits = FALSE)) { - res <- .chainObjective(pars, fixed, conditions, deriv, deriv2, build_hessian, cores, sparse = sparse) + res <- .chainObjective(pars, fixed, conditions, deriv, deriv2, build_hessian, cores, sparse = sparse, + rows = structured) if (!is.null(res)) { pn <- names(pars) H <- if (build_hessian && sparse) .sparseFromSlots(res$hessian, pn) else if (build_hessian) matrix(res$hessian, length(pn), dimnames = list(pn, pn)) out <- if (deriv) objlist(value = res$value, gradient = setNames(res$gradient, pn), hessian = H) else objlist(value = res$value, gradient = NULL, hessian = NULL) + if (structured) + out$structure <- list(jacobian = `colnames<-`(res$rows$jacobian, pn), seeds = res$rows$seeds, hessian = H) attr(out, attrName) <- out$value attr(out, "chi2") <- setNames(res$chi2, attrName) delayedAssign("prediction", x(times = .timesOf(conditions), pars = pars, fixed = fixed, deriv = deriv, @@ -503,7 +541,9 @@ normT <- function(data, x, errmodel = NULL, df, times = NULL, attrName = "data", bloq_mode = optBLOQ, build_hessian = build_hessian, local_blocks = .local || (build_hessian && sparse), - t_df = df + t_df = df, + expected = expected, + want_rows = structured ) # the value, gradient and Hessian of every condition in the condition parameters if (.local) return(setNames(kr$local, conditions)) @@ -515,6 +555,12 @@ normT <- function(data, x, errmodel = NULL, df, times = NULL, attrName = "data", hessian = kr$hessian), names(pars)) else objlist(value = kr$value, gradient = NULL, hessian = NULL) + if (structured) { + J <- kr$rows$jacobian + colnames(J) <- par_names_global + out$structure <- .structureOver(list(jacobian = J, seeds = kr$rows$seeds, hessian = out$hessian), + names(pars)) + } attr(out, attrName) <- out$value # The sum of squares alone, tagged with the contribution it belongs to. # Summing objectives pools terms sharing an `attrName` into one `chi2` and @@ -1363,6 +1409,8 @@ datapointL2 <- function(name, time, parameter, sigma = 1, } lr <- .lowrankBind(e1$lowrank, e2$lowrank) if (!is.null(lr)) out12$lowrank <- lr + if (!is.null(e1$structure) || !is.null(e2$structure)) + out12$structure <- .structureBind(e1$structure, e2$structure, pars) # Numeric attributes are summed, an absent one counting as zero. The chi2 contributions are kept # apart from that: they are pooled by the `attrName` they belong to, not by the attribute they @@ -1636,6 +1684,15 @@ res <- function(data, out, err = NULL) { #' @details Asked for `hessian = "sparse"`, an objective may return part of #' the Hessian in an entry `lowrank`, a list of a matrix `U` with parameter #' rows and a vector `d`: the Hessian is then `hessian + U diag(d) U'`. +#' +#' Asked for `hessian = "structured"`, a data term such as [normL2()] +#' returns the Gauss-Newton Hessian and an entry `structure`, a list of the +#' matrix `jacobian`, one row per data point with the derivatives of the +#' prediction, and one more for a sigma that depends on parameters, the +#' vector `seeds` of the derivatives of the value in these predictions and +#' sigmas, and the Gauss-Newton Hessian `hessian` of the data term. `+` stacks +#' the rows and adds the Hessians; a term without data rows has none. +#' The structured methods of [trust()] read it. #' @return An object of class `objlist`. #' @seealso [as.objlist()] #' @export diff --git a/R/parClass.R b/R/parClass.R index 0f6a90a4..4b9e746e 100644 --- a/R/parClass.R +++ b/R/parClass.R @@ -279,7 +279,7 @@ plotPars.parframe <- function(x, ..., tol = 1) { parOut <- .wide2long.data.frame(out = x[, c("step", "value", parNames)], keep = 1:2) names(parOut) <- c("step", "value", "name", "parvalue") plot <- ggplot2::ggplot(parOut, aes(x = name, y = parvalue, color = step)) + - geom_boxplot(outlier.alpha = 0) + theme_dMod() + scale_color_dMod() + + geom_boxplot(outlier.alpha = 0) + theme_dMod2() + scale_color_dMod2() + guides(x = guide_axis(angle = 90)) attr(plot, "data") <- parOut @@ -313,14 +313,14 @@ plotPars.parframe <- function(x, ..., tol = 1) { } -# Plain numbers below 10^4, powers of ten from there, so that a wide axis keeps short labels. +# Powers of ten as 10^k on every tick when all nonzero breaks are powers of ten, plain numbers +# on every tick otherwise. .decadeLabels <- function(breaks) { labels <- format(breaks, trim = TRUE, scientific = FALSE, drop0trailing = TRUE) - big <- is.finite(breaks) & abs(breaks) >= 1e4 - k <- floor(log10(abs(breaks[big])) + 1e-9) - m <- round(breaks[big] / 10^k) - labels[big] <- ifelse(m == 1, paste0("10^", k), - ifelse(m == -1, paste0("-10^", k), paste0(m, " %*% 10^", k))) + nz <- is.finite(breaks) & breaks != 0 + k <- round(log10(abs(breaks[nz]))) + if (!all(abs(abs(breaks[nz]) / 10^k - 1) < 1e-9)) return(labels) + labels[nz] <- paste0(ifelse(breaks[nz] < 0, "-", ""), "10^", k) parse(text = labels) } @@ -404,11 +404,11 @@ plotValues.list <- function(x, ..., tol = 1, showSteps = FALSE, pseudoLog = FALS # entry for it conv <- pars$converged %in% TRUE unconverged <- if (!all(conv)) list( - geom_point(data = pars[!conv, ], aes(shape = "not converged"), color = dMod_colors[2]), + geom_point(data = pars[!conv, ], aes(shape = "not converged"), color = dMod2_colors[2]), scale_shape_manual(values = c(`not converged` = 19), - guide = guide_legend(override.aes = list(color = dMod_colors[2]), + guide = guide_legend(override.aes = list(color = dMod2_colors[2]), order = 1))) - converged <- if (iterations) list(geom_point(data = pars[conv, ], aes(color = iterations)), scale_color_dMod_c()) + converged <- if (iterations) list(geom_point(data = pars[conv, ], aes(color = iterations)), scale_color_dMod2_c()) else geom_point(data = pars[conv, ]) P <- ggplot2::ggplot(pars, aes(x = index, y = shown)) + @@ -420,7 +420,7 @@ plotValues.list <- function(x, ..., tol = 1, showSteps = FALSE, pseudoLog = FALS scale_x_continuous(breaks = scales::breaks_pretty(n = 3)))) + labs(x = "Fit rank", y = if (!is.null(ref) || relative) "Objective value above the best" else "Objective value", color = "Iterations", shape = NULL) + - theme_dMod() + + theme_dMod2() + (if (!is.null(sets)) theme(panel.spacing.x = ggplot2::unit(1, "lines"))) structure(P, data = pars, jumps = if (is.null(sets)) jumps[[1]] else stats::setNames(jumps, sets)) @@ -832,6 +832,15 @@ print.parvec <- function(x, ...) { #' @export c.parvec <- function(...) { + # An operand without names takes the argument name, numbered for several values. + an <- ...names() + if (any(nzchar(an))) { + args <- list(...) + for (i in which(nzchar(an) & vapply(args, function(z) is.null(names(z)) && length(z) > 0L, TRUE))) + names(args[[i]]) <- if (length(args[[i]]) == 1L) an[i] else paste0(an[i], seq_along(args[[i]])) + return(do.call(c.parvec, unname(args))) + } + # One operand, alone or beside NULL or an empty one, as # prdframe(parameters = c(pars, fixed)) has it for every condition: the same # result as below, without the list machinery. diff --git a/R/parameters.R b/R/parameters.R index e98b8409..e2ad82b7 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -760,7 +760,7 @@ Pexpl <- function(trafo, parameters = NULL, attachInput = FALSE, condition = NUL # Pimpl solver controls merged over their defaults. Unknown names are an error. .pimplPTC <- function(controlsPTC) { def <- list(reltol = 1e-10, abstol = 1e-14, flowTol = 1, maxit = NULL, dtInit = 1e-2, - positive = TRUE, stability = TRUE, stabilityTol = 0, stabilityMargin = 1e-6, + positive = TRUE, stability = TRUE, stabilityTol = 0, nStarts = 20L, startRange = c(-5, 5), startScale = NULL, seed = 1L) given <- as.list(controlsPTC) if (length(given) && (is.null(names(given)) || any(!nzchar(names(given))))) @@ -779,8 +779,6 @@ Pexpl <- function(trafo, parameters = NULL, attachInput = FALSE, condition = NUL stop("Pimpl: a linear startRange below 0 needs positive = FALSE.", call. = FALSE) if (!(is.numeric(ctrl$stabilityTol) && length(ctrl$stabilityTol) == 1L && ctrl$stabilityTol >= 0)) stop("Pimpl: stabilityTol is a number of at least 0.", call. = FALSE) - if (!(is.numeric(ctrl$stabilityMargin) && length(ctrl$stabilityMargin) == 1L && ctrl$stabilityMargin > 0)) - stop("Pimpl: stabilityMargin is a positive number.", call. = FALSE) ctrl } @@ -833,9 +831,6 @@ Pexpl <- function(trafo, parameters = NULL, attachInput = FALSE, condition = NUL #' admits a resting state that departs from rest more slowly than a time #' scale of interest, as near a Hopf bifurcation. [constraintStability()] #' reaches the weight at `stabilityTol`.} -#' \item{`stabilityMargin`}{The width of the ramp of [constraintStability()] -#' below `stabilityTol`, relative to the largest eigenvalue modulus on the -#' manifold of the conserved quantities; default `1e-6`.} #' \item{`nStarts`}{Random starts after the deterministic ones, default #' `20`.} #' \item{`startRange`}{Range of a random start, drawn uniformly per @@ -1062,7 +1057,7 @@ Pimpl <- function(trafo, parameters = NULL, forcings = NULL, condition = NULL, rownames(sp$vectors) <- dependent sp } - attr(p2p, "stabilityTol") <- function() unlist(.pimplPTC(ctl$controlsPTC)[c("stabilityMargin", "stabilityTol")]) + attr(p2p, "stabilityTol") <- function() .pimplPTC(ctl$controlsPTC)$stabilityTol attr(p2p, "equations") <- as.eqnvec(all_exprs) attr(p2p, "parameters") <- parameters attr(p2p, "modelname") <- modelname diff --git a/R/plots.R b/R/plots.R index 4a91a682..1975b6cd 100644 --- a/R/plots.R +++ b/R/plots.R @@ -7,29 +7,27 @@ utils::globalVariables(c("predicted", "observed", "sd_est", "iter", "level", "sh # Theme and color palettes --- -#' Standard Plotting Theme of dMod +#' Standard Plotting Theme of dMod2 #' #' @param base_size Numeric, base font size. Defaults to 12. #' @param base_family Character, font family. Defaults to `""`. #' @param showGrid Logical, keep the panel grid. `FALSE` (default) drops it; #' `TRUE` keeps the grid of [ggplot2::theme_bw()]. #' @return A `ggplot2` theme. -#' @seealso [scale_color_dMod()] +#' @seealso [scale_color_dMod2()] #' @export #' @examples #' library(ggplot2) #' ggplot(data.frame(x = 1:10, y = (1:10)^2), aes(x, y)) + -#' geom_line() + theme_dMod() -theme_dMod <- function(base_size = 12, base_family = "", showGrid = FALSE) { +#' geom_line() + theme_dMod2() +theme_dMod2 <- function(base_size = 12, base_family = "", showGrid = FALSE) { theme_bw(base_size = base_size, base_family = base_family) + theme(line = element_line(color = "black"), rect = element_rect(fill = "white", color = NA), text = element_text(color = "black"), axis.text = element_text(size = rel(1.0), color = "black"), - axis.text.x = element_text(margin = margin(t = 4, r = 4, b = 0, l = 4, unit = "mm")), - axis.text.y = element_text(margin = margin(t = 4, r = 4, b = 4, l = 0, unit = "mm")), axis.ticks = element_line(color = "black"), - axis.ticks.length = unit(-2, "mm"), + axis.ticks.length = unit(1.5, "mm"), legend.key = element_rect(color = NA), panel.border = element_rect(color = "black"), strip.background = element_rect(fill = "white", color = NA), @@ -42,15 +40,15 @@ theme_dMod <- function(base_size = 12, base_family = "", showGrid = FALSE) { # dE: smallest pairwise CIE2000 distance over normal and simulated dichromatic # vision (colorspace, farver::compare_colour()); 10 or above is colorblind-safe. -#' Seed Colors of the dMod Palette +#' Seed Colors of the dMod2 Palette #' #' The ten qualitative house colors. They are not colorblind-safe, see -#' [dMod_palettes()] for alternatives. +#' [dMod2_palettes()] for alternatives. #' #' @format A character vector of hex color codes. -#' @seealso [dMod_colors_cb], [dMod_palette()] +#' @seealso [dMod2_colors_cb], [dMod2_palette()] #' @export -dMod_colors <- c("#000000", "#C5000B", "#0084D1", "#579D1C", "#FF950E", +dMod2_colors <- c("#000000", "#C5000B", "#0084D1", "#579D1C", "#FF950E", "#4B1F6F", "#CC79A7", "#006400", "#F0E442", "#8B4513") #' Colorblind-Safe Seed Colors @@ -59,18 +57,18 @@ dMod_colors <- c("#000000", "#C5000B", "#0084D1", "#579D1C", "#FF950E", #' eight are the Okabe-Ito colors. #' #' @format A character vector of 20 hex color codes. -#' @seealso [dMod_colors], [dMod_palette()] +#' @seealso [dMod2_colors], [dMod2_palette()] #' @export -dMod_colors_cb <- c( +dMod2_colors_cb <- c( "#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7", "#4F3408", "#072F62", "#645B68", "#4E644A", "#A6D38F", "#2600DA", "#3F3644", "#02ECC9", "#7B75FD", "#954A0E", "#323C2D", "#6D7F80") -# Qualitative palettes. Five colorblind-safe, five not; `dMod_palette()` and -# `scale_color_dMod()` pick from here by name. +# Qualitative palettes. Five colorblind-safe, five not; `dMod2_palette()` and +# `scale_color_dMod2()` pick from here by name. .dMod_qual <- list( - okabe = list(dE = 11.1, colors = dMod_colors_cb), + okabe = list(dE = 11.1, colors = dMod2_colors_cb), muted = list(dE = 11.6, colors = c( "#332288", "#88CCEE", "#44AA99", "#117733", "#999933", "#DDCC77", "#CC6677", "#882255", "#AA4499", "#2D330A", "#9B7BFB", "#FC8FB1", "#1E352C", "#A884B7")), @@ -81,7 +79,7 @@ dMod_colors_cb <- c( "#000000", "#004488", "#994455", "#997700", "#8770FD", "#3F2D11", "#8B8491", "#2B303D", "#616689", "#525901", "#758E65", "#6D38DB")), contrast = list(dE = 21.4, colors = c("#004488", "#DDAA33", "#BB5566")), - dMod = list(dE = 2.1, colors = dMod_colors), + dMod = list(dE = 2.1, colors = dMod2_colors), dark2 = list(dE = 2.3, colors = c( "#1B9E77", "#D95F02", "#7570B3", "#E7298A", "#66A61E", "#E6AB02", "#A6761D", "#666666")), @@ -95,42 +93,42 @@ dMod_colors_cb <- c( "#A6CEE3", "#1F78B4", "#B2DF8A", "#33A02C", "#FB9A99", "#E31A1C", "#FDBF6F", "#FF7F00", "#CAB2D6", "#6A3D9A", "#FFFF99", "#B15928"))) -#' Continuous dMod Color Ramps +#' Continuous dMod2 Color Ramps #' -#' `dMod_gradient` is the sequential house ramp, `dMod_divergent` the diverging -#' one; `dMod_gradient_cb` and `dMod_divergent_cb` are their colorblind-safe -#' counterparts and the defaults of [scale_color_dMod_c()] and -#' [scale_color_dMod_div()]. See [dMod_palettes()] for the full set. +#' `dMod2_gradient` is the sequential house ramp, `dMod2_divergent` the diverging +#' one; `dMod2_gradient_cb` and `dMod2_divergent_cb` are their colorblind-safe +#' counterparts and the defaults of [scale_color_dMod2_c()] and +#' [scale_color_dMod2_div()]. See [dMod2_palettes()] for the full set. #' #' @format Character vectors of hex color codes. #' @export -dMod_gradient <- c("#4B1F6F", "#0084D1", "#579D1C", "#FF950E", "#F0E442") +dMod2_gradient <- c("#4B1F6F", "#0084D1", "#579D1C", "#FF950E", "#F0E442") #' @export -#' @rdname dMod_gradient -dMod_gradient_cb <- c("#000000", "#4B1F6F", "#0072B2", "#009E73", +#' @rdname dMod2_gradient +dMod2_gradient_cb <- c("#000000", "#4B1F6F", "#0072B2", "#009E73", "#E69F00", "#F0E442") #' @export -#' @rdname dMod_gradient -dMod_divergent <- c("#0084D1", "#FFFFFF", "#C5000B") +#' @rdname dMod2_gradient +dMod2_divergent <- c("#0084D1", "#FFFFFF", "#C5000B") #' @export -#' @rdname dMod_gradient -dMod_divergent_cb <- c("#072F62", "#56B4E9", "#FFFFFF", "#E69F00", "#4F3408") +#' @rdname dMod2_gradient +dMod2_divergent_cb <- c("#072F62", "#56B4E9", "#FFFFFF", "#E69F00", "#4F3408") .dMod_seq <- list( - okabe = list(dE = 12.0, colors = dMod_gradient_cb), + okabe = list(dE = 12.0, colors = dMod2_gradient_cb), viridis = list(dE = 13.8, colors = c("#440154","#3B528B","#21908C","#5DC863","#FDE725")), gray = list(dE = 13.2, colors = c("#111111", "#DDDDDD")), heat = list(dE = 10.7, colors = c("#FFFFFF", "#FF950E", "#C5000B")), - dMod = list(dE = 5.4, colors = dMod_gradient)) + dMod = list(dE = 5.4, colors = dMod2_gradient)) .dMod_div <- list( - okabe = list(dE = 25.6, colors = dMod_divergent_cb), + okabe = list(dE = 25.6, colors = dMod2_divergent_cb), puor = list(dE = 15.7, colors = c("#5E3C99","#B2ABD2","#F7F7F7","#FDB863","#E66101")), rdbu = list(dE = 15.2, colors = c("#CA0020","#F4A582","#F7F7F7","#92C5DE","#0571B0")), - dMod = list(dE = 12.5, colors = dMod_divergent), + dMod = list(dE = 12.5, colors = dMod2_divergent), brbg = list(dE = 7.9, colors = c("#A6611A","#DFC27D","#F5F5F5","#80CDC1","#018571"))) .dMod_registry <- list(qualitative = .dMod_qual, sequential = .dMod_seq, @@ -139,16 +137,16 @@ dMod_divergent_cb <- c("#072F62", "#56B4E9", "#FFFFFF", "#E69F00", "#4F3408") .dMod_pick <- function(palette, type) { reg <- .dMod_registry[[type]] if (!is.character(palette) || length(palette) != 1L || !palette %in% names(reg)) - stop("dMod: no ", type, " palette \"", paste(palette, collapse = ", "), + stop("dMod2: no ", type, " palette \"", paste(palette, collapse = ", "), "\". Available: ", paste(names(reg), collapse = ", "), - ". See dMod_palettes().", call. = FALSE) + ". See dMod2_palettes().", call. = FALSE) reg[[palette]] } -#' Overview of the dMod Palettes +#' Overview of the dMod2 Palettes #' -#' One row per palette. Pass any of the names as `palette` to [dMod_palette()], -#' [scale_color_dMod()], [scale_color_dMod_c()] or [scale_color_dMod_div()]. +#' One row per palette. Pass any of the names as `palette` to [dMod2_palette()], +#' [scale_color_dMod2()], [scale_color_dMod2_c()] or [scale_color_dMod2_div()]. #' #' @param type `NULL` (default) for all palettes, or any of `"qualitative"`, #' `"sequential"` and `"diverging"`. @@ -157,9 +155,9 @@ dMod_divergent_cb <- c("#072F62", "#56B4E9", "#FFFFFF", "#E69F00", "#4F3408") #' simulated dichromatic vision) and `colorblind` (`dE >= 10`). #' @export #' @examples -#' dMod_palettes() -#' dMod_palettes("qualitative") -dMod_palettes <- function(type = NULL) { +#' dMod2_palettes() +#' dMod2_palettes("qualitative") +dMod2_palettes <- function(type = NULL) { types <- if (is.null(type)) names(.dMod_registry) else match.arg( type, names(.dMod_registry), several.ok = TRUE) out <- do.call(rbind, lapply(types, function(ty) { @@ -173,7 +171,7 @@ dMod_palettes <- function(type = NULL) { out[order(out$type, !out$colorblind, -out$dE), ] } -#' Generate Distinct Colors from a dMod Palette +#' Generate Distinct Colors from a dMod2 Palette #' #' Returns the first `n` colors of the chosen palette. Beyond the seeds of the palette the #' colors come from `Polychrome::createPalette()` if Polychrome is installed and @@ -181,21 +179,21 @@ dMod_palettes <- function(type = NULL) { #' colorblind-safe; a colorblind-safe palette warns when it runs out of seeds. #' #' @param n Integer, number of colors. -#' @param palette Name of a qualitative palette, see [dMod_palettes()]. +#' @param palette Name of a qualitative palette, see [dMod2_palettes()]. #' Defaults to `"okabe"`. #' @return Character vector of length `n` with hex color codes. #' @export #' @examples -#' dMod_palette(3) -#' dMod_palette(3, palette = "muted") -dMod_palette <- function(n, palette = "okabe") { +#' dMod2_palette(3) +#' dMod2_palette(3, palette = "muted") +dMod2_palette <- function(n, palette = "okabe") { n <- as.integer(n) if (n <= 0L) return(character(0)) pal <- .dMod_pick(palette, "qualitative") seeds <- pal$colors if (n <= length(seeds)) return(unname(seeds[seq_len(n)])) if (pal$dE >= 10) - warning("dMod_palette(): palette \"", palette, "\" holds ", length(seeds), + warning("dMod2_palette(): palette \"", palette, "\" holds ", length(seeds), " colorblind-safe colors, ", n, " were requested. The extra ", n - length(seeds), " are not: encode them with linetype, shape ", "or facets instead.", call. = FALSE) @@ -221,13 +219,13 @@ dMod_palette <- function(n, palette = "okabe") { c(seeds, grDevices::hcl.colors(n - length(seeds), "Dark 3")) } -#' Discrete dMod Color Scales +#' Discrete dMod2 Color Scales #' -#' @param palette Name of a qualitative palette, see [dMod_palettes()]. +#' @param palette Name of a qualitative palette, see [dMod2_palettes()]. #' Defaults to the colorblind-safe `"okabe"`. #' @param ... Arguments passed to [ggplot2::discrete_scale()]. #' @return A discrete `ggplot2` scale. -#' @seealso [scale_color_dMod_c()], [dMod_palette()] +#' @seealso [scale_color_dMod2_c()], [dMod2_palette()] #' @export #' @examples #' library(ggplot2) @@ -239,17 +237,17 @@ dMod_palette <- function(n, palette = "okabe") { #' group = rep(c("C1", "C2", "C3", "C4"), each = length(times)) #' ) #' ggplot(data, aes(time, value, color = group)) + geom_line() + -#' theme_dMod() + scale_color_dMod() -scale_color_dMod <- function(..., palette = "okabe") { +#' theme_dMod2() + scale_color_dMod2() +scale_color_dMod2 <- function(..., palette = "okabe") { ggplot2::discrete_scale(aesthetics = "color", - palette = function(n) dMod_palette(n, palette), ...) + palette = function(n) dMod2_palette(n, palette), ...) } #' @export -#' @rdname scale_color_dMod -scale_fill_dMod <- function(..., palette = "okabe") { +#' @rdname scale_color_dMod2 +scale_fill_dMod2 <- function(..., palette = "okabe") { ggplot2::discrete_scale(aesthetics = "fill", - palette = function(n) dMod_palette(n, palette), ...) + palette = function(n) dMod2_palette(n, palette), ...) } .dMod_ramp <- function(cols, direction) if (direction < 0) rev(cols) else cols @@ -259,56 +257,56 @@ scale_fill_dMod <- function(..., palette = "okabe") { scales::rescale_mid(x, to, from, mid) } -#' Continuous dMod Color Scales +#' Continuous dMod2 Color Scales #' #' Sequential (`_c`) and diverging (`_div`) counterparts of the discrete -#' [scale_color_dMod()]. The diverging scales map `mid` to white, also for +#' [scale_color_dMod2()]. The diverging scales map `mid` to white, also for #' asymmetric limits. #' #' @param mid Numeric, the value mapped to white. Defaults to 0. #' @param direction 1 (default) or -1; -1 reverses the ramp. #' @param palette Name of a sequential palette for `_c`, a diverging one for -#' `_div`, see [dMod_palettes()]. Defaults to the colorblind-safe `"okabe"`. +#' `_div`, see [dMod2_palettes()]. Defaults to the colorblind-safe `"okabe"`. #' @param ... Arguments passed to [ggplot2::scale_color_gradientn()] or #' [ggplot2::scale_fill_gradientn()]. #' @return A continuous `ggplot2` scale. -#' @seealso [scale_color_dMod()] +#' @seealso [scale_color_dMod2()] #' @export #' @examples #' library(ggplot2) #' d <- expand.grid(time = seq(0, 10, 0.1), eps = seq(0, 1, 0.1)) #' ggplot(d, aes(time, exp(-eps * time), group = eps, color = eps)) + -#' geom_line() + theme_dMod() + scale_color_dMod_c() -scale_color_dMod_c <- function(..., direction = 1, palette = "okabe") { +#' geom_line() + theme_dMod2() + scale_color_dMod2_c() +scale_color_dMod2_c <- function(..., direction = 1, palette = "okabe") { ggplot2::scale_color_gradientn( colors = .dMod_ramp(.dMod_pick(palette, "sequential")$colors, direction), ...) } #' @export -#' @rdname scale_color_dMod_c -scale_fill_dMod_c <- function(..., direction = 1, palette = "okabe") { +#' @rdname scale_color_dMod2_c +scale_fill_dMod2_c <- function(..., direction = 1, palette = "okabe") { ggplot2::scale_fill_gradientn( colors = .dMod_ramp(.dMod_pick(palette, "sequential")$colors, direction), ...) } #' @export -#' @rdname scale_color_dMod_c -scale_color_dMod_div <- function(mid = 0, ..., direction = 1, palette = "okabe") { +#' @rdname scale_color_dMod2_c +scale_color_dMod2_div <- function(mid = 0, ..., direction = 1, palette = "okabe") { ggplot2::scale_color_gradientn( colors = .dMod_ramp(.dMod_pick(palette, "diverging")$colors, direction), rescaler = .dMod_mid_rescaler(mid), ...) } #' @export -#' @rdname scale_color_dMod_c -scale_fill_dMod_div <- function(mid = 0, ..., direction = 1, palette = "okabe") { +#' @rdname scale_color_dMod2_c +scale_fill_dMod2_div <- function(mid = 0, ..., direction = 1, palette = "okabe") { ggplot2::scale_fill_gradientn( colors = .dMod_ramp(.dMod_pick(palette, "diverging")$colors, direction), rescaler = .dMod_mid_rescaler(mid), ...) } -ggplot <- function(...) ggplot2::ggplot(...) + scale_color_dMod() + theme_dMod() +ggplot <- function(...) ggplot2::ggplot(...) + scale_color_dMod2() + theme_dMod2() # Transformation of plotted values --------------------------------------- @@ -514,9 +512,9 @@ plotPaths <- function(profs, ..., whichPar = NULL, sort = FALSE, relative = TRUE geom_path() + facet_wrap(vars(combination), scales = scales) + labs(x = axisLabel(1), y = axisLabel(2)) + - scale_color_dMod(name = "profiled\nparameter") + + scale_color_dMod2(name = "profiled\nparameter") + scale_linetype_discrete("profile\nlist") + - theme_dMod() + theme_dMod2() # a legend with a single entry says nothing if (length(unique(paths$proflist)) < 2L) p <- p + guides(linetype = "none") if (length(unique(paths$name)) < 2L) p <- p + guides(color = "none") @@ -615,9 +613,9 @@ plotFluxes <- function(pouter, x, times, fluxEquations, legendTitle = "Fluxes:", p <- ggplot2::ggplot(out, aes(time, value, group = name, fill = name)) + geom_area(position = "stack", alpha = 0.3, color = "darkgray", linewidth = 0.4) + facet_wrap(vars(condition)) + - scale_fill_dMod(name = legendTitle) + + scale_fill_dMod2(name = legendTitle) + labs(x = "time", y = "flux contribution") + - theme_dMod() + theme_dMod2() attr(p, "out") <- out p } @@ -761,7 +759,7 @@ plotResiduals.default <- function(parframe, x, data, split = "condition", colorBy <- as.name(split[min(2L, length(split))]) p <- ggplot(out, aes(!!as.name(split[1]), res, color = !!colorBy, group = !!colorBy)) + - theme_dMod() + + theme_dMod2() + geom_point() + geom_line() if (length(split) > 2L) p <- p + facet_wrap(split[-(1:2)]) @@ -874,7 +872,7 @@ plotArray <- function(par, profs, prd, times, ..., direction = c("up", "down"), facet_grid(rows = vars(name), cols = vars(condition), scales = "free_y") + scale_color_viridis_c(name = par) + labs(x = "time", y = "value") + - theme_dMod() + theme_dMod2() } @@ -940,13 +938,13 @@ plotPathsMulti <- function(profs, whichPar, nPars = 5, normalizePaths = FALSE) { data.table::setorder(data, -max.dev) top <- head(unique(data$partner), nPars) data[, label := ifelse(partner %in% top, partner, "Others")] - colors <- c(setNames(dMod_palette(nPars + 1L)[-1L][seq_along(top)], top), Others = "gray") + colors <- c(setNames(dMod2_palette(nPars + 1L)[-1L][seq_along(top)], top), Others = "gray") corner <- .findEmptyCorner(data$x, data$y) p <- ggplot2::ggplot(data, aes(x = x, y = y, color = label, group = partner)) + geom_line() + xlab(whichPar) + ylab(expression(Delta ~ p[j])) + - scale_color_manual(name = NULL, values = colors, breaks = c(top, "Others")) + theme_dMod() + + scale_color_manual(name = NULL, values = colors, breaks = c(top, "Others")) + theme_dMod2() + theme(legend.position = "inside", legend.position.inside = corner, legend.justification = corner, diff --git a/R/plotsEM.R b/R/plotsEM.R index 7cddc770..f0a2906d 100644 --- a/R/plotsEM.R +++ b/R/plotsEM.R @@ -1,6 +1,7 @@ ## NLME plotting and prediction methods for `em` fits. -utils::globalVariables(c("IPRED", "PRED", "eta")) +utils::globalVariables(c("IPRED", "PRED", "eta", "part", "xmin", "xmax", "ymin", "ymax", "inclusion", "label", + "group", "estimate", "lower", "upper", "fit", "position", "width")) #' Random-effect distribution diagnostics #' @@ -55,10 +56,10 @@ plot.em <- function(x, ...) { ggplot2::facet_wrap(~ panel) } p + - scale_color_dMod() + + scale_color_dMod2() + ggplot2::labs(x = "Prediction", y = "Observed", title = sprintf("Observed vs predicted (method = %s)", fit$method)) + - theme_dMod(base_size = 11) + + theme_dMod2(base_size = 11) + ggplot2::theme(legend.position = "none") } @@ -99,11 +100,11 @@ plotResiduals.em <- function(parframe, type = c("IWRES", "CWRES", "NPDE"), nsim ggplot2::geom_abline(data = qq, ggplot2::aes(slope = 1, intercept = 0), linetype = "dashed", color = "gray50") + ggplot2::geom_point(alpha = 0.7, size = 1.2) + ggplot2::geom_smooth(data = scatter, ggplot2::aes(group = 1), se = FALSE, method = "loess", formula = y ~ x, - color = dMod_colors[2], linewidth = 0.6) + + color = dMod2_colors[2], linewidth = 0.6) + ggplot2::facet_grid(type ~ panel, scales = "free") + - scale_color_dMod(guide = if (length(unique(long$name)) > 1L) "legend" else "none") + + scale_color_dMod2(guide = if (length(unique(long$name)) > 1L) "legend" else "none") + ggplot2::labs(x = NULL, y = "residual", color = NULL, title = "Residual diagnostics") + - theme_dMod(base_size = 11) + theme_dMod2(base_size = 11) } #' Data and predictions of a mixed-effects fit @@ -144,7 +145,7 @@ plotCombined.em <- function(prediction, times = NULL, ncol = 4L, showPred = TRUE p <- ggplot2::ggplot() if (showBand && any(is.finite(grd$sigma))) p <- p + ggplot2::geom_ribbon(data = grd, ggplot2::aes(x = time, ymin = IPRED - sigma, ymax = IPRED + sigma), - fill = dMod_colors[3], alpha = 0.2, linetype = 0) + fill = dMod2_colors[3], alpha = 0.2, linetype = 0) p <- p + ggplot2::geom_line(data = grd, ggplot2::aes(x = time, y = IPRED, color = "IPRED"), linewidth = 0.7) if (showPred) p <- p + ggplot2::geom_line(data = grd, ggplot2::aes(x = time, y = PRED, color = "PRED"), @@ -153,9 +154,9 @@ plotCombined.em <- function(prediction, times = NULL, ncol = 4L, showPred = TRUE p <- p + if (multiple) ggplot2::facet_grid(name ~ condition, scales = "free_y") else ggplot2::facet_wrap(~ condition, ncol = ncol, scales = "free_y") title <- paste(sprintf("Data and predictions (method = %s)", fit$method), label) - p + ggplot2::scale_color_manual(values = c(IPRED = dMod_colors[3], PRED = dMod_colors[2])) + + p + ggplot2::scale_color_manual(values = c(IPRED = dMod2_colors[3], PRED = dMod2_colors[2])) + ggplot2::labs(x = "Time", y = "Value", color = NULL, title = trimws(title)) + - theme_dMod(base_size = 11) + theme_dMod2(base_size = 11) } if (is.null(conditionsPerPage)) return(page(pf)) @@ -173,10 +174,21 @@ plotCombined.em <- function(prediction, times = NULL, ncol = 4L, showPred = TRUE #' @rdname plotRandomEffects #' @param x An `em` fit, see [em()]. #' @param type `"conditional"` (default): per group `draws` values from the -#' conditional distribution of the random effects of the group, normal around the mode with -#' the conditional standard error; under the model they follow `N(0, Omega_kk)` -#' whatever the shrinkage. `"modes"`: the modes, narrower than `N(0, Omega_kk)` -#' by the shrinkage. +#' conditional distribution of the random effects of the group; under the +#' model they follow the random-effect distribution whatever the shrinkage. +#' A normal random effect is drawn normal around the mode with the +#' conditional standard error, against `N(0, Omega_kk)`. A spike-and-slab +#' random effect is 0 with the posterior probability `p0` and otherwise +#' normal, with the reported value, or where the reported structure has the +#' spike the mode of the slab, as mean and the variance that gives the +#' conditional standard error; drawn against the prior, the slab density +#' `prob N(0, tau^2)` and a cap at the height of a bar of area `1 - prob` +#' at 0. `"modes"`: the +#' modes, or the reported values of spike-and-slab random effects, narrower +#' than the distribution by the shrinkage. `"inclusion"`: a heatmap of the +#' posterior probability `1 - p0` of a deviation per group and sparse random +#' effect, labeled with the reported value where the reported structure has +#' a deviation. #' @param draws Number of draws per group with `type = "conditional"`. Default 20. #' @param bins Number of bars of every histogram. Default 30. #' @param covariates Columns of the condition grid of the data of the fit @@ -186,53 +198,67 @@ plotCombined.em <- function(prediction, times = NULL, ncol = 4L, showPred = TRUE #' loess trend for a numeric covariate of more than five values, boxes for #' the others. #' @param ... Ignored. -#' @return A ggplot, or without cowplot a list with `hist` and `qq`. With -#' `covariates`, a ggplot for one covariate; for several a cowplot grid, or -#' without cowplot a list of ggplots named by covariate. +#' @return A ggplot, or without cowplot a list with `hist` and `qq`; the QQ +#' plot has the normal random effects only, a fit with sparse random effects +#' alone gives the histograms as one ggplot. With `type = "inclusion"` a +#' ggplot. With `covariates`, a ggplot for one covariate; for several a +#' cowplot grid, or without cowplot a list of ggplots named by covariate. +#' Spike-and-slab random effects that reach no data of the group are left +#' out; Dirichlet-process random effects, which couple the groups, appear in +#' the heatmap only. #' @example inst/examples/plotRandomEffects.R #' @export -plotRandomEffects.em <- function(x, type = c("conditional", "modes"), draws = 20L, bins = 30, covariates = NULL, - ...) { +plotRandomEffects.em <- function(x, type = c("conditional", "modes", "inclusion"), draws = 20L, bins = 30, + covariates = NULL, ...) { if (!is.null(covariates)) return(.randomEffectCovariates(x, covariates)) type <- match.arg(type) - values <- .randomEffectValues(x, type, draws) + if (type == "inclusion") return(.inclusionHeatmap(x)) + values <- rbind(.randomEffectValues(x, type, draws), .spikeSlabValues(x, type, draws)) + if (is.null(values)) + stop("plotRandomEffects: the fit has no normal or spike-and-slab random effects.", call. = FALSE) # the panels in the order of the random effects of the fit values$eta <- factor(values$eta, unique(values$eta)) - # the density of every random effect over at least +/- 3.5 standard deviations - density <- do.call(rbind, lapply(split(values, values$eta), function(v) { - lim <- max(abs(v$value), 3.5 * v$sd[1]) - x <- seq(-lim, lim, length.out = 200L) - data.frame(eta = v$eta[1], x = x, density = stats::dnorm(x, 0, v$sd[1]), stringsAsFactors = FALSE) - })) + bars <- do.call(rbind, lapply(split(values, values$eta), .mixtureBars, bins = bins)) + prior <- do.call(rbind, lapply(split(values, values$eta), .mixturePrior, bars = bars)) what <- if (type == "conditional") "Conditional draws" else "Modes" - hist <- ggplot2::ggplot(values, ggplot2::aes(x = value)) + - ggplot2::geom_histogram(ggplot2::aes(y = ggplot2::after_stat(density)), bins = bins, fill = "gray80", - color = "gray40") + - ggplot2::geom_line(data = density, ggplot2::aes(x = x, y = density), inherit.aes = FALSE, - color = dMod_colors[2], linewidth = 0.8) + + sparse <- any(values$spike > 0) + hist <- ggplot2::ggplot(bars) + + ggplot2::geom_rect(ggplot2::aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = part), + color = "gray40", linewidth = 0.2) + + ggplot2::geom_line(data = prior[prior$part == "slab", ], ggplot2::aes(x = x, y = density), inherit.aes = FALSE, + color = dMod2_colors[2], linewidth = 0.8) + + ggplot2::geom_segment(data = prior[prior$part == "spike", ], + ggplot2::aes(x = x - 1.5 * width, xend = x + 1.5 * width, y = density, yend = density), + inherit.aes = FALSE, color = dMod2_colors[2], linewidth = 0.8) + ggplot2::facet_wrap(~ eta, scales = "free") + - ggplot2::labs(x = "eta value", y = "density", title = paste(what, "vs N(0, Omega_kk)")) + - theme_dMod(base_size = 11) - qq <- ggplot2::ggplot(values, ggplot2::aes(sample = value / sd)) + + ggplot2::scale_fill_manual(values = c(slab = "gray80", spike = dMod2_colors[3]), + labels = c(slab = "deviation", spike = "exactly 0"), + guide = if (sparse) "legend" else "none") + + ggplot2::labs(x = "eta value", y = "density", fill = NULL, + title = paste(what, if (sparse) "vs the prior (red), the prior spike of area 1 - prob as a cap" + else "vs N(0, Omega_kk)")) + + theme_dMod2(base_size = 11) + normal <- values[values$spike == 0, , drop = FALSE] + if (!nrow(normal)) return(hist) + qq <- ggplot2::ggplot(normal, ggplot2::aes(sample = value / sd)) + ggplot2::stat_qq() + - ggplot2::stat_qq_line(color = dMod_colors[2]) + + ggplot2::stat_qq_line(color = dMod2_colors[2]) + ggplot2::facet_wrap(~ eta) + ggplot2::labs(x = "Theoretical quantile (N(0,1))", y = "Standardized eta", title = paste(what, "QQ vs N(0,1)")) + - theme_dMod(base_size = 11) + theme_dMod2(base_size = 11) if (requireNamespace("cowplot", quietly = TRUE)) cowplot::plot_grid(hist, qq, ncol = 1) else list(hist = hist, qq = qq) } -## The values of every normal random effect, the modes or `draws` draws per group from the normal -## around the mode with the conditional standard error, with the standard deviation of Omega; the -## panel names the grouping where there are several and the shrinkage. +## The values of every normal random effect, the modes or `draws` draws per group around the mode +## with the conditional standard error, with the standard deviation of Omega; NULL for a fit +## without normal random effects. .randomEffectValues <- function(fit, type, draws) { several <- is.list(fit$Omega) part <- function(f) if (several) fit[[f]] else list(fit[[f]]) Omegas <- part("Omega"); etaModes <- part("etaModes"); etaSE <- part("etaSE"); shrinkage <- part("shrinkage") keep <- !vapply(Omegas, is.null, TRUE) & !vapply(etaModes, is.null, TRUE) - if (!any(keep)) - stop("plotRandomEffects: the fit has no normal random effects.", call. = FALSE) + if (!any(keep)) return(NULL) do.call(rbind, unlist(lapply(which(keep), function(g) { E <- etaModes[[g]]; O <- Omegas[[g]]; S <- etaSE[[g]] if (type == "conditional" && is.null(S)) @@ -244,11 +270,114 @@ plotRandomEffects.em <- function(x, type = c("conditional", "modes"), draws = 20 sh <- if (is.null(shrinkage[[g]])) NA_real_ else shrinkage[[g]][k] eta <- paste0(if (several) paste0(names(Omegas)[g], ": "), k, if (is.finite(sh)) sprintf(", shrinkage %.0f%%", 100 * sh)) - data.frame(eta = eta, value = value, sd = sqrt(O[k, k]), stringsAsFactors = FALSE) + data.frame(eta = eta, value = value, sd = sqrt(O[k, k]), spike = 0, stringsAsFactors = FALSE) }) }), recursive = FALSE)) } +## The prior of every spike-and-slab random effect of a fit, by the short name of the effect: +## probability `prob` of a deviation and slab standard deviation `tau`. +.spikeSlabPriors <- function(fit) { + sl <- fit$slab + if (is.null(sl)) return(NULL) + sl <- sl[sl$distribution == "spikeSlab", , drop = FALSE] + kind <- sub("_.*$", "", sl$name) + rows <- lapply(unique(sl$symbols), function(s) { + b <- sl[sl$symbols == s, , drop = FALSE] + k <- kind[sl$symbols == s] + data.frame(eta = strsplit(s, ", ", fixed = TRUE)[[1]], prob = b$estimate[k == "prob"], + tau = b$estimate[k == "tau"], stringsAsFactors = FALSE) + }) + do.call(rbind, rows) +} + +## The values of every spike-and-slab random effect that reaches the data of the group, reported or +## `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) { + pri <- .spikeSlabPriors(fit) + r <- fit$random + if (is.null(pri) || is.null(r$p0)) return(NULL) + keep <- r$eta %in% pri$eta + if (!is.null(r$data)) keep <- keep & r$data + r <- r[keep, , drop = FALSE] + if (!nrow(r)) return(NULL) + pri <- pri[match(r$eta, pri$eta), ] + stem <- colnames(fit$etaModes)[match(r$eta, sub("^eta_", "", colnames(fit$etaModes)))] + inner <- if (is.null(fit$innerModes)) r$mode else fit$innerModes[cbind(r$group, stem)] + # the slab mean: the reported value where the structure has the deviation, else the slab mode + m <- ifelse(r$cluster != 0, r$mode, inner) + p0 <- pmin(pmax(r$p0, 0), 1) + s <- sqrt(pmax((r$se^2 - p0 * (1 - p0) * m^2) / pmax(1 - p0, .Machine$double.eps), 0)) + n <- if (type == "modes") 1L else as.integer(draws) + value <- if (type == "modes") r$mode else { + slab <- stats::runif(nrow(r) * n) >= rep(p0, each = n) + ifelse(slab, rep(m, each = n) + rep(s, each = n) * stats::rnorm(nrow(r) * n), 0) + } + data.frame(eta = rep(r$eta, each = n), value = value, sd = rep(pri$tau, each = n), + spike = rep(1 - pri$prob, each = n), stringsAsFactors = FALSE) +} + +## The histogram of the values of one panel as density bars, `bins` over the range of the values +## and centered on multiples of the bin width so that one bin is centered at 0; in a spike-and-slab panel the exact zeros as a bar of +## their own at the bottom of that bin. +.mixtureBars <- function(v, bins) { + w <- diff(range(v$value)) / bins + if (!(w > 0)) w <- 7 * v$sd[1] / bins + at <- round(v$value / w) + zero <- v$spike[1] > 0 & v$value == 0 + height <- function(sel) { + tab <- table(at[sel]) + setNames(as.vector(tab) / (nrow(v) * w), names(tab)) + } + spike <- height(zero); slab <- height(!zero) + base <- ifelse(names(slab) %in% names(spike), spike[names(slab)], 0) + bar <- function(part, mid, lo, hi) if (length(mid)) + data.frame(eta = v$eta[1], part = part, xmin = (mid - 0.5) * w, xmax = (mid + 0.5) * w, ymin = lo, ymax = hi, + width = w, stringsAsFactors = FALSE) + rbind(bar("slab", as.numeric(names(slab)), unname(base), unname(base + slab)), + bar("spike", as.numeric(names(spike)), 0, unname(spike))) +} + +## The density of the prior of one panel over at least +/- 3.5 standard deviations: normal, or for a +## spike-and-slab panel the slab density prob N(0, tau^2) and the height of a spike bar of area +## 1 - prob in the width of the bins of the panel. +.mixturePrior <- function(v, bars) { + lim <- max(abs(v$value), 3.5 * v$sd[1]) + x <- seq(-lim, lim, length.out = 200L) + spike <- v$spike[1] + slab <- data.frame(eta = v$eta[1], part = "slab", x = x, density = (1 - spike) * stats::dnorm(x, 0, v$sd[1]), + width = NA_real_, stringsAsFactors = FALSE) + if (spike == 0) return(slab) + w <- bars$width[bars$eta == v$eta[1]][1] + rbind(slab, data.frame(eta = v$eta[1], part = "spike", x = 0, density = spike / w, width = w, + stringsAsFactors = FALSE)) +} + +## The posterior probability of a deviation, 1 - p0, per group and sparse random effect as tiles, +## effects from top to bottom in the order of the fit, with the reported value where the reported +## structure has a deviation. +.inclusionHeatmap <- function(fit) { + r <- fit$random + if (is.null(r$p0) || all(is.na(r$p0))) + stop("plotRandomEffects: type = \"inclusion\" needs spike-and-slab or Dirichlet-process random effects.", + call. = FALSE) + r <- r[!is.na(r$p0), , drop = FALSE] + if (!is.null(r$grouping)) r$group <- paste0(r$grouping, ": ", r$group) + r$eta <- factor(r$eta, rev(unique(r$eta))) + r$group <- factor(r$group, unique(r$group)) + r$inclusion <- 1 - r$p0 + r$label <- ifelse(r$cluster != 0, sprintf("%.2f", r$mode), "") + if (!is.null(r$data)) r$label[!r$data] <- "no data" + ggplot2::ggplot(r, ggplot2::aes(x = group, y = eta, fill = inclusion)) + + ggplot2::geom_tile(color = "white") + + ggplot2::geom_text(ggplot2::aes(label = label, color = inclusion > 0.6), size = 3) + + ggplot2::scale_fill_gradient(low = "white", high = dMod2_colors[3], limits = c(0, 1)) + + ggplot2::scale_color_manual(values = c(`TRUE` = "white", `FALSE` = "black"), guide = "none") + + ggplot2::labs(x = NULL, y = NULL, fill = "1 - p0", title = "Posterior probability of a deviation") + + theme_dMod2(base_size = 11) +} + #' @rdname plotValues #' @export plotValues.em <- function(x, ..., tol = 1, showSteps = FALSE, pseudoLog = FALSE, relative = FALSE) @@ -256,7 +385,9 @@ plotValues.em <- function(x, ..., tol = 1, showSteps = FALSE, pseudoLog = FALSE, #' @rdname plotTrace #' @param x An `em` fit, see [em()], with a stage trace: every method except `"focei"` -#' with normal random effects only. +#' with normal random effects only. The hyperparameters of spike-and-slab and +#' Dirichlet-process random effects that the trace records (`prob_`, +#' `tau_`, `concentration_`) get one panel each. #' @param ... Ignored. #' @return A ggplot. #' @example inst/examples/plotTrace.R @@ -268,6 +399,8 @@ plotTrace.em <- function(x, ...) { call. = FALSE) panels <- c(OFV = "OFV", deltaPsi = "|delta psi|", deltaPar = "|delta par|", deltaStruct = "|delta theta|", decrement = "Newton decrement", maxSoftmax = "max softmax", nEffMin = "n_eff min") + hyper <- intersect(x$slab$name, names(tr)) + panels <- c(panels, setNames(hyper, hyper)) have <- intersect(names(panels), names(tr)) # the stages in the order they ran stage <- tr$level %||% tr$phase %||% rep("all", nrow(tr)) @@ -275,10 +408,63 @@ plotTrace.em <- function(x, ...) { long <- do.call(rbind, lapply(have, function(v) data.frame(iter = seq_len(nrow(tr)), value = tr[[v]], panel = panels[[v]], stage = stage))) long$panel <- factor(long$panel, unname(panels[have])) + # an iteration without a value in a panel, e.g. the step of the first one, has no point there + long <- long[is.finite(long$value), ] ggplot2::ggplot(long, ggplot2::aes(x = iter, y = value, color = stage)) + ggplot2::geom_line() + ggplot2::geom_point() + ggplot2::facet_wrap(~ panel, scales = "free_y") + - scale_color_dMod() + + scale_color_dMod2() + ggplot2::labs(x = "EM iteration", title = "EM convergence trace") + - theme_dMod(base_size = 11) + theme_dMod2(base_size = 11) +} + + +#' @rdname plotPars +#' @param level With an `em` fit or a list of them: the level of the Wald +#' intervals, see [confint()][confint.em]. Default 0.95. +#' @param which With an `em` fit or a list of them: names of the parameters to +#' show, by default all estimated ones. +#' @details An `em` fit, see [em()], or a list of them, as fits of one model by +#' several methods: the estimates of fixed effects and hyperparameters with +#' Wald intervals, where the fit has standard errors, one row per parameter +#' and one color per fit. The fits of a list are labeled by the names of the +#' list, else by their method. +#' @export +plotPars.em <- function(x, ..., level = 0.95, which = NULL) .plotEstimates(list(x), level, which) + +#' @rdname plotPars +#' @export +plotPars.list <- function(x, ..., level = 0.95, which = NULL) { + if (!length(x) || !all(vapply(x, inherits, TRUE, "em"))) + stop("plotPars: a list of fits is a list of em fits.", call. = FALSE) + .plotEstimates(x, level, which) +} + +## The estimates of the fits `fits` with Wald intervals at `level`, the rows of the parameters in +## the order of their first appearance, the fits side by side within a row. +.plotEstimates <- function(fits, level, which) { + labels <- names(fits) %||% rep("", length(fits)) + labels[!nzchar(labels)] <- vapply(fits[!nzchar(labels)], `[[`, "", "method") + labels <- make.unique(labels, sep = " ") + est <- do.call(rbind, Map(function(f, lab) { + ci <- stats::confint(f, level = level) + data.frame(fit = lab, parameter = ci$name, estimate = ci$value, lower = ci$lower, upper = ci$upper, + stringsAsFactors = FALSE) + }, fits, labels)) + if (!is.null(which)) est <- est[est$parameter %in% which, , drop = FALSE] + if (!nrow(est)) stop("plotPars: none of `which` is an estimated parameter of the fits.", call. = FALSE) + pars <- unique(est$parameter) + est$fit <- factor(est$fit, labels) + # the fits side by side within the row of a parameter, the first on top + offset <- if (length(labels) > 1L) 0.6 * (0.5 - (as.integer(est$fit) - 1) / (length(labels) - 1)) else 0 + est$position <- length(pars) + 1 - match(est$parameter, pars) + offset + ranged <- est[is.finite(est$lower) & is.finite(est$upper), , drop = FALSE] + ggplot2::ggplot(est, ggplot2::aes(x = estimate, y = position, color = fit)) + + ggplot2::geom_segment(data = ranged, ggplot2::aes(x = lower, xend = upper, yend = position)) + + ggplot2::geom_point(size = 1.8) + + ggplot2::scale_y_continuous(breaks = rev(seq_along(pars)), labels = pars, minor_breaks = NULL) + + scale_color_dMod2(limits = labels, guide = if (length(labels) > 1L) "legend" else "none") + + ggplot2::labs(x = "Estimate", y = NULL, color = NULL, + title = sprintf("Estimates with %g%% Wald intervals", 100 * level)) + + theme_dMod2(base_size = 11) } diff --git a/R/prdClass.R b/R/prdClass.R index 748365bc..3ad41214 100644 --- a/R/prdClass.R +++ b/R/prdClass.R @@ -179,7 +179,7 @@ plotCombined.prdlist <- function(prediction, data = NULL, ..., p <- p + geom_ribbon(band, data = prediction[!is.na(prediction$sigma), ], alpha = 0.25, linetype = 0, show.legend = FALSE) # the bands in the colors of the lines - if (!is.null(colorBy) && !is.numeric(rlang::eval_tidy(colorBy, prediction))) p <- p + scale_fill_dMod() + if (!is.null(colorBy) && !is.numeric(rlang::eval_tidy(colorBy, prediction))) p <- p + scale_fill_dMod2() } if (!is.null(prediction)) p <- p + geom_line(data = prediction) if (is.null(data)) return(p) @@ -215,7 +215,7 @@ plotPrediction.prdlist <- function(prediction, ..., errfn = NULL, band <- if (!is.null(errfn)) list(geom_ribbon(aes(ymin = value - sigma, ymax = value + sigma, fill = condition), data = frame[!is.na(frame$sigma), ], linetype = 0, alpha = 0.3), - scale_fill_dMod()) + scale_fill_dMod2()) p <- p + list(band, geom_line()) attr(p, "data") <- frame p diff --git a/R/prediction.R b/R/prediction.R index c49ec178..32cc6918 100644 --- a/R/prediction.R +++ b/R/prediction.R @@ -63,6 +63,14 @@ #' factorizes it where the argument `sparse` takes the sparse path, and [`vcov()`][vcov.objlist] #' solves it for the columns of `which`. #' +#' `hessian = "expected"` returns, in place of the Gauss-Newton Hessian of the +#' forward sweep, the expected (Fisher) information of the likelihood: +#' `2 / sigma^2` in the prediction and `4 / sigma^2` in sigma per data point, +#' positive semidefinite also where an error model depends on the parameters. +#' The Gauss-Newton Hessian keeps the exact curvature of the loss in the +#' prediction and sigma, which is indefinite there and shows the optimizer a +#' saddle. +#' #' With `deriv = FALSE` it returns the value alone. #' #' @seealso [controls()] to change the settings of a function after it is @@ -514,10 +522,8 @@ Xs.cppDE <- function(odemodel, forcings = NULL, events = NULL, names = NULL, con } reverseOpts() - # Checkpoints of the value pass, matched on times and parameters, for the - # backward sweeps over the same trajectory. A lookup keeps the store; the - # cache holds twice the widest batch, at least 4, and evicts the least - # recent, since a store far from the optimum holds many steps. + # checkpoints of the value pass by times and parameters for backward sweeps on the same trajectory: twice + # the widest batch, at least 4, the least recent evicted, since a store far from the optimum holds many steps scache <- new.env(parent = emptyenv()) scache$items <- list() scache$width <- 0L @@ -788,11 +794,9 @@ Xs.cppDE <- function(odemodel, forcings = NULL, events = NULL, names = NULL, con } attr(P2X, "batchfn") <- P2Xbatch - # The prepared solve of the native chain (.chainPlan()): one condition per entry of `timesL`, - # `dirsL` the directions of the condition tangent. With `seeds` the backward solve of forward over - # reverse with that many seeds per condition instead. With `adjoint` the first order: the - # forward solve keeping the checkpoints, or with `seeds` the backward one, which the caller - # hands them. NULL where the leaf cannot take part. + # the prepared solve of the native chain (.chainPlan()), a condition per entry of `timesL` along `dirsL`; + # with `seeds` the backward solve of forward over reverse, with `adjoint` first order with checkpoints + # (backward with `seeds`). NULL where the leaf cannot take part. attr(P2X, "chainSolve") <- function(timesL, dirsL, deriv, deriv2, seeds = 0L, adjoint = FALSE) { if (adjoint) { if (!has_store) return(NULL) diff --git a/R/randomEffects.R b/R/randomEffects.R index 109a0957..0026bc59 100644 --- a/R/randomEffects.R +++ b/R/randomEffects.R @@ -280,10 +280,9 @@ print.redist <- function(x, ...) { sub("^\\+\\s*", "", deparse1(pf$fixed[[2]])), "\".", call. = FALSE) } -## The design of one formula over the rows of `tree`: the fixed-effect matrix with the names of -## the parameters, and per random-effect column the stem, the eta and coefficient of every row. -## A stem already taken by a term of another grouping gets the grouping appended. With `sparse` -## the fixed-effect matrix is a sparse Matrix. +## The design of one formula over the rows of `tree`: the fixed-effect matrix (a sparse Matrix with `sparse`) +## and per random-effect column the stem, eta and coefficient of every row; a stem taken by another grouping +## gets the grouping appended. .effectMatrices <- function(pf, tree, taken = NULL, sparse = FALSE) { .checkEffectColumns(pf, tree) sym <- pf$symbol diff --git a/R/reml.R b/R/reml.R index 8ede2ada..6dc16d6b 100644 --- a/R/reml.R +++ b/R/reml.R @@ -406,14 +406,9 @@ reml <- function(objfun, pars, errpars = NULL, fixed = NULL, ## Restricted likelihood of mixed-effects and alignment fits --------------------------------- -## The term that integrates the parameters `mean` out of the likelihood under a flat prior by -## Laplace, log|S / 2| - p log(2 pi) with S the Schur complement over the etas of the information -## G = sum_r w_r a_r a_r' + C + P over the mean parameters and the etas: a_r the derivative of the -## prediction of data row r, w_r the curvature of the row loss in the prediction with sigma held (the expected -## one for Student-t readings), C the Hessian of the terms of the objective beside the data and P -## the prior precision of the etas, at `full`, the outer parameters and the modes. With `deriv` -## also the gradient of the term in the parameters `theta` of `full`, the others held: -## sum_r q_r dw_r + tr(Gamma dP), q_r = a_r' Gamma a_r, Gamma = G^-1 minus the inverse eta blocks. +## Laplace over `mean` under a flat prior, log|S / 2| - p log(2 pi), S the Schur complement over the etas of the +## information G = sum_r w_r a_r a_r' + C + P at `full`; with `deriv` the gradient in `theta`, sum_r q_r dw_r + +## tr(Gamma dP), q_r = a_r' Gamma a_r, Gamma = G^-1 minus the inverse eta blocks. .remlTerm <- function(design, full, fixed, mean, theta = character(0), deriv = TRUE, cores = 1L) { units <- if (length(.allEtas(design))) .volumeUnits(design, full, fixed) else list() V <- c(mean, unlist(lapply(units, `[[`, "eta"))) diff --git a/R/remoteComputing.R b/R/remoteComputing.R index 76670d05..6370426b 100644 --- a/R/remoteComputing.R +++ b/R/remoteComputing.R @@ -181,10 +181,9 @@ detectFreeCores <- function(machine = NULL) { out } -## Bash script that builds the shared object on the remote machine from the -## sources, or the object files when `link = TRUE`. Beyond the argument limit it -## uses compile()'s chunked archive build, reading the inputs from `filelist`. -## `sources` are the local paths of `files`, read for the precompiled header. +## Bash script that builds the shared object on the remote machine from the sources, or the objects with +## `link = TRUE`, beyond the argument limit by the chunked archive of compile() from `filelist`; `sources` are +## the local paths of `files`, read for the precompiled header. .remoteBuildScript <- function(files, output, compileArgs = "", needsCVODE = FALSE, needsKLU = FALSE, needsLapack = FALSE, @@ -382,11 +381,8 @@ detectFreeCores <- function(machine = NULL) { ## ---- distributedComputing() --------------------------------------------------- -## A job lives in _folder/, one subfolder per node k: in the working -## directory for "localhost", in the home directory elsewhere. The local -## _folder holds the manifest job.rds and the files get() fetches; a copy of -## the manifest lies in the _folder of every remote node and one is -## registered in the data directory of dMod2. +## A job lives in _folder/ per node k (working directory on localhost, else home); the manifest +## job.rds lies in the local and every remote _folder and is registered in the dMod2 data directory. ## "localhost" is the local machine, reached without ssh; every other node by ssh. .isLocalhost <- function(machine) identical(machine, "localhost") @@ -862,10 +858,10 @@ print.dMod2Target <- function(x, ...) { ", see dMod2Jobs()", call. = FALSE) } -## An error when a job of this name still runs where the new one would replace -## the folders: in this working directory, or on one of the same remote nodes, -## also when it was submitted from another machine. -.refuseRunning <- function(jobname, wd, hosts) { +## An error when a job of this name still runs where the new one would replace the folders, here +## or on a remote node, also from another machine, and when a remote folder holds a job of this name +## from another working directory. +.refuseReplace <- function(jobname, wd, hosts) { f <- file.path(wd, paste0(jobname, "_folder"), "job.rds") remote <- hosts[!vapply(hosts, .isLocalhost, NA)] same <- function(m) identical(m$jobname, jobname) && @@ -882,6 +878,15 @@ print.dMod2Target <- function(x, ...) { " tasks; recover = TRUE returns the job functions, and terminate() stops it", call. = FALSE) } + here <- normalizePath(wd, mustWork = FALSE) + for (i in seq_along(remote)) { + m <- onNodes[[i]] + if (!identical(m$jobname, jobname) || + identical(normalizePath(m$wd, mustWork = FALSE), here)) next + stop("the folder of job '", jobname, "' on ", remote[i], " holds the job submitted from ", + m$wd, "; get() the results there and purge() the job, or choose another jobname", + call. = FALSE) + } } ## The functions of the job described by the manifest `m`. @@ -943,10 +948,15 @@ print.dMod2Target <- function(x, ...) { terminate <- function() { for (k in seq_along(m$hosts)) { cmd <- if (m$slurm) paste("scancel", .slurmSelect(m, cancel = TRUE)) - else paste0("for f in slot_*.pid slot_*.run; do [ -f \"$f\" ] || continue; ", - "p=$(cat \"$f\"); kill -TERM -- -$p 2>/dev/null || ", - "{ pkill -TERM -P $p; kill -TERM $p; }; ", - "done 2>/dev/null; true") + # SIGTERM, and SIGKILL to what still runs after 5 seconds, since R may outlive SIGTERM + else { + signal <- function(sig) paste0("for f in slot_*.pid slot_*.run; do [ -f \"$f\" ] || continue; ", + "p=$(cat \"$f\"); kill -", sig, " -- -$p 2>/dev/null || ", + "{ pkill -", sig, " -P $p; kill -", sig, " $p; }; done 2>/dev/null; ") + paste0(signal("TERM"), "i=0; while [ $i -lt 50 ]; do a=; for f in slot_*.pid slot_*.run; do ", + "[ -f \"$f\" ] && kill -0 $(cat \"$f\") 2>/dev/null && a=1; done; [ -z \"$a\" ] && break; ", + "sleep 0.1; i=$((i+1)); done; ", signal("KILL"), "true") + } .onMachine(m$hosts[k], cmd, file.path(m$folder, k), m$wd, ignore.stderr = TRUE) } invisible(NULL) @@ -999,7 +1009,9 @@ print.dMod2Job <- function(x, ...) { #' for `"localhost"` and in the home directory of a remote node. The job manifest #' `job.rds` lies in the local `_folder` and in that of every remote #' node. A job of the same name that still runs there is an error, also when it -#' was submitted from another machine. Every job is registered in +#' was submitted from another machine, and so is a job of the same name in the +#' folder of a remote node that was submitted from another working directory, +#' until it is purged. Every job is registered in #' `tools::R_user_dir("dMod2", "data")` until `purge(local = TRUE)`, and #' [dMod2Jobs()] lists them. #' @@ -1123,7 +1135,7 @@ distributedComputing <- function(expr, tasks = NULL, on = localNode(), jobname = if (is.null(jobname)) jobname <- paste0("job_", paste(sample(c(0:9, letters), 6, replace = TRUE), collapse = "")) if (is.null(seed)) seed <- sample.int(1e6, 1L) - .refuseRunning(jobname, wd, hosts) + .refuseReplace(jobname, wd, hosts) # The worker of every task, dealt in turn: a node, or an array task of SLURM worker <- (seq_len(n) - 1L) %% workers + 1L diff --git a/R/reverse.R b/R/reverse.R index 6d1e163a..17ab4a59 100644 --- a/R/reverse.R +++ b/R/reverse.R @@ -1,10 +1,9 @@ ## Reverse-mode helpers ----------------------------------------------------- ## Copyright (C) 2026 Simon Beyer -# A cotangent: `out` on the node's output matrix, `pars` on the node parameters, -# both optional and additive. The trailing axis of extent K holds the cotangent -# in slice 1 and the directional derivatives after it, or K seeds in seed mode. -# `value`, per seed, is the value correction of refined sweeps below the node. +# 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 +# value correction of refined sweeps below the node. .ct <- function(out = NULL, pars = NULL, value = NULL) { if (!is.null(pars) && is.null(dim(pars))) pars <- matrix(pars, ncol = 1L, dimnames = list(names(pars), NULL)) diff --git a/R/statistics.R b/R/statistics.R index bd837c18..d79c6eb9 100644 --- a/R/statistics.R +++ b/R/statistics.R @@ -981,7 +981,6 @@ mstrust <- function(objfun, center, rinit = .1, rmax = 10, fits = 20, cores = 1, .mstrustRoute <- function(given, optfun, samplefun, samplerName) { accepts <- function(f) intersect(setdiff(names(formals(f)), "..."), names(given)) toOptimizer <- accepts(optfun) - .trustRejectMoved(setdiff(names(given), toOptimizer), "mstrust") toSampler <- accepts(samplefun) if (length(intersect(toOptimizer, toSampler))) stop("Argument names of the optimizer and ", samplerName, "() clash.") @@ -1317,7 +1316,7 @@ fitErrorModel <- function(data, factors, errorModel = "exp(s0)+exp(srel)*x^2", 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") + - scale_y_log10() + ylab("variance") + theme_dMod()) + scale_y_log10() + ylab("variance") + theme_dMod2()) } result$sigma <- result$sigma / sqrt(data$n) diff --git a/R/steadyStates.R b/R/steadyStates.R index 85a6395d..36c6b05f 100644 --- a/R/steadyStates.R +++ b/R/steadyStates.R @@ -1,12 +1,18 @@ #' Analytical Steady States #' #' Computes symbolic steady-state expressions for use in a parameter -#' transformation, following the AlyssaPetit method \[1\], \[2\]. Each balance -#' equation, or a combination of balances, is solved for a state or a rate -#' constant such that the result is a ratio of sums of positive terms. A state -#' whose equation was spent on a rate constant stays a free parameter; -#' compartment volumes are fixed. The solver is a Python module called through -#' \pkg{reticulate}; it needs \pkg{numpy}, \pkg{sympy} and \pkg{scipy}. +#' transformation, following the AlyssaPetit method \[1\], \[2\]. States whose +#' own balance gives a ratio of positive sums are solved from it first. The +#' cycles of the graph of states left are cut then: at a state of a conserved +#' quantity, or at a state whose balance is solved for a rate constant of one +#' flux side instead. Each cut state stays a free parameter. The remaining +#' states and the rate constants of the cuts are then solved, each from a +#' balance or a combination of balances in amounts, such that the result is a +#' ratio of sums of positive terms. Only if that fails, a flux side with +#' separate rate constants is cut as well: the fluxes of the side keep free +#' ratios, the new parameters `r__`. Compartment volumes are fixed. +#' The solver is a Python module called through \pkg{reticulate}; it needs +#' \pkg{numpy}, \pkg{sympy} and \pkg{scipy}. #' #' @param model An [eqnlist], or the path of a csv file describing the model. #' @param file Character, path of the RDS file the result is written to with @@ -19,7 +25,7 @@ #' `c("A + pA = totA", "B + pB = totB")` or as `c("A + pA", "B + pB")`. #' Default `NULL`: a basis is derived, or taken from [customTotals()] when the #' `eqnlist` has them. Each given quantity keeps one of the states in it free, the -#' first where possible. +#' first one on a cycle of the graph of states. #' @param neglect Character vector, states and rate parameters the solver must #' not solve for. Default `NULL`. #' @param testSteady How the solution is verified: `"fast"` (default), a @@ -32,8 +38,8 @@ #' in that state, may be solved for the positive root instead of for a rate constant, which #' introduces `sqrt()` terms. Default `FALSE`. #' @param priority Character vector of state and rate-parameter names, most -#' preferred first: named states are solved earlier, named rate parameters -#' are preferred as pivots. Default `NULL`. +#' preferred first: named states are solved rather than kept free and solved +#' earlier, named rate parameters are preferred as pivots. Default `NULL`. #' @param resolve Logical, whether the result is passed through #' [resolveRecurrence()] so that no equation refers to another. Default #' `TRUE`. diff --git a/R/symmetryDetection.R b/R/symmetryDetection.R index ce1383d4..9a9ecc7e 100644 --- a/R/symmetryDetection.R +++ b/R/symmetryDetection.R @@ -77,7 +77,7 @@ #' first, reduces the directions found and then counts the values of the coordinates with the #' output of a generic one and reconstructs the maps between them, as [discreteSymmetries()] #' (needs msolve, implies `reconstruct = TRUE`). A model the global analysis does not handle -#' gets the reason in `info$discrete$unsupported` and a warning. Needs symident 0.15.0. +#' 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 @@ -211,9 +211,7 @@ symmetryDetection <- function(f, g, trafo = NULL, parameters = NULL, #' proven by a map of the states (`"exact"`). A model with directions is reduced by #' [symmetryReduction()] first and the reduced model is analyzed. #' -#' @param object A `symmetrydetection` result from [symmetryDetection()] of a model -#' with one condition and no events, switches or unknown inputs, detected without -#' `equilibrate` and `reduceCQ`. +#' @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 @@ -373,7 +371,7 @@ reconstControl <- function(relevanceCap = 6L, relevanceCapDir = 24L, relevanceCa # ---- the interface to the Python package symident -------------------------------- -.symidentMin <- "0.15.0" +.symidentMin <- "0.17.0" .symidentReq <- paste0("symident>=", .symidentMin) # whether symident is installed in version .symidentMin or later @@ -419,7 +417,7 @@ reconstControl <- function(relevanceCap = 6L, relevanceCapDir = 24L, relevanceCa "display", "factor", "pins", "new_parameters", "solved_domain", "trafo", "totals", "state_components", "input_change", "jets", "map", - "point")) { + "point", "section", "state_maps", "fiber_coordinates")) { if (!is.list(x)) return(x) nm <- names(x) for (i in seq_along(x)) @@ -633,8 +631,10 @@ reconstControl <- function(relevanceCap = 6L, relevanceCapDir = 24L, relevanceCa d <- res$info$discrete for (k in c("fundamentalDomain", "limits")) d[k] <- list(chr(d[[k]])) if (!is.null(d$reduced)) - d$reduced <- list(trafo = vec(d$reduced$trafo), fixed = chr(d$reduced$fixed), - coordinates = chr(d$reduced$coordinates)) + # one trafo, or one per condition + d$reduced <- list(trafo = if (is.null(names(d$reduced$trafo))) lapply(d$reduced$trafo, vec) + else vec(d$reduced$trafo), fixed = chr(d$reduced$fixed), + coordinates = chr(d$reduced$coordinates), section = vec(d$reduced$section)) if (length(d$counts)) d$counts <- do.call(rbind, lapply(d$counts, function(r) as.data.frame(lapply(r[c("complex", "real", "inDomain", "undecided")], function(v) if (is.null(v)) NA else v)))) @@ -667,9 +667,10 @@ print.symmetrydetection <- function(x, verbose = FALSE, width = getOption("width cat(sprintf(" %s [%s, %s]\n", paste(names(s$map), s$map, sep = " -> ", collapse = ", "), s$level, keeps)) } if (length(domain)) cat(" fundamental domain:", paste(domain, collapse = ", "), "\n") - if (length(info$reduced$trafo)) - cat(" on the model reduced by", paste(names(info$reduced$trafo), info$reduced$trafo, sep = " = ", - collapse = ", "), "\n") + # the section of the reduction: the coordinates it pins + pins <- info$reduced$section[as.character(info$reduced$section) != names(info$reduced$section)] + if (length(pins)) + cat(" on the model reduced by", paste(names(pins), pins, sep = " = ", collapse = ", "), "\n") invisible() } diff --git a/R/trust.R b/R/trust.R index 8d6abfda..49921f7c 100644 --- a/R/trust.R +++ b/R/trust.R @@ -5,6 +5,22 @@ #' trust-region subproblem exactly, via the full eigendecomposition of the #' Hessian. #' +#' @section Default method: +#' Without \code{hessianMethod}, \code{phases}, \code{switches} and a +#' \code{sweep} in \code{...}, \code{trust} runs the hybrid method of Fides +#' (Fröhlich and Sorger 2022): Gauss-Newton until the trust radius stayed the +#' same for 20 consecutive iterations, then BFGS for the rest of the run. The +#' BFGS approximation starts from the Gauss-Newton Hessian at \code{parinit}, +#' made positive definite, takes every accepted step of the Gauss-Newton phase +#' as an update, and the trust radius stays at the switch. These are the +#' phases +#' \preformatted{list(gn = list(hessianMethod = "gn", radiusStall = 20, onStop = "end"), +#' bfgs = list(hessianMethod = "bfgs", sweep = "forward", keepRadius = TRUE, +#' qnControl = list(hessianInit = "tracked")))} +#' The run is Gauss-Newton alone, as with \code{hessianMethod = "gn"}, where +#' phases are not available (multiple shooting, \code{boundary = "clip"}) and +#' on the sparse path, see \code{sparse}. +#' #' @section Box bounds: #' \code{boundary = "reflective"} (default) uses the interior #' trust-region-reflective scheme of Coleman and Li. Iterates stay strictly @@ -49,14 +65,18 @@ #' from the dense eigendecomposition elsewhere. \code{trustL1} applies the #' same condition to the model of the coordinates not held at a kink. Without #' the condition the run goes on, within \code{iterlim}; \code{mtol = 0} -#' drops the condition. +#' drops the condition. A run that goes on this way and then ends on the +#' radius without an accepted step that changes the value by \code{ftol} or +#' more ends on the stop held back, with \code{converged = TRUE}: the decrease +#' the model predicts is below the resolution of the objective. #' #' \code{stopReason} in the result names the test that fired: #' \code{"gradient"}, \code{"fvalue"}, \code{"preddiff"}, \code{"step"}, #' \code{"stagnation"}, \code{"radius"}, \code{"objfun"} (three failed #' evaluations in a row, ten with multiple shooting) or \code{"iterlim"}. -#' Stagnation reports -#' \code{converged = TRUE}. +#' Stagnation reports \code{converged = TRUE} where the full Newton step +#' predicts a decrease of at most \code{mtol} or a stop was held back as +#' above, and \code{converged = FALSE} otherwise. #' #' Only \code{gtol} tests first-order optimality. While \code{switches} #' remain, see \code{phases}, an \code{"fvalue"}, \code{"preddiff"}, @@ -75,13 +95,17 @@ #' @section Multiple shooting: #' An objective built by \code{\link{normL2}(..., multipleShootingControl = )}, #' alone or in a sum, is optimized by multiple shooting with the same controls. -#' Not available then: \code{hessianMethod = "exact"}, more than one phase, +#' Not available then: \code{hessianMethod = "exact"} and the structured +#' methods, more than one phase, #' \code{switches}, \code{qnControl$hessianInit = "exact"}, #' \code{qnControl$hessianReseed}, \code{qnControl$qnMemory}, #' \code{stepControl$nonmonotone}, #' \code{boundary = "clip"}, \code{minimize = FALSE} and \code{traceFile}. #' The run reports \code{converged = TRUE} only when the scaled gaps between -#' the segments are below \code{tolControl$ctol}. The method is described in +#' the segments are below \code{tolControl$ctol}. The stops follow section +#' Convergence, with the full step of the condensed model as the Newton step; +#' stagnation also needs the gaps flat within \code{ctol}. The method is +#' described in #' the methods article #' [Multiple shooting](https://dmodverse.github.io/dMod2/articles/methods-multiple-shooting.html). #' @@ -100,21 +124,34 @@ #' @param iterlim Maximum number of trust-region iterations over all phases. #' Default \code{1000}. #' @param hessianMethod Source of the model Hessian of a run without -#' \code{phases}: \code{"gn"} (default) the Gauss-Newton Hessian of the +#' \code{phases}: \code{"gn"} the Gauss-Newton Hessian of the #' objective, \code{"bfgs"} or \code{"sr1"} a quasi-Newton update seeded as #' \code{qnControl$hessianInit} says, \code{"exact"} the true Hessian at #' every iterate, which needs an objective that takes \code{deriv2}. -#' \code{"bfgs"}, \code{"sr1"} and \code{"exact"} require -#' \code{boundary = "reflective"}. +#' The structured methods take the Gauss-Newton Hessian at every iterate and +#' add a correction learned from the steps, starting at zero: +#' \code{"sbfgs"} by a BFGS update, \code{"ssr1"} by an SR1 update, which may +#' be indefinite; \code{"gnsbfgs"} and \code{"gnssr1"} switch at every +#' accepted step between the Gauss-Newton Hessian alone and the structured +#' BFGS or SR1 model. They count as quasi-Newton phases for the stops and +#' \code{qnEval}. The correction is learned from the secant of Dennis, +#' Martínez and Tapia on the data rows that an objective of class +#' \code{objfn} returns with \code{hessian = "structured"}, see [objlist()]; +#' without them from the gradient and the Gauss-Newton Hessian. The formulas +#' are in the methods article. +#' All but \code{"gn"} require \code{boundary = "reflective"}. #' Also selects the control defaults below. With \code{phases}, each phase -#' names a method, and this argument is an error. +#' names a method, and this argument is an error. Not given: the hybrid of +#' section Default method. #' @param phases List of phases, each a list of settings, run one after the #' other and from the first again after the last. The run hands over to the -#' next phase at a value, model, step or stagnation stop and when a phase -#' uses up the \code{iterlim} of that phase. A handover restarts the trust region at -#' \code{rinit} and discards the quasi-Newton pairs. Default \code{NULL}: one -#' phase from \code{hessianMethod} and \code{qnControl}, evaluated with the -#' \code{sweep} in \code{...}. Names of the list label the phases in the +#' next phase at a value, model, step or stagnation stop, when a phase +#' uses up the \code{iterlim} of that phase and when the radius stayed the same +#' for \code{radiusStall} iterations. A handover restarts the trust region at +#' \code{rinit}, unless \code{keepRadius}, and discards the quasi-Newton +#' pairs. Default \code{NULL}: one phase from \code{hessianMethod} and +#' \code{qnControl}, evaluated with the \code{sweep} in \code{...}, or the +#' phases of section Default method. Names of the list label the phases in the #' result, the Hessian source does otherwise. Not available with multiple #' shooting and \code{boundary = "clip"}. #' \describe{ @@ -122,20 +159,40 @@ #' \code{hessianMethod}. Required.} #' \item{\code{iterlim}}{Maximum number of iterations of one run of the #' phase. Default \code{NULL}: only the total \code{iterlim}.} +#' \item{\code{radiusStall}}{Number of consecutive iterations that leave +#' the trust radius unchanged after which the phase hands over, the +#' switch of the hybrid method of Fides (Fröhlich and Sorger 2022), which +#' takes 20 for a Gauss-Newton phase followed by BFGS. The count starts +#' anew with every change of the radius and at a handover; without a +#' handover left it ends nothing. Default \code{NULL}: no such handover.} #' \item{\code{sweep}}{\code{"forward"} or \code{"reverse"}, the #' \code{sweep} the objective is evaluated with in the phase; a #' \code{sweep} in \code{...} is an error with \code{phases}. Default #' \code{NULL}: for \code{"bfgs"} and \code{"sr1"} reverse if the #' objective can be evaluated backwards at \code{parinit}, as with #' \code{derivMode = c("forward", "reverse")} throughout the chain, -#' forward otherwise. A Gauss-Newton Hessian is always computed forward. +#' forward otherwise. A Gauss-Newton Hessian is always computed forward, +#' also in the structured methods. #' A handover between phases of different sweep evaluates the current #' iterate once more. The result reports the sweeps as #' \code{phaseSweep}.} +#' \item{\code{keepRadius}}{\code{TRUE} starts the phase at the trust +#' radius of the handover instead of \code{rinit}. Default +#' \code{FALSE}.} +#' \item{\code{onStop}}{What a value, model, step or stagnation stop does +#' in the phase: \code{"handover"} (default) hands over while +#' \code{switches} remain, \code{"end"} ends the run. A phase that ends +#' on stops hands over at \code{iterlim} and \code{radiusStall} only.} #' \item{\code{qnControl}}{Quasi-Newton settings of the phase, merged #' over \code{qnControl}; see there. \code{hessianInit} defaults to #' \code{"gn"} in every phase but the first: a quasi-Newton phase starts -#' from the Gauss-Newton Hessian at the iterate of the handover.} +#' from the Gauss-Newton Hessian at the iterate of the handover. +#' \code{"tracked"}, for a \code{"bfgs"} phase after the first with +#' \code{qnMemory = 0}, starts it from a BFGS matrix kept over the whole +#' run instead: the Hessian at \code{parinit} of the first phase, made +#' positive definite as a BFGS seed is, updated with the accepted steps of +#' the phases before, under the \code{qnCautious} test of the phase, and +#' updated on in the phase itself. Not available on the sparse path.} #' } #' @param switches Number of handovers allowed. Default \code{NULL}: one #' fewer than there are phases, so each runs once. A higher value cycles @@ -165,8 +222,9 @@ #' \code{trustL1} reads \code{ftol}, \code{mtol}, \code{gtol}, \code{xtol} #' and \code{rmin}. #' @param qnControl List of quasi-Newton settings, merged into the defaults and -#' read in a \code{"bfgs"} or \code{"sr1"} phase; \code{hessianInit} also in -#' a first phase of source \code{"gn"}. +#' read in a quasi-Newton or structured phase; \code{hessianInit} also in +#' a first phase of source \code{"gn"}. A structured phase takes +#' \code{hessianInit = "gn"} and \code{qnMemory = 0} only. #' \describe{ #' \item{\code{hessianInit}}{Seed of the approximation: \code{"gn"} #' (default) the Gauss-Newton Hessian at \code{parinit}; @@ -185,14 +243,31 @@ #' \item{\code{qnMemory}}{Number of \code{(s, y)} pairs kept. Default #' \code{0}: every update accumulates onto the seed. A positive value #' rebuilds the approximation in each iteration from the last -#' \code{qnMemory} pairs, without the seed.} +#' \code{qnMemory} pairs, without the seed. On the sparse path, see +#' \code{sparse}, BFGS keeps the last \code{qnMemory} pairs, 10 where it +#' is \code{0}, on top of the seed.} #' \item{\code{qnCautious}}{A BFGS pair is used only when #' \eqn{s^\top y > c\,|s|\,|y|} with \eqn{c} = \code{qnCautious}. Default -#' \code{1e-8}, \code{0} disables the test; \code{"sr1"} is exempt. The -#' result reports the rejected pairs as \code{qnSkipped}.} -#' \item{\code{qnRejected}}{Whether \code{"sr1"} also updates from a +#' \code{1e-8}, \code{0} disables the test; also read by \code{"sbfgs"}, +#' the SR1 methods are exempt. The result reports the rejected pairs as +#' \code{qnSkipped}.} +#' \item{\code{qnRejected}}{Whether an SR1 method also updates from a #' rejected trial point. Default \code{TRUE} for a phase whose source is -#' \code{"sr1"}, \code{FALSE} otherwise.} +#' \code{"sr1"}, \code{"ssr1"} or \code{"gnssr1"}, \code{FALSE} +#' otherwise.} +#' \item{\code{qnScaling}}{\code{"none"} (default) or \code{"residual"}: +#' \code{"sbfgs"} and \code{"ssr1"} scale the correction with the +#' residual norm, the norm of the derivatives of the value in the +#' predictions and sigmas of the data, or the square root of the value +#' for an objective without data rows, so it vanishes with the residuals +#' (Huschens). Read by these two methods only.} +#' \item{\code{qnHybridTol}}{Threshold of the switch of \code{"gnsbfgs"} +#' and \code{"gnssr1"}: below it the model is the Gauss-Newton Hessian. +#' Default \code{1e-6}.} +#' \item{\code{qnHybridShift}}{\code{TRUE} adds the residual norm times +#' the identity to the Gauss-Newton Hessian on the Gauss-Newton branch +#' of \code{"gnsbfgs"} and \code{"gnssr1"}, as Zhou and Chen; default +#' \code{FALSE}.} #' } #' @param stepControl List of step and acceptance settings, merged into the #' defaults. @@ -241,11 +316,17 @@ #' @param sparse \code{"auto"} (default), \code{TRUE} or \code{FALSE}. #' \code{TRUE} calls \code{objfun} with \code{hessian = "sparse"} and solves #' every subproblem on sparse Cholesky factors of the returned \code{Matrix}, -#' a low-rank part \code{lowrank} (see [objlist()]) included; the steps equal -#' those of the dense path to rounding. It needs \code{hessianMethod} -#' \code{"gn"} or \code{"exact"} and \code{boundary = "reflective"}. -#' \code{"auto"} takes the sparse path where it applies, outside multiple -#' shooting, for at least \code{parameters} entries of \code{parinit} and a +#' a low-rank part \code{lowrank} (see [objlist()]) included; on the Hessian +#' of the objective the steps equal those of the dense path to rounding. It +#' needs \code{hessianMethod} +#' \code{"gn"} or \code{"exact"}, or \code{"bfgs"} with +#' \code{qnControl$hessianInit = "gn"}, in every phase, and +#' \code{boundary = "reflective"}. A BFGS phase there is limited-memory BFGS: +#' the Hessian of the objective at the start of the phase plus the compact +#' correction of the last \code{qnMemory} pairs (Byrd, Nocedal and Schnabel +#' 1994), a low-rank part of rank twice the number of pairs. +#' \code{"auto"} takes the sparse path where every phase takes the Hessian of +#' the objective, outside multiple shooting, for at least \code{parameters} entries of \code{parinit} and a #' step cheaper than the dense one at \code{parinit}; the settings come from #' \code{getOption("dMod2.sparseAuto")}, see [dMod2-package]. #' @param ... Further named arguments passed to \code{objfun}. @@ -258,7 +339,8 @@ #' \item{\code{iterations}}{Number of iterations.} #' \item{\code{neval}}{Number of objective evaluations.} #' \item{\code{qnEval}}{Evaluations spent in a quasi-Newton phase.} -#' \item{\code{qnSkipped}}{Pairs rejected by the cautious test.} +#' \item{\code{qnSkipped}}{Pairs rejected by the cautious test, and in a +#' structured phase pairs that left the correction unchanged.} #' \item{\code{nSwitch}}{Number of handovers between phases.} #' \item{\code{phaseIterations}}{Named integer, the iterations of each #' phase run, in run order and named after the phase. The sum is @@ -266,10 +348,14 @@ #' evaluations and without the iterations that reseed instead of #' taking a step.} #' \item{\code{phaseSweep}}{Named character, the sweep of each element -#' of \code{phases}, present when \code{phases} is set.} +#' of \code{phases}, present when \code{phases} is set and in the +#' default hybrid.} #' \item{\code{nReseed}}{Number of reseeds by #' \code{qnControl$hessianReseed = "stall"}, which allows each run of a #' phase the same number.} +#' \item{\code{hybridGN}}{Accepted steps of a \code{"gnsbfgs"} or +#' \code{"gnssr1"} phase after which the model is the Gauss-Newton +#' Hessian.} #' \item{\code{evalBySource}}{Named integer, evaluations per Hessian #' source.} #' \item{\code{converged}}{Logical.} @@ -283,15 +369,18 @@ #' \code{stepback}, \code{accept}, \code{r} (radius), \code{rho} (ratio of #' actual to predicted reduction), \code{valpath}, \code{valtry}, #' \code{preddiff}, \code{stepnorm} and, with -#' \code{boundary = "reflective"}, \code{hessianSource}. +#' \code{boundary = "reflective"}, \code{hessianSource}, which is +#' \code{"gn"} for an iteration of a hybrid method on the Gauss-Newton +#' Hessian. #' #' \code{boundary = "clip"} returns only \code{argument}, \code{value}, #' \code{gradient}, \code{hessian}, \code{iterations}, \code{converged}, #' \code{atBound} and \code{stopReason}, plus the trace. #' #' On the sparse path, see \code{sparse}, \code{hessian} is a sparse -#' \code{Matrix}, and \code{lowrank} where the objective returns one: the -#' Hessian is then \code{hessian} plus that part. +#' \code{Matrix}, and \code{lowrank} where the objective returns one or a +#' BFGS phase adds the correction: the Hessian is then \code{hessian} plus +#' that part. #' #' \code{trustL1} returns a list without class with \code{argument}, #' \code{value}, \code{gradient}, \code{hessian}, \code{iterations}, @@ -346,7 +435,11 @@ #' fit$phaseIterations #' fit$evalBySource #' -#' @references Coleman, T. F. and Li, Y. (1996). An interior trust region +#' @references Byrd, R. H., Nocedal, J. and Schnabel, R. B. (1994). +#' Representations of quasi-Newton matrices and their use in limited memory +#' methods. \emph{Mathematical Programming} 63, 129-156. +#' +#' Coleman, T. F. and Li, Y. (1996). An interior trust region #' approach for nonlinear minimization subject to bounds. #' \emph{SIAM Journal on Optimization} 6(2), 418-445. #' @@ -369,6 +462,19 @@ #' identification from uncertain and indirect measurements. #' \emph{International Journal of Bifurcation and Chaos} 14(6), 1905-1933. #' +#' Dennis, J. E., Martínez, H. J. and Tapia, R. A. (1989). Convergence theory +#' for the structured BFGS secant method with an application to nonlinear +#' least squares. \emph{Journal of Optimization Theory and Applications} +#' 61(2), 161-178. +#' +#' Huschens, J. (1994). On the use of product structure in secant methods +#' for nonlinear least squares problems. \emph{SIAM Journal on Optimization} +#' 4(1), 108-129. +#' +#' Zhou, W. and Chen, X. (2010). Global convergence of a new hybrid +#' Gauss-Newton structured BFGS method for nonlinear least squares problems. +#' \emph{SIAM Journal on Optimization} 20(5), 2422-2441. +#' #' Peifer, M. and Timmer, J. (2007). Parameter estimation in ordinary #' differential equations for biochemical processes using the method of #' multiple shooting. \emph{IET Systems Biology} 1(2), 78-88. @@ -376,7 +482,8 @@ #' @export trust <- function(objfun, parinit, rinit = 0.1, rmax = 10, iterlim = 1000L, - hessianMethod = c("gn", "bfgs", "sr1", "exact"), + hessianMethod = c("gn", "bfgs", "sr1", "exact", "sbfgs", "ssr1", + "gnsbfgs", "gnssr1"), phases = NULL, switches = NULL, parupper = NULL, @@ -393,12 +500,12 @@ trust <- function(objfun, parinit, rinit = 0.1, rmax = 10, ...) { dots <- list(...) .checkSparse(sparse, "trust") - .trustRejectMoved(names(dots), "trust") if (!is.null(phases) && !missing(hessianMethod)) stop("trust: with `phases`, every phase names the hessianMethod.", call. = FALSE) if (!is.null(phases) && !is.null(dots$sweep)) stop("trust: with `phases`, every phase sets the sweep.", call. = FALSE) + hybrid <- is.null(phases) && missing(hessianMethod) && is.null(switches) && is.null(dots$sweep) hessianMethod <- if (is.null(phases)) match.arg(hessianMethod) else .phaseMethod(phases[[1L]]$hessianMethod, 1L) @@ -414,8 +521,11 @@ trust <- function(objfun, parinit, rinit = 0.1, rmax = 10, step$boundary <- boundary ph <- .trustPhases(phases, switches, hessianMethod, qnControl) - # the sparse model takes the Hessian of the objective, in every phase + # the sparse model takes the Hessian of the objective in every phase; sparse = TRUE also + # limited-memory BFGS on it fromObjective <- all(vapply(ph$phases, function(p) p$hessianMethod %in% c("gn", "exact"), TRUE)) + lbfgs <- all(vapply(ph$phases, function(p) p$hessianMethod %in% c("gn", "exact") || + (p$hessianMethod == "bfgs" && identical(p$qnControl$hessianInit, "gn")), TRUE)) first <- NULL if (identical(sparse, "auto")) { choice <- if (fromObjective && boundary == "reflective" && !length(.shootingTerms(objfun))) @@ -423,8 +533,14 @@ trust <- function(objfun, parinit, rinit = 0.1, rmax = 10, sparse <- choice$sparse first <- choice$first } - if (isTRUE(sparse) && (!fromObjective || boundary != "reflective")) + # the default is the hybrid of Fides where the run takes the dense path and phases + if (hybrid && !isTRUE(sparse) && boundary == "reflective" && !length(.shootingTerms(objfun))) { + phases <- .hybridPhases + ph <- .trustPhases(phases, NULL, hessianMethod, qnControl) + } + if (isTRUE(sparse) && (!lbfgs || boundary != "reflective")) stop("trust(sparse = TRUE) takes the Hessian of the objective, hessianMethod \"gn\" or \"exact\", ", + "or limited-memory BFGS on it, \"bfgs\" with qnControl$hessianInit = \"gn\", ", "with boundary = \"reflective\".", call. = FALSE) # The objective decides: a normL2 with a multipleShootingControl, alone or @@ -470,6 +586,9 @@ trust <- function(objfun, parinit, rinit = 0.1, rmax = 10, }) pnames <- names(parinit) + # a run with a structured phase asks an objfn for the data rows with every Gauss-Newton Hessian + structured <- !sparse && inherits(objfun, "objfn") && + any(vapply(ph$phases, `[[`, "", "hessianMethod") %in% .structuredMethods) 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 @@ -479,10 +598,12 @@ trust <- function(objfun, parinit, rinit = 0.1, rmax = 10, return(.kernelHessian(out, pnames)) } args <- list(x, deriv = want >= 1L, hessian = if (want >= 2L) (if (sparse) "sparse" else TRUE) else FALSE) + if (want == 2L && structured) args$hessian <- "structured" if (want >= 3L) args$deriv2 <- TRUE d <- phaseDots[[phase + 1L]] if (!is.null(phases) && want == 2L) d$sweep <- NULL out <- .tryObjective(do.call(objfun, c(args, d))) + if (is.list(out) && !is.null(out$structure)) out$structure <- .structureOver(out$structure, pnames) if (!sparse || want < 2L || inherits(out, "try-error")) return(out) if (!is.null(out$hessian) && !.isSparse(out$hessian)) { dense <- .denseTerms(objfun, x, d) @@ -499,14 +620,21 @@ trust <- function(objfun, parinit, rinit = 0.1, rmax = 10, boundary, vapply(ph$phases, `[[`, "", "hessianMethod"), vapply(ph$phases, `[[`, 1L, "iterlim"), + vapply(ph$phases, `[[`, 1L, "radiusStall"), sweeps == "reverse", + vapply(ph$phases, `[[`, TRUE, "keepRadius"), + vapply(ph$phases, function(p) p$onStop == "end", TRUE), vapply(qfield("hessianInit"), function(v) - match.arg(v, c("gn", "identity", "exact")), ""), + match.arg(v, c("gn", "identity", "exact", "tracked")), ""), vapply(qfield("hessianReseed"), function(v) match.arg(v %||% "never", c("never", "stall")), ""), vapply(qfield("qnMemory"), as.integer, 1L), vapply(qfield("qnCautious"), as.numeric, 1), vapply(qfield("qnRejected"), isTRUE, TRUE), + vapply(qfield("qnScaling"), function(v) + match.arg(v, c("none", "residual")) == "residual", TRUE), + vapply(qfield("qnHybridTol"), as.numeric, 1), + vapply(qfield("qnHybridShift"), isTRUE, TRUE), ph$switches, step$nonmonotone, isTRUE(sparse), minimize, blather, parupper, parlower, printIter, traceFile) @@ -538,9 +666,18 @@ trust <- function(objfun, parinit, rinit = 0.1, rmax = 10, .phaseMethod <- function(method, k) { if (is.null(method)) stop("trust: phases[[", k, "]] names no hessianMethod.", call. = FALSE) - match.arg(method, c("gn", "bfgs", "sr1", "exact")) + match.arg(method, .hessianMethods) } +.hessianMethods <- c("gn", "bfgs", "sr1", "exact", "sbfgs", "ssr1", "gnsbfgs", "gnssr1") +# The default run of trust(): the hybrid of Fides (Fröhlich and Sorger 2022). +.hybridPhases <- list( + gn = list(hessianMethod = "gn", radiusStall = 20L, onStop = "end"), + bfgs = list(hessianMethod = "bfgs", sweep = "forward", keepRadius = TRUE, + qnControl = list(hessianInit = "tracked"))) +# Methods that keep the Gauss-Newton Hessian of the objective and update a correction. +.structuredMethods <- c("sbfgs", "ssr1", "gnsbfgs", "gnssr1") + # The phases of a run, each with the Hessian source, budget (NA: no phase # budget), sweep and quasi-Newton settings merged over the defaults of the source # and the top-level qnControl. Without `phases`, one phase from the top level. @@ -551,8 +688,8 @@ trust <- function(objfun, parinit, rinit = 0.1, rmax = 10, !all(vapply(phases, is.list, TRUE))) stop("trust: `phases` must be a non-empty list of lists.", call. = FALSE) - defaults <- list(hessianMethod = NULL, iterlim = NULL, sweep = NULL, - qnControl = NULL) + defaults <- list(hessianMethod = NULL, iterlim = NULL, radiusStall = NULL, + sweep = NULL, keepRadius = FALSE, onStop = "handover", qnControl = NULL) out <- lapply(seq_along(phases), function(k) { p <- .mergeControl(defaults, phases[[k]], paste0("phases[[", k, "]]")) p$hessianMethod <- .phaseMethod(p$hessianMethod, k) @@ -561,12 +698,29 @@ trust <- function(objfun, parinit, rinit = 0.1, rmax = 10, stop("trust: phases[[", k, "]]$iterlim must be a positive number.", call. = FALSE) p$iterlim <- if (is.finite(lim)) as.integer(lim) else NA_integer_ + stall <- p$radiusStall %||% Inf + if (length(stall) != 1L || is.na(stall) || stall < 1) + stop("trust: phases[[", k, "]]$radiusStall must be a positive number.", + call. = FALSE) + p$radiusStall <- if (is.finite(stall)) as.integer(stall) else NA_integer_ + if (!isTRUE(p$keepRadius) && !isFALSE(p$keepRadius)) + stop("trust: phases[[", k, "]]$keepRadius must be TRUE or FALSE.", call. = FALSE) + p$onStop <- match.arg(p$onStop, c("handover", "end")) q <- .mergeControl(.trustDefaults(p$hessianMethod)$qnControl, qnControl, "qnControl") # A later phase starts from the Gauss-Newton Hessian at the handover. if (k > 1L) q$hessianInit <- "gn" p$qnControl <- .mergeControl(q, p$qnControl, paste0("phases[[", k, "]]$qnControl")) + if (p$hessianMethod %in% .structuredMethods && + (!identical(p$qnControl$hessianInit, "gn") || !identical(as.integer(p$qnControl$qnMemory), 0L))) + stop("trust: hessianMethod \"", p$hessianMethod, "\" starts from the Gauss-Newton ", + "Hessian and keeps no pairs; it takes qnControl$hessianInit = \"gn\" and ", + "qnMemory = 0.", call. = FALSE) + if (identical(p$qnControl$hessianInit, "tracked") && + (k == 1L || p$hessianMethod != "bfgs" || !identical(as.integer(p$qnControl$qnMemory), 0L))) + stop("trust: qnControl$hessianInit = \"tracked\" takes a \"bfgs\" phase after the first, ", + "with qnMemory = 0.", call. = FALSE) p }) @@ -585,9 +739,9 @@ trust <- function(objfun, parinit, rinit = 0.1, rmax = 10, # "reverse" has to work. `probe()` is TRUE or the message of the failed probe. .phaseSweep <- function(sweep, method, objfun, probe) { if (!is.null(sweep)) sweep <- match.arg(sweep, c("forward", "reverse")) - if (identical(method, "gn")) { + if (method %in% c("gn", .structuredMethods)) { if (identical(sweep, "reverse")) - stop("trust: a Gauss-Newton phase needs the forward sensitivities; ", + stop("trust: a phase on the Gauss-Newton Hessian needs the forward sensitivities; ", "sweep = \"reverse\" is for \"bfgs\", \"sr1\" and \"exact\".", call. = FALSE) return("forward") @@ -636,9 +790,10 @@ print.trustfit <- function(x, ...) { # all; see the roxygen of `trust` for what they mean. .trustDefaults <- function(hessianMethod = "gn") { qn <- list(hessianInit = "gn", hessianReseed = "never", - qnMemory = 0L, qnCautious = 1e-8, qnRejected = FALSE) + qnMemory = 0L, qnCautious = 1e-8, qnRejected = FALSE, + qnScaling = "none", qnHybridTol = 1e-6, qnHybridShift = FALSE) # Nocedal and Wright, sec. 6.2: SR1 also updates from a rejected step. - if (identical(hessianMethod, "sr1")) qn$qnRejected <- TRUE + if (hessianMethod %in% c("sr1", "ssr1", "gnssr1")) qn$qnRejected <- TRUE list( tolControl = list(ftol = 1e-6, mtol = 1e-6, gtol = 1e-6, xtol = 0, rmin = 0, ctol = 1e-6), @@ -650,32 +805,6 @@ print.trustfit <- function(x, ...) { } -# Members of a control list, refused by name when given flat instead of being -# routed to objfun. -.trustMoved <- c( - ftol = "tolControl$ftol", mtol = "tolControl$mtol", - gtol = "tolControl$gtol", xtol = "tolControl$xtol", - rmin = "tolControl$rmin", - hessianInit = "qnControl$hessianInit", qnMemory = "qnControl$qnMemory", - hessianReseed = "qnControl$hessianReseed", - qnCautious = "qnControl$qnCautious", qnRejected = "qnControl$qnRejected", - thetaMax = "stepControl$thetaMax", theta.max = "stepControl$thetaMax", - nonmonotone = "stepControl$nonmonotone") - -.trustRejectMoved <- function(nms, who) { - gone <- intersect(nms, c("fallbackControl", "hessianFallback", "fallbackLimit")) - if (length(gone)) - stop(who, ": ", paste(gone, collapse = ", "), " is no argument; a run over ", - "several Hessian sources takes `phases` and `switches`, see ?trust.", - call. = FALSE) - hit <- intersect(nms, names(.trustMoved)) - if (length(hit)) - stop(who, ": ", paste(hit, collapse = ", "), " moved into a control list. ", - "Use ", paste(.trustMoved[hit], collapse = ", "), ".", call. = FALSE) - invisible(NULL) -} - - # Merge a user control list into the method's defaults. Names are checked # against the defaults, so a typo errors here instead of being ignored. .mergeControl <- function(defaults, control = NULL, label = "control") { @@ -734,7 +863,9 @@ trustL1 <- function(objfun, parinit, mu = 0 * parinit, one.sided = FALSE, lambda traceFile = NULL, gate = NULL, fuse = NULL, ...) { - .trustRejectMoved(names(list(...)), "trustL1") + if ("hessianMethod" %in% names(list(...))) + stop("trustL1: the model Hessian is the one of the objective; hessianMethod is an ", + "argument of trust().", call. = FALSE) boundary <- match.arg(boundary) tolDefaults <- .trustDefaults("gn")$tolControl[c("ftol", "mtol", "gtol", "xtol", "rmin")] tol <- .mergeControl(tolDefaults, tolControl, "tolControl") diff --git a/R/trustShooting.R b/R/trustShooting.R index a098f02e..1dd6ea62 100644 --- a/R/trustShooting.R +++ b/R/trustShooting.R @@ -14,7 +14,7 @@ hm <- hessianMethod bad <- c( - if (hm == "exact") "hessianMethod = \"exact\"", + if (hm %in% c("exact", .structuredMethods)) paste0("hessianMethod = \"", hm, "\""), if (!identical(qn$hessianInit, "gn") && !identical(qn$hessianInit, "identity")) "qnControl$hessianInit = \"exact\"", if (!identical(qn$hessianReseed %||% "never", "never")) "qnControl$hessianReseed", @@ -441,6 +441,12 @@ } converged <- FALSE; stopReason <- "iterlim" iter <- 0L + # As in trust(), a convergence stop needs the full Newton step to predict at + # most mtol; a stop held back names itself if the run later stagnates or + # ends on the radius before a step changes the value by ftol. + vetoed <- NULL + newtonSmall <- function(C) tol$mtol <= 0 || + .shootNewtonDecrease(C, thx(theta), lbx, ubx, psxOf()) <= tol$mtol trace <- list() C <- NULL @@ -448,6 +454,8 @@ # Peifer and Timmer (2007), sec. 3.4: predictor-corrector damping; a step is # taken when the simplified step at the step end has shrunk. handedOver <- FALSE + # iterations of the natural level function before a handover; iterlim bounds both + itNat <- 0L if (acc == "natural") { if (!is.null(attr(sobj, "args")$errmodel) || !all(vapply(spec$segs, function(sg) all(is.finite(sg$data$sigma)), TRUE))) @@ -465,11 +473,12 @@ h <- .shootViolation(E$gaps, scale) omega <- NA_real_ for (iter in seq_len(iterlim)) { - C <- condense(E) + if (is.null(C)) C <- condense(E) psx <- psxOf() opt <- .shootOptimality(thx(theta), C$g0, lbx, ubx, psx) if (opt$measure <= tol$gtol && h <= tol$ctol) { - converged <- TRUE; stopReason <- "gradient"; break + if (newtonSmall(C)) { converged <- TRUE; stopReason <- "gradient"; break } + vetoed <- "gradient" } FS <- .shootFullStep(C, thx(theta), lbx, ubx, psx, reg) nDu <- FS$norm @@ -521,8 +530,10 @@ if (inherits(ET, "error")) { stopReason <- "objfun"; break } df <- abs(f - (ET$value + PRT$value)) theta <- thetaT; nodes <- nodesT; E <- ET; PR <- PRT + C <- NULL f <- E$value + PR$value h <- .shootViolation(E$gaps, scale) + if (df >= tol$ftol) vetoed <- NULL if (adaptive) { E2 <- splitAt(violators(E)) if (!is.null(E2)) { @@ -533,7 +544,9 @@ } } if (lam == 1 && h <= tol$ctol && df < tol$ftol) { - converged <- TRUE; stopReason <- "fvalue"; break + C <- condense(E) + if (newtonSmall(C)) { converged <- TRUE; stopReason <- "fvalue"; break } + vetoed <- "fvalue" } } C <- NULL @@ -541,6 +554,8 @@ # the full step; the filter's trust region takes over from here. if (stopReason == "damping") { handedOver <- TRUE + itNat <- iter + iter <- 0L acc <- "filter" stopReason <- "iterlim" f <- E$value + PR$value @@ -553,12 +568,13 @@ # 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)) { + if (acc != "natural") for (iter in seq_len(iterlim - itNat)) { if (is.null(C)) C <- condense(E) psx <- psxOf() opt <- .shootOptimality(thx(theta), C$g0, lbx, ubx, psx) if (opt$measure <= tol$gtol && h <= tol$ctol) { - converged <- TRUE; stopReason <- "gradient"; break + if (newtonSmall(C)) { converged <- TRUE; stopReason <- "gradient"; break } + vetoed <- "gradient" } znorm <- C$znorm @@ -713,8 +729,19 @@ next } } - if (n_stall >= 5L) { converged <- TRUE; stopReason <- "stagnation"; break } - if (tol$rmin > 0 && r < tol$rmin) { stopReason <- "radius"; break } + # rejected steps that leave value and gaps flat are convergence only + # where the model predicts no decrease above mtol, or a stop was held back + if (n_stall >= 5L) { + if (is.null(C)) C <- condense(E) + converged <- h <= tol$ctol && (!is.null(vetoed) || newtonSmall(C)) + stopReason <- "stagnation" + break + } + if (tol$rmin > 0 && r < tol$rmin) { + converged <- !is.null(vetoed) + stopReason <- if (converged) vetoed else "radius" + break + } next } @@ -739,11 +766,17 @@ } } - if (hm == "gn" && h <= tol$ctol) { - if (df < tol$ftol) { converged <- TRUE; stopReason <- "fvalue"; break } - if (abs(dmf) < tol$mtol) { converged <- TRUE; stopReason <- "preddiff"; break } - if (tol$xtol > 0 && stepnorm < tol$xtol) { converged <- TRUE; stopReason <- "step"; break } + if (df >= tol$ftol) vetoed <- NULL + if (hm != "gn" || h > tol$ctol) next + stop1 <- if (df < tol$ftol) "fvalue" + else if (abs(dmf) < tol$mtol) "preddiff" + else if (tol$xtol > 0 && stepnorm < tol$xtol) "step" + if (is.null(stop1)) next + if (stop1 != "step") { + C <- condense(E) + if (!newtonSmall(C)) { vetoed <- stop1; next } } + converged <- TRUE; stopReason <- stop1; break } if (is.null(C)) C <- condense(E) @@ -766,7 +799,7 @@ 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 = iter, neval = neval, + iterations = itNat + iter, neval = neval, qnSkipped = qnSkipped, converged = converged, stopReason = stopReason, atBound = opt$atBound[seq_len(K)], @@ -799,7 +832,7 @@ } class(f1) <- c("objfn", "fn") r <- tryCatch(suppressWarnings(trust(f1, theta, rinit = rinit, rmax = rmax, - iterlim = iterlim, + iterlim = iterlim, hessianMethod = "gn", parupper = ub, parlower = lb)), error = function(e) NULL) if (is.null(r) || !all(is.finite(r$argument))) @@ -1163,6 +1196,23 @@ x } +# The decrease the full step of the condensed model predicts, in the variables +# scaled for the bounds as in trust(): the gradient on the pseudoinverse of the +# positive part of the scaled Hessian, plus the change from closing the gaps. +.shootNewtonDecrease <- function(C, x, lb, ub, ps) { + K <- length(x) + gz <- C$g0 / ps + b <- ifelse(gz < 0, ub, lb) + fin <- is.finite(b) + sv <- sqrt(ifelse(fin, abs(x - b) * ps, 1)) + ghat <- sv * (C$g0 + C$gz) / ps + Hhat <- C$H * tcrossprod(sv / ps) + diag(abs(gz) * fin, K) + e <- eigen(0.5 * (Hhat + t(Hhat)), symmetric = TRUE) + keep <- e$values > 8 * K * .Machine$double.eps * max(abs(e$values)) + t1 <- crossprod(e$vectors[, keep, drop = FALSE], ghat) + 0.5 * sum(t1^2 / e$values[keep]) - C$q0 - 0.5 * C$q2 +} + # The optimality measure of the box problem, as trust() computes it. .shootOptimality <- function(x, g, lb, ub, ps) { gz <- g / ps diff --git a/_pkgdown.yml b/_pkgdown.yml index 3c1ff0ec..12efb0f5 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -360,14 +360,14 @@ reference: - plotData - plotPrediction - plotCombined - - theme_dMod - - scale_color_dMod - - scale_color_dMod_c - - dMod_colors - - dMod_colors_cb - - dMod_palette - - dMod_palettes - - dMod_gradient + - theme_dMod2 + - scale_color_dMod2 + - scale_color_dMod2_c + - dMod2_colors + - dMod2_colors_cb + - dMod2_palette + - dMod2_palettes + - dMod2_gradient - title: Data sets contents: diff --git a/bench/multipleShooting/macrospin.R b/bench/multipleShooting/macrospin.R index ec091ca5..6a21023c 100644 --- a/bench/multipleShooting/macrospin.R +++ b/bench/multipleShooting/macrospin.R @@ -142,7 +142,7 @@ aggregate(cbind(hits = hit, sec, neval) ~ method, out, ggplot(out, aes(rank(ss, ties.method = "first"), pmin(ss - best, 1e4), color = method)) + geom_point(size = 0.8) + facet_wrap(~method) + scale_y_continuous(trans = "log1p") + - labs(x = "fit rank", y = "objective - best") + theme_dMod(base_size = 9) + labs(x = "fit rank", y = "objective - best") + theme_dMod2(base_size = 9) # ––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– diff --git a/bench/multipleShooting/preBotC.R b/bench/multipleShooting/preBotC.R index 9646a42a..2f839109 100644 --- a/bench/multipleShooting/preBotC.R +++ b/bench/multipleShooting/preBotC.R @@ -239,7 +239,7 @@ ggplot(traj, aes(time, value)) + facet_wrap(~run, ncol = 1) + labs(x = "time [ms]", y = "V [mV]", title = sprintf("start %d at %.2f decades", pick$start, pick$scale)) + - theme_dMod(base_size = 9) + theme_dMod2(base_size = 9) # The curves are stored to 0.01 mV, far below the noise, which keeps the file # small. diff --git a/bench/nlme/mavoglurant.R b/bench/nlme/mavoglurant.R index e43790c5..412dae72 100644 --- a/bench/nlme/mavoglurant.R +++ b/bench/nlme/mavoglurant.R @@ -165,7 +165,7 @@ best <- tapply(runs$value, runs$method, min, na.rm = TRUE) runs <- runs[order(runs$fit, runs$value), ] runs$rank <- stats::ave(seq_along(runs$value), runs$fit, FUN = seq_along) ggplot2::ggplot(runs[is.finite(runs$value), ], ggplot2::aes(rank, value - best[method] + 1e-3, color = fit)) + - ggplot2::geom_point() + ggplot2::scale_y_log10() + scale_color_dMod() + theme_dMod() + ggplot2::geom_point() + ggplot2::scale_y_log10() + scale_color_dMod2() + theme_dMod2() bestStart <- function(r, m) r$start[r$method == m][which.min(r$value[r$method == m])] seconds <- c( dMod2focei = min(vapply(seq_len(reps), function(i) diff --git a/bench/nlme/tmdd.R b/bench/nlme/tmdd.R index e82d0b05..3dd89bae 100644 --- a/bench/nlme/tmdd.R +++ b/bench/nlme/tmdd.R @@ -149,7 +149,7 @@ summary <- do.call(rbind, lapply(split(res, list(res$method, res$parameter), dro coverage = mean(r$covered)))) summary[order(summary$parameter, summary$method), ] ggplot2::ggplot(res, ggplot2::aes(method, error)) + ggplot2::geom_hline(yintercept = 0, linetype = 2) + - ggplot2::geom_boxplot() + ggplot2::facet_wrap(~ parameter, scales = "free_y") + theme_dMod() + + ggplot2::geom_boxplot() + ggplot2::facet_wrap(~ parameter, scales = "free_y") + theme_dMod2() + ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 45, hjust = 1)) ## Single fits on 10 cores --------------------------------------------------------------- diff --git a/bench/nlme/warfarin.R b/bench/nlme/warfarin.R index ce3f5f79..b5b68488 100644 --- a/bench/nlme/warfarin.R +++ b/bench/nlme/warfarin.R @@ -118,7 +118,7 @@ best <- min(runs$value, na.rm = TRUE) runs <- runs[order(runs$fit, runs$value), ] runs$rank <- stats::ave(seq_along(runs$value), runs$fit, FUN = seq_along) ggplot2::ggplot(runs[is.finite(runs$value), ], ggplot2::aes(rank, value - best + 1e-3, color = fit)) + - ggplot2::geom_point() + ggplot2::scale_y_log10() + scale_color_dMod() + theme_dMod() + ggplot2::geom_point() + ggplot2::scale_y_log10() + scale_color_dMod2() + theme_dMod2() seconds <- c( dMod2focei = min(vapply(seq_len(reps), function(i) system.time(em(obj, random, starts[which.min(dmod$value[dmod$method == "focei"]), ], verbose = FALSE))[["elapsed"]], 0)), diff --git a/bench/symmetry/AB.R b/bench/symmetry/AB.R index e8fd8275..4be061d6 100644 --- a/bench/symmetry/AB.R +++ b/bench/symmetry/AB.R @@ -153,7 +153,7 @@ z[, "time"] <- c(-rev(zb[, "time"]), zf[-1, "time"]) ggplot(wide2long(z), aes(time, value)) + geom_line() + geom_vline(xintercept = 0, linetype = 3) + facet_wrap(~ name, scales = "free_y") + - labs(x = expression(epsilon), y = NULL) + theme_dMod(base_size = 9) + labs(x = expression(epsilon), y = NULL) + theme_dMod2(base_size = 9) theta <- lapply(seq_len(nrow(z)), function(j) replace(truthL, mvL, z[j, mvL])) pred <- lapply(theta, function(th) as.data.frame(prd(times, th, deriv = FALSE))) @@ -175,9 +175,9 @@ long$name <- factor(long$name, levels(long$name)[order(lev %in% names(observable ggplot(long, aes(time, value, group = eps, color = eps)) + geom_line() + facet_wrap(~ name, scales = "free_y") + - scale_color_dMod_div(name = expression(epsilon)) + + scale_color_dMod2_div(name = expression(epsilon)) + labs(title = paste0("A <-> B, X", direction), x = "time", y = NULL) + - theme_dMod(base_size = 9) + theme_dMod2(base_size = 9) # ––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– diff --git a/bench/symmetry/battery.R b/bench/symmetry/battery.R index 020ef919..c1cb8842 100644 --- a/bench/symmetry/battery.R +++ b/bench/symmetry/battery.R @@ -136,7 +136,7 @@ times <- seq(0, 4000, len = 400) pred0 <- as.data.frame(prd(times, truthL, deriv = FALSE)) ggplot(pred0, aes(time, value)) + geom_line() + - facet_wrap(~ name, scales = "free_y") + theme_dMod(base_size = 9) + facet_wrap(~ name, scales = "free_y") + theme_dMod2(base_size = 9) # ---- Every direction, both ways --------------------------------------------- diff --git a/bench/symmetry/macrospin_mtj_switching.R b/bench/symmetry/macrospin_mtj_switching.R index 1d2b91b0..8d915098 100644 --- a/bench/symmetry/macrospin_mtj_switching.R +++ b/bench/symmetry/macrospin_mtj_switching.R @@ -146,7 +146,7 @@ z[, "time"] <- c(-rev(zb[, "time"]), zf[-1, "time"]) orbit <- data.frame(eps = z[, "time"], al = 10^z[, "al_l10"], gam = 10^z[, "gam_l10"]) ggplot(orbit, aes(al, gam, color = eps)) + geom_path() + geom_point() + scale_x_log10() + scale_y_log10() + - scale_color_dMod_div(name = expression(epsilon)) + theme_dMod(base_size = 9) + scale_color_dMod2_div(name = expression(epsilon)) + theme_dMod2(base_size = 9) range(orbit$gam*orbit$al/(1 + orbit$al^2)) pred0 <- as.data.frame(prd(times, truth, deriv = FALSE)) @@ -169,9 +169,9 @@ long <- do.call(rbind, pred) long$name <- factor(long$name, c("y", "mx", "my"), c("y [observed]", "mx", "my")) ggplot(long, aes(time, value, group = eps, color = eps)) + geom_line() + facet_wrap(~ name, ncol = 1, scales = "free_y") + - scale_color_dMod_div(name = expression(epsilon)) + + scale_color_dMod2_div(name = expression(epsilon)) + labs(title = "easy axis, alpha-gamma direction", x = "time [ns]", y = NULL) + - theme_dMod(base_size = 9) + theme_dMod2(base_size = 9) # ––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– diff --git a/bench/symmetry/preBotC.R b/bench/symmetry/preBotC.R index 45408e82..ee7e5709 100644 --- a/bench/symmetry/preBotC.R +++ b/bench/symmetry/preBotC.R @@ -164,7 +164,7 @@ truthO[isLog] <- log10(truthO[isLog]) times <- seq(0, 10000, by = 0.5) pred0 <- as.data.frame(prd(times, truthO, deriv = FALSE)) ggplot(pred0, aes(time, value)) + geom_line() + - facet_wrap(~ name, scales = "free_y", ncol = 1) + theme_dMod(base_size = 9) + facet_wrap(~ name, scales = "free_y", ncol = 1) + theme_dMod2(base_size = 9) # reduced truth: each outer parameter of the reduction evaluated as the invariant it stands for meaning <- unlist(lapply(red$blocks, `[[`, "survivorMeaning")) @@ -253,26 +253,26 @@ orbitPred <- lapply(orbitPred, function(q) { ggplot(orbitPred[[1]], aes(time, value, group = eps, color = eps)) + geom_line(linewidth = 0.3) + facet_wrap(~ name, scales = "free_y", ncol = 2) + - scale_color_dMod_div(name = expression(epsilon)) + + scale_color_dMod2_div(name = expression(epsilon)) + labs(title = sprintf("pre-Boetzinger, X1 (%s)", res$symmetries[[1]]$type), x = "time [ms]", y = NULL) + - theme_dMod(base_size = 9) + theme_dMod2(base_size = 9) ggplot(orbitPred[[2]], aes(time, value, group = eps, color = eps)) + geom_line(linewidth = 0.3) + facet_wrap(~ name, scales = "free_y", ncol = 2) + - scale_color_dMod_div(name = expression(epsilon)) + + scale_color_dMod2_div(name = expression(epsilon)) + labs(title = sprintf("pre-Boetzinger, X2 (%s)", res$symmetries[[2]]$type), x = "time [ms]", y = NULL) + - theme_dMod(base_size = 9) + theme_dMod2(base_size = 9) ggplot(orbitPred[[3]], aes(time, value, group = eps, color = eps)) + geom_line(linewidth = 0.3) + facet_wrap(~ name, scales = "free_y", ncol = 2) + - scale_color_dMod_div(name = expression(epsilon)) + + scale_color_dMod2_div(name = expression(epsilon)) + labs(title = sprintf("pre-Boetzinger, X3 (%s)", res$symmetries[[3]]$type), x = "time [ms]", y = NULL) + - theme_dMod(base_size = 9) + theme_dMod2(base_size = 9) # ––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– diff --git a/examples/TMDD/README.md b/examples/TMDD/README.md index 9a111b4e..2fbc0e69 100644 --- a/examples/TMDD/README.md +++ b/examples/TMDD/README.md @@ -129,6 +129,8 @@ identifiability ``` #> Result: structurally locally identifiable (rank 9 / 9) +#> +#> Discrete symmetries: 0 ``` ## Design and simulation diff --git a/examples/TMDD/figures/unnamed-chunk-10-1.png b/examples/TMDD/figures/unnamed-chunk-10-1.png index b3664b89..113975a7 100644 Binary files a/examples/TMDD/figures/unnamed-chunk-10-1.png and b/examples/TMDD/figures/unnamed-chunk-10-1.png differ diff --git a/examples/TMDD/figures/unnamed-chunk-10-2.png b/examples/TMDD/figures/unnamed-chunk-10-2.png index 13d94cb3..5ef18b14 100644 Binary files a/examples/TMDD/figures/unnamed-chunk-10-2.png and b/examples/TMDD/figures/unnamed-chunk-10-2.png differ diff --git a/examples/TMDD/figures/unnamed-chunk-10-3.png b/examples/TMDD/figures/unnamed-chunk-10-3.png index 46f86c50..e37be7ea 100644 Binary files a/examples/TMDD/figures/unnamed-chunk-10-3.png and b/examples/TMDD/figures/unnamed-chunk-10-3.png differ diff --git a/examples/TMDD/figures/unnamed-chunk-10-4.png b/examples/TMDD/figures/unnamed-chunk-10-4.png index be29bb49..1946c6f9 100644 Binary files a/examples/TMDD/figures/unnamed-chunk-10-4.png and b/examples/TMDD/figures/unnamed-chunk-10-4.png differ diff --git a/examples/TMDD/figures/unnamed-chunk-10-5.png b/examples/TMDD/figures/unnamed-chunk-10-5.png index 0c6d447f..8c3ded45 100644 Binary files a/examples/TMDD/figures/unnamed-chunk-10-5.png and b/examples/TMDD/figures/unnamed-chunk-10-5.png differ diff --git a/examples/TMDD/figures/unnamed-chunk-8-1.png b/examples/TMDD/figures/unnamed-chunk-8-1.png index 0ae1fc5d..406af6e0 100644 Binary files a/examples/TMDD/figures/unnamed-chunk-8-1.png and b/examples/TMDD/figures/unnamed-chunk-8-1.png differ diff --git a/examples/bachmannMSB2011/figures/dose-1.png b/examples/bachmannMSB2011/figures/dose-1.png index 79d2b549..039eec6b 100644 Binary files a/examples/bachmannMSB2011/figures/dose-1.png and b/examples/bachmannMSB2011/figures/dose-1.png differ diff --git a/examples/bachmannMSB2011/figures/parameters-1.png b/examples/bachmannMSB2011/figures/parameters-1.png index 77b24546..30a38f12 100644 Binary files a/examples/bachmannMSB2011/figures/parameters-1.png and b/examples/bachmannMSB2011/figures/parameters-1.png differ diff --git a/examples/bachmannMSB2011/figures/perturbations-1.png b/examples/bachmannMSB2011/figures/perturbations-1.png index 0388e4e8..bca478df 100644 Binary files a/examples/bachmannMSB2011/figures/perturbations-1.png and b/examples/bachmannMSB2011/figures/perturbations-1.png differ diff --git a/examples/bachmannMSB2011/figures/reference-1.png b/examples/bachmannMSB2011/figures/reference-1.png index 9c752d68..ef0e72d3 100644 Binary files a/examples/bachmannMSB2011/figures/reference-1.png and b/examples/bachmannMSB2011/figures/reference-1.png differ diff --git a/examples/bachmannMSB2011/figures/waterfall-1.png b/examples/bachmannMSB2011/figures/waterfall-1.png index 2039ca23..1b154e0c 100644 Binary files a/examples/bachmannMSB2011/figures/waterfall-1.png and b/examples/bachmannMSB2011/figures/waterfall-1.png differ diff --git a/examples/bachmannMSB2011/plots.R b/examples/bachmannMSB2011/plots.R index bda84942..a01e0343 100644 --- a/examples/bachmannMSB2011/plots.R +++ b/examples/bachmannMSB2011/plots.R @@ -49,8 +49,8 @@ plotCombined(pred, data[perturbed], paste(condition, name) %in% recorded, name % aesthetics = list(color = "perturbation", group = "condition"), errfn = e) + facet_grid(rows = vars(name), cols = vars(factor(experiment, names(perturbations), perturbations)), scales = "free_y", labeller = labeller(name = observable)) + - scale_color_dMod(limits = c("control", unname(perturbations))) + - scale_fill_dMod(limits = c("control", unname(perturbations))) + + scale_color_dMod2(limits = c("control", unname(perturbations))) + + scale_fill_dMod2(limits = c("control", unname(perturbations))) + scale_x_continuous(breaks = c(0, 120, 240)) + labs(x = "time [min]", y = "log10 signal [a.u.]", color = NULL) + theme(legend.position = "bottom", panel.spacing.x = unit(1, "lines")) @@ -84,7 +84,7 @@ ggplot(dosePred, aes(epo_level, value, color = measured, fill = measured)) + geom_point(data = doseData) + facet_wrap(~name, scales = "free_y", labeller = observable) + scale_x_log10(breaks = 10^(-9:-5), labels = scales::label_log()) + - scale_color_dMod() + - scale_fill_dMod() + - theme_dMod() + + scale_color_dMod2() + + scale_fill_dMod2() + + theme_dMod2() + labs(x = "Epo [units/cell]", y = "log10 signal [a.u.]", color = "measured at", fill = "measured at") diff --git a/examples/bileAcidTransport/README.md b/examples/bileAcidTransport/README.md index d16a1343..9e172efe 100644 --- a/examples/bileAcidTransport/README.md +++ b/examples/bileAcidTransport/README.md @@ -153,6 +153,6 @@ ggplot(.pred, aes(time, value)) + geom_line() + geom_point(data = .band, aes(y = lower), shape = 4) + geom_point(data = .band, aes(y = upper), shape = 4) + - theme_dMod() + + theme_dMod2() + labs(x = "time", y = "cellular bile acid", title = "closed junctions: prediction band") ``` diff --git a/examples/bileAcidTransport/analysis.R b/examples/bileAcidTransport/analysis.R index 2115e22c..fdae39f7 100644 --- a/examples/bileAcidTransport/analysis.R +++ b/examples/bileAcidTransport/analysis.R @@ -98,8 +98,8 @@ ggplot(.optima, aes(time, value, color = factor(round(.value, 1)), inherit.aes = FALSE, width = 0) + geom_point(data = attr(.optima, "data"), color = "black") + facet_grid(name ~ condition, scales = "free_y") + - theme_dMod() + - scale_color_dMod() + + theme_dMod2() + + scale_color_dMod2() + labs(color = "objective value") bestfit <- as.parvec(fits) @@ -224,5 +224,5 @@ ggplot(.pred, aes(time, value)) + geom_line() + geom_point(data = .band, aes(y = lower), shape = 4) + geom_point(data = .band, aes(y = upper), shape = 4) + - theme_dMod() + + theme_dMod2() + labs(x = "time", y = "cellular bile acid", title = "closed junctions: prediction band") diff --git a/examples/boehmJProteomeRes2014/README.md b/examples/boehmJProteomeRes2014/README.md index 11dce400..925408b6 100644 --- a/examples/boehmJProteomeRes2014/README.md +++ b/examples/boehmJProteomeRes2014/README.md @@ -171,8 +171,8 @@ rbind(ML = best[remlfit$errpars], REML = remlfit$argument[remlfit$errpars]) ``` #> sd_pSTAT5A_rel sd_pSTAT5B_rel sd_rSTAT5A_rel -#> ML 0.5877357 0.8201003 0.4987671 -#> REML 0.6253827 0.8442638 0.5249191 +#> ML 0.5879866 0.8200847 0.4988025 +#> REML 0.6254895 0.8442657 0.5248911 ``` ``` r @@ -181,7 +181,7 @@ remlfit$dof # data points minus the summed leverage, per observable ``` #> pSTAT5A_rel pSTAT5B_rel rSTAT5A_rel -#> 13.67754 14.22182 14.10064 +#> 13.67808 14.22157 14.10035 ``` ``` r @@ -200,7 +200,7 @@ tapply(remlfit$leverage$leverage, remlfit$leverage$name, sum) ``` #> pSTAT5A_rel pSTAT5B_rel rSTAT5A_rel -#> 2.322464 1.778181 1.899355 +#> 2.321924 1.778430 1.899645 ``` ## Prediction band @@ -260,15 +260,15 @@ confint(profiles, level = 0.95, val.column = "data", ``` #> name value lower upper -#> Epo_degradation_BaF3 Epo_degradation_BaF3 -1.5679595 -1.74005895 -1.3901478 -#> k_exp_hetero k_exp_hetero -4.4421935 -Inf -2.9536118 -#> k_exp_homo k_exp_homo -2.2029667 -2.55732648 -1.8892122 -#> k_imp_hetero k_imp_hetero -1.7873087 -1.91091368 -1.6581547 -#> k_imp_homo k_imp_homo 1.4688356 0.09953717 Inf -#> k_phos k_phos 4.1976586 4.10644777 4.2965239 -#> sd_pSTAT5A_rel sd_pSTAT5A_rel 0.5877357 0.40937804 0.7942116 -#> sd_pSTAT5B_rel sd_pSTAT5B_rel 0.8201003 0.66464015 1.0126205 -#> sd_rSTAT5A_rel sd_rSTAT5A_rel 0.4987671 0.34873677 0.6906962 +#> Epo_degradation_BaF3 Epo_degradation_BaF3 -1.5677407 -1.74032814 -1.3897985 +#> k_exp_hetero k_exp_hetero -4.4083675 -Inf -2.9518842 +#> k_exp_homo k_exp_homo -2.2022616 -2.55798090 -1.8885277 +#> k_imp_hetero k_imp_hetero -1.7875168 -1.91111565 -1.6579757 +#> k_imp_homo k_imp_homo 1.4651568 0.09834658 Inf +#> k_phos k_phos 4.1977563 4.10634209 4.2967160 +#> sd_pSTAT5A_rel sd_pSTAT5A_rel 0.5879866 0.40915395 0.7945740 +#> sd_pSTAT5B_rel sd_pSTAT5B_rel 0.8200847 0.66430695 1.0130229 +#> sd_rSTAT5A_rel sd_rSTAT5A_rel 0.4988025 0.34854787 0.6911589 ``` For k_imp_homo and k_exp_hetero the data term stays level and only the prior diff --git a/examples/boehmJProteomeRes2014/figures/unnamed-chunk-10-1.png b/examples/boehmJProteomeRes2014/figures/unnamed-chunk-10-1.png index 3b844667..121eb760 100644 Binary files a/examples/boehmJProteomeRes2014/figures/unnamed-chunk-10-1.png and b/examples/boehmJProteomeRes2014/figures/unnamed-chunk-10-1.png differ diff --git a/examples/boehmJProteomeRes2014/figures/unnamed-chunk-14-1.png b/examples/boehmJProteomeRes2014/figures/unnamed-chunk-14-1.png index f4c411a6..f08e837a 100644 Binary files a/examples/boehmJProteomeRes2014/figures/unnamed-chunk-14-1.png and b/examples/boehmJProteomeRes2014/figures/unnamed-chunk-14-1.png differ diff --git a/examples/boehmJProteomeRes2014/figures/unnamed-chunk-16-1.png b/examples/boehmJProteomeRes2014/figures/unnamed-chunk-16-1.png index a6bb7048..68496c92 100644 Binary files a/examples/boehmJProteomeRes2014/figures/unnamed-chunk-16-1.png and b/examples/boehmJProteomeRes2014/figures/unnamed-chunk-16-1.png differ diff --git a/examples/kokMSB2020/README.md b/examples/kokMSB2020/README.md index 7434c9b8..8d06da60 100644 --- a/examples/kokMSB2020/README.md +++ b/examples/kokMSB2020/README.md @@ -298,10 +298,10 @@ summary(structural) #> ------------------------------------------------------------ #> Computation: #> Lie order 19 (gap order 1), set by condition 1 -#> rank: proven (4 directions, exact scalings) +#> rank: proven (4 directions, proven symmetries) #> 25 conditions, 50 segments #> settings: reduce_cq=False, equilibrate=False, reconstruct=False -#> elapsed: 189.0s (rank 187.1s, reconstruction 0.0s, proofs 0.0s) +#> elapsed: 39.7s (rank 37.4s, reconstruction 0.0s, proofs 0.0s) #> #> Result: rank 92 / 96 | 4 non-identifiable directions #> @@ -404,7 +404,7 @@ system.time(obj(bestfit, deriv = FALSE)) ``` #> user system elapsed -#> 0.086 0.000 0.030 +#> 0.071 0.008 0.095 ``` ``` r @@ -413,7 +413,7 @@ system.time(obj(bestfit)) ``` #> user system elapsed -#> 5.631 0.016 0.779 +#> 6.216 0.024 6.243 ``` ``` r @@ -422,7 +422,7 @@ system.time(obj(bestfit, cores = .cores)) ``` #> user system elapsed -#> 5.411 0.000 0.719 +#> 7.239 0.003 0.451 ``` ``` r @@ -431,7 +431,7 @@ system.time(obj(bestfit, sweep = "reverse")) ``` #> user system elapsed -#> 0.24 0.00 0.06 +#> 0.241 0.004 0.246 ``` ## Multistart @@ -509,7 +509,7 @@ Wall time of a single fit on one core of a Helix node. ggplot(as.data.frame(outframe), aes(elapsed/60)) + geom_histogram(bins = 30) + scale_x_log10() + - theme_dMod() + + theme_dMod2() + labs(x = "wall time per fit [min]", y = "fits") ``` @@ -536,16 +536,16 @@ head(cbind(forward = .fwd$gradient, reverse = .rev$gradient[names(.fwd$gradient) ``` #> forward reverse -#> Rec -0.004120086 -0.004098009 -#> totSTAT1 -0.018542515 -0.018481588 -#> totSTAT2 0.002253855 0.002254689 -#> totIRF9 0.006630967 0.006628104 -#> synthUSP18 0.012820362 0.012662285 -#> synthUSP18mRNAbasal -0.002131137 -0.002148777 -#> hlUSP18mRNA -0.009638635 -0.009529692 -#> degUSP18 -0.013916577 -0.013772130 -#> synthSTAT1mRNAbasal 0.008164342 0.008095536 -#> hlSTAT1mRNA -0.004910047 -0.004872448 +#> Rec -0.004120086 -0.004081095 +#> totSTAT1 -0.018542515 -0.018391053 +#> totSTAT2 0.002253855 0.002271969 +#> totIRF9 0.006630967 0.006614804 +#> synthUSP18 0.012820362 0.012595428 +#> synthUSP18mRNAbasal -0.002131137 -0.002247740 +#> hlUSP18mRNA -0.009638635 -0.009458800 +#> degUSP18 -0.013916577 -0.013701975 +#> synthSTAT1mRNAbasal 0.008164342 0.008155934 +#> hlSTAT1mRNA -0.004910047 -0.004883244 ``` ## Published optimum @@ -618,7 +618,7 @@ ggplot(.model, aes(time, value, color = ifn1, group = condition)) + facet_wrap(~name, scales = "free_y") + coord_cartesian(xlim = c(24, 30)) + .doses(na.value = "black") + - theme_dMod() + + theme_dMod2() + labs(x = "time [h]", y = "log signal [a.u.]", color = "prestimulation\n[U/ml]", title = "5000 U/ml at 24 h, black without prestimulation") ``` @@ -635,7 +635,7 @@ plotCombined(prediction, mydataL, name %in% c("USP18_Cyt", "tSTAT1_Cyt", "pSTAT1_Cyt", "pSTAT2_Cyt"), aesthetics = list(color = "experiment", linetype = "ifn2 > 0"), scales = "free_y") + geom_vline(xintercept = 24, linetype = "dotted") + - scale_color_dMod(limits = c("WT", "USP18kd", "USP18oe")) + + scale_color_dMod2(limits = c("WT", "USP18kd", "USP18oe")) + scale_linetype_manual(values = c(`FALSE` = "solid", `TRUE` = "dashed"), labels = c("no", "yes")) + labs(x = "time [h]", y = "log signal [a.u.]", color = "cell line", linetype = "dose at 24 h") ``` @@ -669,7 +669,7 @@ ggplot(sensitization, aes(dose, ratio)) + geom_rug(data = data.frame(dose = unique(kok$ifn1[.second(kok)])), aes(x = dose), inherit.aes = FALSE, sides = "b", color = "gray50") + scale_x_log10(breaks = 10^(-1:4), labels = scales::label_log()) + - theme_dMod() + + theme_dMod2() + labs(x = "prestimulation at 0 h [U/ml]", y = "ISRE response to 5000 U/ml at 24 h,\nrelative to no prestimulation") ``` diff --git a/examples/kokMSB2020/analysis.R b/examples/kokMSB2020/analysis.R index 3bd7def7..10273f71 100644 --- a/examples/kokMSB2020/analysis.R +++ b/examples/kokMSB2020/analysis.R @@ -360,7 +360,7 @@ table(stopReason = outframe$stopReason, converged = outframe$converged) ggplot(as.data.frame(outframe), aes(elapsed/60)) + geom_histogram(bins = 30) + scale_x_log10() + - theme_dMod() + + theme_dMod2() + labs(x = "wall time per fit [min]", y = "fits") # At the optimum the gradient is small, so the integration error at the @@ -435,7 +435,7 @@ ggplot(.model, aes(time, value, color = ifn1, group = condition)) + facet_wrap(~name, scales = "free_y") + coord_cartesian(xlim = c(24, 30)) + .doses(na.value = "black") + - theme_dMod() + + theme_dMod2() + labs(x = "time [h]", y = "log signal [a.u.]", color = "prestimulation\n[U/ml]", title = "5000 U/ml at 24 h, black without prestimulation") @@ -446,7 +446,7 @@ plotCombined(prediction, mydataL, name %in% c("USP18_Cyt", "tSTAT1_Cyt", "pSTAT1_Cyt", "pSTAT2_Cyt"), aesthetics = list(color = "experiment", linetype = "ifn2 > 0"), scales = "free_y") + geom_vline(xintercept = 24, linetype = "dotted") + - scale_color_dMod(limits = c("WT", "USP18kd", "USP18oe")) + + scale_color_dMod2(limits = c("WT", "USP18kd", "USP18oe")) + scale_linetype_manual(values = c(`FALSE` = "solid", `TRUE` = "dashed"), labels = c("no", "yes")) + labs(x = "time [h]", y = "log signal [a.u.]", color = "cell line", linetype = "dose at 24 h") @@ -474,6 +474,6 @@ ggplot(sensitization, aes(dose, ratio)) + geom_rug(data = data.frame(dose = unique(kok$ifn1[.second(kok)])), aes(x = dose), inherit.aes = FALSE, sides = "b", color = "gray50") + scale_x_log10(breaks = 10^(-1:4), labels = scales::label_log()) + - theme_dMod() + + theme_dMod2() + labs(x = "prestimulation at 0 h [U/ml]", y = "ISRE response to 5000 U/ml at 24 h,\nrelative to no prestimulation") diff --git a/examples/kokMSB2020/figures/unnamed-chunk-15-1.png b/examples/kokMSB2020/figures/unnamed-chunk-15-1.png index 0422195f..652b501f 100644 Binary files a/examples/kokMSB2020/figures/unnamed-chunk-15-1.png and b/examples/kokMSB2020/figures/unnamed-chunk-15-1.png differ diff --git a/examples/kokMSB2020/figures/unnamed-chunk-16-1.png b/examples/kokMSB2020/figures/unnamed-chunk-16-1.png index 2063ff57..92a262b5 100644 Binary files a/examples/kokMSB2020/figures/unnamed-chunk-16-1.png and b/examples/kokMSB2020/figures/unnamed-chunk-16-1.png differ diff --git a/examples/kokMSB2020/figures/unnamed-chunk-19-1.png b/examples/kokMSB2020/figures/unnamed-chunk-19-1.png index a083f43b..8177e76b 100644 Binary files a/examples/kokMSB2020/figures/unnamed-chunk-19-1.png and b/examples/kokMSB2020/figures/unnamed-chunk-19-1.png differ diff --git a/examples/kokMSB2020/figures/unnamed-chunk-20-1.png b/examples/kokMSB2020/figures/unnamed-chunk-20-1.png index f747e53e..4d64bfc6 100644 Binary files a/examples/kokMSB2020/figures/unnamed-chunk-20-1.png and b/examples/kokMSB2020/figures/unnamed-chunk-20-1.png differ diff --git a/examples/kokMSB2020/figures/unnamed-chunk-21-1.png b/examples/kokMSB2020/figures/unnamed-chunk-21-1.png index 02c15aa5..1df3ed0f 100644 Binary files a/examples/kokMSB2020/figures/unnamed-chunk-21-1.png and b/examples/kokMSB2020/figures/unnamed-chunk-21-1.png differ diff --git a/examples/kokMSB2020/figures/unnamed-chunk-22-1.png b/examples/kokMSB2020/figures/unnamed-chunk-22-1.png index 9c3825b3..13f0f30f 100644 Binary files a/examples/kokMSB2020/figures/unnamed-chunk-22-1.png and b/examples/kokMSB2020/figures/unnamed-chunk-22-1.png differ diff --git a/examples/kokMSB2020/figures/unnamed-chunk-23-1.png b/examples/kokMSB2020/figures/unnamed-chunk-23-1.png index a7bd20d3..6c30e9a5 100644 Binary files a/examples/kokMSB2020/figures/unnamed-chunk-23-1.png and b/examples/kokMSB2020/figures/unnamed-chunk-23-1.png differ diff --git a/examples/oppeltNPJSystBiolAppl2018/README.Rmd b/examples/oppeltNPJSystBiolAppl2018/README.Rmd index 2a87678f..7dcddc5c 100644 --- a/examples/oppeltNPJSystBiolAppl2018/README.Rmd +++ b/examples/oppeltNPJSystBiolAppl2018/README.Rmd @@ -1,16 +1,16 @@ # NFκB signaling (Oppelt 2018) -Shows: `Pimpl()`, `symmetryDetection()`, `symmetryReduction()`, `mstrust()`, `trust()`, `profile()`, `constraintStability()`, `randomEffects()`, `msem()`, `exportPEtab()`, `importPEtab()`. +Shows: `Pimpl()`, `symmetryDetection()`, `symmetryReduction()`, `mstrust()`, `trust()`, `trustL1()`, `profile()`, `constraintStability()`, `randomEffects()`, `msem()`, `exportPEtab()`, `importPEtab()`. ```{r, include = FALSE} knitr::read_chunk("plots.R") ``` -NFκB signaling in HepG2 cells after TNFα and the effects of five hepatotoxic compounds, after +NFκB signaling in HepG2 cells after TNFα and the effects of diclofenac (DCF), after Oppelt et al. (2018), npj Syst Biol Appl 4:23. The full model has 38 reactions in cytoplasm and nucleus and starts from a steady state solved by `Pimpl()`; the symmetries are removed by a gauge, and the profiles reduce it to the core model of the publication. 312 measurements of untreated and -stimulated cells determine the model, 444 further ones the effects of the compounds. Data of the +stimulated cells determine the model, 182 further ones under DCF the effects of DCF. Data of the publication; model after Daniel Kaschek's dMod implementation (dkaschek/dMod_Examples, TNFa). The [guide](https://dmodverse.github.io/dMod2/articles/guide-model.html) explains the code. @@ -28,10 +28,12 @@ publication; model after Daniel Kaschek's dMod implementation (dkaschek/dMod_Exa | `profiles.R` | profiles of all parameters, saves `results/profiles.rds` | | `variants.R` | core model of the publication and variants that release one setting, likelihood ratios, saves `results/variants.rds` | | `reduced.R` | the model reduced by the limits the profiles point to | +| `discrete.R` | the discrete symmetry of the reduced model and the chart of a fundamental domain, saves `results/discrete.rds` | +| `fundamental.R` | fit and profiles of the reduced model in the chart of the fundamental domain, saves `results/fundamental.rds` | | `refit.R` | fit and profiles of the reduced model, likelihood ratio, saves `results/reduced.rds` | | `prediction.R` | prediction band of nuclear IκBα, saves `results/prediction.rds` | -| `compounds.R` | the changes the compounds cause, by spike-and-slab random effects, saves `results/compounds.rds` | -| `helix.R` | the expensive runs (multistarts, profiles, optimizers, compounds, the profiles of the reduced model and the prediction profiles) as array jobs of one or two cores per task on the Helix cluster | +| `dcf.R` | the changes by DCF as in the publication, by the L1 scan and by spike-and-slab random effects, saves `results/dcf.rds` and `results/dcfL1.rds` | +| `helix.R` | the expensive runs (multistarts, profiles, optimizers, the L1 scan and spike and slab of DCF, the profiles of the reduced model and the prediction profiles) as array jobs of one or two cores per task on the Helix cluster | | `petab.R` | the model as a PEtab problem with the resting state as a pre-equilibration, written to `results/petab/` and read back | | `plots.R` | figures from the saved results | | `results/` | saved results, each with the md5 of the files it is computed from in the attribute `"stamp"` | @@ -51,7 +53,7 @@ source("profiles.R") source("variants.R") source("refit.R") source("prediction.R") -source("compounds.R") +source("dcf.R") source("petab.R") source("plots.R") ``` @@ -111,16 +113,15 @@ The 95% prediction band of nuclear IκBα, not measured, in the reduced model: ```{r band, echo = FALSE, fig.height = 3.5, eval = predicted} ``` -## Compounds +## DCF ```{r, echo = FALSE, results = "asis"} -grouped <- file.exists("results/compounds.rds") -if (!grouped) cat("> Results pending: `results/compounds.rds` is written by `compounds.R`.\n") +dcfDone <- file.exists("results/dcfL1.rds") +if (!dcfDone) cat("> Results pending: `results/dcfL1.rds` is written by `dcf.R`.\n") ``` -Changes of the rate constants by the five compounds from spike-and-slab random effects; color: -mode on the log scale, opacity: evidence against no change: +The differences by DCF over the strength of the L1 penalty, as in Fig. 2a of the publication; in +color those kept at the selected strength (dashed): -```{r changes, echo = FALSE, fig.height = 5, eval = grouped} +```{r dcfpaths, echo = FALSE, fig.height = 3.5, eval = dcfDone} ``` - diff --git a/examples/oppeltNPJSystBiolAppl2018/README.md b/examples/oppeltNPJSystBiolAppl2018/README.md index 8af289a1..227397bf 100644 --- a/examples/oppeltNPJSystBiolAppl2018/README.md +++ b/examples/oppeltNPJSystBiolAppl2018/README.md @@ -1,14 +1,14 @@ # NFκB signaling (Oppelt 2018) -Shows: `Pimpl()`, `symmetryDetection()`, `symmetryReduction()`, `mstrust()`, `trust()`, `profile()`, `constraintStability()`, `randomEffects()`, `msem()`, `exportPEtab()`, `importPEtab()`. +Shows: `Pimpl()`, `symmetryDetection()`, `symmetryReduction()`, `mstrust()`, `trust()`, `trustL1()`, `profile()`, `constraintStability()`, `randomEffects()`, `msem()`, `exportPEtab()`, `importPEtab()`. -NFκB signaling in HepG2 cells after TNFα and the effects of five hepatotoxic compounds, after +NFκB signaling in HepG2 cells after TNFα and the effects of diclofenac (DCF), after Oppelt et al. (2018), npj Syst Biol Appl 4:23. The full model has 38 reactions in cytoplasm and nucleus and starts from a steady state solved by `Pimpl()`; the symmetries are removed by a gauge, and the profiles reduce it to the core model of the publication. 312 measurements of untreated and -stimulated cells determine the model, 444 further ones the effects of the compounds. Data of the +stimulated cells determine the model, 182 further ones under DCF the effects of DCF. Data of the publication; model after Daniel Kaschek's dMod implementation (dkaschek/dMod_Examples, TNFa). The [guide](https://dmodverse.github.io/dMod2/articles/guide-model.html) explains the code. @@ -26,10 +26,12 @@ publication; model after Daniel Kaschek's dMod implementation (dkaschek/dMod_Exa | `profiles.R` | profiles of all parameters, saves `results/profiles.rds` | | `variants.R` | core model of the publication and variants that release one setting, likelihood ratios, saves `results/variants.rds` | | `reduced.R` | the model reduced by the limits the profiles point to | +| `discrete.R` | the discrete symmetry of the reduced model and the chart of a fundamental domain, saves `results/discrete.rds` | +| `fundamental.R` | fit and profiles of the reduced model in the chart of the fundamental domain, saves `results/fundamental.rds` | | `refit.R` | fit and profiles of the reduced model, likelihood ratio, saves `results/reduced.rds` | | `prediction.R` | prediction band of nuclear IκBα, saves `results/prediction.rds` | -| `compounds.R` | the changes the compounds cause, by spike-and-slab random effects, saves `results/compounds.rds` | -| `helix.R` | the expensive runs (multistarts, profiles, optimizers, compounds, the profiles of the reduced model and the prediction profiles) as array jobs of one or two cores per task on the Helix cluster | +| `dcf.R` | the changes by DCF as in the publication, by the L1 scan and by spike-and-slab random effects, saves `results/dcf.rds` and `results/dcfL1.rds` | +| `helix.R` | the expensive runs (multistarts, profiles, optimizers, the L1 scan and spike and slab of DCF, the profiles of the reduced model and the prediction profiles) as array jobs of one or two cores per task on the Helix cluster | | `petab.R` | the model as a PEtab problem with the resting state as a pre-equilibration, written to `results/petab/` and read back | | `plots.R` | figures from the saved results | | `results/` | saved results, each with the md5 of the files it is computed from in the attribute `"stamp"` | @@ -49,7 +51,7 @@ source("profiles.R") source("variants.R") source("refit.R") source("prediction.R") -source("compounds.R") +source("dcf.R") source("petab.R") source("plots.R") ``` @@ -63,7 +65,7 @@ it reads `results/` and simulates the compiled models. ## Fit -200 fits, 180 converged. The best value is -488.675, reached by 9 fits within 0.1. +200 fits, 187 converged. The best value is -488.677, reached by 10 fits within 0.1. @@ -88,13 +90,12 @@ The 95% prediction band of nuclear IκBα, not measured, in the reduced model: -## Compounds +## DCF -Changes of the rate constants by the five compounds from spike-and-slab random effects; color: -mode on the log scale, opacity: evidence against no change: +The differences by DCF over the strength of the L1 penalty, as in Fig. 2a of the publication; in +color those kept at the selected strength (dashed): - - + diff --git a/examples/oppeltNPJSystBiolAppl2018/compounds.R b/examples/oppeltNPJSystBiolAppl2018/compounds.R deleted file mode 100644 index d3eedb38..00000000 --- a/examples/oppeltNPJSystBiolAppl2018/compounds.R +++ /dev/null @@ -1,99 +0,0 @@ -# The DILI compounds as a grouping of the reduced model: which rates each compound changes, by -# spike-and-slab random effects. Saves results/compounds.rds. - -# reduced.R, unless it ran in this session -if (!exists("objReduced")) source("reduced.R") - -## ---- compounddata -# HepG2 cells: the first blot scale with and without TNFα and DCF, the third with TNFα and the -# other four compounds; a condition without a compound belongs to no group -cells <- subset(raw, cell == "HepG2" & (scale == 1 | (scale == 3 & treatment == "TNF")) & - (scale == 3 | compound %in% c("no", "DCF"))) -cells$compound[cells$compound == "no"] <- NA -cells$blot <- paste0("blot", cells$scale) -cells$condition <- with(cells, paste(ifelse(treatment == "TNF", "TNF", "control"), - ifelse(is.na(compound), "none", compound), blot, sep = "_")) -dataCompounds <- as.datalist(cells[c("name", "time", "value", "sigma", "condition", "treatment", - "compound", "blot")], - splitBy = "condition", keepCovariates = c("treatment", "compound", "blot")) - - -## ---- compoundmodel -# the reduced model with second derivatives forward over reverse, which the mixed-effects fit uses; -# the resting state of reduced.R holds for every value of the rate constants, so a compound -# changes the dynamics from the time of TNFα on -dm <- c("forward", "reverse", "forward-reverse") -candidates <- setdiff(getParameters(odemodel(reactionsReduced, compile = FALSE)), - c(reactionsReduced$states, names(gauge), names(fixedReduced), "dose_TNF")) -modelCompounds <- odemodel(reactionsReduced, events = events, modelname = "oppelt_cmp_ode", - compile = FALSE, derivMode = dm) -xCompounds <- Xs(modelCompounds, options = list(atol = 1e-10, rtol = 1e-8)) -gCompounds <- Y(observablesReduced, xCompounds, modelname = "oppelt_cmp_obs", compile = FALSE, - derivMode = dm) -eCompounds <- Y(errors, gCompounds, modelname = "oppelt_cmp_err", compile = FALSE, derivMode = dm) - - -## ---- compoundeffects -# every rate constant the reduced model estimates, with a spike-and-slab random effect over the -# compounds; the blots of the third scale with scales and offsets of their own -blot3 <- setdiff(c("s_IkBa", "off_IkBa", "s_pIkBa", "off_pIkBa", "s_pIKK", "off_pIKK", "s_pNFkB", - "off_pNFkB"), names(fixedReduced)) -trafoCompounds <- eqnvec() |> - define("x <- x", x = setdiff(getParameters(xCompounds, gCompounds, eCompounds), - reactionsReduced$states)) |> - define("x <- y", x = names(fixedReduced), y = fixedReduced) |> - define("x <- y", x = names(resting), y = resting) |> - insert("x <- exp(x)", x = .currentSymbols) |> - define("TNF <- 0") |> - branch(covariates(dataCompounds)) |> - define("dose_TNF <- 0", conditionMatch = "^control") |> - define("dose_TNF <- 1", conditionMatch = "^TNF") |> - insert("x <- y", x = blot3, y = paste0(blot3, "_blot3"), conditionMatch = "blot3$") |> - insert(x ~ 1 + (1 | gr(compound, dist = spikeSlab())), x = candidates) -pCompounds <- P(trafoCompounds, method = "explicit", modelname = "oppelt_cmp_par", compile = FALSE, - derivMode = dm) - -compile(gCompounds, xCompounds, pCompounds, eCompounds, output = "oppelt_cmp", - cores = getOption("dMod2.cores")) -prdCompounds <- gCompounds * xCompounds * pCompounds -objCompounds <- normL2(dataCompounds, prdCompounds, eCompounds) - - -## ---- compoundfit -# the fixed effects from the reduced model at the optimum, those of the third blot from the first; -# the effects of the compounds start at 0, the hyperparameters at a few changes of moderate size -bestReduced <- as.parvec(readRDS("results/reduced.rds")$fits) -random <- randomEffects(pCompounds) -population <- setdiff(getParameters(prdCompounds), c(unlist(random$etas), names(gaugeReduced))) -init <- bestReduced[intersect(population, names(bestReduced))] -init[paste0(blot3, "_blot3")] <- bestReduced[blot3] -init[c("prob_compound", "tau_compound")] <- c(0.2, 0.5) -# the prior of model.R, that of the first blot also for the third -third <- function(v) c(v, setNames(v[blot3], paste0(blot3, "_blot3")))[population] -priorCompounds <- constraintL2(third(muReduced), sigma = third(sigmaReduced)) -# the spread of the starts: per fixed effect half the 68 % profile interval of the reduced model, -# between 0.1 and 0.5 on the log scale, 0.5 where the profile is open and for the hyperparameters -ci <- confint(readRDS("results/reduced.rds")$profiles, level = 0.68) -width <- setNames(pmin(pmax((ci$upper - ci$lower) / 2, 0.1), 0.5), ci$name) -width <- c(width, setNames(width[intersect(blot3, names(width))], paste0(intersect(blot3, names(width)), "_blot3"))) -sdStart <- setNames(rep(0.5, length(init)), names(init)) -known <- intersect(names(sdStart), names(width)[!is.na(width)]) -sdStart[known] <- width[known] -# 200 starts: the one above and 199 moved by sdStart, the probability of a change on the logit -# scale and the spread by a factor; a start whose fit fails is drawn again; every start runs to the -# end, with up to 1000 iterations of the trust region, one core each -set.seed(3) -fitCompounds <- msem(objCompounds + priorCompounds, random, init, fixed = gaugeReduced, - control = list(sparseFit = list(maxOuter = 1000, trustControl = list(tolControl = tolerances))), - fits = 200, sd = sdStart, keepFits = TRUE, - cores = getOption("dMod2.cores")) - -## ---- compoundsave -# the best fit with the table and the fits of all starts, saved without the model, which an -# evaluation at the estimates restores -saved <- fitCompounds -saved[c("design", "prdfn", "errfn", "data")] <- NULL -# the md5 of the files the result is computed from, which the guide checks on reading -sources <- c("model.R", "reduced.R", "compounds.R", "data/oppelt2018.csv", "results/reduced.rds") -attr(saved, "stamp") <- list(md5 = tools::md5sum(sources), dMod2 = packageVersion("dMod2")) -saveRDS(saved, "results/compounds.rds") diff --git a/examples/oppeltNPJSystBiolAppl2018/dcf.R b/examples/oppeltNPJSystBiolAppl2018/dcf.R new file mode 100644 index 00000000..3c5505ff --- /dev/null +++ b/examples/oppeltNPJSystBiolAppl2018/dcf.R @@ -0,0 +1,243 @@ +# The problem of the publication: TNFα-stimulated HepG2 cells of the first blot scale with and +# without DCF, every rate constant of the reduced model changed by DCF. The changes selected by +# spike-and-slab random effects and by an L1 scan as in the publication. Saves results/dcf.rds and +# results/dcfL1.rds. + +# reduced.R, unless it ran in this session +if (!exists("objReduced")) source("reduced.R") + +## ---- dcfdata +# the TNFα-stimulated cells of the first blot scale, without compound and with DCF +cellsDCF <- subset(raw, cell == "HepG2" & scale == 1 & treatment == "TNF" & compound %in% c("no", "DCF")) +cellsDCF$compound[cellsDCF$compound == "no"] <- NA +cellsDCF$condition <- ifelse(is.na(cellsDCF$compound), "TNF_none", "TNF_DCF") +dataDCF <- as.datalist(cellsDCF[c("name", "time", "value", "sigma", "condition", "treatment", "compound")], + splitBy = "condition", keepCovariates = c("treatment", "compound")) + +## ---- dcfmodel +# every rate constant the publication does not fix has a change by DCF, 24 as in the publication, +# a spike-and-slab random effect over the compound; for the spike and slab without the four rate +# constants of the gauge, whose change equals that of a partner; second derivatives forward over +# reverse for em() +ratesDCF <- setdiff(getParameters(odemodel(reactionsReduced, compile = FALSE)), + c(reactionsReduced$states, names(fixedReduced), "Vnuc", "TNF", "dose_TNF")) +dm <- c("forward", "reverse", "forward-reverse") +modelDCF <- odemodel(reactionsReduced, events = events, modelname = "oppelt_dcf_ode", compile = FALSE, + derivMode = dm) +# solves without sensitivities at atol 1e-12: at atol 1e-10 they can leave the positive orthant, where +# the complex formation is unstable; those with sensitivities hold at 1e-10 +xDCF <- Xs(modelDCF, options = list(atol = 1e-12, rtol = 1e-8), optionsSens = list(atol = 1e-10)) +gDCF <- Y(observablesReduced, xDCF, modelname = "oppelt_dcf_obs", compile = FALSE, derivMode = dm) +eDCF <- Y(errors, gDCF, modelname = "oppelt_dcf_err", compile = FALSE, derivMode = dm) +trafoBase <- eqnvec() |> + define("x <- x", x = setdiff(getParameters(xDCF, gDCF, eDCF), reactionsReduced$states)) |> + define("x <- y", x = names(fixedReduced), y = fixedReduced) |> + define("x <- y", x = names(resting), y = resting) |> + insert("x <- exp(x)", x = .currentSymbols) |> + define("TNF <- 0") |> + branch(covariates(dataDCF)) |> + define("dose_TNF <- 1") +ratesSS <- setdiff(ratesDCF, names(gauge)) +pDCF <- P(insert(trafoBase, x ~ 1 + (1 | gr(compound, dist = spikeSlab())), x = ratesDCF), + method = "explicit", modelname = "oppelt_dcf_par", compile = FALSE, derivMode = dm) +pSS <- P(insert(trafoBase, x ~ 1 + (1 | gr(compound, dist = spikeSlab())), x = ratesSS), + method = "explicit", modelname = "oppelt_dcfss_par", compile = FALSE, derivMode = dm) +compile(gDCF, xDCF, pDCF, pSS, eDCF, output = "oppelt_dcf", cores = getOption("dMod2.cores")) +prdDCF <- gDCF * xDCF * pDCF + +## ---- dcfobjective +# the prior of reduced.R on the rate constants and observation parameters; the changes start at 0 +randomDCF <- randomEffects(pDCF) +changesDCF <- unique(na.omit(unlist(randomDCF$etas))) +populationDCF <- setdiff(getParameters(prdDCF), c(changesDCF, names(gaugeReduced))) +priorDCF <- constraintL2(muReduced[populationDCF], sigma = sigmaReduced[populationDCF]) +objDCF <- normL2(dataDCF, prdDCF, eDCF) + priorDCF +randomSS <- randomEffects(pSS) +objSS <- normL2(dataDCF, gDCF * xDCF * pSS, eDCF) + priorDCF +bestReduced <- as.parvec(readRDS("results/reduced.rds")$fits) +initDCF <- bestReduced[populationDCF] + +## ---- dcfspikeslab +# the changes as spike-and-slab random effects: 1000 starts of msem(), the population parameters +# drawn around the fit of the reduced model with sd 1 on the log scale, the probability of a change +# starting at 0.2 and the spread at 0.5 +initSS <- c(initDCF, prob_compound = 0.2, tau_compound = 0.5) +set.seed(3) +fitDCF <- msem(objSS, randomSS, initSS, fixed = gaugeReduced, + control = list(sparseFit = list(trustControl = list(tolControl = tolerances))), + fits = 1000, sd = 1, cores = getOption("dMod2.cores")) + +## ---- dcfspikeslabmore +# 200 more starts around the best fit, sd 1 as above: the waterfall of the optimum +set.seed(4) +moreDCF <- msem(objSS, randomSS, fitDCF$argument, fixed = gaugeReduced, + control = list(sparseFit = list(trustControl = list(tolControl = tolerances))), + fits = 200, sd = 1, cores = getOption("dMod2.cores")) +starts <- rbind(cbind(fitDCF$multistart, round = 1L), cbind(moreDCF$multistart, round = 2L)) +if (moreDCF$value < fitDCF$value) fitDCF <- moreDCF +fitDCF$multistart <- starts + +## ---- dcfspikeslabsave +# saved without the model, which an evaluation at the estimates restores +saved <- fitDCF +saved[c("design", "prdfn", "errfn", "data")] <- NULL +sources <- c("model.R", "reduced.R", "dcf.R", "data/oppelt2018.csv", "results/reduced.rds") +attr(saved, "stamp") <- list(md5 = tools::md5sum(sources), dMod2 = packageVersion("dMod2")) +saveRDS(saved, "results/dcf.rds") + +## ---- dcfL1 +# The L1 scan over the 20 candidates of the spike and slab, the changes of the four partners of the +# gauge at 0: the penalty lambda |eta| on every candidate, lambda = 0, 31 values from 1e-2 to 1e4 +# evenly on the log scale and four more between 10^0.8 and 10, per lambda 1000 starts, the +# population parameters drawn around the fit of the reduced model with sd 1, the changes at 0, the +# first start the fit itself +zeroDCF <- setNames(numeric(length(changesDCF)), changesDCF) +changesL1 <- paste0("eta_", ratesSS, "_DCF") +offL1 <- setdiff(changesDCF, changesL1) +stopifnot(all(changesL1 %in% changesDCF)) +lambdasDCF <- sort(c(0, 10^seq(-2, 4, by = 0.2), 10^seq(0.84, 0.96, by = 0.04))) +startsL1 <- msParframe(c(initDCF, zeroDCF), n = 1000, seed = 12, + sd = c(setNames(rep(1, length(initDCF)), names(initDCF)), zeroDCF)) +startL1 <- function(i) unlist(startsL1[i, c(names(initDCF), changesL1)]) +# a start vector with the population parameters and candidates of `argument`, the others at the start +fullStart <- function(argument) { + start <- c(initDCF, zeroDCF[changesL1]) + shared <- intersect(names(argument), names(start)) + start[shared] <- argument[shared] + start +} +# the penalized fit of a task, with -2 log L without the penalty +penalizedDCF <- function(task) { + fit <- try(trustL1(objDCF, task$start, mu = zeroDCF[changesL1], lambda = task$lambda, rinit = 1, + rmax = 10, iterlim = 1000, fixed = c(gaugeReduced, zeroDCF[offL1]), + tolControl = tolerances), silent = TRUE) + if (inherits(fit, "try-error")) return(NULL) + list(lambda = task$lambda, argument = fit$argument, + value = objDCF(c(fit$argument, zeroDCF[offL1]), fixed = gaugeReduced, deriv = FALSE)$value, + converged = fit$converged) +} +# the candidates of a set fitted without penalty, the other changes at 0 +refitDCF <- function(task) { + off <- setdiff(changesDCF, task$set) + start <- task$start[setdiff(names(task$start), off)] + fit <- try(trust(objDCF, start, rinit = 1, rmax = 10, iterlim = 1000, + fixed = c(gaugeReduced, zeroDCF[off]), tolControl = tolerances), silent = TRUE) + if (inherits(fit, "try-error")) return(NULL) + list(set = task$set, argument = fit$argument, value = fit$value, converged = fit$converged) +} +# the penalized objective of every fit in penalizedFits at `x` +penalizedAt <- function(x) vapply(penalizedFits, function(r) r$value + x * sum(abs(r$argument[changesL1])), 0) +# the fits of a list of tasks, one per task; helix.R runs them on the cluster instead +fitTasks <- function(tasks, fn) + Filter(Negate(is.null), parallel::mclapply(tasks, fn, mc.cores = getOption("dMod2.cores"), + mc.preschedule = FALSE)) + +## ---- dcfL1fit +tasksL1 <- expand.grid(start = seq_len(nrow(startsL1)), lambda = lambdasDCF) +penalizedFits <- fitTasks(lapply(seq_len(nrow(tasksL1)), function(i) + list(start = startL1(tasksL1$start[i]), lambda = tasksL1$lambda[i])), penalizedDCF) + +## ---- dcfL1continue +# every lambda also from the five best fits of the other lambdas, evaluated at it, and from the +# five best of the lambda itself, until no lambda improves by more than 0.01 +bestAt <- function() vapply(lambdasDCF, function(x) { + own <- vapply(penalizedFits, `[[`, 0, "lambda") == x + min(penalizedAt(x)[own]) +}, 0) +repeat { + before <- bestAt() + lambdaOf <- vapply(penalizedFits, `[[`, 0, "lambda") + tasks <- unlist(lapply(lambdasDCF, function(x) { + value <- penalizedAt(x) + other <- which(lambdaOf != x); own <- which(lambdaOf == x) + pick <- c(other[order(value[other])][1:5], own[order(value[own])][1:5]) + lapply(pick, function(i) list(start = penalizedFits[[i]]$argument[c(names(initDCF), changesL1)], lambda = x)) + }), recursive = FALSE) + penalizedFits <- c(penalizedFits, fitTasks(tasks, penalizedDCF)) + if (all(before - bestAt() <= 0.01)) break +} + +## ---- dcfL1sets +# per lambda the best penalized fit and the candidates it keeps; the sets refitted without penalty: +# all candidates, those of every lambda, the seven of the publication (Table S7 of the supplement, +# estimates and 95 % intervals) and those the spike and slab selects +lambdaOf <- vapply(penalizedFits, `[[`, 0, "lambda") +bestDCF <- lapply(lambdasDCF, function(x) { + i <- which(lambdaOf == x) + penalizedFits[[i[which.min(penalizedAt(x)[i])]]] +}) +names(bestDCF) <- lambdasDCF +keptDCF <- lapply(bestDCF, function(r) changesL1[abs(r$argument[changesL1]) > 1e-8]) +publicationDCF <- data.frame( + rate = c("act_Ikk_by_TNF", "trigger_iIkk", "act_pIkk", "act_Ikb_by_Ikk", "prod_mIkb_by_nNfk", + "degrad_mIkb", "shuttle_RnaA20"), + value = c(-0.72, 1.56, 0.91, -0.94, -0.83, -1.77, -0.96), + lower = c(-0.98, 1.10, 0.57, -1.66, -0.94, -2.06, -1.68), + upper = c(-0.46, 2.05, 1.27, -0.45, -0.73, -1.50, -0.52)) +fitSS <- readRDS("results/dcf.rds") +key <- function(set) paste(sort(set), collapse = " ") +setsDCF <- c(list(all = changesL1, + publication = paste0("eta_", publicationDCF$rate, "_DCF"), + spikeSlab = paste0("eta_", fitSS$random$eta[fitSS$random$p0 < 0.5], "_DCF")), + keptDCF[lengths(keptDCF) > 0]) +setsDCF <- setsDCF[!duplicated(vapply(setsDCF, key, ""))] + +## ---- dcfL1refit +# per set the best penalized fit of every lambda and 300 starts around the fit of the reduced model +# (sd 1, the changes at 0); where fewer than five fits reach the best value within 0.1, 300 more, +# then 1000 more and the best refit of every set +drawn <- function(n, seed) { + d <- msParframe(c(initDCF, zeroDCF[changesL1]), n = n, seed = seed, + sd = c(setNames(rep(1, length(initDCF)), names(initDCF)), zeroDCF[changesL1])) + lapply(seq_len(nrow(d)), function(i) unlist(d[i, c(names(initDCF), changesL1)])) +} +refitsOf <- function(set) Filter(function(r) identical(key(r$set), key(set)), refitFits) +bestRefit <- function(set) { f <- refitsOf(set); f[[which.min(vapply(f, `[[`, 0, "value"))]] } +reached <- function(set) { v <- vapply(refitsOf(set), `[[`, 0, "value"); sum(v < min(v) + 0.1) } +refitFits <- list() +open <- seq_along(setsDCF) +for (round in 1:3) { + starts <- switch(round, + c(lapply(bestDCF, function(r) fullStart(r$argument)), drawn(300, 21)), + drawn(300, 22), + c(lapply(setsDCF, function(set) fullStart(bestRefit(set)$argument)), drawn(1000, 30))) + tasks <- unlist(lapply(open, function(k) lapply(starts, function(s) list(set = setsDCF[[k]], start = s))), + recursive = FALSE) + refitFits <- c(refitFits, fitTasks(tasks, refitDCF)) + open <- which(vapply(setsDCF, reached, 0L) < 5L) + if (!length(open)) break +} + +## ---- dcfL1select +# the likelihood ratio test of the set of each lambda against all candidates, the selection that +# of the largest lambda not worse at p < 0.001, the threshold of the publication +valueOf <- function(set) bestRefit(set)$value +scanDCF <- data.frame(lambda = lambdasDCF, changes = lengths(keptDCF), + data = vapply(bestDCF, `[[`, 0, "value"), + penalty = lambdasDCF * vapply(bestDCF, function(r) sum(abs(r$argument[changesL1])), 0), + refit = vapply(keptDCF, function(set) if (length(set)) valueOf(set) else NA_real_, 0), + row.names = NULL) +scanDCF$p <- pchisq(scanDCF$refit - valueOf(changesL1), df = length(changesL1) - scanDCF$changes, + lower.tail = FALSE) +scanDCF$p[scanDCF$changes == length(changesL1)] <- 1 +lambdaDCF <- max(scanDCF$lambda[!is.na(scanDCF$p) & scanDCF$p >= 0.001]) +selectedL1 <- keptDCF[[as.character(lambdaDCF)]] +pathDCF <- t(vapply(bestDCF, function(r) r$argument[changesL1], zeroDCF[changesL1])) + +## ---- dcfL1save +# the penalized fits and refits as values for the waterfalls, the best ones in full +dcfL1 <- list(scan = scanDCF, path = pathDCF, lambda = lambdaDCF, selected = selectedL1, + penalizedSelected = bestDCF[[as.character(lambdaDCF)]]$argument, + refitSelected = bestRefit(selectedL1), publication = publicationDCF, + refitPublication = bestRefit(setsDCF$publication), + refitSpikeSlab = bestRefit(setsDCF$spikeSlab), all = bestRefit(changesL1), + sets = setsDCF, refits = lapply(setsDCF, bestRefit), + penalized = data.frame(lambda = lambdaOf, value = vapply(penalizedFits, `[[`, 0, "value"), + L1 = vapply(penalizedFits, function(r) sum(abs(r$argument[changesL1])), 0), + converged = vapply(penalizedFits, `[[`, TRUE, "converged")), + refitValues = data.frame(set = vapply(refitFits, function(r) key(r$set), ""), + value = vapply(refitFits, `[[`, 0, "value"))) +sources <- c("model.R", "reduced.R", "dcf.R", "data/oppelt2018.csv", "results/reduced.rds", + "results/dcf.rds") +attr(dcfL1, "stamp") <- list(md5 = tools::md5sum(sources), dMod2 = packageVersion("dMod2")) +saveRDS(dcfL1, "results/dcfL1.rds") diff --git a/examples/oppeltNPJSystBiolAppl2018/discrete.R b/examples/oppeltNPJSystBiolAppl2018/discrete.R new file mode 100644 index 00000000..e716a339 --- /dev/null +++ b/examples/oppeltNPJSystBiolAppl2018/discrete.R @@ -0,0 +1,30 @@ +# Discrete symmetries of the reduced model of reduced.R, by symident: isolated parameter values with +# the output of a given one, and the chart of one side of the fixed set. Saves results/discrete.rds, +# which the guide reads. + +# reduced.R, unless it ran in this session +if (!exists("objReduced")) source("reduced.R") + +## ---- discrete +# the settings of symmetries.R; the resting state and the fixed values of reduced.R enter as +# initial values and parameters of the detection +doses <- data.frame(dose_TNF = c(0, 1), row.names = c("control", "TNF")) +unbleachedReduced <- setNames(eqnvec(sub(" - tau_.*$", "", observablesReduced)), + names(observablesReduced)) +known <- c(fixedReduced[names(fixedReduced) != "tau_A20GFP"], resting[names(resting) != "TNF"]) +discrete <- symmetryDetection(reactionsReduced, unbleachedReduced, + trafo = setNames(as.character(known), names(known)), events = events, + forcings = "TNF", conditions = doses, mode = "global", + cores = getOption("dMod2.cores")) + +## ---- fundamental +# the side degrad_A20 < degrad_RnaA20 of the fixed set, in a chart of positive coordinates +fundamental <- symmetryReduction(discrete, branch = "degrad_A20 < degrad_RnaA20") + +## ---- discretesave +dir.create("results", showWarnings = FALSE) +# the md5 of the files the result is computed from, which the guide checks on reading +sources <- c("model.R", "reduced.R", "discrete.R") +saved <- list(discrete = discrete, fundamental = fundamental) +attr(saved, "stamp") <- list(md5 = tools::md5sum(sources), dMod2 = packageVersion("dMod2")) +saveRDS(saved, "results/discrete.rds") diff --git a/examples/oppeltNPJSystBiolAppl2018/figures/band-1.png b/examples/oppeltNPJSystBiolAppl2018/figures/band-1.png index a6570522..7849f51c 100644 Binary files a/examples/oppeltNPJSystBiolAppl2018/figures/band-1.png and b/examples/oppeltNPJSystBiolAppl2018/figures/band-1.png differ diff --git a/examples/oppeltNPJSystBiolAppl2018/figures/changes-1.png b/examples/oppeltNPJSystBiolAppl2018/figures/changes-1.png deleted file mode 100644 index 84338a96..00000000 Binary files a/examples/oppeltNPJSystBiolAppl2018/figures/changes-1.png and /dev/null differ diff --git a/examples/oppeltNPJSystBiolAppl2018/figures/dcfpaths-1.png b/examples/oppeltNPJSystBiolAppl2018/figures/dcfpaths-1.png new file mode 100644 index 00000000..0dafdbef Binary files /dev/null and b/examples/oppeltNPJSystBiolAppl2018/figures/dcfpaths-1.png differ diff --git a/examples/oppeltNPJSystBiolAppl2018/figures/prediction-1.png b/examples/oppeltNPJSystBiolAppl2018/figures/prediction-1.png index 5367c062..27fdf865 100644 Binary files a/examples/oppeltNPJSystBiolAppl2018/figures/prediction-1.png and b/examples/oppeltNPJSystBiolAppl2018/figures/prediction-1.png differ diff --git a/examples/oppeltNPJSystBiolAppl2018/figures/waterfall-1.png b/examples/oppeltNPJSystBiolAppl2018/figures/waterfall-1.png index d8d5cfc8..768fa4da 100644 Binary files a/examples/oppeltNPJSystBiolAppl2018/figures/waterfall-1.png and b/examples/oppeltNPJSystBiolAppl2018/figures/waterfall-1.png differ diff --git a/examples/oppeltNPJSystBiolAppl2018/fundamental.R b/examples/oppeltNPJSystBiolAppl2018/fundamental.R new file mode 100644 index 00000000..21c00a2b --- /dev/null +++ b/examples/oppeltNPJSystBiolAppl2018/fundamental.R @@ -0,0 +1,75 @@ +# The reduced model of reduced.R in the chart of the fundamental domain degrad_A20 < degrad_RnaA20 +# of the discrete symmetry of discrete.R: one fit from the best fit of refit.R and the profiles of +# all parameters. Saves results/fundamental.rds, which the guide reads. + +# reduced.R, unless it ran in this session +if (!exists("objReduced")) source("reduced.R") + +## ---- fundamentaltrafo +# the parameters of reduced.R with degrad_RnaA20 above degrad_A20 by exp(delta_RnaA20), the chart +# of symmetryReduction(branch = "degrad_A20 < degrad_RnaA20"); ODE, observables and errors of +# reduced.R +trafoFundamental <- eqnvec() |> + define("x <- x", x = setdiff(getParameters(xReduced, gReduced, eReduced), + reactionsReduced$states)) |> + define("x <- y", x = names(fixedReduced), y = fixedReduced) |> + define("x <- y", x = names(resting), y = resting) |> + define("degrad_RnaA20 <- degrad_A20 + delta_RnaA20") |> + insert("x <- exp(x)", x = .currentSymbols) |> + define("TNF <- 0") |> + branch(covariates(data)) |> + define("dose_TNF <- 0", conditionMatch = "control") |> + define("dose_TNF <- 1", conditionMatch = "TNF") +pFundamental <- P(trafoFundamental, modelname = "oppelt_fund_par", compile = FALSE) +compile(pFundamental, output = "oppelt_fund", cores = getOption("dMod2.cores")) +prdFundamental <- gReduced * xReduced * pFundamental + +## ---- fundamentalobjective +# the prior of reduced.R; the difference of the two rates with the prior of degrad_RnaA20 +outerFundamental <- getParameters(prdFundamental) +muFundamental <- c(muReduced, delta_RnaA20 = muReduced[["degrad_RnaA20"]])[outerFundamental] +sigmaFundamental <- c(sigmaReduced, + delta_RnaA20 = sigmaReduced[["degrad_RnaA20"]])[outerFundamental] +objFundamental <- normL2(data, prdFundamental, eReduced) + + constraintL2(muFundamental, sigma = sigmaFundamental) + +## ---- fundamentalfit +# the best fit of refit.R, on the side degrad_A20 < degrad_RnaA20, in the chart +bestReduced <- as.parvec(readRDS("results/reduced.rds")$fits) +ordered <- sort(exp(unclass(bestReduced)[c("degrad_A20", "degrad_RnaA20")])) +start <- unclass(bestReduced)[setdiff(names(bestReduced), "degrad_RnaA20")] +start[c("degrad_A20", "delta_RnaA20")] <- log(c(ordered[[1]], ordered[[2]] - ordered[[1]])) +fitFundamental <- trust(objFundamental, start[setdiff(outerFundamental, names(gaugeReduced))], + fixed = gaugeReduced, rinit = 0.1, rmax = 10, iterlim = 1000, + tolControl = tolerances) +# the data terms of the best fit of refit.R, of the same point in the chart, and of the fit +dataFundamental <- normL2(data, prdFundamental, eReduced) +dataTermReduced <- normL2(data, prdReduced, eReduced) +dataTerms <- c(reduced = dataTermReduced(bestReduced, fixed = gaugeReduced)$value, + chart = dataFundamental(start, fixed = gaugeReduced)$value, + fit = dataFundamental(fitFundamental$argument, fixed = gaugeReduced)$value) + +## ---- fundamentalprofileprior +# the prior of the profiles of refit.R, standard deviation 20 at the fit, and one fit from there +objFundamentalProfile <- normL2(data, prdFundamental, eReduced) + + constraintL2(fitFundamental$argument, sigma = 20) +fitFundamentalProfile <- trust(objFundamentalProfile, fitFundamental$argument, fixed = gaugeReduced, + rinit = 0.1, rmax = 10, iterlim = 1000, tolControl = tolerances) +bestFundamentalProfile <- fitFundamentalProfile$argument + +## ---- fundamentalprofiles +# the settings of refit.R +profilesFundamental <- profile(objFundamentalProfile, bestFundamentalProfile, + names(bestFundamentalProfile), fixed = gaugeReduced, + limits = c(lower = -7, upper = 7), stepControl = list(stop = "data"), + algoControl = list(reoptimize = TRUE), + optControl = list(iterlim = 100, tolControl = tolerances), + cores = getOption("dMod2.cores")) + +## ---- fundamentalsave +# the md5 of the files the result is computed from, which the guide checks on reading +sources <- c("model.R", "reduced.R", "fundamental.R", "data/oppelt2018.csv") +saved <- list(fit = fitFundamental, dataTerms = dataTerms, fitProfile = fitFundamentalProfile, + profiles = profilesFundamental) +attr(saved, "stamp") <- list(md5 = tools::md5sum(sources), dMod2 = packageVersion("dMod2")) +saveRDS(saved, "results/fundamental.rds") diff --git a/examples/oppeltNPJSystBiolAppl2018/helix.R b/examples/oppeltNPJSystBiolAppl2018/helix.R index c6fcd359..a343bf41 100644 --- a/examples/oppeltNPJSystBiolAppl2018/helix.R +++ b/examples/oppeltNPJSystBiolAppl2018/helix.R @@ -2,10 +2,10 @@ # with one or two cores each, which start sooner than a task on many cores. The models compile on # this machine; distributedComputing() copies the sources and builds them once on Helix against # the cppDE installed there. Needs an account on Helix under the host alias helix of ~/.ssh/config, -# with dMod2 and cppDE installed there in the versions of the machine that submits. Run from the -# project directory, step by step; a job folder in the working directory means the job was -# submitted already, and the call recovers it. onefit.R, sensitivities.R and symmetries.R run on -# this machine. +# with dMod2 and cppDE installed there in ~/R/lib-devel4, in the versions of the machine that +# submits. Run from the project directory, step by step; a job folder in the working directory +# means the job was submitted already, and the call recovers it. onefit.R, sensitivities.R and +# symmetries.R run on this machine. library(dMod2) # the job script dMod2 ships for Helix, set up once @@ -38,7 +38,7 @@ fitsJob <- distributedComputing({ mstrust(obj, mu[free], fixed = gauge, sd = sigma[free], fits = 2, iterlim = 1000, tolControl = tolerances, cores = cores) |> as.parframe() }, tasks = 100, on = slurmCluster("helix", cores = 2, walltime = "08:00:00"), -jobname = "oppelt_fits", seed = 1L, build = "compile", +jobname = "oppelt_fits", seed = 1L, build = "compile", libs = "~/R/lib-devel4", input = c("obj", "mu", "sigma", "free", "gauge", "tolerances"), recover = dir.exists("oppelt_fits_folder")) @@ -50,20 +50,16 @@ run("fit.R", "fitsave") ## ---- helixprofiles # The profiles of profiles.R, one parameter per array task on 2 cores, from the fit under the prior -# of the profiles; with a profile below that fit, the fit restarts at the lowest point of the -# profiles (`lowest`, from helixprofilescollect) and the job runs again. +# of the profiles +source("model.R") run("profiles.R", "refit", "^## ---- profiles$") -if (exists("lowest")) { - fitProfile <- bestFit(lowest) - best <- fitProfile$argument -} limits <- c(lower = -7, upper = 7) profilesJob <- distributedComputing({ profile(objProfile, best, task, fixed = gauge, limits = limits, stepControl = list(stop = "data"), algoControl = list(reoptimize = TRUE), optControl = list(iterlim = 100, tolControl = tolerances), cores = cores) }, tasks = as.list(names(best)), on = slurmCluster("helix", cores = 2, walltime = "24:00:00"), -jobname = "oppelt_profiles", seed = 1L, build = "compile", +jobname = "oppelt_profiles", seed = 1L, build = "compile", libs = "~/R/lib-devel4", input = c("objProfile", "best", "gauge", "limits", "tolerances"), recover = dir.exists("oppelt_profiles_folder")) @@ -71,13 +67,12 @@ recover = dir.exists("oppelt_profiles_folder")) profilesJob$check() profilesJob$wait() profiles <- results(profilesJob) -min(profiles$value) - fitProfile$value # below -1e-2: helixprofiles again, from `lowest` -lowest <- unlist(as.data.frame(profiles)[which.min(profiles$value), names(best)]) +min(profiles$value) - fitProfile$value # how far a profile reaches below the fit run("profiles.R", "profilessave") ## ---- helixoptimizers -# optimizers.R: one fit per task, a start by a method; the exact Hessian on 16 GB +# optimizers.R: one fit per task, a start by a method, at most 30 minutes; the exact Hessian on 16 GB source("model.R") run("sensitivities.R", "reversechain", "^## ---- gradients") run("optimizers.R", "optimizers", "^optimizers <- do.call") @@ -85,17 +80,19 @@ exact <- tasks$method == "exact" optimizersJobs <- lapply(c(FALSE, TRUE), function(heavy) { distributedComputing({ fitOne(task$method, task$start) }, tasks = split(tasks[exact == heavy, ], seq_len(sum(exact == heavy))), - on = slurmCluster("helix", cores = 1, walltime = "06:00:00", memPerCore = if (heavy) 16 else 2), + on = slurmCluster("helix", cores = 1, walltime = "00:30:00", memPerCore = if (heavy) 16 else 2), jobname = paste0("oppelt_optimizers", if (heavy) "_exact"), seed = 1L, build = "compile", + libs = "~/R/lib-devel4", input = c("fitOne", "objR", "starts", "free", "gauge", "tolerances", "methods"), recover = dir.exists(paste0("oppelt_optimizers", if (heavy) "_exact", "_folder"))) }) ## ---- helixoptimizerscollect for (job in optimizersJobs) job$wait() -# a task without result, a fit the queue ended for memory, is a fit without value +# a task without result, a fit the queue ended for time or memory, is a fit without value failedFit <- function(task) data.frame(method = task$method, start = task$start, value = NA_real_, - converged = FALSE, iterations = NA_integer_, elapsed = NA_real_) + converged = FALSE, iterations = NA_integer_, + stopReason = NA_character_, elapsed = NA_real_) optimizers <- do.call(rbind, Map(function(job, heavy) { out <- suppressWarnings(job$get(combine = FALSE)) part <- tasks[exact == heavy, ] @@ -109,14 +106,9 @@ run("optimizers.R", "optimizerssave") ## ---- helixreduced # refit.R on the reduced model of reduced.R, once the limits are decided against the profiles: -# the fits on this machine, one profile per task; with a profile below the fit, as for the full -# model, again from `lowest` +# the fits on this machine, one profile per task source("reduced.R") run("refit.R", "reducedfit", "^## ---- reducedprofiles$") -if (exists("lowestReduced")) { - fitReducedProfile <- bestReducedFit(lowestReduced) - bestReducedProfile <- fitReducedProfile$argument -} reducedJob <- distributedComputing({ profile(objReducedProfile, bestReducedProfile, task, fixed = gaugeReduced, limits = c(lower = -7, upper = 7), stepControl = list(stop = "data"), @@ -124,25 +116,47 @@ reducedJob <- distributedComputing({ optControl = list(iterlim = 100, tolControl = tolerances), cores = cores) }, tasks = as.list(names(bestReducedProfile)), on = slurmCluster("helix", cores = 2, walltime = "12:00:00"), -jobname = "oppelt_reduced", seed = 1L, build = "compile", +jobname = "oppelt_reduced", seed = 1L, build = "compile", libs = "~/R/lib-devel4", input = c("objReducedProfile", "bestReducedProfile", "gaugeReduced", "tolerances"), recover = dir.exists("oppelt_reduced_folder")) ## ---- helixreducedcollect reducedJob$wait() profilesReduced <- results(reducedJob) -min(profilesReduced$value) - fitReducedProfile$value # below -1e-2: helixreduced again -lowestReduced <- unlist(as.data.frame(profilesReduced)[which.min(profilesReduced$value), - names(bestReducedProfile)]) +min(profilesReduced$value) - fitReducedProfile$value # how far a profile reaches below the fit run("refit.R", "reducedsave") +## ---- helixfundamental +# fundamental.R on the reduced model in the chart of the fundamental domain: the fits on this +# machine, one profile per task +source("reduced.R") +run("fundamental.R", "fundamentaltrafo", "^## ---- fundamentalprofiles$") +fundamentalJob <- distributedComputing({ + profile(objFundamentalProfile, bestFundamentalProfile, task, fixed = gaugeReduced, + limits = c(lower = -7, upper = 7), stepControl = list(stop = "data"), + algoControl = list(reoptimize = TRUE), + optControl = list(iterlim = 100, tolControl = tolerances), cores = cores) +}, tasks = as.list(names(bestFundamentalProfile)), +on = slurmCluster("helix", cores = 2, walltime = "12:00:00"), +jobname = "oppelt_fundamental", seed = 1L, build = "compile", libs = "~/R/lib-devel4", +input = c("objFundamentalProfile", "bestFundamentalProfile", "gaugeReduced", "tolerances"), +recover = dir.exists("oppelt_fundamental_folder")) + +## ---- helixfundamentalcollect +fundamentalJob$wait() +profilesFundamental <- results(fundamentalJob) +# how far a profile reaches below the fit +min(profilesFundamental$value) - fitFundamentalProfile$value +run("fundamental.R", "fundamentalsave") + ## ---- helixprediction # prediction.R, after refit.R: the profile of the prediction at one time per task +source("reduced.R") run("prediction.R", "predictionsetup", "^predictionProfiles <- ") predictionJob <- distributedComputing({ predictionProfile(task) }, tasks = as.list(times), on = slurmCluster("helix", cores = 1, walltime = "06:00:00"), jobname = "oppelt_prediction", - seed = 1L, build = "compile", + seed = 1L, build = "compile", libs = "~/R/lib-devel4", input = c("predictionProfile", "predicted", "data", "prdPrediction", "ePrediction", "muReduced", "sigmaReduced", "bestReduced", "gaugeReduced", "tolerances"), recover = dir.exists("oppelt_prediction_folder")) @@ -153,22 +167,78 @@ predictionProfiles <- results(predictionJob, combine = FALSE) run("prediction.R", "predictionband") -## ---- helixcompounds -# compounds.R, after refit.R: the 200 starts of msem(), 2 per task; every task draws all starts -# from the seed of the script and fits the two that `which` names -run("compounds.R", to = "^set.seed\\(3\\)") -compoundsJob <- distributedComputing({ +## ---- helixdcfspikeslab +# the spike-and-slab fit of dcf.R: the 1000 starts of msem(), one per task, at most 30 minutes each +run("dcf.R", to = "^## ---- dcfspikeslab$") +dcfJob <- distributedComputing({ set.seed(3) - msem(objCompounds + priorCompounds, random, init, fixed = gaugeReduced, - control = list(sparseFit = list(maxOuter = 1000, trustControl = list(tolControl = tolerances))), - fits = 200, sd = sdStart, keepFits = TRUE, which = task, cores = cores) -}, tasks = split(1:200, rep(1:100, each = 2)), -on = slurmCluster("helix", cores = 2, walltime = "24:00:00"), jobname = "oppelt_compounds", -seed = 1L, build = "compile", -input = c("objCompounds", "priorCompounds", "random", "init", "gaugeReduced", "sdStart", - "tolerances"), recover = dir.exists("oppelt_compounds_folder")) - -## ---- helixcompoundscollect -compoundsJob$wait() -fitCompounds <- results(compoundsJob) -run("compounds.R", "compoundsave") + msem(objSS, randomSS, c(initDCF, prob_compound = 0.2, tau_compound = 0.5), fixed = gaugeReduced, + control = list(sparseFit = list(trustControl = list(tolControl = tolerances))), + fits = 1000, sd = 1, which = task, cores = 1) +}, tasks = as.list(1:1000), on = slurmCluster("helix", cores = 1, walltime = "00:30:00", memPerCore = 4), +jobname = "oppelt_dcf_ss", seed = 1L, build = "compile", libs = "~/R/lib-016d", +input = c("objSS", "randomSS", "initDCF", "gaugeReduced", "tolerances"), +recover = dir.exists("oppelt_dcf_ss_folder")) + +## ---- helixdcfspikeslabcollect +# a start at the time limit has no result; get() leaves it out with a warning +dcfJob$wait() +fitDCF <- dcfJob$get() + +## ---- helixdcfspikeslabmore +# the second round of dcf.R: 200 starts around the best fit +bestSS <- fitDCF$argument +moreJob <- distributedComputing({ + set.seed(4) + msem(objSS, randomSS, bestSS, fixed = gaugeReduced, + control = list(sparseFit = list(trustControl = list(tolControl = tolerances))), + fits = 200, sd = 1, which = task, cores = 1) +}, tasks = as.list(1:200), on = slurmCluster("helix", cores = 1, walltime = "00:30:00", memPerCore = 4), +jobname = "oppelt_dcf_ss_more", seed = 1L, build = "compile", libs = "~/R/lib-016d", +input = c("objSS", "randomSS", "bestSS", "gaugeReduced", "tolerances"), +recover = dir.exists("oppelt_dcf_ss_more_folder")) + +## ---- helixdcfspikeslabmorecollect +moreJob$wait() +moreDCF <- moreJob$get() +starts <- rbind(cbind(fitDCF$multistart, round = 1L), cbind(moreDCF$multistart, round = 2L)) +if (moreDCF$value < fitDCF$value) fitDCF <- moreDCF +fitDCF$multistart <- starts +run("dcf.R", "dcfspikeslabsave", "^## ---- dcfL1$") + +## ---- helixdcfl1 +# the L1 scan of dcf.R with fitTasks() on the cluster: the tasks of each call in array jobs of at +# most 1000 tasks, one fit per task, at most ten minutes; a job goes out when at most 1048 tasks of +# the user are queued, since the queue holds at most 2048 of one user, and comes back when it +# finished. The jobs of a call are numbered, so a second run of the section recovers them. +run("dcf.R", to = "^## ---- dcfspikeslab$") +run("dcf.R", "dcfL1", "^## ---- dcfL1fit$") +queued <- function() as.integer(system("ssh helix 'squeue -u $USER -h -r | wc -l'", intern = TRUE)) +calls <- 0L +fitTasks <- function(tasks, fn) { + calls <<- calls + 1L + parts <- split(seq_along(tasks), ceiling(seq_along(tasks) / 1000)) + out <- vector("list", length(parts)) + jobs <- list() + k <- 1L + while (k <= length(parts) || length(jobs)) { + while (k <= length(parts)) { + name <- paste0("oppelt_dcf_l1_", calls, "_", k) + if (!dir.exists(paste0(name, "_folder")) && queued() > 1048L) break + jobs[[as.character(k)]] <- distributedComputing({ fn(task) }, tasks = tasks[parts[[k]]], + on = slurmCluster("helix", cores = 1, walltime = "00:10:00", memPerCore = 2), + jobname = name, seed = 1L, build = "compile", libs = "~/R/lib-016d", + input = c("fn", "objDCF", "initDCF", "changesDCF", "changesL1", "offL1", "zeroDCF", + "gaugeReduced", "tolerances"), recover = dir.exists(paste0(name, "_folder"))) + k <- k + 1L + } + for (j in names(jobs)) { + if (!isTRUE(suppressWarnings(jobs[[j]]$check()))) next + out[[as.integer(j)]] <- suppressWarnings(jobs[[j]]$get(combine = FALSE)) + jobs[[j]] <- NULL + } + if (length(jobs)) Sys.sleep(60) + } + Filter(function(r) is.list(r) && !inherits(r, "try-error"), unlist(out, recursive = FALSE)) +} +run("dcf.R", "dcfL1fit") diff --git a/examples/oppeltNPJSystBiolAppl2018/model.R b/examples/oppeltNPJSystBiolAppl2018/model.R index 65b71efc..07b5d5b1 100644 --- a/examples/oppeltNPJSystBiolAppl2018/model.R +++ b/examples/oppeltNPJSystBiolAppl2018/model.R @@ -194,8 +194,10 @@ sigma[turnover] <- 2 mu["trigger_iIkk"] <- log(1 / 240) sigma["trigger_iIkk"] <- 2 # the cells rest: a term that is zero on a stable resting state and reaches 100 where it loses -# stability -stability <- constraintStability(pSS, p) +# stability, on a ramp of a tenth of the inverse time span of the data, wide enough for the model +# of a fit step to see the boundary before the step crosses it +rampWidth <- 0.1 / max(as.data.frame(data)$time) +stability <- constraintStability(pSS, p, width = rampWidth) obj <- normL2(data, prd, e) + constraintL2(mu, sigma = sigma) + stability diff --git a/examples/oppeltNPJSystBiolAppl2018/optimizers.R b/examples/oppeltNPJSystBiolAppl2018/optimizers.R index 0af47101..8bd2ec8d 100644 --- a/examples/oppeltNPJSystBiolAppl2018/optimizers.R +++ b/examples/oppeltNPJSystBiolAppl2018/optimizers.R @@ -1,22 +1,48 @@ # The Hessian sources of trust() on the full model: fits by Gauss-Newton, BFGS and SR1 with -# reverse gradients, the exact Hessian by forward over reverse, and Gauss-Newton handing over to -# BFGS, all from the same 100 starts. Saves results/optimizers.rds, which the guide reads. +# reverse gradients, the exact Hessian by forward over reverse, Gauss-Newton handing over to BFGS, +# and the structured secant updates with their Gauss-Newton hybrids, all from the same 100 starts. +# Saves results/optimizers.rds, which the guide reads. # the chain with the reverse sweep, from sensitivities.R if (!exists("objR")) source("sensitivities.R") ## ---- optimizers -# 100 starts drawn from the prior, as in fit.R. BFGS and SR1 take the reverse gradient and start -# from the identity; the BFGS phase after Gauss-Newton starts from the Gauss-Newton Hessian +# 100 starts drawn from the prior, as in fit.R; a start without a stable resting state is replaced +# by the next one of a second draw, as mstrust() draws anew. BFGS and SR1 take the reverse gradient +# and start from the identity; the BFGS phase after Gauss-Newton, after 20 iterations or once the +# radius stays unchanged, starts from the Gauss-Newton Hessian; the structured methods add a learned correction to the Gauss-Newton Hessian at every +# iterate, scaled with the residual norm or, on the Gauss-Newton branch of a hybrid, shifted by it free <- setdiff(names(mu), names(gauge)) -starts <- msParframe(mu[free], n = 100, seed = 2, sd = sigma[free], keepfirst = FALSE) +draw <- function(seed) msParframe(mu[free], n = 100, seed = seed, sd = sigma[free], keepfirst = FALSE) +feasible <- function(p) !inherits(try(objR(p, fixed = gauge, deriv = FALSE), silent = TRUE), + "try-error") +starts <- draw(2) +spare <- draw(3) +spare <- spare[vapply(seq_len(nrow(spare)), function(i) + feasible(setNames(as.numeric(spare[i, free]), free)), TRUE), ] +bad <- which(!vapply(seq_len(nrow(starts)), function(i) + feasible(setNames(as.numeric(starts[i, free]), free)), TRUE)) +starts[bad, ] <- spare[seq_along(bad), ] methods <- list( + `default (Fides hybrid)` = list(), `Gauss-Newton` = list(hessianMethod = "gn"), BFGS = list(hessianMethod = "bfgs", sweep = "reverse", qnControl = list(hessianInit = "identity")), SR1 = list(hessianMethod = "sr1", sweep = "reverse", qnControl = list(hessianInit = "identity")), exact = list(hessianMethod = "exact", sweep = "reverse"), `GN, then BFGS` = list(phases = list(list(hessianMethod = "gn", iterlim = 20), - list(hessianMethod = "bfgs")))) + list(hessianMethod = "bfgs"))), + `GN, then BFGS at stall 25` = list(phases = list(list(hessianMethod = "gn", radiusStall = 25), + list(hessianMethod = "bfgs"))), + `GN, then BFGS at stall 50` = list(phases = list(list(hessianMethod = "gn", radiusStall = 50), + list(hessianMethod = "bfgs"))), + SBFGS = list(hessianMethod = "sbfgs"), + `SBFGS, scaled` = list(hessianMethod = "sbfgs", qnControl = list(qnScaling = "residual")), + SSR1 = list(hessianMethod = "ssr1"), + `SSR1, scaled` = list(hessianMethod = "ssr1", qnControl = list(qnScaling = "residual")), + GNSBFGS = list(hessianMethod = "gnsbfgs"), + `GNSBFGS, shifted` = list(hessianMethod = "gnsbfgs", qnControl = list(qnHybridShift = TRUE)), + GNSSR1 = list(hessianMethod = "gnssr1"), + `GNSSR1, shifted` = list(hessianMethod = "gnssr1", qnControl = list(qnHybridShift = TRUE))) # one fit of start `i` by method `m`, with the wall time fitOne <- function(m, i) { t0 <- proc.time()[["elapsed"]] @@ -26,6 +52,7 @@ fitOne <- function(m, i) { data.frame(method = m, start = i, value = if (is.null(fit)) NA_real_ else fit$value, converged = !is.null(fit) && isTRUE(fit$converged), iterations = if (is.null(fit)) NA_integer_ else as.integer(fit$iterations), + stopReason = if (is.null(fit)) NA_character_ else fit$stopReason, elapsed = proc.time()[["elapsed"]] - t0) } tasks <- expand.grid(method = names(methods), start = seq_len(nrow(starts)), stringsAsFactors = FALSE) diff --git a/examples/oppeltNPJSystBiolAppl2018/plots.R b/examples/oppeltNPJSystBiolAppl2018/plots.R index 1b98985b..7c52d246 100644 --- a/examples/oppeltNPJSystBiolAppl2018/plots.R +++ b/examples/oppeltNPJSystBiolAppl2018/plots.R @@ -44,22 +44,22 @@ ggplot(course, aes(time, value)) + scale_x_continuous(breaks = seq(0, 360, 60)) + scale_y_log10() + labs(x = "time [min]", y = "nuclear IκBα [total NFκB]") + - theme_dMod() + theme_dMod2() -## ---- changes -# the changes of the rate constants by the compounds, from compounds.R: color the mode, opacity -# the evidence against the spike, -log10 p0 cut at 6; a circle where p0 < 0.05 -changes <- readRDS("results/compounds.rds")$random -changes$eta <- factor(changes$eta, levels = unique(changes$eta)) -changes$evidence <- -log10(pmax(changes$p0, 1e-6)) -ggplot(changes, aes(group, eta)) + - geom_tile(aes(fill = mode, alpha = evidence), color = "white") + - geom_point(data = changes[changes$p0 < 0.05, ], aes(shape = "p0 < 0.05"), size = 1.8, fill = "white") + - scale_y_discrete(limits = rev) + - scale_fill_gradient2(low = "#2166ac", mid = "white", high = "#b2182b") + - scale_alpha(range = c(0.1, 1), limits = c(0, 6), breaks = 1:3, - labels = c("1, p0 = 0.1", "2, p0 = 0.01", "3, p0 = 0.001"), - guide = guide_legend(override.aes = list(fill = "gray30"))) + - scale_shape_manual(values = 21) + - labs(x = NULL, y = NULL, fill = "change [log]", alpha = "evidence, -log10 p0", shape = NULL) + - theme_dMod() +## ---- dcfpaths +# the differences by DCF over the strength of the L1 penalty, from dcf.R, in color those kept at +# the selected strength +dcfL1 <- readRDS("results/dcfL1.rds") +paths <- data.frame(lambda = rep(as.numeric(rownames(dcfL1$path)), ncol(dcfL1$path)), + difference = rep(sub("^eta_(.*)_DCF$", "\\1", colnames(dcfL1$path)), + each = nrow(dcfL1$path)), + value = as.vector(dcfL1$path)) +paths <- paths[paths$lambda > 0, ] +kept <- sub("^eta_(.*)_DCF$", "\\1", dcfL1$selected) +ggplot(paths, aes(lambda, value, group = difference)) + + geom_vline(xintercept = dcfL1$lambda, linetype = 2, color = "gray50") + + geom_line(data = paths[!paths$difference %in% kept, ], color = "gray75") + + geom_line(data = paths[paths$difference %in% kept, ], aes(color = difference)) + + scale_x_log10(breaks = 10^(-2:4), labels = trimws(format(10^(-2:4), scientific = FALSE, drop0trailing = TRUE))) + + labs(x = expression(lambda), y = expression(Delta ~ "[log]"), color = NULL) + + theme_dMod2() diff --git a/examples/oppeltNPJSystBiolAppl2018/profiles.R b/examples/oppeltNPJSystBiolAppl2018/profiles.R index bbbaffe5..8d77156f 100644 --- a/examples/oppeltNPJSystBiolAppl2018/profiles.R +++ b/examples/oppeltNPJSystBiolAppl2018/profiles.R @@ -11,35 +11,21 @@ refit <- trust(obj, as.parvec(readRDS("results/fits.rds")), fixed = gauge, rinit ## ---- profileprior # the profiles replace the prior of model.R by one of standard deviation 20 at the refit, so that -# the data term shapes them; they start at the optimum of that objective +# the data term shapes them; they start at the optimum of that objective, one fit from the refit objProfile <- normL2(data, prd, e) + constraintL2(refit$argument, sigma = 20) + stability -# the best of 20 fits from `center` and from starts about it, sd 0.1, which reaches the floor of -# a flat valley where a single fit stops on it -bestFit <- function(center) { - fits <- mstrust(objProfile, center, fixed = gauge, sd = 0.1, fits = 20, startFromCenter = TRUE, - rinit = 0.1, rmax = 10, iterlim = 1000, tolControl = tolerances, - cores = getOption("dMod2.cores")) - values <- vapply(fits, function(f) if (is.numeric(f$value)) f$value else Inf, 0) - fits[[which.min(values)]] -} -fitProfile <- bestFit(refit$argument) +fitProfile <- trust(objProfile, refit$argument, fixed = gauge, rinit = 0.1, rmax = 10, + iterlim = 1000, tolControl = tolerances) best <- fitProfile$argument ## ---- profiles # the profiles integrated, every step re-optimized, each side until the data term has risen by the # threshold or the parameter has moved by 7 on the natural log scale, the settings of refit.R. -# Where a profile reaches a lower value than the fit, the fit restarts from there and all -# profiles run again. helix.R runs one profile per array task. +# helix.R runs one profile per array task. limits <- c(lower = -7, upper = 7) -repeat { - profiles <- profile(objProfile, best, names(best), fixed = gauge, limits = limits, - stepControl = list(stop = "data"), algoControl = list(reoptimize = TRUE), - optControl = list(iterlim = 100, tolControl = tolerances), - cores = getOption("dMod2.cores")) - if (min(profiles$value) > fitProfile$value - 1e-2) break - fitProfile <- bestFit(as.parvec(profiles)[names(best)]) - best <- fitProfile$argument -} +profiles <- profile(objProfile, best, names(best), fixed = gauge, limits = limits, + stepControl = list(stop = "data"), algoControl = list(reoptimize = TRUE), + optControl = list(iterlim = 100, tolControl = tolerances), + cores = getOption("dMod2.cores")) ## ---- profilessave dir.create("results", showWarnings = FALSE) diff --git a/examples/oppeltNPJSystBiolAppl2018/refit.R b/examples/oppeltNPJSystBiolAppl2018/refit.R index 1eaefdeb..97e4d6fe 100644 --- a/examples/oppeltNPJSystBiolAppl2018/refit.R +++ b/examples/oppeltNPJSystBiolAppl2018/refit.R @@ -30,31 +30,20 @@ ratio <- c(full = dataFull, reduced = dataReduced, difference = dataReduced - da removed = removed, threshold = qchisq(0.95, removed)) ## ---- reducedprofileprior -# the prior of the profiles of profiles.R, standard deviation 20 at the best fit +# the prior of the profiles of profiles.R, standard deviation 20 at the best fit, and one fit from +# there objReducedProfile <- normL2(data, prdReduced, eReduced) + constraintL2(bestReduced, sigma = 20) -# the best of 20 fits from `center` and from starts about it, sd 0.1, as for the full model -bestReducedFit <- function(center) { - fits <- mstrust(objReducedProfile, center, fixed = gaugeReduced, sd = 0.1, fits = 20, - startFromCenter = TRUE, rinit = 0.1, rmax = 10, iterlim = 1000, - tolControl = tolerances, cores = getOption("dMod2.cores")) - values <- vapply(fits, function(f) if (is.numeric(f$value)) f$value else Inf, 0) - fits[[which.min(values)]] -} -fitReducedProfile <- bestReducedFit(bestReduced) +fitReducedProfile <- trust(objReducedProfile, bestReduced, fixed = gaugeReduced, rinit = 0.1, + rmax = 10, iterlim = 1000, tolControl = tolerances) bestReducedProfile <- fitReducedProfile$argument ## ---- reducedprofiles -# the settings of the full model, with the same restart from a lower point of a profile -repeat { - profilesReduced <- profile(objReducedProfile, bestReducedProfile, names(bestReducedProfile), - fixed = gaugeReduced, limits = c(lower = -7, upper = 7), - stepControl = list(stop = "data"), algoControl = list(reoptimize = TRUE), - optControl = list(iterlim = 100, tolControl = tolerances), - cores = getOption("dMod2.cores")) - if (min(profilesReduced$value) > fitReducedProfile$value - 1e-2) break - fitReducedProfile <- bestReducedFit(as.parvec(profilesReduced)[names(bestReducedProfile)]) - bestReducedProfile <- fitReducedProfile$argument -} +# the settings of the full model +profilesReduced <- profile(objReducedProfile, bestReducedProfile, names(bestReducedProfile), + fixed = gaugeReduced, limits = c(lower = -7, upper = 7), + stepControl = list(stop = "data"), algoControl = list(reoptimize = TRUE), + optControl = list(iterlim = 100, tolControl = tolerances), + cores = getOption("dMod2.cores")) ## ---- reducedsave # the md5 of the files the result is computed from, which the guide checks on reading diff --git a/examples/oppeltNPJSystBiolAppl2018/results/compounds.rds b/examples/oppeltNPJSystBiolAppl2018/results/compounds.rds deleted file mode 100644 index 6ea042bd..00000000 Binary files a/examples/oppeltNPJSystBiolAppl2018/results/compounds.rds and /dev/null differ diff --git a/examples/oppeltNPJSystBiolAppl2018/results/dcf.rds b/examples/oppeltNPJSystBiolAppl2018/results/dcf.rds new file mode 100644 index 00000000..0a99aca1 Binary files /dev/null and b/examples/oppeltNPJSystBiolAppl2018/results/dcf.rds differ diff --git a/examples/oppeltNPJSystBiolAppl2018/results/dcfL1.rds b/examples/oppeltNPJSystBiolAppl2018/results/dcfL1.rds new file mode 100644 index 00000000..34eb2992 Binary files /dev/null and b/examples/oppeltNPJSystBiolAppl2018/results/dcfL1.rds differ diff --git a/examples/oppeltNPJSystBiolAppl2018/results/discrete.rds b/examples/oppeltNPJSystBiolAppl2018/results/discrete.rds new file mode 100644 index 00000000..cb782410 Binary files /dev/null and b/examples/oppeltNPJSystBiolAppl2018/results/discrete.rds differ diff --git a/examples/oppeltNPJSystBiolAppl2018/results/fits.rds b/examples/oppeltNPJSystBiolAppl2018/results/fits.rds index aa5e191c..b433a1df 100644 Binary files a/examples/oppeltNPJSystBiolAppl2018/results/fits.rds and b/examples/oppeltNPJSystBiolAppl2018/results/fits.rds differ diff --git a/examples/oppeltNPJSystBiolAppl2018/results/fundamental.rds b/examples/oppeltNPJSystBiolAppl2018/results/fundamental.rds new file mode 100644 index 00000000..eb7e9a91 Binary files /dev/null and b/examples/oppeltNPJSystBiolAppl2018/results/fundamental.rds differ diff --git a/examples/oppeltNPJSystBiolAppl2018/results/onefit.rds b/examples/oppeltNPJSystBiolAppl2018/results/onefit.rds index a67f4132..473c9b53 100644 Binary files a/examples/oppeltNPJSystBiolAppl2018/results/onefit.rds and b/examples/oppeltNPJSystBiolAppl2018/results/onefit.rds differ diff --git a/examples/oppeltNPJSystBiolAppl2018/results/optimizers.rds b/examples/oppeltNPJSystBiolAppl2018/results/optimizers.rds index 2948aaf2..77d1e1f6 100644 Binary files a/examples/oppeltNPJSystBiolAppl2018/results/optimizers.rds and b/examples/oppeltNPJSystBiolAppl2018/results/optimizers.rds differ diff --git a/examples/oppeltNPJSystBiolAppl2018/results/petab/oppelt.xml b/examples/oppeltNPJSystBiolAppl2018/results/petab/oppelt.xml index bc59c262..805d909a 100644 --- a/examples/oppeltNPJSystBiolAppl2018/results/petab/oppelt.xml +++ b/examples/oppeltNPJSystBiolAppl2018/results/petab/oppelt.xml @@ -31,69 +31,69 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/oppeltNPJSystBiolAppl2018/results/petab/parameters_oppelt.tsv b/examples/oppeltNPJSystBiolAppl2018/results/petab/parameters_oppelt.tsv index 2c2327bf..16f6441b 100644 --- a/examples/oppeltNPJSystBiolAppl2018/results/petab/parameters_oppelt.tsv +++ b/examples/oppeltNPJSystBiolAppl2018/results/petab/parameters_oppelt.tsv @@ -1,65 +1,65 @@ parameterId lowerBound upperBound nominalValue estimate -deact_TNFR 3.65297190311e-07 3652.97190311 0.0365297190310715 true -act_Ikk_by_TNF 1.21800550635e-06 12180.0550635 0.121800550635356 true -inh_Ikk 4.99723426e-06 49972.3426 0.499723425999981 true -act_Ikk_Base 8.55944959893e-10 8.55944959893 8.55944959893067e-05 true -trigger_iIkk 2.99791787553e-08 299.791787553 0.0029979178755258 true -act_pIkk 8.32167006982e-07 8321.67006982 0.0832167006981881 true -deact_ppIkk 7.0115148895e-07 7011.5148895 0.0701151488949883 true -act_Ikb_Base 2.32697854579e-08 232.697854579 0.00232697854578642 true -act_Ikb_by_Ikk 6.00808950474e-06 60080.8950474 0.600808950474054 true -eta_s_ppIkk 9.7729781248e-07 9772.9781248 0.0977297812479598 true -act_Nfk_Base 1.93069367585e-09 19.3069367585 0.000193069367585375 true -act_Nfk_by_Ikk 5.07184209411e-06 50718.4209411 0.507184209410593 true -form_complex 5.95691548915e-05 595691.548915 5.956915489148 true -ext_nNfkIkb 0.000126924712643 1269247.12643 12.6924712642527 true -eta_act_Nfk_Base_c_NfkpIkb 7.36402142728e-06 73640.2142728 0.736402142727535 true -eta_act_Nfk_c_NfkpIkb 5.37157454115e-06 53715.7454115 0.537157454114856 true -split_NfkpIkb 8.14720538179e-07 8147.20538179 0.0814720538178575 true -eta_act_Ikb_Base_c_pNfkIkb 0.00161756423012 16175642.3012 161.756423011589 true -eta_act_Ikb_c_pNfkIkb 2.37843273477e-05 237843.273477 2.37843273476911 true -eta_split_pNfkpIkb 9.5263693507e-06 95263.693507 0.952636935070155 true -int_Nfk 2.03600493009e-07 2036.00493009 0.0203600493009198 true -degrad_Ikb 2.86989532566e-05 286989.532566 2.86989532565694 true -eta_int_pNfk 0.000111604912919 1116049.12919 11.1604912919231 true -eta_int_Ikb 0.000112164753884 1121647.53884 11.2164753884048 true -prod_mIkb_by_nNfk 4.68290072086e-08 468.290072086 0.00468290072085889 true -degrad_mIkb 3.46494244027e-07 3464.94244027 0.034649424402682 true -eta_form_complex_nuc 0.000263750292757 2637502.92757 26.3750292756985 true -deact_pnNfk 4.90053721649e-06 49005.3721649 0.490053721648745 true -shuttle_RnaA20 3.23947469744e-07 3239.47469744 0.0323947469744286 true -degrad_RnaA20 3.74246370526e-08 374.246370526 0.00374246370526202 true -build_A20 2.13256162889e-08 213.256162889 0.0021325616288881 true -degrad_A20 5.43409363753e-07 5434.09363753 0.0543409363753047 true -s_nucNFkB 1.21021362172e-05 121021.362172 1.21021362172087 true -off_nucNFkB 9.61506220532e-06 96150.6220532 0.961506220531505 true -tau_nucNFkB 3.33072798532e-09 33.3072798532 0.000333072798531899 true -s_cytNFkB 3.137236925e-06 31372.36925 0.313723692499986 true -off_cytNFkB 8.00685059692e-06 80068.5059692 0.800685059691613 true -tau_cytNFkB 4.47865850206e-09 44.7865850206 0.000447865850206228 true -off_A20GFP 4.46345342985e-06 44634.5342985 0.446345342985189 true -tau_A20GFP 1.44666365812e-10 1.44666365812 1.44666365811987e-05 true -s_IkBa 1.36377554567e-05 136377.554567 1.36377554566657 true -off_IkBa 8.8410151531e-08 884.10151531 0.00884101515310477 true -s_pNFkB 8.38741971012e-05 838741.971012 8.38741971011762 true -off_pNFkB 2.4692721471e-06 24692.721471 0.246927214709602 true -s_pIkBa 7.81197953314e-05 781197.953314 7.81197953314478 true -off_pIkBa 1.95398418242e-07 1953.98418242 0.0195398418241525 true -s_pIKK 2.39378950815e-05 239378.950815 2.39378950814564 true -off_pIKK 4.13872688578e-06 41387.2688578 0.413872688578114 true -s_ipIkBa_ibIkBa 1.76706022617e-05 176706.022617 1.76706022617471 true -off_ipIkBa_ibIkBa 9.66263352091e-07 9662.63352091 0.0966263352091017 true -s_ipNFkB_ibNFkB 1.56050882449e-06 15605.0882449 0.156050882448888 true -off_ipNFkB_ibNFkB 9.30839262563e-06 93083.9262563 0.93083926256277 true -s_ipNFkB_ibpIkBa 6.23324036535e-05 623324.036535 6.23324036535474 true -off_ipNFkB_ibpIkBa 2.12787699687e-07 2127.87699687 0.0212787699686893 true -s_ipNFkB_ibpNFkB 3.59093112169e-05 359093.112169 3.59093112168635 true -off_ipNFkB_ibpNFkB 3.98803698204e-06 39880.3698204 0.398803698204199 true -s_ipIkBa_ibpNFkB 6.7822171229e-05 678221.71229 6.78221712289826 true -off_ipIkBa_ibpNFkB 3.28397595562e-06 32839.7595562 0.328397595562139 true -s_ipIkBa_ibNFkB 1.40687509923e-05 140687.509923 1.40687509922877 true -off_ipIkBa_ibNFkB 2.52942719425e-06 25294.2719425 0.252942719424793 true -sigma_nucNFkB 1.83943497349e-07 1839.43497349 0.0183943497348926 true -sigma_cytNFkB 2.02775600461e-07 2027.75600461 0.0202775600461311 true -sigma_A20GFP 4.68003988632e-07 4680.03988632 0.046800398863214 true +deact_TNFR 3.64753183116e-07 3647.53183116 0.0364753183116464 true +act_Ikk_by_TNF 1.22061130927e-06 12206.1130927 0.12206113092685 true +inh_Ikk 4.96444119263e-06 49644.4119263 0.496444119262577 true +act_Ikk_Base 8.55850258616e-10 8.55850258616 8.55850258616356e-05 true +trigger_iIkk 2.99698812656e-08 299.698812656 0.00299698812656316 true +act_pIkk 8.31782672288e-07 8317.82672288 0.0831782672288466 true +deact_ppIkk 7.00810430585e-07 7008.10430585 0.0700810430584749 true +act_Ikb_Base 2.32639247379e-08 232.639247379 0.00232639247378677 true +act_Ikb_by_Ikk 6.00916921849e-06 60091.6921849 0.600916921848849 true +eta_s_ppIkk 9.71791373106e-07 9717.91373106 0.0971791373106429 true +act_Nfk_Base 1.92992263353e-09 19.2992263353 0.000192992263352572 true +act_Nfk_by_Ikk 5.0761896948e-06 50761.896948 0.507618969479803 true +form_complex 5.95390982892e-05 595390.982892 5.95390982891758 true +ext_nNfkIkb 0.000127102146746 1271021.46746 12.7102146745631 true +eta_act_Nfk_Base_c_NfkpIkb 7.42222793632e-06 74222.2793632 0.742222793632236 true +eta_act_Nfk_c_NfkpIkb 5.36757260719e-06 53675.7260719 0.536757260718537 true +split_NfkpIkb 8.14277919081e-07 8142.77919081 0.0814277919080927 true +eta_act_Ikb_Base_c_pNfkIkb 0.0016180037771 16180037.771 161.800377710303 true +eta_act_Ikb_c_pNfkIkb 2.37966263185e-05 237966.263185 2.37966263184922 true +eta_split_pNfkpIkb 9.51253886042e-06 95125.3886042 0.951253886041802 true +int_Nfk 2.0328632161e-07 2032.8632161 0.0203286321610271 true +degrad_Ikb 2.86237212519e-05 286237.212519 2.8623721251923 true +eta_int_pNfk 0.000111752668619 1117526.68619 11.1752668619159 true +eta_int_Ikb 0.000112378453775 1123784.53775 11.2378453775194 true +prod_mIkb_by_nNfk 4.68306577349e-08 468.306577349 0.00468306577349406 true +degrad_mIkb 3.46512000548e-07 3465.12000548 0.034651200054846 true +eta_form_complex_nuc 0.000264463411107 2644634.11107 26.44634111069 true +deact_pnNfk 4.90109655628e-06 49010.9655628 0.490109655628073 true +shuttle_RnaA20 3.23932921185e-07 3239.32921185 0.0323932921184719 true +degrad_RnaA20 5.43430386038e-07 5434.30386038 0.0543430386037799 true +build_A20 2.13291954873e-08 213.291954873 0.00213291954873236 true +degrad_A20 3.74283549406e-08 374.283549406 0.00374283549405667 true +s_nucNFkB 1.21030267647e-05 121030.267647 1.21030267647211 true +off_nucNFkB 9.61509652025e-06 96150.9652025 0.961509652024519 true +tau_nucNFkB 3.33086601704e-09 33.3086601704 0.000333086601703648 true +s_cytNFkB 3.13747184538e-06 31374.7184538 0.313747184537767 true +off_cytNFkB 8.00660672624e-06 80066.0672624 0.800660672623777 true +tau_cytNFkB 4.47861725304e-09 44.7861725304 0.000447861725304422 true +off_A20GFP 4.46372257267e-06 44637.2257267 0.446372257266893 true +tau_A20GFP 1.44667167217e-10 1.44667167217 1.44667167216864e-05 true +s_IkBa 1.36386425401e-05 136386.425401 1.36386425401352 true +off_IkBa 8.84054287002e-08 884.054287002 0.00884054287002248 true +s_pNFkB 8.38302539547e-05 838302.539547 8.38302539546816 true +off_pNFkB 2.46917604674e-06 24691.7604674 0.24691760467423 true +s_pIkBa 7.80879952909e-05 780879.952909 7.8087995290923 true +off_pIkBa 1.95490142404e-07 1954.90142404 0.0195490142404188 true +s_pIKK 2.39328364076e-05 239328.364076 2.39328364076429 true +off_pIKK 4.13850315602e-06 41385.0315602 0.413850315601773 true +s_ipIkBa_ibIkBa 1.76722227348e-05 176722.227348 1.76722227348091 true +off_ipIkBa_ibIkBa 9.66187528842e-07 9661.87528842 0.0966187528841599 true +s_ipNFkB_ibNFkB 1.56048287842e-06 15604.8287842 0.156048287841578 true +off_ipNFkB_ibNFkB 9.30832613547e-06 93083.2613547 0.930832613546659 true +s_ipNFkB_ibpIkBa 6.23169500221e-05 623169.500221 6.23169500220751 true +off_ipNFkB_ibpIkBa 2.1279906384e-07 2127.9906384 0.0212799063839782 true +s_ipNFkB_ibpNFkB 3.58951511707e-05 358951.511707 3.58951511706507 true +off_ipNFkB_ibpNFkB 3.98746711844e-06 39874.6711844 0.398746711843725 true +s_ipIkBa_ibpNFkB 6.77586626922e-05 677586.626922 6.77586626921939 true +off_ipIkBa_ibpNFkB 3.28370186241e-06 32837.0186241 0.32837018624117 true +s_ipIkBa_ibNFkB 1.40694380842e-05 140694.380842 1.40694380841896 true +off_ipIkBa_ibNFkB 2.52930623246e-06 25293.0623246 0.252930623245547 true +sigma_nucNFkB 1.83943355333e-07 1839.43355333 0.0183943355332795 true +sigma_cytNFkB 2.02773231702e-07 2027.73231702 0.0202773231701902 true +sigma_A20GFP 4.68003798079e-07 4680.03798079 0.0468003798078697 true s_A20GFP -Inf Inf 1 false diff --git a/examples/oppeltNPJSystBiolAppl2018/results/prediction.rds b/examples/oppeltNPJSystBiolAppl2018/results/prediction.rds index ff891252..3d4c9f88 100644 Binary files a/examples/oppeltNPJSystBiolAppl2018/results/prediction.rds and b/examples/oppeltNPJSystBiolAppl2018/results/prediction.rds differ diff --git a/examples/oppeltNPJSystBiolAppl2018/results/profiles.rds b/examples/oppeltNPJSystBiolAppl2018/results/profiles.rds index 4f4a458e..00833728 100644 Binary files a/examples/oppeltNPJSystBiolAppl2018/results/profiles.rds and b/examples/oppeltNPJSystBiolAppl2018/results/profiles.rds differ diff --git a/examples/oppeltNPJSystBiolAppl2018/results/reduced.rds b/examples/oppeltNPJSystBiolAppl2018/results/reduced.rds index ca31c168..5c29d72e 100644 Binary files a/examples/oppeltNPJSystBiolAppl2018/results/reduced.rds and b/examples/oppeltNPJSystBiolAppl2018/results/reduced.rds differ diff --git a/examples/oppeltNPJSystBiolAppl2018/results/reduction.rds b/examples/oppeltNPJSystBiolAppl2018/results/reduction.rds index 5d924e2e..39df6880 100644 Binary files a/examples/oppeltNPJSystBiolAppl2018/results/reduction.rds and b/examples/oppeltNPJSystBiolAppl2018/results/reduction.rds differ diff --git a/examples/oppeltNPJSystBiolAppl2018/results/sensitivities.rds b/examples/oppeltNPJSystBiolAppl2018/results/sensitivities.rds index cdef7f1a..eca29cc8 100644 Binary files a/examples/oppeltNPJSystBiolAppl2018/results/sensitivities.rds and b/examples/oppeltNPJSystBiolAppl2018/results/sensitivities.rds differ diff --git a/examples/oppeltNPJSystBiolAppl2018/results/symmetries.rds b/examples/oppeltNPJSystBiolAppl2018/results/symmetries.rds index ae2bbb71..7d0b596b 100644 Binary files a/examples/oppeltNPJSystBiolAppl2018/results/symmetries.rds and b/examples/oppeltNPJSystBiolAppl2018/results/symmetries.rds differ diff --git a/examples/oppeltNPJSystBiolAppl2018/results/variants.rds b/examples/oppeltNPJSystBiolAppl2018/results/variants.rds index 45b0eff1..6166e750 100644 Binary files a/examples/oppeltNPJSystBiolAppl2018/results/variants.rds and b/examples/oppeltNPJSystBiolAppl2018/results/variants.rds differ diff --git a/examples/oppeltNPJSystBiolAppl2018/sensitivities.R b/examples/oppeltNPJSystBiolAppl2018/sensitivities.R index d3d351c0..658b53be 100644 --- a/examples/oppeltNPJSystBiolAppl2018/sensitivities.R +++ b/examples/oppeltNPJSystBiolAppl2018/sensitivities.R @@ -19,7 +19,7 @@ pSSR <- Pimpl(reactions, modelname = "oppelt_rev_ss", compile = FALSE, deriv2 = pR <- P(trafo, modelname = "oppelt_rev_par", compile = FALSE, deriv2 = TRUE, derivMode = dm) compile(gR, xR, pSSR, pR, eR, output = "oppelt_rev", cores = getOption("dMod2.cores")) objR <- normL2(data, gR * xR * pSSR * pR, eR) + constraintL2(mu, sigma = sigma) + - constraintStability(pSSR, pR) + constraintStability(pSSR, pR, width = rampWidth) ## ---- gradients # the data term, whose gradient the prior balances at the optimum, so that it does not vanish diff --git a/examples/oppeltNPJSystBiolAppl2018/symmetries.R b/examples/oppeltNPJSystBiolAppl2018/symmetries.R index 3ca16cd4..80a77d2e 100644 --- a/examples/oppeltNPJSystBiolAppl2018/symmetries.R +++ b/examples/oppeltNPJSystBiolAppl2018/symmetries.R @@ -11,7 +11,7 @@ if (!exists("obj")) source("model.R") doses <- data.frame(dose_TNF = c(0, 1), row.names = c("control", "TNF")) # without the bleaching terms: in the resting control the states are constant, and the slope of # an imaging readout is the bleaching rate alone -unbleached <- eqnvec(sub(" - tau_.*$", "", observables), names = names(observables)) +unbleached <- setNames(eqnvec(sub(" - tau_.*$", "", observables)), names(observables)) symmetries <- symmetryDetection(reactions, unbleached, events = events, forcings = "TNF", conditions = doses, equilibrate = TRUE, reduceCQ = TRUE, reconstruct = TRUE, cores = getOption("dMod2.cores")) diff --git a/examples/pharmacometrics/README.md b/examples/pharmacometrics/README.md index c6dafd99..e9420575 100644 --- a/examples/pharmacometrics/README.md +++ b/examples/pharmacometrics/README.md @@ -93,7 +93,7 @@ plotStarts <- function(runs, title) { seconds <- do.call(rbind, lapply(names(runs), function(m) data.frame(method = m, seconds = runs[[m]]$seconds))) s <- ggplot2::ggplot(seconds, ggplot2::aes(method, seconds)) + ggplot2::geom_boxplot() + ggplot2::scale_y_log10(labels = scales::label_log()) + - ggplot2::labs(x = NULL, y = "seconds per fit, one core") + theme_dMod() + ggplot2::labs(x = NULL, y = "seconds per fit, one core") + theme_dMod2() cowplot::plot_grid(w, s, nrow = 1, rel_widths = c(2, 1)) } @@ -585,7 +585,7 @@ compileSeconds ``` #> theophylline warfarin mavoglurant -#> 26.972 38.035 152.680 +#> 27.201 33.187 100.286 ``` ## Diagnostics diff --git a/examples/pharmacometrics/analysis.R b/examples/pharmacometrics/analysis.R index 26447c92..922f745f 100644 --- a/examples/pharmacometrics/analysis.R +++ b/examples/pharmacometrics/analysis.R @@ -75,7 +75,7 @@ plotStarts <- function(runs, title) { seconds <- do.call(rbind, lapply(names(runs), function(m) data.frame(method = m, seconds = runs[[m]]$seconds))) s <- ggplot2::ggplot(seconds, ggplot2::aes(method, seconds)) + ggplot2::geom_boxplot() + ggplot2::scale_y_log10(labels = scales::label_log()) + - ggplot2::labs(x = NULL, y = "seconds per fit, one core") + theme_dMod() + ggplot2::labs(x = NULL, y = "seconds per fit, one core") + theme_dMod2() cowplot::plot_grid(w, s, nrow = 1, rel_widths = c(2, 1)) } diff --git a/examples/pharmacometrics/figures/unnamed-chunk-10-1.png b/examples/pharmacometrics/figures/unnamed-chunk-10-1.png index b9a09422..3443d1c6 100644 Binary files a/examples/pharmacometrics/figures/unnamed-chunk-10-1.png and b/examples/pharmacometrics/figures/unnamed-chunk-10-1.png differ diff --git a/examples/pharmacometrics/figures/unnamed-chunk-12-1.png b/examples/pharmacometrics/figures/unnamed-chunk-12-1.png index 93079b51..a37622c6 100644 Binary files a/examples/pharmacometrics/figures/unnamed-chunk-12-1.png and b/examples/pharmacometrics/figures/unnamed-chunk-12-1.png differ diff --git a/examples/pharmacometrics/figures/unnamed-chunk-12-2.png b/examples/pharmacometrics/figures/unnamed-chunk-12-2.png index 963e1e88..f2493737 100644 Binary files a/examples/pharmacometrics/figures/unnamed-chunk-12-2.png and b/examples/pharmacometrics/figures/unnamed-chunk-12-2.png differ diff --git a/examples/pharmacometrics/figures/unnamed-chunk-12-3.png b/examples/pharmacometrics/figures/unnamed-chunk-12-3.png index bcdc1f7e..8703d1c9 100644 Binary files a/examples/pharmacometrics/figures/unnamed-chunk-12-3.png and b/examples/pharmacometrics/figures/unnamed-chunk-12-3.png differ diff --git a/examples/pharmacometrics/figures/unnamed-chunk-12-4.png b/examples/pharmacometrics/figures/unnamed-chunk-12-4.png index 9560db33..b1d7d178 100644 Binary files a/examples/pharmacometrics/figures/unnamed-chunk-12-4.png and b/examples/pharmacometrics/figures/unnamed-chunk-12-4.png differ diff --git a/examples/pharmacometrics/figures/unnamed-chunk-12-5.png b/examples/pharmacometrics/figures/unnamed-chunk-12-5.png index 9d4b3b2f..0b2b3216 100644 Binary files a/examples/pharmacometrics/figures/unnamed-chunk-12-5.png and b/examples/pharmacometrics/figures/unnamed-chunk-12-5.png differ diff --git a/examples/pharmacometrics/figures/unnamed-chunk-12-6.png b/examples/pharmacometrics/figures/unnamed-chunk-12-6.png index f4ba3d38..320d4e61 100644 Binary files a/examples/pharmacometrics/figures/unnamed-chunk-12-6.png and b/examples/pharmacometrics/figures/unnamed-chunk-12-6.png differ diff --git a/examples/pharmacometrics/figures/unnamed-chunk-13-1.png b/examples/pharmacometrics/figures/unnamed-chunk-13-1.png index e9b8821b..5f76109d 100644 Binary files a/examples/pharmacometrics/figures/unnamed-chunk-13-1.png and b/examples/pharmacometrics/figures/unnamed-chunk-13-1.png differ diff --git a/examples/pharmacometrics/figures/unnamed-chunk-6-1.png b/examples/pharmacometrics/figures/unnamed-chunk-6-1.png index f46958fc..58a947d7 100644 Binary files a/examples/pharmacometrics/figures/unnamed-chunk-6-1.png and b/examples/pharmacometrics/figures/unnamed-chunk-6-1.png differ diff --git a/examples/pharmacometrics/figures/unnamed-chunk-6-2.png b/examples/pharmacometrics/figures/unnamed-chunk-6-2.png index 4493802b..d1bb6cdd 100644 Binary files a/examples/pharmacometrics/figures/unnamed-chunk-6-2.png and b/examples/pharmacometrics/figures/unnamed-chunk-6-2.png differ diff --git a/examples/pharmacometrics/figures/unnamed-chunk-6-3.png b/examples/pharmacometrics/figures/unnamed-chunk-6-3.png index ed037b16..100e9641 100644 Binary files a/examples/pharmacometrics/figures/unnamed-chunk-6-3.png and b/examples/pharmacometrics/figures/unnamed-chunk-6-3.png differ diff --git a/examples/pharmacometrics/figures/unnamed-chunk-6-4.png b/examples/pharmacometrics/figures/unnamed-chunk-6-4.png index c1834ba9..58fb1ec8 100644 Binary files a/examples/pharmacometrics/figures/unnamed-chunk-6-4.png and b/examples/pharmacometrics/figures/unnamed-chunk-6-4.png differ diff --git a/examples/pharmacometrics/figures/unnamed-chunk-6-5.png b/examples/pharmacometrics/figures/unnamed-chunk-6-5.png index bdbfe1c6..95c2194c 100644 Binary files a/examples/pharmacometrics/figures/unnamed-chunk-6-5.png and b/examples/pharmacometrics/figures/unnamed-chunk-6-5.png differ diff --git a/examples/pharmacometrics/figures/unnamed-chunk-6-6.png b/examples/pharmacometrics/figures/unnamed-chunk-6-6.png index bb683284..b9a6d879 100644 Binary files a/examples/pharmacometrics/figures/unnamed-chunk-6-6.png and b/examples/pharmacometrics/figures/unnamed-chunk-6-6.png differ diff --git a/examples/pharmacometrics/figures/unnamed-chunk-7-1.png b/examples/pharmacometrics/figures/unnamed-chunk-7-1.png index 80ea3a31..3c4cc512 100644 Binary files a/examples/pharmacometrics/figures/unnamed-chunk-7-1.png and b/examples/pharmacometrics/figures/unnamed-chunk-7-1.png differ diff --git a/examples/pharmacometrics/figures/unnamed-chunk-9-1.png b/examples/pharmacometrics/figures/unnamed-chunk-9-1.png index 86dbe7f5..4959369c 100644 Binary files a/examples/pharmacometrics/figures/unnamed-chunk-9-1.png and b/examples/pharmacometrics/figures/unnamed-chunk-9-1.png differ diff --git a/examples/pharmacometrics/figures/unnamed-chunk-9-2.png b/examples/pharmacometrics/figures/unnamed-chunk-9-2.png index d38fac95..ba1309af 100644 Binary files a/examples/pharmacometrics/figures/unnamed-chunk-9-2.png and b/examples/pharmacometrics/figures/unnamed-chunk-9-2.png differ diff --git a/examples/pharmacometrics/figures/unnamed-chunk-9-3.png b/examples/pharmacometrics/figures/unnamed-chunk-9-3.png index 9ec60aed..9dd1a5d8 100644 Binary files a/examples/pharmacometrics/figures/unnamed-chunk-9-3.png and b/examples/pharmacometrics/figures/unnamed-chunk-9-3.png differ diff --git a/examples/pharmacometrics/figures/unnamed-chunk-9-4.png b/examples/pharmacometrics/figures/unnamed-chunk-9-4.png index 7207ca46..f9ad08ca 100644 Binary files a/examples/pharmacometrics/figures/unnamed-chunk-9-4.png and b/examples/pharmacometrics/figures/unnamed-chunk-9-4.png differ diff --git a/examples/pharmacometrics/figures/unnamed-chunk-9-5.png b/examples/pharmacometrics/figures/unnamed-chunk-9-5.png index 88fccd03..ff7521c9 100644 Binary files a/examples/pharmacometrics/figures/unnamed-chunk-9-5.png and b/examples/pharmacometrics/figures/unnamed-chunk-9-5.png differ diff --git a/examples/pharmacometrics/figures/unnamed-chunk-9-6.png b/examples/pharmacometrics/figures/unnamed-chunk-9-6.png index 7240d3fb..e6684915 100644 Binary files a/examples/pharmacometrics/figures/unnamed-chunk-9-6.png and b/examples/pharmacometrics/figures/unnamed-chunk-9-6.png differ diff --git a/inst/code/AlyssaPetit.py b/inst/code/AlyssaPetit.py index 339f4bf1..ed349f81 100644 --- a/inst/code/AlyssaPetit.py +++ b/inst/code/AlyssaPetit.py @@ -14,8 +14,12 @@ # identical atoms share one coefficient, # - solutions stay lazy and small: they reference each other, the LP keeps # the references acyclic, and one resolution happens at output time. -# Where the greedy choice of unknowns runs into a dead end, the states whose -# solutions block it are left free and the search restarts. +# States whose own balance gives a ratio of positive sums are solved first. The +# cycles of the graph of states left are cut then, as in Rosenblatt et al. (2016), +# which fixes the free states and the rate constants to solve for; a side with +# separate rate constants is cut with free flux ratios only if nothing else solves. +# Where the greedy choice of unknowns then runs into a dead end, the unknowns whose +# solutions block it go last and the search restarts. import os import sys @@ -487,28 +491,31 @@ def _zero_states(states, fluxes, stoich, volumes): fluxes, stoich=nf, ns return states, fluxes, stoich, zero -def _atoms(states, fluxes, stoich): - # Expand every flux into atoms; the balance of state i is - # sum_a B[i][a] * atom_a with exact rational B. +def _atoms(states, fluxes, stoich, volumes=None): + # Expand every flux into atoms; the balance of state i, in amounts (times the + # volume of the state), is sum_a B[i][a] * atom_a with exact rational B. In + # amounts a conserved quantity across compartments is a rational row dependency. + scale=(lambda f, s: _amount_key(f*volumes.get(s, 1))) if volumes else (lambda f, s: f) index={} atoms=[] B=[dict() for _ in states] for f, col in zip(fluxes, stoich): - for t in sympy.Add.make_args(sympy.expand(f)): - coeff, mono=t.as_coeff_Mul() - if not coeff.is_positive: - raise ValueError('flux term '+str(t)+' is not positive') - if mono not in index: - index[mono]=len(atoms) - atoms.append(mono) - a=index[mono] - for i, s in enumerate(col): - if s!=0: - v=B[i].get(a, Fraction(0))+Fraction(int(s.p), int(s.q))*Fraction(int(coeff.p), int(coeff.q)) - if v==0: - B[i].pop(a, None) - else: - B[i][a]=v + for i, s in enumerate(col): + if s==0: + continue + for t in sympy.Add.make_args(sympy.expand(scale(f, states[i]))): + coeff, mono=t.as_coeff_Mul() + if not coeff.is_positive: + raise ValueError('flux term '+str(t)+' is not positive') + if mono not in index: + index[mono]=len(atoms) + atoms.append(mono) + a=index[mono] + v=B[i].get(a, Fraction(0))+Fraction(int(s.p), int(s.q))*Fraction(int(coeff.p), int(coeff.q)) + if v==0: + B[i].pop(a, None) + else: + B[i][a]=v return atoms, B def _linear_factor(atom, s): @@ -518,7 +525,7 @@ def _linear_factor(atom, s): return False return n.as_powers_dict().get(s, 0)==1 -def _candidates(states, atoms, neglect): +def _candidates(states, atoms, neglect, positive=()): # Symbols linear in at least one atom: states and rate constants. Per # symbol, the atoms linear in it (usable on the symbol side of an equation) and # the atoms it sits in otherwise (a denominator, a square), which the @@ -535,8 +542,8 @@ def _candidates(states, atoms, neglect): continue lin=[a for a in idx if _linear_factor(atoms[a], s)] # a rate constant whose fluxes all contain a neglected symbol would be - # solved as a ratio over it, and that symbol may be 0 - if lin and all(atoms[a].free_symbols & held for a in lin) and s not in states: + # solved as a ratio over it, and that symbol may be 0; a volume is not + if lin and all(atoms[a].free_symbols & (held-positive) for a in lin) and s not in states: continue if lin: cands[s]=lin @@ -821,8 +828,17 @@ def _reaches(start, target, deps): stack.extend(deps.get(x, ())) return False +def _ratio_symbol(state, j, names): + # r__, made unique against the names in `names`, which it joins. + nm='r_'+str(state)+'_'+str(j) + while names is not None and nm in names: + nm+='_' + if names is not None: + names.add(nm) + return sympy.Symbol(nm) + def _group_unknown(order, cands, nonlin, atoms, atom_syms, basis, Rnp, span, - sol, deps, B_rows, row_of, state_set): + sol, deps, B_rows, row_of, state_set, names=None): # One side of an unsolved state's balance, every atom of it with a separate # unsolved rate constant. The fluxes of that side share their sum by # new free flux ratios, flux_g = r_g * flux_g0 (v1.3's r_*), and the sum @@ -867,12 +883,12 @@ def _group_unknown(order, cands, nonlin, atoms, atom_syms, basis, Rnp, span, if not G: continue g0=G[0] - rho={p: sympy.Symbol('r_'+str(y)+'_'+str(i)) for i, p in enumerate(G) if i>0} + rho={p: _ratio_symbol(y, i, names) for i, p in enumerate(G) if i>0} return g0, [(p, rho[p]) for p in G[1:]], w, c, Au, phi return None def _greedy(order, cands, nonlin, atoms, basis, Rnp, r, check_time, B_rows, row_of, - quadratic=(), roots=None): + quadratic=(), roots=None, names=None): """Pick r unknowns, in `order`, each the first one an LP can isolate. States in `quadratic` may take the positive root of their own balance; they @@ -938,7 +954,7 @@ def root_of_some_state(): if picked is None: # no single unknown: let one side of a balance share a scale grp=_group_unknown(order, cands, nonlin, atoms, atom_syms, basis, Rnp, - span, sol, deps, B_rows, row_of, state_set) + span, sol, deps, B_rows, row_of, state_set, names) if grp is not None: g0, others, w, c, Au, phi=grp num=sympy.Add(*[sympy.Rational(v.numerator, v.denominator)*atoms[a] @@ -988,6 +1004,357 @@ def root_of_some_state(): return ([(u, sol[u]) for u in solved]+extra, ratios), None +# ––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– +# Cycle removal (Rosenblatt et al. 2016) +# ––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– + +def _state_graph(states, atoms, B): + # Edge x -> y if y appears in the balance of x; x -> x only if the balance is + # not linear in x. Solving each balance for the state it belongs to is acyclic iff + # the graph is. + state_set=set(states) + graph={} + for s, row in zip(states, B): + succ=set() + for a in row: + for y in atoms[a].free_symbols & state_set: + if y!=s or not _linear_factor(atoms[a], s): + succ.add(y) + graph[s]=succ + return graph + +def _simple_cycles(graph, cap=20000): + # Every simple directed cycle once, from the first of the nodes on it, at most cap. + nodes=sorted(graph, key=str) + index={n: i for i, n in enumerate(nodes)} + cycles=[] + for start in nodes: + stack=[(start, iter(sorted(graph[start], key=str)))] + path=[start] + on_path={start} + while stack: + node, it=stack[-1] + nxt=next(it, None) + if nxt is None: + stack.pop() + on_path.discard(path.pop()) + continue + if nxt==start: + cycles.append(list(path)) + if len(cycles)>=cap: + return cycles + elif index[nxt]>index[start] and nxt not in on_path: + path.append(nxt) + on_path.add(nxt) + stack.append((nxt, iter(sorted(graph[nxt], key=str)))) + return cycles + +def _derived_cqs(states, B, n_atoms): + # Basis of the conserved quantities: the left null space of the amount balances. + M=sympy.Matrix(len(states), n_atoms, + lambda i, a: sympy.Rational(B[i].get(a, 0).numerator, B[i].get(a, 0).denominator) + if a in B[i] else 0) + return [{s: v for s, v in zip(states, vec) if v!=0} for vec in M.T.nullspace()] + +def _given_cqs(givenCQs, states): + # Each given quantity "lhs = total" as the coefficients of the states in lhs. + out=[] + for cq in givenCQs: + lhs=str(cq).split('=')[0] + names=dict.fromkeys(sympy.Symbol(nm) for nm in re.findall(r'[A-Za-z_][A-Za-z0-9_]*', lhs)) + lhs=sympy.expand(parse_expr(lhs)) + vec={s: lhs.diff(s) for s in names if s in states} + vec={s: v for s, v in vec.items() if v!=0} + if vec: + out.append(vec) + return out + +def _side_type(counts): + # 1: a single flux term in no other balance, 2: several, each in no other + # balance, 3: cutting there rewires other balances. + if len(counts)==1 and counts[0]==1: + return 1 + if len(counts)>1 and all(c==1 for c in counts): + return 2 + return 3 + +def _ratio_side(side, atoms, cands, state_set, taken): + """Rate constants of a side whose flux terms have no common one, or None. + + Each term gets the rate constant linear in it that is linear in the fewest + terms; at least two distinct ones are needed. Returns {rate constant: terms}, + the first entry the one solved for. Every other rate constant has one term, + and no flux term contains two of them, so the ratios substitute into + single terms. + """ + assign={} + for a in side: + ps=[p for p in atoms[a].free_symbols if p in cands and p not in state_set + and p not in taken and a in cands[p]] + if not ps: + return None + assign.setdefault(min(ps, key=lambda q: (len(cands[q]), str(q))), []).append(a) + G=set(assign) + if len(G)<2 or sum(len(t)>1 for t in assign.values())>1: + return None + if any(len(at.free_symbols & G)>1 for at in atoms): + return None + g0=max(assign, key=lambda p: len(assign[p])) + return {g0: assign[g0], **{p: t for p, t in assign.items() if p!=g0}} + +def _unsolved_refs(names, solved): + # States reached from `names` through the solved states (state -> referenced + # states), the solved ones left out. + seen=set() + stack=list(names) + while stack: + y=stack.pop() + if y in seen: + continue + seen.add(y) + if y in solved: + stack.extend(solved[y]) + return {y for y in seen if y not in solved} + +def _state_graph_after(states, atoms, B, solved): + # The state graph with the states in `solved` contracted: an edge to a solved + # state leads to the states the solution for that state refers to. + graph=_state_graph(states, atoms, B) + return {s: _unsolved_refs(succ, solved) for s, succ in graph.items() if s not in solved} + +def _cut_cycles(states, atoms, B, cands, cqs, prio_rank, given, solved=None, locked=(), + ratios=True, replay=()): + """Free states and rate constants that remove every cycle of the state graph. + + A cycle is cut at a state of a conserved quantity, whose balance is then the + dependent one, or at a state whose balance on one side (influx or outflux) + has a rate constant common to all flux terms, which is solved instead of the + state. With `ratios`, a side whose flux terms have separate rate constants + is a cut as well: the fluxes of the side keep free ratios, and one rate + constant is solved. Cuts are ranked as in the publication: a rate + constant named in `priority` first and a state named there last, conserved + quantity, then side type, rewired balances, number of terms, number of + cycles through the state, and occurrence in other balances; a side with one + rate constant before one with ratios. States in `solved` (state -> + referenced states) are solved directly beforehand and leave the graph, rate + constants in `locked` are not cut at, and the cuts in `replay` are made + first, in their order. + + Returns (free states, rate constants, cuts, states on cycles left without a + cut, None), or, when a ratio cut ranks first, (.., .., cuts so far, .., + (state, {rate constant: flux terms of the side})) for the caller to + substitute the ratios and cut again. + """ + solved=solved or {} + graph=_state_graph_after(states, atoms, B, solved) + state_set=set(states) + row_of={s: i for i, s in enumerate(states)} + atom_rows={} + for i, row in enumerate(B): + for a in row: + atom_rows[a]=atom_rows.get(a, 0)+1 + cqs=[dict(c) for c in cqs] + used=[False]*len(cqs) + free, pivots, cuts=[], [], [] + taken=set(locked) + replay=list(replay) + + def rank(*names): + return min((prio_rank[str(x)] for x in names if str(x) in prio_rank), default=len(prio_rank)) + + while True: + if replay: + s, kind, x=replay.pop(0) + if kind=='cq': + x=next(k for k, c in enumerate(cqs) if not used[k] and c.get(s, 0)!=0) + sides=() + else: + sides=(list(B[row_of[s]]), []) + else: + cycles=_simple_cycles(graph) + if not cycles: + return free, pivots, cuts, set(), None + n_cyc={} + for cyc in cycles: + for y in cyc: + n_cyc[y]=n_cyc.get(y, 0)+1 + in_rhs={y: sum(1 for z, succ in graph.items() if z!=y and y in succ) for y in graph} + rows=[] + for s in sorted(n_cyc, key=str): + tail=(-n_cyc[s], in_rhs[s]) + # a given quantity keeps the first state on a cycle free + k=next((k for k, c in enumerate(cqs) if not used[k] and c.get(s, 0)!=0), None) + if k is not None: + first=0 if not given else list(cqs[k]).index(s) + rows.append(((len(prio_rank), str(s) in prio_rank, 0, first, 0, 0, 0)+tail+(0, str(s)), + ('cq', s, k, ()))) + continue + row=B[row_of[s]] + for sign in (1, -1): + side=[a for a, v in row.items() if (v>0)==(sign>0)] + if not side: + continue + ps=[p for p in cands if p not in state_set and p not in taken + and all(_linear_factor(atoms[a], p) for a in side)] + if ps: + G={min(ps, key=lambda q: (len(cands[q]), str(q))): side} + elif ratios: + G=_ratio_side(side, atoms, cands, state_set, taken) + if G is None: + continue + else: + continue + counts=[atom_rows[a] for a in side] + typ=_side_type(counts) + risk=sum(c-1 for c in counts) + rows.append(((rank(*G), str(s) in prio_rank, typ, 0, risk, + int(typ==3 and len(side)==1), len(side))+tail+(len(G)>1, str(s)), + ('pivot' if len(G)==1 else 'ratio', s, G, + (side, [a for a in row if a not in side])))) + if not rows: + return free, pivots, cuts, set(n_cyc), None + kind, s, x, sides=min(rows, key=lambda r: r[0])[1] + if kind=='ratio': + return free, pivots, cuts, set(n_cyc), (s, x) + if kind=='pivot': + x=next(iter(x)) + if kind=='cq': + # the remaining quantities no longer contain s + c=cqs[x] + for m, d in enumerate(cqs): + if m!=x and d.get(s, 0)!=0: + f=d[s]/c[s] + d={y: sympy.cancel(d.get(y, 0)-f*c.get(y, 0)) for y in set(d)|set(c)} + cqs[m]={y: v for y, v in d.items() if v!=0} + used[x]=True + else: + # a balance with the rate constant refers to the states of the solution for it + pivots.append(x) + taken.add(x) + via=set().union(*(atoms[a].free_symbols for a in sides[0]+sides[1])) & state_set + # free states are parameters, solved ones refer on + via=_unsolved_refs(via, solved) & set(graph) + for y, succ in graph.items(): + if y!=s and any(x in atoms[a].free_symbols for a in B[row_of[y]]): + succ|=via + free.append(s) + cuts.append((s, kind, x)) + del graph[s] + for succ in graph.values(): + succ.discard(s) + + +def _on_cycles(graph): + # Nodes on a directed cycle: a strongly connected component of two or more + # nodes, or a node with a loop (Tarjan, iterative). + index, low, stack, on=0, {}, [], set() + order={} + out=set() + for root in sorted(graph, key=str): + if root in order: + continue + work=[(root, iter(sorted(graph[root], key=str)))] + order[root]=low[root]=index + index+=1 + stack.append(root) + on.add(root) + while work: + v, it=work[-1] + w=next(it, None) + if w is not None: + if w not in graph: + continue + if w not in order: + order[w]=low[w]=index + index+=1 + stack.append(w) + on.add(w) + work.append((w, iter(sorted(graph[w], key=str)))) + elif w in on: + low[v]=min(low[v], order[w]) + continue + work.pop() + if work: + low[work[-1][0]]=min(low[work[-1][0]], low[v]) + if low[v]==order[v]: + scc=[] + while True: + x=stack.pop() + on.discard(x) + scc.append(x) + if x==v: + break + if len(scc)>1 or v in graph[v]: + out|=set(scc) + return out + +def _has_cut(s, row, atoms, cands, state_set, cqs, locked): + # Whether a cycle through s can be cut at s with the rate constants not locked. + if any(c.get(s, 0)!=0 for c in cqs): + return True + for sign in (1, -1): + side=[a for a, v in row.items() if (v>0)==(sign>0)] + if not side: + continue + if any(p not in state_set and p not in locked and all(_linear_factor(atoms[a], p) for a in side) + for p in cands): + return True + if _ratio_side(side, atoms, cands, state_set, locked) is not None: + return True + return False + +def _direct_pass(states, atoms, B, cands, neglect, cqs, keep=()): + """States solved from their own balance before the cycles are cut. + + A state qualifies if the balance is linear in it, with every term of the state + on one side and the rest on the other, so the solution is a ratio of positive + sums, and if the solution does not lead back to the state through the states + solved before. The rate constants in the solution are no longer cut at; a + state whose solution would leave a cycle without a cut stays for the cuts, as + do the states in `keep`. Returns ({state: states referenced}, locked rate constants). + """ + state_set=set(states) + row_of={s: i for i, s in enumerate(states)} + solved={} + locked=set() + progress=True + while progress: + progress=False + for i, y in enumerate(states): + if y in solved or y in keep or str(y) in neglect or y not in cands: + continue + row=B[i] + Au=set(cands[y]) + if any(a not in Au for a in row if y in atoms[a].free_symbols): + continue + if not (row and all((v<0)==(a in Au) for a, v in row.items()) + and any(v>0 for v in row.values()) and any(v<0 for v in row.values())): + continue + syms=set().union(*(atoms[a].free_symbols for a in row)) + refs=(syms & state_set)-{y} + reach=set() + stack=list(refs) + while stack: + x=stack.pop() + if x in reach: + continue + reach.add(x) + stack.extend(solved.get(x, ())) + if y in reach: + continue + trial={**solved, y: refs} + lock=locked|(syms-state_set) + graph=_state_graph_after(states, atoms, B, trial) + if any(_has_cut(x, B[row_of[x]], atoms, cands, state_set, cqs, locked) and + not _has_cut(x, B[row_of[x]], atoms, cands, state_set, cqs, lock) + for x in _on_cycles(graph)): + continue + solved=trial + locked=lock + progress=True + return solved, locked + + # ––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– # Entry point, same interface as v1.3 # ––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– @@ -1011,37 +1378,25 @@ def Alyssa(model_csv, injections=(), givenCQs=(), neglect=(), testSteady='fast', states, fluxes, stoich=_read_model(filename, injections) ODE_states=list(states) ODE=[sympy.Add(*[col[i]*f for f, col in zip(fluxes, stoich)]) for i in range(len(states))] - states, fluxes, stoich, zero=_zero_states(states, fluxes, stoich, - ParseVolumes(volumes)) - atoms, B=_atoms(states, fluxes, stoich) - basis=_row_basis(B, len(atoms)) + vol=ParseVolumes(volumes) + states, fluxes, stoich, zero=_zero_states(states, fluxes, stoich, vol) + vol_syms=set().union(*(v.free_symbols for v in vol.values())) if vol else set() + + def balances(fluxes, held, positive=frozenset()): + # Balances in amounts: a quantity conserved across compartments is a row dependency. + atoms, B=_atoms(states, fluxes, stoich, vol) + basis=_row_basis(B, len(atoms)) + Rnp=numpy.array([[float(row.get(a, 0)) for a in range(len(atoms))] for row in basis]) + # volumes and flux ratios are positive, a neglected rate constant may be 0 + cands_all, nonlin=_candidates(states, atoms, held, vol_syms|set(positive)) + cqs=_given_cqs(givenCQs, states) if givenCQs else _derived_cqs(states, B, len(atoms)) + return atoms, B, basis, Rnp, cands_all, nonlin, cqs + + atoms, B, basis, Rnp, cands_all, nonlin, cqs=balances(fluxes, neglect) r=len(basis) - Rnp=numpy.array([[float(row.get(a, 0)) for a in range(len(atoms))] for row in basis]) - cands_all, nonlin=_candidates(states, atoms, neglect) - # a given conserved quantity keeps one of the quantity states free, the first by - # default; if that state's balance is left, the next one is tried - cq_groups=[] - for cq in givenCQs: - lhs=str(cq).split('=')[0] - g=[sympy.Symbol(nm) for nm in re.findall(r'[A-Za-z_][A-Za-z0-9_]*', lhs)] - g=[x for x in dict.fromkeys(g) if x in states] - if g: - cq_groups.append(g) - cq_pick=[0]*len(cq_groups) - - def keep_free(): - free=[] - for g, k in zip(cq_groups, cq_pick): - rest=[x for x in g if x not in free] - if k1 else '')+ + ' of '+', '.join(left)+' '+('are' if len(left)>1 else 'is')+ + ' left without a positive unknown.', flush=True) + print(' neglect, priority'+('' if solveQuadratic else ' or solveQuadratic = TRUE')+ + ' change which unknowns are solved.', flush=True) + else: + print('No positive steady state found.', flush=True) + _print_notes() + return 0 + return _finish(solution, ratios, cq_free, states, state_set, ODE, ODE_states, zero, + injections, simplify, testSteady, check_time, t0) + + +def _run_greedy(states, atoms, B, basis, Rnp, r, cands_all, nonlin, neglect, prio_rank, + solveQuadratic, check_time, row_of, names, direct, cut): + # The greedy runs after one choice of direct solutions and cuts. Returns + # (solution or None, ratios of the greedy, states freed by conserved quantities). + free, pivots, cuts, cyclic, _=cut + state_set=set(states) + if direct: + _say(' solved directly: '+', '.join(str(y) for y in direct)) + if cuts: + _say(' cycles cut at '+', '.join(str(s)+(' (conserved quantity)' if kind=='cq' + else ' ('+str(x)+')') for s, kind, x in cuts)) + # a cycle without a cut leaves the choice among all rate constants to the greedy runs + if cyclic: + _say(' no cut for the cycles through '+', '.join(sorted(str(x) for x in cyclic))) + cands={x: v for x, v in cands_all.items() + if (x in state_set and x not in free) or x in pivots or (cyclic and x not in state_set)} + cq_free=[s for s, kind, _ in cuts if kind=='cq'] + _say('') # A state whose flux terms occur in no other balance (an mRNA, a protein) - # is safe to solve first. One that hands mass on (a precursor, a chain, a - # receptor pool) would put the rate constants of the state into the solution, and a - # later balance may need exactly those: such states come after the rate - # constants. + # is safe to solve first. One that hands mass on would put the rate constants + # of the state into the solution, and a later balance may need exactly those: + # such states come after the rate constants. atom_rows={} for i, row in enumerate(B): for a in row: atom_rows.setdefault(a, set()).add(i) isolated={s for i, s in enumerate(states) if all(atom_rows[a]=={i} for a in B[i])} + first={y: i for i, y in enumerate(direct)} def ordering(defer): - # user priority first, then isolated states, rate constants, coupled - # states, and last whatever blocked a former run + # direct solutions first, user priority, then isolated states, rate + # constants, coupled states, and last whatever blocked a former run def key(s): tier=0 if s in isolated else (2 if s in state_set else 1) - return (0 if str(s) in prio_rank else 1, prio_rank.get(str(s), 0), - s in defer, tier, str(s)) + return (first.get(s, len(first)), 0 if str(s) in prio_rank else 1, + prio_rank.get(str(s), 0), s in defer, tier, str(s)) return sorted(cands, key=key) + # Greedy runs over the unknowns, each moving the unknowns that blocked the + # last run to the end. ratios=[] solution=None - blockers=None + defer=set() no_root=set() + prev=set() attempt=0 - for rotation in range(1+sum(len(g) for g in cq_groups)): - defer=set() - no_root=set() - prev=set() - for _ in range(4*len(cands)+len(states)+1): - attempt+=1 - order=ordering(defer) - quadratic=[] - if solveQuadratic: - quadratic=[s for s in order if s in state_set]+\ - sorted((s for s in states if s not in cands and str(s) not in neglect - and s not in cq_free), key=str) - quadratic=[s for s in quadratic if s not in no_root] - roots=[] - result, blockers=_greedy(order, cands, nonlin, atoms, basis, Rnp, r, check_time, - B, {s: i for i, s in enumerate(states)}, quadratic, roots) - solution=None if result is None else result[0] - if solution is not None or blockers is None: - ratios=result[1] if result is not None else [] - break - n_used, left, used=_STUCK[0] - head=' attempt '+str(attempt)+': '+str(n_used)+'/'+str(r)+' balances, left '+', '.join(left) - # full trace: which unknowns this attempt solved differently - gained=[u for u in used if u not in prev] - lost=sorted(prev-set(used)) - if prev and (gained or lost): - _trace(' '+' '.join(['+'+u for u in gained]+['-'+u for u in lost])) - prev=set(used) - # a kept state of a conserved quantity is changed before anything else - left_syms={sympy.Symbol(x) for x in left} - if any(cq_pick[i]+1 conserved quantity '+' + '.join(str(x) for x in cq_groups[moved])+': '+ - str(cq_free[moved])+' free instead of '+str(old)) - _say('') + defer|=new + _say(head+'; next: '+', '.join(sorted(str(s) for s in new))+' last') if no_root and solution is not None: _note('no root for '+', '.join(sorted(str(s) for s in no_root))+ ': it would take a balance another unknown needs') if attempt>1: _say('') - if solution is None: - if check_time(): - print('No positive steady state found: walltime exceeded.', flush=True) - elif _STUCK[0] is not None: - left=_STUCK[0][1] - print('No positive steady state found: the balance'+('s' if len(left)>1 else '')+ - ' of '+', '.join(left)+' '+('are' if len(left)>1 else 'is')+ - ' left without a positive unknown.', flush=True) - print(' neglect, priority'+('' if solveQuadratic else ' or solveQuadratic = TRUE')+ - ' change which unknowns are solved.', flush=True) - else: - print('No positive steady state found.', flush=True) - _print_notes() - return 0 + return solution, ratios, cq_free + +def _finish(solution, ratios, cq_free, states, state_set, ODE, ODE_states, zero, + injections, simplify, testSteady, check_time, t0): + # Output of a solution: simplification, the steady-state test, resolution. n_state=sum(1 for u, _ in solution if u in state_set) if ratios: _say(' '+str(len(ratios))+' new ratio parameter(s): '+ diff --git a/man/P.Rd b/man/P.Rd index 750713c5..65099e42 100644 --- a/man/P.Rd +++ b/man/P.Rd @@ -122,6 +122,14 @@ as a sparse \code{Matrix}, assembled from the blocks of the conditions; \code{\l factorizes it where the argument \code{sparse} takes the sparse path, and \code{\link[=vcov.objlist]{vcov()}} solves it for the columns of \code{which}. +\code{hessian = "expected"} returns, in place of the Gauss-Newton Hessian of the +forward sweep, the expected (Fisher) information of the likelihood: +\code{2 / sigma^2} in the prediction and \code{4 / sigma^2} in sigma per data point, +positive semidefinite also where an error model depends on the parameters. +The Gauss-Newton Hessian keeps the exact curvature of the loss in the +prediction and sigma, which is indefinite there and shows the optimizer a +saddle. + With \code{deriv = FALSE} it returns the value alone. } diff --git a/man/Pexpl.Rd b/man/Pexpl.Rd index a21a9287..5ddde2f5 100644 --- a/man/Pexpl.Rd +++ b/man/Pexpl.Rd @@ -126,6 +126,14 @@ as a sparse \code{Matrix}, assembled from the blocks of the conditions; \code{\l factorizes it where the argument \code{sparse} takes the sparse path, and \code{\link[=vcov.objlist]{vcov()}} solves it for the columns of \code{which}. +\code{hessian = "expected"} returns, in place of the Gauss-Newton Hessian of the +forward sweep, the expected (Fisher) information of the likelihood: +\code{2 / sigma^2} in the prediction and \code{4 / sigma^2} in sigma per data point, +positive semidefinite also where an error model depends on the parameters. +The Gauss-Newton Hessian keeps the exact curvature of the loss in the +prediction and sigma, which is indefinite there and shows the optimizer a +saddle. + With \code{deriv = FALSE} it returns the value alone. } diff --git a/man/Pimpl.Rd b/man/Pimpl.Rd index 2677f6bd..0394b509 100644 --- a/man/Pimpl.Rd +++ b/man/Pimpl.Rd @@ -74,9 +74,6 @@ absolute value in the units of the rates; default \code{0}. A positive value admits a resting state that departs from rest more slowly than a time scale of interest, as near a Hopf bifurcation. \code{\link[=constraintStability]{constraintStability()}} reaches the weight at \code{stabilityTol}.} -\item{\code{stabilityMargin}}{The width of the ramp of \code{\link[=constraintStability]{constraintStability()}} -below \code{stabilityTol}, relative to the largest eigenvalue modulus on the -manifold of the conserved quantities; default \code{1e-6}.} \item{\code{nStarts}}{Random starts after the deterministic ones, default \code{20}.} \item{\code{startRange}}{Range of a random start, drawn uniformly per @@ -174,6 +171,14 @@ as a sparse \code{Matrix}, assembled from the blocks of the conditions; \code{\l factorizes it where the argument \code{sparse} takes the sparse path, and \code{\link[=vcov.objlist]{vcov()}} solves it for the columns of \code{which}. +\code{hessian = "expected"} returns, in place of the Gauss-Newton Hessian of the +forward sweep, the expected (Fisher) information of the likelihood: +\code{2 / sigma^2} in the prediction and \code{4 / sigma^2} in sigma per data point, +positive semidefinite also where an error model depends on the parameters. +The Gauss-Newton Hessian keeps the exact curvature of the loss in the +prediction and sigma, which is indefinite there and shows the optimizer a +saddle. + With \code{deriv = FALSE} it returns the value alone. } diff --git a/man/Xd.Rd b/man/Xd.Rd index 5fc90bfa..27fd5f7d 100644 --- a/man/Xd.Rd +++ b/man/Xd.Rd @@ -86,6 +86,14 @@ as a sparse \code{Matrix}, assembled from the blocks of the conditions; \code{\l factorizes it where the argument \code{sparse} takes the sparse path, and \code{\link[=vcov.objlist]{vcov()}} solves it for the columns of \code{which}. +\code{hessian = "expected"} returns, in place of the Gauss-Newton Hessian of the +forward sweep, the expected (Fisher) information of the likelihood: +\code{2 / sigma^2} in the prediction and \code{4 / sigma^2} in sigma per data point, +positive semidefinite also where an error model depends on the parameters. +The Gauss-Newton Hessian keeps the exact curvature of the loss in the +prediction and sigma, which is indefinite there and shows the optimizer a +saddle. + With \code{deriv = FALSE} it returns the value alone. } diff --git a/man/Xf.Rd b/man/Xf.Rd index 0f990ed0..f4167886 100644 --- a/man/Xf.Rd +++ b/man/Xf.Rd @@ -115,6 +115,14 @@ as a sparse \code{Matrix}, assembled from the blocks of the conditions; \code{\l factorizes it where the argument \code{sparse} takes the sparse path, and \code{\link[=vcov.objlist]{vcov()}} solves it for the columns of \code{which}. +\code{hessian = "expected"} returns, in place of the Gauss-Newton Hessian of the +forward sweep, the expected (Fisher) information of the likelihood: +\code{2 / sigma^2} in the prediction and \code{4 / sigma^2} in sigma per data point, +positive semidefinite also where an error model depends on the parameters. +The Gauss-Newton Hessian keeps the exact curvature of the loss in the +prediction and sigma, which is indefinite there and shows the optimizer a +saddle. + With \code{deriv = FALSE} it returns the value alone. } diff --git a/man/Xs.Rd b/man/Xs.Rd index c4b6c725..35cd92f8 100644 --- a/man/Xs.Rd +++ b/man/Xs.Rd @@ -228,6 +228,14 @@ as a sparse \code{Matrix}, assembled from the blocks of the conditions; \code{\l factorizes it where the argument \code{sparse} takes the sparse path, and \code{\link[=vcov.objlist]{vcov()}} solves it for the columns of \code{which}. +\code{hessian = "expected"} returns, in place of the Gauss-Newton Hessian of the +forward sweep, the expected (Fisher) information of the likelihood: +\code{2 / sigma^2} in the prediction and \code{4 / sigma^2} in sigma per data point, +positive semidefinite also where an error model depends on the parameters. +The Gauss-Newton Hessian keeps the exact curvature of the loss in the +prediction and sigma, which is indefinite there and shows the optimizer a +saddle. + With \code{deriv = FALSE} it returns the value alone. } diff --git a/man/Xt.Rd b/man/Xt.Rd index acbafaa8..3db03a3d 100644 --- a/man/Xt.Rd +++ b/man/Xt.Rd @@ -81,6 +81,14 @@ as a sparse \code{Matrix}, assembled from the blocks of the conditions; \code{\l factorizes it where the argument \code{sparse} takes the sparse path, and \code{\link[=vcov.objlist]{vcov()}} solves it for the columns of \code{which}. +\code{hessian = "expected"} returns, in place of the Gauss-Newton Hessian of the +forward sweep, the expected (Fisher) information of the likelihood: +\code{2 / sigma^2} in the prediction and \code{4 / sigma^2} in sigma per data point, +positive semidefinite also where an error model depends on the parameters. +The Gauss-Newton Hessian keeps the exact curvature of the loss in the +prediction and sigma, which is indefinite there and shows the optimizer a +saddle. + With \code{deriv = FALSE} it returns the value alone. } diff --git a/man/Y.Rd b/man/Y.Rd index 56a5386a..ab38e60c 100644 --- a/man/Y.Rd +++ b/man/Y.Rd @@ -152,6 +152,14 @@ as a sparse \code{Matrix}, assembled from the blocks of the conditions; \code{\l factorizes it where the argument \code{sparse} takes the sparse path, and \code{\link[=vcov.objlist]{vcov()}} solves it for the columns of \code{which}. +\code{hessian = "expected"} returns, in place of the Gauss-Newton Hessian of the +forward sweep, the expected (Fisher) information of the likelihood: +\code{2 / sigma^2} in the prediction and \code{4 / sigma^2} in sigma per data point, +positive semidefinite also where an error model depends on the parameters. +The Gauss-Newton Hessian keeps the exact curvature of the loss in the +prediction and sigma, which is indefinite there and shows the optimizer a +saddle. + With \code{deriv = FALSE} it returns the value alone. } diff --git a/man/constraintL2.Rd b/man/constraintL2.Rd index 66abe1e9..c8661c5d 100644 --- a/man/constraintL2.Rd +++ b/man/constraintL2.Rd @@ -104,6 +104,14 @@ as a sparse \code{Matrix}, assembled from the blocks of the conditions; \code{\l factorizes it where the argument \code{sparse} takes the sparse path, and \code{\link[=vcov.objlist]{vcov()}} solves it for the columns of \code{which}. +\code{hessian = "expected"} returns, in place of the Gauss-Newton Hessian of the +forward sweep, the expected (Fisher) information of the likelihood: +\code{2 / sigma^2} in the prediction and \code{4 / sigma^2} in sigma per data point, +positive semidefinite also where an error model depends on the parameters. +The Gauss-Newton Hessian keeps the exact curvature of the loss in the +prediction and sigma, which is indefinite there and shows the optimizer a +saddle. + With \code{deriv = FALSE} it returns the value alone. } diff --git a/man/constraintStability.Rd b/man/constraintStability.Rd index 2dd22ac8..de70b4bd 100644 --- a/man/constraintStability.Rd +++ b/man/constraintStability.Rd @@ -4,7 +4,14 @@ \alias{constraintStability} \title{Stability of the steady state of Pimpl() as a constraint} \usage{ -constraintStability(pSS, p = NULL, weight = 100, attrName = "stability") +constraintStability( + pSS, + p = NULL, + weight = 100, + width = 0, + margin = 1e-06, + attrName = "stability" +) } \arguments{ \item{pSS}{A parfn of \code{\link[=Pimpl]{Pimpl()}}, built with \code{deriv2 = TRUE}.} @@ -16,6 +23,15 @@ parameters of the objective.} eigenvalue reaches the stability tolerance, in units of \eqn{-2 \log L}. Default 100.} +\item{width}{\eqn{d}, the least width of the ramp in the units of the rates, +default \code{0}. A ramp wide against the change of the real parts over a step +shows the boundary to the model of a trust-region step before the step +crosses it; a resting state whose slowest mode decays faster than +\code{width} is not affected.} + +\item{margin}{\eqn{m}, the least width of the ramp relative to the largest +eigenvalue modulus, the precision of the eigenvalues; default \code{1e-6}.} + \item{attrName}{Name of the attribute that holds the value of the term, default \code{"stability"}.} } @@ -31,15 +47,17 @@ quantities, it adds the square of the residual \eqn{\sqrt{w}\, r^{3/2}} for \eqn{r \le 1} and \eqn{\sqrt{w}\, (1 + 3 (r - 1) / 2)} beyond, with \eqn{r = \max(0, \mathrm{Re}\,\lambda - \lambda_0) / (\lambda_{tol} - \lambda_0)}. -With \eqn{s} the largest eigenvalue modulus there, \eqn{\lambda_{tol}} the -\code{stabilityTol} and \eqn{m} the \code{stabilityMargin} of the \code{controlsPTC} of -\code{pSS}, the ramp begins at \eqn{\lambda_0 = \lambda_{tol} - m s}. The term is -zero on a steady state whose leading real part lies more than \eqn{m s} -below \eqn{\lambda_{tol}}, reaches the weight \eqn{w} for each eigenvalue, both of -a complex pair, whose real part reaches \eqn{\lambda_{tol}}, and grows -quadratically beyond. Value, gradient and Gauss-Newton Hessian are -continuous. Steady states that agree in the parameters, resting states and -start values they read count once. The gradient is exact. +With \eqn{\lambda_{tol}} the \code{stabilityTol} of the \code{controlsPTC} of \code{pSS}, +the ramp begins at \eqn{\lambda_0 = \lambda_{tol} - \max(d, m s)}, with +\eqn{d} the \code{width}, \eqn{m} the \code{margin} and \eqn{s} the largest +eigenvalue modulus on the manifold. The term is zero on a steady state +whose leading real part lies below \eqn{\lambda_0}, reaches the weight +\eqn{w} for each eigenvalue, both of a complex pair, whose real part +reaches \eqn{\lambda_{tol}}, and grows quadratically beyond. Value, +gradient and Gauss-Newton Hessian are continuous. Steady states that agree in the parameters, resting states and +start values they read count once. The gradient is exact; eigenvalues that +coincide within the precision of the eigenvalues take the mean of their +derivatives, exact where they stay equal. } \details{ The term is an assumption of the model, that the system rests where diff --git a/man/dMod_colors.Rd b/man/dMod2_colors.Rd similarity index 51% rename from man/dMod_colors.Rd rename to man/dMod2_colors.Rd index 949b840e..0312e6f2 100644 --- a/man/dMod_colors.Rd +++ b/man/dMod2_colors.Rd @@ -1,18 +1,18 @@ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/plots.R -\name{dMod_colors} -\alias{dMod_colors} -\title{Seed Colors of the dMod Palette} +\name{dMod2_colors} +\alias{dMod2_colors} +\title{Seed Colors of the dMod2 Palette} \format{ A character vector of hex color codes. } \usage{ -dMod_colors +dMod2_colors } \description{ The ten qualitative house colors. They are not colorblind-safe, see -\code{\link[=dMod_palettes]{dMod_palettes()}} for alternatives. +\code{\link[=dMod2_palettes]{dMod2_palettes()}} for alternatives. } \seealso{ -\link{dMod_colors_cb}, \code{\link[=dMod_palette]{dMod_palette()}} +\link{dMod2_colors_cb}, \code{\link[=dMod2_palette]{dMod2_palette()}} } diff --git a/man/dMod_colors_cb.Rd b/man/dMod2_colors_cb.Rd similarity index 70% rename from man/dMod_colors_cb.Rd rename to man/dMod2_colors_cb.Rd index b3e77e05..b4eb5024 100644 --- a/man/dMod_colors_cb.Rd +++ b/man/dMod2_colors_cb.Rd @@ -1,18 +1,18 @@ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/plots.R -\name{dMod_colors_cb} -\alias{dMod_colors_cb} +\name{dMod2_colors_cb} +\alias{dMod2_colors_cb} \title{Colorblind-Safe Seed Colors} \format{ A character vector of 20 hex color codes. } \usage{ -dMod_colors_cb +dMod2_colors_cb } \description{ Okabe-Ito palette, extended to twenty colorblind-safe colors. The first eight are the Okabe-Ito colors. } \seealso{ -\link{dMod_colors}, \code{\link[=dMod_palette]{dMod_palette()}} +\link{dMod2_colors}, \code{\link[=dMod2_palette]{dMod2_palette()}} } diff --git a/man/dMod2_gradient.Rd b/man/dMod2_gradient.Rd new file mode 100644 index 00000000..12b53877 --- /dev/null +++ b/man/dMod2_gradient.Rd @@ -0,0 +1,26 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/plots.R +\name{dMod2_gradient} +\alias{dMod2_gradient} +\alias{dMod2_gradient_cb} +\alias{dMod2_divergent} +\alias{dMod2_divergent_cb} +\title{Continuous dMod2 Color Ramps} +\format{ +Character vectors of hex color codes. +} +\usage{ +dMod2_gradient + +dMod2_gradient_cb + +dMod2_divergent + +dMod2_divergent_cb +} +\description{ +\code{dMod2_gradient} is the sequential house ramp, \code{dMod2_divergent} the diverging +one; \code{dMod2_gradient_cb} and \code{dMod2_divergent_cb} are their colorblind-safe +counterparts and the defaults of \code{\link[=scale_color_dMod2_c]{scale_color_dMod2_c()}} and +\code{\link[=scale_color_dMod2_div]{scale_color_dMod2_div()}}. See \code{\link[=dMod2_palettes]{dMod2_palettes()}} for the full set. +} diff --git a/man/dMod_palette.Rd b/man/dMod2_palette.Rd similarity index 75% rename from man/dMod_palette.Rd rename to man/dMod2_palette.Rd index 1fb2ec7e..abc5814b 100644 --- a/man/dMod_palette.Rd +++ b/man/dMod2_palette.Rd @@ -1,15 +1,15 @@ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/plots.R -\name{dMod_palette} -\alias{dMod_palette} -\title{Generate Distinct Colors from a dMod Palette} +\name{dMod2_palette} +\alias{dMod2_palette} +\title{Generate Distinct Colors from a dMod2 Palette} \usage{ -dMod_palette(n, palette = "okabe") +dMod2_palette(n, palette = "okabe") } \arguments{ \item{n}{Integer, number of colors.} -\item{palette}{Name of a qualitative palette, see \code{\link[=dMod_palettes]{dMod_palettes()}}. +\item{palette}{Name of a qualitative palette, see \code{\link[=dMod2_palettes]{dMod2_palettes()}}. Defaults to \code{"okabe"}.} } \value{ @@ -22,6 +22,6 @@ from \code{\link[grDevices:hcl.colors]{grDevices::hcl.colors()}} otherwise. Thes colorblind-safe; a colorblind-safe palette warns when it runs out of seeds. } \examples{ -dMod_palette(3) -dMod_palette(3, palette = "muted") +dMod2_palette(3) +dMod2_palette(3, palette = "muted") } diff --git a/man/dMod_palettes.Rd b/man/dMod2_palettes.Rd similarity index 59% rename from man/dMod_palettes.Rd rename to man/dMod2_palettes.Rd index 86e809d1..3ab8fea6 100644 --- a/man/dMod_palettes.Rd +++ b/man/dMod2_palettes.Rd @@ -1,10 +1,10 @@ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/plots.R -\name{dMod_palettes} -\alias{dMod_palettes} -\title{Overview of the dMod Palettes} +\name{dMod2_palettes} +\alias{dMod2_palettes} +\title{Overview of the dMod2 Palettes} \usage{ -dMod_palettes(type = NULL) +dMod2_palettes(type = NULL) } \arguments{ \item{type}{\code{NULL} (default) for all palettes, or any of \code{"qualitative"}, @@ -16,10 +16,10 @@ colors), \code{dE} (smallest pairwise CIE2000 color distance under normal and simulated dichromatic vision) and \code{colorblind} (\code{dE >= 10}). } \description{ -One row per palette. Pass any of the names as \code{palette} to \code{\link[=dMod_palette]{dMod_palette()}}, -\code{\link[=scale_color_dMod]{scale_color_dMod()}}, \code{\link[=scale_color_dMod_c]{scale_color_dMod_c()}} or \code{\link[=scale_color_dMod_div]{scale_color_dMod_div()}}. +One row per palette. Pass any of the names as \code{palette} to \code{\link[=dMod2_palette]{dMod2_palette()}}, +\code{\link[=scale_color_dMod2]{scale_color_dMod2()}}, \code{\link[=scale_color_dMod2_c]{scale_color_dMod2_c()}} or \code{\link[=scale_color_dMod2_div]{scale_color_dMod2_div()}}. } \examples{ -dMod_palettes() -dMod_palettes("qualitative") +dMod2_palettes() +dMod2_palettes("qualitative") } diff --git a/man/dMod_gradient.Rd b/man/dMod_gradient.Rd deleted file mode 100644 index 485d388f..00000000 --- a/man/dMod_gradient.Rd +++ /dev/null @@ -1,26 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/plots.R -\name{dMod_gradient} -\alias{dMod_gradient} -\alias{dMod_gradient_cb} -\alias{dMod_divergent} -\alias{dMod_divergent_cb} -\title{Continuous dMod Color Ramps} -\format{ -Character vectors of hex color codes. -} -\usage{ -dMod_gradient - -dMod_gradient_cb - -dMod_divergent - -dMod_divergent_cb -} -\description{ -\code{dMod_gradient} is the sequential house ramp, \code{dMod_divergent} the diverging -one; \code{dMod_gradient_cb} and \code{dMod_divergent_cb} are their colorblind-safe -counterparts and the defaults of \code{\link[=scale_color_dMod_c]{scale_color_dMod_c()}} and -\code{\link[=scale_color_dMod_div]{scale_color_dMod_div()}}. See \code{\link[=dMod_palettes]{dMod_palettes()}} for the full set. -} diff --git a/man/dModfn.Rd b/man/dModfn.Rd index 5e462189..d7d307fd 100644 --- a/man/dModfn.Rd +++ b/man/dModfn.Rd @@ -71,6 +71,14 @@ as a sparse \code{Matrix}, assembled from the blocks of the conditions; \code{\l factorizes it where the argument \code{sparse} takes the sparse path, and \code{\link[=vcov.objlist]{vcov()}} solves it for the columns of \code{which}. +\code{hessian = "expected"} returns, in place of the Gauss-Newton Hessian of the +forward sweep, the expected (Fisher) information of the likelihood: +\code{2 / sigma^2} in the prediction and \code{4 / sigma^2} in sigma per data point, +positive semidefinite also where an error model depends on the parameters. +The Gauss-Newton Hessian keeps the exact curvature of the loss in the +prediction and sigma, which is indefinite there and shows the optimizer a +saddle. + With \code{deriv = FALSE} it returns the value alone. } diff --git a/man/datapointL2.Rd b/man/datapointL2.Rd index 9681efff..dd78da71 100644 --- a/man/datapointL2.Rd +++ b/man/datapointL2.Rd @@ -111,6 +111,14 @@ as a sparse \code{Matrix}, assembled from the blocks of the conditions; \code{\l factorizes it where the argument \code{sparse} takes the sparse path, and \code{\link[=vcov.objlist]{vcov()}} solves it for the columns of \code{which}. +\code{hessian = "expected"} returns, in place of the Gauss-Newton Hessian of the +forward sweep, the expected (Fisher) information of the likelihood: +\code{2 / sigma^2} in the prediction and \code{4 / sigma^2} in sigma per data point, +positive semidefinite also where an error model depends on the parameters. +The Gauss-Newton Hessian keeps the exact curvature of the loss in the +prediction and sigma, which is indefinite there and shows the optimizer a +saddle. + With \code{deriv = FALSE} it returns the value alone. } diff --git a/man/discreteSymmetries.Rd b/man/discreteSymmetries.Rd index 5a6bdd8f..2e532d57 100644 --- a/man/discreteSymmetries.Rd +++ b/man/discreteSymmetries.Rd @@ -14,9 +14,7 @@ discreteSymmetries( ) } \arguments{ -\item{object}{A \code{symmetrydetection} result from \code{\link[=symmetryDetection]{symmetryDetection()}} of a model -with one condition and no events, switches or unknown inputs, detected without -\code{equilibrate} and \code{reduceCQ}.} +\item{object}{A \code{symmetrydetection} result from \code{\link[=symmetryDetection]{symmetryDetection()}}.} \item{order}{Highest Taylor coefficient; \code{NULL} (default) twice the number of coordinates.} diff --git a/man/distributedComputing.Rd b/man/distributedComputing.Rd index 14d820b3..95cbc111 100644 --- a/man/distributedComputing.Rd +++ b/man/distributedComputing.Rd @@ -118,7 +118,9 @@ tasks of a SLURM job, and a worker runs the tasks dealt to it one after the othe for \code{"localhost"} and in the home directory of a remote node. The job manifest \code{job.rds} lies in the local \verb{_folder} and in that of every remote node. A job of the same name that still runs there is an error, also when it -was submitted from another machine. Every job is registered in +was submitted from another machine, and so is a job of the same name in the +folder of a remote node that was submitted from another working directory, +until it is purged. Every job is registered in \code{tools::R_user_dir("dMod2", "data")} until \code{purge(local = TRUE)}, and \code{\link[=dMod2Jobs]{dMod2Jobs()}} lists them. diff --git a/man/em.Rd b/man/em.Rd index ef59f7ba..a4e8b5ff 100644 --- a/man/em.Rd +++ b/man/em.Rd @@ -46,10 +46,30 @@ the inner modes.} \describe{ \item{\code{sd}}{start of the standard deviations of the random effects, default 0.3.} -\item{\code{innerControl}}{the trust region of the modes; it stops where the -Newton step is below \code{steptol}, default 1e-8.} +\item{\code{inner}}{\code{"nested"} (default) solves the modes at every +evaluation of the outer search; \code{"sqp"} takes \code{sqpIterlim} iterations of +the inner search from the modes predicted along d eta / d theta, with +value and gradient corrected to first order for the eta gradient left +over, until the outer search stops, and then goes on nested from there, +so that the estimates are those of the nested search. Applies to FOCEI +and to spike-and-slab and Dirichlet-process random effects.} +\item{\code{innerControl}}{the trust region of the modes: \code{rinit} and \code{rmax}, +the initial and largest radius (default 1 and 10); \code{iterlim}, default +30 and over several groupings 100; \code{steptol}, default 1e-8, the Newton +step at which it stops; \code{mtol}, default 1e-12, the predicted change of +-2 log L, relative to -2 log L, at which a step on the boundary of the +region stops it; \code{eigenFloorRelative}, default 1e-10, the floor of the +eigenvalues of the inner Hessian relative to their mean (one grouping); +\code{sqpIterlim}, default 2, the inner iterations per evaluation with +\code{inner = "sqp"}. With spike-and-slab and Dirichlet-process random +effects only \code{sqpIterlim} applies. Other entries are an error.} \item{\code{trustControl}}{the outer trust region; it stops where the -predicted change of -2 log L is below \code{mtol}, default 1e-5.} +predicted change of -2 log L is below \code{mtol}, default 1e-5. Takes +\code{ftol}, \code{mtol}, \code{gtol} and \code{xtol} flat or in \code{tolControl}. With random +effects over several groupings the outer search is \code{\link[=trust]{trust()}}, and +every argument of \code{\link[=trust]{trust()}} passes, \code{hessianMethod}, \code{phases} and +\code{qnControl} included; FOCEI of one grouping reads \code{rinit}, \code{rmax}, +\code{iterlim}, \code{ftol} and \code{mtol}. Other entries are an error.} \item{\code{secondOrderCorrection}}{the derivative of the volume term, default \code{TRUE}.} \item{\code{derivMode}}{how FOCEI gets the second derivatives of the volume @@ -65,7 +85,7 @@ standard deviation ends below 0.1 is dropped and the fit repeated from the estimates; where -2 log L rises by at most \code{boundary}, that fit is returned and names the hyperparameter in \code{boundary}.} \item{\code{quadrature}, \code{saem}, \code{sparseFit}}{lists of the sections -Quadrature, SAEM and Sparse random effects.} +Quadrature, SAEM and Sparse random effects; other entries are an error.} }} \item{cores}{Number of cores over the groups and conditions inside the @@ -89,9 +109,20 @@ part of the Hessian kept apart (see \code{\link[=objlist]{objlist()}}).} \item{\code{information}}{with spike-and-slab random effects the empirical information that gives the standard errors: \code{G / (G - 1)} times the sum of the outer products of the centered scores of the \code{G} -groups, plus half the Hessian of the conditions without random -effects.} -\item{\code{converged}, \code{iterations}}{} +groups, of rank at most \code{G - 1}, plus half the curvature of the terms +without random effects (conditions outside every group, priors) by +their expected information (\code{hessian = "expected"}, see \link{dModfn}), +positive semidefinite. It is not the Hessian of the marginal -2 log L +and is singular where the scores and those terms span fewer directions +than there are parameters. \link[=vcov.em]{vcov()} inverts it where it is +positive definite.} +\item{\code{converged}, \code{iterations}}{the convergence of the outer search +and the iterations; with several groupings also \code{phaseIterations} of +\code{\link[=trust]{trust()}}.} +\item{\code{innerIterations}, \code{sqpIterations}}{with FOCEI and sparse random +effects the iterations of the inner searches summed over the groups and +evaluations, and with \code{control$inner = "sqp"} the outer iterations on +inexact modes.} \item{\code{Omega}, \code{omega}}{the covariance of the normal random effects, their standard deviations and correlations with standard errors.} \item{\code{random}}{per group the modes with conditional standard errors; @@ -132,14 +163,14 @@ Methods: \describe{ \item{\code{"focei"}}{Laplace approximation at the conditional modes with the exact derivative of the volume term. The default, and the method for -spike-and-slab and Dirichlet-process random effects (at most 14 -groups) and for several groupings.} +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.} \item{\code{"laplaceEM"}}{ECM on the Laplace approximation with the covariance-corrected update of \code{Omega}.} -\item{\code{"saem"}}{stochastic-approximation EM, also for Dirichlet-process -random effects; section SAEM.} +\item{\code{"saem"}}{stochastic-approximation EM, also for spike-and-slab and +Dirichlet-process random effects; section SAEM.} } } \section{Quadrature}{ @@ -152,17 +183,27 @@ in \verb{phi = X beta + eta}. Entries of \code{control$quadrature}: \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. -\code{Inf} keeps the -levels of the stages.} +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{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}}{highest level, default \code{K + 8}.} +\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 +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 +and cap per group.} \item{\code{tolDecrement}}{a stage ends when a Newton step on the rebuilt -nodes would lower -2 log L by less than this, default 1e-4, or than the -nodes resolve.} +nodes would lower -2 log L by less than this, default 1e-4 +(\code{stopReason} \code{"decrement"}), or when -2 log L rose after a step on nodes +of unchanged levels, so the step lies below what the levels resolve +(\code{"resolution"}). \code{converged} means stationary at the levels reached, +capped ones included; the fit returns the iterate of lowest -2 log L on +the highest levels.} \item{\code{maxEcmPerStage}, \code{cm1Control}, \code{maxCm1Iter}}{rebuilds per stage -(default 10), \code{\link[=trust]{trust()}} settings and iterations of a step (default 30).} +(default 10, \code{stopReason} \code{"iterlim"} where they run out), \code{\link[=trust]{trust()}} +settings and iterations of a step (default 30).} \item{\code{pruneTol}}{nodes whose weight lies this much in log below the largest are dropped, default \code{Inf}.} \item{\code{certificate}}{\code{FALSE}, or a list of \code{points} (default 256) and @@ -186,23 +227,55 @@ models. Entries of \code{control$saem}: \item{\code{nBurnin}, \code{nEM}}{at most that many burn-in and averaging iterations, default 200 and 300.} \item{\code{nMcmc}, \code{nLaplace}}{random-walk and independence steps per -iteration, default 3 each.} +iteration, default 3 each; \code{nLaplace} with normal random effects alone.} \item{\code{laplaceEvery}, \code{laplaceScale}}{iterations between refreshes of the -modes, default 5, and the factor of the proposal covariance, default -1.5.} +modes, default 5, with normal random effects alone, and the factor of the +proposal covariance, default 1.5, also of the slab value of an indicator +move.} \item{\code{window}, \code{mcTol}}{the burn-in ends when no parameter has a significant slope over the last \code{window} iterations (default 25), the averaging when the expected rise of -2 log L from the Monte Carlo error is below \code{mcTol} (default 0.05).} -\item{\code{particles}}{with Dirichlet-process random effects the particles of -the sequential importance sampling of -2 log L, default 500.} +\item{\code{particles}}{the particles of the sequential importance sampling +of -2 log L with Dirichlet-process random effects, default 500.} \item{\code{cm1Control}}{\code{\link[=trust]{trust()}} settings of the Newton steps of the other parameters, default one iteration per SAEM iteration.} +\item{\code{nFlip}}{with spike-and-slab random effects the sweeps over the +indicators per iteration, default 1.} +\item{\code{nodes}}{Gauss-Hermite nodes of the slab mass of an indicator, 3 +(default) or 5.} +\item{\code{integral}}{\code{"importance"} takes -2 log L by importance sampling +over the partitions also where Dirichlet-process random effects beside +spike-and-slab ones allow the exact sum.} } -With Dirichlet-process random effects a Gibbs sweep draws the clusters of -the groups (Neal 2000, algorithm 8), the averaging runs \code{nEM} iterations, -and the reported clusters are the most frequent partition of the late -draws. +With normal random effects alone, -2 log L at the estimate is the +quadrature of level \code{K + 2}, and \code{maxLevel}, \code{maxNodes} and \code{pruneTol} of +\code{control$quadrature} apply to it. +With spike-and-slab or Dirichlet-process random effects the averaging runs +\code{nEM} iterations. A sweep of Metropolis-Hastings moves visits every +indicator of a group once, in random order and for all groups at once, +with the slab value integrated out: the other slab values of the group +follow along the regression of the local quadratic model of the data, the +slab mass on that line is a Gauss-Hermite sum with the exact model at the +nodes, and the proposal draws the indicator from the resulting conditional +inclusion probability and the slab value from the local Gaussian; the +independence Metropolis-Hastings step keeps the posterior exact. \code{nMcmc} +random-walk steps move the slab values of every group jointly. \code{prob} and +\code{tau} follow in closed form from the averaged conditional inclusion +probabilities and slab second moments of the sweeps, not from the drawn +indicators; an estimated \code{tau} starts at least at the largest group mode +under the slab alone. An \code{em} fit as \code{init} starts the chain at the +selected random effects of that fit instead, the way to check a FOCEI +optimum by SAEM. The acceptance rates of births, deaths and random-walk +steps per iteration are columns of \code{stageTrace}. A Gibbs sweep draws +the clusters of the Dirichlet-process random effects (Neal 2000, +algorithm 8). The reported clusters are the most frequent partition of +the late draws, a spike-and-slab random effect is selected where the mean +conditional inclusion probability of the late sweeps is above 1/2, \code{p0} +one minus that mean. -2 log L is that of \code{method = "focei"} at the +estimate; with Dirichlet-process random effects alone, or beside +spike-and-slab ones on more than 14 groups, by importance sampling over the +partitions, with \code{valueSE}. } \section{Sparse random effects}{ @@ -215,8 +288,9 @@ nodes; else it is the expectation consistent (EC) approximation, and a trial point at which EC does not converge is a failed evaluation. Entries of \code{control$sparseFit}: \describe{ \item{\code{maxOuter}}{iterations of the trust region, default 200.} -\item{\code{trustControl}}{the \code{\link[=trust]{trust()}} settings; \code{ftol}, \code{mtol} and \code{gtol} -of the \code{tolControl} there also end the search of the modes (else 1e-10).} +\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.} } } diff --git a/man/evalConditionResidual.Rd b/man/evalConditionResidual.Rd index ae5f6c46..2c679856 100644 --- a/man/evalConditionResidual.Rd +++ b/man/evalConditionResidual.Rd @@ -7,7 +7,6 @@ evalConditionResidual( dataI, predictionI, - pars, errfn = NULL, fixed = NULL, cn = NULL, @@ -24,8 +23,6 @@ evalConditionResidual( \item{predictionI}{\link{prdframe} of that condition.} -\item{pars}{Named numeric parameter vector.} - \item{errfn}{Optional \link{obsfn}, the error model. Default \code{NULL}.} \item{fixed}{Optional named numeric vector of fixed parameters, passed to diff --git a/man/logLik.em.Rd b/man/logLik.em.Rd index 774ba871..2499358c 100644 --- a/man/logLik.em.Rd +++ b/man/logLik.em.Rd @@ -4,17 +4,28 @@ \alias{logLik.em} \title{Log-likelihood of a mixed-effects fit} \usage{ -\method{logLik}{em}(object, ...) +\method{logLik}{em}(object, method = c("fit", "importance"), draws = 1000L, ...) } \arguments{ \item{object}{An \code{em} object, see \code{\link[=em]{em()}}.} +\item{method}{\code{"fit"} (default) the marginal log-likelihood of the fit; +\code{"importance"} the marginal log-likelihood at the estimates by importance +sampling on the model, for spike-and-slab random effects of one grouping +(normal ones beside). The proposal is the mixture of the approximation of +the fit with widened spreads; the fit must contain the design.} + +\item{draws}{Draws per group for \code{method = "importance"}, default 1000.} + \item{...}{Ignored.} } \value{ The marginal log-likelihood, \code{-value / 2}, of class \code{logLik} with the number of estimated parameters as \code{df} and the number of -observations as \code{nobs}, so \code{\link[stats:AIC]{stats::AIC()}} and \code{\link[stats:BIC]{stats::BIC()}} apply. +observations as \code{nobs}, so \code{\link[stats:AIC]{stats::AIC()}} and \code{\link[stats:BIC]{stats::BIC()}} apply. With +\code{method = "importance"} the attributes \code{se} (standard error), \code{ess} +(effective sample size per group) and \code{approximation} (the log-likelihood +of the approximation of the fit at the estimates). } \description{ Log-likelihood of a mixed-effects fit diff --git a/man/msem.Rd b/man/msem.Rd index ffa16752..4d87b28a 100644 --- a/man/msem.Rd +++ b/man/msem.Rd @@ -52,10 +52,30 @@ the inner modes.} \describe{ \item{\code{sd}}{start of the standard deviations of the random effects, default 0.3.} -\item{\code{innerControl}}{the trust region of the modes; it stops where the -Newton step is below \code{steptol}, default 1e-8.} +\item{\code{inner}}{\code{"nested"} (default) solves the modes at every +evaluation of the outer search; \code{"sqp"} takes \code{sqpIterlim} iterations of +the inner search from the modes predicted along d eta / d theta, with +value and gradient corrected to first order for the eta gradient left +over, until the outer search stops, and then goes on nested from there, +so that the estimates are those of the nested search. Applies to FOCEI +and to spike-and-slab and Dirichlet-process random effects.} +\item{\code{innerControl}}{the trust region of the modes: \code{rinit} and \code{rmax}, +the initial and largest radius (default 1 and 10); \code{iterlim}, default +30 and over several groupings 100; \code{steptol}, default 1e-8, the Newton +step at which it stops; \code{mtol}, default 1e-12, the predicted change of +-2 log L, relative to -2 log L, at which a step on the boundary of the +region stops it; \code{eigenFloorRelative}, default 1e-10, the floor of the +eigenvalues of the inner Hessian relative to their mean (one grouping); +\code{sqpIterlim}, default 2, the inner iterations per evaluation with +\code{inner = "sqp"}. With spike-and-slab and Dirichlet-process random +effects only \code{sqpIterlim} applies. Other entries are an error.} \item{\code{trustControl}}{the outer trust region; it stops where the -predicted change of -2 log L is below \code{mtol}, default 1e-5.} +predicted change of -2 log L is below \code{mtol}, default 1e-5. Takes +\code{ftol}, \code{mtol}, \code{gtol} and \code{xtol} flat or in \code{tolControl}. With random +effects over several groupings the outer search is \code{\link[=trust]{trust()}}, and +every argument of \code{\link[=trust]{trust()}} passes, \code{hessianMethod}, \code{phases} and +\code{qnControl} included; FOCEI of one grouping reads \code{rinit}, \code{rmax}, +\code{iterlim}, \code{ftol} and \code{mtol}. Other entries are an error.} \item{\code{secondOrderCorrection}}{the derivative of the volume term, default \code{TRUE}.} \item{\code{derivMode}}{how FOCEI gets the second derivatives of the volume @@ -71,7 +91,7 @@ standard deviation ends below 0.1 is dropped and the fit repeated from the estimates; where -2 log L rises by at most \code{boundary}, that fit is returned and names the hyperparameter in \code{boundary}.} \item{\code{quadrature}, \code{saem}, \code{sparseFit}}{lists of the sections -Quadrature, SAEM and Sparse random effects.} +Quadrature, SAEM and Sparse random effects; other entries are an error.} }} \item{fits}{Number of starts. Default 20.} diff --git a/man/normL2.Rd b/man/normL2.Rd index 8c9afe06..ce0bac51 100644 --- a/man/normL2.Rd +++ b/man/normL2.Rd @@ -165,6 +165,14 @@ as a sparse \code{Matrix}, assembled from the blocks of the conditions; \code{\l factorizes it where the argument \code{sparse} takes the sparse path, and \code{\link[=vcov.objlist]{vcov()}} solves it for the columns of \code{which}. +\code{hessian = "expected"} returns, in place of the Gauss-Newton Hessian of the +forward sweep, the expected (Fisher) information of the likelihood: +\code{2 / sigma^2} in the prediction and \code{4 / sigma^2} in sigma per data point, +positive semidefinite also where an error model depends on the parameters. +The Gauss-Newton Hessian keeps the exact curvature of the loss in the +prediction and sigma, which is indefinite there and shows the optimizer a +saddle. + With \code{deriv = FALSE} it returns the value alone. } diff --git a/man/objlist.Rd b/man/objlist.Rd index 15dd6856..436c6b97 100644 --- a/man/objlist.Rd +++ b/man/objlist.Rd @@ -27,6 +27,15 @@ along when two objective lists are added with \code{+}, see \link{sumobjlist}. Asked for \code{hessian = "sparse"}, an objective may return part of the Hessian in an entry \code{lowrank}, a list of a matrix \code{U} with parameter rows and a vector \code{d}: the Hessian is then \verb{hessian + U diag(d) U'}. + +Asked for \code{hessian = "structured"}, a data term such as \code{\link[=normL2]{normL2()}} +returns the Gauss-Newton Hessian and an entry \code{structure}, a list of the +matrix \code{jacobian}, one row per data point with the derivatives of the +prediction, and one more for a sigma that depends on parameters, the +vector \code{seeds} of the derivatives of the value in these predictions and +sigmas, and the Gauss-Newton Hessian \code{hessian} of the data term. \code{+} stacks +the rows and adds the Hessians; a term without data rows has none. +The structured methods of \code{\link[=trust]{trust()}} read it. } \examples{ a <- objlist(1, c(a = 1, b = 2), diff --git a/man/obsfn.Rd b/man/obsfn.Rd index c166f2c5..56aeb229 100644 --- a/man/obsfn.Rd +++ b/man/obsfn.Rd @@ -91,6 +91,14 @@ as a sparse \code{Matrix}, assembled from the blocks of the conditions; \code{\l factorizes it where the argument \code{sparse} takes the sparse path, and \code{\link[=vcov.objlist]{vcov()}} solves it for the columns of \code{which}. +\code{hessian = "expected"} returns, in place of the Gauss-Newton Hessian of the +forward sweep, the expected (Fisher) information of the likelihood: +\code{2 / sigma^2} in the prediction and \code{4 / sigma^2} in sigma per data point, +positive semidefinite also where an error model depends on the parameters. +The Gauss-Newton Hessian keeps the exact curvature of the loss in the +prediction and sigma, which is indefinite there and shows the optimizer a +saddle. + With \code{deriv = FALSE} it returns the value alone. } diff --git a/man/parfn.Rd b/man/parfn.Rd index 927827ea..5414b99f 100644 --- a/man/parfn.Rd +++ b/man/parfn.Rd @@ -95,6 +95,14 @@ as a sparse \code{Matrix}, assembled from the blocks of the conditions; \code{\l factorizes it where the argument \code{sparse} takes the sparse path, and \code{\link[=vcov.objlist]{vcov()}} solves it for the columns of \code{which}. +\code{hessian = "expected"} returns, in place of the Gauss-Newton Hessian of the +forward sweep, the expected (Fisher) information of the likelihood: +\code{2 / sigma^2} in the prediction and \code{4 / sigma^2} in sigma per data point, +positive semidefinite also where an error model depends on the parameters. +The Gauss-Newton Hessian keeps the exact curvature of the loss in the +prediction and sigma, which is indefinite there and shows the optimizer a +saddle. + With \code{deriv = FALSE} it returns the value alone. } diff --git a/man/plotPars.Rd b/man/plotPars.Rd index cba071ac..ad67a767 100644 --- a/man/plotPars.Rd +++ b/man/plotPars.Rd @@ -1,9 +1,11 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/parClass.R, R/plots.R +% Please edit documentation in R/parClass.R, R/plots.R, R/plotsEM.R \name{plotPars.parlist} \alias{plotPars.parlist} \alias{plotPars.parframe} \alias{plotPars} +\alias{plotPars.em} +\alias{plotPars.list} \title{Plot Parameter Values of a Collection of Fits} \usage{ \method{plotPars}{parlist}(x, ..., tol = 1) @@ -11,6 +13,10 @@ \method{plotPars}{parframe}(x, ..., tol = 1) plotPars(x, ...) + +\method{plotPars}{em}(x, ..., level = 0.95, which = NULL) + +\method{plotPars}{list}(x, ..., level = 0.95, which = NULL) } \arguments{ \item{x}{A \link{parframe} or the result of \code{\link[=mstrust]{mstrust()}}.} @@ -19,6 +25,12 @@ plotPars(x, ...) \item{tol}{A value more than \code{tol} above the lowest value of the current step starts a new step. Defaults to 1.} + +\item{level}{With an \code{em} fit or a list of them: the level of the Wald +intervals, see \link[=confint.em]{confint()}. Default 0.95.} + +\item{which}{With an \code{em} fit or a list of them: names of the parameters to +show, by default all estimated ones.} } \value{ A \code{ggplot} object with the plotted data frame as attribute \code{"data"}. @@ -27,6 +39,13 @@ A \code{ggplot} object with the plotted data frame as attribute \code{"data"}. Draws one box per parameter, colored by the step of the objective value the fits belong to. } +\details{ +An \code{em} fit, see \code{\link[=em]{em()}}, or a list of them, as fits of one model by +several methods: the estimates of fixed effects and hyperparameters with +Wald intervals, where the fit has standard errors, one row per parameter +and one color per fit. The fits of a list are labeled by the names of the +list, else by their method. +} \examples{ fits <- parframe(data.frame(value = c(10, 10.2, 15, 40), converged = TRUE, iterations = 20, a = c(1, 1.1, 2, 3), diff --git a/man/plotRandomEffects.Rd b/man/plotRandomEffects.Rd index be7d14f6..d1058244 100644 --- a/man/plotRandomEffects.Rd +++ b/man/plotRandomEffects.Rd @@ -9,7 +9,7 @@ plotRandomEffects(x, ...) \method{plotRandomEffects}{em}( x, - type = c("conditional", "modes"), + type = c("conditional", "modes", "inclusion"), draws = 20L, bins = 30, covariates = NULL, @@ -22,10 +22,21 @@ plotRandomEffects(x, ...) \item{...}{Ignored.} \item{type}{\code{"conditional"} (default): per group \code{draws} values from the -conditional distribution of the random effects of the group, normal around the mode with -the conditional standard error; under the model they follow \code{N(0, Omega_kk)} -whatever the shrinkage. \code{"modes"}: the modes, narrower than \code{N(0, Omega_kk)} -by the shrinkage.} +conditional distribution of the random effects of the group; under the +model they follow the random-effect distribution whatever the shrinkage. +A normal random effect is drawn normal around the mode with the +conditional standard error, against \code{N(0, Omega_kk)}. A spike-and-slab +random effect is 0 with the posterior probability \code{p0} and otherwise +normal, with the reported value, or where the reported structure has the +spike the mode of the slab, as mean and the variance that gives the +conditional standard error; drawn against the prior, the slab density +\verb{prob N(0, tau^2)} and a cap at the height of a bar of area \code{1 - prob} +at 0. \code{"modes"}: the +modes, or the reported values of spike-and-slab random effects, narrower +than the distribution by the shrinkage. \code{"inclusion"}: a heatmap of the +posterior probability \code{1 - p0} of a deviation per group and sparse random +effect, labeled with the reported value where the reported structure has +a deviation.} \item{draws}{Number of draws per group with \code{type = "conditional"}. Default 20.} @@ -41,9 +52,14 @@ the others.} \value{ A ggplot (or a list of ggplots if \code{cowplot} is unavailable). -A ggplot, or without cowplot a list with \code{hist} and \code{qq}. With -\code{covariates}, a ggplot for one covariate; for several a cowplot grid, or -without cowplot a list of ggplots named by covariate. +A ggplot, or without cowplot a list with \code{hist} and \code{qq}; the QQ +plot has the normal random effects only, a fit with sparse random effects +alone gives the histograms as one ggplot. With \code{type = "inclusion"} a +ggplot. With \code{covariates}, a ggplot for one covariate; for several a +cowplot grid, or without cowplot a list of ggplots named by covariate. +Spike-and-slab random effects that reach no data of the group are left +out; Dirichlet-process random effects, which couple the groups, appear in +the heatmap only. } \description{ Per random effect a histogram against the estimated diff --git a/man/plotTrace.Rd b/man/plotTrace.Rd index 9f1dca00..029f3258 100644 --- a/man/plotTrace.Rd +++ b/man/plotTrace.Rd @@ -11,7 +11,9 @@ plotTrace(x, ...) } \arguments{ \item{x}{An \code{em} fit, see \code{\link[=em]{em()}}, with a stage trace: every method except \code{"focei"} -with normal random effects only.} +with normal random effects only. The hyperparameters of spike-and-slab and +Dirichlet-process random effects that the trace records (\verb{prob_}, +\verb{tau_}, \verb{concentration_}) get one panel each.} \item{...}{Ignored.} } diff --git a/man/prdfn.Rd b/man/prdfn.Rd index 164e6b87..d6283b46 100644 --- a/man/prdfn.Rd +++ b/man/prdfn.Rd @@ -91,6 +91,14 @@ as a sparse \code{Matrix}, assembled from the blocks of the conditions; \code{\l factorizes it where the argument \code{sparse} takes the sparse path, and \code{\link[=vcov.objlist]{vcov()}} solves it for the columns of \code{which}. +\code{hessian = "expected"} returns, in place of the Gauss-Newton Hessian of the +forward sweep, the expected (Fisher) information of the likelihood: +\code{2 / sigma^2} in the prediction and \code{4 / sigma^2} in sigma per data point, +positive semidefinite also where an error model depends on the parameters. +The Gauss-Newton Hessian keeps the exact curvature of the loss in the +prediction and sigma, which is indefinite there and shows the optimizer a +saddle. + With \code{deriv = FALSE} it returns the value alone. } diff --git a/man/scale_color_dMod.Rd b/man/scale_color_dMod2.Rd similarity index 63% rename from man/scale_color_dMod.Rd rename to man/scale_color_dMod2.Rd index 4d4043b6..90276327 100644 --- a/man/scale_color_dMod.Rd +++ b/man/scale_color_dMod2.Rd @@ -1,25 +1,25 @@ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/plots.R -\name{scale_color_dMod} -\alias{scale_color_dMod} -\alias{scale_fill_dMod} -\title{Discrete dMod Color Scales} +\name{scale_color_dMod2} +\alias{scale_color_dMod2} +\alias{scale_fill_dMod2} +\title{Discrete dMod2 Color Scales} \usage{ -scale_color_dMod(..., palette = "okabe") +scale_color_dMod2(..., palette = "okabe") -scale_fill_dMod(..., palette = "okabe") +scale_fill_dMod2(..., palette = "okabe") } \arguments{ \item{...}{Arguments passed to \code{\link[ggplot2:discrete_scale]{ggplot2::discrete_scale()}}.} -\item{palette}{Name of a qualitative palette, see \code{\link[=dMod_palettes]{dMod_palettes()}}. +\item{palette}{Name of a qualitative palette, see \code{\link[=dMod2_palettes]{dMod2_palettes()}}. Defaults to the colorblind-safe \code{"okabe"}.} } \value{ A discrete \code{ggplot2} scale. } \description{ -Discrete dMod Color Scales +Discrete dMod2 Color Scales } \examples{ library(ggplot2) @@ -31,8 +31,8 @@ data <- data.frame( group = rep(c("C1", "C2", "C3", "C4"), each = length(times)) ) ggplot(data, aes(time, value, color = group)) + geom_line() + - theme_dMod() + scale_color_dMod() + theme_dMod2() + scale_color_dMod2() } \seealso{ -\code{\link[=scale_color_dMod_c]{scale_color_dMod_c()}}, \code{\link[=dMod_palette]{dMod_palette()}} +\code{\link[=scale_color_dMod2_c]{scale_color_dMod2_c()}}, \code{\link[=dMod2_palette]{dMod2_palette()}} } diff --git a/man/scale_color_dMod_c.Rd b/man/scale_color_dMod2_c.Rd similarity index 52% rename from man/scale_color_dMod_c.Rd rename to man/scale_color_dMod2_c.Rd index 00aa0ef0..ce7c1cbb 100644 --- a/man/scale_color_dMod_c.Rd +++ b/man/scale_color_dMod2_c.Rd @@ -1,19 +1,19 @@ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/plots.R -\name{scale_color_dMod_c} -\alias{scale_color_dMod_c} -\alias{scale_fill_dMod_c} -\alias{scale_color_dMod_div} -\alias{scale_fill_dMod_div} -\title{Continuous dMod Color Scales} +\name{scale_color_dMod2_c} +\alias{scale_color_dMod2_c} +\alias{scale_fill_dMod2_c} +\alias{scale_color_dMod2_div} +\alias{scale_fill_dMod2_div} +\title{Continuous dMod2 Color Scales} \usage{ -scale_color_dMod_c(..., direction = 1, palette = "okabe") +scale_color_dMod2_c(..., direction = 1, palette = "okabe") -scale_fill_dMod_c(..., direction = 1, palette = "okabe") +scale_fill_dMod2_c(..., direction = 1, palette = "okabe") -scale_color_dMod_div(mid = 0, ..., direction = 1, palette = "okabe") +scale_color_dMod2_div(mid = 0, ..., direction = 1, palette = "okabe") -scale_fill_dMod_div(mid = 0, ..., direction = 1, palette = "okabe") +scale_fill_dMod2_div(mid = 0, ..., direction = 1, palette = "okabe") } \arguments{ \item{...}{Arguments passed to \code{\link[ggplot2:scale_color_gradientn]{ggplot2::scale_color_gradientn()}} or @@ -22,7 +22,7 @@ scale_fill_dMod_div(mid = 0, ..., direction = 1, palette = "okabe") \item{direction}{1 (default) or -1; -1 reverses the ramp.} \item{palette}{Name of a sequential palette for \verb{_c}, a diverging one for -\verb{_div}, see \code{\link[=dMod_palettes]{dMod_palettes()}}. Defaults to the colorblind-safe \code{"okabe"}.} +\verb{_div}, see \code{\link[=dMod2_palettes]{dMod2_palettes()}}. Defaults to the colorblind-safe \code{"okabe"}.} \item{mid}{Numeric, the value mapped to white. Defaults to 0.} } @@ -31,15 +31,15 @@ A continuous \code{ggplot2} scale. } \description{ Sequential (\verb{_c}) and diverging (\verb{_div}) counterparts of the discrete -\code{\link[=scale_color_dMod]{scale_color_dMod()}}. The diverging scales map \code{mid} to white, also for +\code{\link[=scale_color_dMod2]{scale_color_dMod2()}}. The diverging scales map \code{mid} to white, also for asymmetric limits. } \examples{ library(ggplot2) d <- expand.grid(time = seq(0, 10, 0.1), eps = seq(0, 1, 0.1)) ggplot(d, aes(time, exp(-eps * time), group = eps, color = eps)) + - geom_line() + theme_dMod() + scale_color_dMod_c() + geom_line() + theme_dMod2() + scale_color_dMod2_c() } \seealso{ -\code{\link[=scale_color_dMod]{scale_color_dMod()}} +\code{\link[=scale_color_dMod2]{scale_color_dMod2()}} } diff --git a/man/steadyStates.Rd b/man/steadyStates.Rd index 4f6e2489..dcbae182 100644 --- a/man/steadyStates.Rd +++ b/man/steadyStates.Rd @@ -34,7 +34,7 @@ at zero and treated as exogenous. Default \code{NULL}.} \code{c("A + pA = totA", "B + pB = totB")} or as \code{c("A + pA", "B + pB")}. Default \code{NULL}: a basis is derived, or taken from \code{\link[=customTotals]{customTotals()}} when the \code{eqnlist} has them. Each given quantity keeps one of the states in it free, the -first where possible.} +first one on a cycle of the graph of states.} \item{neglect}{Character vector, states and rate parameters the solver must not solve for. Default \code{NULL}.} @@ -53,8 +53,8 @@ in that state, may be solved for the positive root instead of for a rate constan introduces \code{sqrt()} terms. Default \code{FALSE}.} \item{priority}{Character vector of state and rate-parameter names, most -preferred first: named states are solved earlier, named rate parameters -are preferred as pivots. Default \code{NULL}.} +preferred first: named states are solved rather than kept free and solved +earlier, named rate parameters are preferred as pivots. Default \code{NULL}.} \item{resolve}{Logical, whether the result is passed through \code{\link[=resolveRecurrence]{resolveRecurrence()}} so that no equation refers to another. Default @@ -70,12 +70,18 @@ free parameter. } \description{ Computes symbolic steady-state expressions for use in a parameter -transformation, following the AlyssaPetit method [1], [2]. Each balance -equation, or a combination of balances, is solved for a state or a rate -constant such that the result is a ratio of sums of positive terms. A state -whose equation was spent on a rate constant stays a free parameter; -compartment volumes are fixed. The solver is a Python module called through -\pkg{reticulate}; it needs \pkg{numpy}, \pkg{sympy} and \pkg{scipy}. +transformation, following the AlyssaPetit method [1], [2]. States whose +own balance gives a ratio of positive sums are solved from it first. The +cycles of the graph of states left are cut then: at a state of a conserved +quantity, or at a state whose balance is solved for a rate constant of one +flux side instead. Each cut state stays a free parameter. The remaining +states and the rate constants of the cuts are then solved, each from a +balance or a combination of balances in amounts, such that the result is a +ratio of sums of positive terms. Only if that fails, a flux side with +separate rate constants is cut as well: the fluxes of the side keep free +ratios, the new parameters \verb{r__}. Compartment volumes are fixed. +The solver is a Python module called through \pkg{reticulate}; it needs +\pkg{numpy}, \pkg{sympy} and \pkg{scipy}. } \examples{ \dontshow{if (requireNamespace("reticulate", quietly = TRUE) && reticulate::py_module_available("sympy") && reticulate::py_module_available("scipy")) withAutoprint(\{ # examplesIf} diff --git a/man/symmetryDetection.Rd b/man/symmetryDetection.Rd index f9c46a95..fc407e32 100644 --- a/man/symmetryDetection.Rd +++ b/man/symmetryDetection.Rd @@ -121,7 +121,7 @@ models without \code{equilibrate} and later events).} first, reduces the directions found and then counts the values of the coordinates with the output of a generic one and reconstructs the maps between them, as \code{\link[=discreteSymmetries]{discreteSymmetries()}} (needs msolve, implies \code{reconstruct = TRUE}). A model the global analysis does not handle -gets the reason in \code{info$discrete$unsupported} and a warning. Needs symident 0.15.0.} +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()}}.} diff --git a/man/theme_dMod.Rd b/man/theme_dMod2.Rd similarity index 67% rename from man/theme_dMod.Rd rename to man/theme_dMod2.Rd index dcbf9ff6..1e757be2 100644 --- a/man/theme_dMod.Rd +++ b/man/theme_dMod2.Rd @@ -1,10 +1,10 @@ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/plots.R -\name{theme_dMod} -\alias{theme_dMod} -\title{Standard Plotting Theme of dMod} +\name{theme_dMod2} +\alias{theme_dMod2} +\title{Standard Plotting Theme of dMod2} \usage{ -theme_dMod(base_size = 12, base_family = "", showGrid = FALSE) +theme_dMod2(base_size = 12, base_family = "", showGrid = FALSE) } \arguments{ \item{base_size}{Numeric, base font size. Defaults to 12.} @@ -18,13 +18,13 @@ theme_dMod(base_size = 12, base_family = "", showGrid = FALSE) A \code{ggplot2} theme. } \description{ -Standard Plotting Theme of dMod +Standard Plotting Theme of dMod2 } \examples{ library(ggplot2) ggplot(data.frame(x = 1:10, y = (1:10)^2), aes(x, y)) + - geom_line() + theme_dMod() + geom_line() + theme_dMod2() } \seealso{ -\code{\link[=scale_color_dMod]{scale_color_dMod()}} +\code{\link[=scale_color_dMod2]{scale_color_dMod2()}} } diff --git a/man/trust.Rd b/man/trust.Rd index 1703af2b..e554464f 100644 --- a/man/trust.Rd +++ b/man/trust.Rd @@ -11,7 +11,7 @@ trust( rinit = 0.1, rmax = 10, iterlim = 1000L, - hessianMethod = c("gn", "bfgs", "sr1", "exact"), + hessianMethod = c("gn", "bfgs", "sr1", "exact", "sbfgs", "ssr1", "gnsbfgs", "gnssr1"), phases = NULL, switches = NULL, parupper = NULL, @@ -72,22 +72,35 @@ outside \code{[parlower, parupper]} are clipped with a warning; with Default \code{1000}.} \item{hessianMethod}{Source of the model Hessian of a run without -\code{phases}: \code{"gn"} (default) the Gauss-Newton Hessian of the +\code{phases}: \code{"gn"} the Gauss-Newton Hessian of the objective, \code{"bfgs"} or \code{"sr1"} a quasi-Newton update seeded as \code{qnControl$hessianInit} says, \code{"exact"} the true Hessian at every iterate, which needs an objective that takes \code{deriv2}. -\code{"bfgs"}, \code{"sr1"} and \code{"exact"} require -\code{boundary = "reflective"}. +The structured methods take the Gauss-Newton Hessian at every iterate and +add a correction learned from the steps, starting at zero: +\code{"sbfgs"} by a BFGS update, \code{"ssr1"} by an SR1 update, which may +be indefinite; \code{"gnsbfgs"} and \code{"gnssr1"} switch at every +accepted step between the Gauss-Newton Hessian alone and the structured +BFGS or SR1 model. They count as quasi-Newton phases for the stops and +\code{qnEval}. The correction is learned from the secant of Dennis, +Martínez and Tapia on the data rows that an objective of class +\code{objfn} returns with \code{hessian = "structured"}, see \code{\link[=objlist]{objlist()}}; +without them from the gradient and the Gauss-Newton Hessian. The formulas +are in the methods article. +All but \code{"gn"} require \code{boundary = "reflective"}. Also selects the control defaults below. With \code{phases}, each phase -names a method, and this argument is an error.} +names a method, and this argument is an error. Not given: the hybrid of +section Default method.} \item{phases}{List of phases, each a list of settings, run one after the other and from the first again after the last. The run hands over to the -next phase at a value, model, step or stagnation stop and when a phase -uses up the \code{iterlim} of that phase. A handover restarts the trust region at -\code{rinit} and discards the quasi-Newton pairs. Default \code{NULL}: one -phase from \code{hessianMethod} and \code{qnControl}, evaluated with the -\code{sweep} in \code{...}. Names of the list label the phases in the +next phase at a value, model, step or stagnation stop, when a phase +uses up the \code{iterlim} of that phase and when the radius stayed the same +for \code{radiusStall} iterations. A handover restarts the trust region at +\code{rinit}, unless \code{keepRadius}, and discards the quasi-Newton +pairs. Default \code{NULL}: one phase from \code{hessianMethod} and +\code{qnControl}, evaluated with the \code{sweep} in \code{...}, or the +phases of section Default method. Names of the list label the phases in the result, the Hessian source does otherwise. Not available with multiple shooting and \code{boundary = "clip"}. \describe{ @@ -95,20 +108,40 @@ shooting and \code{boundary = "clip"}. \code{hessianMethod}. Required.} \item{\code{iterlim}}{Maximum number of iterations of one run of the phase. Default \code{NULL}: only the total \code{iterlim}.} +\item{\code{radiusStall}}{Number of consecutive iterations that leave +the trust radius unchanged after which the phase hands over, the +switch of the hybrid method of Fides (Fröhlich and Sorger 2022), which +takes 20 for a Gauss-Newton phase followed by BFGS. The count starts +anew with every change of the radius and at a handover; without a +handover left it ends nothing. Default \code{NULL}: no such handover.} \item{\code{sweep}}{\code{"forward"} or \code{"reverse"}, the \code{sweep} the objective is evaluated with in the phase; a \code{sweep} in \code{...} is an error with \code{phases}. Default \code{NULL}: for \code{"bfgs"} and \code{"sr1"} reverse if the objective can be evaluated backwards at \code{parinit}, as with \code{derivMode = c("forward", "reverse")} throughout the chain, -forward otherwise. A Gauss-Newton Hessian is always computed forward. +forward otherwise. A Gauss-Newton Hessian is always computed forward, +also in the structured methods. A handover between phases of different sweep evaluates the current iterate once more. The result reports the sweeps as \code{phaseSweep}.} +\item{\code{keepRadius}}{\code{TRUE} starts the phase at the trust +radius of the handover instead of \code{rinit}. Default +\code{FALSE}.} +\item{\code{onStop}}{What a value, model, step or stagnation stop does +in the phase: \code{"handover"} (default) hands over while +\code{switches} remain, \code{"end"} ends the run. A phase that ends +on stops hands over at \code{iterlim} and \code{radiusStall} only.} \item{\code{qnControl}}{Quasi-Newton settings of the phase, merged over \code{qnControl}; see there. \code{hessianInit} defaults to \code{"gn"} in every phase but the first: a quasi-Newton phase starts -from the Gauss-Newton Hessian at the iterate of the handover.} +from the Gauss-Newton Hessian at the iterate of the handover. +\code{"tracked"}, for a \code{"bfgs"} phase after the first with +\code{qnMemory = 0}, starts it from a BFGS matrix kept over the whole +run instead: the Hessian at \code{parinit} of the first phase, made +positive definite as a BFGS seed is, updated with the accepted steps of +the phases before, under the \code{qnCautious} test of the phase, and +updated on in the phase itself. Not available on the sparse path.} }} \item{switches}{Number of handovers allowed. Default \code{NULL}: one @@ -143,8 +176,9 @@ before. Default \code{1e-6}.} and \code{rmin}.} \item{qnControl}{List of quasi-Newton settings, merged into the defaults and -read in a \code{"bfgs"} or \code{"sr1"} phase; \code{hessianInit} also in -a first phase of source \code{"gn"}. +read in a quasi-Newton or structured phase; \code{hessianInit} also in +a first phase of source \code{"gn"}. A structured phase takes +\code{hessianInit = "gn"} and \code{qnMemory = 0} only. \describe{ \item{\code{hessianInit}}{Seed of the approximation: \code{"gn"} (default) the Gauss-Newton Hessian at \code{parinit}; @@ -163,14 +197,31 @@ reseed. The result reports the count as \code{nReseed}.} \item{\code{qnMemory}}{Number of \code{(s, y)} pairs kept. Default \code{0}: every update accumulates onto the seed. A positive value rebuilds the approximation in each iteration from the last -\code{qnMemory} pairs, without the seed.} +\code{qnMemory} pairs, without the seed. On the sparse path, see +\code{sparse}, BFGS keeps the last \code{qnMemory} pairs, 10 where it +is \code{0}, on top of the seed.} \item{\code{qnCautious}}{A BFGS pair is used only when \eqn{s^\top y > c\,|s|\,|y|} with \eqn{c} = \code{qnCautious}. Default -\code{1e-8}, \code{0} disables the test; \code{"sr1"} is exempt. The -result reports the rejected pairs as \code{qnSkipped}.} -\item{\code{qnRejected}}{Whether \code{"sr1"} also updates from a +\code{1e-8}, \code{0} disables the test; also read by \code{"sbfgs"}, +the SR1 methods are exempt. The result reports the rejected pairs as +\code{qnSkipped}.} +\item{\code{qnRejected}}{Whether an SR1 method also updates from a rejected trial point. Default \code{TRUE} for a phase whose source is -\code{"sr1"}, \code{FALSE} otherwise.} +\code{"sr1"}, \code{"ssr1"} or \code{"gnssr1"}, \code{FALSE} +otherwise.} +\item{\code{qnScaling}}{\code{"none"} (default) or \code{"residual"}: +\code{"sbfgs"} and \code{"ssr1"} scale the correction with the +residual norm, the norm of the derivatives of the value in the +predictions and sigmas of the data, or the square root of the value +for an objective without data rows, so it vanishes with the residuals +(Huschens). Read by these two methods only.} +\item{\code{qnHybridTol}}{Threshold of the switch of \code{"gnsbfgs"} +and \code{"gnssr1"}: below it the model is the Gauss-Newton Hessian. +Default \code{1e-6}.} +\item{\code{qnHybridShift}}{\code{TRUE} adds the residual norm times +the identity to the Gauss-Newton Hessian on the Gauss-Newton branch +of \code{"gnsbfgs"} and \code{"gnssr1"}, as Zhou and Chen; default +\code{FALSE}.} }} \item{stepControl}{List of step and acceptance settings, merged into the @@ -225,11 +276,17 @@ and parameters. Default \code{NULL}, no file.} \item{sparse}{\code{"auto"} (default), \code{TRUE} or \code{FALSE}. \code{TRUE} calls \code{objfun} with \code{hessian = "sparse"} and solves every subproblem on sparse Cholesky factors of the returned \code{Matrix}, -a low-rank part \code{lowrank} (see \code{\link[=objlist]{objlist()}}) included; the steps equal -those of the dense path to rounding. It needs \code{hessianMethod} -\code{"gn"} or \code{"exact"} and \code{boundary = "reflective"}. -\code{"auto"} takes the sparse path where it applies, outside multiple -shooting, for at least \code{parameters} entries of \code{parinit} and a +a low-rank part \code{lowrank} (see \code{\link[=objlist]{objlist()}}) included; on the Hessian +of the objective the steps equal those of the dense path to rounding. It +needs \code{hessianMethod} +\code{"gn"} or \code{"exact"}, or \code{"bfgs"} with +\code{qnControl$hessianInit = "gn"}, in every phase, and +\code{boundary = "reflective"}. A BFGS phase there is limited-memory BFGS: +the Hessian of the objective at the start of the phase plus the compact +correction of the last \code{qnMemory} pairs (Byrd, Nocedal and Schnabel +1994), a low-rank part of rank twice the number of pairs. +\code{"auto"} takes the sparse path where every phase takes the Hessian of +the objective, outside multiple shooting, for at least \code{parameters} entries of \code{parinit} and a step cheaper than the dense one at \code{parinit}; the settings come from \code{getOption("dMod2.sparseAuto")}, see \link{dMod2-package}.} @@ -275,7 +332,8 @@ gradient and model Hessian at \code{argument}.} \item{\code{iterations}}{Number of iterations.} \item{\code{neval}}{Number of objective evaluations.} \item{\code{qnEval}}{Evaluations spent in a quasi-Newton phase.} -\item{\code{qnSkipped}}{Pairs rejected by the cautious test.} +\item{\code{qnSkipped}}{Pairs rejected by the cautious test, and in a +structured phase pairs that left the correction unchanged.} \item{\code{nSwitch}}{Number of handovers between phases.} \item{\code{phaseIterations}}{Named integer, the iterations of each phase run, in run order and named after the phase. The sum is @@ -283,10 +341,14 @@ phase run, in run order and named after the phase. The sum is evaluations and without the iterations that reseed instead of taking a step.} \item{\code{phaseSweep}}{Named character, the sweep of each element -of \code{phases}, present when \code{phases} is set.} +of \code{phases}, present when \code{phases} is set and in the +default hybrid.} \item{\code{nReseed}}{Number of reseeds by \code{qnControl$hessianReseed = "stall"}, which allows each run of a phase the same number.} +\item{\code{hybridGN}}{Accepted steps of a \code{"gnsbfgs"} or +\code{"gnssr1"} phase after which the model is the Gauss-Newton +Hessian.} \item{\code{evalBySource}}{Named integer, evaluations per Hessian source.} \item{\code{converged}}{Logical.} @@ -300,15 +362,18 @@ row per iteration, and the per-iteration vectors \code{steptype}, \code{stepback}, \code{accept}, \code{r} (radius), \code{rho} (ratio of actual to predicted reduction), \code{valpath}, \code{valtry}, \code{preddiff}, \code{stepnorm} and, with -\code{boundary = "reflective"}, \code{hessianSource}. +\code{boundary = "reflective"}, \code{hessianSource}, which is +\code{"gn"} for an iteration of a hybrid method on the Gauss-Newton +Hessian. \code{boundary = "clip"} returns only \code{argument}, \code{value}, \code{gradient}, \code{hessian}, \code{iterations}, \code{converged}, \code{atBound} and \code{stopReason}, plus the trace. On the sparse path, see \code{sparse}, \code{hessian} is a sparse -\code{Matrix}, and \code{lowrank} where the objective returns one: the -Hessian is then \code{hessian} plus that part. +\code{Matrix}, and \code{lowrank} where the objective returns one or a +BFGS phase adds the correction: the Hessian is then \code{hessian} plus +that part. \code{trustL1} returns a list without class with \code{argument}, \code{value}, \code{gradient}, \code{hessian}, \code{iterations}, @@ -335,6 +400,24 @@ value, gradient and Hessian are available. It solves a Moré-Sorensen trust-region subproblem exactly, via the full eigendecomposition of the Hessian. } +\section{Default method}{ + +Without \code{hessianMethod}, \code{phases}, \code{switches} and a +\code{sweep} in \code{...}, \code{trust} runs the hybrid method of Fides +(Fröhlich and Sorger 2022): Gauss-Newton until the trust radius stayed the +same for 20 consecutive iterations, then BFGS for the rest of the run. The +BFGS approximation starts from the Gauss-Newton Hessian at \code{parinit}, +made positive definite, takes every accepted step of the Gauss-Newton phase +as an update, and the trust radius stays at the switch. These are the +phases +\preformatted{list(gn = list(hessianMethod = "gn", radiusStall = 20, onStop = "end"), + bfgs = list(hessianMethod = "bfgs", sweep = "forward", keepRadius = TRUE, + qnControl = list(hessianInit = "tracked")))} +The run is Gauss-Newton alone, as with \code{hessianMethod = "gn"}, where +phases are not available (multiple shooting, \code{boundary = "clip"}) and +on the sparse path, see \code{sparse}. +} + \section{Box bounds}{ \code{boundary = "reflective"} (default) uses the interior @@ -382,14 +465,18 @@ from the factorization of \eqn{H} where \eqn{H} is positive definite and from the dense eigendecomposition elsewhere. \code{trustL1} applies the same condition to the model of the coordinates not held at a kink. Without the condition the run goes on, within \code{iterlim}; \code{mtol = 0} -drops the condition. +drops the condition. A run that goes on this way and then ends on the +radius without an accepted step that changes the value by \code{ftol} or +more ends on the stop held back, with \code{converged = TRUE}: the decrease +the model predicts is below the resolution of the objective. \code{stopReason} in the result names the test that fired: \code{"gradient"}, \code{"fvalue"}, \code{"preddiff"}, \code{"step"}, \code{"stagnation"}, \code{"radius"}, \code{"objfun"} (three failed evaluations in a row, ten with multiple shooting) or \code{"iterlim"}. -Stagnation reports -\code{converged = TRUE}. +Stagnation reports \code{converged = TRUE} where the full Newton step +predicts a decrease of at most \code{mtol} or a stop was held back as +above, and \code{converged = FALSE} otherwise. Only \code{gtol} tests first-order optimality. While \code{switches} remain, see \code{phases}, an \code{"fvalue"}, \code{"preddiff"}, @@ -410,13 +497,17 @@ the last accepted one when \code{stepControl$nonmonotone = 0}. An objective built by \code{\link{normL2}(..., multipleShootingControl = )}, alone or in a sum, is optimized by multiple shooting with the same controls. -Not available then: \code{hessianMethod = "exact"}, more than one phase, +Not available then: \code{hessianMethod = "exact"} and the structured +methods, more than one phase, \code{switches}, \code{qnControl$hessianInit = "exact"}, \code{qnControl$hessianReseed}, \code{qnControl$qnMemory}, \code{stepControl$nonmonotone}, \code{boundary = "clip"}, \code{minimize = FALSE} and \code{traceFile}. The run reports \code{converged = TRUE} only when the scaled gaps between -the segments are below \code{tolControl$ctol}. The method is described in +the segments are below \code{tolControl$ctol}. The stops follow section +Convergence, with the full step of the condensed model as the Newton step; +stagnation also needs the gaps flat within \code{ctol}. The method is +described in the methods article \href{https://dmodverse.github.io/dMod2/articles/methods-multiple-shooting.html}{Multiple shooting}. } @@ -451,6 +542,10 @@ fit$evalBySource } \references{ +Byrd, R. H., Nocedal, J. and Schnabel, R. B. (1994). +Representations of quasi-Newton matrices and their use in limited memory +methods. \emph{Mathematical Programming} 63, 129-156. + Coleman, T. F. and Li, Y. (1996). An interior trust region approach for nonlinear minimization subject to bounds. \emph{SIAM Journal on Optimization} 6(2), 418-445. @@ -474,6 +569,19 @@ Voss, H. U., Timmer, J. and Kurths, J. (2004). Nonlinear dynamical system identification from uncertain and indirect measurements. \emph{International Journal of Bifurcation and Chaos} 14(6), 1905-1933. +Dennis, J. E., Martínez, H. J. and Tapia, R. A. (1989). Convergence theory +for the structured BFGS secant method with an application to nonlinear +least squares. \emph{Journal of Optimization Theory and Applications} +61(2), 161-178. + +Huschens, J. (1994). On the use of product structure in secant methods +for nonlinear least squares problems. \emph{SIAM Journal on Optimization} +4(1), 108-129. + +Zhou, W. and Chen, X. (2010). Global convergence of a new hybrid +Gauss-Newton structured BFGS method for nonlinear least squares problems. +\emph{SIAM Journal on Optimization} 20(5), 2422-2441. + Peifer, M. and Timmer, J. (2007). Parameter estimation in ordinary differential equations for biochemical processes using the method of multiple shooting. \emph{IET Systems Biology} 1(2), 78-88. diff --git a/pkgdown/index.md b/pkgdown/index.md index 3d68bef3..558c54a2 100644 --- a/pkgdown/index.md +++ b/pkgdown/index.md @@ -7,7 +7,7 @@ and estimates their parameters from data. remotes::install_github("dModverse/dMod2") ``` -## Where to go +## Documentation - [Get started](articles/dMod2.html): a model of bile acid transport from reactions to profile likelihoods. diff --git a/src/Makevars b/src/Makevars index 495ed357..72b13c81 100644 --- a/src/Makevars +++ b/src/Makevars @@ -8,4 +8,5 @@ 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: residual_kernel.h trust_subproblem.h trust_model.h trust_driver.h +focei_kernel.o: nlme_kernel.h trust_model.h trust_driver.h +nlme_kernel.o: nlme_kernel.h residual_kernel.h trust_subproblem.h diff --git a/src/Makevars.win b/src/Makevars.win index 495ed357..72b13c81 100644 --- a/src/Makevars.win +++ b/src/Makevars.win @@ -8,4 +8,5 @@ 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: residual_kernel.h trust_subproblem.h trust_model.h trust_driver.h +focei_kernel.o: nlme_kernel.h trust_model.h trust_driver.h +nlme_kernel.o: nlme_kernel.h residual_kernel.h trust_subproblem.h diff --git a/src/RcppExports.cpp b/src/RcppExports.cpp index 0fc0448b..d8a42ce4 100644 --- a/src/RcppExports.cpp +++ b/src/RcppExports.cpp @@ -123,8 +123,8 @@ BEGIN_RCPP END_RCPP } // chain_data -SEXP chain_data(List plan, List pre, List raw, bool deriv, bool deriv2, bool build_hessian, bool local, int threads, std::string bloq_mode, double t_df, bool want_seed, bool sparse); -RcppExport SEXP _dMod2_chain_data(SEXP planSEXP, SEXP preSEXP, SEXP rawSEXP, SEXP derivSEXP, SEXP deriv2SEXP, SEXP build_hessianSEXP, SEXP localSEXP, SEXP threadsSEXP, SEXP bloq_modeSEXP, SEXP t_dfSEXP, SEXP want_seedSEXP, SEXP sparseSEXP) { +SEXP chain_data(List plan, List pre, List raw, bool deriv, bool deriv2, bool build_hessian, bool local, int threads, std::string bloq_mode, double t_df, bool want_seed, bool sparse, bool want_rows); +RcppExport SEXP _dMod2_chain_data(SEXP planSEXP, SEXP preSEXP, SEXP rawSEXP, SEXP derivSEXP, SEXP deriv2SEXP, SEXP build_hessianSEXP, SEXP localSEXP, SEXP threadsSEXP, SEXP bloq_modeSEXP, SEXP t_dfSEXP, SEXP want_seedSEXP, SEXP sparseSEXP, SEXP want_rowsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; @@ -140,7 +140,8 @@ BEGIN_RCPP Rcpp::traits::input_parameter< double >::type t_df(t_dfSEXP); Rcpp::traits::input_parameter< bool >::type want_seed(want_seedSEXP); Rcpp::traits::input_parameter< bool >::type sparse(sparseSEXP); - rcpp_result_gen = Rcpp::wrap(chain_data(plan, pre, raw, deriv, deriv2, build_hessian, local, threads, bloq_mode, t_df, want_seed, sparse)); + Rcpp::traits::input_parameter< bool >::type want_rows(want_rowsSEXP); + rcpp_result_gen = Rcpp::wrap(chain_data(plan, pre, raw, deriv, deriv2, build_hessian, local, threads, bloq_mode, t_df, want_seed, sparse, want_rows)); return rcpp_result_gen; END_RCPP } @@ -266,29 +267,9 @@ BEGIN_RCPP return rcpp_result_gen; END_RCPP } -// focei_inner_trust -List focei_inner_trust(Function model_cb, Function err_cb, NumericVector pars_full, NumericMatrix eta_warmstart, List subject_meta, NumericMatrix Omega_inv_mat, double Omega_log_det, Nullable fixed, List control, Nullable predict_cb); -RcppExport SEXP _dMod2_focei_inner_trust(SEXP model_cbSEXP, SEXP err_cbSEXP, SEXP pars_fullSEXP, SEXP eta_warmstartSEXP, SEXP subject_metaSEXP, SEXP Omega_inv_matSEXP, SEXP Omega_log_detSEXP, SEXP fixedSEXP, SEXP controlSEXP, SEXP predict_cbSEXP) { -BEGIN_RCPP - Rcpp::RObject rcpp_result_gen; - Rcpp::RNGScope rcpp_rngScope_gen; - Rcpp::traits::input_parameter< Function >::type model_cb(model_cbSEXP); - Rcpp::traits::input_parameter< Function >::type err_cb(err_cbSEXP); - Rcpp::traits::input_parameter< NumericVector >::type pars_full(pars_fullSEXP); - Rcpp::traits::input_parameter< NumericMatrix >::type eta_warmstart(eta_warmstartSEXP); - Rcpp::traits::input_parameter< List >::type subject_meta(subject_metaSEXP); - Rcpp::traits::input_parameter< NumericMatrix >::type Omega_inv_mat(Omega_inv_matSEXP); - Rcpp::traits::input_parameter< double >::type Omega_log_det(Omega_log_detSEXP); - Rcpp::traits::input_parameter< Nullable >::type fixed(fixedSEXP); - Rcpp::traits::input_parameter< List >::type control(controlSEXP); - Rcpp::traits::input_parameter< Nullable >::type predict_cb(predict_cbSEXP); - rcpp_result_gen = Rcpp::wrap(focei_inner_trust(model_cb, err_cb, pars_full, eta_warmstart, subject_meta, Omega_inv_mat, Omega_log_det, fixed, control, predict_cb)); - return rcpp_result_gen; -END_RCPP -} // focei_run -List focei_run(Function model_cb, Function err_cb, Function joint_cb, NumericVector init, List subject_meta, Nullable fixed, List control, std::string correction_mode, Nullable correction_cb, Nullable predict_cb); -RcppExport SEXP _dMod2_focei_run(SEXP model_cbSEXP, SEXP err_cbSEXP, SEXP joint_cbSEXP, SEXP initSEXP, SEXP subject_metaSEXP, SEXP fixedSEXP, SEXP controlSEXP, SEXP correction_modeSEXP, SEXP correction_cbSEXP, SEXP predict_cbSEXP) { +List focei_run(Function model_cb, Function err_cb, Function joint_cb, NumericVector init, List subject_meta, Nullable fixed, List control, std::string correction_mode, Nullable correction_cb, Nullable predict_cb, Nullable eta_init); +RcppExport SEXP _dMod2_focei_run(SEXP model_cbSEXP, SEXP err_cbSEXP, SEXP joint_cbSEXP, SEXP initSEXP, SEXP subject_metaSEXP, SEXP fixedSEXP, SEXP controlSEXP, SEXP correction_modeSEXP, SEXP correction_cbSEXP, SEXP predict_cbSEXP, SEXP eta_initSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; @@ -302,13 +283,14 @@ BEGIN_RCPP Rcpp::traits::input_parameter< std::string >::type correction_mode(correction_modeSEXP); Rcpp::traits::input_parameter< Nullable >::type correction_cb(correction_cbSEXP); Rcpp::traits::input_parameter< Nullable >::type predict_cb(predict_cbSEXP); - rcpp_result_gen = Rcpp::wrap(focei_run(model_cb, err_cb, joint_cb, init, subject_meta, fixed, control, correction_mode, correction_cb, predict_cb)); + Rcpp::traits::input_parameter< Nullable >::type eta_init(eta_initSEXP); + rcpp_result_gen = Rcpp::wrap(focei_run(model_cb, err_cb, joint_cb, init, subject_meta, fixed, control, correction_mode, correction_cb, predict_cb, eta_init)); return rcpp_result_gen; END_RCPP } // focei_run_sparse -List focei_run_sparse(Function trial, Function complete, NumericVector init, int N, int K, List outer_ctrl, double inner_rinit); -RcppExport SEXP _dMod2_focei_run_sparse(SEXP trialSEXP, SEXP completeSEXP, SEXP initSEXP, SEXP NSEXP, SEXP KSEXP, SEXP outer_ctrlSEXP, SEXP inner_rinitSEXP) { +List focei_run_sparse(Function trial, Function complete, NumericVector init, int N, int K, List outer_ctrl, double inner_rinit, Nullable eta_init); +RcppExport SEXP _dMod2_focei_run_sparse(SEXP trialSEXP, SEXP completeSEXP, SEXP initSEXP, SEXP NSEXP, SEXP KSEXP, SEXP outer_ctrlSEXP, SEXP inner_rinitSEXP, SEXP eta_initSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; @@ -319,7 +301,8 @@ BEGIN_RCPP Rcpp::traits::input_parameter< int >::type K(KSEXP); Rcpp::traits::input_parameter< List >::type outer_ctrl(outer_ctrlSEXP); Rcpp::traits::input_parameter< double >::type inner_rinit(inner_rinitSEXP); - rcpp_result_gen = Rcpp::wrap(focei_run_sparse(trial, complete, init, N, K, outer_ctrl, inner_rinit)); + Rcpp::traits::input_parameter< Nullable >::type eta_init(eta_initSEXP); + rcpp_result_gen = Rcpp::wrap(focei_run_sparse(trial, complete, init, N, K, outer_ctrl, inner_rinit, eta_init)); return rcpp_result_gen; END_RCPP } @@ -332,9 +315,29 @@ BEGIN_RCPP return R_NilValue; END_RCPP } +// nlme_group_kernel +List nlme_group_kernel(Function model_cb, Function err_cb, NumericVector pars_full, NumericMatrix eta_warmstart, List subject_meta, NumericMatrix Omega_inv_mat, double Omega_log_det, Nullable fixed, List control, Nullable predict_cb); +RcppExport SEXP _dMod2_nlme_group_kernel(SEXP model_cbSEXP, SEXP err_cbSEXP, SEXP pars_fullSEXP, SEXP eta_warmstartSEXP, SEXP subject_metaSEXP, SEXP Omega_inv_matSEXP, SEXP Omega_log_detSEXP, SEXP fixedSEXP, SEXP controlSEXP, SEXP predict_cbSEXP) { +BEGIN_RCPP + Rcpp::RObject rcpp_result_gen; + Rcpp::RNGScope rcpp_rngScope_gen; + Rcpp::traits::input_parameter< Function >::type model_cb(model_cbSEXP); + Rcpp::traits::input_parameter< Function >::type err_cb(err_cbSEXP); + Rcpp::traits::input_parameter< NumericVector >::type pars_full(pars_fullSEXP); + Rcpp::traits::input_parameter< NumericMatrix >::type eta_warmstart(eta_warmstartSEXP); + Rcpp::traits::input_parameter< List >::type subject_meta(subject_metaSEXP); + Rcpp::traits::input_parameter< NumericMatrix >::type Omega_inv_mat(Omega_inv_matSEXP); + Rcpp::traits::input_parameter< double >::type Omega_log_det(Omega_log_detSEXP); + Rcpp::traits::input_parameter< Nullable >::type fixed(fixedSEXP); + Rcpp::traits::input_parameter< List >::type control(controlSEXP); + Rcpp::traits::input_parameter< Nullable >::type predict_cb(predict_cbSEXP); + rcpp_result_gen = Rcpp::wrap(nlme_group_kernel(model_cb, err_cb, pars_full, eta_warmstart, subject_meta, Omega_inv_mat, Omega_log_det, fixed, control, predict_cb)); + return rcpp_result_gen; +END_RCPP +} // normL2_kernel -List normL2_kernel(List prediction, Nullable err_list_opt, List meta_list, CharacterVector par_names_global, bool deriv2_requested, int threads, std::string bloq_mode, bool build_hessian, bool want_seed, bool local_blocks, double t_df); -RcppExport SEXP _dMod2_normL2_kernel(SEXP predictionSEXP, SEXP err_list_optSEXP, SEXP meta_listSEXP, SEXP par_names_globalSEXP, SEXP deriv2_requestedSEXP, SEXP threadsSEXP, SEXP bloq_modeSEXP, SEXP build_hessianSEXP, SEXP want_seedSEXP, SEXP local_blocksSEXP, SEXP t_dfSEXP) { +List normL2_kernel(List prediction, Nullable err_list_opt, List meta_list, CharacterVector par_names_global, bool deriv2_requested, int threads, std::string bloq_mode, bool build_hessian, bool want_seed, bool local_blocks, double t_df, bool expected, bool want_rows); +RcppExport SEXP _dMod2_normL2_kernel(SEXP predictionSEXP, SEXP err_list_optSEXP, SEXP meta_listSEXP, SEXP par_names_globalSEXP, SEXP deriv2_requestedSEXP, SEXP threadsSEXP, SEXP bloq_modeSEXP, SEXP build_hessianSEXP, SEXP want_seedSEXP, SEXP local_blocksSEXP, SEXP t_dfSEXP, SEXP expectedSEXP, SEXP want_rowsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; @@ -349,7 +352,9 @@ BEGIN_RCPP Rcpp::traits::input_parameter< bool >::type want_seed(want_seedSEXP); Rcpp::traits::input_parameter< bool >::type local_blocks(local_blocksSEXP); Rcpp::traits::input_parameter< double >::type t_df(t_dfSEXP); - rcpp_result_gen = Rcpp::wrap(normL2_kernel(prediction, err_list_opt, meta_list, par_names_global, deriv2_requested, threads, bloq_mode, build_hessian, want_seed, local_blocks, t_df)); + Rcpp::traits::input_parameter< bool >::type expected(expectedSEXP); + Rcpp::traits::input_parameter< bool >::type want_rows(want_rowsSEXP); + rcpp_result_gen = Rcpp::wrap(normL2_kernel(prediction, err_list_opt, meta_list, par_names_global, deriv2_requested, threads, bloq_mode, build_hessian, want_seed, local_blocks, t_df, expected, want_rows)); return rcpp_result_gen; END_RCPP } @@ -559,8 +564,8 @@ BEGIN_RCPP END_RCPP } // trust_impl -List trust_impl(Function objfun, NumericVector parinit, double rinit, double rmax, Nullable parscale, int iterlim, double ftol, double mtol, double gtol, double xtol, double rmin, double thetamax, std::string boundary, CharacterVector phaseMethod, IntegerVector phaseIterlim, LogicalVector phaseReverse, CharacterVector phaseInit, CharacterVector phaseReseed, IntegerVector phaseMemory, NumericVector phaseCautious, LogicalVector phaseRejected, int switches, double nonmonotone, bool sparse, bool minimize, bool blather, Nullable parupper, Nullable parlower, bool printIter, Nullable traceFile); -RcppExport SEXP _dMod2_trust_impl(SEXP objfunSEXP, SEXP parinitSEXP, SEXP rinitSEXP, SEXP rmaxSEXP, SEXP parscaleSEXP, SEXP iterlimSEXP, SEXP ftolSEXP, SEXP mtolSEXP, SEXP gtolSEXP, SEXP xtolSEXP, SEXP rminSEXP, SEXP thetamaxSEXP, SEXP boundarySEXP, SEXP phaseMethodSEXP, SEXP phaseIterlimSEXP, SEXP phaseReverseSEXP, SEXP phaseInitSEXP, SEXP phaseReseedSEXP, SEXP phaseMemorySEXP, SEXP phaseCautiousSEXP, SEXP phaseRejectedSEXP, SEXP switchesSEXP, SEXP nonmonotoneSEXP, SEXP sparseSEXP, SEXP minimizeSEXP, SEXP blatherSEXP, SEXP parupperSEXP, SEXP parlowerSEXP, SEXP printIterSEXP, SEXP traceFileSEXP) { +List trust_impl(Function objfun, NumericVector parinit, double rinit, double rmax, Nullable parscale, int iterlim, double ftol, double mtol, double gtol, double xtol, double rmin, double thetamax, std::string boundary, CharacterVector phaseMethod, IntegerVector phaseIterlim, IntegerVector phaseRadiusStall, LogicalVector phaseReverse, LogicalVector phaseKeepRadius, LogicalVector phaseStopEnds, CharacterVector phaseInit, CharacterVector phaseReseed, IntegerVector phaseMemory, NumericVector phaseCautious, LogicalVector phaseRejected, LogicalVector phaseScaled, NumericVector phaseHybridTol, LogicalVector phaseHybridShift, int switches, double nonmonotone, bool sparse, bool minimize, bool blather, Nullable parupper, Nullable parlower, bool printIter, Nullable traceFile); +RcppExport SEXP _dMod2_trust_impl(SEXP objfunSEXP, SEXP parinitSEXP, SEXP rinitSEXP, SEXP rmaxSEXP, SEXP parscaleSEXP, SEXP iterlimSEXP, SEXP ftolSEXP, SEXP mtolSEXP, SEXP gtolSEXP, SEXP xtolSEXP, SEXP rminSEXP, SEXP thetamaxSEXP, SEXP boundarySEXP, SEXP phaseMethodSEXP, SEXP phaseIterlimSEXP, SEXP phaseRadiusStallSEXP, SEXP phaseReverseSEXP, SEXP phaseKeepRadiusSEXP, SEXP phaseStopEndsSEXP, SEXP phaseInitSEXP, SEXP phaseReseedSEXP, SEXP phaseMemorySEXP, SEXP phaseCautiousSEXP, SEXP phaseRejectedSEXP, SEXP phaseScaledSEXP, SEXP phaseHybridTolSEXP, SEXP phaseHybridShiftSEXP, SEXP switchesSEXP, SEXP nonmonotoneSEXP, SEXP sparseSEXP, SEXP minimizeSEXP, SEXP blatherSEXP, SEXP parupperSEXP, SEXP parlowerSEXP, SEXP printIterSEXP, SEXP traceFileSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; @@ -579,12 +584,18 @@ BEGIN_RCPP Rcpp::traits::input_parameter< std::string >::type boundary(boundarySEXP); Rcpp::traits::input_parameter< CharacterVector >::type phaseMethod(phaseMethodSEXP); Rcpp::traits::input_parameter< IntegerVector >::type phaseIterlim(phaseIterlimSEXP); + Rcpp::traits::input_parameter< IntegerVector >::type phaseRadiusStall(phaseRadiusStallSEXP); Rcpp::traits::input_parameter< LogicalVector >::type phaseReverse(phaseReverseSEXP); + Rcpp::traits::input_parameter< LogicalVector >::type phaseKeepRadius(phaseKeepRadiusSEXP); + Rcpp::traits::input_parameter< LogicalVector >::type phaseStopEnds(phaseStopEndsSEXP); Rcpp::traits::input_parameter< CharacterVector >::type phaseInit(phaseInitSEXP); Rcpp::traits::input_parameter< CharacterVector >::type phaseReseed(phaseReseedSEXP); Rcpp::traits::input_parameter< IntegerVector >::type phaseMemory(phaseMemorySEXP); Rcpp::traits::input_parameter< NumericVector >::type phaseCautious(phaseCautiousSEXP); Rcpp::traits::input_parameter< LogicalVector >::type phaseRejected(phaseRejectedSEXP); + Rcpp::traits::input_parameter< LogicalVector >::type phaseScaled(phaseScaledSEXP); + Rcpp::traits::input_parameter< NumericVector >::type phaseHybridTol(phaseHybridTolSEXP); + Rcpp::traits::input_parameter< LogicalVector >::type phaseHybridShift(phaseHybridShiftSEXP); Rcpp::traits::input_parameter< int >::type switches(switchesSEXP); Rcpp::traits::input_parameter< double >::type nonmonotone(nonmonotoneSEXP); Rcpp::traits::input_parameter< bool >::type sparse(sparseSEXP); @@ -594,7 +605,7 @@ BEGIN_RCPP Rcpp::traits::input_parameter< Nullable >::type parlower(parlowerSEXP); Rcpp::traits::input_parameter< bool >::type printIter(printIterSEXP); Rcpp::traits::input_parameter< Nullable >::type traceFile(traceFileSEXP); - rcpp_result_gen = Rcpp::wrap(trust_impl(objfun, parinit, rinit, rmax, parscale, iterlim, ftol, mtol, gtol, xtol, rmin, thetamax, boundary, phaseMethod, phaseIterlim, phaseReverse, phaseInit, phaseReseed, phaseMemory, phaseCautious, phaseRejected, switches, nonmonotone, sparse, minimize, blather, parupper, parlower, printIter, traceFile)); + rcpp_result_gen = Rcpp::wrap(trust_impl(objfun, parinit, rinit, rmax, parscale, iterlim, ftol, mtol, gtol, xtol, rmin, thetamax, boundary, phaseMethod, phaseIterlim, phaseRadiusStall, phaseReverse, phaseKeepRadius, phaseStopEnds, phaseInit, phaseReseed, phaseMemory, phaseCautious, phaseRejected, phaseScaled, phaseHybridTol, phaseHybridShift, switches, nonmonotone, sparse, minimize, blather, parupper, parlower, printIter, traceFile)); return rcpp_result_gen; END_RCPP } @@ -706,7 +717,7 @@ static const R_CallMethodDef CallEntries[] = { {"_dMod2_bmm_rb", (DL_FUNC) &_dMod2_bmm_rb, 6}, {"_dMod2_bmm_bb", (DL_FUNC) &_dMod2_bmm_bb, 6}, {"_dMod2_chain_params", (DL_FUNC) &_dMod2_chain_params, 6}, - {"_dMod2_chain_data", (DL_FUNC) &_dMod2_chain_data, 12}, + {"_dMod2_chain_data", (DL_FUNC) &_dMod2_chain_data, 13}, {"_dMod2_chain_frames", (DL_FUNC) &_dMod2_chain_frames, 5}, {"_dMod2_chain_rows", (DL_FUNC) &_dMod2_chain_rows, 4}, {"_dMod2_chain_back", (DL_FUNC) &_dMod2_chain_back, 8}, @@ -714,11 +725,11 @@ static const R_CallMethodDef CallEntries[] = { {"_dMod2_chain_unit_sums", (DL_FUNC) &_dMod2_chain_unit_sums, 3}, {"_dMod2_constraintL2_scalar_kernel", (DL_FUNC) &_dMod2_constraintL2_scalar_kernel, 12}, {"_dMod2_datapointL2_kernel", (DL_FUNC) &_dMod2_datapointL2_kernel, 11}, - {"_dMod2_focei_inner_trust", (DL_FUNC) &_dMod2_focei_inner_trust, 10}, - {"_dMod2_focei_run", (DL_FUNC) &_dMod2_focei_run, 10}, - {"_dMod2_focei_run_sparse", (DL_FUNC) &_dMod2_focei_run_sparse, 7}, + {"_dMod2_focei_run", (DL_FUNC) &_dMod2_focei_run, 11}, + {"_dMod2_focei_run_sparse", (DL_FUNC) &_dMod2_focei_run_sparse, 8}, {"_dMod2_release_heap", (DL_FUNC) &_dMod2_release_heap, 0}, - {"_dMod2_normL2_kernel", (DL_FUNC) &_dMod2_normL2_kernel, 11}, + {"_dMod2_nlme_group_kernel", (DL_FUNC) &_dMod2_nlme_group_kernel, 10}, + {"_dMod2_normL2_kernel", (DL_FUNC) &_dMod2_normL2_kernel, 13}, {"_dMod2_parvec_attach", (DL_FUNC) &_dMod2_parvec_attach, 3}, {"_dMod2_parvec_concat", (DL_FUNC) &_dMod2_parvec_concat, 1}, {"_dMod2_pimpl_state", (DL_FUNC) &_dMod2_pimpl_state, 1}, @@ -733,7 +744,7 @@ static const R_CallMethodDef CallEntries[] = { {"_dMod2_sparse_factor", (DL_FUNC) &_dMod2_sparse_factor, 6}, {"_dMod2_systemTimes", (DL_FUNC) &_dMod2_systemTimes, 0}, {"_dMod2_trustL1_impl", (DL_FUNC) &_dMod2_trustL1_impl, 24}, - {"_dMod2_trust_impl", (DL_FUNC) &_dMod2_trust_impl, 30}, + {"_dMod2_trust_impl", (DL_FUNC) &_dMod2_trust_impl, 36}, {"_dMod2_sparse_factor_cost", (DL_FUNC) &_dMod2_sparse_factor_cost, 3}, {"_dMod2_trust_model_step", (DL_FUNC) &_dMod2_trust_model_step, 5}, {"_dMod2_trust_step_impl", (DL_FUNC) &_dMod2_trust_step_impl, 8}, diff --git a/src/chain_kernel.cpp b/src/chain_kernel.cpp index 35e2ba17..9f525288 100644 --- a/src/chain_kernel.cpp +++ b/src/chain_kernel.cpp @@ -647,11 +647,15 @@ List sparseHessian(const List& conds, const std::vector& in, const std::vect // `want_seed` also seed_pred and seed_sigma, the derivatives of the value in the prediction and // sigma of every data row, in the order of the conditions and of their data, and seed_chi2_pred, // seed_chi2_sigma those of chi2. With `sparse` the Hessian over the global parameters is -// list(i, p, x), the 0-based slots of a column-compressed matrix without zero entries. NULL where -// a solve or a function fails or a prediction at a data point is not finite. +// list(i, p, x), the 0-based slots of a column-compressed matrix without zero entries. With +// `want_rows` also rows = list(jacobian, seeds): the derivatives of the predictions, and of the sigmas +// that depend on parameters, over the global parameters, one row per data row, and the derivatives +// of the value in them. NULL where a solve or a function fails or a prediction at a data point is +// not finite. // [[Rcpp::export]] SEXP chain_data(List plan, List pre, List raw, bool deriv, bool deriv2, bool build_hessian, bool local, - int threads, std::string bloq_mode, double t_df, bool want_seed, bool sparse = false) { + int threads, std::string bloq_mode, double t_df, bool want_seed, bool sparse = false, + bool want_rows = false) { List conds = plan["cond"]; const int K = conds.size(); const int nGlobal = as(plan["n_global"]); @@ -672,6 +676,9 @@ SEXP chain_data(List plan, List pre, List raw, bool deriv, bool deriv2, bool bui std::vector ok(K, 1); std::vector value(K, 0.0), chi2(K, 0.0); std::vector> grad(K), hess(K); + // with `want_rows` the data rows of each condition in the condition directions and their seeds + const bool seeds_on = want_seed || want_rows; + std::vector> rowJ(K), rowU(K); const int nt = chainThreads(threads, K); #ifdef _OPENMP #pragma omp parallel for schedule(dynamic) num_threads(nt) if (nt > 1) @@ -737,7 +744,7 @@ SEXP chain_data(List plan, List pre, List raw, bool deriv, bool deriv2, bool bui opts.sigma_depends_on_par = hasDs; opts.d2sigma_present = d2 && hasDs; double v = 0.0, ch = 0.0; - std::vector sp(want_seed ? n : 0, 0.0), ss(want_seed ? n : 0, 0.0), cp(want_seed ? n : 0, 0.0), + std::vector sp(seeds_on ? n : 0, 0.0), ss(seeds_on ? n : 0, 0.0), cp(want_seed ? n : 0, 0.0), cs(want_seed ? n : 0, 0.0); if (want_seed && na > 0) dmod::chi2_seeds(na, pred.data(), ydat.data(), sig.data(), cp.data(), cs.data()); if (na > 0) @@ -745,7 +752,7 @@ SEXP chain_data(List plan, List pre, List raw, bool deriv, bool deriv2, bool bui sig.data(), hasDs ? dsig.data() : nullptr, d2 && hasDs ? d2sig.data() : nullptr, lloq.data(), opts, v, ch, grad[c].data(), build_hessian ? hess[c].data() : nullptr, - want_seed ? sp.data() : nullptr, want_seed ? ss.data() : nullptr); + seeds_on ? sp.data() : nullptr, seeds_on ? ss.data() : nullptr); if (n > na) { const std::size_t off = na, off2 = off * nd, off3 = off * nd2; dmod::accumulate_bloq_residual(n - na, nd, pred.data() + off, dpred.data() + off2, @@ -753,7 +760,18 @@ SEXP chain_data(List plan, List pre, List raw, bool deriv, bool deriv2, bool bui hasDs ? dsig.data() + off2 : nullptr, d2 && hasDs ? d2sig.data() + off3 : nullptr, lloq.data() + off, opts, v, grad[c].data(), build_hessian ? hess[c].data() : nullptr, - want_seed ? sp.data() + off : nullptr, want_seed ? ss.data() + off : nullptr); + 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); + std::copy(dpred.begin(), dpred.end(), rowJ[c].begin()); + std::copy(sp.begin(), sp.end(), rowU[c].begin()); + if (hasDs) { + std::copy(dsig.begin(), dsig.end(), rowJ[c].begin() + (std::size_t) n * nd); + std::copy(ss.begin(), ss.end(), rowU[c].begin() + n); + } } // the seeds back in the order of the data for (int j = 0; j < n && want_seed; ++j) { @@ -818,6 +836,25 @@ SEXP chain_data(List plan, List pre, List raw, bool deriv, bool deriv2, bool bui } } out["gradient"] = NumericVector(g.begin(), g.end()); + if (want_rows) { + int nRows = 0; + for (int c = 0; c < K; ++c) nRows += (int) rowU[c].size(); + NumericMatrix J(nRows, nGlobal); + NumericVector u(nRows); + int r0 = 0; + for (int c = 0; c < K; ++c) { + List pc = conds[c]; + IntegerVector dg = pc["dir_global"]; + const int nd = in[c].nd, m = (int) rowU[c].size(); + for (int j = 0; j < m; ++j) { + u[r0 + j] = rowU[c][j]; + for (int a = 0; a < nd; ++a) + if (dg[a] >= 0) J(r0 + j, dg[a]) = rowJ[c][(std::size_t) j * nd + a]; + } + r0 += m; + } + out["rows"] = List::create(Named("jacobian") = J, Named("seeds") = u); + } if (build_hessian && sparse) out["hessian"] = sparseHessian(conds, in, hess, nGlobal); else if (build_hessian) { NumericMatrix Hm(nGlobal, nGlobal); diff --git a/src/focei_kernel.cpp b/src/focei_kernel.cpp index 37dbcd8e..5979084f 100644 --- a/src/focei_kernel.cpp +++ b/src/focei_kernel.cpp @@ -1,4 +1,4 @@ -// dMod FOCEI kernel. +// dMod FOCEI kernel: the outer problem on the group kernel of nlme_kernel.h. // // Math anchors (load-bearing, do not change without re-deriving): // - Envelope theorem: at eta = eta*(theta), d/dtheta f(theta, eta*) = @@ -18,136 +18,16 @@ #include #include #include +#include -#include -#include -#include - -#include "residual_kernel.h" -#include "trust_subproblem.h" +#include "nlme_kernel.h" #include "trust_model.h" -#include #include "trust_driver.h" using namespace Rcpp; +using dmod::nlme::ctrl_tol; +using dmod::nlme::shrunk_radius; -// R >= 3.6.2 appends hidden Fortran string lengths to BLAS/LAPACK char args. -#ifndef FCONE -#define FCONE -#endif - -// Tolerance from a control list, accepting the deprecated trust() alias. -static double ctrl_tol(const List& ctrl, const char* key, const char* legacy, - double dflt) { - if (ctrl.containsElementNamed(key)) return as(ctrl[key]); - if (ctrl.containsElementNamed(legacy)) return as(ctrl[legacy]); - return dflt; -} - - -// Whether a trial is accepted: by the ratio of the actual to the predicted decrease, and near the -// modes, where a Newton step predicts less than 1e-6 of the value, also by a smaller gradient: the -// solver's error in the value there exceeds what the step gains, the gradient is still measured. -static bool accept_trial(double rho, bool is_newton, double predicted_red, double val, const std::vector& grad, - const std::vector& grad_try) { - if (rho >= 0.25) return true; - if (!is_newton || predicted_red > 1e-6 * std::max(1.0, std::fabs(val))) return false; - double g0 = 0.0, g1 = 0.0; - for (std::size_t k = 0; k < grad.size(); ++k) { g0 += grad[k] * grad[k]; g1 += grad_try[k] * grad_try[k]; } - return g1 < g0; -} - -// The modes are found where the Gauss-Newton step H^-1 g, on H and not on the secant model, is below -// `steptol`, as the volume term is linear in their error; or where a step on the boundary gains less -// than `mtol` of the value `val`, the region shrunk below the distance to the modes. -static bool modes_found(int K, const std::vector& grad, const std::vector& eigvals, - const std::vector& eigvecs, double predicted_red, bool is_newton, double steptol, - double mtol, double val) { - if (!is_newton) return std::fabs(predicted_red) <= mtol * std::max(1.0, std::fabs(val)); - double tr = 0.0; - for (int k = 0; k < K; ++k) tr += std::fabs(eigvals[k]); - const double floor = 1e-10 * tr / std::max(K, 1); - double s2 = 0.0; - for (int k = 0; k < K; ++k) { - double c = 0.0; - for (int j = 0; j < K; ++j) c += eigvecs[j + (std::size_t) K * k] * grad[j]; - const double step = c / std::max(eigvals[k], floor); - s2 += step * step; - } - return std::sqrt(s2) <= steptol; -} - - -// Thin wrappers over the Moré-Sorensen subproblem and eigendecomposition in -// trust_subproblem.h, shared with trust_kernel.cpp and covering the hard case. -// A Hessian that is not finite stops the evaluation: LAPACK does not return on NaN input. -static inline void eigen_sym(double* A, int K, double* vals, double* vecs) { - for (std::size_t i = 0; i < (std::size_t) K * K; ++i) - if (!std::isfinite(A[i])) throw std::runtime_error("FOCEI: the Hessian is not finite."); - dmod::trust_internal::eigen_sym_local(A, K, vals, vecs); -} - -// The inner trust steps on the Gauss-Newton Hessian H plus S, the curvature of the prediction -// in the etas that Gauss-Newton drops, learned by SR1 from the gradients of accepted steps: -// (H_new + S) step = g_new - g_old after the update. -static void secant_update(int K, std::vector& S, const std::vector& step, - const std::vector& g_old, const std::vector& g_new, - const std::vector& H_new) { - std::vector v(K); - double vs = 0.0, vv = 0.0, ss = 0.0; - for (int r = 0; r < K; ++r) { - double hs = 0.0; - for (int c = 0; c < K; ++c) hs += (H_new[r + c * K] + S[r + c * K]) * step[c]; - v[r] = g_new[r] - g_old[r] - hs; - } - for (int r = 0; r < K; ++r) { vs += v[r] * step[r]; vv += v[r] * v[r]; ss += step[r] * step[r]; } - if (!(std::fabs(vs) > 1e-8 * std::sqrt(vv * ss))) return; - for (int c = 0; c < K; ++c) - for (int r = 0; r < K; ++r) S[r + c * K] += v[r] * v[c] / vs; -} - -// The radius after a rejected step: a quarter of the radius or of the step, whichever is -// shorter, so that a rejected Newton step well inside the region is not tried again. -static double shrunk_radius(double r, const double* step, int n) { - double ss = 0.0; - for (int k = 0; k < n; ++k) ss += step[k] * step[k]; - return 0.25 * std::min(r, std::sqrt(ss)); -} - -// Eigen decomposition of the step model H + S, or of H where H + S is not positive definite. -static void model_eigen(int K, const std::vector& H, const std::vector& S, - std::vector& vals, std::vector& vecs) { - std::vector B(H); - for (std::size_t q = 0; q < B.size(); ++q) B[q] += S[q]; - eigen_sym(B.data(), K, vals.data(), vecs.data()); - if (vals[0] <= 0.0) { - B = H; - eigen_sym(B.data(), K, vals.data(), vecs.data()); - } -} - -static inline void trust_subproblem(int K, const double* g, - const double* vals, const double* vecs, - double r, double* p, double* predicted_red, - bool* is_newton) { - bool is_hard = false, is_easy = false; - dmod::trust_internal::trust_sub(K, g, vals, vecs, r, p, predicted_red, - is_newton, &is_hard, &is_easy); -} - - -// Result of one subject's inner trust loop. -struct InnerResult { - std::vector eta; // K - std::vector grad; // K (analytical gradient at the final eta) - std::vector H_GN; // K*K column-major - std::vector H_inv; // K*K column-major (Moore-Penrose with eigen floor) - std::vector eigvals; // K (last-iter eigenvalues, ascending) - double log_det_H; - double value; - int iterations; - bool converged; -}; // Build 0-based indices into `haystack` for each name in `needles`; throws if @@ -170,754 +50,19 @@ static std::vector name_indices(const CharacterVector& haystack, } - - -// Parameter names of a [time, observable, parameter] deriv array. -static CharacterVector deriv_par_names(const NumericVector& d) { - const List dn = d.attr("dimnames"); - return as(dn[2]); -} - -// The derivative of sum_i log|H_i| in theta comes from R (`.foceiVolume`) through -// `correction_cb`, at the start, at accepted trials and at the final point; the -// trust ratio of a trial needs the trial value only. - - -// Inner objective for one subject from one model_cb and one err_cb call, without -// the normL2 / constraintL2 stack. Gauss-Newton: second derivatives of pred and -// sigma are dropped, first-order cross terms of an eta-dependent sigma kept. -struct EvalResult { - double value; - std::vector grad; // K - std::vector hess; // K*K column-major -}; - -static inline bool all_finite(const EvalResult& e) { - if (!std::isfinite(e.value)) return false; - for (double v : e.grad) if (!std::isfinite(v)) return false; - for (double v : e.hess) if (!std::isfinite(v)) return false; - return true; -} - -// The prediction and error-model frames of a subject, one per condition block; -// `failed` where the prediction of one of the subject blocks failed. -struct SubjectFrames { - std::vector pred, err; - bool failed = false; -}; - -// Split in two so the lock-step driver can batch the callbacks: this half -// runs them for the condition blocks of one subject, `eval_one_subject_from` -// is the pure math. -static void predict_one_subject( - Function& model_cb, Function& err_cb, NumericVector& pars, - Nullable fixed, const List& meta_i, const double* eta_block, - SubjectFrames* out) { - IntegerVector eta_idx_in_pars = meta_i["eta_idx_in_pars"]; - const int K = static_cast(eta_idx_in_pars.size()); - for (int k = 0; k < K; ++k) pars[eta_idx_in_pars[k] - 1] = eta_block[k]; - - List blocks = meta_i["blocks"]; - out->pred.assign(blocks.size(), NumericMatrix()); - out->err.assign(blocks.size(), NumericMatrix()); - for (int b = 0; b < blocks.size(); ++b) { - List block = blocks[b]; - NumericVector model_times = block["times"]; - CharacterVector condition = block["condition"]; - List pred_list = as(model_cb( - Rcpp::Named("times") = model_times, - Rcpp::Named("pars") = pars, - Rcpp::Named("fixed") = fixed, - Rcpp::Named("deriv") = true, - Rcpp::Named("conditions") = condition)); - out->pred[b] = as(pred_list[0]); - NumericVector pinner = out->pred[b].attr("parameters"); - List err_list = as(err_cb( - Rcpp::Named("out") = out->pred[b], - Rcpp::Named("pars") = pinner, - Rcpp::Named("conditions") = condition)); - out->err[b] = as(err_list[0]); - } -} - -// Data term of one condition block of a subject in the K subject etas, Gauss-Newton, -// added to value, grad and hess. -static void accumulate_block( - NumericMatrix& pred_i, - NumericMatrix& err_i, - const List& meta_i, - const CharacterVector& eta_names, - int K, - double& value, - std::vector& grad, - std::vector& hess) { - IntegerVector t_idx_in_pred = meta_i["t_idx_in_pred"]; - NumericVector y_data = meta_i["y_data"]; - IntegerVector o_idx_in_pred = meta_i["o_idx_in_pred"]; - IntegerVector o_idx_in_deriv = meta_i["o_idx_in_deriv"]; - IntegerVector t_idx_in_err = meta_i["t_idx_in_err"]; - IntegerVector o_idx_in_err = meta_i["o_idx_in_err"]; - IntegerVector o_idx_in_err_deriv = meta_i["o_idx_in_err_deriv"]; - // a recorded sigma replaces the error model of the row, NA where the model applies - const bool have_sigma_data = meta_i.containsElementNamed("sigma_data"); - NumericVector sigma_data = have_sigma_data ? as(meta_i["sigma_data"]) : NumericVector(0); - - const int T = y_data.size(); - - NumericVector deriv_attr = as(pred_i.attr("deriv")); - IntegerVector deriv_dim = deriv_attr.attr("dim"); - const int Dp0 = deriv_dim[0]; // model deriv: time - const int Dp1 = deriv_dim[1]; // model deriv: observable - // eta columns by name: the parameter axis depends on `fixed` and on the call; an eta - // without a column enters only the error model - std::vector eta_col(K, -1); - { - const CharacterVector dpn = deriv_par_names(deriv_attr); - for (int k = 0; k < K; ++k) - for (int j = 0; j < dpn.size(); ++j) - if (as(dpn[j]) == as(eta_names[k])) { eta_col[k] = j; break; } - } - - // The err deriv attribute is read only where it exists, the row has an - // err-deriv observable and the eta has a column in it (indices > 0). - Nullable err_deriv_attr_opt = err_i.attr("deriv"); - const bool have_err_deriv = err_deriv_attr_opt.isNotNull(); - NumericVector err_deriv_attr; - int De0 = 0, De1 = 0; - if (have_err_deriv) { - err_deriv_attr = as(err_deriv_attr_opt); - IntegerVector dim_e = err_deriv_attr.attr("dim"); - De0 = dim_e[0]; // err deriv: time - De1 = dim_e[1]; // err deriv: observable - } - // an eta without a column in the err deriv does not enter sigma - std::vector eta_col_err(K, -1); - if (have_err_deriv) { - const CharacterVector epn = deriv_par_names(err_deriv_attr); - for (int k = 0; k < K; ++k) - for (int j = 0; j < epn.size(); ++j) - if (as(epn[j]) == as(eta_names[k])) { eta_col_err[k] = j; break; } - } - - // Per-row predictions, sigmas and Jacobian rows in packed row-major buffers - // of stride K, the layout the shared residual kernel reads. - std::vector pred_row(T); - std::vector sigma_row(T); - std::vector y_row(T); - std::vector dpred_row((std::size_t) T * (std::size_t) K, 0.0); - std::vector dsigma_row; - bool sigma_has_eta = false; // any row with non-trivial err-deriv slice? - - for (int row = 0; row < T; ++row) { - const int tp = t_idx_in_pred [row] - 1; - const int op = o_idx_in_pred [row] - 1; - const int od = o_idx_in_deriv[row] - 1; - const int te = t_idx_in_err [row] - 1; - const int oe = o_idx_in_err [row] - 1; - - const bool recorded = have_sigma_data && !ISNAN(sigma_data[row]); - pred_row [row] = pred_i(tp, op); - sigma_row[row] = recorded ? sigma_data[row] : err_i(te, oe); - y_row [row] = y_data[row]; - - double* dpred_i = dpred_row.data() + (std::size_t) row * (std::size_t) K; - for (int k = 0; k < K; ++k) { - const int p = eta_col[k]; - dpred_i[k] = p < 0 ? 0.0 : deriv_attr[tp + od * Dp0 + p * Dp0 * Dp1]; - } - - // dsigma row: populated lazily on first eta-dependent row. - const int oed_one = o_idx_in_err_deriv[row]; - if (!recorded && have_err_deriv && oed_one > 0) { - if (!sigma_has_eta) { - dsigma_row.assign((std::size_t) T * (std::size_t) K, 0.0); - sigma_has_eta = true; - } - double* dsigma_i = dsigma_row.data() + (std::size_t) row * (std::size_t) K; - const int oed = oed_one - 1; - for (int k = 0; k < K; ++k) { - const int pe = eta_col_err[k]; - if (pe >= 0) { - dsigma_i[k] = err_deriv_attr[te + oed * De0 + pe * De0 * De1]; - } - } - } - } - - // Shared residual kernel, Gauss-Newton in eta: the rows above the limit, then the - // censored rows (M3), which the meta orders last. The plain sum of squares of these rows is not reported. - const int n_aloq = meta_i.containsElementNamed("n_aloq") ? as(meta_i["n_aloq"]) : T; - double chi2_unused = 0.0; - dmod::AccumOpts opts; - opts.use_deriv2_exact = false; - opts.bloq_mode = dmod::BloqMode::M3; - if (meta_i.containsElementNamed("t_df")) opts.t_df = as(meta_i["t_df"]); - opts.sigma_depends_on_par = sigma_has_eta; - // All first-order Hessian parts. - opts.aloq_part1 = opts.aloq_part2 = opts.aloq_part3 = true; - - dmod::accumulate_aloq_residual( - /*n_obs =*/ n_aloq, - /*n_par =*/ K, - pred_row.data(), - dpred_row.data(), - /*d2pred =*/ nullptr, - y_row.data(), - sigma_row.data(), - sigma_has_eta ? dsigma_row.data() : nullptr, - /*d2sigma=*/ nullptr, - /*lloq =*/ nullptr, - opts, - value, - chi2_unused, - grad.data(), - hess.data()); - if (n_aloq < T) { - NumericVector lloq = meta_i["lloq"]; - const std::size_t off = (std::size_t) n_aloq * (std::size_t) K; - dmod::accumulate_bloq_residual( - T - n_aloq, K, - pred_row.data() + n_aloq, - dpred_row.data() + off, - /*d2pred =*/ nullptr, - y_row.data() + n_aloq, - sigma_row.data() + n_aloq, - sigma_has_eta ? dsigma_row.data() + off : nullptr, - /*d2sigma=*/ nullptr, - lloq.begin() + n_aloq, - opts, - value, - grad.data(), - hess.data()); - } -} - -// Inner objective of one subject: the data terms of the subject condition blocks plus -// the MVN prior of the subject etas. -static EvalResult eval_one_subject_from( - SubjectFrames& frames, - NumericVector& pars, - const List& meta_i, - const double* eta_block, - const double* Omega_inv, - double Omega_log_det) { - IntegerVector eta_idx_in_pars = meta_i["eta_idx_in_pars"]; - CharacterVector eta_names = meta_i["eta_names"]; - const int K = static_cast(eta_idx_in_pars.size()); - for (int k = 0; k < K; ++k) pars[eta_idx_in_pars[k] - 1] = eta_block[k]; - - double value = 0.0; - std::vector grad(K, 0.0); - std::vector hess(K * K, 0.0); - List blocks = meta_i["blocks"]; - for (int b = 0; b < blocks.size(); ++b) - accumulate_block(frames.pred[b], frames.err[b], as(blocks[b]), eta_names, K, - value, grad, hess); - - // MVN prior: quadratic + log|Omega| per subject; the constraintL2_mvn - // convention drops the 2*pi factor (joint sums log|Omega| N times overall). - std::vector Oeta(K, 0.0); - for (int j = 0; j < K; ++j) - for (int k = 0; k < K; ++k) - Oeta[k] += Omega_inv[k + j * K] * eta_block[j]; - for (int k = 0; k < K; ++k) value += eta_block[k] * Oeta[k]; - value += Omega_log_det; - for (int k = 0; k < K; ++k) grad[k] += 2.0 * Oeta[k]; - for (int j = 0; j < K; ++j) - for (int k = 0; k < K; ++k) - hess[k + j * K] += 2.0 * Omega_inv[k + j * K]; - - EvalResult out; - out.value = value; - out.grad = std::move(grad); - out.hess = std::move(hess); - return out; -} - - -static EvalResult eval_one_subject( - Function& model_cb, Function& err_cb, NumericVector& pars, - Nullable fixed, const List& meta_i, const double* eta_block, - const double* Omega_inv, double Omega_log_det) { - SubjectFrames frames; - predict_one_subject(model_cb, err_cb, pars, fixed, meta_i, eta_block, &frames); - return eval_one_subject_from(frames, pars, meta_i, eta_block, Omega_inv, Omega_log_det); -} - - -// Eigen-floored log|H| and H_inv, shared by the serial and lock-step drivers. -static InnerResult finish_inner(int K, const std::vector& eta_curr, - const std::vector& grad, - const std::vector& hess, - const std::vector& eigvals, - const std::vector& eigvecs, - double val_curr, int iter, bool converged, - double eigen_floor_relative) { - double tr_H = 0.0; - for (int j = 0; j < K; ++j) tr_H += eigvals[j]; - double eps_floor = eigen_floor_relative * std::fabs(tr_H) / K; - std::vector lam_floor(K); - for (int j = 0; j < K; ++j) lam_floor[j] = std::max(eigvals[j], eps_floor); - double log_det = 0.0; - for (int j = 0; j < K; ++j) log_det += std::log(lam_floor[j]); - std::vector H_inv(K * K, 0.0); - for (int i = 0; i < K; ++i) - for (int j = 0; j < K; ++j) { - double s = 0.0; - for (int q = 0; q < K; ++q) - s += eigvecs[i + q * K] * eigvecs[j + q * K] / lam_floor[q]; - H_inv[i + j * K] = s; - } - - InnerResult res; - res.eta = eta_curr; - res.grad = grad; - res.H_GN = hess; - res.H_inv = H_inv; - res.eigvals = eigvals; - res.log_det_H = log_det; - res.value = val_curr; - res.iterations = iter; - res.converged = converged; - return res; -} - - -// Inner trust for one subject on eval_one_subject; writes the final eta into `pars`. -static InnerResult inner_trust_one_subject( - Function& model_cb, - Function& err_cb, - NumericVector& pars, - const Nullable& fixed, - const List& meta_i, - const NumericVector& eta_init, - const double* Omega_inv, - double Omega_log_det, - double rinit, double rmax, - int iterlim, - double steptol, double mtol, - double eigen_floor_relative) { - const int K = eta_init.size(); - - std::vector eta_curr(eta_init.begin(), eta_init.end()); - EvalResult fr = eval_one_subject( - model_cb, err_cb, pars, fixed, meta_i, - eta_curr.data(), Omega_inv, Omega_log_det); - double val_curr = fr.value; - std::vector grad(fr.grad), hess(fr.hess); - - // Eigen on current hessian - std::vector eigvals(K), eigvecs(K * K); - eigen_sym(hess.data(), K, eigvals.data(), eigvecs.data()); - - double r = rinit; - bool converged = false; - int iter = 0; - std::vector eta_try(K), p_step(K); - std::vector S((std::size_t) K * K, 0.0), mvals(eigvals), mvecs(eigvecs); - - for (iter = 1; iter <= iterlim; ++iter) { - bool is_newton = false; - double predicted_red = 0.0; - trust_subproblem(K, grad.data(), mvals.data(), mvecs.data(), - r, p_step.data(), &predicted_red, &is_newton); - if (modes_found(K, grad, eigvals, eigvecs, predicted_red, is_newton, steptol, mtol, val_curr)) { - converged = true; - break; - } - for (int k = 0; k < K; ++k) eta_try[k] = eta_curr[k] + p_step[k]; - - EvalResult ft = eval_one_subject( - model_cb, err_cb, pars, fixed, meta_i, - eta_try.data(), Omega_inv, Omega_log_det); - // a trial whose value or derivatives are not finite is rejected like one that does not decrease - if (!all_finite(ft)) { - r = shrunk_radius(r, p_step.data(), K); - std::fill(S.begin(), S.end(), 0.0); - model_eigen(K, hess, S, mvals, mvecs); - continue; - } - double val_try = ft.value; - std::vector grad_try(ft.grad), hess_try(ft.hess); - std::vector eigvals_try(K), eigvecs_try(K * K); - eigen_sym(hess_try.data(), K, eigvals_try.data(), eigvecs_try.data()); - - double actual_red = val_curr - val_try; - double rho = (predicted_red > 0.0 && std::isfinite(val_try)) - ? actual_red / predicted_red - : -std::numeric_limits::infinity(); - - const bool accept = std::isfinite(val_try) && accept_trial(rho, is_newton, predicted_red, val_curr, grad, grad_try); - if (!accept) r = shrunk_radius(r, p_step.data(), K); - else if (rho > 0.75 && !is_newton) r = std::min(2.0 * r, rmax); - - if (accept) { - secant_update(K, S, p_step, grad, grad_try, hess_try); - eta_curr = eta_try; - val_curr = val_try; - grad = grad_try; - hess = hess_try; - eigvals = eigvals_try; - eigvecs = eigvecs_try; - } else { - std::fill(S.begin(), S.end(), 0.0); - } - model_eigen(K, hess, S, mvals, mvecs); - } - - // Final eta into pars for the joint call at the modes. - IntegerVector eta_idx_in_pars = meta_i["eta_idx_in_pars"]; - for (int k = 0; k < K; ++k) { - pars[eta_idx_in_pars[k] - 1] = eta_curr[k]; - } - - // a loop that reaches iterlim leaves iter one past it - return finish_inner(K, eta_curr, grad, hess, eigvals, eigvecs, - val_curr, std::min(iter, iterlim), converged, eigen_floor_relative); -} - - -// Lock-step inner trust: every active subject takes one step per round and the -// round's predictions go out as one batched callback. Subjects are independent, -// so this is exact; converged ones drop out. -static List inner_trust_lockstep( - Function& predict_cb, NumericVector& pars_full, NumericMatrix& eta_warmstart, - List& subject_meta_fast, CharacterVector& subjects, - const std::vector& Omega_inv, double Omega_log_det, - Nullable fixed, int K, int N, - double rinit, double rmax, int iterlim, double steptol, double mtol, - double eflr) { - - struct LS { - std::vector eta, grad, hess, eigvals, eigvecs, eta_try, p_step, S, mvals, mvecs; - double val = 0.0, r = 0.0, predicted_red = 0.0; - int iter = 0; - bool converged = false, done = false, is_newton = false; - NumericVector pars; - }; - std::vector st(N); - - // One batched callback for the condition blocks of a set of subjects at given - // etas; the frames come back per subject. - auto run_round = [&](const std::vector& idx, - const std::vector& etas) { - const int M = static_cast(idx.size()); - int n_req = 0; - for (int j = 0; j < M; ++j) - n_req += as(as(subject_meta_fast[idx[j]])["blocks"]).size(); - List timesL(n_req), parsL(n_req); - CharacterVector conds(n_req); - int q = 0; - for (int j = 0; j < M; ++j) { - const int i = idx[j]; - List meta_i = as(subject_meta_fast[i]); - IntegerVector eip = meta_i["eta_idx_in_pars"]; - NumericVector pj = clone(st[i].pars); - for (int k = 0; k < K; ++k) pj[eip[k] - 1] = etas[j][k]; - st[i].pars = pj; - List blocks = meta_i["blocks"]; - for (int b = 0; b < blocks.size(); ++b, ++q) { - List block = blocks[b]; - parsL[q] = pj; - timesL[q] = block["times"]; - conds[q] = as(block["condition"])[0]; - } - } - List got = as(predict_cb(Rcpp::Named("timesList") = timesL, - Rcpp::Named("parsList") = parsL, - Rcpp::Named("conditions") = conds, - Rcpp::Named("fixed") = fixed)); - List preds = as(got["pred"]), errs = as(got["err"]); - std::vector frames(M); - q = 0; - for (int j = 0; j < M; ++j) { - const int nb = as(as(subject_meta_fast[idx[j]])["blocks"]).size(); - for (int b = 0; b < nb; ++b, ++q) { - SEXP pq = preds[q], eq = errs[q]; - if (TYPEOF(pq) != REALSXP || TYPEOF(eq) != REALSXP) { frames[j].failed = true; continue; } - frames[j].pred.push_back(as(pq)); - frames[j].err.push_back(as(eq)); - } - } - return frames; - }; - - for (int i = 0; i < N; ++i) { - st[i].pars = clone(pars_full); - st[i].eta.assign(K, 0.0); - for (int k = 0; k < K; ++k) st[i].eta[k] = eta_warmstart(i, k); - st[i].eta_try.assign(K, 0.0); - st[i].p_step.assign(K, 0.0); - st[i].r = rinit; - } - - { - std::vector idx(N); - std::vector etas(N); - for (int i = 0; i < N; ++i) { idx[i] = i; etas[i] = st[i].eta.data(); } - std::vector frames = run_round(idx, etas); - for (int i = 0; i < N; ++i) { - if (frames[i].failed) - Rcpp::stop("FOCEI: the prediction fails at the modes the inner search starts from."); - List meta_i = as(subject_meta_fast[i]); - EvalResult fr = eval_one_subject_from(frames[i], st[i].pars, meta_i, - st[i].eta.data(), Omega_inv.data(), - Omega_log_det); - st[i].val = fr.value; st[i].grad = fr.grad; st[i].hess = fr.hess; - st[i].eigvals.assign(K, 0.0); st[i].eigvecs.assign((size_t)K * K, 0.0); - eigen_sym(st[i].hess.data(), K, st[i].eigvals.data(), st[i].eigvecs.data()); - st[i].S.assign((size_t)K * K, 0.0); - st[i].mvals = st[i].eigvals; st[i].mvecs = st[i].eigvecs; - } - } - - for (int round = 1; round <= iterlim; ++round) { - std::vector idx; - std::vector etas; - for (int i = 0; i < N; ++i) { - if (st[i].done) continue; - st[i].iter = round; - trust_subproblem(K, st[i].grad.data(), st[i].mvals.data(), - st[i].mvecs.data(), st[i].r, st[i].p_step.data(), - &st[i].predicted_red, &st[i].is_newton); - if (modes_found(K, st[i].grad, st[i].eigvals, st[i].eigvecs, st[i].predicted_red, st[i].is_newton, steptol, - mtol, st[i].val)) { - st[i].converged = true; st[i].done = true; continue; - } - for (int k = 0; k < K; ++k) st[i].eta_try[k] = st[i].eta[k] + st[i].p_step[k]; - idx.push_back(i); - etas.push_back(st[i].eta_try.data()); - } - if (idx.empty()) break; - - std::vector frames = run_round(idx, etas); - - for (size_t j = 0; j < idx.size(); ++j) { - const int i = idx[j]; - // a trial where the prediction fails, or whose value or derivatives are not finite, is - // rejected like one that does not decrease - auto reject = [&]() { - st[i].r = shrunk_radius(st[i].r, st[i].p_step.data(), K); - std::fill(st[i].S.begin(), st[i].S.end(), 0.0); - model_eigen(K, st[i].hess, st[i].S, st[i].mvals, st[i].mvecs); - }; - if (frames[j].failed) { reject(); continue; } - List meta_i = as(subject_meta_fast[i]); - EvalResult ft = eval_one_subject_from(frames[j], st[i].pars, meta_i, - st[i].eta_try.data(), - Omega_inv.data(), Omega_log_det); - if (!all_finite(ft)) { reject(); continue; } - std::vector eigvals_try(K), eigvecs_try((size_t)K * K); - eigen_sym(ft.hess.data(), K, eigvals_try.data(), eigvecs_try.data()); - - const double actual_red = st[i].val - ft.value; - const double rho = (st[i].predicted_red > 0.0 && std::isfinite(ft.value)) - ? actual_red / st[i].predicted_red - : -std::numeric_limits::infinity(); - const bool accept = std::isfinite(ft.value) && - accept_trial(rho, st[i].is_newton, st[i].predicted_red, st[i].val, st[i].grad, ft.grad); - if (!accept) st[i].r = shrunk_radius(st[i].r, st[i].p_step.data(), K); - else if (rho > 0.75 && !st[i].is_newton) st[i].r = std::min(2.0 * st[i].r, rmax); - if (accept) { - secant_update(K, st[i].S, st[i].p_step, st[i].grad, ft.grad, ft.hess); - st[i].eta = st[i].eta_try; st[i].val = ft.value; - st[i].grad = ft.grad; st[i].hess = ft.hess; - st[i].eigvals = eigvals_try; st[i].eigvecs = eigvecs_try; - } else { - std::fill(st[i].S.begin(), st[i].S.end(), 0.0); - } - model_eigen(K, st[i].hess, st[i].S, st[i].mvals, st[i].mvecs); - } - } - - NumericMatrix eta_modes(N, K), grad_mat(N, K), eigvals_mat(N, K); - NumericVector log_det_H(N), value(N); - IntegerVector iterations(N); - LogicalVector converged(N); - List H_GN_list(N), H_inv_list(N); - for (int i = 0; i < N; ++i) { - IntegerVector eip = as(subject_meta_fast[i])["eta_idx_in_pars"]; - for (int k = 0; k < K; ++k) pars_full[eip[k] - 1] = st[i].eta[k]; - InnerResult r = finish_inner(K, st[i].eta, st[i].grad, st[i].hess, - st[i].eigvals, st[i].eigvecs, st[i].val, - st[i].iter, st[i].converged, eflr); - for (int k = 0; k < K; ++k) { - eta_modes(i, k) = r.eta[k]; grad_mat(i, k) = r.grad[k]; - eigvals_mat(i, k) = r.eigvals[k]; - } - NumericMatrix hg(K, K), hi(K, K); - for (int c = 0; c < K; ++c) for (int rr = 0; rr < K; ++rr) { - hg(rr, c) = r.H_GN[rr + c * K]; hi(rr, c) = r.H_inv[rr + c * K]; - } - CharacterVector eta_nm = - as(as(subject_meta_fast[i])["eta_names"]); - List dn = List::create(eta_nm, eta_nm); - hg.attr("dimnames") = dn; - hi.attr("dimnames") = dn; - H_GN_list[i] = hg; H_inv_list[i] = hi; - log_det_H[i] = r.log_det_H; value[i] = r.value; - iterations[i] = r.iterations; converged[i] = r.converged; - } - rownames(eta_modes) = subjects; - rownames(grad_mat) = subjects; - rownames(eigvals_mat) = subjects; - log_det_H .names() = subjects; - value .names() = subjects; - iterations.names() = subjects; - converged .names() = subjects; - H_GN_list .names() = subjects; - H_inv_list.names() = subjects; - - return List::create( - Rcpp::Named("eta_modes") = eta_modes, - Rcpp::Named("gradient") = grad_mat, - Rcpp::Named("H_GN") = H_GN_list, - Rcpp::Named("H_inv") = H_inv_list, - Rcpp::Named("eigvals") = eigvals_mat, - Rcpp::Named("log_det_H") = log_det_H, - Rcpp::Named("value") = value, - Rcpp::Named("iterations") = iterations, - Rcpp::Named("converged") = converged); -} - - -// Inner trust for all subjects on the fast objective. Omega_inv is fixed during -// the inner loop, so R computes it once per outer iteration. -// [[Rcpp::export]] -List focei_inner_trust(Function model_cb, - Function err_cb, - NumericVector pars_full, - NumericMatrix eta_warmstart, - List subject_meta, - NumericMatrix Omega_inv_mat, - double Omega_log_det, - Nullable fixed, - List control, - Nullable predict_cb = R_NilValue) { - CharacterVector subjects = subject_meta["subjects"]; - List subject_meta_fast = subject_meta["fast_meta"]; - const int K = as(subject_meta["K"]); - const int N = subjects.size(); - if (eta_warmstart.nrow() != N || eta_warmstart.ncol() != K) - throw std::runtime_error("focei_inner_trust: eta_warmstart shape mismatch."); - if (Omega_inv_mat.nrow() != K || Omega_inv_mat.ncol() != K) - throw std::runtime_error("focei_inner_trust: Omega_inv_mat shape mismatch."); - - std::vector Omega_inv(K * K); - for (int c = 0; c < K; ++c) - for (int r = 0; r < K; ++r) - Omega_inv[r + c * K] = Omega_inv_mat(r, c); - - double rinit = control.containsElementNamed("rinit") ? - as(control["rinit"]) : 1.0; - double rmax = control.containsElementNamed("rmax") ? - as(control["rmax"]) : 10.0; - int iterlim = control.containsElementNamed("iterlim") ? - as(control["iterlim"]) : 30; - double steptol = ctrl_tol(control, "steptol", "steptol", 1e-8); - double mtol = ctrl_tol(control, "mtol", "mterm", 1e-12); - double eflr = control.containsElementNamed("eigen_floor_relative") ? - as(control["eigen_floor_relative"]) : 1e-10; - - if (predict_cb.isNotNull()) { - Function pcb(predict_cb); - return inner_trust_lockstep(pcb, pars_full, eta_warmstart, subject_meta_fast, - subjects, Omega_inv, Omega_log_det, fixed, K, N, - rinit, rmax, iterlim, steptol, mtol, eflr); - } - - // Other subjects' etas stay at their warmstart: working copy per subject. - std::vector base_pars(pars_full.begin(), pars_full.end()); - - NumericMatrix eta_modes(N, K); - NumericMatrix grad_mat(N, K); - NumericMatrix eigvals_mat(N, K); - NumericVector log_det_H(N); - NumericVector value(N); - IntegerVector iterations(N); - LogicalVector converged(N); - List H_GN_list(N); - List H_inv_list(N); - - for (int i = 0; i < N; ++i) { - NumericVector eta_init(K); - for (int k = 0; k < K; ++k) eta_init[k] = eta_warmstart(i, k); - - NumericVector working_pars(base_pars.begin(), base_pars.end()); - working_pars.attr("names") = pars_full.attr("names"); - - List meta_i = as(subject_meta_fast[i]); - - InnerResult r = inner_trust_one_subject( - model_cb, err_cb, working_pars, fixed, meta_i, eta_init, - Omega_inv.data(), Omega_log_det, - rinit, rmax, iterlim, steptol, mtol, eflr); - - for (int k = 0; k < K; ++k) { - eta_modes (i, k) = r.eta[k]; - grad_mat (i, k) = r.grad[k]; - eigvals_mat(i, k) = r.eigvals[k]; - } - NumericMatrix H_GN_i (K, K); - NumericMatrix H_inv_i(K, K); - for (int c = 0; c < K; ++c) - for (int rw = 0; rw < K; ++rw) { - H_GN_i (rw, c) = r.H_GN [rw + c * K]; - H_inv_i(rw, c) = r.H_inv[rw + c * K]; - } - CharacterVector eta_nm = as(as(meta_i)["eta_names"]); - List dn = List::create(eta_nm, eta_nm); - H_GN_i .attr("dimnames") = dn; - H_inv_i.attr("dimnames") = dn; - H_GN_list [i] = H_GN_i; - H_inv_list[i] = H_inv_i; - log_det_H [i] = r.log_det_H; - value [i] = r.value; - iterations[i] = r.iterations; - converged [i] = r.converged; - } - - // Write the converged modes into pars_full (caller-visible side effect) - IntegerMatrix eta_idx_global = subject_meta["eta_idx_global"]; - for (int i = 0; i < N; ++i) - for (int k = 0; k < K; ++k) - pars_full[eta_idx_global(i, k) - 1] = eta_modes(i, k); - - rownames(eta_modes) = subjects; - rownames(grad_mat) = subjects; - rownames(eigvals_mat) = subjects; - log_det_H .names() = subjects; - value .names() = subjects; - iterations.names() = subjects; - converged .names() = subjects; - H_GN_list .names() = subjects; - H_inv_list.names() = subjects; - - return List::create( - Rcpp::Named("eta_modes") = eta_modes, - Rcpp::Named("gradient") = grad_mat, - Rcpp::Named("H_GN") = H_GN_list, - Rcpp::Named("H_inv") = H_inv_list, - Rcpp::Named("eigvals") = eigvals_mat, - Rcpp::Named("log_det_H") = log_det_H, - Rcpp::Named("value") = value, - Rcpp::Named("iterations") = iterations, - Rcpp::Named("converged") = converged); -} - - // Adds the volume derivatives of `correction_cb`, a list of the gradient named by // outer parameter and an optional Hessian with outer dimnames, to the outer model; // the callback gets the outer gradient without them as `data_gradient`. Returns the // `eta_shift`, d eta*/d theta per subject (K x n_outer), or an empty list. static List add_correction(Function& correction_cb, const CharacterVector& outer_names, const NumericVector& pars_full, const NumericMatrix& H_full, - const List& H_inv_list, NumericVector& grad_outer, + const List& H_inv_list, const List& weight_list, NumericVector& grad_outer, NumericMatrix& Hess) { List corr = as(correction_cb( Rcpp::Named("full_pars") = pars_full, Rcpp::Named("joint_hessian") = H_full, Rcpp::Named("H_inv_list") = H_inv_list, + Rcpp::Named("weight_list") = weight_list, Rcpp::Named("data_gradient") = clone(grad_outer))); NumericVector g = as(corr["gradient"]); std::vector at = name_indices(outer_names, CharacterVector(g.names()), "correction/gradient"); @@ -972,15 +117,14 @@ List focei_outer_objfn(Function model_cb, std::string correction_mode = "none", Nullable correction_cb_opt = R_NilValue, Nullable predict_cb = R_NilValue, - bool apply_correction = true) { + bool apply_correction = true, + bool newton_value = false) { CharacterVector subjects = subject_meta["subjects"]; - IntegerMatrix eta_idx_global = subject_meta["eta_idx_global"]; List eta_names_list = subject_meta["eta_names"]; CharacterVector outer_names = subject_meta["outer_names"]; IntegerVector outer_idx_full = subject_meta["outer_idx_in_full"]; NumericVector other_etas_init = subject_meta["other_etas_init"]; CharacterVector pars_full_names = subject_meta["pars_full_names"]; - const int K = as(subject_meta["K"]); const int N = subjects.size(); const int n_outer = outer_names.size(); @@ -999,21 +143,25 @@ List focei_outer_objfn(Function model_cb, for (int i = 0; i < n_outer; ++i) pars_full[outer_idx_full[i] - 1] = outer_pars[i]; - // Fast inner trust (mutates pars_full to hold the modes) - List inner_res = focei_inner_trust( - model_cb, err_cb, pars_full, eta_warmstart, - subject_meta, Omega_inv_mat, Omega_log_det, fixed, inner_ctrl, predict_cb); - NumericMatrix eta_modes = as(inner_res["eta_modes"]); - List H_GN_list = as(inner_res["H_GN"]); - List H_inv_list = as(inner_res["H_inv"]); - NumericVector log_det_H = as(inner_res["log_det_H"]); - IntegerVector iterations = as(inner_res["iterations"]); - LogicalVector converged = as(inner_res["converged"]); - - double sum_logdetH = 0.0; - for (int i = 0; i < N; ++i) sum_logdetH += log_det_H[i]; - - // Gauss-Newton joint Hessian: H_inv_list and log|H| use the GN inner block, + // the group kernel with Laplace on the normal block; the modes go into pars_full + dmod::nlme::GroupProblem prob; + prob.model_cb = &model_cb; + prob.err_cb = &err_cb; + Function pcb = predict_cb.isNotNull() ? Function(predict_cb) : model_cb; + if (predict_cb.isNotNull()) prob.predict_cb = &pcb; + prob.fixed = fixed; + prob.meta = subject_meta; + prob.Omega_inv.assign(Omega_inv_mat.begin(), Omega_inv_mat.end()); + prob.Omega_log_det = Omega_log_det; + prob.control = dmod::nlme::inner_control(inner_ctrl); + const dmod::nlme::LaplaceNormal laplace; + const dmod::nlme::Groups groups = dmod::nlme::evaluate_groups(prob, pars_full, eta_warmstart, laplace); + List inner_res = dmod::nlme::groups_list(groups, subject_meta); + + double sum_terms = 0.0; + for (int i = 0; i < N; ++i) sum_terms += groups.integrals[i].term; + + // Gauss-Newton joint Hessian: the local models use the GN inner block, // and the stage-2 implicit chain must differentiate the same matrix it inverts. const bool want_deriv2 = false; List out_mode = as(joint_cb( @@ -1024,8 +172,7 @@ List focei_outer_objfn(Function model_cb, Rcpp::Named("conditions") = subject_meta["conditions"])); // the joint objective at the modes: the inner values of the subjects plus the data of // the conditions that belong to no subject - const double OFV = as(out_mode["value"]) + sum_logdetH - - (double)N * (double)K * std::log(2.0); + const double OFV = as(out_mode["value"]) + sum_terms + groups.constant; NumericVector grad_full = as(out_mode["gradient"]); NumericMatrix H_full = as(out_mode["hessian"]); CharacterVector grad_names = grad_full.names(); @@ -1036,83 +183,60 @@ List focei_outer_objfn(Function model_cb, "fast_outer/grad"); std::vector outer_idx_hess = name_indices(H_rownames, outer_names, "fast_outer/hess"); - std::vector > eta_idx_hess(N); - for (int i = 0; i < N; ++i) { - CharacterVector eta_nm_i = as(eta_names_list[i]); - eta_idx_hess[i] = name_indices(H_rownames, eta_nm_i, - "fast_outer/eta_hess"); - } - NumericVector grad_outer(n_outer); for (int i = 0; i < n_outer; ++i) grad_outer[i] = grad_full[outer_idx_grad[i]]; grad_outer.attr("names") = outer_names; - // Schur Hessian. Per subject: - // tmp = H_oi * H_inv_i (n_outer x K) via dgemm "N", "N" - // Hess = Hess - tmp * H_oi^T (n_outer x n_outer) via dgemm "N", "T" - NumericMatrix Hess(n_outer, n_outer); - for (int c = 0; c < n_outer; ++c) - for (int r = 0; r < n_outer; ++r) - Hess(r, c) = H_full(outer_idx_hess[r], outer_idx_hess[c]); - std::vector H_oi(n_outer * K), tmp(n_outer * K); - std::vector H_inv_col(K * K); + // the outer model: the normal block of every group eliminated from the joint Gauss-Newton Hessian, + // and the eta gradient g_i the inner search leaves taken through the coupling, grad -= H_oi H_i^-1 g_i, + // the gradient at the exact modes to first order std::vector Hess_col(n_outer * n_outer); - std::vector > eta_idx_grad(N); - for (int i = 0; i < N; ++i) - eta_idx_grad[i] = name_indices(grad_names, as(eta_names_list[i]), - "fast_outer/eta_grad"); for (int c = 0; c < n_outer; ++c) - for (int r = 0; r < n_outer; ++r) Hess_col[r + c * n_outer] = Hess(r, c); - const double one = 1.0, m_one = -1.0, zero = 0.0; + for (int r = 0; r < n_outer; ++r) Hess_col[r + c * n_outer] = H_full(outer_idx_hess[r], outer_idx_hess[c]); + std::vector H_oi, g_N; + // with `newton_value` the value at the exact modes to second order in the eta gradient of the joint + // objective, OFV - g_N' H_NN^-1 g_N / 2; the volume term stays that at the modes found + double decrement = 0.0; for (int i = 0; i < N; ++i) { - NumericMatrix H_inv_i = as(H_inv_list[i]); - // Pack H_inv_i to column-major buffer (it already is, but force layout) - for (int c = 0; c < K; ++c) - for (int r = 0; r < K; ++r) H_inv_col[r + c * K] = H_inv_i(r, c); - // Pack H_oi from H_full - for (int k = 0; k < K; ++k) - for (int r = 0; r < n_outer; ++r) - H_oi[r + k * n_outer] = H_full(outer_idx_hess[r], eta_idx_hess[i][k]); - // tmp = H_oi * H_inv_i (n_outer x K) - F77_CALL(dgemm)("N", "N", &n_outer, &K, &K, &one, - H_oi.data(), &n_outer, - H_inv_col.data(), &K, - &zero, tmp.data(), &n_outer FCONE FCONE); - // Hess -= tmp * H_oi^T (n_outer x n_outer) - F77_CALL(dgemm)("N", "T", &n_outer, &n_outer, &K, &m_one, - tmp.data(), &n_outer, - H_oi.data(), &n_outer, - &one, Hess_col.data(), &n_outer FCONE FCONE); - // the gradient at the exact modes to first order: the eta gradient g_i the inner search leaves - // enters through the coupling, grad -= H_oi H_i^-1 g_i - for (int r = 0; r < n_outer; ++r) { - double d = 0.0; - for (int k = 0; k < K; ++k) d += tmp[r + k * n_outer] * grad_full[eta_idx_grad[i][k]]; - grad_outer[r] -= d; + const dmod::nlme::LocalModel& m = groups.models[i]; + CharacterVector eta_nm_i = as(eta_names_list[i]); + std::vector eh = name_indices(H_rownames, eta_nm_i, "fast_outer/eta_hess"); + std::vector eg = name_indices(grad_names, eta_nm_i, "fast_outer/eta_grad"); + const int n = m.normal.size(); + H_oi.assign((std::size_t) n_outer * n, 0.0); + g_N.assign(n, 0.0); + for (int k = 0; k < n; ++k) { + g_N[k] = grad_full[eg[m.normal[k]]]; + for (int r = 0; r < n_outer; ++r) H_oi[r + k * n_outer] = H_full(outer_idx_hess[r], eh[m.normal[k]]); } + dmod::nlme::eliminate_normal(n_outer, m, H_oi.data(), Hess_col.data(), grad_outer.begin(), g_N.data()); + if (newton_value) dmod::nlme::eliminate_normal(1, m, g_N.data(), &decrement, nullptr, g_N.data()); } + NumericMatrix Hess(n_outer, n_outer); for (int c = 0; c < n_outer; ++c) for (int r = 0; r < n_outer; ++r) Hess(r, c) = Hess_col[r + c * n_outer]; Hess.attr("dimnames") = List::create(outer_names, outer_names); + List H_inv_list = inner_res["H_inv"], weight_list = inner_res["weight"]; List eta_shift; if (apply_correction && correction_mode != "none" && correction_cb_opt.isNotNull()) { Function correction_cb(correction_cb_opt); - eta_shift = add_correction(correction_cb, outer_names, pars_full, H_full, H_inv_list, + eta_shift = add_correction(correction_cb, outer_names, pars_full, H_full, H_inv_list, weight_list, grad_outer, Hess); } return List::create( - Rcpp::Named("value") = OFV, + Rcpp::Named("value") = OFV + decrement / 2.0, Rcpp::Named("gradient") = grad_outer, Rcpp::Named("hessian") = Hess, - Rcpp::Named("eta_modes") = eta_modes, - Rcpp::Named("H_GN") = H_GN_list, + Rcpp::Named("eta_modes") = inner_res["eta_modes"], + Rcpp::Named("H_GN") = inner_res["H_GN"], Rcpp::Named("H_inv") = H_inv_list, - Rcpp::Named("log_det_H") = log_det_H, - Rcpp::Named("sum_logdetH") = sum_logdetH, - Rcpp::Named("iterations") = iterations, - Rcpp::Named("converged") = converged, + Rcpp::Named("weight") = weight_list, + Rcpp::Named("log_det_H") = inner_res["log_det_H"], + Rcpp::Named("sum_logdetH") = sum_terms, + Rcpp::Named("iterations") = inner_res["iterations"], + Rcpp::Named("converged") = inner_res["converged"], Rcpp::Named("pars_full") = pars_full, Rcpp::Named("H_full") = H_full, Rcpp::Named("eta_shift") = eta_shift); @@ -1134,22 +258,30 @@ struct OuterEval { // gains less than mtol in the region rmax or five rejected trials leave the value flat within ftol. template List focei_outer_loop(OuterEval& ev, NumericVector init, CharacterVector outer_names, - List outer_ctrl, double inner_rinit, int N, int K) { + List outer_ctrl, double inner_rinit, int N, int K, NumericMatrix eta_init) { const int n_outer = init.size(); double rinit = outer_ctrl.containsElementNamed("rinit") ? as(outer_ctrl["rinit"]) : 1.0; double rmax = outer_ctrl.containsElementNamed("rmax") ? as(outer_ctrl["rmax"]) : 10.0; int iterlim = outer_ctrl.containsElementNamed("iterlim") ? as(outer_ctrl["iterlim"]) : 100; - double ftol = ctrl_tol(outer_ctrl, "ftol", "fterm", 1e-6); - double mtol = ctrl_tol(outer_ctrl, "mtol", "mterm", 1e-6); + double ftol = ctrl_tol(outer_ctrl, "ftol", 1e-6); + double mtol = ctrl_tol(outer_ctrl, "mtol", 1e-6); NumericVector theta(clone(init)); theta.attr("names") = outer_names; - NumericMatrix eta_warm(N, K); + NumericMatrix eta_warm = eta_init.nrow() == N && eta_init.ncol() == K ? clone(eta_init) : NumericMatrix(N, K); Model model(n_outer); + // the inner iterations of all trials, summed over the groups + int inner_iter = 0; + auto count = [&](const RObject& T) { + if (T.isNULL()) return; + List out(T); + if (out.containsElementNamed("iterations")) for (int it : as(out["iterations"])) inner_iter += it; + }; const std::vector ones(n_outer, 1.0), zeros(n_outer, 0.0); RObject keep; double f_curr = ev.trial(theta, eta_warm, keep); + count(keep); std::vector g_curr; typename Model::Hess H_curr; List shift_curr; @@ -1190,6 +322,7 @@ List focei_outer_loop(OuterEval& ev, NumericVector init, CharacterVector bool eval_ok = true; try { f_try = ev.trial(theta_try, eta_warm, T); + count(T); } catch (std::exception&) { eval_ok = false; } double actual_red = f_curr - f_try; @@ -1257,6 +390,7 @@ List focei_outer_loop(OuterEval& ev, NumericVector init, CharacterVector Rcpp::Named("value") = f_curr, Rcpp::Named("keep") = keep, Rcpp::Named("iterations") = iter, + Rcpp::Named("innerIterations") = inner_iter, Rcpp::Named("converged") = converged, Rcpp::Named("trace") = trace); } @@ -1274,7 +408,8 @@ List focei_run(Function model_cb, List control, std::string correction_mode = "none", Nullable correction_cb = R_NilValue, - Nullable predict_cb = R_NilValue) { + Nullable predict_cb = R_NilValue, + Nullable eta_init = R_NilValue) { CharacterVector subjects = subject_meta["subjects"]; CharacterVector outer_names = subject_meta["outer_names"]; const int N = subjects.size(); @@ -1340,13 +475,14 @@ List focei_run(Function model_cb, const double inner_rinit = inner_ctrl.containsElementNamed("rinit") ? as(inner_ctrl["rinit"]) : 1.0; List outer_ctrl = control.containsElementNamed("outer") ? as(control["outer"]) : List(); + const bool newton_value = control.containsElementNamed("newtonValue") && as(control["newtonValue"]); auto eval_outer = [&](NumericVector& th, NumericMatrix& warm, bool correct) -> List { auto OL = build_Omega_inv_and_logdet(th); return focei_outer_objfn( model_cb, err_cb, joint_cb, th, warm, subject_meta, OL.first, OL.second, fixed, inner_ctrl, - correction_mode, correction_cb, predict_cb, correct); + correction_mode, correction_cb, predict_cb, correct, newton_value); }; const bool corrected = correction_mode != "none" && correction_cb.isNotNull(); // the trial point by the inner search with the outer gradient and Schur Hessian; at an accepted @@ -1364,7 +500,7 @@ List focei_run(Function model_cb, if (corrected) { Function cb(correction_cb); shift = add_correction(cb, outer_names, as(out["pars_full"]), - as(out["H_full"]), as(out["H_inv"]), gt, Ht); + as(out["H_full"]), as(out["H_inv"]), as(out["weight"]), gt, Ht); } out["gradient"] = gt; out["hessian"] = Ht; @@ -1373,7 +509,8 @@ List focei_run(Function model_cb, T = out; }; ev.modes = [](const RObject& T) { return NumericMatrix(as(T)["eta_modes"]); }; - List res = focei_outer_loop(ev, init, outer_names, outer_ctrl, inner_rinit, N, K); + List res = focei_outer_loop(ev, init, outer_names, outer_ctrl, inner_rinit, N, K, + eta_init.isNotNull() ? NumericMatrix(eta_init) : NumericMatrix(0, 0)); List out_final = as(res["keep"]); return List::create( @@ -1384,9 +521,11 @@ List focei_run(Function model_cb, Rcpp::Named("etaModes") = as(out_final["eta_modes"]), Rcpp::Named("H_GN") = as(out_final["H_GN"]), Rcpp::Named("H_inv") = as(out_final["H_inv"]), + Rcpp::Named("weight") = as(out_final["weight"]), Rcpp::Named("log_det_H") = as(out_final["log_det_H"]), Rcpp::Named("sum_logdetH")= as(out_final["sum_logdetH"]), Rcpp::Named("iterations") = res["iterations"], + Rcpp::Named("innerIterations") = res["innerIterations"], Rcpp::Named("converged") = res["converged"], Rcpp::Named("trace") = res["trace"]); } @@ -1396,7 +535,7 @@ List focei_run(Function model_cb, // `lowrank` and `shift`, the mode shifts with their outer columns in "idx". // [[Rcpp::export]] List focei_run_sparse(Function trial, Function complete, NumericVector init, int N, int K, - List outer_ctrl, double inner_rinit) { + List outer_ctrl, double inner_rinit, Nullable eta_init = R_NilValue) { CharacterVector outer_names = init.names(); const int n_outer = init.size(); OuterEval ev; @@ -1416,5 +555,6 @@ List focei_run_sparse(Function trial, Function complete, NumericVector init, int T = out; }; ev.modes = [](const RObject& T) { return NumericMatrix(as(T)["eta_modes"]); }; - return focei_outer_loop(ev, init, outer_names, outer_ctrl, inner_rinit, N, K); + return focei_outer_loop(ev, init, outer_names, outer_ctrl, inner_rinit, N, K, + eta_init.isNotNull() ? NumericMatrix(eta_init) : NumericMatrix(0, 0)); } diff --git a/src/nlme_kernel.cpp b/src/nlme_kernel.cpp new file mode 100644 index 00000000..fc402910 --- /dev/null +++ b/src/nlme_kernel.cpp @@ -0,0 +1,981 @@ +// NLME group kernel: inner modes, local models and integrals of all groups of one evaluation; the +// interface and the formulas are in nlme_kernel.h. +// +// Math anchors (load-bearing, do not change without re-deriving): +// - Inner objective per group, Gauss-Newton in eta: second derivatives of prediction and sigma +// dropped, first-order cross terms of an eta-dependent sigma kept; the prior eta' P eta adds 2 P. +// - Laplace on the normal block: int exp(-Phi/2) d eta ~ exp(-Phi(m)/2) (2 pi)^{|N|/2} |H_NN / 2|^-1/2, +// so -2 log L_i ~ Phi_i(m_i) + log|H_NN| - |N| log 2 up to the constant of the normal density, +// which the prior omits as well. + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "residual_kernel.h" +#include "trust_subproblem.h" +#include "nlme_kernel.h" + +using namespace Rcpp; + +#ifndef FCONE +#define FCONE +#endif + +namespace dmod { +namespace nlme { + +// Whether a trial is accepted: by the ratio of the actual to the predicted decrease, and near the +// modes, where a Newton step predicts less than 1e-6 of the value, also by a smaller gradient: the +// solver's error in the value there exceeds what the step gains, the gradient is still measured. +static bool accept_trial(double rho, bool is_newton, double predicted_red, double val, const std::vector& grad, + const std::vector& grad_try) { + if (rho >= 0.25) return true; + if (!is_newton || predicted_red > 1e-6 * std::max(1.0, std::fabs(val))) return false; + double g0 = 0.0, g1 = 0.0; + for (std::size_t k = 0; k < grad.size(); ++k) { g0 += grad[k] * grad[k]; g1 += grad_try[k] * grad_try[k]; } + return g1 < g0; +} + +// The modes are found where the Gauss-Newton step H^-1 g, on H and not on the secant model, is below +// `steptol`, as the volume term is linear in their error; or where a step on the boundary gains less +// than `mtol` of the value `val`, the region shrunk below the distance to the modes. +static bool modes_found(int K, const std::vector& grad, const std::vector& eigvals, + const std::vector& eigvecs, double predicted_red, bool is_newton, double steptol, + double mtol, double val) { + if (!is_newton) return std::fabs(predicted_red) <= mtol * std::max(1.0, std::fabs(val)); + double tr = 0.0; + for (int k = 0; k < K; ++k) tr += std::fabs(eigvals[k]); + const double floor = 1e-10 * tr / std::max(K, 1); + double s2 = 0.0; + for (int k = 0; k < K; ++k) { + double c = 0.0; + for (int j = 0; j < K; ++j) c += eigvecs[j + (std::size_t) K * k] * grad[j]; + const double step = c / std::max(eigvals[k], floor); + s2 += step * step; + } + return std::sqrt(s2) <= steptol; +} + + +// Thin wrappers over the Moré-Sorensen subproblem and eigendecomposition in +// trust_subproblem.h, shared with trust_kernel.cpp and covering the hard case. +// A Hessian that is not finite stops the evaluation: LAPACK does not return on NaN input. +static inline void eigen_sym(double* A, int K, double* vals, double* vecs) { + for (std::size_t i = 0; i < (std::size_t) K * K; ++i) + if (!std::isfinite(A[i])) throw std::runtime_error("FOCEI: the Hessian is not finite."); + dmod::trust_internal::eigen_sym_local(A, K, vals, vecs); +} + +// The inner trust steps on the Gauss-Newton Hessian H plus S, the curvature of the prediction +// in the etas that Gauss-Newton drops, learned by SR1 from the gradients of accepted steps: +// (H_new + S) step = g_new - g_old after the update. +static void secant_update(int K, std::vector& S, const std::vector& step, + const std::vector& g_old, const std::vector& g_new, + const std::vector& H_new) { + std::vector v(K); + double vs = 0.0, vv = 0.0, ss = 0.0; + for (int r = 0; r < K; ++r) { + double hs = 0.0; + for (int c = 0; c < K; ++c) hs += (H_new[r + c * K] + S[r + c * K]) * step[c]; + v[r] = g_new[r] - g_old[r] - hs; + } + for (int r = 0; r < K; ++r) { vs += v[r] * step[r]; vv += v[r] * v[r]; ss += step[r] * step[r]; } + if (!(std::fabs(vs) > 1e-8 * std::sqrt(vv * ss))) return; + for (int c = 0; c < K; ++c) + for (int r = 0; r < K; ++r) S[r + c * K] += v[r] * v[c] / vs; +} + +// Eigen decomposition of the step model H + S, or of H where H + S is not positive definite. +static void model_eigen(int K, const std::vector& H, const std::vector& S, + std::vector& vals, std::vector& vecs) { + std::vector B(H); + for (std::size_t q = 0; q < B.size(); ++q) B[q] += S[q]; + eigen_sym(B.data(), K, vals.data(), vecs.data()); + if (vals[0] <= 0.0) { + B = H; + eigen_sym(B.data(), K, vals.data(), vecs.data()); + } +} + +static inline void trust_subproblem(int K, const double* g, + const double* vals, const double* vecs, + double r, double* p, double* predicted_red, + bool* is_newton) { + bool is_hard = false, is_easy = false; + dmod::trust_internal::trust_sub(K, g, vals, vecs, r, p, predicted_red, + is_newton, &is_hard, &is_easy); +} + + +// Parameter names of a [time, observable, parameter] deriv array. +static CharacterVector deriv_par_names(const NumericVector& d) { + const List dn = d.attr("dimnames"); + return as(dn[2]); +} + +// Inner objective for one subject from one model_cb and one err_cb call, without +// the normL2 / constraintL2 stack. Gauss-Newton: second derivatives of pred and +// sigma are dropped, first-order cross terms of an eta-dependent sigma kept. +struct EvalResult { + double value; + std::vector grad; // K + std::vector hess; // K*K column-major +}; + +static inline bool all_finite(const EvalResult& e) { + if (!std::isfinite(e.value)) return false; + for (double v : e.grad) if (!std::isfinite(v)) return false; + for (double v : e.hess) if (!std::isfinite(v)) return false; + return true; +} + +// The prediction and error-model frames of a subject, one per condition block; +// `failed` where the prediction of one of the subject blocks failed. +struct SubjectFrames { + std::vector pred, err; + bool failed = false; +}; + +// Split in two so the lock-step driver can batch the callbacks: this half +// runs them for the condition blocks of one subject, `eval_one_subject_from` +// is the pure math. +static void predict_one_subject( + Function& model_cb, Function& err_cb, NumericVector& pars, + Nullable fixed, const List& meta_i, const double* eta_block, + SubjectFrames* out) { + IntegerVector eta_idx_in_pars = meta_i["eta_idx_in_pars"]; + const int K = static_cast(eta_idx_in_pars.size()); + for (int k = 0; k < K; ++k) pars[eta_idx_in_pars[k] - 1] = eta_block[k]; + + List blocks = meta_i["blocks"]; + out->pred.assign(blocks.size(), NumericMatrix()); + out->err.assign(blocks.size(), NumericMatrix()); + for (int b = 0; b < blocks.size(); ++b) { + List block = blocks[b]; + NumericVector model_times = block["times"]; + CharacterVector condition = block["condition"]; + List pred_list = as(model_cb( + Rcpp::Named("times") = model_times, + Rcpp::Named("pars") = pars, + Rcpp::Named("fixed") = fixed, + Rcpp::Named("deriv") = true, + Rcpp::Named("conditions") = condition)); + out->pred[b] = as(pred_list[0]); + NumericVector pinner = out->pred[b].attr("parameters"); + List err_list = as(err_cb( + Rcpp::Named("out") = out->pred[b], + Rcpp::Named("pars") = pinner, + Rcpp::Named("conditions") = condition)); + out->err[b] = as(err_list[0]); + } +} + +// Data term of one condition block of a subject in the K subject etas, Gauss-Newton, +// added to value, grad and hess. +static void accumulate_block( + NumericMatrix& pred_i, + NumericMatrix& err_i, + const List& meta_i, + const CharacterVector& eta_names, + int K, + double& value, + std::vector& grad, + std::vector& hess) { + IntegerVector t_idx_in_pred = meta_i["t_idx_in_pred"]; + NumericVector y_data = meta_i["y_data"]; + IntegerVector o_idx_in_pred = meta_i["o_idx_in_pred"]; + IntegerVector o_idx_in_deriv = meta_i["o_idx_in_deriv"]; + IntegerVector t_idx_in_err = meta_i["t_idx_in_err"]; + IntegerVector o_idx_in_err = meta_i["o_idx_in_err"]; + IntegerVector o_idx_in_err_deriv = meta_i["o_idx_in_err_deriv"]; + // a recorded sigma replaces the error model of the row, NA where the model applies + const bool have_sigma_data = meta_i.containsElementNamed("sigma_data"); + NumericVector sigma_data = have_sigma_data ? as(meta_i["sigma_data"]) : NumericVector(0); + + const int T = y_data.size(); + + NumericVector deriv_attr = as(pred_i.attr("deriv")); + IntegerVector deriv_dim = deriv_attr.attr("dim"); + const int Dp0 = deriv_dim[0]; // model deriv: time + const int Dp1 = deriv_dim[1]; // model deriv: observable + // eta columns by name: the parameter axis depends on `fixed` and on the call; an eta + // without a column enters only the error model + std::vector eta_col(K, -1); + { + const CharacterVector dpn = deriv_par_names(deriv_attr); + for (int k = 0; k < K; ++k) + for (int j = 0; j < dpn.size(); ++j) + if (as(dpn[j]) == as(eta_names[k])) { eta_col[k] = j; break; } + } + + // The err deriv attribute is read only where it exists, the row has an + // err-deriv observable and the eta has a column in it (indices > 0). + Nullable err_deriv_attr_opt = err_i.attr("deriv"); + const bool have_err_deriv = err_deriv_attr_opt.isNotNull(); + NumericVector err_deriv_attr; + int De0 = 0, De1 = 0; + if (have_err_deriv) { + err_deriv_attr = as(err_deriv_attr_opt); + IntegerVector dim_e = err_deriv_attr.attr("dim"); + De0 = dim_e[0]; // err deriv: time + De1 = dim_e[1]; // err deriv: observable + } + // an eta without a column in the err deriv does not enter sigma + std::vector eta_col_err(K, -1); + if (have_err_deriv) { + const CharacterVector epn = deriv_par_names(err_deriv_attr); + for (int k = 0; k < K; ++k) + for (int j = 0; j < epn.size(); ++j) + if (as(epn[j]) == as(eta_names[k])) { eta_col_err[k] = j; break; } + } + + // Per-row predictions, sigmas and Jacobian rows in packed row-major buffers + // of stride K, the layout the shared residual kernel reads. + std::vector pred_row(T); + std::vector sigma_row(T); + std::vector y_row(T); + std::vector dpred_row((std::size_t) T * (std::size_t) K, 0.0); + std::vector dsigma_row; + bool sigma_has_eta = false; // any row with non-trivial err-deriv slice? + + for (int row = 0; row < T; ++row) { + const int tp = t_idx_in_pred [row] - 1; + const int op = o_idx_in_pred [row] - 1; + const int od = o_idx_in_deriv[row] - 1; + const int te = t_idx_in_err [row] - 1; + const int oe = o_idx_in_err [row] - 1; + + const bool recorded = have_sigma_data && !ISNAN(sigma_data[row]); + pred_row [row] = pred_i(tp, op); + sigma_row[row] = recorded ? sigma_data[row] : err_i(te, oe); + y_row [row] = y_data[row]; + + double* dpred_i = dpred_row.data() + (std::size_t) row * (std::size_t) K; + for (int k = 0; k < K; ++k) { + const int p = eta_col[k]; + dpred_i[k] = p < 0 ? 0.0 : deriv_attr[tp + od * Dp0 + p * Dp0 * Dp1]; + } + + // dsigma row: populated lazily on first eta-dependent row. + const int oed_one = o_idx_in_err_deriv[row]; + if (!recorded && have_err_deriv && oed_one > 0) { + if (!sigma_has_eta) { + dsigma_row.assign((std::size_t) T * (std::size_t) K, 0.0); + sigma_has_eta = true; + } + double* dsigma_i = dsigma_row.data() + (std::size_t) row * (std::size_t) K; + const int oed = oed_one - 1; + for (int k = 0; k < K; ++k) { + const int pe = eta_col_err[k]; + if (pe >= 0) { + dsigma_i[k] = err_deriv_attr[te + oed * De0 + pe * De0 * De1]; + } + } + } + } + + // Shared residual kernel, Gauss-Newton in eta: the rows above the limit, then the + // censored rows (M3), which the meta orders last. The plain sum of squares of these rows is not reported. + const int n_aloq = meta_i.containsElementNamed("n_aloq") ? as(meta_i["n_aloq"]) : T; + double chi2_unused = 0.0; + dmod::AccumOpts opts; + opts.use_deriv2_exact = false; + opts.bloq_mode = dmod::BloqMode::M3; + if (meta_i.containsElementNamed("t_df")) opts.t_df = as(meta_i["t_df"]); + opts.sigma_depends_on_par = sigma_has_eta; + // All first-order Hessian parts. + opts.aloq_part1 = opts.aloq_part2 = opts.aloq_part3 = true; + + dmod::accumulate_aloq_residual( + /*n_obs =*/ n_aloq, + /*n_par =*/ K, + pred_row.data(), + dpred_row.data(), + /*d2pred =*/ nullptr, + y_row.data(), + sigma_row.data(), + sigma_has_eta ? dsigma_row.data() : nullptr, + /*d2sigma=*/ nullptr, + /*lloq =*/ nullptr, + opts, + value, + chi2_unused, + grad.data(), + hess.data()); + if (n_aloq < T) { + NumericVector lloq = meta_i["lloq"]; + const std::size_t off = (std::size_t) n_aloq * (std::size_t) K; + dmod::accumulate_bloq_residual( + T - n_aloq, K, + pred_row.data() + n_aloq, + dpred_row.data() + off, + /*d2pred =*/ nullptr, + y_row.data() + n_aloq, + sigma_row.data() + n_aloq, + sigma_has_eta ? dsigma_row.data() + off : nullptr, + /*d2sigma=*/ nullptr, + lloq.begin() + n_aloq, + opts, + value, + grad.data(), + hess.data()); + } +} + +// Inner objective of one subject: the data terms of the subject condition blocks plus +// the MVN prior of the subject etas. +static EvalResult eval_one_subject_from( + SubjectFrames& frames, + NumericVector& pars, + const List& meta_i, + const double* eta_block, + const double* Omega_inv, + double Omega_log_det) { + IntegerVector eta_idx_in_pars = meta_i["eta_idx_in_pars"]; + CharacterVector eta_names = meta_i["eta_names"]; + const int K = static_cast(eta_idx_in_pars.size()); + for (int k = 0; k < K; ++k) pars[eta_idx_in_pars[k] - 1] = eta_block[k]; + + double value = 0.0; + std::vector grad(K, 0.0); + std::vector hess(K * K, 0.0); + List blocks = meta_i["blocks"]; + for (int b = 0; b < blocks.size(); ++b) + accumulate_block(frames.pred[b], frames.err[b], as(blocks[b]), eta_names, K, + value, grad, hess); + + // MVN prior: quadratic + log|Omega| per subject; the constraintL2_mvn + // convention drops the 2*pi factor (joint sums log|Omega| N times overall). + std::vector Oeta(K, 0.0); + for (int j = 0; j < K; ++j) + for (int k = 0; k < K; ++k) + Oeta[k] += Omega_inv[k + j * K] * eta_block[j]; + for (int k = 0; k < K; ++k) value += eta_block[k] * Oeta[k]; + value += Omega_log_det; + for (int k = 0; k < K; ++k) grad[k] += 2.0 * Oeta[k]; + for (int j = 0; j < K; ++j) + for (int k = 0; k < K; ++k) + hess[k + j * K] += 2.0 * Omega_inv[k + j * K]; + + EvalResult out; + out.value = value; + out.grad = std::move(grad); + out.hess = std::move(hess); + return out; +} + + +static EvalResult eval_one_subject( + Function& model_cb, Function& err_cb, NumericVector& pars, + Nullable fixed, const List& meta_i, const double* eta_block, + const double* Omega_inv, double Omega_log_det) { + SubjectFrames frames; + predict_one_subject(model_cb, err_cb, pars, fixed, meta_i, eta_block, &frames); + return eval_one_subject_from(frames, pars, meta_i, eta_block, Omega_inv, Omega_log_det); +} + + +// The local model from the state the search ends in, before the normal block is factored. +static LocalModel end_state(int K, const std::vector& eta, const std::vector& grad, + const std::vector& hess, const std::vector& eigvals, + const std::vector& eigvecs, double value, int iterations, bool converged) { + LocalModel m; + m.K = K; + m.eta = eta; + m.grad = grad; + m.H = hess; + m.eigvals = eigvals; + m.eigvecs = eigvecs; + m.value = value; + m.iterations = iterations; + m.converged = converged; + return m; +} + + +// Inner trust for one subject on eval_one_subject; writes the final eta into `pars`. +static LocalModel inner_trust_one_subject( + Function& model_cb, + Function& err_cb, + NumericVector& pars, + const Nullable& fixed, + const List& meta_i, + const NumericVector& eta_init, + const double* Omega_inv, + double Omega_log_det, + double rinit, double rmax, + int iterlim, + double steptol, double mtol) { + const int K = eta_init.size(); + + std::vector eta_curr(eta_init.begin(), eta_init.end()); + EvalResult fr = eval_one_subject( + model_cb, err_cb, pars, fixed, meta_i, + eta_curr.data(), Omega_inv, Omega_log_det); + double val_curr = fr.value; + std::vector grad(fr.grad), hess(fr.hess); + + // Eigen on current hessian + std::vector eigvals(K), eigvecs(K * K); + eigen_sym(hess.data(), K, eigvals.data(), eigvecs.data()); + + double r = rinit; + bool converged = false; + int iter = 0; + std::vector eta_try(K), p_step(K); + std::vector S((std::size_t) K * K, 0.0), mvals(eigvals), mvecs(eigvecs); + + for (iter = 1; iter <= iterlim; ++iter) { + bool is_newton = false; + double predicted_red = 0.0; + trust_subproblem(K, grad.data(), mvals.data(), mvecs.data(), + r, p_step.data(), &predicted_red, &is_newton); + if (modes_found(K, grad, eigvals, eigvecs, predicted_red, is_newton, steptol, mtol, val_curr)) { + converged = true; + break; + } + for (int k = 0; k < K; ++k) eta_try[k] = eta_curr[k] + p_step[k]; + + EvalResult ft = eval_one_subject( + model_cb, err_cb, pars, fixed, meta_i, + eta_try.data(), Omega_inv, Omega_log_det); + // a trial whose value or derivatives are not finite is rejected like one that does not decrease + if (!all_finite(ft)) { + r = shrunk_radius(r, p_step.data(), K); + std::fill(S.begin(), S.end(), 0.0); + model_eigen(K, hess, S, mvals, mvecs); + continue; + } + double val_try = ft.value; + std::vector grad_try(ft.grad), hess_try(ft.hess); + std::vector eigvals_try(K), eigvecs_try(K * K); + eigen_sym(hess_try.data(), K, eigvals_try.data(), eigvecs_try.data()); + + double actual_red = val_curr - val_try; + double rho = (predicted_red > 0.0 && std::isfinite(val_try)) + ? actual_red / predicted_red + : -std::numeric_limits::infinity(); + + const bool accept = std::isfinite(val_try) && accept_trial(rho, is_newton, predicted_red, val_curr, grad, grad_try); + if (!accept) r = shrunk_radius(r, p_step.data(), K); + else if (rho > 0.75 && !is_newton) r = std::min(2.0 * r, rmax); + + if (accept) { + secant_update(K, S, p_step, grad, grad_try, hess_try); + eta_curr = eta_try; + val_curr = val_try; + grad = grad_try; + hess = hess_try; + eigvals = eigvals_try; + eigvecs = eigvecs_try; + } else { + std::fill(S.begin(), S.end(), 0.0); + } + model_eigen(K, hess, S, mvals, mvecs); + } + + // Final eta into pars for the joint call at the modes. + IntegerVector eta_idx_in_pars = meta_i["eta_idx_in_pars"]; + for (int k = 0; k < K; ++k) { + pars[eta_idx_in_pars[k] - 1] = eta_curr[k]; + } + + // a loop that reaches iterlim leaves iter one past it + return end_state(K, eta_curr, grad, hess, eigvals, eigvecs, val_curr, std::min(iter, iterlim), converged); +} +// Lock-step inner trust: every active subject takes one step per round and the +// round's predictions go out as one batched callback. Subjects are independent, +// so this is exact; converged ones drop out. +static std::vector inner_trust_lockstep( + Function& predict_cb, NumericVector& pars_full, NumericMatrix& eta_warmstart, + List& subject_meta_fast, const std::vector>& coords, + const std::vector>& P_sub, double Omega_log_det, + Nullable fixed, int N, + double rinit, double rmax, int iterlim, double steptol, double mtol) { + + struct LS { + std::vector eta, grad, hess, eigvals, eigvecs, eta_try, p_step, S, mvals, mvecs; + double val = 0.0, r = 0.0, predicted_red = 0.0; + int iter = 0, K = 0; + bool converged = false, done = false, is_newton = false; + NumericVector pars; + }; + std::vector st(N); + + // One batched callback for the condition blocks of a set of subjects at given + // etas; the frames come back per subject. + auto run_round = [&](const std::vector& idx, + const std::vector& etas) { + const int M = static_cast(idx.size()); + int n_req = 0; + for (int j = 0; j < M; ++j) + n_req += as(as(subject_meta_fast[idx[j]])["blocks"]).size(); + List timesL(n_req), parsL(n_req); + CharacterVector conds(n_req); + int q = 0; + for (int j = 0; j < M; ++j) { + const int i = idx[j]; + List meta_i = as(subject_meta_fast[i]); + IntegerVector eip = meta_i["eta_idx_in_pars"]; + NumericVector pj = clone(st[i].pars); + for (int k = 0; k < st[i].K; ++k) pj[eip[k] - 1] = etas[j][k]; + st[i].pars = pj; + List blocks = meta_i["blocks"]; + for (int b = 0; b < blocks.size(); ++b, ++q) { + List block = blocks[b]; + parsL[q] = pj; + timesL[q] = block["times"]; + conds[q] = as(block["condition"])[0]; + } + } + List got = as(predict_cb(Rcpp::Named("timesList") = timesL, + Rcpp::Named("parsList") = parsL, + Rcpp::Named("conditions") = conds, + Rcpp::Named("fixed") = fixed)); + List preds = as(got["pred"]), errs = as(got["err"]); + std::vector frames(M); + q = 0; + for (int j = 0; j < M; ++j) { + const int nb = as(as(subject_meta_fast[idx[j]])["blocks"]).size(); + for (int b = 0; b < nb; ++b, ++q) { + SEXP pq = preds[q], eq = errs[q]; + if (TYPEOF(pq) != REALSXP || TYPEOF(eq) != REALSXP) { frames[j].failed = true; continue; } + frames[j].pred.push_back(as(pq)); + frames[j].err.push_back(as(eq)); + } + } + return frames; + }; + + for (int i = 0; i < N; ++i) { + const int K = st[i].K = coords[i].size(); + st[i].pars = clone(pars_full); + st[i].eta.assign(K, 0.0); + for (int k = 0; k < K; ++k) st[i].eta[k] = eta_warmstart(i, coords[i][k]); + st[i].eta_try.assign(K, 0.0); + st[i].p_step.assign(K, 0.0); + st[i].r = rinit; + } + + { + std::vector idx(N); + std::vector etas(N); + for (int i = 0; i < N; ++i) { idx[i] = i; etas[i] = st[i].eta.data(); } + std::vector frames = run_round(idx, etas); + for (int i = 0; i < N; ++i) { + if (frames[i].failed) + Rcpp::stop("FOCEI: the prediction fails at the modes the inner search starts from."); + List meta_i = as(subject_meta_fast[i]); + const int K = st[i].K; + EvalResult fr = eval_one_subject_from(frames[i], st[i].pars, meta_i, + st[i].eta.data(), P_sub[i].data(), + Omega_log_det); + st[i].val = fr.value; st[i].grad = fr.grad; st[i].hess = fr.hess; + st[i].eigvals.assign(K, 0.0); st[i].eigvecs.assign((size_t)K * K, 0.0); + eigen_sym(st[i].hess.data(), K, st[i].eigvals.data(), st[i].eigvecs.data()); + st[i].S.assign((size_t)K * K, 0.0); + st[i].mvals = st[i].eigvals; st[i].mvecs = st[i].eigvecs; + } + } + + for (int round = 1; round <= iterlim; ++round) { + std::vector idx; + std::vector etas; + for (int i = 0; i < N; ++i) { + if (st[i].done) continue; + const int K = st[i].K; + st[i].iter = round; + trust_subproblem(K, st[i].grad.data(), st[i].mvals.data(), + st[i].mvecs.data(), st[i].r, st[i].p_step.data(), + &st[i].predicted_red, &st[i].is_newton); + if (modes_found(K, st[i].grad, st[i].eigvals, st[i].eigvecs, st[i].predicted_red, st[i].is_newton, steptol, + mtol, st[i].val)) { + st[i].converged = true; st[i].done = true; continue; + } + for (int k = 0; k < K; ++k) st[i].eta_try[k] = st[i].eta[k] + st[i].p_step[k]; + idx.push_back(i); + etas.push_back(st[i].eta_try.data()); + } + if (idx.empty()) break; + + std::vector frames = run_round(idx, etas); + + for (size_t j = 0; j < idx.size(); ++j) { + const int i = idx[j]; + const int K = st[i].K; + // a trial where the prediction fails, or whose value or derivatives are not finite, is + // rejected like one that does not decrease + auto reject = [&]() { + st[i].r = shrunk_radius(st[i].r, st[i].p_step.data(), K); + std::fill(st[i].S.begin(), st[i].S.end(), 0.0); + model_eigen(K, st[i].hess, st[i].S, st[i].mvals, st[i].mvecs); + }; + if (frames[j].failed) { reject(); continue; } + List meta_i = as(subject_meta_fast[i]); + EvalResult ft = eval_one_subject_from(frames[j], st[i].pars, meta_i, + st[i].eta_try.data(), + P_sub[i].data(), Omega_log_det); + if (!all_finite(ft)) { reject(); continue; } + std::vector eigvals_try(K), eigvecs_try((size_t)K * K); + eigen_sym(ft.hess.data(), K, eigvals_try.data(), eigvecs_try.data()); + + const double actual_red = st[i].val - ft.value; + const double rho = (st[i].predicted_red > 0.0 && std::isfinite(ft.value)) + ? actual_red / st[i].predicted_red + : -std::numeric_limits::infinity(); + const bool accept = std::isfinite(ft.value) && + accept_trial(rho, st[i].is_newton, st[i].predicted_red, st[i].val, st[i].grad, ft.grad); + if (!accept) st[i].r = shrunk_radius(st[i].r, st[i].p_step.data(), K); + else if (rho > 0.75 && !st[i].is_newton) st[i].r = std::min(2.0 * st[i].r, rmax); + if (accept) { + secant_update(K, st[i].S, st[i].p_step, st[i].grad, ft.grad, ft.hess); + st[i].eta = st[i].eta_try; st[i].val = ft.value; + st[i].grad = ft.grad; st[i].hess = ft.hess; + st[i].eigvals = eigvals_try; st[i].eigvecs = eigvecs_try; + } else { + std::fill(st[i].S.begin(), st[i].S.end(), 0.0); + } + model_eigen(K, st[i].hess, st[i].S, st[i].mvals, st[i].mvecs); + } + } + + std::vector out(N); + for (int i = 0; i < N; ++i) { + const int K = st[i].K; + IntegerVector eip = as(subject_meta_fast[i])["eta_idx_in_pars"]; + for (int k = 0; k < K; ++k) pars_full[eip[k] - 1] = st[i].eta[k]; + out[i] = end_state(K, st[i].eta, st[i].grad, st[i].hess, st[i].eigvals, st[i].eigvecs, st[i].val, + st[i].iter, st[i].converged); + } + return out; +} + + +// log|A| and A^-1 of a symmetric n x n matrix from the eigendecomposition, eigenvalues floored at +// eflr |tr(A)| / n. +static void floored_inverse(int n, const std::vector& eigvals, const std::vector& eigvecs, + double eflr, std::vector& A_inv, double& log_det) { + double tr_H = 0.0; + for (int j = 0; j < n; ++j) tr_H += eigvals[j]; + double eps_floor = eflr * std::fabs(tr_H) / n; + std::vector lam_floor(n); + for (int j = 0; j < n; ++j) lam_floor[j] = std::max(eigvals[j], eps_floor); + log_det = 0.0; + for (int j = 0; j < n; ++j) log_det += std::log(lam_floor[j]); + A_inv.assign((std::size_t) n * n, 0.0); + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) { + double s = 0.0; + for (int q = 0; q < n; ++q) + s += eigvecs[i + q * n] * eigvecs[j + q * n] / lam_floor[q]; + A_inv[i + j * n] = s; + } +} + +void eliminate_normal(int n, const LocalModel& m, const double* C, double* T, double* t, const double* g) { + int k = static_cast(m.normal.size()); + if (n == 0 || k == 0) return; + std::vector tmp((std::size_t) n * k); + const double one = 1.0, m_one = -1.0, zero = 0.0; + // tmp = C H_NN^-1, T -= tmp C' + F77_CALL(dgemm)("N", "N", &n, &k, &k, &one, C, &n, m.H_inv.data(), &k, &zero, tmp.data(), &n FCONE FCONE); + F77_CALL(dgemm)("N", "T", &n, &n, &k, &m_one, tmp.data(), &n, C, &n, &one, T, &n FCONE FCONE); + if (!t) return; + for (int r = 0; r < n; ++r) { + double d = 0.0; + for (int q = 0; q < k; ++q) d += tmp[r + q * n] * g[q]; + t[r] -= d; + } +} + +// The normal block of `m` on the coordinates `isN`: the floored inverse and log-determinant, and +// with other coordinates S and r on them. +static void factor_normal(LocalModel& m, const std::vector& isN, double eflr) { + const int K = m.K; + m.normal.clear(); + m.other.clear(); + for (int j = 0; j < K; ++j) (isN[j] ? m.normal : m.other).push_back(j); + const int n = m.normal.size(), l = m.other.size(); + if (n == K) { + floored_inverse(K, m.eigvals, m.eigvecs, eflr, m.H_inv, m.log_det); + return; + } + m.H_inv.clear(); + m.log_det = 0.0; + if (n > 0) { + std::vector A((std::size_t) n * n), vals(n), vecs((std::size_t) n * n); + for (int c = 0; c < n; ++c) + for (int r = 0; r < n; ++r) A[r + c * n] = m.H[m.normal[r] + (std::size_t) K * m.normal[c]]; + eigen_sym(A.data(), n, vals.data(), vecs.data()); + floored_inverse(n, vals, vecs, eflr, m.H_inv, m.log_det); + } + m.S.assign((std::size_t) l * l, 0.0); + m.r.assign(l, 0.0); + std::vector C((std::size_t) l * n), gN(n); + for (int c = 0; c < l; ++c) { + m.r[c] = m.grad[m.other[c]]; + for (int r = 0; r < l; ++r) m.S[r + c * l] = m.H[m.other[r] + (std::size_t) K * m.other[c]]; + } + for (int c = 0; c < n; ++c) { + gN[c] = m.grad[m.normal[c]]; + for (int r = 0; r < l; ++r) C[r + c * l] = m.H[m.other[r] + (std::size_t) K * m.normal[c]]; + } + eliminate_normal(l, m, C.data(), m.S.data(), m.r.data(), gN.data()); +} + +void LaplaceNormal::integrate(const LocalModel& m, GroupIntegral& out) const { + const int K = m.K, n = m.normal.size(); + out.term = m.log_det; + if (n == K) { + out.weight = m.H_inv; + return; + } + out.weight.assign((std::size_t) K * K, 0.0); + for (int c = 0; c < n; ++c) + for (int r = 0; r < n; ++r) out.weight[m.normal[r] + (std::size_t) K * m.normal[c]] = m.H_inv[r + c * n]; +} + +double LaplaceNormal::constant(const std::vector& models) const { + double n = 0.0; + for (const LocalModel& m : models) n += m.normal.size(); + return -n * std::log(2.0); +} + +InnerControl inner_control(const List& control) { + InnerControl c; + if (control.containsElementNamed("rinit")) c.rinit = as(control["rinit"]); + if (control.containsElementNamed("rmax")) c.rmax = as(control["rmax"]); + if (control.containsElementNamed("iterlim")) c.iterlim = as(control["iterlim"]); + c.steptol = ctrl_tol(control, "steptol", 1e-8); + c.mtol = ctrl_tol(control, "mtol", 1e-12); + if (control.containsElementNamed("eigenFloorRelative")) + c.eigen_floor_relative = as(control["eigenFloorRelative"]); + return c; +} + +std::vector subject_coords(const List& meta_i, int K) { + std::vector c; + if (meta_i.containsElementNamed("coords")) { + IntegerVector ci = meta_i["coords"]; + for (int j : ci) { + if (j < 1 || j > K) throw std::runtime_error("nlme_group_kernel: coords out of range."); + c.push_back(j - 1); + } + return c; + } + for (int j = 0; j < K; ++j) c.push_back(j); + return c; +} + +// The K x K matrix P on the coordinates `c`. +static std::vector restrict_square(const std::vector& P, int K, const std::vector& c) { + const int n = c.size(); + std::vector out((std::size_t) n * n); + for (int b = 0; b < n; ++b) + for (int a = 0; a < n; ++a) out[a + (std::size_t) n * b] = P[c[a] + (std::size_t) K * c[b]]; + return out; +} + +Groups evaluate_groups(const GroupProblem& prob, NumericVector& pars, const NumericMatrix& warm_in, + const Integrator& integrator) { + CharacterVector subjects = prob.meta["subjects"]; + List subject_meta_fast = prob.meta["fast_meta"]; + const int K = as(prob.meta["K"]); + const int N = subjects.size(); + NumericMatrix warm(warm_in); + if (warm.nrow() != N || warm.ncol() != K) + throw std::runtime_error("nlme_group_kernel: eta_warmstart shape mismatch."); + const InnerControl& c = prob.control; + std::vector> coords(N); + std::vector> P_sub(N); + for (int i = 0; i < N; ++i) { + coords[i] = subject_coords(as(subject_meta_fast[i]), K); + P_sub[i] = restrict_square(prob.Omega_inv, K, coords[i]); + } + Groups out; + if (prob.predict_cb) { + out.models = inner_trust_lockstep(*prob.predict_cb, pars, warm, subject_meta_fast, coords, P_sub, + prob.Omega_log_det, prob.fixed, N, c.rinit, c.rmax, c.iterlim, + c.steptol, c.mtol); + } else { + // the etas of the other groups stay at their warm start: a working copy per group + std::vector base_pars(pars.begin(), pars.end()); + out.models.resize(N); + for (int i = 0; i < N; ++i) { + NumericVector eta_init(coords[i].size()); + for (std::size_t k = 0; k < coords[i].size(); ++k) eta_init[k] = warm(i, coords[i][k]); + NumericVector working_pars(base_pars.begin(), base_pars.end()); + working_pars.attr("names") = pars.attr("names"); + out.models[i] = inner_trust_one_subject(*prob.model_cb, *prob.err_cb, working_pars, prob.fixed, + as(subject_meta_fast[i]), eta_init, P_sub[i].data(), + prob.Omega_log_det, c.rinit, c.rmax, c.iterlim, c.steptol, c.mtol); + } + for (int i = 0; i < N; ++i) { + IntegerVector eip = as(subject_meta_fast[i])["eta_idx_in_pars"]; + for (std::size_t k = 0; k < coords[i].size(); ++k) pars[eip[k] - 1] = out.models[i].eta[k]; + } + } + out.integrals.resize(N); + std::vector isN(K, !prob.normal_given); + for (int j : prob.normal) isN[j] = true; + for (int i = 0; i < N; ++i) { + LocalModel& m = out.models[i]; + m.group = i; + m.coords = coords[i]; + std::vector sub(coords[i].size()); + for (std::size_t k = 0; k < coords[i].size(); ++k) sub[k] = isN[coords[i][k]]; + factor_normal(m, sub, c.eigen_floor_relative); + integrator.integrate(m, out.integrals[i]); + } + out.constant = integrator.constant(out.models); + return out; +} + +// A column-major n x n buffer as a matrix with the names `nm` on both sides. +static NumericMatrix named_square(const std::vector& x, int n, const CharacterVector& nm) { + NumericMatrix out(n, n); + std::copy(x.begin(), x.end(), out.begin()); + out.attr("dimnames") = List::create(nm, nm); + return out; +} + +// A vector with the names `nm`. +static NumericVector named_vector(const std::vector& x, const CharacterVector& nm) { + NumericVector out(x.begin(), x.end()); + out.attr("names") = nm; + return out; +} + +List groups_list(const Groups& groups, const List& meta) { + CharacterVector subjects = meta["subjects"]; + List fast = meta["fast_meta"]; + const int K = as(meta["K"]); + const int N = subjects.size(); + NumericMatrix eta_modes(N, K), grad_mat(N, K), eigvals_mat(N, K); + NumericVector log_det_H(N), value(N), term(N); + IntegerVector iterations(N); + LogicalVector converged(N), ok(N); + List H_GN_list(N), H_inv_list(N), weight_list(N), S_list(N), r_list(N), dgrad(N), deta(N), hyper(N), mean(N), + cov(N); + bool other = false, derivs = false; + for (int i = 0; i < N; ++i) { + const LocalModel& m = groups.models[i]; + const GroupIntegral& gi = groups.integrals[i]; + std::fill(eigvals_mat.row(i).begin(), eigvals_mat.row(i).end(), NA_REAL); + for (int k = 0; k < m.K; ++k) { + eta_modes(i, m.coords[k]) = m.eta[k]; grad_mat(i, m.coords[k]) = m.grad[k]; eigvals_mat(i, k) = m.eigvals[k]; + } + CharacterVector eta_nm = as(as(fast[i])["eta_names"]); + CharacterVector nN(m.normal.size()), nL(m.other.size()); + for (std::size_t j = 0; j < m.normal.size(); ++j) nN[j] = eta_nm[m.normal[j]]; + for (std::size_t j = 0; j < m.other.size(); ++j) nL[j] = eta_nm[m.other[j]]; + H_GN_list[i] = named_square(m.H, m.K, eta_nm); + H_inv_list[i] = named_square(m.H_inv, m.normal.size(), nN); + weight_list[i] = named_square(gi.weight, m.K, eta_nm); + if (!m.other.empty()) { + other = true; + S_list[i] = named_square(m.S, m.other.size(), nL); + NumericVector r(m.r.begin(), m.r.end()); + r.attr("names") = nL; + r_list[i] = r; + } + if (!gi.grad.empty() || !gi.eta.empty()) { + derivs = true; + dgrad[i] = named_vector(gi.grad, eta_nm); + deta[i] = named_vector(gi.eta, eta_nm); + hyper[i] = NumericVector(gi.hyper.begin(), gi.hyper.end()); + mean[i] = named_vector(gi.mean, nL); + if (!gi.cov.empty()) cov[i] = named_square(gi.cov, m.other.size(), nL); + } + log_det_H[i] = m.log_det; value[i] = m.value; term[i] = gi.term; + iterations[i] = m.iterations; converged[i] = m.converged; ok[i] = gi.ok; + } + rownames(eta_modes) = subjects; + rownames(grad_mat) = subjects; + rownames(eigvals_mat) = subjects; + log_det_H.names() = subjects; + value.names() = subjects; + term.names() = subjects; + iterations.names() = subjects; + converged.names() = subjects; + H_GN_list.names() = subjects; + H_inv_list.names() = subjects; + weight_list.names() = subjects; + List out = List::create( + Rcpp::Named("eta_modes") = eta_modes, + Rcpp::Named("gradient") = grad_mat, + Rcpp::Named("H_GN") = H_GN_list, + Rcpp::Named("H_inv") = H_inv_list, + Rcpp::Named("eigvals") = eigvals_mat, + Rcpp::Named("log_det_H") = log_det_H, + Rcpp::Named("value") = value, + Rcpp::Named("iterations") = iterations, + Rcpp::Named("converged") = converged, + Rcpp::Named("term") = term, + Rcpp::Named("weight") = weight_list, + Rcpp::Named("constant") = groups.constant); + if (other) { + S_list.names() = subjects; + r_list.names() = subjects; + out["S"] = S_list; + out["r"] = r_list; + } + if (derivs) { + ok.names() = subjects; + for (List* x : {&dgrad, &deta, &hyper, &mean, &cov}) x->names() = subjects; + out["ok"] = ok; + out["dgrad"] = dgrad; + out["deta"] = deta; + out["hyper"] = hyper; + out["mean"] = mean; + out["cov"] = cov; + } + return out; +} + +} // namespace nlme +} // namespace dmod + + +// The group kernel with Laplace on the normal block for all groups at the start `eta_warmstart`; +// control$normal (1-based) names the normal coordinates where not all are. The modes are written +// into `pars_full`. +// [[Rcpp::export]] +List nlme_group_kernel(Function model_cb, Function err_cb, NumericVector pars_full, NumericMatrix eta_warmstart, + List subject_meta, NumericMatrix Omega_inv_mat, double Omega_log_det, + Nullable fixed, List control, Nullable predict_cb = R_NilValue) { + const int K = as(subject_meta["K"]); + if (Omega_inv_mat.nrow() != K || Omega_inv_mat.ncol() != K) + throw std::runtime_error("nlme_group_kernel: Omega_inv_mat shape mismatch."); + dmod::nlme::GroupProblem prob; + prob.model_cb = &model_cb; + prob.err_cb = &err_cb; + Function pcb = predict_cb.isNotNull() ? Function(predict_cb) : model_cb; + if (predict_cb.isNotNull()) prob.predict_cb = &pcb; + prob.fixed = fixed; + prob.meta = subject_meta; + prob.Omega_inv.assign(Omega_inv_mat.begin(), Omega_inv_mat.end()); + prob.Omega_log_det = Omega_log_det; + prob.control = dmod::nlme::inner_control(control); + if (control.containsElementNamed("normal")) { + prob.normal_given = true; + IntegerVector nm = control["normal"]; + for (int j : nm) { + if (j < 1 || j > K) throw std::runtime_error("nlme_group_kernel: control$normal out of range."); + prob.normal.push_back(j - 1); + } + } + dmod::nlme::LaplaceNormal laplace; + dmod::nlme::Groups groups = dmod::nlme::evaluate_groups(prob, pars_full, eta_warmstart, laplace); + return dmod::nlme::groups_list(groups, subject_meta); +} diff --git a/src/nlme_kernel.h b/src/nlme_kernel.h new file mode 100644 index 00000000..183585b9 --- /dev/null +++ b/src/nlme_kernel.h @@ -0,0 +1,155 @@ +// The group kernel of the NLME methods: per evaluation of the marginal, for all groups at once, the +// inner modes, the local model of every group at the mode and the integral of every group by an +// Integrator. +// +// Group i has etas eta in R^K and the inner objective +// Phi_i(eta) = -2 log p(y_i | eta, psi) + eta' P eta + log|Omega|, +// P the prior precision of the search (Omega^-1 for normal effects), without the constant of the +// normal density. The kernel forms, in this order: +// +// mode m_i = argmin Phi_i, trust region on the Gauss-Newton curvature with an SR1 correction; +// the trial points of all groups in one batched prediction per round (predict_cb). +// local Phi_i(m_i + d) ~ Phi_i(m_i) + g_i' d + d' H_i d / 2, g_i the gradient the search +// model leaves, H_i the Gauss-Newton curvature with 2 P. The coordinates split into normal +// ones N and others L (`normal`, all of them unless the caller names a subset). +// normal H_NN by the eigendecomposition, eigenvalues floored at eigen_floor_relative +// block tr(H_NN) / |N|: log|H_NN| and the inverse H_NN^-1 on the floored eigenvalues. +// Schur eliminate_normal(): T - C H_NN^-1 C' and t - C H_NN^-1 g_N for a block C coupled to N. +// With C = H_LN, T = H_LL, t = g_L it gives S_i and r_i, the curvature and gradient on +// L once N is integrated out; with C = H_psi,N of the joint Hessian the outer model. +// integral -2 log L_i ~ Phi_i(m_i) + term_i, plus constant() over all groups, by an Integrator +// from the local model alone. +// +// A subject may have fewer coordinates than the problem: `coords` in the subject description names them +// (1-based among the K), the others rest where `pars` holds them; P is then restricted to them. +// +// Interface kernel to integrator. An Integrator reads a LocalModel and returns a GroupIntegral. The +// term is a function of the data parts of the local model, H - 2 P and g - 2 P m, of the mode m and of +// the hyperparameters of the integrator: +// term the share of -2 log L_i beyond Phi_i(m_i), without the constant; +// weight W_i (K x K) = d term_i / d H_i: the derivative of the term in psi is tr(W_i dH_i/dpsi), +// dH_i/dpsi the total derivative, the mode moving with psi (the volume callbacks in R); +// grad d term_i / d g_i, empty where the term does not depend on g; +// eta d term_i / d m_i at fixed data parts, empty likewise; +// hyper d term_i / d h for the hyperparameters h of the integrator, in the order it names; +// mean, the posterior mean and covariance on the coordinates L the integrator integrates, +// cov where it forms them. +// The derivative of -2 log L_i in psi is then that of Phi_i at the mode plus tr(W dH) + grad' dg + +// eta' dm, with dm the mode shift. LaplaceNormal integrates the normal block: term log|H_NN|, +// weight H_NN^-1, constant -|groups| |N| log 2, which is FOCEI. An integrator over L reads S_i, g_L +// and m_L; H includes 2 P on L, which such an integrator, holding a separate prior on L, takes off S_i. + +#ifndef DMOD_NLME_KERNEL_H +#define DMOD_NLME_KERNEL_H + +#include +#include +#include +#include + +namespace dmod { +namespace nlme { + +// Tolerance `key` from a control list, `dflt` where the list lacks it. +inline double ctrl_tol(const Rcpp::List& ctrl, const char* key, double dflt) { + if (ctrl.containsElementNamed(key)) return Rcpp::as(ctrl[key]); + return dflt; +} + +// The radius after a rejected step: a quarter of the radius or of the step, whichever is +// shorter, so that a rejected Newton step well inside the region is not tried again. +inline double shrunk_radius(double r, const double* step, int n) { + double ss = 0.0; + for (int k = 0; k < n; ++k) ss += step[k] * step[k]; + return 0.25 * std::min(r, std::sqrt(ss)); +} + +// Settings of the inner search. +struct InnerControl { + double rinit = 1.0, rmax = 10.0, steptol = 1e-8, mtol = 1e-12, eigen_floor_relative = 1e-10; + int iterlim = 30; +}; +InnerControl inner_control(const Rcpp::List& control); + +// The local model of one group at the mode; matrices K x K column-major, K the coordinates of the +// subject, at the positions `coords` among those of the problem. +struct LocalModel { + int K = 0, group = 0; + std::vector coords; + std::vector eta; // m_i + std::vector grad; // g_i + std::vector H; // H_i + std::vector eigvals, eigvecs; // of H_i, ascending, from the last step of the search + std::vector normal, other; // N and L, 0-based + std::vector H_inv; // H_NN^-1 on the floored eigenvalues, |N| x |N| + double log_det = 0.0; // log|H_NN| on the floored eigenvalues + std::vector S, r; // the curvature and gradient on L, empty without L + double value = 0.0; // Phi_i(m_i) + int iterations = 0; + bool converged = false; +}; + +// T (n x n) -= C H_NN^-1 C' and t (n) -= C H_NN^-1 g_N for C (n x |N|, leading dimension n), on the +// floored inverse of `m`; `t` may be null, `g` holds g_N. +void eliminate_normal(int n, const LocalModel& m, const double* C, double* T, double* t, const double* g); + +// What an integrator gives for one group; see the header comment. +struct GroupIntegral { + bool ok = true; + double term = 0.0; + std::vector weight, grad, eta, hyper, mean, cov; +}; + +class Integrator { + public: + virtual ~Integrator() = default; + virtual void integrate(const LocalModel& m, GroupIntegral& out) const = 0; + virtual double constant(const std::vector& models) const = 0; +}; + +// Laplace on the normal block, FOCEI. +class LaplaceNormal : public Integrator { + public: + void integrate(const LocalModel& m, GroupIntegral& out) const override; + double constant(const std::vector& models) const override; +}; + +// The inner problem of one evaluation: model_cb and err_cb predict one condition block, predict_cb +// (when not null) all blocks of a round in one call; `pars` the full parameter vector, the etas of +// a group at the rows of `warm`, `meta` the group description of .foceiMeta(), P = Omega_inv (K x K). +struct GroupProblem { + Rcpp::Function* model_cb = nullptr; + Rcpp::Function* err_cb = nullptr; + Rcpp::Function* predict_cb = nullptr; + Rcpp::Nullable fixed = R_NilValue; + Rcpp::List meta; + std::vector Omega_inv; + double Omega_log_det = 0.0; + std::vector normal; // every coordinate unless normal_given + bool normal_given = false; + InnerControl control; +}; + +// The groups at one evaluation: local models, integrals and the constant. +struct Groups { + std::vector models; + std::vector integrals; + double constant = 0.0; +}; + +// The coordinates of a subject among the K of the problem, 0-based. +std::vector subject_coords(const Rcpp::List& meta_i, int K); + +// The modes from `warm` (N x K), the local models and their integrals; the modes are written into +// `pars` at the eta positions of the groups. +Groups evaluate_groups(const GroupProblem& prob, Rcpp::NumericVector& pars, const Rcpp::NumericMatrix& warm, + const Integrator& integrator); + +// The groups as the list the R side reads: eta_modes, gradient, H_GN, H_inv, eigvals, log_det_H, +// value, iterations, converged per group, the integral as term, weight and constant, S and r with L. +Rcpp::List groups_list(const Groups& groups, const Rcpp::List& meta); + +} // namespace nlme +} // namespace dmod + +#endif diff --git a/src/normL2_kernel.cpp b/src/normL2_kernel.cpp index 6ce184bb..41dd19ab 100644 --- a/src/normL2_kernel.cpp +++ b/src/normL2_kernel.cpp @@ -353,7 +353,9 @@ List normL2_kernel( bool build_hessian = true, bool want_seed = false, bool local_blocks = false, - double t_df = 0) { + double t_df = 0, + bool expected = false, + bool want_rows = false) { const int n_cond = prediction.size(); if ((int) meta_list.size() != n_cond) @@ -416,6 +418,7 @@ List normL2_kernel( // Student-t with t_df degrees of freedom; 0 or infinite is the normal likelihood if (t_df > 0) base_opts.t_df = t_df; base_opts.build_hessian = build_hessian; + base_opts.expected_information = expected; // One slot per condition in the condition local parameter space, allocated here so the // workers neither allocate nor share; merged serially after the region. @@ -426,11 +429,12 @@ List normL2_kernel( // built: ALOQ rows first, then BLOQ. The caller scatters them back onto // times and observables. std::vector > seedp_c(n_cond), seeds_c(n_cond), chip_c(n_cond), chis_c(n_cond); + const bool seeds_on = want_seed || want_rows; for (int c = 0; c < n_cond; ++c) { const int npl = conds[c].n_par_local; grad_c[c].assign(npl, 0.0); if (build_hessian) hess_c[c].assign((std::size_t) npl * npl, 0.0); - if (want_seed) { + if (seeds_on) { const int nrow = conds[c].n_aloq + conds[c].n_bloq; seedp_c[c].assign(nrow, 0.0); seeds_c[c].assign(nrow, 0.0); @@ -471,8 +475,8 @@ List normL2_kernel( C.lloq.data(), opts, value_cond, chi2_cond, grad_cond, hess_cond, - want_seed ? seedp_c[c].data() : nullptr, - want_seed ? seeds_c[c].data() : nullptr); + seeds_on ? seedp_c[c].data() : nullptr, + seeds_on ? seeds_c[c].data() : nullptr); if (want_seed) dmod::chi2_seeds(C.n_aloq, C.pred.data(), C.y_data.data(), C.sigma.data(), chip_c[c].data(), chis_c[c].data()); @@ -494,8 +498,8 @@ List normL2_kernel( C.lloq.data() + off_n, opts, value_cond, grad_cond, hess_cond, - want_seed ? (seedp_c[c].data() + off_n) : nullptr, - want_seed ? (seeds_c[c].data() + off_n) : nullptr); + seeds_on ? (seedp_c[c].data() + off_n) : nullptr, + seeds_on ? (seeds_c[c].data() + off_n) : nullptr); } value_c[c] = value_cond; @@ -560,6 +564,37 @@ List normL2_kernel( Named("chi2_sigma") = cs); } + // The data rows of all conditions, stacked in condition order: the rows of the predictions, then + // those of the sigmas that depend on parameters, with the derivatives of the value in them. + RObject rows_R = R_NilValue; + if (want_rows) { + int n_rows = 0; + for (int c = 0; c < n_cond; ++c) + n_rows += conds[c].n_par_local > 0 ? conds[c].n_data * (conds[c].has_dsigma ? 2 : 1) : 0; + NumericMatrix J(n_rows, n_par_global); + NumericVector u(n_rows); + int r0 = 0; + for (int c = 0; c < n_cond; ++c) { + const CondInputs& C = conds[c]; + const int npl = C.n_par_local; + if (npl == 0) continue; + const int nb = C.has_dsigma ? 2 : 1; + for (int b = 0; b < nb; ++b) { + const std::vector& D = b == 0 ? C.dpred : C.dsigma; + const std::vector& U = b == 0 ? seedp_c[c] : seeds_c[c]; + for (int j = 0; j < C.n_data; ++j) { + u[r0 + j] = U[j]; + for (int p = 0; p < npl; ++p) { + const int g = C.par_idx_global[p] - 1; + if (g >= 0) J(r0 + j, g) = D[(std::size_t) j * npl + p]; + } + } + r0 += C.n_data; + } + } + rows_R = List::create(Named("jacobian") = J, Named("seeds") = u); + } + // Each condition in the condition parameter space, named after the columns of the // sensitivity block. RObject local_R = R_NilValue; @@ -599,5 +634,6 @@ List normL2_kernel( Named("gradient") = grad_R, Named("hessian") = hess_R, Named("seed") = seed_R, - Named("local") = local_R); + Named("local") = local_R, + Named("rows") = rows_R); } diff --git a/src/pimpl_kernel.cpp b/src/pimpl_kernel.cpp index 474361c6..b2c2d995 100644 --- a/src/pimpl_kernel.cpp +++ b/src/pimpl_kernel.cpp @@ -329,8 +329,9 @@ bool derivatives(const State& s, const std::vector& pv, int order, Root& } // The eigenvalues `re` + i `im` of J = df/dx on ker C, the scale max |lambda| with gradient; for each -// real part above `onset` - `rel` * scale (`active`, 1-based) the gradient Re w^H (J_p + J_x D) u / (w^H u), -// D = dx/dp, and |u| scaled to a largest entry of 1 (`vectors`). +// real part above `onset` - `rel` * scale (`active`, 1-based) the gradient Re tr(P (J_p + J_x D)) / m, +// D = dx/dp, P the spectral projector of the cluster of m eigenvalues (one for a simple eigenvalue), +// and the moduli of an eigenvector scaled to a largest entry of 1 (`vectors`). bool spectrum(const State& s, const std::vector& pv, const std::vector& x, double onset, double rel, std::vector& re, std::vector& im, std::vector& active, std::vector& grad, double& scale, std::vector& scaleGrad, @@ -419,66 +420,122 @@ bool spectrum(const State& s, const std::vector& pv, const std::vector vl, vr, wrJ, wiJ, vlJ, vrJ; - if (!eigen(A, q, false, re, im, vl, vr) || !eigen(J, n, true, wrJ, wiJ, vlJ, vrJ)) { + std::vector vl, vr; + if (!eigen(A, q, false, re, im, vl, vr)) { error = "the eigenvalues of the Jacobian at the steady state failed"; return false; } + // the complex Schur form J = Z T Z^H, reordered per cluster below + std::vector T0((std::size_t) n * n), Z0((std::size_t) n * n), wJ(n); + { + for (std::size_t t = 0; t < (std::size_t) n * n; ++t) T0[t] = J[t]; + int nn = n, sdim = 0, lwork = -1, info = 0; + std::vector rwork(std::max(n, 1)); + std::vector bwork(1); + cd wq = 0.0; + F77_CALL(zgees)("V", "N", nullptr, &nn, reinterpret_cast(T0.data()), &nn, &sdim, + reinterpret_cast(wJ.data()), reinterpret_cast(Z0.data()), &nn, + reinterpret_cast(&wq), &lwork, rwork.data(), bwork.data(), &info FCONE FCONE); + lwork = std::max(1, (int) wq.real()); + std::vector w(lwork); + F77_CALL(zgees)("V", "N", nullptr, &nn, reinterpret_cast(T0.data()), &nn, &sdim, + reinterpret_cast(wJ.data()), reinterpret_cast(Z0.data()), &nn, + reinterpret_cast(w.data()), &lwork, rwork.data(), bwork.data(), &info FCONE FCONE); + if (info != 0) { + error = "the Schur decomposition of the Jacobian at the steady state failed"; + return false; + } + } auto H = [&](int i, int j, int l) { return d2y[i + (std::size_t) m * (j + (std::size_t) nd * l)]; }; - // the gradient in the parameters of eigenvalue t of A, complex, and the moduli of the right - // eigenvector; false where the eigenvalue has no match in J + // the scale: the largest modulus, d|lambda| = Re(conj(lambda) dlambda) / |lambda| + scale = 0.0; + int lead = -1; + for (int t = 0; t < q; ++t) + if (std::hypot(re[t], im[t]) > scale) { scale = std::hypot(re[t], im[t]); lead = t; } + // the Frobenius norm of J and the precision of a defective double eigenvalue relative to it + double normJ = 0.0; + for (double v : J) normJ += v * v; + normJ = std::sqrt(normJ); + const double precision = 16.0 * std::sqrt(std::numeric_limits::epsilon()) * normJ; + // Eigenvalue t and those within the error of t, at most the precision of a defective double, form a + // cluster; each takes tr(P dJ) / m, P the spectral projector of J on the cluster, m the members on + // ker C: exact for a simple eigenvalue and a cluster that stays degenerate. False without a match. auto derivative = [&](int t, std::vector& g, std::vector& umod) { - int c = 0; - double best = std::numeric_limits::infinity(); + const cd lam(re[t], im[t]); + int e0 = 0; + for (int e = 1; e < n; ++e) + if (std::abs(wJ[e] - lam) < std::abs(wJ[e0] - lam)) e0 = e; + const double nearest = std::abs(wJ[e0] - lam); + if (nearest > std::max(1e-6 * (1.0 + std::abs(lam)), precision)) return false; + std::vector select(n, 0); + std::vector T(T0), Z(Z0), w(n), work(std::max(n * n, 1)); + int nn = n, mm = 0, lwork = (int) work.size(), info = 0; + double cond = 0.0, sepdummy = 0.0; + // the error of the eigenvalue alone, eps |J| / s with s the reciprocal condition number + select[e0] = 1; + F77_CALL(ztrsen)("E", "N", select.data(), &nn, reinterpret_cast(T.data()), &nn, + reinterpret_cast(Z.data()), &nn, reinterpret_cast(w.data()), &mm, + &cond, &sepdummy, reinterpret_cast(work.data()), &lwork, &info FCONE FCONE); + if (info != 0) return false; + const double err = 16.0 * std::numeric_limits::epsilon() * normJ; + const double radius = std::max(nearest, cond * precision > err ? err / cond : precision); + int mJ = 0, mA = 0; for (int e = 0; e < n; ++e) { - const double dist = std::hypot(wrJ[e] - re[t], wiJ[e] - im[t]); - if (dist < best) { best = dist; c = e; } + select[e] = std::abs(wJ[e] - lam) <= radius ? 1 : 0; + mJ += select[e]; } - if (best > 1e-6 * (1.0 + std::hypot(re[t], im[t]))) return false; - std::vector u(n), w(n); - for (int i = 0; i < n; ++i) { - if (wiJ[c] == 0.0) { - u[i] = vrJ[i + (std::size_t) n * c]; - w[i] = vlJ[i + (std::size_t) n * c]; - } else if (wiJ[c] > 0.0) { - u[i] = cd(vrJ[i + (std::size_t) n * c], vrJ[i + (std::size_t) n * (c + 1)]); - w[i] = cd(vlJ[i + (std::size_t) n * c], vlJ[i + (std::size_t) n * (c + 1)]); - } else { - u[i] = cd(vrJ[i + (std::size_t) n * (c - 1)], -vrJ[i + (std::size_t) n * c]); - w[i] = cd(vlJ[i + (std::size_t) n * (c - 1)], -vlJ[i + (std::size_t) n * c]); - } + for (int e = 0; e < q; ++e) + if (std::abs(cd(re[e], im[e]) - lam) <= radius) ++mA; + T = T0; + Z = Z0; + F77_CALL(ztrsen)("N", "V", select.data(), &nn, reinterpret_cast(T.data()), &nn, + reinterpret_cast(Z.data()), &nn, reinterpret_cast(w.data()), &mm, + &cond, &sepdummy, reinterpret_cast(work.data()), &lwork, &info FCONE FCONE); + if (info != 0 || mm != mJ) return false; + // P = Z1 Y^H with Y^H = Z1^H + X Z2^H, where T11 X - X T22 = T12 + const int r2 = n - mJ; + std::vector X((std::size_t) mJ * std::max(r2, 1), 0.0); + if (r2 > 0) { + for (int j = 0; j < r2; ++j) + for (int i = 0; i < mJ; ++i) X[i + (std::size_t) mJ * j] = T[i + (std::size_t) n * (mJ + j)]; + int isgn = -1, a1 = mJ, a2 = r2; + double sc = 1.0; + F77_CALL(ztrsyl)("N", "N", &isgn, &a1, &a2, reinterpret_cast(T.data()), &nn, + reinterpret_cast(T.data() + (std::size_t) n * mJ + mJ), &nn, + reinterpret_cast(X.data()), &a1, &sc, &info FCONE FCONE); + if (info < 0 || !(sc > 0.0)) return false; + for (cd& v : X) v /= sc; } + 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; + } double umax = 0.0; - for (int i = 0; i < n; ++i) umax = std::max(umax, std::abs(u[i])); + for (int i = 0; i < n; ++i) umax = std::max(umax, std::abs(Z[i])); umod.assign(n, 0.0); - for (int i = 0; i < n; ++i) umod[i] = umax > 0.0 ? std::abs(u[i]) / umax : 0.0; - cd den = 0.0; - for (int i = 0; i < n; ++i) den += std::conj(w[i]) * u[i]; - // Q_l = w^H (dJ/dz_l) u for every variable and parameter z_l + for (int i = 0; i < n; ++i) umod[i] = umax > 0.0 ? std::abs(Z[i]) / umax : 0.0; + // Q_l = tr(P dJ/dz_l) for every variable and parameter z_l std::vector Q(nd, 0.0); for (int l = 0; l < nd; ++l) - for (int j = 0; j < n; ++j) { - if (u[j] == cd(0.0)) continue; - cd v = 0.0; - for (int i = 0; i < n; ++i) v += std::conj(w[i]) * H(i, j, l); - Q[l] += v * u[j]; - } + for (int j = 0; j < n; ++j) + for (int i = 0; i < n; ++i) { + const double h = H(i, j, l); + if (h != 0.0) Q[l] += P[j + (std::size_t) n * i] * h; + } g.assign(np, 0.0); for (int a = 0; a < np; ++a) { cd v = Q[n + a]; for (int l = 0; l < n; ++l) v += Q[l] * r.D[l + (std::size_t) n * a]; - g[a] = v / den; + g[a] = v / (double) std::max(mA, 1); } return true; }; std::vector g; std::vector umod; - // the scale: the largest modulus, d|lambda| = Re(conj(lambda) dlambda) / |lambda| - scale = 0.0; scaleGrad.assign(np, 0.0); - int lead = -1; - for (int t = 0; t < q; ++t) - if (std::hypot(re[t], im[t]) > scale) { scale = std::hypot(re[t], im[t]); lead = t; } if (lead >= 0) { if (!derivative(lead, g, umod)) { error = "an eigenvalue on ker C has no match in the Jacobian"; diff --git a/src/residual_kernel.cpp b/src/residual_kernel.cpp index 18a042e5..dd3816e6 100644 --- a/src/residual_kernel.cpp +++ b/src/residual_kernel.cpp @@ -117,8 +117,13 @@ static void accumulate_t_rows(int n_obs, int n_par, const double* pred, const do } // derivatives of the loss in pred and sigma const double lp = m1 * inv_s, ls = (two - w * m1) * inv_s; - const double lpp = m2 * inv_s2, lps = -(m1 + w * m2) * inv_s2; - const double lss = (2.0 * w * m1 + w * w * m2 - two) * inv_s2; + double lpp = m2 * inv_s2, lps = -(m1 + w * m2) * inv_s2; + double lss = (2.0 * w * m1 + w * w * m2 - two) * inv_s2; + if (!censored && opts.expected_information && !opts.use_deriv2_exact) { + lpp = 2.0 * (nu + 1.0) / (nu + 3.0) * inv_s2; + lps = 0.0; + lss = 4.0 * nu / (nu + 3.0) * inv_s2; + } const double* dp = dpred + (std::size_t) i * n_par; const double* ds = has_dsig ? dsigma + (std::size_t) i * n_par : nullptr; for (int k = 0; k < n_par; ++k) @@ -261,7 +266,11 @@ void accumulate_aloq_residual( double coef_cross = 0.0; double coef_dsig2 = 0.0; double coef_dw02 = 0.0; - if (has_dsig) { + if (has_dsig && opts.expected_information && !opts.use_deriv2_exact && !m4beal_aloq) { + // with Part0 2/sigma^2 (dpred - wr dsigma)^2 this gives 2/sigma^2 dpred^2 + 4/sigma^2 dsigma^2 + coef_cross = 2.0 * wr * inv_s2; + coef_dsig2 = (4.0 - 2.0 * wr * wr) * inv_s2; + } else if (has_dsig) { if (opts.aloq_part1) coef_cross += -2.0 * wr * inv_s2; if (opts.aloq_part2) coef_dsig2 += 4.0 * wr * wr * inv_s2; if (opts.aloq_part3) coef_dsig2 += -2.0 * inv_s2; diff --git a/src/residual_kernel.h b/src/residual_kernel.h index 94682978..35e42adf 100644 --- a/src/residual_kernel.h +++ b/src/residual_kernel.h @@ -11,6 +11,8 @@ // grad += 2 * (wr * dwr/dtheta + 1/sigma * dsigma/dtheta) // hess += 2 * outer(dwr/dtheta, dwr/dtheta) -- Part0 (GN) // + ALOQ_part1 + ALOQ_part2 + ALOQ_part3 -- toggleable +// or, with expected_information, the Fisher information +// 2/sigma^2 outer(dpred, dpred) + 4/sigma^2 outer(dsigma, dsigma) // + (if use_deriv2_exact) 2 * wr/sigma * d2pred/dtheta^2 // + (2/sigma) (1 - wr^2) * d2sigma/dtheta^2 // @@ -38,7 +40,8 @@ // M3: obj += -2 log F_nu(-wr) // grad and hess from the derivatives of the loss in (pred, sigma), the // Hessian J' L J with L the exact 2 x 2 Hessian of the loss, plus the -// deriv2-exact terms weighted by the first derivatives of the loss. +// deriv2-exact terms weighted by the first derivatives of the loss; with +// expected_information on ALOQ rows L = diag(2 (nu + 1), 4 nu) / ((nu + 3) sigma^2). // // Conventions: // - dpred is stored row-major: dpred[row*n_par + p] = d pred_row / d par_p. @@ -93,6 +96,11 @@ struct AccumOpts { // dependence on parameters in gradient and Hessian (Parts 1/2/3). bool sigma_depends_on_par = false; + // If true and use_deriv2_exact is false, the curvature of an uncensored row in (pred, sigma) is + // the expected (Fisher) information of the row likelihood, positive semidefinite, in place of the + // exact Hessian of the row loss, which is indefinite where sigma depends on the parameters. + bool expected_information = false; + // If true, d2sigma must be non-null. Activates the d2sigma exact-Hessian // term in accumulate_aloq / accumulate_bloq (gated also by use_deriv2_exact // and sigma_depends_on_par). diff --git a/src/trustL1_kernel.cpp b/src/trustL1_kernel.cpp index 37fc8558..f091b98b 100644 --- a/src/trustL1_kernel.cpp +++ b/src/trustL1_kernel.cpp @@ -388,6 +388,9 @@ struct RefState { bool accept = true, converged = false, bail = false, done = false; int iter = 0, n_iter = 0, n_fail = 0, n_stall = 0; std::string stop_reason = "iterlim"; + // The convergence stop held back by ref_newton_small() since the last accepted step that changed + // the value by ftol or more; a run that then ends on the radius ends on that stop. + const char* vetoed = nullptr; std::vector rc; std::vector zr, lbr, ubr, gr, Hr, absv, jv, sqrtv, ghat, Bhat; @@ -540,8 +543,11 @@ bool ref_propose(RefState& s, const RefTune& t) { const int K = s.K; if (s.accept) { ref_build(s, t); - if (s.opt_measure <= t.gtol && ref_newton_small(s, t)) { - s.converged = true; s.stop_reason = "gradient"; s.done = true; return false; + if (s.opt_measure <= t.gtol) { + if (ref_newton_small(s, t)) { + s.converged = true; s.stop_reason = "gradient"; s.done = true; return false; + } + s.vetoed = "gradient"; } } const int Kred = static_cast(s.rc.size()); @@ -638,6 +644,7 @@ bool ref_accept(RefState& s, const RefTune& t, bool eval_ok, double val_obj_try, // Count rejected steps that also left the objective flat. if (s.accept || !eval_ok || dval >= t.ftol) s.n_stall = 0; else s.n_stall++; + if (s.accept && eval_ok && dval >= t.ftol) s.vetoed = nullptr; if (s.accept && eval_ok) { s.theta = s.theta_try; @@ -665,12 +672,20 @@ bool ref_accept(RefState& s, const RefTune& t, bool eval_ok, double val_obj_try, const char* soft = (dval < t.ftol) ? "fvalue" : (std::fabs(s.m_value) < t.mtol) ? "preddiff" : nullptr; if (soft) ref_build(s, t); if (soft && ref_newton_small(s, t)) { s.converged = true; s.stop_reason = soft; s.done = true; return false; } + if (soft) s.vetoed = soft; if (!soft && t.xtol > 0.0 && s.stepnorm < t.xtol) { s.converged = true; s.stop_reason = "step"; s.done = true; return false; } } - if (s.r < t.rmin) { s.stop_reason = "radius"; s.done = true; return false; } + if (s.r < t.rmin) { + if (s.vetoed != nullptr) { s.converged = true; s.stop_reason = s.vetoed; } + else s.stop_reason = "radius"; + s.done = true; return false; + } + // stagnation is convergence where the model predicts at most mtol or a convergence stop was held back if (s.n_stall >= kStallLimit) { - s.converged = true; s.stop_reason = "stagnation"; s.done = true; return false; + ref_build(s, t); + s.converged = s.vetoed != nullptr || ref_newton_small(s, t); + s.stop_reason = "stagnation"; s.done = true; return false; } return true; } diff --git a/src/trust_kernel.cpp b/src/trust_kernel.cpp index 59c94717..0a8585db 100644 --- a/src/trust_kernel.cpp +++ b/src/trust_kernel.cpp @@ -54,11 +54,18 @@ namespace { // lives in the working Hessian `H_full`, so the scaling, eigendecomposition // and subproblem downstream are untouched. enum HessianMethod { HM_NONE = -1, HM_GN = 0, HM_BFGS = 1, HM_SR1 = 2, - HM_EXACT = 3 }; + HM_EXACT = 3, HM_SBFGS = 4, HM_SSR1 = 5, HM_GNSBFGS = 6, + HM_GNSSR1 = 7 }; + +// Structured methods keep the Gauss-Newton Hessian of the objective and update +// only a correction A; the hybrid ones choose between both per accepted step. +inline bool hm_structured(int m) { return m >= HM_SBFGS; } +inline bool hm_hybrid(int m) { return m == HM_GNSBFGS || m == HM_GNSSR1; } +inline bool hm_sr1_type(int m) { return m == HM_SR1 || m == HM_SSR1 || m == HM_GNSSR1; } // Seed of the quasi-Newton approximation. Identity is all a gradient-only // derivative scheme can supply. -enum HessianInit { HI_GN = 0, HI_IDENTITY = 1, HI_EXACT = 2 }; +enum HessianInit { HI_GN = 0, HI_IDENTITY = 1, HI_EXACT = 2, HI_TRACKED = 3 }; enum HessianReseed { HR_NEVER = 0, HR_STALL = 1 }; // Quasi-Newton settings of one phase. @@ -68,6 +75,9 @@ struct QnParams { int memory; double cautious; bool rejected; + bool scaled; // A scaled with the residual norm (Huschens) + double hybrid_tol; // threshold of the switch rule of the hybrid methods + bool hybrid_shift; // rho I added on the Gauss-Newton branch of the hybrid methods }; // One phase of a run: the Hessian source, a separate iteration budget, the sweep @@ -75,7 +85,10 @@ struct QnParams { struct Phase { int method; int iterlim; + int radius_stall; // handover after this many iterations at an unchanged radius, 0 off bool reverse; + bool keep_radius; // the phase starts at the radius of the handover instead of rinit + bool stop_ends; // a value, model, step or stagnation stop ends the run instead of handing over QnParams qn; }; @@ -102,6 +115,28 @@ void qn_assemble(int kind, int K, std::vector& H, double gamma, for (std::size_t t = 0; t < KK; ++t) H[t] = sgn * B[t]; } +// A BFGS update keeps the inertia of the matrix it starts from, so an indefinite seed stays +// indefinite for the whole phase. Such a seed takes the absolute values of the eigenvalues, floored +// at the noise level of the decomposition; a positive semidefinite seed is left as it is. +void bfgs_seed_definite(int K, std::vector& H, double sgn) { + const std::size_t KK = (std::size_t) K * K; + std::vector B(KK), vals(K), vecs(KK); + for (std::size_t t = 0; t < KK; ++t) B[t] = sgn * H[t]; + eigen_sym_local(B.data(), K, vals.data(), vecs.data()); + if (!(vals[0] < 0.0)) return; + double vmax = 0.0; + for (int j = 0; j < K; ++j) vmax = std::max(vmax, std::fabs(vals[j])); + const double cut = 8.0 * K * std::numeric_limits::epsilon() * vmax; + std::fill(B.begin(), B.end(), 0.0); + for (int k = 0; k < K; ++k) { + const double lam = std::max(std::fabs(vals[k]), cut); + const double* q = vecs.data() + (std::size_t) k * K; + for (int j = 0; j < K; ++j) + for (int i = 0; i < K; ++i) B[i + (std::size_t) j * K] += lam * q[i] * q[j]; + } + for (std::size_t t = 0; t < KK; ++t) H[t] = sgn * B[t]; +} + // Li-Fukushima cautious update: a pair with negligible curvature along the step // contains no information. SR1 is exempt, negative curvature is legal there. bool qn_pair_informative(int K, const std::vector& s, @@ -112,30 +147,302 @@ bool qn_pair_informative(int K, const std::vector& s, return sy > cautious * std::sqrt(ss * yy); } +// Pairs kept by limited-memory BFGS on the sparse model where qnMemory is 0. +const int kSparseMemory = 10; + +// y = H x for the Hessian of the sparse model in the sign of the value: S from the upper triangle +// in compressed columns plus U diag(d) U'. +void sparse_hess_apply(int K, const dmod::trust_model::SparseModel::Hess& h, const double* x, double* y) { + std::fill(y, y + K, 0.0); + for (int j = 0; j < K; ++j) + for (int k = h.p[j]; k < h.p[j + 1]; ++k) { + const int i = h.i[k]; + if (i > j) continue; + y[i] += h.x[k] * x[j]; + if (i != j) y[j] += h.x[k] * x[i]; + } + const int m = (int) h.d.size(); + for (int l = 0; l < m; ++l) { + const double* Ul = h.U.data() + (std::size_t) l * K; + double t = 0.0; + for (int i = 0; i < K; ++i) t += Ul[i] * x[i]; + t *= h.d[l]; + for (int i = 0; i < K; ++i) y[i] += t * Ul[i]; + } +} + +// A BFGS update keeps the inertia of the matrix it starts from. A sparse seed that is not positive +// definite, by the inertia of the factorization, takes tau I added, tau the smallest of a geometric +// sequence that makes it definite, refined by bisection (Nocedal and Wright, Algorithm 3.3). +void sparse_seed_definite(int K, dmod::trust_model::SparseModel::Hess& h, double sgn) { + dmod::trust_model::SparseModel sm(K); + std::vector w(K, 1.0), zero(K, 0.0); + sm.build(h, w.data(), sgn, zero.data()); + if (sm.factor(0.0)) return; + double lo = 0.0, hi = 1e-8 * sm.scale; + while (!sm.factor(hi)) { + lo = hi; + hi *= 10.0; + if (!(hi < 1e3 * sm.scale)) return; + } + for (int b = 0; b < 8 && lo > 0.0; ++b) { + const double mid = std::sqrt(lo * hi); + if (sm.factor(mid)) hi = mid; else lo = mid; + } + // tau I joins the sparse part, with a diagonal entry added to a column that has none + std::vector p(K + 1, 0), i; + std::vector x; + for (int j = 0; j < K; ++j) { + bool has = false; + for (int k = h.p[j]; k < h.p[j + 1]; ++k) { + i.push_back(h.i[k]); + x.push_back(h.x[k] + (h.i[k] == j ? sgn * hi : 0.0)); + has = has || h.i[k] == j; + } + if (!has) { i.push_back(j); x.push_back(sgn * hi); } + p[j + 1] = (int) i.size(); + } + h.p = std::move(p); h.i = std::move(i); h.x = std::move(x); + if (!Rf_isNull(h.hessian)) { + Environment mat = Environment::namespace_env("Matrix"); + Function diagonal = mat["Diagonal"], plus("+"); + h.hessian = plus(h.hessian, diagonal(K, sgn * hi)); + } +} + +// Limited-memory BFGS on the sparse model: H = H0 plus the compact correction of Byrd, Nocedal and +// Schnabel (1994) from the pairs (S, Y) in the minimized sign, -W M^-1 W' with W = [B0 S, Y] and +// M = [S'B0 S, L; L', -D], which joins the low-rank part of H0 as W P diag(-1/theta) P' W' from +// M = P diag(theta) P'. False where M is singular to rounding. +bool lbfgs_compose(int K, const dmod::trust_model::SparseModel::Hess& H0, + const std::deque>& S, const std::deque>& Y, + double sgn, const CharacterVector& parnames, dmod::trust_model::SparseModel::Hess& H) { + const int m = (int) S.size(), n = 2 * m; + std::vector W((std::size_t) K * n); + for (int l = 0; l < m; ++l) { + double* BSl = W.data() + (std::size_t) l * K; + sparse_hess_apply(K, H0, S[l].data(), BSl); + for (int i = 0; i < K; ++i) BSl[i] *= sgn; + std::copy(Y[l].begin(), Y[l].end(), W.data() + (std::size_t) (m + l) * K); + } + std::vector M((std::size_t) n * n, 0.0); + auto dot = [&](const double* a, const double* b) { + double t = 0.0; + for (int i = 0; i < K; ++i) t += a[i] * b[i]; + return t; + }; + for (int a = 0; a < m; ++a) + for (int b = 0; b < m; ++b) { + M[a + (std::size_t) b * n] = dot(S[a].data(), W.data() + (std::size_t) b * K); + const double sy = dot(S[a].data(), Y[b].data()); + if (a > b) { M[a + (std::size_t) (m + b) * n] = sy; M[(m + b) + (std::size_t) a * n] = sy; } + if (a == b) M[(m + a) + (std::size_t) (m + a) * n] = -sy; + } + std::vector theta(n), P((std::size_t) n * n); + eigen_sym_local(M.data(), n, theta.data(), P.data()); + double tmax = 0.0; + for (int a = 0; a < n; ++a) tmax = std::max(tmax, std::fabs(theta[a])); + for (int a = 0; a < n; ++a) if (!(std::fabs(theta[a]) > 1e-12 * tmax)) return false; + const int m0 = (int) H0.d.size(); + H.p = H0.p; H.i = H0.i; H.x = H0.x; H.hessian = H0.hessian; + H.U = H0.U; + H.U.resize((std::size_t) K * (m0 + n), 0.0); + H.d = H0.d; + H.d.resize(m0 + n); + for (int e = 0; e < n; ++e) { + double* Ue = H.U.data() + (std::size_t) (m0 + e) * K; + for (int a = 0; a < n; ++a) { + const double pa = P[a + (std::size_t) e * n]; + const double* Wa = W.data() + (std::size_t) a * K; + for (int i = 0; i < K; ++i) Ue[i] += Wa[i] * pa; + } + H.d[m0 + e] = -sgn / theta[e]; + } + NumericMatrix U(K, m0 + n); + std::copy(H.U.begin(), H.U.end(), U.begin()); + U.attr("dimnames") = List::create(parnames, R_NilValue); + H.lowrank = List::create(Named("U") = U, Named("d") = NumericVector(H.d.begin(), H.d.end())); + return true; +} + // `exact` and `gn` are both pass-throughs of the objective's own Hessian and // differ only in which one was asked for, so they are told apart by the // running phase's method rather than by the quasi-Newton state. +// Slot of the source currently producing the model Hessian, ordered as +// kHessianSourceNames, which follows the HessianMethod values. +const char* const kHessianSourceNames[] = {"gn", "bfgs", "sr1", "exact", "sbfgs", + "ssr1", "gnsbfgs", "gnssr1"}; +const int kHessianSourceCount = 8; + +inline int hessian_source_slot(bool qn_active, int qn_kind, int method) { + if (!qn_active) return (method == HM_EXACT) ? HM_EXACT : HM_GN; + return qn_kind; +} + inline const char* hessian_source_label(bool qn_active, int qn_kind, int method) { - if (!qn_active) return (method == HM_EXACT) ? "exact" : "gn"; - if (qn_kind == HM_SR1) return "sr1"; - return "bfgs"; + return kHessianSourceNames[hessian_source_slot(qn_active, qn_kind, method)]; } -// Slot of the source currently producing the model Hessian, ordered as -// kHessianSourceNames. -const char* const kHessianSourceNames[] = {"gn", "bfgs", "sr1", "exact"}; -const int kHessianSourceCount = 4; +// BFGS update A + z z' / z's - u u' / s'u, u = A s, of a symmetric `A` in place, so that A s = z +// afterwards also where s'As <= 0, and from A = 0. A pair without positive curvature z's, or with +// s'As = 0 but As != 0, leaves `A` unchanged. Returns whether `A` changed. +bool bfgs_update_secant(int K, std::vector& A, const std::vector& s, + const std::vector& z) { + std::vector u(K, 0.0); + for (int j = 0; j < K; ++j) + for (int i = 0; i < K; ++i) u[i] += A[i + (std::size_t) j * K] * s[j]; + double c = 0.0, b = 0.0, un = 0.0; + for (int i = 0; i < K; ++i) { c += u[i] * s[i]; b += z[i] * s[i]; un += u[i] * u[i]; } + if (!(b > 0.0)) return false; + if (c == 0.0 && un > 0.0) return false; + for (int j = 0; j < K; ++j) + for (int i = 0; i < K; ++i) { + double d = z[i] * z[j] / b; + if (c != 0.0) d -= u[i] * u[j] / c; + A[i + (std::size_t) j * K] += d; + } + return true; +} -inline int hessian_source_slot(bool qn_active, int qn_kind, int method) { - if (!qn_active) return (method == HM_EXACT) ? 3 : 0; - if (qn_kind == HM_SR1) return 2; +// The data rows an objective returns with `structure` (see objlist()), in the sign of the +// objective: the Jacobian J of the predictions and sigmas, column-major with one row per data row, +// the derivatives u of the value in them, and the Gauss-Newton Hessian G_LS of the data term. +// n < 0 where the evaluation returned none. +struct Rows { + std::vector J, u, GLS; + int n = -1; + bool ok() const { return n >= 0; } +}; + +bool read_rows(const List& out, int K, Rows& r) { + r.n = -1; + if (!out.containsElementNamed("structure")) return false; + SEXP st = out["structure"]; + if (TYPEOF(st) != VECSXP) return false; + List L(st); + if (!L.containsElementNamed("jacobian") || !L.containsElementNamed("seeds") || + !L.containsElementNamed("hessian")) return false; + SEXP J = L["jacobian"], u = L["seeds"], H = L["hessian"]; + if (TYPEOF(J) != REALSXP || TYPEOF(u) != REALSXP || TYPEOF(H) != REALSXP) return false; + const int n = Rf_length(u); + if ((std::size_t) Rf_length(J) != (std::size_t) n * K || Rf_length(H) != K * K) return false; + r.J.assign(REAL(J), REAL(J) + (std::size_t) n * K); + r.u.assign(REAL(u), REAL(u) + n); + r.GLS.assign(REAL(H), REAL(H) + (std::size_t) K * K); + r.n = n; + return true; +} + +// The residual norm of the scaled methods: |u| with data rows, sqrt(f) without, which agree up to +// a constant factor for a sum of squares. +double residual_norm(const Rows& r, double f) { + if (!r.ok()) return std::sqrt(std::max(f, 0.0)); + double uu = 0.0; + for (double v : r.u) uu += v * v; + return std::sqrt(uu); +} + +// State of a structured phase, in the minimized sign: the Gauss-Newton Hessian G and the +// residual norm rho at the current iterate, the correction A and, for a hybrid method, the +// branch of the last accepted step. With residual scaling, A approximates S / rho. +struct Structured { + std::vector G, A; + double rho = 0.0; + bool gn_branch = false; + + void reset(int K, const std::vector& H, double sgn, double rho0) { + const std::size_t KK = (std::size_t) K * K; + G.resize(KK); A.assign(KK, 0.0); + for (std::size_t t = 0; t < KK; ++t) G[t] = sgn * H[t]; + rho = rho0; + gn_branch = false; + } + // The model Hessian in the sign of the objective: G + c A, c = rho with scaling and 1 + // otherwise, or on the Gauss-Newton branch of a hybrid method G, or G + rho I with `shift`. + void compose(int K, std::vector& H, double sgn, int method, bool scaled, + bool shift) const { + const std::size_t KK = (std::size_t) K * K; + H.resize(KK); + const bool gn = hm_hybrid(method) && gn_branch; + const double c = gn ? 0.0 : (scaled ? rho : 1.0); + for (std::size_t t = 0; t < KK; ++t) H[t] = sgn * (G[t] + c * A[t]); + if (gn && shift) + for (int i = 0; i < K; ++i) H[i + (std::size_t) i * K] += sgn * rho; + } +}; + +// Update of the structured correction from the pair (s, y), y = g+ - g, with G+ and rho+ at the +// trial point, all in the minimized sign, and the data rows `rc` at the iterate and `rt` at the +// trial point. The structured secant is y# = y - J'(u+ - u) - (G+ - G_LS+) s, which is (J+ - J)'u+ +// for the data term and y - G+ s for the other terms; without data rows y - G+ s throughout. The +// scaled methods use z = y# rho+ / rho. Returns 1 for an update, 0 for a skipped pair, and for a +// hybrid method 2 where the switch rule takes the Gauss-Newton branch. +int structured_update(int method, const QnParams& q, int K, Structured& st, + const std::vector& s, const std::vector& y, + const std::vector& Gp, double rho_p, + const Rows& rc, const Rows& rt, double sgn) { + const std::size_t KK = (std::size_t) K * K; + std::vector ysh(y); + for (int j = 0; j < K; ++j) + for (int i = 0; i < K; ++i) ysh[i] -= Gp[i + (std::size_t) j * K] * s[j]; + if (rc.ok() && rt.ok() && rc.n == rt.n) { + const int n = rc.n; + std::vector du(n); + for (int r = 0; r < n; ++r) du[r] = rt.u[r] - rc.u[r]; + for (int k = 0; k < K; ++k) { + const double* Jk = rc.J.data() + (std::size_t) k * n; + double v = 0.0; + for (int r = 0; r < n; ++r) v += Jk[r] * du[r]; + ysh[k] -= sgn * v; + } + for (int j = 0; j < K; ++j) + for (int i = 0; i < K; ++i) ysh[i] += sgn * rt.GLS[i + (std::size_t) j * K] * s[j]; + } + const bool hybrid = hm_hybrid(method); + const bool scaled = hybrid || q.scaled; + std::vector z(ysh); + if (scaled) { + if (!(st.rho > 0.0)) return 0; + for (int i = 0; i < K; ++i) z[i] *= rho_p / st.rho; + } + + if (hybrid) { + double zs = 0.0, ss = 0.0; + for (int i = 0; i < K; ++i) { zs += z[i] * s[i]; ss += s[i] * s[i]; } + const double ratio = (method == HM_GNSSR1) ? std::fabs(zs) / ss : zs / ss; + if (!(ratio >= q.hybrid_tol)) return 2; + if (method == HM_GNSBFGS) return bfgs_update_secant(K, st.A, s, z) ? 1 : 0; + return qn_update_B(HM_SR1, K, st.A, s, z) ? 1 : 0; + } + + // Huschens: the update acts on rho+ A, the estimate of S at the trial point. + if (scaled && !(rho_p > 0.0)) return 0; + const double c = scaled ? rho_p : 1.0; + std::vector At(KK); + for (std::size_t t = 0; t < KK; ++t) At[t] = c * st.A[t]; + bool changed; + if (method == HM_SSR1) { + changed = qn_update_B(HM_SR1, K, At, s, z); + } else { + // BFGS on G+ + A with the secant G+ s + z, undamped: G+ changes from iterate to iterate, + // so G+ + A need not be positive definite, and the update restores the secant along s. + std::vector Bs(KK), ys(z); + for (std::size_t t = 0; t < KK; ++t) Bs[t] = Gp[t] + At[t]; + for (int j = 0; j < K; ++j) + for (int i = 0; i < K; ++i) ys[i] += Gp[i + (std::size_t) j * K] * s[j]; + if (!qn_pair_informative(K, s, ys, q.cautious)) return 0; + changed = bfgs_update_secant(K, Bs, s, ys); + if (changed) for (std::size_t t = 0; t < KK; ++t) At[t] = Bs[t] - Gp[t]; + } + if (!changed) return 0; + for (std::size_t t = 0; t < KK; ++t) st.A[t] = At[t] / c; return 1; } // ---- Coleman-Li interior trust-region-reflective -------------------------- // One kernel for both curvature models of trust_model.h: the dense one and the sparse one with -// its low-rank part take the same steps; quasi-Newton phases update a dense Hessian. +// a low-rank part take the same steps; quasi-Newton phases update a dense Hessian. template List trust_reflective(Function objfun, NumericVector parinit, double rinit, double rmax, @@ -219,6 +526,25 @@ List trust_reflective(Function objfun, NumericVector parinit, "quasi-Newton approximation with the identity instead"); } if (!seeded) Model::identity(K, minimize ? 1.0 : -1.0, H_full); + if constexpr (Model::dense) + if (seeded && hessianMethod == HM_BFGS) bfgs_seed_definite(K, H_full.H, minimize ? 1.0 : -1.0); + Structured st; + int n_hybrid_gn = 0; + // The data rows at the current iterate and at the trial point; `rows_seen` once the objective + // returned any. + Rows rows_cur, rows_try; + bool rows_seen = read_rows(out_init, K, rows_cur); + if constexpr (Model::dense) + if (hm_structured(hessianMethod)) + st.reset(K, H_full.H, minimize ? 1.0 : -1.0, residual_norm(rows_cur, minimize ? val : -val)); + + // The sparse model of a BFGS phase: the Hessian of the objective at the start of the phase, made + // positive definite, to which the kept pairs add the compact correction. + typename Model::Hess H_lb0; + if constexpr (!Model::dense) if (hessianMethod == HM_BFGS) { + sparse_seed_definite(K, H_full, minimize ? 1.0 : -1.0); + H_lb0 = H_full; + } int neval = 1; report(neval, val, x_named, /*head=*/true); @@ -234,6 +560,13 @@ List trust_reflective(Function objfun, NumericVector parinit, bool accept = true, converged = false, bail = false; int n_iter = 0, n_fail = 0, n_stall = 0; std::string stop_reason = "iterlim"; + // The convergence stop held back by newton_small() since the last accepted step that changed the + // value by ftol or more. A run that then ends on the radius ends on that stop. + const char* vetoed = nullptr; + auto end_on_radius = [&]() { + if (vetoed != nullptr) { converged = true; stop_reason = vetoed; } + else stop_reason = "radius"; + }; // Zhang-Hager reference value for acceptance. nonmonotone = 0 holds zh_C at // f_used, which is the monotone rule. @@ -266,11 +599,13 @@ List trust_reflective(Function objfun, NumericVector parinit, // phase it ends. int phase_iter = 0; std::vector phase_iters(1, 0); + // Consecutive iterations of the running phase that left the radius unchanged. + int radius_same = 0; // "exact" is a Newton run: the objective's own Hessian at every iterate, the // way gn passes J^T J through, and the subproblem solver takes an indefinite // matrix natively. bool qn_active = (method != HM_GN && method != HM_EXACT); - int qn_kind = (method == HM_SR1) ? HM_SR1 : HM_BFGS; + int qn_kind = hm_structured(method) ? method : ((method == HM_SR1) ? HM_SR1 : HM_BFGS); int qn_neval = 0, qn_skipped = 0, n_switch = 0; // At a standing iterate a reseed refetches the same matrix. The allowance // kReseedLimit holds per phase, n_reseed counts over the run. @@ -281,6 +616,16 @@ List trust_reflective(Function objfun, NumericVector parinit, eval_src[hessian_source_slot(qn_active, qn_kind, method)] = 1; const double qn_sgn = minimize ? 1.0 : -1.0; std::vector s_qn(K), y_qn(K); + // The BFGS matrix of a phase seeded "tracked": the start Hessian made positive definite, updated + // with every accepted pair while no tracked phase runs, and taken over by such a phase. + int track_k = -1; + for (int k = 0; k < (int) phases.size() && track_k < 0; ++k) + if (phases[k].qn.init == HI_TRACKED) track_k = k; + std::vector H_track; + if constexpr (Model::dense) if (track_k >= 0) { + H_track = H_full.H; + bfgs_seed_definite(K, H_track, qn_sgn); + } // qnMemory = 0 accumulates onto the seed, otherwise rebuild from the window. std::deque> qn_S, qn_Y; double qn_gamma = 1.0; @@ -294,7 +639,7 @@ List trust_reflective(Function objfun, NumericVector parinit, auto reseed = [&]() { pending_level = (qp->init == HI_EXACT) ? CV_EXACT : CV_GN; n_reseed++; phase_reseed++; moved_since_reseed = false; - n_stall = 0; r = rinit; + n_stall = 0; r = rinit; radius_same = 0; qn_S.clear(); qn_Y.clear(); qn_gamma = 1.0; }; @@ -374,8 +719,24 @@ List trust_reflective(Function objfun, NumericVector parinit, }; List out_now; if (eval_objfun(objfun, x_now, out_now, level, cur)) { - if (level >= CV_GN) Model::read(out_now, K, H_full); + if (level >= CV_GN && Model::read(out_now, K, H_full)) { + if constexpr (Model::dense) + if (qn_active && qn_kind == HM_BFGS) bfgs_seed_definite(K, H_full.H, qn_sgn); + if constexpr (!Model::dense) + if (qn_active && qn_kind == HM_BFGS) { + sparse_seed_definite(K, H_full, qn_sgn); + H_lb0 = H_full; qn_S.clear(); qn_Y.clear(); + } + } + if (level >= CV_GN) { + Rows fresh; + if (read_rows(out_now, K, fresh)) { rows_cur = std::move(fresh); rows_seen = true; } + } if (refresh && !split) take(out_now); + // A structured phase starts from A = 0 at the fresh Gauss-Newton Hessian. + if constexpr (Model::dense) + if (qn_active && hm_structured(qn_kind)) + st.reset(K, H_full.H, qn_sgn, residual_norm(rows_cur, qn_sgn * val)); neval++; eval_src[hessian_source_slot(qn_active, qn_kind, method)]++; } @@ -396,8 +757,9 @@ List trust_reflective(Function objfun, NumericVector parinit, qn_dirty = false; refresh_current(); build_model(); - if (opt_measure <= gtol && newton_small()) { - converged = true; stop_reason = "gradient"; break; + if (opt_measure <= gtol) { + if (newton_small()) { converged = true; stop_reason = "gradient"; break; } + vetoed = "gradient"; } } @@ -407,6 +769,8 @@ List trust_reflective(Function objfun, NumericVector parinit, trace.valpath.push_back(val); } + const bool hyb_gn_now = st.gn_branch; + const double r_head = r; bool is_newton = false, is_hard = false, is_easy = false; model.solve(ghat.data(), r, shat.data(), &is_newton, &is_hard, &is_easy); @@ -437,7 +801,7 @@ List trust_reflective(Function objfun, NumericVector parinit, bool moved = false; for (int i = 0; i < K && !moved; ++i) moved = z_try[i] != z[i]; if (!moved && can_reseed()) { reseed(); continue; } - if (!moved) { stop_reason = "radius"; break; } + if (!moved) { end_on_radius(); break; } NumericVector x_try(K); x_try.names() = parnames; @@ -445,7 +809,8 @@ List trust_reflective(Function objfun, NumericVector parinit, // The quasi-Newton phase maintains a separate Hessian, so it asks the // objective not to build J^T J; only the gn pass-through reads it back. - const bool want_h = !qn_active; + const bool structured = qn_active && hm_structured(qn_kind); + const bool want_h = !qn_active || structured; List out_try; bool eval_ok = eval_objfun(objfun, x_try, out_try, want_h ? want_level : CV_GRADIENT, cur); @@ -460,6 +825,8 @@ List trust_reflective(Function objfun, NumericVector parinit, if (want_h && !Model::read(out_try, K, Htry)) eval_ok = false; if (!std::isfinite(val_try)) eval_ok = false; } + rows_try.n = -1; + if (eval_ok && want_h && read_rows(out_try, K, rows_try)) rows_seen = true; neval++; if (qn_active) qn_neval++; eval_src[hessian_source_slot(qn_active, qn_kind, method)]++; @@ -491,12 +858,14 @@ List trust_reflective(Function objfun, NumericVector parinit, // Count rejected steps that also left the objective flat. if (accept || !eval_ok || dval >= ftol) n_stall = 0; else n_stall++; + if (accept && eval_ok && dval >= ftol) vetoed = nullptr; // SR1 also takes the pair from a rejected trial point, where the curvature // along s is still valid (Nocedal and Wright, sec. 6.2). BFGS needs an // accepted step for the curvature condition. const bool qn_pair = qn_active && eval_ok && - (accept || (qp->rejected && qn_kind == HM_SR1)); + (accept || (qp->rejected && hm_sr1_type(qn_kind))); + const double rho_try = residual_norm(rows_try, ftry_used); // (s, y) in minimized sign, before z/grad_full are overwritten. if (qn_pair) @@ -505,6 +874,18 @@ List trust_reflective(Function objfun, NumericVector parinit, y_qn[i] = qn_sgn * (grad_try[i] - grad_full[i]); } + if constexpr (Model::dense) + if (track_k >= 0 && accept && eval_ok && !(qn_active && qp->init == HI_TRACKED)) { + std::vector s_tr(K), y_tr(K); + for (int i = 0; i < K; ++i) { + s_tr[i] = (z_try[i] - z[i]) / ps[i]; + y_tr[i] = qn_sgn * (grad_try[i] - grad_full[i]); + } + if (qn_pair_informative(K, s_tr, y_tr, phases[track_k].qn.cautious)) + qn_update(HM_BFGS, K, H_track, s_tr, y_tr, qn_sgn); + else qn_skipped++; + } + if (accept && eval_ok) { moved_since_reseed = true; z = z_try; @@ -516,7 +897,55 @@ List trust_reflective(Function objfun, NumericVector parinit, if (!qn_active) H_full = std::move(Htry); } - if constexpr (Model::dense) if (qn_pair) { + // The structured correction is updated with G+ of the trial point; an accepted step also + // moves G and rho, and the model is composed afresh. + if constexpr (Model::dense) if (structured && eval_ok && (qn_pair || accept)) { + std::vector Gp(Htry.H.size()); + for (std::size_t t = 0; t < Gp.size(); ++t) Gp[t] = qn_sgn * Htry.H[t]; + if (qn_pair) { + const int res = structured_update(qn_kind, *qp, K, st, s_qn, y_qn, Gp, rho_try, + rows_cur, rows_try, qn_sgn); + if (res == 0) qn_skipped++; + if (accept && hm_hybrid(qn_kind)) { + st.gn_branch = (res == 2); + if (st.gn_branch) n_hybrid_gn++; + } + } + if (accept) { st.G = std::move(Gp); st.rho = rho_try; } + st.compose(K, H_full.H, qn_sgn, qn_kind, qp->scaled, qp->hybrid_shift); + if (!accept) qn_dirty = true; + } + + // The data rows move with the iterate; a trial point without them leaves none. + if (accept && eval_ok) { rows_cur = std::move(rows_try); rows_try = Rows(); } + + // The pair is damped as in the dense update, against the model Hessian it updates, and kept so. + if constexpr (!Model::dense) if (qn_pair && !structured) { + std::vector Bs(K); + sparse_hess_apply(K, H_full, s_qn.data(), Bs.data()); + double sy = 0.0, sBs = 0.0; + for (int i = 0; i < K; ++i) { Bs[i] *= qn_sgn; sy += s_qn[i] * y_qn[i]; sBs += s_qn[i] * Bs[i]; } + const double th = (sy < 0.2 * sBs) ? 0.8 * sBs / (sBs - sy) : 1.0; + std::vector yd(K); + double syd = 0.0; + for (int i = 0; i < K; ++i) { yd[i] = th * y_qn[i] + (1.0 - th) * Bs[i]; syd += s_qn[i] * yd[i]; } + if (!qn_pair_informative(K, s_qn, y_qn, qp->cautious) || !(sBs > 0.0) || !(syd > 0.0)) { + qn_skipped++; + } else { + const int mem = qp->memory > 0 ? qp->memory : kSparseMemory; + qn_S.push_back(s_qn); + qn_Y.push_back(yd); + if ((int) qn_S.size() > mem) { qn_S.pop_front(); qn_Y.pop_front(); } + // a singular middle matrix drops the oldest pairs + while (!lbfgs_compose(K, H_lb0, qn_S, qn_Y, qn_sgn, parnames, H_full)) { + qn_S.pop_front(); qn_Y.pop_front(); + if (qn_S.empty()) { H_full = H_lb0; break; } + } + if (!accept) qn_dirty = true; + } + } + + if constexpr (Model::dense) if (qn_pair && !structured) { const bool keep = (qn_kind == HM_SR1) || qn_pair_informative(K, s_qn, y_qn, qp->cautious); if (!keep) { @@ -546,7 +975,8 @@ List trust_reflective(Function objfun, NumericVector parinit, trace.rho.push_back(rho); trace.steptype.push_back(subproblem_label(is_newton, is_hard, is_easy)); trace.stepback.push_back(sb_label); - trace.hsource.push_back( + // a hybrid phase on the Gauss-Newton branch reports "gn" + trace.hsource.push_back(qn_active && hm_hybrid(qn_kind) && hyb_gn_now ? "gn" : hessian_source_label(qn_active, qn_kind, method)); } n_iter = iter; @@ -570,11 +1000,11 @@ List trust_reflective(Function objfun, NumericVector parinit, } // "fvalue" and "preddiff" end the run only where the full Newton step predicts at most mtol; // a quasi-Newton phase drops them further down. - const bool ends_run = model_stop && n_switch >= switches && !qn_active; + const bool ends_run = model_stop && (n_switch >= switches || phases[cur].stop_ends) && !qn_active; if (ends_run && std::strcmp(soft_stop, "step") != 0) { refresh_current(); build_model(); - if (!newton_small()) { soft_stop = nullptr; model_stop = false; } + if (!newton_small()) { vetoed = soft_stop; soft_stop = nullptr; model_stop = false; } } if (soft_stop == nullptr && r >= rmin && n_stall >= kStallLimit) soft_stop = "stagnation"; @@ -591,12 +1021,21 @@ List trust_reflective(Function objfun, NumericVector parinit, soft_stop = "iterlim"; budget_out = true; } - - // A soft stop hands over to the next phase and restarts the trust region. - // A quasi-Newton phase seeded "gn" starts from the last accepted J^T J, - // which is why H_full is not reset for it. - if (soft_stop != nullptr && n_switch < switches) { + // A radius unchanged for radius_stall iterations hands over; with no handover left it is no stop. + radius_same = (r == r_head) ? radius_same + 1 : 0; + if (soft_stop == nullptr && phases[cur].radius_stall > 0 && + radius_same >= phases[cur].radius_stall && n_switch < switches) + soft_stop = "radiusStall"; + + // A soft stop hands over to the next phase and restarts the trust region, unless the phase + // ends the run on a stop. A quasi-Newton phase seeded "gn" starts from the last accepted + // J^T J, which is why H_full is not reset for it. + const bool by_stop = soft_stop != nullptr && std::strcmp(soft_stop, "iterlim") != 0 && + std::strcmp(soft_stop, "radiusStall") != 0; + if (soft_stop != nullptr && n_switch < switches && !(by_stop && phases[cur].stop_ends)) { + if constexpr (Model::dense) if (qn_active && qp->init == HI_TRACKED) H_track = H_full.H; const bool was_qn = qn_active; + const int prev_method = method; const int next = (cur + 1) % n_phases; const bool refreshOnSwitch = phases[next].reverse != phases[cur].reverse; cur = next; @@ -604,11 +1043,30 @@ List trust_reflective(Function objfun, NumericVector parinit, method = phases[cur].method; want_level = (method == HM_EXACT) ? CV_EXACT : CV_GN; qn_active = (method != HM_GN && method != HM_EXACT); - if (qn_active) { + if (qn_active && hm_structured(method)) { + // From a gn phase, H_full is the Gauss-Newton Hessian at the iterate; otherwise it is + // fetched, with value and gradient where the sweep changes. + qn_kind = method; + if constexpr (Model::dense) { + st.reset(K, H_full.H, qn_sgn, residual_norm(rows_cur, qn_sgn * val)); + if (prev_method != HM_GN || (rows_seen && !rows_cur.ok())) pending_level = CV_GN; + else if (refreshOnSwitch) pending_level = CV_GRADIENT; + } + qn_dirty = true; + } else if (qn_active) { qn_kind = (method == HM_SR1) ? HM_SR1 : HM_BFGS; - if (qp->init == HI_IDENTITY) { + if (qp->init == HI_TRACKED) { + if constexpr (Model::dense) H_full.H = H_track; + qn_dirty = true; + } else if (qp->init == HI_IDENTITY) { Model::identity(K, qn_sgn, H_full); qn_dirty = true; + } else if constexpr (Model::dense) { + if (qn_kind == HM_BFGS) { bfgs_seed_definite(K, H_full.H, qn_sgn); qn_dirty = true; } + } else { + sparse_seed_definite(K, H_full, qn_sgn); + H_lb0 = H_full; + qn_dirty = true; } if (qp->init == HI_EXACT) pending_level = CV_EXACT; else if (qp->init == HI_GN && was_qn) pending_level = CV_GN; @@ -617,9 +1075,10 @@ List trust_reflective(Function objfun, NumericVector parinit, pending_level = want_level; } pending_refresh = refreshOnSwitch; - phase_iter = 0; phase_reseed = 0; + phase_iter = 0; phase_reseed = 0; radius_same = 0; phase_iters.push_back(0); - n_switch++; n_stall = 0; r = rinit; + n_switch++; n_stall = 0; + if (!phases[cur].keep_radius) r = rinit; qn_S.clear(); qn_Y.clear(); qn_gamma = 1.0; soft_stop = nullptr; budget_out = false; @@ -629,9 +1088,17 @@ List trust_reflective(Function objfun, NumericVector parinit, // ends on the gradient; stagnation reads accepted steps and still applies. if (soft_stop != nullptr && qn_active && model_stop) soft_stop = nullptr; if (soft_stop != nullptr) { - converged = !budget_out; stop_reason = soft_stop; break; + converged = !budget_out; stop_reason = soft_stop; + // Stagnation is convergence only where the model predicts no decrease above mtol, or a + // convergence stop was held back since the last step that changed the value by ftol. + if (converged && std::strcmp(soft_stop, "stagnation") == 0 && vetoed == nullptr) { + refresh_current(); + build_model(); + converged = newton_small(); + } + break; } - if (r < rmin) { stop_reason = "radius"; break; } + if (r < rmin) { end_on_radius(); break; } } // fvalue, preddiff, step and the iteration limit end the run right after an @@ -676,6 +1143,7 @@ List trust_reflective(Function objfun, NumericVector parinit, Named("qnSkipped") = qn_skipped, Named("nSwitch") = n_switch, Named("nReseed") = n_reseed, + Named("hybridGN") = n_hybrid_gn, Named("phaseIterations") = IntegerVector(phase_iters.begin(), phase_iters.end()), Named("evalBySource") = eval_by_source, Named("converged") = converged, @@ -949,12 +1417,18 @@ List trust_impl(Function objfun, std::string boundary, CharacterVector phaseMethod, IntegerVector phaseIterlim, + IntegerVector phaseRadiusStall, LogicalVector phaseReverse, + LogicalVector phaseKeepRadius, + LogicalVector phaseStopEnds, CharacterVector phaseInit, CharacterVector phaseReseed, IntegerVector phaseMemory, NumericVector phaseCautious, LogicalVector phaseRejected, + LogicalVector phaseScaled, + NumericVector phaseHybridTol, + LogicalVector phaseHybridShift, int switches = 0, double nonmonotone = 0.0, bool sparse = false, @@ -974,10 +1448,12 @@ List trust_impl(Function objfun, const int P = phaseMethod.size(); if (P < 1) stop("trust: at least one phase is needed"); - if (phaseIterlim.size() != P || phaseReverse.size() != P || + if (phaseIterlim.size() != P || phaseRadiusStall.size() != P || phaseReverse.size() != P || + phaseKeepRadius.size() != P || phaseStopEnds.size() != P || phaseInit.size() != P || phaseReseed.size() != P || phaseMemory.size() != P || phaseCautious.size() != P || - phaseRejected.size() != P) + phaseRejected.size() != P || phaseScaled.size() != P || + phaseHybridTol.size() != P || phaseHybridShift.size() != P) stop("trust: the phase settings differ in length"); if (switches < 0) stop("trust: switches must be >= 0"); @@ -989,12 +1465,21 @@ List trust_impl(Function objfun, else if (m == "bfgs") ph.method = HM_BFGS; else if (m == "sr1") ph.method = HM_SR1; else if (m == "exact") ph.method = HM_EXACT; + else if (m == "sbfgs") ph.method = HM_SBFGS; + else if (m == "ssr1") ph.method = HM_SSR1; + else if (m == "gnsbfgs") ph.method = HM_GNSBFGS; + else if (m == "gnssr1") ph.method = HM_GNSSR1; else stop("trust: hessianMethod must be one of \"gn\", \"bfgs\", \"sr1\", " - "\"exact\""); + "\"exact\", \"sbfgs\", \"ssr1\", \"gnsbfgs\", \"gnssr1\""); // NA: no phase budget, only the total iterlim. ph.iterlim = (phaseIterlim[k] == NA_INTEGER) ? INT_MAX : phaseIterlim[k]; if (ph.iterlim < 1) stop("trust: the iterlim of a phase must be >= 1"); + // NA: no handover on the radius. + ph.radius_stall = (phaseRadiusStall[k] == NA_INTEGER) ? 0 : phaseRadiusStall[k]; + if (ph.radius_stall < 0) stop("trust: the radiusStall of a phase must be >= 1"); ph.reverse = phaseReverse[k] == TRUE; + ph.keep_radius = phaseKeepRadius[k] == TRUE; + ph.stop_ends = phaseStopEnds[k] == TRUE; QnParams& q = ph.qn; const std::string init = as(phaseInit[k]); @@ -1002,25 +1487,36 @@ List trust_impl(Function objfun, if (init == "gn") q.init = HI_GN; else if (init == "identity") q.init = HI_IDENTITY; else if (init == "exact") q.init = HI_EXACT; + else if (init == "tracked") q.init = HI_TRACKED; else stop("trust: hessianInit must be one of \"gn\", \"identity\", " - "\"exact\""); + "\"exact\", \"tracked\""); if (reseed == "never") q.reseed = HR_NEVER; else if (reseed == "stall") q.reseed = HR_STALL; else stop("trust: hessianReseed must be one of \"never\", \"stall\""); q.memory = phaseMemory[k]; q.cautious = phaseCautious[k]; q.rejected = phaseRejected[k] == TRUE; + q.scaled = phaseScaled[k] == TRUE; + q.hybrid_tol = phaseHybridTol[k]; + q.hybrid_shift = phaseHybridShift[k] == TRUE; if (q.memory < 0) stop("trust: qnMemory must be >= 0"); + if (!(q.hybrid_tol > 0.0)) stop("trust: qnHybridTol must be > 0"); + if (hm_structured(ph.method) && (q.memory != 0 || q.init != HI_GN)) + stop("trust: a structured hessianMethod starts from the Gauss-Newton Hessian and keeps " + "no pairs; it takes qnControl$hessianInit = \"gn\" and qnMemory = 0"); if (q.cautious < 0.0) stop("trust: qnCautious must be >= 0"); + if (q.init == HI_TRACKED && (k == 0 || ph.method != HM_BFGS || q.memory != 0 || sparse)) + stop("trust: hessianInit = \"tracked\" takes a \"bfgs\" phase after the first, with " + "qnMemory = 0, on the dense path"); } if (!(nonmonotone >= 0.0 && nonmonotone < 1.0)) stop("trust: nonmonotone must be in [0, 1)"); if (sparse) for (const Phase& ph : phases) - if (ph.method != HM_GN && ph.method != HM_EXACT) - stop("trust(sparse = TRUE): the Hessian comes from the objective, \"gn\" or \"exact\"; " - "quasi-Newton phases are dense"); + if (ph.method != HM_GN && ph.method != HM_EXACT && !(ph.method == HM_BFGS && ph.qn.init == HI_GN)) + stop("trust(sparse = TRUE): the Hessian comes from the objective, \"gn\" or \"exact\", or " + "from limited-memory BFGS on it, \"bfgs\" with hessianInit = \"gn\""); if (boundary == "clip") { if (sparse) stop("trust(sparse = TRUE) takes boundary = \"reflective\""); if (P != 1 || phases[0].method != HM_GN || switches > 0) diff --git a/src/units_kernel.cpp b/src/units_kernel.cpp index 9522de1b..96fc9fed 100644 --- a/src/units_kernel.cpp +++ b/src/units_kernel.cpp @@ -71,7 +71,8 @@ bool newtonStep(const Unit& u, std::vector& s) { // `data_cb(idx, etas)`: per component idx (1-based) at the component etas, list(value, gradient, hessian) of the // data terms in the order of the etas, NULL where the prediction fails. `warm` holds the etas the // search starts from, `P` the prior precisions, `control` rinit, rmax, iterlim, steptol and mtol. -// Returns the etas at the modes per component. +// Returns the etas at the modes per component, with the evaluated steps per component in attribute +// "iterations". // [[Rcpp::export]] List focei_units_lockstep(Function data_cb, List warm, List P, List control) { const int U = warm.size(); @@ -105,6 +106,7 @@ List focei_units_lockstep(Function data_cb, List warm, List P, List control) { for (const Unit& u : cur) if (!u.ok) stop("FOCEI: the prediction fails at the modes the inner search starts from."); std::vector r(U, rinit); + IntegerVector iterations(U); for (int it = 1; it <= iterlim && !active.empty(); ++it) { std::vector moving; @@ -146,6 +148,7 @@ List focei_units_lockstep(Function data_cb, List warm, List P, List control) { } active = moving; if (active.empty()) break; + for (int i : active) ++iterations[i]; std::vector trial = evaluate(active, trials); for (std::size_t j = 0; j < active.size(); ++j) { const int i = active[j]; @@ -172,5 +175,6 @@ List focei_units_lockstep(Function data_cb, List warm, List P, List control) { } List out(U); for (int i = 0; i < U; ++i) out[i] = NumericVector(w[i].begin(), w[i].end()); + out.attr("iterations") = iterations; return out; } diff --git a/tests/testthat/_snaps/statsOutput.md b/tests/testthat/_snaps/statsOutput.md index b4186760..224b2743 100644 --- a/tests/testthat/_snaps/statsOutput.md +++ b/tests/testthat/_snaps/statsOutput.md @@ -122,6 +122,6 @@ Code ss Output - k1 A B - "B*k2/A" "A" "B" + B A + "A*k1/k2" "A" diff --git a/tests/testthat/test-EM.R b/tests/testthat/test-EM.R index db02caf5..d7caadf9 100644 --- a/tests/testthat/test-EM.R +++ b/tests/testthat/test-EM.R @@ -655,6 +655,22 @@ test_that("the lock-step search of the modes stops on the Newton step, not on a expect_lt(max(abs(step)), 1e-8) }) +test_that("FOCEI over several groupings on inexact modes ends at the nested optimum", { + m <- .crossed() + re <- randomEffects(m$pn) + init <- c(a = 0.5, s = log(0.3)) + for (sp in c(FALSE, TRUE)) { + nested <- em(m$objn, re, init, verbose = FALSE, sparse = sp) + sqp <- em(m$objn, re, init, verbose = FALSE, sparse = sp, control = list(inner = "sqp")) + expect_true(sqp$converged) + expect_equal(sqp$value, nested$value, tolerance = 1e-6) + expect_lt(max(abs(sqp$argument - nested$argument[names(sqp$argument)])), 1e-3) + expect_equal(sqp$eta, nested$eta, tolerance = 1e-3) + expect_true(is.integer(sqp$innerIterations) && sqp$innerIterations > 0L) + expect_true(sqp$sqpIterations >= 1L && sqp$sqpIterations <= sqp$iterations) + } +}) + test_that("one grouping through the component path equals the kernel path", { m <- .lin() fit <- em(m$obj, randomEffects(m$p), c(a = 0.5, b = 0.2), verbose = FALSE) @@ -667,6 +683,26 @@ test_that("one grouping through the component path equals the kernel path", { expect_equal(unname(at$hessian), unname(fit$hessian), tolerance = 1e-6) }) +test_that("the outer search over several groupings takes the arguments of trust(), others are an error", { + m <- .crossed() + re <- randomEffects(m$p) + ph <- list(list(hessianMethod = "gn", iterlim = 1), list(hessianMethod = "bfgs")) + tight <- list(mtol = 1e-10, ftol = 1e-12) + gn <- em(m$obj, re, c(a = 0.5), verbose = FALSE, sparse = FALSE, control = list(trustControl = tight)) + for (sp in c(FALSE, TRUE)) { + fit <- em(m$obj, re, c(a = 0.5), verbose = FALSE, sparse = sp, + control = list(trustControl = c(tight, list(phases = ph)))) + expect_identical(names(fit$phaseIterations), c("gn", "bfgs")) + expect_identical(fit$phaseIterations[["gn"]], 1L) + expect_equal(fit$value, gn$value, tolerance = 1e-6) + } + expect_error(em(m$obj, re, c(a = 0.5), verbose = FALSE, control = list(trustControl = list(nope = 1))), + "unknown entries nope") + l <- .lin() + expect_error(em(l$obj, randomEffects(l$p), c(a = 0.5, b = 0.2), verbose = FALSE, + control = list(trustControl = list(phases = ph))), "several groupings only") +}) + test_that("sparse FOCEI equals the dense fit, for one grouping and for crossed groupings", { m <- .lin() re <- randomEffects(m$p) diff --git a/tests/testthat/test-EMsparse.R b/tests/testthat/test-EMsparse.R index 4d84e250..792e8485 100644 --- a/tests/testthat/test-EMsparse.R +++ b/tests/testthat/test-EMsparse.R @@ -116,7 +116,8 @@ # The marginal of `p` at `theta` with every slab probability or concentration `share` and slab # standard deviation `tau`; the decay data unless `obj` is given. .marginalAt <- function(p, theta, share = NA, tau = NA, grad = TRUE, obj = NULL, - scores = FALSE, derivMode = NULL, reach = TRUE) { + scores = FALSE, derivMode = NULL, reach = TRUE, tolControl = NULL, + warm = NULL, iterlim = 300L) { m <- .sparse() obj <- obj %||% normL2(m$data, m$g * Xt() * p, errmodel = m$err) d <- dMod2:::.emDesign(obj, randomEffects(p)) @@ -125,10 +126,11 @@ hyp <- lapply(list(prob = share, concentration = share, tau = tau), function(v) setNames(rep(v, nrow(lay)), lay$stem)) prior <- if (d$normal$K) dMod2:::.normalPrior(d) - warm <- matrix(0, length(d$groups), ncol(d$etaNames)) + warm <- warm %||% matrix(0, length(d$groups), ncol(d$etaNames)) dMod2:::.sparseMarginal(d, dMod2:::.conditionObjectives(d), prior, theta, hyp, names(theta), dMod2:::.sparseHypers(lay), NULL, warm, grad = grad, - control = list(iterlim = 300, derivMode = derivMode), scores = scores) + control = list(iterlim = iterlim, derivMode = derivMode, + trustControl = list(tolControl = tolControl)), scores = scores) } # The slope of a marginal: the inner iterations leave noise of about 1e-10 in the value, so the @@ -145,7 +147,8 @@ test_that("the marginal alone needs no second-order sensitivities under forward real(...) }, .package = "dMod2") alone <- .marginalAt(m$ps, theta, 0.4, 0.5, grad = FALSE, derivMode = "forward-reverse") - expect_equal(alone$value, full$value, tolerance = 1e-10) + # the value alone lacks the first-order correction for the modes, which needs the exact inner Hessian + expect_equal(alone$value, full$value, tolerance = 1e-8) }) test_that("forward over reverse gives the gradient and the model Hessian rows of forward over forward", { @@ -358,11 +361,33 @@ test_that("the group scores of a sparse marginal sum to the gradient, each the g } }) -test_that("em refuses entries of control$sparseFit it does not read", { +test_that("em refuses entries of control$sparseFit, $quadrature, $saem and $innerControl it does not read", { m <- .sparse() obj <- normL2(m$data, m$g * Xt() * m$ps, errmodel = m$err) expect_error(em(obj, randomEffects(m$ps), m$init, control = list(sparseFit = list(coupling = "meanField"))), - "unknown") + "unknown entries of `control\\$sparseFit`: coupling") + expect_error(em(obj, randomEffects(m$ps), m$init, control = list(quadrature = list(level = 3))), + "unknown entries of `control\\$quadrature`: level") + expect_error(em(obj, randomEffects(m$ps), m$init, control = list(saem = list(nIter = 3))), + "unknown entries of `control\\$saem`: nIter") + expect_error(em(obj, randomEffects(m$ps), m$init, control = list(innerControl = list(ftol = 1e-8))), + "unknown entries of `control\\$innerControl`: ftol") + expect_error(em(obj, randomEffects(m$ps), m$init, control = list(sparseFit = list(trustControl = list(nope = 1)))), + "unknown entries nope") +}) + +test_that("the joint trust region of sparse random effects runs the phases of trust()", { + m <- .sparse() + obj <- normL2(m$data, m$g * Xt() * m$ps, errmodel = m$err) + ph <- list(list(hessianMethod = "gn", iterlim = 2), list(hessianMethod = "bfgs")) + fit <- em(obj, randomEffects(m$ps), m$init, verbose = FALSE, + control = list(sparseFit = list(trustControl = list(phases = ph)))) + expect_true(is.finite(fit$value)) + expect_lt(max(abs(.freeGradient(fit))), 0.05) + expect_warning(em(obj, randomEffects(m$ps), m$init, verbose = FALSE, + control = list(sparseFit = list(maxOuter = 1L, trustControl = list( + phases = list(list(hessianMethod = "gn"), list(hessianMethod = "nope")))))), + "trust region stopped") }) test_that("an eta that reaches no data of the group rests at the prior, with the marginal and gradient unchanged", { @@ -653,6 +678,23 @@ test_that("the spike-and-slab and cluster marginals have the exact gradient, nor } }) +test_that("the marginal is that at the exact modes to first order, whatever the outer tolerances", { + m <- .sparse() + theta <- m$init + c(0.05, -0.02, 0.1) + for (p in list(m$ps, m$psm)) { + th <- if (any(randomEffects(p)$terms$dist == "normal")) c(theta, omega_A_A = log(0.2)) else theta + exact <- .marginalAt(p, th, share = 0.4, tau = 0.5) + loose <- .marginalAt(p, th, share = 0.4, tau = 0.5, tolControl = list(ftol = 1e-4, mtol = 1e-4, gtol = 1e-2)) + expect_equal(loose$value, exact$value, tolerance = 1e-9) + expect_equal(loose$gradient, exact$gradient, tolerance = 1e-6) + # modes moved off and held there: the value is off at second order in the shift only + off <- vapply(c(2e-3, 1e-3), function(h) + abs(suppressWarnings(.marginalAt(p, th, share = 0.4, tau = 0.5, warm = exact$modes + h, iterlim = 0L))$value - + exact$value), 0) + expect_gt(off[1] / off[2], 3.5) + } +}) + test_that("the curvature of the hyperparameters is that of the complete-data prior, the secant the M-step", { lay <- data.frame(stem = c("b", "c"), probName = c("prob_ID", NA), concentrationName = c(NA, "concentration_ID"), tauName = c("tau_ID", "tau_ID_2"), stringsAsFactors = FALSE) @@ -763,3 +805,46 @@ test_that("spike-and-slab fits select the groups that differ and estimate the th expect_true(all(A$mode == 0)) expect_true(all(A$p0 > 0.5)) }) + +test_that("spike-and-slab and Dirichlet-process fits on inexact modes end at the nested optimum", { + m <- .sparse() + objOf <- function(p) normL2(m$data, m$g * Xt() * p, errmodel = m$err) + for (p in list(m$ps, m$psk, m$psm)) { + init <- if (any(randomEffects(p)$terms$dist == "normal")) c(m$init, omega_A_A = log(0.2)) else m$init + nested <- em(objOf(p), randomEffects(p), init, verbose = FALSE) + sqp <- em(objOf(p), randomEffects(p), init, verbose = FALSE, control = list(inner = "sqp")) + expect_true(sqp$converged) + expect_equal(sqp$value, nested$value, tolerance = 1e-6) + expect_lt(max(abs(sqp$argument - nested$argument[names(sqp$argument)])), 1e-3) + expect_equal(sqp$etaModes, nested$etaModes, tolerance = 1e-3) + expect_true(is.integer(sqp$innerIterations) && sqp$innerIterations > 0L) + expect_true(sqp$sqpIterations >= 1L && sqp$sqpIterations <= sqp$iterations) + expect_true(nested$innerIterations > 0L) + } +}) + +test_that("NPDE and the random-effect plots of a fit with spike-and-slab random effects alone", { + m <- .sparse() + fit <- em(normL2(m$data, m$g * Xt() * m$ps, errmodel = m$err), randomEffects(m$ps), m$init, verbose = FALSE) + npde <- residuals(fit, type = "NPDE", nsim = 100, seed = 1) + expect_length(npde, sum(vapply(m$data, nrow, 0L))) + expect_true(all(is.finite(npde))) + set.seed(1) + expect_s3_class(plotRandomEffects(fit), "ggplot") + d <- plotRandomEffects(fit, type = "inclusion")$data + expect_equal(d$inclusion, 1 - fit$random$p0) + expect_true(all(c("prob_ID", "tau_ID") %in% levels(plotTrace(fit)$data$panel))) +}) + +test_that("importance sampling on the model agrees with the marginal where the approximation is exact", { + m <- .sparse() + withr::local_seed(1) + fit <- em(normL2(m$linear, m$gl * Xt() * m$pls), randomEffects(m$pls), c(a = 1, b = 0.5, omega_a_a = log(0.5)), + verbose = FALSE) + l <- logLik(fit, "importance", draws = 2000L) + expect_equal(attr(l, "approximation"), as.numeric(logLik(fit)), tolerance = 1e-6) + expect_lt(abs(as.numeric(l) - as.numeric(logLik(fit))), 4 * attr(l, "se")) + expect_true(all(attr(l, "ess") > 200)) + fit$design <- NULL + expect_error(logLik(fit, "importance"), "no design") +}) diff --git a/tests/testthat/test-Pimpl.R b/tests/testthat/test-Pimpl.R index 96c44d97..15b4b31a 100644 --- a/tests/testthat/test-Pimpl.R +++ b/tests/testthat/test-Pimpl.R @@ -157,11 +157,15 @@ pp_models <- function() { flow = TRUE, modelname = mn("bruss_s"), deriv2 = TRUE, verbose = FALSE) bruss_c <- P(list(C1 = c(a = "exp(la)", b = "exp(lb)", s = "1"), C2 = c(a = "exp(la)", b = "exp(lb)", s = "2")), modelname = mn("bruss_c")) + # two states in a chain whose rates can coincide, a defective double eigenvalue, beside a fast mode + chain <- Pimpl(c(x = "k0 - k1 * x", y = "k1 * x - k2 * y + c * z", z = "kf0 - kf * z + d * y"), + parameters = c("k0", "k1", "k2", "kf0", "kf", "c", "d"), modelname = mn("chain"), + deriv2 = TRUE, verbose = FALSE) compile(lin, d2, d2_2, d2_cq, moiety2_im, dimer_im, recycle, sing, noroot, noparam, erk_im, px, px_same, zero, pd, pd2, plasmid, bistable, unstable, kink, catalyst, vol, rest, rest_ode, rest_obs, rest_p0, rest_p1, bruss, bruss_p, - bruss_s, bruss_c, trans, output = mn("impl"), cores = test_cores()) + bruss_s, bruss_c, trans, chain, output = mn("impl"), cores = test_cores()) .pp_env$models <- list( lin = lin, d2 = d2, d2_2 = d2_2, d2_cq = d2_cq, moiety2_im = moiety2_im, @@ -170,7 +174,8 @@ pp_models <- function() { zero = zero, pd = pd, pd2 = pd2, plasmid = plasmid, bistable = bistable, unstable = unstable, kink = kink, catalyst = catalyst, vol = vol, rest = rest, rest_ode = rest_ode, rest_obs = rest_obs, rest_p0 = rest_p0, rest_p1 = rest_p1, - bruss = bruss, bruss_p = bruss_p, bruss_s = bruss_s, bruss_c = bruss_c, trans = trans) + bruss = bruss, bruss_p = bruss_p, bruss_s = bruss_s, bruss_c = bruss_c, trans = trans, + chain = chain) } @@ -942,6 +947,32 @@ test_that("the spectrum of a steady state has the exact gradients of the eigenva expect_equal(unname(sp$scaleGrad[c("a", "b")]), c(1, 0), tolerance = 1e-10) }) +test_that("coinciding eigenvalues have the exact gradient of their sum", { + skip_if_no_compile() + m <- pp_models() + spec <- attr(attr(m$chain, "mappings")[[1]], "spectrum") + # a double eigenvalue with one eigenvector: each takes the mean of the derivatives + pars <- c(k0 = 2, k1 = 1.3, k2 = 1.3, kf0 = 1, kf = 10, c = 0, d = 0) + sp <- spec(pars, onset = -Inf) + slow <- which(abs(sp$re + 1.3) < 1e-8) + expect_length(slow, 2L) + expect_equal(unname(sp$grad[slow, c("k1", "k2", "kf")]), rbind(c(-0.5, -0.5, 0), c(-0.5, -0.5, 0)), + tolerance = 1e-10) + # the term on a ramp that holds both, smooth in the rates + w <- 10 + stab <- constraintStability(m$chain, weight = w, margin = 0.2) + r <- 1 - 1.3 / (0.2 * 10) + out <- stab(pars) + expect_equal(out$value, 2 * w * r^3, tolerance = 1e-8) + expect_equal(out$gradient[c("k1", "k2", "kf")], c(k1 = -3 * w * r^2 / 2, k2 = -3 * w * r^2 / 2, + kf = 2 * 3 * w * r^2 * 1.3 / (0.2 * 100)), tolerance = 1e-8) + # with feedback through the fast mode the pair splits; the gradient is that of the value + for (q in list(pars, replace(pars, c("c", "d"), c(0.5, 0.3)))) { + num <- numDeriv::grad(function(v) stab(setNames(v, names(q)))$value, unname(q)) + expect_equal(unname(stab(q)$gradient[names(q)]), num, tolerance = 1e-7) + } +}) + test_that("the rate scale has the exact gradient, also where a volume moves the manifold", { skip_if_no_compile() pv <- pp_models()$vol @@ -971,7 +1002,7 @@ test_that("constraintStability is zero on stable steady states and rises at the skip_if_no_compile() m <- pp_models() w <- 10 - stab <- constraintStability(m$bruss, m$bruss_p, weight = w) + stab <- constraintStability(m$bruss, m$bruss_p, weight = w, margin = 1e-6) expect_setequal(attr(stab, "parameters"), c("la", "lb")) # the term of the complex pair from the closed-form eigenvalues and rate scale exact <- function(la, lb) { @@ -1025,16 +1056,28 @@ test_that("constraintStability is zero on stable steady states and rises at the # beyond the boundary the unstable steady state, on which the term rises expect_equal(as.numeric(m$bruss(c(a = 1, b = 2.5))[[1]][c("x", "y")]), c(1, 2.5), tolerance = 1e-8) # without p on the inputs of the steady state, the same value - expect_equal(constraintStability(m$bruss, weight = w)(c(a = 1, b = 2 + 1e-6))$value, + expect_equal(constraintStability(m$bruss, weight = w, margin = 1e-6)(c(a = 1, b = 2 + 1e-6))$value, stab(c(la = 0, lb = log(2 + 1e-6)))$value, tolerance = 1e-3) expect_error(constraintStability(m$bruss, m$bruss_p, weight = 0), "weight") + expect_error(constraintStability(m$bruss, m$bruss_p, margin = 0), "margin") + expect_error(constraintStability(m$bruss, m$bruss_p, width = -1), "width") + # an absolute width beyond margin * s: a ramp that does not move with the scale + wide <- constraintStability(m$bruss, m$bruss_p, weight = w, width = 0.05) + for (re in c(-0.06, -0.03, -0.01, 0.02)) { + pars <- c(la = 0, lb = log(2 + 2 * re)) + ref <- .stabilityExact(re, c(-1, 1 + re), 1, c(0, 0), w, margin = 0.05) + out <- wide(pars) + expect_equal(out$value, 2 * ref$value, tolerance = 1e-6) + expect_equal(unname(out$gradient), 2 * ref$gradient, tolerance = 1e-6) + expect_equal(unname(out$hessian), 2 * ref$hessian, tolerance = 1e-6) + } }) test_that("constraintStability follows a real eigenvalue through 0 smoothly", { skip_if_no_compile() m <- pp_models() w <- 10 - stab <- constraintStability(m$trans, weight = w) + stab <- constraintStability(m$trans, weight = w, margin = 1e-6) # a start that leads to the root whose eigenvalue crosses 0 pars <- function(re) c(q = -re, x = -sign(re), y = 1) at <- function(re) { @@ -1058,16 +1101,16 @@ test_that("constraintStability follows a real eigenvalue through 0 smoothly", { expect_equal(g, numDeriv::grad(function(z) stab(c(q = z, x = -sign(re), y = 1))$value, -re), tolerance = 1e-6) } - old <- controls(m$trans, name = "controlsPTC") - on.exit(controls(m$trans, name = "controlsPTC") <- old, add = TRUE) - # stabilityMargin sets the width of the ramp - controls(m$trans, name = "controlsPTC") <- c(old, list(stabilityMargin = 0.1)) + # margin sets the width of the ramp relative to the scale + wide <- constraintStability(m$trans, weight = w, margin = 0.1) for (re in c(-0.2, -0.05, 0.05)) { - o <- stab(pars(re)) + o <- wide(pars(re)) expect_equal(o$value, .stabilityExact(re, -1, 1, 0, w, margin = 0.1)$value, tolerance = 1e-8) - expect_equal(o$gradient[["q"]], numDeriv::grad(function(z) stab(c(q = z, x = -sign(re), y = 1))$value, -re), + expect_equal(o$gradient[["q"]], numDeriv::grad(function(z) wide(c(q = z, x = -sign(re), y = 1))$value, -re), tolerance = 1e-6) } + old <- controls(m$trans, name = "controlsPTC") + on.exit(controls(m$trans, name = "controlsPTC") <- old, add = TRUE) # an absolute stabilityTol moves the ramp controls(m$trans, name = "controlsPTC") <- list(stabilityTol = 0.5, positive = FALSE) for (re in c(0.2, 0.5 - 5e-7, 0.7)) { @@ -1076,15 +1119,14 @@ test_that("constraintStability follows a real eigenvalue through 0 smoothly", { } expect_equal(stab(pars(0.7))$gradient[["q"]], numDeriv::grad(function(z) stab(c(q = z, x = -1, y = 1))$value, -0.7), tolerance = 1e-6) - expect_error(controls(m$trans, name = "controlsPTC") <- list(stabilityMargin = 0), "stabilityMargin") }) test_that("constraintStability counts a steady state once over conditions that differ elsewhere", { skip_if_no_compile() m <- pp_models() pars <- c(la = 0, lb = log(2 - 1e-6)) - one <- constraintStability(m$bruss, m$bruss_p, weight = 10)(pars) - two <- constraintStability(m$bruss_s, m$bruss_c, weight = 10)(pars) + one <- constraintStability(m$bruss, m$bruss_p, weight = 10, margin = 1e-6)(pars) + two <- constraintStability(m$bruss_s, m$bruss_c, weight = 10, margin = 1e-6)(pars) expect_gt(one$value, 0) expect_equal(two$value, one$value, tolerance = 1e-3) expect_equal(two$gradient, one$gradient, tolerance = 1e-3) diff --git a/tests/testthat/test-alignment.R b/tests/testthat/test-alignment.R index 6c426c1d..1c46a08b 100644 --- a/tests/testthat/test-alignment.R +++ b/tests/testthat/test-alignment.R @@ -292,7 +292,7 @@ test_that("a random background per gel fits through EM, censored readings by M3" expect_true(all(is.na(fit$aligned$lloq[fit$aligned$time != "0"]))) # FOCEI on the sparse Hessian: the same marginal, gradient and Hessian, and standard errors # beside the optimum, where the gradient is not of the size of the convergence of the modes - ctl <- list(trustControl = list(iterlim = 0), innerControl = list(ftol = 1e-12, mtol = 1e-12, iterlim = 200)) + ctl <- list(trustControl = list(iterlim = 0), innerControl = list(mtol = 1e-12, iterlim = 200)) point <- fit$fit$argument + 0.05 at <- function(sparse) em(fit$objfn, fit$randomEffects, point, fixed = fit$fit$fixed, control = ctl, verbose = FALSE, sparse = sparse) @@ -430,7 +430,7 @@ test_that("censored readings without random terms have the exact Hessian of M3", .foceiAt <- function(fit, p, iterlim = 0) { ctrl <- list(trustControl = list(iterlim = iterlim), - innerControl = list(ftol = 1e-12, mtol = 1e-12, iterlim = 200)) + innerControl = list(mtol = 1e-12, iterlim = 200)) em(fit$objfn, fit$randomEffects, p, method = "focei", verbose = FALSE, control = ctrl) } @@ -731,7 +731,7 @@ test_that("the restricted likelihood through FOCEI: sigma near the drawn noise, expect_equal(term(point)$value, ee(V) - sum(vapply(V[-seq_along(mean)], ee, 0)) - length(mean) * log(4 * pi), tolerance = 1e-10) expect_equal(unname(term(point)$gradient[setdiff(names(point), theta)]), rep(0, length(mean))) - ctl <- list(trustControl = list(iterlim = 0), innerControl = list(ftol = 1e-12, mtol = 1e-12, iterlim = 200)) + ctl <- list(trustControl = list(iterlim = 0), innerControl = list(mtol = 1e-12, iterlim = 200)) at <- function(p, sparse = FALSE) suppressMessages(em(re$objfn + term, re$randomEffects, p, control = ctl, verbose = FALSE, sparse = sparse)) r0 <- at(point) @@ -811,7 +811,7 @@ test_that("a fit reports the modes at the fit parameters, a positive definite He prior = constraintL2(mu = c(omega_bj_bj = log(0.3), b = -2), sigma = c(omega_bj_bj = 0.3, b = 1))) fit <- suppressMessages(align(m, fits = 1, reml = FALSE)) # the modes the fit reports are those at the fit parameters, and the Hessian there is positive definite - ctl <- list(trustControl = list(iterlim = 0), innerControl = list(ftol = 1e-12, mtol = 1e-12, iterlim = 200)) + ctl <- list(trustControl = list(iterlim = 0), innerControl = list(mtol = 1e-12, iterlim = 200)) at <- suppressMessages(em(fit$objfn, fit$randomEffects, fit$fit$argument, control = ctl, verbose = FALSE)) expect_equal(fit$fit$etaModes, at$etaModes, tolerance = 1e-4) H <- .fullHessian(fit$fit) diff --git a/tests/testthat/test-arguments.R b/tests/testthat/test-arguments.R index 5e26c9d4..302d91ad 100644 --- a/tests/testthat/test-arguments.R +++ b/tests/testthat/test-arguments.R @@ -4,8 +4,7 @@ test_that("an argument a function does not take is an error", { expect_error(constraintGamma(c(a = 1), bogus = 1), "unused argument") expect_error(normL2(NULL, NULL, attr.name = "p"), "unused argument") expect_error(dMod2:::.pimplPTC(list(rtol = 1e-9)), "unknown controlsPTC entry rtol") - expect_error(trust(constraintL2(c(a = 0)), c(a = 1), ftol = 1e-3), - "tolControl\\$ftol") + expect_error(trust(constraintL2(c(a = 0)), c(a = 1), ftol = 1e-3), "unknown argument ftol") }) test_that("the snake-case names of the symmetry controls are derived", { diff --git a/tests/testthat/test-focei.R b/tests/testthat/test-focei.R index 5bfeea5c..ee2fbd88 100644 --- a/tests/testthat/test-focei.R +++ b/tests/testthat/test-focei.R @@ -140,7 +140,7 @@ test_that("FOCEI reproduces the Theoph reference fit and agrees with nlmixr2", { map <- c(Ka = "tka", V = "tv", Cl = "tcl", sigma_add = "log_sigma_add", omega_Ka_Ka = "omega_Ka_Ka", omega_V_V = "omega_V_V", omega_Cl_Cl = "omega_Cl_Cl") fit <- em(obj, randomEffects(mods$p), init = setNames(ref$init[map], names(map)), verbose = FALSE, - control = list(innerControl = list(iterlim = 30, ftol = 1e-7, mtol = 1e-7), + control = list(innerControl = list(iterlim = 30, mtol = 1e-7), trustControl = list(iterlim = 100))) expect_true(fit$converged) expect_lt(abs(fit$value - ref$value), 1e-2) @@ -151,6 +151,41 @@ test_that("FOCEI reproduces the Theoph reference fit and agrees with nlmixr2", { expect_lt(abs(fit$value - ref$nlmixr2Value), 0.5) }) +test_that("FOCEI on inexact modes ends at the nested optimum, dense and sparse, and counts the inner iterations", { + skip_on_cran() + ref <- readRDS("fixtures/focei_theoph_reference.rds") + oldwd <- setwd(tempdir()); on.exit(setwd(oldwd)) + mods <- .focei_models()$theoph + obj <- normL2(mods$data, mods$g * mods$x * mods$p, errmodel = mods$err) + map <- c(Ka = "tka", V = "tv", Cl = "tcl", sigma_add = "log_sigma_add", + omega_Ka_Ka = "omega_Ka_Ka", omega_V_V = "omega_V_V", omega_Cl_Cl = "omega_Cl_Cl") + init <- setNames(ref$init[map], names(map)) + for (sp in c(FALSE, TRUE)) { + nested <- em(obj, randomEffects(mods$p), init, verbose = FALSE, sparse = sp) + for (k in 1:2) { + sqp <- em(obj, randomEffects(mods$p), init, verbose = FALSE, sparse = sp, + control = list(inner = "sqp", innerControl = list(sqpIterlim = k))) + expect_true(sqp$converged) + expect_equal(sqp$value, nested$value, tolerance = 1e-6) + expect_lt(max(abs(sqp$argument - nested$argument)), 1e-3) + expect_lt(max(abs(sqp$gradient)), 1e-2) + expect_true(is.integer(sqp$innerIterations) && sqp$innerIterations > 0L) + expect_true(sqp$sqpIterations >= 1L && sqp$sqpIterations <= sqp$iterations) + expect_length(sqp$trace$value, sqp$iterations + 1L) + } + expect_true(is.integer(nested$innerIterations) && nested$innerIterations > 0L) + expect_null(nested$sqpIterations) + } + # without outer iterations the inexact search is skipped: the nested marginal at the start + at <- em(obj, randomEffects(mods$p), init, verbose = FALSE, control = list(trustControl = list(iterlim = 0))) + sq <- em(obj, randomEffects(mods$p), init, verbose = FALSE, + control = list(inner = "sqp", trustControl = list(iterlim = 0))) + expect_identical(sq$value, at$value) + expect_error(em(obj, randomEffects(mods$p), init, control = list(inner = "exact")), "nested") + expect_error(em(obj, randomEffects(mods$p), init, control = list(inner = "sqp", innerControl = list(sqpIterlim = 0))), + "sqpIterlim") +}) + test_that("the FOCEI gradient with a random effect in the error model is the slope of the objective", { skip_on_cran() oldwd <- setwd(tempdir()); on.exit(setwd(oldwd)) @@ -167,7 +202,7 @@ test_that("the FOCEI gradient with a random effect in the error model is the slo obj <- normL2(data, model, errmodel = mods$err) init <- c(truth + 0.05, omega_V_V = log(0.3)) ctl <- list(trustControl = list(iterlim = 0), - innerControl = list(ftol = 1e-12, mtol = 1e-12, iterlim = 200)) + innerControl = list(mtol = 1e-12, iterlim = 200)) run <- function(p) em(obj, randomEffects(mods$p), setNames(p, names(init)), control = ctl, verbose = FALSE) at <- run(init) slope <- numDeriv::grad(function(p) run(p)$value, unname(init), @@ -265,7 +300,7 @@ test_that("the volume rows give the exact joint blocks and d eta*/d theta is the sigma = NA_real_, condition = s)))) obj <- normL2(data, model, errmodel = mods$err) theta <- c(truth + 0.05, omega_V_V = log(0.3)) - ctl <- list(trustControl = list(iterlim = 0), innerControl = list(ftol = 1e-12, mtol = 1e-12, iterlim = 200)) + ctl <- list(trustControl = list(iterlim = 0), innerControl = list(mtol = 1e-12, iterlim = 200)) modes <- function(th) em(obj, randomEffects(mods$p), setNames(th, names(theta)), control = ctl, verbose = FALSE)$etaModes[, 1] design <- dMod2:::.emDesign(obj, randomEffects(mods$p)) @@ -368,7 +403,7 @@ test_that("the inner kernel has the value, gradient and Gauss-Newton Hessian of km <- .kernelMeta(obj, mods$p, outer, eta_vals) Omega_inv <- matrix(1 / 0.3^2) Omega_log_det <- log(0.3^2) - res <- dMod2:::focei_inner_trust( + res <- dMod2:::nlme_group_kernel( model_cb = model, err_cb = err, pars_full = km$full, eta_warmstart = matrix(eta_vals, ncol = 1), subject_meta = km$meta, Omega_inv_mat = Omega_inv, Omega_log_det = Omega_log_det, fixed = NULL, @@ -393,7 +428,7 @@ test_that("the inner kernel has the value, gradient and Gauss-Newton Hessian of list(value = value, grad = grad, hess = hess) } # the batched predictor of the lock-step trust - batched <- dMod2:::focei_inner_trust( + batched <- dMod2:::nlme_group_kernel( model_cb = model, err_cb = err, pars_full = km$full, eta_warmstart = matrix(eta_vals, ncol = 1), subject_meta = km$meta, Omega_inv_mat = Omega_inv, Omega_log_det = Omega_log_det, fixed = NULL, @@ -438,7 +473,7 @@ test_that("a failed prediction at an inner trial point rejects the trial of that } predict(timesList, parsList, conditions, fixed) } - modes <- function(cb) dMod2:::focei_inner_trust( + modes <- function(cb) dMod2:::nlme_group_kernel( model_cb = model, err_cb = mods$err, pars_full = km$full, eta_warmstart = matrix(0, 3, 1), subject_meta = km$meta, Omega_inv_mat = matrix(1 / 0.3^2), Omega_log_det = log(0.3^2), fixed = NULL, control = list(iterlim = 50, ftol = 1e-12, mtol = 1e-12), predict_cb = cb) @@ -482,7 +517,7 @@ test_that("an inner trial point whose derivatives are not finite rejects the tri } out } - modes <- function(cb) dMod2:::focei_inner_trust( + modes <- function(cb) dMod2:::nlme_group_kernel( model_cb = model, err_cb = mods$err, pars_full = km$full, eta_warmstart = matrix(0, 3, 1), subject_meta = km$meta, Omega_inv_mat = matrix(1 / 0.3^2), Omega_log_det = log(0.3^2), fixed = NULL, control = list(iterlim = 50, ftol = 1e-12, mtol = 1e-12), predict_cb = cb) @@ -524,7 +559,7 @@ test_that("the inner kernel matches the R replica for two observables per subjec K <- 2L Omega_inv <- diag(1 / 0.3^2, K) Omega_log_det <- 2 * log(0.3^2) - res <- dMod2:::focei_inner_trust( + res <- dMod2:::nlme_group_kernel( model_cb = model, err_cb = err, pars_full = km$full, eta_warmstart = matrix(eta_vals, ncol = K), subject_meta = km$meta, Omega_inv_mat = Omega_inv, Omega_log_det = Omega_log_det, fixed = NULL, @@ -562,6 +597,24 @@ test_that("the inner kernel matches the R replica for two observables per subjec expect_equal(as.numeric(res$gradient[s, ]), unname(R$grad), tolerance = 1e-10) expect_equal(as.numeric(res$H_GN[[s]]), as.numeric(R$hess), tolerance = 1e-10) } + # Laplace on all coordinates: the term log|H|, the weight H^-1, the constant -G K log 2 + expect_identical(res$term, res$log_det_H) + expect_identical(res$weight, res$H_inv) + expect_identical(res$constant, -length(subjects) * K * log(2)) + # the first coordinate normal: H_NN alone is integrated, the second has the Schur complement + part <- dMod2:::nlme_group_kernel( + model_cb = model, err_cb = err, pars_full = km$full, + eta_warmstart = matrix(eta_vals, ncol = K), subject_meta = km$meta, + Omega_inv_mat = Omega_inv, Omega_log_det = Omega_log_det, fixed = NULL, + control = list(iterlim = 0, normal = 1L)) + for (s in subjects) { + H <- res$H_GN[[s]]; g <- res$gradient[s, ] + expect_equal(unname(part$term[[s]]), log(H[1, 1]), tolerance = 1e-12) + expect_equal(unname(part$weight[[s]]), matrix(c(1 / H[1, 1], 0, 0, 0), 2), tolerance = 1e-12) + expect_equal(unname(part$S[[s]]), matrix(H[2, 2] - H[2, 1] * H[1, 2] / H[1, 1]), tolerance = 1e-12) + expect_equal(unname(part$r[[s]]), unname(g[2] - H[2, 1] * g[1] / H[1, 1]), tolerance = 1e-12) + } + expect_identical(part$constant, -length(subjects) * log(2)) }) test_that("an eta block with a vanishing variance is solved on the unit diagonal", { diff --git a/tests/testthat/test-mstrust.R b/tests/testthat/test-mstrust.R index 70ceff83..819b07a2 100644 --- a/tests/testthat/test-mstrust.R +++ b/tests/testthat/test-mstrust.R @@ -22,6 +22,23 @@ test_that("mstrust returns the global minimum across random starts on a convex q }) +test_that("mstrust passes structured Hessian methods and phases through to trust", { + target <- c(a = 1.0, b = -0.5) + obj <- constraintL2(mu = target, sigma = 1) + oldwd <- setwd(tempdir()); on.exit(setwd(oldwd), add = TRUE) + for (args in list(list(hessianMethod = "gnssr1"), + list(phases = list(list(hessianMethod = "gn", iterlim = 2), + list(hessianMethod = "sbfgs"))))) { + fits <- do.call(mstrust, c(list(objfun = obj, center = c(a = 0, b = 0), + name = "test_mstrust_structured", rinit = 1, iterlim = 100, + fits = 3, sd = 1, cores = 1, output = FALSE), args)) + pf <- as.parframe(fits) + expect_identical(nrow(pf), 3L) + expect_equal(min(pf$value), 0, tolerance = 1e-8) + } +}) + + test_that("set.seed() reproduces the starts of a multi-start whatever the cores", { skip_on_os("windows") obj <- constraintL2(mu = c(a = 1, b = -0.5), sigma = 1) diff --git a/tests/testthat/test-multipleShooting.R b/tests/testthat/test-multipleShooting.R index e8b11df2..27e8aaaa 100644 --- a/tests/testthat/test-multipleShooting.R +++ b/tests/testthat/test-multipleShooting.R @@ -463,6 +463,69 @@ test_that("the natural level function converges to the single-shooting optimum", stepControl = list(acceptance = "natural")), "hessianMethod") }) +# A summand that rises steeply off the start rejects every trial, so a run +# ends on stagnation at the start. With `slope`, the gradient off the start +# also defeats every damping of the natural level function. +.ms_wall <- function(start, slope = 0) { + nm <- names(start) + wall <- function(pars, fixed = NULL, deriv = TRUE, ...) { + off <- any(pars[nm] != start) + objlist(value = 1e6 * off, gradient = setNames(rep(slope * off, length(nm)), nm), + hessian = matrix(0, length(nm), length(nm), dimnames = list(nm, nm))) + } + class(wall) <- c("objfn", "fn") + wall +} + +test_that("stagnation is convergence only where the Newton step predicts no decrease", { + mo <- .ms_models() + obj0 <- normL2(mo$data, mo$g * mo$x * mo$p) + ref <- trust(obj0, mo$truth, iterlim = 200) + ms <- normL2(mo$data, mo$g * mo$x * mo$p, + multipleShootingControl = list(nodes = seq(2, 18, 2), init = "simulation")) + start <- mo$truth + c(0.8, -0.6, 0.4, -0.3, 0.3) + for (th in list(start, ref$argument)) { + fit <- trust(ms + .ms_wall(th), th, iterlim = 50, + tolControl = list(ftol = 1e7, gtol = 0), + stepControl = list(anneal = FALSE)) + expect_identical(fit$stopReason, "stagnation") + expect_equal(fit$argument, th) + expect_lt(fit$multipleShooting$violation, 1e-6) + expect_identical(fit$converged, identical(th, ref$argument)) + } +}) + +test_that("the handover from the natural level function keeps the total iterlim", { + mo <- .ms_models() + ms <- normL2(mo$data, mo$g * mo$x * mo$p, + multipleShootingControl = list(nodes = seq(2, 18, 2), init = "simulation")) + start <- mo$truth + c(0.8, -0.6, 0.4, -0.3, 0.3) + fit <- trust(ms + .ms_wall(start, slope = 1e6), start, iterlim = 5, blather = TRUE, + tolControl = list(ftol = 1e7), + stepControl = list(anneal = FALSE, acceptance = "natural")) + expect_identical(fit$multipleShooting$acceptance, "natural, then filter") + expect_identical(fit$stopReason, "iterlim") + expect_identical(fit$iterations, 5L) + expect_length(fit$multipleShooting$trace, 5L) + expect_false(fit$converged) +}) + +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) + ref <- trust(obj0, mo$truth, iterlim = 200) + ms <- normL2(mo$data, mo$g * mo$x * mo$p, + multipleShootingControl = list(nodes = seq(2, 18, 2), init = "simulation")) + start <- mo$truth + c(0.8, -0.6, 0.4, -0.3, 0.3) + for (acc in c("filter", "natural")) { + fit <- trust(ms, start, iterlim = 200, tolControl = list(ftol = 1e7, ctol = 1e3), + stepControl = list(anneal = FALSE, acceptance = acc)) + # gaps within ctol leave the value near, not at, the single-shooting one + expect_true(fit$converged, info = acc) + expect_equal(fit$value, ref$value, tolerance = 1e-2, info = acc) + } +}) + test_that("the residuals of a segment make up the segment value, gradient and Hessian", { mo <- .ms_models() obj <- normL2(mo$data, mo$g * mo$x * mo$p, multipleShootingControl = list(nodes = c(5, 10, 15))) diff --git a/tests/testthat/test-normL2.R b/tests/testthat/test-normL2.R index abf05c48..089dea62 100644 --- a/tests/testthat/test-normL2.R +++ b/tests/testthat/test-normL2.R @@ -267,6 +267,30 @@ test_that("normL2 gradient with proportional errmodel follows the analytic close }) +test_that("hessian = \"expected\" gives the expected information, positive semidefinite with an error model", { + skip_if_no_compile() + ec <- .nl2_fx()$prop + data <- fx_decay_data(pars = c(A = 1.0, k = 0.5), sigma = 0.05) + data$C1$sigma <- NA_real_ + pars <- c(A = 1.2, k = 0.45, srel = 0.08) + t <- data$C1$time + A <- pars[["A"]]; k <- pars[["k"]]; srel <- pars[["srel"]] + pred <- A * exp(-k * t) + sigma <- srel * pred + dpred <- cbind(A = exp(-k * t), k = -t * A * exp(-k * t), srel = 0) + dsigma <- srel * dpred + dsigma[, "srel"] <- pred + h_ref <- crossprod(dpred, 2 / sigma^2 * dpred) + crossprod(dsigma, 4 / sigma^2 * dsigma) + obj <- normL2(data, ec$prd, errmodel = ec$e) + h <- obj(pars, hessian = "expected")$hessian[colnames(h_ref), colnames(h_ref)] + expect_equal(unname(h), unname(h_ref), tolerance = 1e-4) + expect_gt(min(eigen(h, symmetric = TRUE, only.values = TRUE)$values), 0) + # the Gauss-Newton Hessian keeps the exact curvature of the loss, value and gradient are shared + expect_equal(obj(pars, hessian = "expected")$gradient, obj(pars)$gradient) + expect_false(isTRUE(all.equal(obj(pars)$hessian, obj(pars, hessian = "expected")$hessian))) +}) + + test_that("rows with explicit sigma keep it; NA rows fall through to errmodel", { skip_if_no_compile() bench <- fx_decay_compiled() @@ -586,7 +610,7 @@ test_that("evalConditionResidual keeps fixed error parameters without sensitivit pars <- bench$outerpars_id fixed <- c(sigma_y = 0.1) pr <- ec$prd(times = data$C1$time, pars = pars, fixed = fixed, deriv = FALSE)[["C1"]] - r <- evalConditionResidual(data$C1, pr, pars, errfn = ec$e, fixed = fixed, cn = "C1", + r <- evalConditionResidual(data$C1, pr, errfn = ec$e, fixed = fixed, cn = "C1", deriv = FALSE) ref <- normL2(data, ec$prd, errmodel = ec$e)(pars, fixed = fixed, deriv = FALSE) expect_equal(r$value, ref$value, tolerance = 1e-10) @@ -609,7 +633,7 @@ test_that("an error parameter outside the prediction's derivatives has a gradien num <- numDeriv::grad(function(q) obj(setNames(q, names(pars)), deriv = FALSE)$value, unname(pars)) expect_equal(unname(obj(pars)$gradient[names(pars)]), num, tolerance = 1e-6) pr <- x(times = 0:3, pars = pars, conditions = "C1")[["C1"]] - r <- evalConditionResidual(data$C1, pr, pars, errfn = e, cn = "C1") + r <- evalConditionResidual(data$C1, pr, errfn = e, cn = "C1") expect_equal(unname(r$gradient[names(pars)]), num, tolerance = 1e-6) }) diff --git a/tests/testthat/test-parDataClasses.R b/tests/testthat/test-parDataClasses.R index b23cd9fb..b2cbb935 100644 --- a/tests/testthat/test-parDataClasses.R +++ b/tests/testthat/test-parDataClasses.R @@ -174,3 +174,13 @@ test_that("covariates of a datalist are the condition grid", { expect_identical(covariates(dl), attr(dl, "condition.grid")) expect_null(covariates(structure(list(), class = c("datalist", "list")))) }) + +test_that("c() of a parvec names unnamed operands by their argument names", { + pv <- as.parvec(c(a = 1, b = 2)) + out <- c(pv, z = 3, w = c(4, 5)) + expect_s3_class(out, "parvec") + expect_identical(names(out), c("a", "b", "z", "w1", "w2")) + expect_equal(unclass(out)[["z"]], 3) + expect_identical(names(c(pv, z = 3)), c("a", "b", "z")) + expect_identical(names(c(pv, d = c(d = 7))), c("a", "b", "d")) +}) diff --git a/tests/testthat/test-plots.R b/tests/testthat/test-plots.R index 66721ac3..d11bba1b 100644 --- a/tests/testthat/test-plots.R +++ b/tests/testthat/test-plots.R @@ -175,3 +175,109 @@ test_that("plot() of a prdframe takes a data frame", { data <- data.frame(name = "A", time = times, value = exp(-times / 2), sigma = 0.1) expect_s3_class(plot(pred[[1]], data), "ggplot") }) + +# A fit of spike-and-slab random effects k and A over three groups, as em() returns it, without +# the model: A of group G3 reaches no data. +.slabFit <- function(method = "focei", shift = 0) { + groups <- paste0("G", 1:3) + random <- data.frame(group = rep(groups, 2), eta = rep(c("k", "A"), each = 3), + parameter = paste0("eta_", rep(c("k", "A"), each = 3), "_", groups), + mode = c(0, 0.8, -0.5, 0, 0, 0), se = c(0.05, 0.1, 0.2, 0.3, 0.02, 0.5), + data = c(TRUE, TRUE, TRUE, TRUE, TRUE, FALSE), cluster = c(0, 1, 2, 0, 0, 0), + p0 = c(0.9, 0.01, 0.2, 0.6, 0.95, 0.7), stringsAsFactors = FALSE) + modes <- matrix(random$mode, 3, dimnames = list(groups, c("eta_k", "eta_A"))) + inner <- modes + inner[, "eta_A"] <- c(0.2, -0.1, 0) + argument <- c(k = -0.5 + shift, A = 2.3, prob_ID = 0.3, tau_ID = 0.7) + information <- diag(c(50, 40, 30, 20)) + 1 + dimnames(information) <- list(names(argument), names(argument)) + structure(list(argument = argument, value = -40, gradient = 0 * argument, method = method, + information = information, etaModes = modes, innerModes = inner, + random = random, + slab = data.frame(name = c("prob_ID", "tau_ID"), distribution = "spikeSlab", symbols = "k, A", + estimate = c(0.3, 0.7), fixed = FALSE, stringsAsFactors = FALSE), + stageTrace = data.frame(iter = 1:3, phase = "trust", OFV = c(-30, -39, -40), + deltaPar = c(NA, 0.2, 0.01), prob_ID = c(0.5, 0.35, 0.3), + tau_ID = c(0.3, 0.6, 0.7)), + multistart = data.frame(start = 1:4, value = c(-40, -40, -35, NA), converged = TRUE, + iterations = 10L)), + class = c("em", "list")) +} + +test_that("the inclusion heatmap shows 1 - p0 with the reported values of the deviations", { + fit <- .slabFit() + d <- plotRandomEffects(fit, type = "inclusion")$data + expect_equal(d$inclusion, 1 - fit$random$p0) + expect_equal(d$label, c("", "0.80", "-0.50", "", "", "no data")) + expect_equal(levels(d$eta), c("A", "k")) +}) + +test_that("conditional draws of spike-and-slab effects: spike mass p0, the conditional variance, the prior", { + fit <- .slabFit() + set.seed(1) + v <- dMod2:::.spikeSlabValues(fit, "conditional", 20000L) + # the effect without data stays out + expect_equal(nrow(v), 5 * 20000) + r <- fit$random[fit$random$data, ] + for (i in seq_len(nrow(r))) { + x <- v$value[(i - 1) * 20000 + 1:20000] + expect_equal(mean(x == 0), r$p0[i], tolerance = 0.02) + expect_equal(sd(x), r$se[i], tolerance = 0.05) + } + expect_equal(unique(v$spike), 0.7) + expect_equal(unique(v$sd), 0.7) + # histogram bars have area 1, the exact zeros the mean p0; the prior spike has area 1 - prob + p <- plotRandomEffects(fit, draws = 2000L) + bars <- p$data + for (e in c("k", "A")) { + b <- bars[bars$eta == e, ] + area <- (b$xmax - b$xmin) * (b$ymax - b$ymin) + expect_equal(sum(area), 1) + expect_equal(sum(area[b$part == "spike"]), mean(r$p0[r$eta == e]), tolerance = 0.03) + } + spike <- p$layers[[3]]$data + expect_equal(spike$width * spike$density, c(0.7, 0.7)) + # with only sparse effects there is no QQ plot + expect_s3_class(p, "ggplot") + expect_s3_class(plotRandomEffects(fit, type = "modes"), "ggplot") +}) + +test_that("plotTrace draws the hyperparameters of a sparse fit", { + d <- plotTrace(.slabFit())$data + expect_equal(levels(d$panel), c("OFV", "|delta par|", "prob_ID", "tau_ID")) + expect_true(all(is.finite(d$value))) +}) + +test_that("plotTrace leaves out iterations without a value", { + fit <- .slabFit() + fit$stageTrace$deltaPar[1] <- NA + d <- plotTrace(fit)$data + expect_equal(sum(d$panel == "|delta par|"), nrow(fit$stageTrace) - 1L) + expect_true(all(is.finite(d$value))) +}) + +test_that("plotPars draws the estimates of several em fits side by side with Wald intervals", { + fits <- list(focei = .slabFit(), saem = .slabFit("saem", shift = 0.1)) + fits$saem$information <- NULL + p <- plotPars(fits, which = c("k", "A", "prob_ID")) + d <- p$data + expect_equal(nrow(d), 6) + expect_equal(levels(d$fit), c("focei", "saem")) + expect_equal(d$estimate[d$fit == "saem" & d$parameter == "k"], -0.4) + # Wald intervals where the fit has standard errors only + se <- sqrt(diag(solve(fits$focei$information)))[1:3] + expect_equal(d$upper[d$fit == "focei"] - d$estimate[d$fit == "focei"], unname(qnorm(0.975) * se)) + expect_true(all(is.na(d$lower[d$fit == "saem"]))) + # the first fit of a row on top + expect_gt(d$position[1], d$position[4]) + # unnamed fits are labeled by their method + expect_equal(levels(plotPars(unname(fits))$data$fit), c("focei", "saem")) + expect_error(plotPars(list(a = 1)), "em fits") +}) + +test_that("plotValues draws the multistart of an em fit and of a list of them", { + fit <- .slabFit() + expect_equal(plotValues(fit)$data$value, c(-40, -40, -35)) + d <- plotValues(list(a = fit, b = fit))$data + expect_equal(as.vector(table(d$set)), c(3, 3)) +}) diff --git a/tests/testthat/test-quadrature.R b/tests/testthat/test-quadrature.R index e9efd24b..86221ad4 100644 --- a/tests/testthat/test-quadrature.R +++ b/tests/testthat/test-quadrature.R @@ -95,7 +95,7 @@ test_that("evalConditionResidual sums to normL2", { pars <- c(mu = 0.7, eta_mu_s1 = 0.1, eta_mu_s2 = -0.1, eta_mu_s3 = 0.2) prediction <- (m$g * Xt() * m$p)(times = 0, pars = pars, deriv = TRUE, conditions = names(m$data)) agg <- Reduce(`+`, lapply(names(m$data), function(cn) - evalConditionResidual(dataI = m$data[[cn]], predictionI = prediction[[cn]], pars = pars, + evalConditionResidual(dataI = m$data[[cn]], predictionI = prediction[[cn]], cn = cn, deriv = TRUE))) res <- m$obj(pars) expect_equal(agg$value, res$value, tolerance = 1e-10) @@ -165,7 +165,7 @@ test_that("on nodes frozen in phi the referenced fixed effects, the error model }, 0)), tolerance = 1e-10) }) -test_that("a stage ends at what the stage nodes resolve, at the best iterate", { +test_that("a fit on capped levels ends where the levels resolve, at the best iterate", { m <- .quad_models() fit <- suppressMessages(em(m$objE, randomEffects(m$pw), c(mu = 0.7, mu_w = 0.1, s = log(0.3)), method = "quadrature", verbose = FALSE, @@ -174,10 +174,79 @@ test_that("a stage ends at what the stage nodes resolve, at the best iterate", { tr <- fit$stageTrace expect_true(fit$converged) expect_lt(nrow(tr), 10L) - last <- tr[nrow(tr), ] - # ended where a Newton step gains less than the nodes resolve, or after a step that rose - expect_true(last$decrement < last$resolution || tr$OFV[nrow(tr)] > tr$OFV[nrow(tr) - 1L]) - expect_equal(fit$value, min(tr$OFV), tolerance = 1e-7) + # every group is held at level 2 with an error above tol / G + expect_true(all(tr$capped == 3L)) + lv <- attr(tr, "levels") + expect_equal(lv$level, rep(2L, 3)) + expect_true(all(lv$capped & lv$levelError > 1e-12)) + # the decrement stays above tolDecrement: the stop is a rise on unchanged levels + expect_identical(fit$stopReason, "resolution") + expect_gt(tr$OFV[nrow(tr)], tr$OFV[nrow(tr) - 1L]) + # the best iterate, not the last + expect_equal(fit$value, min(tr$OFV), tolerance = 1e-10) + expect_lt(fit$value, tr$OFV[nrow(tr)]) +}) + +test_that("a fit returns the best iterate when the rebuilds run out", { + m <- .quad_models() + fit <- suppressMessages(em(m$objE, randomEffects(m$pw), c(mu = 0.7, mu_w = 0.1, s = log(0.3)), + method = "quadrature", verbose = FALSE, + control = list(quadrature = list(maxLevel = 2, tol = 1e-12, tolDecrement = 0, + maxEcmPerStage = 2, certificate = FALSE)))) + tr <- fit$stageTrace + expect_false(fit$converged) + expect_identical(fit$stopReason, "iterlim") + expect_equal(nrow(tr), 2L) + expect_equal(fit$value, min(tr$OFV), tolerance = 1e-10) +}) + +test_that("a fit on uncapped levels is stationary at tolDecrement", { + m <- .quad_models() + fit <- suppressMessages(em(m$objE, randomEffects(m$pw), c(mu = 0.7, mu_w = 0.1, s = log(0.3)), + method = "quadrature", verbose = FALSE, + control = list(quadrature = list(tol = 1e-8, tolDecrement = 1e-10, + certificate = FALSE)))) + tr <- fit$stageTrace + expect_true(fit$converged) + expect_identical(fit$stopReason, "decrement") + expect_true(all(tr$capped == 0L)) + expect_lt(tr$decrement[nrow(tr)], 1e-10) + expect_lt(max(abs(fit$gradient)), 1e-5) +}) + +test_that("levels over the node budget are rejected and the error comes from the level below", { + # nodes per group at K = 20 for levels K + 1 to K + 3: the default budget ends at K + 2 + expect_equal(vapply(21:23, function(l) dMod2:::.levelNodes(20L, l), 0L), c(41L, 801L, 10041L)) + m <- .quad_models() + d <- dMod2:::.emDesign(m$obj, randomEffects(m$p)) + psi <- c(mu = 0.7, omega_mu_mu = log(0.3)) + # one eta: levels 2, 4 and 9 have 3, 9 and 19 nodes + logL <- function(level) { + q <- dMod2:::.quadratureObjective(d, psi, NULL, list()) + q$rebuild(psi, level) + vapply(seq_along(d$groups), function(i) { + n <- q$state$nodes[[i]] + log(sum(n$signs * exp(q$integrand(d$groups[i], list(n$eta), psi)[[1]] + n$logW))) + }, 0) + } + q <- dMod2:::.quadratureObjective(d, psi, NULL, list(maxNodes = 9)) + q$rebuild(psi, 1, tol = 1e-6) + st <- q$state + expect_equal(st$levels, rep(4L, 3)) + expect_true(all(st$capped)) + expect_true(all(vapply(st$nodes, function(n) nrow(n$eta), 0L) <= 9L)) + expect_equal(st$levelError, 2 * abs(logL(4) - logL(2)), tolerance = 1e-8) + expect_false(q$allowed(9L)) + # a requested level over the budget falls to the highest one within it + q <- dMod2:::.quadratureObjective(d, psi, NULL, list(maxNodes = 9)) + q$rebuild(psi, 9) + expect_equal(vapply(q$state$nodes, function(n) nrow(n$eta), 0L), rep(9L, 3)) + expect_true(all(q$state$capped)) + # within the budget the levels are those without it + q <- dMod2:::.quadratureObjective(d, psi, NULL, list(maxNodes = 35)) + q$rebuild(psi, 1, tol = 1e-6) + expect_equal(q$state$levels, rep(9L, 3)) + expect_false(any(q$state$capped)) }) test_that("the certificate at the estimate agrees with the quadrature and is reproducible", { diff --git a/tests/testthat/test-remote-libs.R b/tests/testthat/test-remote-libs.R index b9d1d301..d0ea3117 100644 --- a/tests/testthat/test-remote-libs.R +++ b/tests/testthat/test-remote-libs.R @@ -207,6 +207,11 @@ test_that("a job submitted from another machine is recovered from the nodes and input = character(0), jobname = "jm")) expect_true(wait_for(job)) expect_true(file.exists(file.path(remote, "jm_folder", "job.rds"))) + # the finished job is not replaced by one of the same name from another working directory + elsewhere(expect_error( + distributedComputing(1, on = on, input = character(0), jobname = "jm"), + "the folder of job 'jm' on h1 holds the job submitted from")) + expect_identical(job$get(), list(1L, 2L, 3L)) elsewhere({ expect_error(distributedComputing(NULL, jobname = "jm", recover = TRUE), "no job 'jm'") moved <- distributedComputing(NULL, on = on, jobname = "jm", recover = TRUE) diff --git a/tests/testthat/test-saemSparse.R b/tests/testthat/test-saemSparse.R new file mode 100644 index 00000000..d3fc30d8 --- /dev/null +++ b/tests/testthat/test-saemSparse.R @@ -0,0 +1,318 @@ +# SAEM with spike-and-slab random effects: the indicators against the exact posterior of a linear +# model with a normal intercept, the selection and the estimates against FOCEI, beside normal and Dirichlet-process effects. + +# The decay model y = A exp(-k dose) of test-EMsparse.R, five groups with two conditions each, the +# linear model y = a + b dose with a known sigma, and a decay model with 14 spike-and-slab random +# effects per group, three of 56 not 0. +.saemSparse <- local({ + cache <- NULL + function() { + if (!is.null(cache)) return(cache) + withr::local_preserve_seed() + dir <- file.path(tempdir(), "saemsparse_models") + dir.create(dir, showWarnings = FALSE) + withr::local_dir(dir) + groups <- paste0("L", 1:5) + tab <- data.frame(ID = rep(groups, each = 2), dose = rep(c(0.5, 2), 5), + row.names = paste0(rep(groups, each = 2), c("a", "b"))) + base <- function() { + tr <- branch(define(NULL, "x <- x", x = c("k", "A", "s")), table = tab) + tr <- define(tr, "dose <- d", d = dose) + insert(tr, "x <- exp(x)", x = c("k", "A", "s")) + } + # second derivatives forward over reverse + .dm <- c("forward", "reverse", "forward-reverse") + pOf <- function(tr, name) P(tr, method = "explicit", compile = FALSE, modelname = name, derivMode = .dm) + g <- Y(c(y = "A * exp(-k * dose)"), f = NULL, parameters = c("A", "k", "dose"), compile = FALSE, + modelname = "ss_g", derivMode = .dm) + err <- Y(c(y = "s"), g, attachInput = FALSE, compile = FALSE, modelname = "ss_err", derivMode = .dm) + ps <- pOf(insert(base(), k + A ~ 1 + (1 | gr(ID, dist = spikeSlab()))), "ss_slab") + pdp <- pOf(insert(base(), k ~ 1 + (1 | gr(ID, dist = dirichletProcess())), A ~ 1 + (1 | gr(ID, dist = spikeSlab(prob = 0.3, tau = 0.5)))), + "ss_dpslab") + tr <- branch(define(NULL, "x <- x", x = c("a", "b")), table = tab) + tr <- define(tr, "dose <- d", d = dose) + gl <- Y(c(y = "a + b * dose"), f = NULL, parameters = c("a", "b", "dose"), compile = FALSE, modelname = "ss_glin", + derivMode = .dm) + pls <- pOf(insert(tr, a ~ 1 + (1 | ID), b ~ 1 + (1 | gr(ID, dist = spikeSlab()))), "ss_linslab") + # seven observables y_j = A_j exp(-(k_j + k_(j+1)) dose) on a cycle, every parameter with a + # spike-and-slab random effect: 14 per group + J <- 7 + ks <- paste0("k", 1:J); As <- paste0("A", 1:J) + trm <- branch(define(NULL, "x <- x", x = c(ks, As, "s")), table = tab[tab$ID != "L5", ]) + trm <- define(trm, "dose <- d", d = dose) + trm <- insert(trm, "x <- exp(x)", x = c(ks, As, "s")) + pm <- pOf(insert(trm, as.formula(paste(paste(c(ks, As), collapse = " + "), "~ 1 + (1 | gr(ID, dist = spikeSlab()))"))), + "ss_many") + gm <- Y(setNames(paste0(As, " * exp(-(", ks, " + ", c(ks[-1], ks[1]), ") * dose)"), paste0("y", 1:J)), f = NULL, + parameters = c(ks, As, "dose"), compile = FALSE, modelname = "ss_gmany", derivMode = .dm) + errm <- Y(setNames(rep("s", J), paste0("y", 1:J)), gm, attachInput = FALSE, compile = FALSE, modelname = "ss_errmany", + derivMode = .dm) + # ten observables y_j = A_j exp(-(k_j + k_(j+1)) dose) on a chain, k_11 = 0, 20 spike-and-slab random + # effects per group of five, three conditions without a group; in the groups seven observables + # with a noise far above the signal, so most effects are hardly informed + J2 <- 10 + ks2 <- paste0("k", 1:J2); As2 <- paste0("A", 1:J2) + groups2 <- paste0("C", 1:5) + tab2 <- data.frame(ID = c(rep(groups2, each = 2), NA, NA, NA), dose = c(rep(c(0.5, 2), 5), 0.5, 1, 2), + row.names = c(paste0(rep(groups2, each = 2), c("a", "b")), "R1", "R2", "R3")) + trc <- branch(define(NULL, "x <- x", x = c(ks2, As2)), table = tab2) + trc <- define(trc, "dose <- d", d = dose) + trc <- insert(trc, "x <- exp(x)", x = c(ks2, As2)) + pc <- pOf(insert(trc, as.formula(paste(paste(c(ks2, As2), collapse = " + "), "~ 1 + (1 | gr(ID, dist = spikeSlab()))"))), + "ss_cmp") + gc <- Y(setNames(paste0(As2, " * exp(-(", ks2, c(paste(" +", ks2[-1]), ""), ") * dose)"), paste0("y", 1:J2)), f = NULL, + parameters = c(ks2, As2, "dose"), compile = FALSE, modelname = "ss_gcmp", derivMode = .dm) + compile(g, err, ps, pdp, gl, pls, gm, errm, pm, gc, pc, output = "saemsparse_models", cores = test_cores()) + set.seed(7) + dev <- matrix(0, 4, 2 * J, dimnames = list(groups[1:4], c(ks, As))) + dev["L3", "k1"] <- 1; dev["L2", "k2"] <- -1; dev["L4", "A3"] <- 0.7 + rows <- lapply(rownames(tab)[tab$ID != "L5"], function(cn) { + id <- tab[cn, "ID"] + do.call(rbind, lapply(1:J, function(j) { + k <- 0.6 * (exp(dev[id, ks[j]]) + exp(dev[id, ks[j %% J + 1]])) + data.frame(name = paste0("y", j), time = 0:3, value = 10 * exp(dev[id, As[j]] - k * tab[cn, "dose"]) + rnorm(4, 0, 1), + sigma = NA_real_, condition = cn) + })) + }) + many <- list(g = gm, err = errm, p = pm, data = as.datalist(do.call(rbind, rows)), deviates = dev != 0, + init = c(setNames(rep(log(0.6), J), ks), setNames(rep(log(10), J), As), s = 0)) + set.seed(11) + dev2 <- matrix(0, 5, 2 * J2, dimnames = list(groups2, c(ks2, As2))) + dev2["C2", "k3"] <- 1; dev2["C4", "A2"] <- -0.8; dev2["C5", "k1"] <- -0.9; dev2["C1", "A1"] <- 0.7 + dev2["C3", "A3"] <- 0.6; dev2["C1", "k4"] <- 0.8; dev2["C3", "k2"] <- -0.7; dev2["C5", "A2"] <- 0.5 + A0 <- c(rep(10, 3), rep(1, 7)); sig <- c(rep(0.5, 3), rep(50, 7)) + rows <- lapply(rownames(tab2), function(cn) { + id <- tab2[cn, "ID"] + d <- if (is.na(id)) setNames(numeric(2 * J2), c(ks2, As2)) else dev2[id, ] + do.call(rbind, lapply(1:J2, function(j) { + k <- 0.6 * (exp(d[[ks2[j]]]) + if (j < J2) exp(d[[ks2[j + 1]]]) else 0) + sj <- if (is.na(id)) 0.05 * A0[j] else sig[j] + data.frame(name = paste0("y", j), time = 0:3, value = A0[j] * exp(d[[As2[j]]] - k * tab2[cn, "dose"]) + + rnorm(4, 0, sj), sigma = sj, condition = cn) + })) + }) + compounds <- list(g = gc, p = pc, data = as.datalist(do.call(rbind, rows)), + init = c(setNames(rep(log(0.6), J2), ks2), setNames(log(A0), As2), prob_ID = 0.2, tau_ID = 0.5)) + set.seed(4) + dk <- c(L1 = 0, L2 = 0, L3 = 0.8, L4 = 0.8, L5 = -0.6) + rows <- lapply(rownames(tab), function(cn) { + k <- 0.6 * exp(dk[[tab[cn, "ID"]]]) + data.frame(name = "y", time = c(0, 1, 2, 3), value = 10 * exp(-k * tab[cn, "dose"]) + rnorm(4, 0, 0.1), + sigma = NA_real_, condition = cn) + }) + data <- as.datalist(do.call(rbind, rows)) + ea <- setNames(rnorm(5, 0, 0.5), groups) + eb <- c(L1 = 0, L2 = 0, L3 = 0.4, L4 = -0.3, L5 = 0) + rows <- lapply(rownames(tab), function(cn) { + id <- tab[cn, "ID"] + data.frame(name = "y", time = c(0, 1, 2, 3), + value = 1 + ea[[id]] + (0.5 + eb[[id]]) * tab[cn, "dose"] + rnorm(4, 0, 0.3), + sigma = 0.3, condition = cn) + }) + cache <<- list(g = g, err = err, ps = ps, pdp = pdp, gl = gl, pls = pls, tab = tab, + data = data, linear = as.datalist(do.call(rbind, rows)), + init = c(k = log(0.6), A = log(10), s = log(0.1)), many = many, compounds = compounds) + cache + } +}) + +# Per group of the linear model the exact posterior probability of the spike, and -2 log L: y of +# a group is normal with covariance sigma^2 I + omega^2 11', plus tau^2 dose dose' in the slab. +.linearSpike <- function(theta, prob, tau) { + m <- .saemSparse() + ids <- unique(m$tab$ID) + terms <- vapply(ids, function(id) { + cn <- rownames(m$tab)[m$tab$ID == id] + y <- unlist(lapply(m$linear[cn], `[[`, "value")) + dose <- rep(m$tab[cn, "dose"], each = 4) + C <- diag(0.3^2, length(y)) + exp(theta[["omega_a_a"]])^2 + logN <- function(V) { + r <- y - theta[["a"]] - theta[["b"]] * dose + -0.5 * (sum(r * solve(V, r)) + as.numeric(determinant(2 * pi * V)$modulus)) + } + c(log1p(-prob) + logN(C), log(prob) + logN(C + tau^2 * tcrossprod(dose))) + }, numeric(2)) + top <- apply(terms, 2, max) + logI <- top + log(colSums(exp(sweep(terms, 2, top)))) + list(p0 = exp(terms[1, ] - logI), value = -2 * sum(logI)) +} + +test_that("SAEM with spike-and-slab random effects: the indicators follow the exact posterior", { + m <- .saemSparse() + set.seed(5) + theta <- c(a = 1.1, b = 0.4, omega_a_a = log(0.4)) + obj <- normL2(m$linear, m$gl * Xt() * m$pls) + fit <- em(obj, randomEffects(m$pls), fixed = c(theta, prob_ID = 0.4, tau_ID = 0.5), method = "saem", + control = list(saem = list(nEM = 600L)), verbose = FALSE) + exact <- .linearSpike(theta, 0.4, 0.5) + b <- fit$random[fit$random$eta == "b", ] + expect_lt(max(abs(setNames(b$p0, b$group)[names(exact$p0)] - exact$p0)), 0.08) + # with one sparse coordinate per group of a linear model the reported marginal is exact + expect_equal(fit$value, exact$value, tolerance = 1e-6) + expect_null(fit$valueSE) +}) + +test_that("the collapsed indicator move samples the exact posterior of the subsets of a Gaussian model", { + set.seed(6) + J <- 3; G <- 4 + H <- matrix(c(6, 2, 1, 2, 4, 1.5, 1, 1.5, 3), J) + grad <- c(-3, 1, -0.5); ref <- c(0.2, 0, 0) + prob <- c(0.3, 0.3, 0.3); tau <- c(0.8, 0.8, 0.8) + quad <- function(v) drop(sum(grad * (v - ref)) + (v - ref) %*% H %*% (v - ref) / 2) + dataAt <- function(V) if (is.list(V)) vapply(V, function(v) apply(v, 1, quad), numeric(G)) else apply(V, 1, quad) + model <- list(ref = matrix(ref, G, J, byrow = TRUE), grad = matrix(grad, G, J, byrow = TRUE), H = rep(list(H), G)) + # the exact posterior of every subset with the slab values integrated out + subsets <- as.matrix(expand.grid(rep(list(c(FALSE, TRUE)), J))) + logPost <- apply(subsets, 1, function(z) { + s <- which(z) + out <- sum(ifelse(z, log(prob), log1p(-prob))) + if (!length(s)) return(out) + Lam <- H[s, s, drop = FALSE] / 2 + diag(1 / tau[s]^2, length(s)) + h <- ((H %*% ref)[s] - grad[s]) / 2 + out - sum(log(tau[s])) - as.numeric(determinant(Lam)$modulus) / 2 + sum(h * solve(Lam, h)) / 2 + }) + exact <- exp(logPost - max(logPost)); exact <- exact / sum(exact) + inclusion <- colSums(subsets * exact) + V <- matrix(0, G, J); Z <- matrix(FALSE, G, J); value <- dataAt(V) + gh <- dMod2:::.hermiteNodes(3L) + n <- 1500 + visits <- matrix(0, G, nrow(subsets)); rb <- matrix(0, G, J) + for (it in seq_len(n)) { + for (r in sample.int(J)) { + fl <- dMod2:::.slabCollapsed(V, Z, value, dataAt, model, prob, tau, rep(r, G), 1.5, gh) + V <- fl$V; Z <- fl$Z; value <- fl$value + rb[, r] <- rb[, r] + fl$pinc + } + key <- drop(Z %*% 2^(seq_len(J) - 1)) + 1 + visits[cbind(seq_len(G), key)] <- visits[cbind(seq_len(G), key)] + 1 + } + expect_equal(value, dataAt(ifelse(Z, V, 0))) + # subsets ordered as expand.grid, the first coordinate fastest: the binary key above + expect_lt(max(abs(colSums(visits) / (G * n) - exact)), 0.03) + # on a Gaussian model the Gauss-Hermite sum is exact: the Rao-Blackwellized inclusion has less noise + expect_lt(max(abs(colMeans(rb) / n - inclusion)), 0.015) +}) + +# The estimates and the -2 log L of a SAEM fit and of the FOCEI fit of the same model. +# Without the refit of a normal random effect whose variance tends to 0. +.againstFocei <- function(p, nEM = 150L) { + m <- .saemSparse() + obj <- normL2(m$data, m$g * Xt() * p, errmodel = m$err) + focei <- suppressMessages(em(obj, randomEffects(p), m$init, control = list(boundary = FALSE), verbose = FALSE)) + saem <- suppressMessages(em(obj, randomEffects(p), m$init, method = "saem", + control = list(boundary = FALSE, saem = list(nEM = nEM)), verbose = FALSE)) + list(focei = focei, saem = saem, diff = saem$argument[names(focei$argument)] - focei$argument, + value = saem$value - focei$value, k = saem$random[saem$random$eta == "k", ], + A = saem$random[saem$random$eta == "A", ]) +} + +test_that("SAEM selects the groups whose decay rate deviates, with the estimates of FOCEI", { + m <- .saemSparse() + set.seed(1) + # spike and slab on k and A in one block + r <- .againstFocei(m$ps) + expect_identical(r$k$group[r$k$cluster > 0], c("L3", "L4", "L5")) + expect_true(all(r$k$p0[r$k$group %in% c("L1", "L2")] > 0.9)) + expect_true(all(r$k$p0[r$k$group %in% c("L3", "L4", "L5")] < 0.05)) + expect_equal(r$k$mode, r$focei$random$mode[r$focei$random$eta == "k"], tolerance = 0.05) + expect_lt(max(abs(r$diff[c("k", "A", "s")])), 0.05) + expect_lt(max(abs(r$diff[c("prob_ID", "tau_ID")])), 0.1) + expect_lt(abs(r$value), 0.3) + expect_null(r$saem$valueSE) + expect_true(all(r$A$cluster == 0 & r$A$mode == 0)) + # importance sampling at the SAEM estimate starts from the inner modes of the fit, so the + # approximation it reports is the value of the fit + expect_identical(dim(r$saem$innerModes), dim(r$saem$etaModes)) + l <- logLik(r$saem, "importance", draws = 500L) + expect_equal(attr(l, "approximation"), -r$saem$value / 2, tolerance = 1e-6) +}) + +test_that("SAEM with Dirichlet-process and spike-and-slab random effects in one fit", { + m <- .saemSparse() + set.seed(2) + r <- .againstFocei(m$pdp, nEM = 300L) + cl <- setNames(r$k$cluster, r$k$group) + expect_identical(cl[["L1"]], 0) + expect_identical(cl[["L2"]], 0) + expect_identical(cl[["L3"]], cl[["L4"]]) + expect_false(cl[["L5"]] %in% cl[c("L1", "L3")]) + # the slab of A has fixed hyperparameters: no group deviates in A, they are not identified + expect_setequal(names(r$saem$argument), c("k", "A", "s", "concentration_ID_1", "tau_ID_1")) + expect_true(all(r$A$cluster == 0)) + expect_lt(max(abs(r$diff[c("k", "A", "s", "tau_ID_1")])), 0.05) + expect_lt(abs(r$value), 0.3) + # at the FOCEI estimate -2 log L by importance sampling over the partitions against the exact sum + set.seed(2) + is <- suppressMessages(em(normL2(m$data, m$g * Xt() * m$pdp, errmodel = m$err), randomEffects(m$pdp), + fixed = r$focei$argument, method = "saem", verbose = FALSE, + control = list(saem = list(nBurnin = 5L, nEM = 5L, integral = "importance")))) + expect_true(is.finite(is$valueSE) && is$valueSE < 0.2) + expect_lt(abs(is$value - r$focei$value), 3 * is$valueSE + 0.02) + expect_error(em(normL2(m$data, m$g * Xt() * m$ps, errmodel = m$err), randomEffects(m$ps), m$init, + method = "laplaceEM"), "\"focei\" or \"saem\"") +}) + +test_that("SAEM with many spike-and-slab random effects per group, most of them 0", { + m <- .saemSparse()$many + obj <- normL2(m$data, m$g * Xt() * m$p, errmodel = m$err) + focei <- suppressMessages(em(obj, randomEffects(m$p), m$init, verbose = FALSE)) + set.seed(1) + saem <- suppressMessages(em(obj, randomEffects(m$p), m$init, method = "saem", verbose = FALSE, + control = list(saem = list(nEM = 100L)))) + selected <- function(fit) setNames(fit$random$p0 < 0.5, fit$random$parameter) + truth <- setNames(as.vector(m$deviates), paste0("eta_", rep(colnames(m$deviates), each = 4), "_", + rownames(m$deviates))) + expect_identical(selected(saem)[names(truth)], truth) + expect_identical(selected(focei)[names(truth)], truth) + expect_lt(abs(saem$argument[["prob_ID"]] - focei$argument[["prob_ID"]]), 0.03) + expect_lt(abs(saem$value - focei$value), 2) + # every move type is tried and accepted at some rate + tr <- saem$stageTrace[saem$stageTrace$phase == "averaging", ] + rates <- colMeans(tr[c("acceptBirth", "acceptDeath", "acceptWalk")], na.rm = TRUE) + expect_true(all(rates > 0 & rates < 1)) + # a FOCEI fit as init: the chain starts at the selected effects of the fit and keeps them + set.seed(2) + again <- suppressMessages(em(obj, randomEffects(m$p), focei, method = "saem", verbose = FALSE, + control = list(saem = list(nBurnin = 30L, nEM = 60L)))) + expect_identical(selected(again)[names(truth)], truth) + expect_lt(abs(again$value - focei$value), 2) +}) + +test_that("SAEM with 20 spike-and-slab random effects per group, most of them hardly informed", { + m <- .saemSparse()$compounds + obj <- normL2(m$data, m$g * Xt() * m$p) + set.seed(1) + saem <- suppressMessages(em(obj, randomEffects(m$p), m$init, method = "saem", verbose = FALSE, + control = list(saem = list(nBurnin = 100L, nEM = 100L)))) + # the FOCEI fit of this fixture, 1 min: -2 log L, prob, the 9 effects with p0 below 1/2 and those + # of them with p0 below 0.05 + focei <- list(value = 2980.078, prob = 0.4289, + clear = c("eta_k1_C5", "eta_A1_C1", "eta_A2_C4", "eta_A2_C5", "eta_A3_C1", "eta_A3_C3")) + selected <- saem$random$parameter[saem$random$p0 < 0.5] + expect_true(all(focei$clear %in% selected)) + expect_lte(abs(length(selected) - 9), 3) + expect_lt(abs(saem$value - focei$value), 2) + # prob is weakly determined: -2 log L of FOCEI changes by about 0.2 over 0.06 + expect_lt(abs(saem$argument[["prob_ID"]] - focei$prob), 0.1) + # the hardly informed effects keep prob where the informed ones put it, no run to every effect in the slab + tr <- saem$stageTrace + expect_lt(max(tr$included), 0.8 * nrow(saem$random)) +}) + +test_that("msem runs SAEM fits of spike-and-slab random effects, the parts of a run join into one fit", { + m <- .saemSparse() + obj <- normL2(m$data, m$g * Xt() * m$ps, errmodel = m$err) + run <- function(which = NULL) { + set.seed(3) + suppressMessages(msem(obj, randomEffects(m$ps), m$init, method = "saem", fits = 2L, sd = 0.2, which = which, + control = list(saem = list(nBurnin = 20L, nEM = 20L)))) + } + whole <- run() + expect_equal(whole$method, "saem") + expect_true(all(is.finite(whole$multistart$value))) + expect_true(all(c("cluster", "p0") %in% names(whole$random))) + expect_setequal(whole$slab$name, c("prob_ID", "tau_ID")) + joined <- dMod2:::.joinMsem(lapply(1:2, run)) + expect_equal(joined$multistart$value, whole$multistart$value) + expect_equal(joined$argument, whole$argument) +}) diff --git a/tests/testthat/test-sparse.R b/tests/testthat/test-sparse.R index d3cb13a7..8e9641f9 100644 --- a/tests/testthat/test-sparse.R +++ b/tests/testthat/test-sparse.R @@ -31,6 +31,115 @@ test_that("trust(sparse = TRUE) reaches the dense optimum", { expect_equal(s$argument[names(d$argument)], d$argument, tolerance = 1e-5) }) +# Nonlinear least squares with a tridiagonal Gauss-Newton Hessian plus a penalty on the sum, which +# the sparse Hessian passes as a low-rank part. +.chainLsq <- function(K = 6L, c = 0.3) { + nm <- paste0("x", seq_len(K)) + t <- seq(0.5, 2, length.out = K) + function(pars, hessian = TRUE, ...) { + x <- pars[nm] + i <- seq_len(K - 1L) + r <- c(exp(x) - t, x[i] * x[i + 1L] - 0.5) + J <- rbind(diag(exp(x)), matrix(0, K - 1L, K)) + J[cbind(K + i, i)] <- x[i + 1L] + J[cbind(K + i, i + 1L)] <- x[i] + u <- sum(x) - 1 + G <- 2 * crossprod(J) + dimnames(G) <- list(nm, nm) + lr <- list(U = matrix(1, K, 1L, dimnames = list(nm, NULL)), d = c) + out <- objlist(sum(r^2) + 0.5 * c * u^2, setNames(drop(2 * crossprod(J, r)) + c * u, nm), + if (identical(hessian, "sparse")) Matrix::Matrix(G, sparse = TRUE) else G + c) + if (identical(hessian, "sparse")) out$lowrank <- lr + out + } +} + +test_that("limited-memory BFGS on the sparse model: the dense optimum and the compact Hessian", { + obj <- .chainLsq() + p0 <- setNames(rep(0.3, 6), paste0("x", 1:6)) + ph <- list(list(hessianMethod = "gn", iterlim = 2), + list(hessianMethod = "bfgs", qnControl = list(qnMemory = 3))) + d <- trust(obj, p0, rinit = 1, rmax = 10, phases = ph) + s <- trust(obj, p0, rinit = 1, rmax = 10, phases = ph, sparse = TRUE, blather = TRUE) + expect_true(s$converged) + expect_equal(s$value, d$value, tolerance = 1e-8) + expect_equal(s$argument, d$argument, tolerance = 1e-5) + expect_identical(s$phaseIterations[["gn"]], 2L) + + # B0 the Gauss-Newton Hessian at the handover, the correction of Byrd, Nocedal and Schnabel from + # the last qnMemory accepted pairs that pass the cautious test, damped as they enter + bf <- which(s$hessianSource == "bfgs") + B0 <- obj(s$argpath[bf[1], ])$hessian + compact <- function(S, Y) { + if (!ncol(S)) return(B0) + SY <- crossprod(S, Y) + L <- SY * lower.tri(SY) + M <- rbind(cbind(crossprod(S, B0 %*% S), L), cbind(t(L), -diag(diag(SY), ncol(S)))) + W <- cbind(B0 %*% S, Y) + B0 - W %*% solve(M, t(W)) + } + model <- function(pts) { + if (nrow(pts) > 1) pts <- pts[c(TRUE, rowSums(abs(diff(pts))) > 0), , drop = FALSE] + g <- t(apply(pts, 1, function(x) obj(x)$gradient)) + S <- Y <- matrix(0, ncol(pts), 0) + for (k in seq_len(nrow(pts) - 1L)) { + sk <- pts[k + 1, ] - pts[k, ]; yk <- g[k + 1, ] - g[k, ] + if (sum(sk * yk) <= 1e-8 * sqrt(sum(sk^2) * sum(yk^2))) next + Bs <- drop(compact(S, Y) %*% sk) + sBs <- sum(sk * Bs); sy <- sum(sk * yk) + th <- if (sy < 0.2 * sBs) 0.8 * sBs / (sBs - sy) else 1 + S <- cbind(S, sk); Y <- cbind(Y, th * yk + (1 - th) * Bs) + if (ncol(S) > 3) { S <- S[, -1, drop = FALSE]; Y <- Y[, -1, drop = FALSE] } + } + compact(S, Y) + } + # the predicted decrease of every full step of the phase + for (k in bf[s$stepback[bf] == "full"]) { + B <- model(s$argpath[bf[1]:k, , drop = FALSE]) + step <- s$argtry[k, ] - s$argpath[k, ] + g <- obj(s$argpath[k, ])$gradient + expect_equal(s$preddiff[k], sum(g * step) + 0.5 * drop(step %*% B %*% step), tolerance = 1e-8) + } + # the model Hessian of the result: the sparse B0 and the low-rank part of B0 and the correction + H <- as.matrix(s$hessian) + s$lowrank$U %*% (s$lowrank$d * t(s$lowrank$U)) + expect_equal(unname(H), unname(model(rbind(s$argpath[bf, ], s$argument))), tolerance = 1e-8) + + expect_error(trust(obj, p0, phases = list(list(hessianMethod = "gn"), list(hessianMethod = "sr1")), + sparse = TRUE), "limited-memory BFGS") +}) + +test_that("a sparse BFGS phase from an indefinite Hessian keeps a positive definite model", { + # double-well terms coupled along a chain: the Hessian is indefinite near zero + K <- 6L + nm <- paste0("x", seq_len(K)) + obj <- function(pars, hessian = TRUE, ...) { + x <- pars[nm] + i <- seq_len(K - 1L) + dx <- x[i] - x[i + 1L] + g <- 4 * x * (x^2 - 1) + g[i] <- g[i] + dx + g[i + 1L] <- g[i + 1L] - dx + H <- diag(12 * x^2 - 4) + H[cbind(i, i)] <- H[cbind(i, i)] + 1 + H[cbind(i + 1L, i + 1L)] <- H[cbind(i + 1L, i + 1L)] + 1 + H[cbind(i, i + 1L)] <- H[cbind(i + 1L, i)] <- -1 + dimnames(H) <- list(nm, nm) + objlist(sum((x^2 - 1)^2) + 0.5 * sum(dx^2), setNames(g, nm), + if (identical(hessian, "sparse")) Matrix::Matrix(H, sparse = TRUE) else H) + } + p0 <- setNames(c(0.1, -0.05, 0.2, 0.15, -0.1, 0.05), nm) + ph <- list(list(hessianMethod = "gn", iterlim = 1), list(hessianMethod = "bfgs")) + d <- trust(obj, p0, rinit = 0.1, rmax = 10, phases = ph) + s <- trust(obj, p0, rinit = 0.1, rmax = 10, phases = ph, sparse = TRUE, blather = TRUE) + bf <- which(s$hessianSource == "bfgs") + expect_lt(min(eigen(obj(s$argpath[bf[1], ])$hessian, only.values = TRUE)$values), 0) + expect_true(s$converged) + expect_equal(s$value, d$value, tolerance = 1e-8) + H <- as.matrix(s$hessian) + if (!is.null(s$lowrank)) H <- H + s$lowrank$U %*% (s$lowrank$d * t(s$lowrank$U)) + expect_gt(min(eigen(H, symmetric = TRUE, only.values = TRUE)$values), 0) +}) + test_that("sparse Hessians of the constraints equal the dense ones, also through a chain", { outer <- c(u = 0.3, v = -0.2, w = 1.1, z = 0.5) inner <- c(a = 0.3 * -0.2, b = exp(1.1), c = 0.5, s = 0.1) diff --git a/tests/testthat/test-steadystates.R b/tests/testthat/test-steadystates.R index 3560a465..d396242e 100644 --- a/tests/testthat/test-steadystates.R +++ b/tests/testthat/test-steadystates.R @@ -504,3 +504,216 @@ test_that("steadyStates writes nothing without file and writes the RDS with it", expect_identical(readRDS("ss.rds"), ss2) expect_identical(ss2, ss) }) + + +# Evaluates every steady-state definition at random positive values of the free +# symbols and returns the definitions and the right-hand side there. +.ssResidual <- function(model, ss, seed = 7) { + odes <- as.eqnvec(model) + symbolsOf <- function(x) unique(unlist(lapply(x, function(e) all.vars(parse(text = e))))) + defs <- ss[trimws(ss) != names(ss)] + set.seed(seed) + free <- setdiff(symbolsOf(c(as.character(odes), defs)), names(defs)) + env <- as.list(setNames(stats::runif(length(free), 0.3, 2), free)) + for (n in names(defs)) env[[n]] <- eval(parse(text = defs[[n]]), env) + list(values = unlist(env[names(defs)]), + residual = vapply(odes, function(e) eval(parse(text = e), env), numeric(1))) +} + +test_that("a conserved quantity across compartments is a dependent balance", { + withr::local_dir(tempdir()) + r <- eqnlist() |> + assignCompartment(nIkb = "nucleus", nNfk = "nucleus", nNfkIkb = "nucleus", volume = "Vnuc") |> + addReaction("NfkIkb", "NfkpIkb", "k_phos * NfkIkb") |> + addReaction("NfkpIkb", "Nfk + pIkb", "k_split * NfkpIkb") |> + addReaction("pIkb", "", "k_dg * pIkb") |> + addReaction("Nfk + Ikb", "NfkIkb", "k_on * Nfk * Ikb") |> + addReaction("", "mIkb", "k_tx * nNfk") |> + addReaction("mIkb", "", "k_dgm * mIkb") |> + addReaction("", "Ikb", "k_tl * mIkb") |> + addReaction("Ikb", "nIkb", "k_in * eta_in * Ikb") |> + addReaction("Nfk", "nNfk", "k_in * Nfk") |> + addReaction("nIkb + nNfk", "nNfkIkb", "k_on * eta_on * nNfk * nIkb") |> + addReaction("nNfkIkb", "NfkIkb", "k_ex * nNfkIkb") + ss <- steadyStates(r) + expect_false(identical(ss, 0)) + # 9 states, 8 independent balances + expect_equal(sum(ss != names(ss)), 8) + chk <- .ssResidual(r, ss) + expect_true(all(chk$values > 0)) + expect_lt(max(abs(chk$residual)), 1e-10) +}) + +test_that("the cycles of the state graph are cut where the greedy runs fail", { + # the full NFkB model of Oppelt et al. (2018), npj Syst Biol Appl 4:23 + withr::local_dir(tempdir()) + reactions <- eqnlist() |> + assignCompartment(nIkb = "nucleus", pnNfk = "nucleus", nNfk = "nucleus", nNfkIkb = "nucleus", + volume = "Vnuc") |> + addReaction("TNF", "TNF + TNFR", "uptake * TNF", "receptor activation") |> + addReaction("TNFR", "", "deact_TNFR * TNFR", "receptor deactivation") |> + addReaction("Ikk", "pIkk", "act_Ikk_by_TNF / (1 + A20 / inh_Ikk) * TNFR * Ikk", "IKK activation") |> + addReaction("Ikk", "pIkk", "act_Ikk_Base * Ikk", "basal IKK activation") |> + addReaction("pIkk", "ppIkk", "act_pIkk * pIkk", "IKK phosphorylation") |> + addReaction("ppIkk", "iIkk", "deact_ppIkk * ppIkk", "IKK inactivation") |> + addReaction("iIkk", "Ikk", "trigger_iIkk * iIkk", "IKK recovery") |> + addReaction("NfkIkb", "NfkpIkb", "act_Ikb_Base * NfkIkb", "basal IkBa phosphorylation") |> + addReaction("NfkIkb", "NfkpIkb", "act_Ikb_by_Ikk * pIkk * NfkIkb", "IkBa phosphorylation by pIKK") |> + addReaction("NfkIkb", "NfkpIkb", "act_Ikb_by_Ikk * eta_s_ppIkk * ppIkk * NfkIkb", + "IkBa phosphorylation by ppIKK") |> + addReaction("NfkIkb", "pNfkIkb", "act_Nfk_Base * NfkIkb", "basal NFkB phosphorylation") |> + addReaction("NfkIkb", "pNfkIkb", "act_Nfk_by_Ikk * pIkk * NfkIkb", "NFkB phosphorylation by pIKK") |> + addReaction("NfkIkb", "pNfkIkb", "act_Nfk_by_Ikk * eta_s_ppIkk * ppIkk * NfkIkb", + "NFkB phosphorylation by ppIKK") |> + addReaction("pNfkIkb", "pNfkpIkb", "act_Ikb_Base * eta_act_Ikb_Base_c_pNfkIkb * pNfkIkb", + "basal IkBa phosphorylation, pNFkB complex") |> + addReaction("pNfkIkb", "pNfkpIkb", "act_Ikb_by_Ikk * eta_act_Ikb_c_pNfkIkb * pIkk * pNfkIkb", + "IkBa phosphorylation by pIKK, pNFkB complex") |> + addReaction("pNfkIkb", "pNfkpIkb", + "act_Ikb_by_Ikk * eta_s_ppIkk * eta_act_Ikb_c_pNfkIkb * ppIkk * pNfkIkb", + "IkBa phosphorylation by ppIKK, pNFkB complex") |> + addReaction("NfkpIkb", "pNfkpIkb", "act_Nfk_Base * eta_act_Nfk_Base_c_NfkpIkb * NfkpIkb", + "basal NFkB phosphorylation, pIkBa complex") |> + addReaction("NfkpIkb", "pNfkpIkb", "act_Nfk_by_Ikk * eta_act_Nfk_c_NfkpIkb * pIkk * NfkpIkb", + "NFkB phosphorylation by pIKK, pIkBa complex") |> + addReaction("NfkpIkb", "pNfkpIkb", + "act_Nfk_by_Ikk * eta_s_ppIkk * eta_act_Nfk_c_NfkpIkb * ppIkk * NfkpIkb", + "NFkB phosphorylation by ppIKK, pIkBa complex") |> + addReaction("NfkpIkb", "Nfk + pIkb", "split_NfkpIkb * NfkpIkb", "release of NFkB") |> + addReaction("pNfkpIkb", "pNfk + pIkb", "split_NfkIkb * eta_split_pNfkpIkb * pNfkpIkb", + "release of pNFkB") |> + addReaction("Nfk + Ikb", "NfkIkb", "form_complex * Nfk * Ikb", "complex formation") |> + addReaction("", "mIkb", "prod_mIkb_by_nNfk * nNfk", "IkBa transcription") |> + addReaction("mIkb", "", "degrad_mIkb * mIkb", "IkBa transcript degradation") |> + addReaction("", "Ikb", "prod_Ikb * mIkb", "IkBa translation") |> + addReaction("pIkb", "", "degrad_Ikb * pIkb", "pIkBa degradation") |> + addReaction("Ikb", "nIkb", "int_Nfk * eta_int_Ikb * Ikb", "IkBa import") |> + addReaction("pNfk", "pnNfk", "int_Nfk * eta_int_pNfk * pNfk", "pNFkB import") |> + addReaction("Nfk", "nNfk", "int_Nfk * Nfk", "NFkB import") |> + addReaction("pnNfk", "nNfk", "deact_pnNfk * pnNfk", "nuclear pNFkB dephosphorylation") |> + addReaction("nIkb + nNfk", "nNfkIkb", "form_complex * eta_form_complex_nuc * nNfk * nIkb", + "nuclear complex formation") |> + addReaction("nNfkIkb", "NfkIkb", "ext_nNfkIkb * nNfkIkb", "complex export") |> + addReaction("", "RnaA20_1", "build_RnaA20 * nNfk", "A20 transcription") |> + addReaction("RnaA20_1", "RnaA20_2", "shuttle_RnaA20 * RnaA20_1", "A20 transcript, delay 1") |> + addReaction("RnaA20_2", "RnaA20", "shuttle_RnaA20 * RnaA20_2", "A20 transcript, delay 2") |> + addReaction("RnaA20", "", "degrad_RnaA20 * RnaA20", "A20 transcript degradation") |> + addReaction("", "A20", "build_A20 * RnaA20", "A20 translation") |> + addReaction("A20", "", "degrad_A20 * A20", "A20 degradation") + + ss <- steadyStates(reactions, forcings = c("TNF", "TNFR")) + expect_false(identical(ss, 0)) + expect_setequal(names(ss)[ss == names(ss)], c("Ikk", "NfkIkb", "Ikb", "nIkb")) + expect_true(all(c("eta_int_Ikb", "prod_Ikb") %in% names(ss))) + expect_false(any(grepl("-", ss, fixed = TRUE))) + chk <- .ssResidual(reactions, ss) + expect_true(all(chk$values[!names(chk$values) %in% c("TNF", "TNFR")] > 0)) + expect_lt(max(abs(chk$residual)), 1e-10) + + # given conserved quantities keep their first states free + cq <- c("Ikk + pIkk + ppIkk + iIkk", + "NfkIkb + NfkpIkb + pNfkIkb + pNfkpIkb + Nfk + pNfk + Vnuc*(nNfk + pnNfk + nNfkIkb)") + ss <- steadyStates(reactions, forcings = c("TNF", "TNFR"), givenCQs = cq) + expect_false(identical(ss, 0)) + expect_true(all(c("Ikk", "NfkIkb") %in% names(ss)[ss == names(ss)])) + chk <- .ssResidual(reactions, ss) + expect_true(all(chk$values[!names(chk$values) %in% c("TNF", "TNFR")] > 0)) + expect_lt(max(abs(chk$residual)), 1e-10) +}) + +test_that("a side with separate rate constants is cut with free flux ratios", { + # no cut by one rate constant and no greedy choice of unknowns solves this network + withr::local_dir(tempdir()) + r <- eqnlist() |> + addReaction("A", "", "kd_A*A") |> + addReaction("", "B", "ks_B") |> + addReaction("B", "", "kd_B*B") |> + addReaction("A", "B", "k_ab*A") |> + addReaction("B", "A", "k_ba*B") |> + addReaction("A", "B", "k_ab_ind*A") |> + addReaction("", "B", "k_cat*A") |> + addReaction("B", "A", "k_ba_ind*B") + ss <- steadyStates(r, verbose = FALSE) + expect_false(identical(ss, 0)) + if (identical(ss, 0)) return() + ratios <- grep("^r_", getSymbols(ss), value = TRUE) + expect_setequal(ratios, c("r_A_1", "r_B_1", "r_B_2", "r_B_3")) + expect_false(any(ratios %in% names(ss))) + expect_false(any(grepl("-", ss, fixed = TRUE))) + chk <- .ssResidual(r, ss) + expect_true(all(chk$values > 0)) + expect_lt(max(abs(chk$residual)), 1e-10) +}) + +test_that("a state whose balance gives a ratio of positive sums is solved from it", { + withr::local_dir(tempdir()) + r <- eqnlist() |> + addReaction("", "A", "ka") |> addReaction("A", "B", "kab*A") |> + addReaction("B", "C", "kbc*B") |> addReaction("C", "A", "kca*C") |> + addReaction("A", "", "kda*A") |> addReaction("B", "", "kdb*B") |> + addReaction("C", "", "kdc*C") |> addReaction("B", "A", "kba*B") + ss <- steadyStates(r, verbose = FALSE) + expect_false(identical(ss, 0)) + expect_setequal(names(ss)[ss == names(ss)], c("A", "B")) + # C from the balance of C, not kept free with kbc solved instead + expect_false("kbc" %in% names(ss)) + env <- list(B = 0.7, kbc = 1.3, kca = 0.4, kdc = 0.9) + expect_equal(eval(parse(text = ss[["C"]]), env), with(env, kbc * B / (kca + kdc))) + chk <- .ssResidual(r, ss) + expect_true(all(chk$values > 0)) + expect_lt(max(abs(chk$residual)), 1e-10) +}) + +test_that("cuts are ranked as in v1.3", { + reticulate::py_require(c("numpy", "sympy", "scipy")) + ap <- reticulate::import_from_path("AlyssaPetit", + path = system.file("code", package = "dMod2")) + py <- reticulate::py_run_string(" +def first_cut(ap, f, ratios, priority): + states, fluxes, stoich = ap._read_model(f, []) + atoms, B = ap._atoms(states, fluxes, stoich, {}) + cands, nonlin = ap._candidates(states, atoms, set(), set()) + cqs = ap._derived_cqs(states, B, len(atoms)) + prio = {p: i for i, p in enumerate(priority)} + cut = ap._cut_cycles(states, atoms, B, cands, cqs, prio, False, ratios=ratios) + if cut[4] is not None: + return [str(cut[4][0]), 'ratio'] + [str(p) for p in cut[4][1]] + s, kind, x = cut[2][0] + return [str(s), kind] + ([] if kind == 'cq' else [str(x)]) +", convert = TRUE) + firstCut <- function(model, ratios = TRUE, priority = character(0)) { + f <- tempfile(fileext = ".csv") + on.exit(unlink(f)) + utils::write.csv(dMod2:::.volumeScaledReactions(model), f, row.names = FALSE, na = "") + unlist(py$first_cut(ap, f, ratios, as.list(priority))) + } + + # a conserved quantity first + closed <- eqnlist() |> addReaction("A", "B", "k_ab*A") |> addReaction("B", "A", "k_ba*B") |> + addReaction("B", "C", "k_bc*B") |> addReaction("C", "A", "k_ca*C") + expect_identical(firstCut(closed), c("A", "cq")) + # a side whose flux terms occur in no other balance before one that rewires others + feedback <- eqnlist() |> addReaction("", "B", "k_s*A") |> addReaction("B", "A", "k_x*B") |> + addReaction("A", "", "k_d*A") + expect_identical(firstCut(feedback), c("A", "pivot", "k_d")) + # several flux terms with ratios before a single term that rewires another balance + twoway <- eqnlist() |> addReaction("", "A", "k1") |> addReaction("A", "B", "k3*A") |> + addReaction("B", "A", "k2*B") |> addReaction("A", "", "k4*A") |> addReaction("B", "", "k5*B") + expect_identical(firstCut(twoway), c("A", "ratio", "k1", "k2")) + expect_identical(firstCut(twoway, ratios = FALSE), c("B", "pivot", "k3")) + # a side with a rate constant named in priority before all + expect_identical(firstCut(twoway, priority = "k5"), c("B", "ratio", "k2", "k5")) +}) + +test_that("a cut does not link to a state cut before", { + withr::local_dir(tempdir()) + r <- eqnlist() |> + addReaction("", "B", "ks_B") |> addReaction("B", "", "kd_B*B") |> + addReaction("A + C", "B", "k_on*A*C") |> addReaction("", "A", "k_A*B") |> + addReaction("B", "C", "k_C*B") + ss <- steadyStates(r, verbose = FALSE) + expect_false(identical(ss, 0)) + chk <- .ssResidual(r, ss) + expect_true(all(chk$values > 0)) + expect_lt(max(abs(chk$residual)), 1e-10) +}) diff --git a/tests/testthat/test-trust.R b/tests/testthat/test-trust.R index 05285e90..d513089c 100644 --- a/tests/testthat/test-trust.R +++ b/tests/testthat/test-trust.R @@ -6,7 +6,11 @@ skip_if_no_compile <- function() { testthat::skip_on_cran() } -fx_register(multicond = TRUE) +fx_register(multicond = TRUE, extra = function(bench) list( + trust_err = Y(c(y = "sqrt(s0^2 + srel^2 * y^2)"), f = bench$gfn, attachInput = FALSE, + condition = "C1", modelname = "trust_err", compile = FALSE), + trust_p_err = P(eqnvec(A = "exp(A_log)", k = "exp(k_log)", s0 = "exp(s0_log)", srel = "srel"), + condition = "C1", modelname = "trust_p_err", compile = FALSE))) # Synthetic quadratic objective in arbitrary dimension. Minimum at `target`. @@ -68,7 +72,7 @@ test_that("a gradient stop needs the full Newton step to predict at most mtol", }) test_that("a value stop needs the full Newton step to predict at most mtol", { - fit <- trust(.flat_objfn, c(x = 0, y = 9), rinit = 0.05, rmax = 0.05, + fit <- trust(.flat_objfn, c(x = 0, y = 9), rinit = 0.05, rmax = 0.05, hessianMethod = "gn", tolControl = list(ftol = 1e-3, mtol = 1e-4, gtol = 1e-6)) expect_true(fit$converged) expect_identical(fit$stopReason, "fvalue") @@ -76,6 +80,20 @@ test_that("a value stop needs the full Newton step to predict at most mtol", { }) +test_that("a stop held back by the Newton decrease ends the run when the radius collapses", { + # the gradient predicts a decrease along the flat direction that the noisy value does not follow + h <- c(1, 1e-4) + obj <- function(p, ...) { + objlist(0.5 * sum(h * p^2) + 5e-5 * sin(1e6 * p[["y"]]), h * p + c(0, 0.01), + diag(h) |> `dimnames<-`(list(names(p), names(p)))) + } + fit <- trust(obj, c(x = 1, y = 1), rinit = 1, rmax = 10, iterlim = 200, + tolControl = list(ftol = 1e-4, mtol = 1e-4, gtol = 1e-6, rmin = 1e-3)) + expect_true(fit$converged) + expect_identical(fit$stopReason, "fvalue") +}) + + ## ---- Simulated-truth recovery ---------------------------------------- test_that("trust(normL2) recovers true (A, k) from simulated decay data within noise budget", { @@ -352,6 +370,22 @@ test_that("a flat objective under repeated rejection stops as stagnation", { }) +test_that("stagnation is convergence only where the Newton decrease is at most mtol", { + # a value that follows no step: the gradient predicts a decrease the run never finds + flat <- function(p, ...) list(value = 1, gradient = c(1, 1), hessian = diag(2)) + fit <- trust(flat, c(a = 0, b = 0), iterlim = 500) + expect_identical(fit$stopReason, "stagnation") + expect_false(fit$converged) + # noise above ftol around the minimum of a quadratic: no step is accepted, the model is at rest + start <- c(a = 1e-4, b = 0) + noisy <- function(p, ...) list(value = sum(p^2) + 5e-5 * any(p != start), gradient = 2 * p, + hessian = diag(2, 2)) + fit <- trust(noisy, start, rinit = 1e-6, iterlim = 500, + tolControl = list(ftol = 1e-4, mtol = 1e-4, gtol = 1e-6)) + expect_identical(fit$stopReason, "stagnation") + expect_true(fit$converged) +}) + test_that("a rank-deficient Gauss-Newton Hessian gives a minimum-norm step", { # Rank-deficient Gauss-Newton Hessian with the gradient orthogonal to the null # space: the step must not extend along the zero-curvature direction. @@ -452,11 +486,11 @@ test_that("boundary = 'clip' keeps landing exactly on the bound", { }) -test_that("an argument that moved into a control list is rejected by name", { - obj <- .quadratic_objfn(c(a = 1)) - expect_error(trust(obj, c(a = 0), gtol = 1e-8), "tolControl\\$gtol") - expect_error(trust(obj, c(a = 0), qnMemory = 3L), "qnControl\\$qnMemory") - expect_error(trust(obj, c(a = 0), stepControl = list(boundary = "clip")), +test_that("a control entry given flat reaches the objective, which refuses it", { + obj <- constraintL2(mu = c(a = 1), sigma = 1) + expect_error(trust(obj, c(a = 0), gtol = 1e-8), "unknown argument gtol") + expect_error(trust(obj, c(a = 0), qnMemory = 3L), "unknown argument qnMemory") + expect_error(trust(.quadratic_objfn(c(a = 1)), c(a = 0), stepControl = list(boundary = "clip")), "argument of trust") }) @@ -555,8 +589,8 @@ test_that("evalBySource and nSwitch account for every evaluation", { # objective has no `deriv2` argument, so it is not driven here. for (hm in c("gn", "bfgs", "sr1")) { fit <- trust(obj, init, hessianMethod = hm) - expect_identical(names(fit$evalBySource), c("gn", "bfgs", "sr1", "exact"), - info = hm) + expect_identical(names(fit$evalBySource), c("gn", "bfgs", "sr1", "exact", "sbfgs", + "ssr1", "gnsbfgs", "gnssr1"), info = hm) expect_identical(fit$evalBySource[["exact"]], 0L, info = hm) expect_identical(sum(fit$evalBySource), fit$neval, info = hm) expect_identical(fit$nSwitch, 0L, info = hm) # no handover @@ -660,7 +694,8 @@ test_that("a soft stop past the handover ends the run", { init <- c(a = 0, b = 0) hy <- suppressWarnings(trust(obj, init, iterlim = 500, phases = list(list(hessianMethod = "gn"), list(hessianMethod = "bfgs")))) - expect_true(hy$converged) + # the gradient the value never follows leaves a Newton decrease above mtol: not converged + expect_false(hy$converged) expect_identical(hy$stopReason, "stagnation") expect_lt(hy$iterations, 500L) }) @@ -679,6 +714,26 @@ test_that("hessianInit is inert for the methods that need the objective Hessian" } }) +test_that("a BFGS phase seeded from an indefinite Hessian starts positive definite", { + # a double well in a, coupled to a quadratic in b, from a start of negative curvature + obj <- function(x, ...) { + a <- x[["a"]]; b <- x[["b"]] + list(value = a^4 / 4 - a^2 / 2 + (b - 1)^2 + 0.3 * a * b, + gradient = c(a = a^3 - a + 0.3 * b, b = 2 * (b - 1) + 0.3 * a), + hessian = matrix(c(3 * a^2 - 1, 0.3, 0.3, 2), 2, dimnames = list(c("a", "b"), c("a", "b")))) + } + init <- c(a = 0.1, b = 0) + runs <- list( + seed = list(hessianMethod = "bfgs", qnControl = list(hessianInit = "gn")), + handover = list(phases = list(list(hessianMethod = "gn", iterlim = 1), list(hessianMethod = "bfgs")))) + for (k in names(runs)) { + fit <- do.call(trust, c(list(obj, init, iterlim = 200), runs[[k]])) + expect_true(fit$converged, info = k) + expect_identical(fit$stopReason, "gradient", info = k) + expect_gt(min(eigen(fit$hessian, symmetric = TRUE, only.values = TRUE)$values), 0) + } +}) + test_that("quasi-Newton methods require the reflective boundary and a known name", { obj <- .quadratic_objfn(c(a = 1.0)) init <- c(a = 0) @@ -790,7 +845,7 @@ test_that("an iteration-limit stop also reports the last accepted iterate", { test_that("a single phase or no switch reproduces the plain run", { obj <- .misscaled_objfn(c(a = 1, b = -2)) init <- c(a = 0, b = 0) - plain <- trust(obj, init, iterlim = 200) + plain <- trust(obj, init, iterlim = 200, hessianMethod = "gn") expect_identical(plain$phaseIterations, c(gn = plain$iterations)) expect_null(plain$phaseSweep) for (alt in list(list(phases = list(list(hessianMethod = "gn"))), @@ -853,9 +908,6 @@ test_that("phases are checked by name and the fallback arguments refused", { phases = list(list(hessianMethod = "gn"))), "every phase names the hessianMethod") expect_error(trust(obj, init, phases = list(list(hessianMethod = "gn")), sweep = "reverse"), "every phase sets the sweep") - expect_error(trust(obj, init, fallbackControl = list(hessianMethod = "sr1")), - "`phases` and `switches`") - expect_error(trust(obj, init, hessianFallback = "sr1"), "`phases` and `switches`") expect_error(trust(obj, init, boundary = "clip", phases = list(list(hessianMethod = "gn"), list(hessianMethod = "gn"))), "single \"gn\" phase") @@ -895,6 +947,164 @@ test_that("a phase that uses up the phase iterations ends unconverged", { expect_identical(utils::tail(g$hessianSource, 1L), "gn") }) +test_that("a phase hands over after radiusStall iterations at an unchanged radius", { + # every step ends on the boundary of the region, so the radius grows to rmax and stays there + obj <- function(p, ...) list(value = 0.5 * sum((p - 10)^2), gradient = p - 10, hessian = diag(2)) + init <- c(a = 0, b = 0) + ph <- list(list(hessianMethod = "gn", radiusStall = 3), list(hessianMethod = "bfgs")) + f <- trust(obj, init, rinit = 0.1, rmax = 0.1, blather = TRUE, phases = ph) + expect_identical(f$phaseIterations[["gn"]], 3L) + expect_identical(f$hessianSource[1:4], c("gn", "gn", "gn", "bfgs")) + expect_true(f$converged) + + # a change of the radius restarts the count + g <- trust(obj, init, rinit = 0.1, rmax = 0.4, blather = TRUE, phases = ph) + expect_equal(g$r[1:6], c(0.1, 0.2, 0.4, 0.4, 0.4, 0.1)) + expect_identical(g$phaseIterations[["gn"]], 5L) + + # without a handover left the count stops nothing + h <- trust(obj, init, rinit = 0.1, rmax = 0.1, blather = TRUE, phases = ph, switches = 0) + expect_identical(names(h$phaseIterations), "gn") + expect_true(h$converged) + expect_error(trust(obj, init, phases = list(list(hessianMethod = "gn", radiusStall = 0))), + "radiusStall must be a positive number") +}) + +## ---- Default: the hybrid of Fides ------------------------------------------- + +# The misscaled quadratic with names on the Hessian, in a dense and a sparse version. +.misscaled_named <- function(target, sparse = FALSE) { + f <- .misscaled_objfn(target) + function(p, ..., hessian = TRUE) { + out <- f(p) + dimnames(out$hessian) <- list(names(p), names(p)) + if (sparse && identical(hessian, "sparse")) out$hessian <- Matrix::Matrix(out$hessian, sparse = TRUE) + out + } +} + +# 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) + Bs <- as.vector(B %*% s) + sy <- sum(s * y); sBs <- sum(s * Bs) + th <- if (sy < 0.2 * sBs) 0.8 * sBs / (sBs - sy) else 1 + r <- th * y + (1 - th) * Bs + B + tcrossprod(r) / sum(s * r) - tcrossprod(Bs) / sBs +} + +test_that("the default runs Gauss-Newton, then BFGS after 20 iterations at an unchanged radius", { + obj <- .misscaled_named(c(a = 1, b = -2, c = 3)) + init <- c(a = 0, b = 0, c = 0) + fit <- trust(obj, init, iterlim = 200, blather = TRUE) + expect_true(fit$converged) + expect_identical(fit$nSwitch, 1L) + expect_identical(names(fit$phaseIterations), c("gn", "bfgs")) + n <- fit$phaseIterations[["gn"]] + expect_identical(fit$hessianSource, rep(c("gn", "bfgs"), fit$phaseIterations)) + # the radius at the head of the last 20 Gauss-Newton iterations is the one at the switch + expect_true(all(fit$r[(n - 19):(n + 1)] == fit$r[n + 1])) + expect_false(fit$r[n - 20] == fit$r[n + 1]) + expect_equal(fit$argument, c(a = 1, b = -2, c = 3), tolerance = 1e-6) +}) + +test_that("the tracked BFGS matrix is the start Hessian updated with every accepted pair", { + obj <- .misscaled_named(c(a = 1, b = -2, c = 3)) + init <- c(a = 0, b = 0, c = 0) + fit <- trust(obj, init, iterlim = 200, blather = TRUE) + expect_identical(fit$nSwitch, 1L) + B <- obj(init)$hessian + for (i in which(fit$accept == 1)) { + s <- fit$argtry[i, ] - fit$argpath[i, ] + B <- .bfgs_r(B, s, obj(fit$argtry[i, ])$gradient - obj(fit$argpath[i, ])$gradient) + } + expect_equal(fit$hessian, B, tolerance = 1e-10, ignore_attr = TRUE) + expect_false(isTRUE(all.equal(B, obj(init)$hessian, check.attributes = FALSE))) + + # an indefinite start Hessian enters with the absolute values of the eigenvalues + ind <- function(p, ...) { + out <- obj(p) + out$hessian[] <- diag(c(20, -20, 20)) + out + } + expect_warning(f2 <- trust(ind, init, iterlim = 3, blather = TRUE, phases = list( + list(hessianMethod = "gn", iterlim = 3), + list(hessianMethod = "bfgs", qnControl = list(hessianInit = "tracked")))), "Maximum number") + B <- diag(20, 3) + for (i in which(f2$accept == 1)) { + s <- f2$argtry[i, ] - f2$argpath[i, ] + B <- .bfgs_r(B, s, ind(f2$argtry[i, ])$gradient - ind(f2$argpath[i, ])$gradient) + } + expect_identical(f2$nSwitch, 1L) + expect_equal(f2$hessian, B, tolerance = 1e-10, ignore_attr = TRUE) +}) + +test_that("keepRadius keeps the radius at the handover, and onStop = \"end\" ends the run", { + obj <- .misscaled_named(c(a = 1, b = -2, c = 3)) + init <- c(a = 0, b = 0, c = 0) + ph <- function(keep) list(list(hessianMethod = "gn", radiusStall = 20, onStop = "end"), + list(hessianMethod = "bfgs", keepRadius = keep, + qnControl = list(hessianInit = "tracked"))) + kept <- trust(obj, init, iterlim = 200, blather = TRUE, phases = ph(TRUE)) + restart <- trust(obj, init, iterlim = 200, blather = TRUE, phases = ph(FALSE)) + n <- kept$phaseIterations[["gn"]] + expect_identical(restart$phaseIterations[["gn"]], n) + expect_gt(kept$r[n], 0.1) + expect_identical(kept$r[n + 1], kept$r[n]) + expect_identical(restart$r[n + 1], 0.1) + + # a value stop of the first phase hands over by default and ends the run with "end" + flat <- function(p, ...) list(value = 0.5 * sum(c(1, 1e-3) * p^2), gradient = c(1, 1e-3) * p, + hessian = diag(c(1, 1e-3))) + run <- function(stop) trust(flat, c(x = 0, y = 9), rinit = 0.05, rmax = 0.05, + tolControl = list(ftol = 1e-3, mtol = 1e-4, gtol = 1e-6), + phases = list(list(hessianMethod = "gn", onStop = stop), + list(hessianMethod = "bfgs"))) + expect_identical(run("handover")$nSwitch, 1L) + ended <- run("end") + expect_identical(ended$nSwitch, 0L) + expect_identical(ended$stopReason, "fvalue") + expect_true(ended$converged) + + expect_error(trust(obj, init, phases = list(list(hessianMethod = "bfgs", + qnControl = list(hessianInit = "tracked")))), + "after the first") + expect_error(trust(obj, init, phases = list(list(hessianMethod = "gn"), + list(hessianMethod = "sr1", + qnControl = list(hessianInit = "tracked")))), + "after the first") + expect_error(trust(obj, init, phases = list(list(hessianMethod = "gn", keepRadius = NA))), + "TRUE or FALSE") + expect_error(trust(obj, init, phases = list(list(hessianMethod = "gn", onStop = "nope"))), + "should be one of") +}) + +test_that("explicit gn, the sparse path and the clip boundary stay Gauss-Newton", { + target <- c(a = 1, b = -2, c = 3) + init <- c(a = 0, b = 0, c = 0) + dense <- .misscaled_named(target) + expect_identical(names(trust(dense, init, iterlim = 200)$phaseIterations), c("gn", "bfgs")) + gn <- trust(dense, init, iterlim = 200, hessianMethod = "gn") + expect_identical(gn$phaseIterations, c(gn = gn$iterations)) + expect_null(gn$phaseSweep) + + sp <- .misscaled_named(target, sparse = TRUE) + forced <- trust(sp, init, iterlim = 200, sparse = TRUE) + auto <- withr::with_options(list(dMod2.sparseAuto = list(parameters = 0, fill = 1)), + trust(sp, init, iterlim = 200)) + for (f in list(forced, auto)) { + expect_s4_class(f$hessian, "sparseMatrix") + expect_identical(f$phaseIterations, c(gn = f$iterations)) + expect_identical(f$iterations, gn$iterations) + } + expect_error(trust(sp, init, sparse = TRUE, phases = list( + list(hessianMethod = "gn"), list(hessianMethod = "bfgs", qnControl = list(hessianInit = "tracked")))), + "limited-memory BFGS") + clip <- trust(dense, init, iterlim = 200, boundary = "clip") + expect_true(clip$converged) + expect_null(clip$phaseIterations) +}) + ## ---- Counters across repeated handovers ------------------------------------- # The flat objective with a `sweep` argument; `log()` lists the sweep and the @@ -918,7 +1128,7 @@ test_that("phase iterations add up, and the handover iteration counts on the pha expect_identical(sum(f$phaseIterations), f$iterations) expect_identical(rle(f$hessianSource)$lengths, unname(f$phaseIterations)) expect_identical(f$stopReason, "stagnation") - expect_true(f$converged) + expect_false(f$converged) } # A budget on the first phase ends it after exactly that many iterations. @@ -926,7 +1136,7 @@ test_that("phase iterations add up, and the handover iteration counts on the pha list(hessianMethod = "bfgs")))) expect_identical(g$phaseIterations[["gn"]], 3L) expect_identical(g$nSwitch, 1L) - expect_true(g$converged) + expect_false(g$converged) }) test_that("a budget run out after the last handover ends unconverged on either source", { @@ -1040,3 +1250,283 @@ test_that("a trial point without a Hessian is a failed evaluation, not an error" expect_identical(fit$stopReason, "objfun") expect_false(fit$converged) }) + + +## ---- Structured quasi-Newton methods -------------------------------- + +# A least-squares objective from residuals: value sum(r^2), gradient 2 J'r, Gauss-Newton Hessian +# 2 J'J, and with deriv2 the exact Hessian. `res(p)` returns r, J and the residual Hessians Hr. +.lsq_objfn <- function(res) { + function(p, deriv = TRUE, hessian = TRUE, deriv2 = FALSE, ...) { + e <- res(p); n <- names(p) + H <- 2 * crossprod(e$J) + if (deriv2) H <- H + 2 * Reduce(`+`, Map(`*`, e$r, e$Hr)) + dimnames(H) <- list(n, n) + objlist(sum(e$r^2), setNames(as.vector(2 * crossprod(e$J, e$r)), n), H) + } +} + +# The same with the data rows of the residuals, as objlist() describes them: Jacobian J, seeds 2 r +# and the Gauss-Newton Hessian, under hessian = "structured". +.lsq_rows_objfn <- function(res) { + base <- .lsq_objfn(res) + function(p, deriv = TRUE, hessian = TRUE, ...) { + out <- base(p, deriv = deriv, hessian = hessian, ...) + if (identical(hessian, "structured")) { + e <- res(p) + out$structure <- list(jacobian = unname(e$J), seeds = 2 * e$r, hessian = out$hessian) + } + out + } +} + +# Residuals (x + 1, l x^2 + x - 1) per coordinate: minimum at 0 with value 4 for every l, where +# the second-order term S = -2 l is not small against J'J = 2. +.ds_objfn <- function(l) .lsq_objfn(function(p) { + x <- p[[1]]; y <- p[[2]] + Z <- matrix(0, 2, 2) + list(r = c(x + 1, l * x^2 + x - 1, y + 1, l * y^2 + y - 1), + J = rbind(c(1, 0), c(2 * l * x + 1, 0), c(0, 1), c(0, 2 * l * y + 1)), + Hr = list(Z, matrix(c(2 * l, 0, 0, 0), 2), Z, matrix(c(0, 0, 0, 2 * l), 2))) +}) + +# Exponential decay fitted to exact data: residual zero at (a, k) = (1, 0.5). +.exp_objfn <- local({ + tt <- seq(0, 4, by = 0.5) + .lsq_objfn(function(p) { + a <- p[[1]]; k <- p[[2]]; e <- exp(-k * tt) + list(r = a * e - exp(-0.5 * tt), J = cbind(e, -a * tt * e), + Hr = lapply(seq_along(tt), function(i) + tt[i] * e[i] * matrix(c(0, -1, -1, a * tt[i]), 2))) + }) +}) + +.structured <- c("sbfgs", "ssr1", "gnsbfgs", "gnssr1") +.tight <- list(gtol = 1e-6, ftol = 0, mtol = 0) + +test_that("every Hessian method reaches the minimum of a large-residual problem", { + obj <- .ds_objfn(-0.8) + for (hm in c("gn", "bfgs", "sr1", "exact", .structured)) { + fit <- trust(obj, c(x = 1, y = -1), rinit = 1, iterlim = 200, hessianMethod = hm, + tolControl = .tight) + expect_true(fit$converged, info = hm) + expect_equal(unname(fit$argument), c(0, 0), tolerance = 1e-6, info = hm) + expect_equal(fit$value, 4, tolerance = 1e-10, info = hm) + expect_gt(fit$evalBySource[[hm]], 0L) + } +}) + +test_that("structured methods need fewer iterations than gn where the residual is large", { + obj <- .ds_objfn(-0.8) + it <- vapply(c("gn", .structured), function(hm) + trust(obj, c(x = 1, y = -1), rinit = 1, iterlim = 200, hessianMethod = hm, + tolControl = .tight)$iterations, 1L) + expect_gt(it[["gn"]], 40L) + expect_true(all(it[.structured] <= 15L), info = paste(names(it), it, collapse = " ")) +}) + +test_that("the hybrid methods and residual scaling keep Gauss-Newton speed at zero residual", { + init <- c(a = 3, k = 2) + run <- function(hm, ...) trust(.exp_objfn, init, rinit = 1, iterlim = 200, hessianMethod = hm, + tolControl = .tight, ...) + gn <- run("gn") + expect_true(gn$converged) + fast <- list(run("gnsbfgs"), run("gnssr1"), + run("sbfgs", qnControl = list(qnScaling = "residual")), + run("ssr1", qnControl = list(qnScaling = "residual"))) + for (f in fast) { + expect_true(f$converged) + expect_equal(unname(f$argument), c(1, 0.5), tolerance = 1e-6) + expect_lte(f$iterations, gn$iterations + 1L) + } + # without the scaling a structured correction remains and slows the end + expect_gt(run("sbfgs")$iterations, gn$iterations + 2L) + expect_gt(fast[[1]]$hybridGN, 0L) +}) + +test_that("the hybrid switch follows the ratio z's / s's against qnHybridTol", { + # z = (g+ - g - G+ s) sqrt(f+ / f); "gnsbfgs" takes the Gauss-Newton branch where z's / s's + # is below the tolerance, "gnssr1" where |z's| / s's is + for (hm in c("gnsbfgs", "gnssr1")) for (tol in c(1e-6, 1e-2)) { + fit <- trust(.exp_objfn, c(a = 3, k = 2), rinit = 1, iterlim = 200, hessianMethod = hm, + tolControl = .tight, qnControl = list(qnHybridTol = tol), blather = TRUE) + acc <- which(fit$accept == 1) + expect_gt(length(acc), 2L) + branch <- vapply(acc, function(i) { + x0 <- fit$argpath[i, ]; x1 <- fit$argtry[i, ] + o0 <- .exp_objfn(x0); o1 <- .exp_objfn(x1) + s <- x1 - x0 + z <- (o1$gradient - o0$gradient - o1$hessian %*% s) * sqrt(o1$value / o0$value) + q <- sum(z * s) / sum(s * s) + if (hm == "gnssr1") q <- abs(q) + if (q < tol) "gn" else hm + }, "") + inner <- acc < fit$iterations + expect_identical(fit$hessianSource[acc[inner] + 1L], branch[inner], info = paste(hm, tol)) + expect_identical(fit$hybridGN, sum(branch == "gn"), info = paste(hm, tol)) + } + # a negative curvature term keeps "gnsbfgs" on Gauss-Newton, "gnssr1" takes it + neg <- .ds_objfn(0.5) + b <- trust(neg, c(x = 1, y = 1), rinit = 1, hessianMethod = "gnsbfgs", tolControl = .tight) + s <- trust(neg, c(x = 1, y = 1), rinit = 1, hessianMethod = "gnssr1", tolControl = .tight) + expect_gte(b$hybridGN, b$iterations - 2L) + expect_identical(s$hybridGN, 0L) + expect_lt(s$iterations, b$iterations) +}) + +test_that("qnHybridShift adds the residual norm to the Gauss-Newton branch", { + neg <- .ds_objfn(0.5) + fit <- trust(neg, c(x = 1, y = 1), rinit = 1, hessianMethod = "gnsbfgs", tolControl = .tight, + qnControl = list(qnHybridShift = TRUE), blather = TRUE) + expect_true(fit$converged) + gn <- which(fit$hessianSource == "gn") + expect_gt(length(gn), 2L) + for (i in gn) { + x0 <- fit$argpath[i, ]; s <- fit$argtry[i, ] - x0; o <- neg(x0) + m <- sum(o$gradient * s) + 0.5 * sum(s * ((o$hessian + sqrt(o$value) * diag(2)) %*% s)) + expect_equal(fit$preddiff[i], m, tolerance = 1e-8, info = i) + } +}) + +test_that("a structured SR1 pair orthogonal to the step is skipped", { + # f = p'Qp / 2 reported with G = Q + D, so the structured secant is w = -D s, orthogonal to + # a first step s = (-1, -1) + Q <- c(2, 3); D <- c(1, -1) + obj <- function(p, ...) { + n <- names(p) + objlist(sum(Q * p^2) / 2, setNames(Q * p, n), matrix(diag(Q + D), 2, 2, dimnames = list(n, n))) + } + one <- function(init) suppressWarnings( + trust(obj, init, rinit = 2, iterlim = 1L, hessianMethod = "ssr1", blather = TRUE)) + skip <- one(c(a = 1.5, b = 2 / 3)) + expect_equal(unname(skip$argtry[1, ] - skip$argpath[1, ]), c(-1, -1), tolerance = 1e-12) + expect_identical(skip$qnSkipped, 1L) + expect_equal(unname(skip$hessian), diag(Q + D), tolerance = 1e-12) + # off the orthogonal direction the pair updates G by w w' / w's + upd <- one(c(a = 1.5, b = 1)) + s <- upd$argtry[1, ] - upd$argpath[1, ] + w <- -D * s + expect_identical(upd$qnSkipped, 0L) + expect_equal(unname(upd$hessian), diag(Q + D) + tcrossprod(w) / sum(w * s), tolerance = 1e-10) +}) + +test_that("structured methods run as phases and take over from any source", { + obj <- .ds_objfn(-0.8) + init <- c(x = 1, y = -1) + gn <- trust(obj, init, rinit = 1, tolControl = .tight) + for (first in c("gn", "bfgs", "exact")) for (hm in .structured) { + fit <- trust(obj, init, rinit = 1, tolControl = .tight, + phases = list(list(hessianMethod = first, iterlim = 3), list(hessianMethod = hm))) + info <- paste(first, hm) + expect_true(fit$converged, info = info) + expect_identical(fit$nSwitch, 1L, info = info) + expect_identical(names(fit$phaseIterations), c(first, hm), info = info) + expect_gt(fit$evalBySource[[hm]], 0L) + expect_identical(sum(fit$evalBySource), fit$neval, info = info) + expect_lt(fit$iterations, gn$iterations) + expect_equal(unname(fit$argument), c(0, 0), tolerance = 1e-6, info = info) + } +}) + +test_that("structured methods honor bounds and maximization", { + obj <- .ds_objfn(-0.8) + for (hm in .structured) { + fit <- trust(obj, c(x = 1, y = -1), rinit = 1, hessianMethod = hm, tolControl = .tight, + parlower = c(x = 0.2)) + expect_true(fit$converged, info = hm) + expect_equal(fit$argument[["x"]], 0.2, tolerance = 1e-6, info = hm) + expect_true(fit$atBound[["x"]], info = hm) + neg <- function(p, ...) { o <- obj(p, ...); objlist(-o$value, -o$gradient, -o$hessian) } + mx <- trust(neg, c(x = 1, y = -1), rinit = 1, hessianMethod = hm, tolControl = .tight, + minimize = FALSE) + expect_equal(unname(mx$argument), c(0, 0), tolerance = 1e-6, info = hm) + } +}) + +test_that("structured methods refuse settings they cannot honor", { + obj <- .ds_objfn(-0.8) + init <- c(x = 1, y = -1) + expect_error(trust(obj, init, hessianMethod = "sbfgs", qnControl = list(qnMemory = 3)), + "keeps no pairs") + expect_error(trust(obj, init, hessianMethod = "ssr1", + qnControl = list(hessianInit = "identity")), "Gauss-Newton") + expect_error(trust(obj, init, phases = list(list(hessianMethod = "gnsbfgs", sweep = "reverse"))), + "forward sensitivities") + expect_error(trust(obj, init, hessianMethod = "sbfgs", sparse = TRUE), "sparse") + expect_error(trust(obj, init, hessianMethod = "sbfgs", boundary = "clip"), "reflective") + expect_error(trust(obj, init, hessianMethod = "gnsbfgs", qnControl = list(qnScaling = "x"))) + expect_error(trustL1(obj, init, hessianMethod = "sbfgs"), "argument of trust") +}) + +test_that("structured methods fit a sum of normL2 and a prior to the gn optimum", { + skip_if_no_compile() + bench <- fx_decay_compiled() + data <- fx_decay_data(pars = c(A = 1.0, k = 0.5), sigma = 0.02, + times = seq(0, 8, by = 0.5), seed = 17L) + obj <- normL2(data, bench$prd_id) + constraintL2(mu = c(A = 0.8, k = 0.4), sigma = 0.1) + init <- c(A = 0.6, k = 0.9) + ref <- trust(obj, init, rinit = 1, iterlim = 200) + for (hm in .structured) { + fit <- trust(obj, init, rinit = 1, iterlim = 200, hessianMethod = hm) + expect_true(fit$converged, info = hm) + expect_equal(fit$argument, ref$argument, tolerance = 1e-4, ignore_attr = TRUE, info = hm) + } +}) + +test_that("the structured secant of an objective with data rows is (J+ - J)'u+", { + # one accepted SR1 step from A = 0: the model is G+ + w w' / w's with w the secant + res <- function(p) { + a <- p[[1]]; k <- p[[2]]; tt <- c(0.5, 1, 2, 3); e <- exp(-k * tt) + list(r = a * e - c(2, 0.5, 1.5, 0.2), J = cbind(e, -a * tt * e)) + } + obj <- .lsq_rows_objfn(res) + class(obj) <- c("objfn", "fn") + fit <- suppressWarnings(trust(obj, c(a = 1, k = 0.3), rinit = 0.2, iterlim = 1L, + hessianMethod = "ssr1", blather = TRUE)) + expect_true(fit$accept) + x0 <- fit$argpath[1, ]; x1 <- fit$argtry[1, ] + w <- drop(crossprod(res(x1)$J - res(x0)$J, 2 * res(x1)$r)) + o1 <- obj(x1) + expect_equal(unname(fit$hessian), unname(o1$hessian + tcrossprod(w) / sum(w * (x1 - x0))), + tolerance = 1e-10) +}) + +test_that("normL2 returns the data rows, and the secant of a sum with a prior is that of the data", { + skip_if_no_compile() + bench <- fx_decay_compiled() + x <- fx_extra() + data <- fx_decay_data(pars = c(A = 1.0, k = 0.5), sigma = 0.02, times = seq(0, 8, by = 0.5), + seed = 17L) + data[["C1"]]$sigma <- NA + data[["C1"]]$value <- data[["C1"]]$value * rep_len(c(1.3, 0.7), nrow(data[["C1"]])) + term <- normL2(data, bench$gfn * bench$xfn * x$trust_p_err, x$trust_err) + obj <- term + constraintL2(mu = c(A_log = 0, k_log = log(0.4)), sigma = 0.5) + init <- c(A_log = log(2), k_log = log(0.9), s0_log = log(0.05), srel = 0.3) + rowsOf <- list() + for (ev in c("C++", "R")) { + withr::local_options(dMod2.evaluation = ev) + o <- obj(init, hessian = "structured") + d <- term(init) + st <- o$structure + # a row per data point and one per sigma that depends on parameters + expect_identical(dim(st$jacobian), c(2L * nrow(data[["C1"]]), 4L), info = ev) + expect_equal(drop(crossprod(st$jacobian, st$seeds)), d$gradient[names(init)], tolerance = 1e-10, + ignore_attr = TRUE, info = ev) + expect_equal(st$hessian, d$hessian[names(init), names(init)], tolerance = 1e-10, info = ev) + expect_null(obj(init)$structure) + rowsOf[[ev]] <- st + } + expect_equal(rowsOf[["C++"]], rowsOf[["R"]], tolerance = 1e-8) + # a scaled objective scales seeds and Hessian + sc <- (2 %.*% term)(init, hessian = "structured")$structure + expect_equal(sc$seeds, 2 * rowsOf[["C++"]]$seeds, tolerance = 1e-12) + + fit <- suppressWarnings(trust(obj, init, rinit = 0.1, iterlim = 1L, hessianMethod = "ssr1", + blather = TRUE)) + expect_true(fit$accept) + x0 <- fit$argpath[1, ]; x1 <- fit$argtry[1, ] + o0 <- obj(x0, hessian = "structured"); o1 <- obj(x1, hessian = "structured") + w <- drop(crossprod(o1$structure$jacobian - o0$structure$jacobian, o1$structure$seeds)) + expect_equal(unname(fit$hessian), unname(o1$hessian + tcrossprod(w) / sum(w * (x1 - x0))), + tolerance = 1e-8) +}) diff --git a/tests/testthat/test-trustL1.R b/tests/testthat/test-trustL1.R index 6a4d5e4f..f7fd58d9 100644 --- a/tests/testthat/test-trustL1.R +++ b/tests/testthat/test-trustL1.R @@ -262,11 +262,11 @@ test_that("trustL1 maximizing subtracts the penalty", { }) -test_that("trustL1 takes the tolerances in tolControl and refuses them flat", { +test_that("trustL1 takes the tolerances in tolControl, the objective refuses them flat", { obj <- .quadratic_objfn(c(a = 1, b = 0.5)) init <- c(a = 0, b = 0) - expect_error(trustL1(obj, init, gtol = 1e-8), "tolControl\\$gtol") - expect_error(trustL1(obj, init, theta.max = 0.9), "stepControl\\$thetaMax") + expect_error(trustL1(constraintL2(mu = c(a = 1, b = 0.5), sigma = 1), init, gtol = 1e-8), + "unknown argument gtol") expect_error(trustL1(obj, init, tolControl = list(ctol = 1)), "unknown entries ctol") fit <- trustL1(obj, init, lambda = 0.1, tolControl = list(gtol = 1e-10), stepControl = list(thetaMax = 0.9)) @@ -294,3 +294,25 @@ test_that("trustL1 stops for convergence only where the full Newton step predict expect_identical(val$stopReason, "fvalue") expect_lte(val$value, 1e-4) }) + +test_that("trustL1 ends on a stop held back by the Newton decrease when the radius collapses", { + # the gradient predicts a decrease along the flat direction that the noisy value does not follow + h <- c(1, 1e-4) + obj <- function(p, ...) { + objlist(0.5 * sum(h * p^2) + 5e-5 * sin(1e6 * p[["y"]]), h * p + c(0, 0.01), + diag(h) |> `dimnames<-`(list(names(p), names(p)))) + } + fit <- trustL1(obj, c(x = 1, y = 1), mu = c(x = 0, y = 0), lambda = 0, rinit = 1, rmax = 10, + iterlim = 200, tolControl = list(ftol = 1e-4, mtol = 1e-4, gtol = 1e-6, rmin = 1e-3)) + expect_true(fit$converged) + expect_identical(fit$stopReason, "fvalue") +}) + +test_that("trustL1 ends on stagnation unconverged where the Newton decrease exceeds mtol", { + # a value that follows no step: the gradient predicts a decrease the run never finds + flat <- function(p, ...) objlist(value = 1, gradient = c(x = 1, y = 1), + hessian = diag(2) |> `dimnames<-`(list(names(p), names(p)))) + fit <- trustL1(flat, c(x = 0, y = 0), mu = c(x = 5), lambda = 0.1, iterlim = 500) + expect_identical(fit$stopReason, "stagnation") + expect_false(fit$converged) +}) diff --git a/vignettes/articles/dMod2.Rmd b/vignettes/articles/dMod2.Rmd index e5fe8c22..e1485a20 100644 --- a/vignettes/articles/dMod2.Rmd +++ b/vignettes/articles/dMod2.Rmd @@ -127,11 +127,4 @@ are bounded on one side only, a practical non-identifiability. call returns values with their derivatives in the outer parameters, the objective value, gradient and Hessian. -## Next steps - -- [Setting up models](guide-model.html): reactions, compartments, error models, steady states and - events on the NFκB model. -- [Optimization](guide-optimization.html) and [Profile likelihood](guide-profiles.html): fits - and identifiability. -- [Nonlinear mixed-effects models](guide-nlme.html): random effects with `em()`. -- [Installation and troubleshooting](installation.html): compilers and Python. +[1. Setting up models →](guide-model.html) diff --git a/vignettes/articles/guide-alignment.Rmd b/vignettes/articles/guide-alignment.Rmd index 418b981b..f1e55505 100644 --- a/vignettes/articles/guide-alignment.Rmd +++ b/vignettes/articles/guide-alignment.Rmd @@ -14,10 +14,9 @@ do.call(knitr::read_chunk, list(file.path("results", "guide-alignment.R"))) saved <- stored("results/guide-alignment.rds", "results/guide-alignment.R", envir = new.env()) ``` -Western blots, plate readers and similar assays read on experiment-specific scales: exposure and -background differ between gels or plates. `alignmentModel()` and `align()` bring all experiments -onto one common scale by maximum likelihood, before or instead of a dynamic model, with the -reading model written as an expression, as in the R package +Western blots, plate readers and similar assays read on experiment-specific scales. +`alignmentModel()` and `align()` bring all experiments onto one common scale by maximum likelihood, +with the reading model written as an expression, as in the R package [blotIt](https://github.com/JetiLab/blotIt). ```{r} @@ -29,9 +28,8 @@ dir.create(getOption("dMod2.outdir"), showWarnings = FALSE) ## Simulated blot data -A phosphorylation at five time points after stimulation in six biological replicates, each with -own cells, stimulation and lysates on a separate gel, every sample in three lanes (technical -replicates). Simulated: 20 % biological variability per sample, exposure and background per gel, +A phosphorylation at five time points, six biological replicates on six gels, every sample in +three lanes. Simulated: 20 % biological variability per sample, exposure and background per gel, 15 % technical noise per lane. ```{r data} @@ -39,24 +37,21 @@ replicates). Simulated: 20 % biological variability per sample, exposure and bac ## Alignment model -A reading is value `yi` times gel scale `sj` plus background `bj`, with standard deviation -proportional to the prediction. Each symbol is a linear predictor over the data columns, one -formula per role: a value per time point, a scale per gel, one background and one error parameter. -All symbols are on log scale, hence positive. `technical = "lane"` replaces the three lanes of a -sample by their mean, see [technical and biological replicates](#technical-and-biological-replicates). +A reading is value `yi` times gel scale `sj` plus background `bj`, with relative error. Each +symbol is a linear predictor over the data columns, on log scale. `technical = "lane"` averages +the lanes of a sample, see +[technical and biological replicates](#technical-and-biological-replicates). ```{r model} ``` -Doubling all values and halving all scales changes nothing; the alignment holds the geometric -mean of the values at 1 within each block of experiments sharing values. +The geometric mean of the values is held at 1 within each block of experiments sharing values. ## Fit by restricted likelihood -`align()` fits from several perturbed starts and keeps the best. Error parameters are estimated by -restricted maximum likelihood by default, correcting for the degrees of freedom of the prediction -parameters: here 5 values, 6 scales and the background against 30 readings. The print names the -likelihood of $-2 \log L$ and lists the maximum likelihood fits the restricted one starts from. +`align()` fits from several perturbed starts and keeps the best; error parameters by restricted +maximum likelihood. The fits of this chapter are loaded from `results/guide-alignment.rds`, +computed by `results/guide-alignment.R`. ```{r fit, eval = FALSE} ``` @@ -74,8 +69,7 @@ fit$aligned ## Comparison with the simulation -On the alignment scale the simulated course is `truth / exp(mean(log(truth)))`. Error (log ratio -of aligned to simulated) against the standard error `se`: +Error (log ratio of aligned to simulated course) against the standard error `se`: ```{r} simulated <- data.frame(time = times, value = truth / exp(mean(log(truth)))) @@ -93,23 +87,15 @@ ggplot(fit$aligned, aes(time, value)) + geom_point(aes(shape = "aligned")) + geom_point(data = simulated, aes(shape = "simulated")) + scale_shape_manual(values = c(aligned = 16, simulated = 4), name = NULL) + - labs(x = "time [min]", y = "value") + theme_dMod() + labs(x = "time [min]", y = "value") + theme_dMod2() ``` ## Technical and biological replicates -A biological replicate repeats the experiment (cells, stimulation, lysate) and differs by -biological variability and every measurement step. A technical replicate measures the same sample -again (lysate in another lane, cDNA in another well) and differs by the measurement steps alone. - -The lanes of a sample share the biological deviation of that sample, so they are not independent readings of the -biology. `technical = "lane"` averages them before the alignment; readings agreeing in all columns -but `value`, `lloq` and the technical columns form one sample. The mean is geometric for a -relative error model, as here, and arithmetic for an absolute one, as for readings already on log -scale. The error model then describes the scatter of sample means: biological variability plus -technical noise of a three-lane mean. - -The same data with every lane as a separate reading: +Technical replicates (lanes, wells) measure the same sample and share the biological deviation +of that sample. `technical = "lane"` averages them before the alignment; readings agreeing in all +columns but `value`, `lloq` and the technical columns form one sample. The mean is geometric for a +relative error model, arithmetic for an absolute one. The same data with every lane as a reading: ```{r lanes, eval = FALSE} ``` @@ -128,19 +114,15 @@ signif(errors(fitLanes), 2) inSE <- function(fit) with(errors(fit), max(abs(error / se))) ``` -Both fits find nearly the same values and errors, but the lane fit reports standard errors -smaller by about $\sqrt{3}$: it counts 90 readings, while most of the error is the biological -deviation of 30 samples. The errors of the lane fit reach `r round(inSE(fitLanes), 1)` standard errors, those of -the fit of means stay within `r inWords(ceiling(inSE(fit)))`. +The lane fit reports standard errors smaller by about $\sqrt{3}$; the errors reach +`r round(inSE(fitLanes), 1)` standard errors, those of the fit of means stay within +`r inWords(ceiling(inSE(fit)))`. ## Random background per gel -Instead of six free backgrounds, the background can be a random effect per gel around a common -value. The role then takes a list of formulas; the fit integrates the random effects by FOCEI as -in [Nonlinear mixed-effects models](guide-nlme.html), with their standard deviation by restricted -likelihood. Five readings per gel say little about it, so a prior holds the standard deviation of -the log background near 0.3: `omega_bj_bj`, the log of that standard deviation, normal around -$\log 0.3$ with standard deviation 0.3. +A random effect per gel around a common background, integrated by FOCEI as in +[Nonlinear mixed-effects models](guide-nlme.html). A prior on `omega_bj_bj`, the log standard +deviation, normal around $\log 0.3$ with standard deviation 0.3: ```{r background, eval = FALSE} ``` @@ -154,7 +136,7 @@ fit2 signif(errors(fit2), 2) ``` -Background per gel, common value times the random effect at the mode, against the simulation: +Background per gel against the simulation: ```{r} bg <- exp(fit2$parameters[["bj"]] + fit2$random$mode[match(gels, fit2$random$group)]) @@ -162,10 +144,9 @@ data.frame(gel = gels, simulated = round(background), common = round(exp(fit$par random = round(bg)) ``` -Both fits have nearly the same likelihood; values change by less than their standard errors. -The random backgrounds lie below the simulated ones with little spread, since the bands lie far -above the background. In the [Western blots](#western-blot-and-targeted-mass-spectrometry) below, -gels with weak lanes resolve it. +Values change by less than their standard errors. Bands far above the background leave it +unresolved; gels with weak lanes resolve it, see +[Western blots](#western-blot-and-targeted-mass-spectrometry). ## Fit options @@ -177,44 +158,35 @@ gels with weak lanes resolve it. | `method` | `"focei"` | with random terms, `"focei"` or `"quadrature"` | | `cores` | `1` | fits in parallel | -The alignment objective needs no ODE solver and is exact up to rounding, so fits stop at -tolerances near the square root of machine precision, about $10^{-8}$, for value change, predicted -decrease and gradient. - -Absolute readings, such as targeted mass spectrometry concentrations, are marked in a column -`absolute` and fix the scale of their block. The two sections below treat qPCR with wells below the -detection limit, and Western blots with random background per gel plus mass spectrometry in nM. +Fits stop at tolerances of about $10^{-8}$. Absolute readings, such as mass spectrometry +concentrations, are marked in a column `absolute` and fix the scale of their block. ## qPCR with censored wells -Target mRNA at seven time points after stimulation in four experiments (biological replicates), -each with own cells, cDNA, plate and a subset of time points, none shared by all; every sample in -two wells (technical duplicates). A well reports the cycle Ct at which fluorescence crosses a -threshold above background during exponential growth. The amount doubles per cycle, so 36 - Ct is -the log2 concentration in arbitrary units, shifted by an experiment offset. Untreated cells barely -express the target: a well not crossing the threshold in 40 cycles reports no Ct, and the reading lies -below 36 - 40 = -4. +Target mRNA at seven time points in four experiments, each on a subset of time points, every +sample in two wells. 36 - Ct is the log2 concentration in arbitrary units; a well without Ct after +40 cycles lies below -4. ### qPCR data -Column `lloq` holds the limit of each reading; an `NA` reading is censored there. Samples scatter -around their experiment course by 0.5 cycles (standard deviation), wells of a sample by 0.25. +Column `lloq` holds the limit of each reading; an `NA` reading is censored there. Standard +deviation 0.5 cycles between samples, 0.25 between wells. ```{r qpcrdata} ``` ### qPCR model -A reading is `yi + sj`, log2 concentration per time point plus experiment offset, with absolute -error. `technical = "well"` averages the wells arithmetically, since readings are already log2. A -sample with one well below the limit is censored at the mean of the other well and the limit. +A reading is `yi + sj`, log2 concentration plus experiment offset, with absolute error. +`technical = "well"` averages the wells; a sample with one well below the limit is censored at the +mean of the other well and the limit. ```{r qpcrmodel} ``` ### qPCR fit -The mean of the values is held at 0; differences to the untreated value are log2 fold changes. +The mean of the values is held at 0; `log2fc` is relative to the untreated value. ```{r qpcrfit, eval = FALSE} ``` @@ -230,8 +202,7 @@ a$log2fc <- a$estimate - a$estimate[a$time == 0] cbind(a[c("time", "estimate", "se", "log2fc")], simulated = log2fold[match(a$time, times)]) ``` -Duplicate means per experiment before and after alignment; censored samples enter by the limit -and are not drawn. +Sample means before and after alignment, censored samples not drawn: ```{r} s <- fit$scaled[!fit$scaled$bloq, ] @@ -243,7 +214,7 @@ both$stage <- factor(both$stage, c("before", "after")) ggplot(both, aes(factor(time), value, color = experiment)) + geom_point() + facet_wrap(~ stage) + labs(x = "time [h]", y = "log2(conc.) [a.u.]", color = "experiment") + - scale_color_dMod() + theme_dMod() + scale_color_dMod2() + theme_dMod2() ``` ```{r fig.height = 3.5} @@ -261,41 +232,31 @@ as.datalist(fit) ## Western blot and targeted mass spectrometry -A phosphoprotein after ligand stimulation, quantified on ten gels and by targeted mass -spectrometry. Five gels hold a short course up to 4 h, five a long one up to 48 h, sharing only the -untreated lane and 4 h. Each gel holds four time points of one course on a separate scale, the long -gels far lower. Each gel adds a background (the membrane signal around the bands), scaled with the -bands by the image; it shows on weak lanes, untreated and late, and hides under the others. With a -background per gel, untreated level and typical background are told apart only by the variation -between gels: a normal random effect per gel. Mass spectrometry measures nM at four time points of -both courses, three samples each. These readings are marked in column `absolute`, predicted by the -expression `absolute` (by default the first biological symbol), depend on no scaling parameter and -have gel `NA`; their block is not normalized but comes out in nM. +A phosphoprotein on ten gels, five with a short course up to 4 h and five with a long one up to +48 h, sharing the untreated lane and 4 h, and by targeted mass spectrometry in nM at four time +points. The background per gel is a normal random effect. Mass spectrometry readings are marked in +column `absolute`, predicted by the expression `absolute` (by default the first biological symbol) +and have gel `NA`; the block comes out in nM. ### Blot and mass spectrometry data -One row per reading: log2 of the band in arbitrary units or of the concentration in nM. Short -course gels S1 to S5, long course L1 to L5. +Log2 band in arbitrary units or log2 concentration in nM; gels S1 to S5 short, L1 to L5 long. ```{r wbdata} ``` ### Blot and mass spectrometry model -A band reads `log2(2^yi + 2^(b + bj)) + sj`: log2 concentration `yi` in nM per time point plus -background, shifted by `sj` per gel. The log2 background is the common fixed `b` plus `bj`, a -normal random effect around 0 per gel. A mass spectrometry reading is `yi`. Errors are absolute, -one per method. The data say little about the background (small spread, hidden by bands), so a -prior holds the standard deviation of `bj` near 0.3 (`omega_bj_bj`, the log of that standard -deviation, normal around $\log 0.3$ with standard deviation 0.3), and a weak prior puts `b` around 1 nM (normal around 0, standard -deviation 2). +A band reads `log2(2^yi + 2^(b + bj)) + sj`, a mass spectrometry reading `yi`, with absolute +error per method. Priors: `omega_bj_bj` normal around $\log 0.3$ with standard deviation 0.3, `b` +normal around 0 with standard deviation 2. ```{r wbmodel} ``` ### Blot and mass spectrometry fit -Values come out as log2 concentrations in nM, also at time points without mass spectrometry: +Values in log2 nM, also at time points without mass spectrometry: ```{r wbfit, eval = FALSE} ``` @@ -318,8 +279,7 @@ round(2^p[["b"]], 2) c(MS = exp(p[["sigma"]]), WB = exp(p[["sigma"]] + p[["sigma_methodWB"]])) ``` -Readings per gel and of mass spectrometry before (bands in arbitrary units, mass spectrometry in -nM) and after alignment (all in nM); absolute readings stay unchanged: +Readings before and after alignment; absolute readings stay unchanged: ```{r} s <- fit$scaled @@ -335,7 +295,7 @@ ggplot(both[is.finite(both$reading), ], aes(factor(time), reading, color = gel, geom_point() + facet_wrap(~ panel, scales = "free_y") + guides(x = guide_axis(angle = 45)) + labs(x = "time [min]", y = "log2(conc.)", color = "gel", shape = "method") + - scale_color_dMod(palette = "dMod") + theme_dMod() + theme(legend.position = "bottom") + scale_color_dMod2(palette = "dMod") + theme_dMod2() + theme(legend.position = "bottom") ``` ```{r fig.height = 3.5} @@ -349,33 +309,27 @@ plotResiduals(fit) ### Random background Standard deviation of the log2 background between gels, and per gel the mode with conditional -standard error. The standard deviation lies near the prior mean, so it comes mostly from the -prior. +standard error: ```{r} fit$omega fit$random ``` -The shrinkage $1 - \operatorname{SD}(\text{modes}) / \omega$ measures how much the data know about -the random effect of one gel; where bands hide the background, the mode stays near 0. Aligned -values, `b` and $\omega$ integrate over the random effects and do not depend on the modes; a mode -is no measurement of the gel background, and plots of modes look too narrow. +Shrinkage $1 - \operatorname{SD}(\text{modes}) / \omega$; aligned values, `b` and $\omega$ do +not depend on the modes. ```{r} fit$fit$shrinkage ``` -Conditional draws of the random effects against the estimated normal, which they follow -whatever the shrinkage. At high shrinkage the draws mostly repeat that normal, so the plot could -hardly reveal a background distributed otherwise. +Conditional draws against the estimated normal: ```{r fig.height = 5} plotRandomEffects(fit$fit) ``` -Readings against the individual prediction (IPRED, random effects at the modes) and the -population prediction (PRED, every gel at the population background): +Individual (IPRED) and population prediction (PRED): ```{r fig.height = 3.5} plot(fit$fit) + theme(legend.position = "right") + labs(color = "gel") diff --git a/vignettes/articles/guide-model.Rmd b/vignettes/articles/guide-model.Rmd index 74e96ac0..37c33749 100644 --- a/vignettes/articles/guide-model.Rmd +++ b/vignettes/articles/guide-model.Rmd @@ -14,51 +14,46 @@ source("results/stored.R") knitr::read_chunk("../../examples/oppeltNPJSystBiolAppl2018/model.R") ``` -A model in dMod2 is a chain of function objects, each returning an output together with the -derivatives with respect to the parameters: +A model in dMod2 is a chain of function objects, each returning output and derivatives: | class | constructors | mapping | |---|---|---| -| `parfn` | `P()`, `Pexpl()`, `Pimpl()` | outer to inner parameters per condition, or parameters to a steady state (`Pimpl()`) | -| `prdfn` | `Xs()`, `Xf()` | parameters to state trajectories, with sensitivities (`Xs()`) or without (`Xf()`) | -| `obsfn` | `Y()` | states to observables, observables to standard deviations (error model) | -| `objfn` | `normL2()`, `constraintL2()`, `datapointL2()`, `constraintStability()` | parameters to $-2 \log L$ with gradient and Hessian | +| `parfn` | `P()`, `Pexpl()`, `Pimpl()` | outer to inner parameters, or to a steady state | +| `prdfn` | `Xs()`, `Xf()` | parameters to trajectories, with (`Xs()`) or without sensitivities | +| `obsfn` | `Y()` | states to observables, observables to standard deviations | +| `objfn` | `normL2()`, `constraintL2()`, `datapointL2()`, `constraintStability()` | $-2 \log L$ | -`*` concatenates two objects by the chain rule. For $y = g(x(p(\theta)))$, +`*` concatenates by the chain rule, $$\frac{\partial y}{\partial \theta} = \frac{\partial g}{\partial x}\,\frac{\partial x}{\partial p}\, \frac{\partial p}{\partial \theta},$$ -each factor computed exactly by the object it belongs to, the middle one from the sensitivity equations. -`g*x*pSS*p` maps the outer parameters to the observables of all conditions, -`normL2(data, g*x*pSS*p, e)` is the objective, and `+` adds objectives, e.g. a prior. Inner -parameters are the symbols of the equations, with values per condition; outer parameters are -those of the fit, shared by all conditions they enter. +each factor exact, the middle one from the sensitivity equations; `+` adds objectives. +`normL2(data, g*x*pSS*p, e)` is the objective. Inner parameters are the symbols of the equations, +per condition; outer parameters are those of the fit. The guide uses the model of Oppelt et al. [@oppelt2018model], NFκB signaling in HepG2 cells after TNFα, from the project [`examples/oppeltNPJSystBiolAppl2018`](https://github.com/dModverse/dMod2/tree/master/examples/oppeltNPJSystBiolAppl2018). -This chapter follows `model.R`, the full model of the publication. +This chapter follows `model.R`. Multistarts, profiles and other expensive results were computed +once by the scripts of the project and are stored in `results/*.rds`; the chapters load them with +`stored()`, which warns if a source script changed since. ```{r setup} ``` ## Reaction network -TNFα activates the receptor, the receptor activates IKK, and IKK phosphorylates IκBα and NFκB in -their complex. Phosphorylated IκBα is degraded, free NFκB enters the nucleus and induces IκBα and -A20. IκBα exports NFκB, A20 inhibits IKK activation; the two negative feedbacks give damped -oscillations of nuclear NFκB. IKK passes through the states `Ikk`, `pIkk`, `ppIkk` and the -refractory `iIkk`. +TNFα activates the receptor, the receptor IKK, and IKK phosphorylates IκBα and NFκB in their +complex. Free NFκB enters the nucleus and induces IκBα and A20, the two negative feedbacks. -`addReaction()` adds a reaction to an `eqnlist`. `assignCompartment()` places the four nuclear -species in the nucleus of volume `Vnuc` relative to the cytoplasm. Rates are concentration rates -in the compartment of the educts, of the products for a reaction without net educts, so +`addReaction()` adds a reaction to an `eqnlist`; `assignCompartment()` places the nuclear species +in the nucleus of relative volume `Vnuc`. Rates are concentration rates in the compartment of the +educts (of the products without net educts): $$\dot x_i = \frac{1}{V_i} \sum_r S_{ri}\, V_{c(r)}\, v_r(x, p),$$ with $S_{ri}$ the stoichiometry and $V_{c(r)}$ the volume of the compartment of reaction $r$. -TNFα is not used up: the reaction `TNF -> TNF + TNFR` keeps it constant as a catalyst. ```{r reactions, echo = FALSE} ``` @@ -91,9 +86,8 @@ knitr::kable(data.frame(reaction = paste(side(written$from), "→", side(written Expressions follow the -[expression language of cppDE](https://dmodverse.github.io/cppDE/reference/expressions.html). -Factors named `eta_` relate two rates, e.g. `eta_form_complex_nuc` the nuclear to the cytoplasmic -complex formation. +[expression language of cppDE](https://dmodverse.github.io/cppDE/reference/expressions.html); +factors `eta_` relate two rates. ```{r} length(reactions$states) @@ -102,10 +96,8 @@ as.eqnvec(reactions)[c("NfkIkb", "nNfk", "TNF", "TNFR")] ## Observation functions -The data are live-cell imaging of NFκB and A20-GFP, immunoblots of the cytoplasm, and immunoblots -after immunoprecipitation of NFκB or IκBα. Each readout but the ratio `ratioNFkBIkBa` measures a -sum of species up to a scale `s_` and an offset `off_`; imaging signals bleach with rate `tau_`. On the natural log scale of -the data, +Readouts (live-cell imaging, immunoblots) are sums of species with scale `s_`, offset `off_` and, +for imaging, bleaching rate `tau_`, on the natural log scale: $$y = \log(s\, x + o) - \tau t .$$ @@ -114,48 +106,45 @@ $$y = \log(s\, x + o) - \tau t .$$ ## Error model -Blots have a standard deviation per point in the column `sigma`. The imaging readouts get an -estimated standard deviation on the log scale; rows with a value in `sigma` ignore the error model. +Blots have a standard deviation per point in the column `sigma`; imaging readouts get an +estimated one. Rows with a value in `sigma` ignore the error model. ```{r errors} ``` ## Steady-state constraints -The cells rest before TNFα. NFκB and IKK are conserved, so $f(x, p) = 0$ determines the resting -state only together with the totals: +NFκB and IKK are conserved, so $f(x, p) = 0$ determines the resting state only with the totals: ```{r} conservedQuantities(reactions) ``` -`Pimpl()` solves the steady state numerically in every evaluation, with the totals `totalNfk` and -`totalIkk` as parameters, `TNF` held at 0, and exact derivatives of the root -([Methods > Steady states](methods-steady-states.html)). `steadyStates()`, the analytic -alternative, finds no positive closed form for this network. +`Pimpl()` solves the steady state numerically, with the totals `totalNfk` and `totalIkk` as +parameters, `TNF` at 0, and exact derivatives of the root +([Methods > Steady states](methods-steady-states.html)). `steadyStates()` is the analytic +alternative. ```{r steadystate} ``` ## Events and switches -TNFα is added at time 0: an event replaces `TNF` by `dose_TNF`, 1 under stimulation and 0 in the -control. Event times and values may be parameters; the sensitivities pass the event. A switch on a -state needs no event: `"piecewise(kon, A > A0, koff)"` switches the rate when `A` crosses `A0`, -with exact sensitivities ([cppDE > Events](https://dmodverse.github.io/cppDE/articles/methods-events.html)). +An event at time 0 sets `TNF` to `dose_TNF`, 1 under stimulation, 0 in the control. Event times +and values may be parameters. `"piecewise(kon, A > A0, koff)"` switches a rate on a state, with +exact sensitivities +([cppDE > Events](https://dmodverse.github.io/cppDE/articles/methods-events.html)). ## Prediction functions -`odemodel()` generates C++ code for the right-hand side and the sensitivity equations; `Xs()` turns -it into the `prdfn` `x`, `Y()` builds the observables `g` and the error model `e`. `compile = -FALSE` defers compilation to one joint `compile()`. +`odemodel()` generates C++ code for the ODE and the sensitivity equations, `Xs()` the `prdfn` `x`, +`Y()` the observables `g` and the error model `e`; `compile = FALSE` defers to one `compile()`. ```{r odemodel} ``` -The default backend `"cppDE"` integrates by BDF with first- and, with `deriv2 = TRUE`, -second-order sensitivities; `backend = "Sundials"` uses CVODES, `"deSolve"` deSolve. A step is -accepted if the weighted RMS norm of the local errors is at most one, +The backend `"cppDE"` (default) integrates by BDF, `"Sundials"` uses CVODES, `"deSolve"` deSolve. +A step is accepted if $\bigl(\tfrac1n \sum_i \varepsilon_i^2 / (\mathrm{atol} + \mathrm{rtol}\,|x_i|)^2\bigr)^{1/2} \le 1$: | option | default | controls | @@ -166,13 +155,11 @@ $\bigl(\tfrac1n \sum_i \varepsilon_i^2 / (\mathrm{atol} + \mathrm{rtol}\,|x_i|)^ | `hini` | `0` | first step, 0 estimates it | | `sensErrCon` | `TRUE` | (`optionsSens` only) sensitivities in the error test | -Logarithmic observables magnify the relative error of small states; `model.R` sets -`rtol = 1e-8`, `atol = 1e-10`. +`model.R` sets `rtol = 1e-8`, `atol = 1e-10`, since log observables magnify errors of small states. ## Experimental data -`model.R` reads the CSV of the publication and keeps HepG2 cells without compound: 312 points in -two conditions. +HepG2 cells without compound: 312 points in two conditions. ```{r data} ``` @@ -182,9 +169,6 @@ table(hepg2$name, hepg2$condition) covariates(data) ``` -`as.datalist()` splits the data by condition; `covariates()` lists the columns that describe the -conditions. - ```{r, fig.height = 5} plotData(data, name %in% c("nucNFkB", "cytNFkB", "A20GFP", "IkBa", "pIkBa", "pIKK")) + ggplot2::labs(x = "time [min]", y = "log signal [a.u.]") @@ -209,8 +193,7 @@ getEquations(p, conditions = "TNF")[c("dose_TNF", "TNF", "totalNfk", "Vnuc")] getEquations(p, conditions = "control")[c("dose_TNF", "TNF")] ``` -`compile()` builds all sources into one shared object in `getOption("dMod2.outdir")` and reuses -object files whose source and flags are unchanged. +`compile()` builds one shared object in `getOption("dMod2.outdir")`, reusing unchanged objects. ```{r compile} ``` @@ -223,10 +206,8 @@ length(getParameters(prd)) `normL2(data, prd, e)` returns $-2 \log L$ with gradient and Gauss-Newton Hessian ([Methods > Likelihood and prior](methods-objective.html)). `constraintL2()` adds a Gaussian prior -on the log scale, which keeps parameters the data do not determine finite; the multistart of -[Optimization](guide-optimization.html) draws the starts from it. Mean 0 and standard deviation 4, -a factor of $e^4 \approx 55$, for parameters of unknown magnitude; narrower where the magnitude is -known: +on the log scale, also the start distribution of [Optimization](guide-optimization.html): mean 0 +and standard deviation 4 by default, narrower where the magnitude is known: | parameters | mean | sd | reason | |---|---|---|---| @@ -236,14 +217,10 @@ known: | `shuttle_RnaA20`, `degrad_RnaA20`, `build_A20`, `degrad_A20`, `degrad_mIkb` | $\log(1/60)$ | 2 | transcripts and A20 turn over within about an hour | | `trigger_iIkk` | $\log(1/240)$ | 2 | IKK recovers over hours | -Starts far outside these ranges end on plateaus where a signal bleaches away, the noise explains -every residual or A20 follows NFκB within minutes. - -`pSS` returns unstable roots too (`controlsPTC = list(stability = FALSE)`); -`constraintStability()` adds a term that is zero on a stable resting state, rises on a narrow ramp -below the stability boundary and reaches 100 for each eigenvalue at the boundary. It needs -`Pimpl(deriv2 = TRUE)`. Profiles with `stop = "data"` and likelihood ratios read the data term -without it ([Methods > Steady states](methods-steady-states.html#stability)). +`pSS` also returns unstable roots (`controlsPTC = list(stability = FALSE)`); +`constraintStability()` is zero on a stable resting state and reaches 100 per eigenvalue at the +stability boundary, and needs `Pimpl(deriv2 = TRUE)` +([Methods > Steady states](methods-steady-states.html#stability)). ```{r objective} ``` @@ -257,8 +234,8 @@ without it ([Methods > Steady states](methods-steady-states.html#stability)). invisible(stored("results/fits.rds", "fit.R")) ``` -At the best fit of [Optimization](guide-optimization.html), with the parameters fixed by the gauge -of [Symmetries](guide-symmetries.html): +The best fit of [Optimization](guide-optimization.html), with the gauge of +[Symmetries](guide-symmetries.html): ```{r gauge, echo = FALSE} ``` @@ -270,8 +247,7 @@ c(value = value$value, data = attr(value, "data"), prior = attr(value, "prior")) max(abs(value$gradient)) ``` -The prediction against the data, with one standard deviation of the error model as a band, -each observable up to the last time point of the data: +Prediction and data, with one standard deviation of the error model as a band: ```{r, fig.height = 7} times <- seq(0, 360, length.out = 361) diff --git a/vignettes/articles/guide-nlme.Rmd b/vignettes/articles/guide-nlme.Rmd index 579ca166..7e71ec74 100644 --- a/vignettes/articles/guide-nlme.Rmd +++ b/vignettes/articles/guide-nlme.Rmd @@ -14,33 +14,28 @@ source("results/stored.R") do.call(knitr::read_chunk, list(file.path("results", "guide-nlme.R"))) ``` -A mixed-effects model writes each individual parameter (subject, cell, cell line) as a -population value plus a random deviation, estimates population values and spread, and integrates -the deviations out of the likelihood. In dMod2 random effects are declared in the `parfn`; `em()` -fits by the EM algorithm with one of four approximations of the integral. Example: -theophylline, twelve subjects, one oral dose each, plasma concentrations over a day. +A mixed-effects model writes each individual parameter as a population value plus a random +deviation and integrates the deviations out of the likelihood. Random effects are declared in the +`parfn`; `em()` fits the model. Example: theophylline, twelve subjects, one oral dose each. ```{r setup} ``` ## Pharmacokinetic model -The dose enters a depot, is absorbed into the central compartment of volume $V$ and cleared by the -flux $\mathrm{Cl}\, C_c$ in the unit frame: clearance $\mathrm{Cl}$ is a volume per time, the -concentration falls at rate $\mathrm{Cl}/V$. +Depot, central compartment of volume $V$, clearance $\mathrm{Cl}$ (volume per time). ```{r reactions} ``` -`em()` needs second derivatives: build with `deriv2 = TRUE` and the forward-over-reverse -derivative modes. +`em()` needs second derivatives: `deriv2 = TRUE` and the forward-over-reverse derivative modes. ```{r model} ``` ## Theophylline data -Each subject is a condition; the condition table holds dose in mg and body weight. +One condition per subject; the condition table holds dose in mg and body weight. ```{r data} ``` @@ -53,17 +48,16 @@ plotData(data) + ## Random-effect formulas -`define("x <- x", x = ...)` starts the transformation as in [Setting up models](guide-model.html), -`branch()` copies it per table row, and `insert()` sets the dose into the depot, an empty central -compartment and log-scale parameters. An effect formula turns a symbol into a linear predictor with -fixed and random effects in lme4 notation: +`define()` starts the transformation as in [Setting up models](guide-model.html), `branch()` +copies it per table row, `insert()` sets dose, initial values and log parameters. Effect formulas +in lme4 notation give the linear predictors: ```{r trafo} ``` -The formula acts after the log transformation, so $\log \mathrm{Cl}_i = \mathrm{Cl} + -\eta_{\mathrm{Cl},i}$, $\eta_{\mathrm{Cl},i} \sim \mathcal{N}(0, \omega_{\mathrm{Cl}}^2)$: log-normal -individual parameters. Further forms: +The formula acts after the log transformation: $\log \mathrm{Cl}_i = \mathrm{Cl} + +\eta_{\mathrm{Cl},i}$, $\eta_{\mathrm{Cl},i} \sim \mathcal{N}(0, \omega_{\mathrm{Cl}}^2)$. +Further forms: - `Cl ~ 1 + (1 | ID)`: random intercept per subject. - `Cl ~ 1 + logWeight + (1 | ID)`: a covariate, fixed effect `Cl_logWeight` on a table column. @@ -73,21 +67,16 @@ individual parameters. Further forms: - `Cl ~ 1 + (1 | ID) + (1 | ID:OCC)`: variability between subjects and between occasions. - `Cl ~ 1 + (1 | gr(ID, dist = spikeSlab()))`: spike-and-slab instead of normal random effects. -A group (a level of the grouping, such as a subject) may own several conditions, which share the -group random effects; a condition outside every group has none. The random effects of one ID, or of one -term without ID, form a block with full covariance, so $\Omega$ is block diagonal; `omega__` -are the entries of the Cholesky factor of each block, with the log of the factor diagonal on the diagonal, -for a random effect alone in a block the log of the standard deviation of that effect. -This chapter treats normal random effects; spike-and-slab and Dirichlet-process ones are in +Conditions of one group share the group random effects. The random effects of one ID form a block +with full covariance; `omega__` are the entries of the Cholesky factor of the block, with +the log of the diagonal. Spike-and-slab and Dirichlet-process random effects: [Sparse deviations](guide-sparse-deviations.html). ## Marginal likelihood `em()` maximizes the likelihood of fixed effects, $\Omega$ and error parameters with the random -effects of every group integrated out. It takes the data objective -`normL2(data, g * x * p, errmodel = e)` and builds the random-effect prior from `randomEffects(p)`; -`normT(..., df = 4)` instead of `normL2()` gives Student-t residuals. `method` picks the -approximation: +effects integrated out. It takes `normL2(data, g * x * p, errmodel = e)`, or `normT(..., df = 4)` +for Student-t residuals, and builds the prior from `randomEffects(p)`. `method`: | method | use | reported $-2 \log L$ | |---|---|---| @@ -96,19 +85,18 @@ approximation: | `"laplaceEM"` | EM on the Laplace approximation | quadrature of level $K + 2$ | | `"saem"` | many random effects per group, non-Gaussian posteriors | quadrature of level $K + 2$ | -$K$ is the number of random effects of a group. Derivations: [Methods > Marginal likelihood](methods-nlme.html#marginal-likelihood) and +$K$ is the number of random effects of a group. Derivations: +[Methods > Marginal likelihood](methods-nlme.html#marginal-likelihood), [Methods > EM algorithm](methods-nlme.html#em-algorithm). ## First-order conditional estimation (FOCEI) -First-order conditional estimation with interaction replaces each integral by Laplace's -approximation at the mode of the group; $-2 \log L$ may lie above or below the exact one. Inner -and outer trust regions and gradient: [Methods > FOCEI](methods-nlme.html#focei). +Laplace's approximation at the mode of each group, [Methods > FOCEI](methods-nlme.html#focei). ### FOCEI fit -`init` holds the parameters that are neither random effects nor created by effect formulas (those -start at 0); random-effect standard deviations start at `control$sd`. +`init` holds the parameters other than random effects and effect-formula coefficients (those start +at 0); standard deviations start at `control$sd`. ```{r focei, eval = FALSE} ``` @@ -123,21 +111,19 @@ fit[model] <- em(obj, random, fit, control = list(trustControl = list(iterlim = verbose = FALSE)[model] ``` +The fit is loaded from `results/guide-nlme.rds`, computed by `results/guide-nlme.R`. + ```{r, echo = FALSE} summary(fit) ``` -Every block here holds one random effect, so `omega_*` are log standard deviations, shown on -natural scale in the random-effects table. -Shrinkage near 0 means the modes spread as widely as the random effects, near 1 that the data of a -subject hardly move the individual parameter. +`omega_*` are log standard deviations here. Shrinkage near 1 means the data of a subject hardly +move the individual parameter. -`value` is $-2 \log L$ with all data constants; `valueNonmem`, $-2 \log L$ less $\log(2\pi)$ per -reading above the limit of quantification, compares with the NONMEM `OBJ` (`NA` for `normT()`). The fit holds `argument`, `Omega`, -`omega` (standard deviations and correlations with standard errors), `random` (modes per group with -conditional standard errors), `etaModes`, `etaSE` and `shrinkage`. Methods: `coef()`, `vcov()`, -`confint()` (Wald or `method = "profile"`), `logLik()`, `AIC()`, `BIC()`, `anova()` of nested fits, -`predict()` (individual and population), `residuals()`, `simulate()` and the plots below. +`value` is $-2 \log L$; `valueNonmem` compares with the NONMEM `OBJ` (`NA` for `normT()`). The fit +holds `Omega`, `omega`, `random`, `etaModes`, `etaSE` and `shrinkage`. Methods: `coef()`, `vcov()`, +`confint()` (Wald or `method = "profile"`), `logLik()`, `AIC()`, `BIC()`, `anova()`, `predict()`, +`residuals()`, `simulate()` and the plots below. ### FOCEI settings @@ -149,20 +135,16 @@ conditional standard errors), `etaModes`, `etaSE` and `shrinkage`. Methods: `coe | `derivMode` | `"forward-reverse"` | volume-term second derivatives, or `"forward-forward"` | | `secondOrderCorrection` | `TRUE` | derivative of the volume term | -`"forward-forward"` needs `deriv2 = TRUE`; `summary()` says whether the Hessian is exact; -`secondOrderCorrection = FALSE` biases the estimates -([Methods > Volume term](methods-nlme.html#volume-term)). `fixed` holds parameters at given values. -`sparse = TRUE` uses sparse Hessians for many fixed effects, `"auto"` decides as `trust()`. The -outer `mtol` is a predicted change of $10^{-5}$ in $-2 \log L$, the inner tolerances are tighter; -the solver error must stay below them. `em(cores = )` spreads groups and conditions over threads, -[Remote computing](guide-remote-computing.html#threads-and-processes). +`"forward-forward"` needs `deriv2 = TRUE`. `secondOrderCorrection = FALSE` biases the estimates +([Methods > Volume term](methods-nlme.html#volume-term)). `fixed` holds parameters at given values, +`sparse = TRUE` uses sparse Hessians. The solver error must stay below the tolerances. +`em(cores = )`: [Remote computing](guide-remote-computing.html#threads-and-processes). ## Adaptive sparse-grid quadrature -Laplace's approximation biases $\Omega$ most for skewed posteriors, e.g. oral doses sampled near -absorption. `method = "quadrature"` starts from the converged FOCEI fit and integrates on a sparse -grid around each group mode at the level `tol` requires; level $K$ is Laplace's approximation. A -certificate flags groups whose posterior the grid does not resolve. Grid, stages and certificate: [Methods > Adaptive sparse-grid +`method = "quadrature"` starts from the FOCEI fit and integrates on a sparse grid around each group +mode; level $K$ is Laplace's approximation. A certificate flags groups whose posterior the grid +does not resolve. [Methods > Adaptive sparse-grid quadrature](methods-nlme.html#adaptive-sparse-grid-quadrature). | entry of `control$quadrature` | default | controls | @@ -176,26 +158,21 @@ quadrature](methods-nlme.html#adaptive-sparse-grid-quadrature). | `pruneTol` | `Inf` | drop nodes with log weight this far below the largest | | `certificate` | `points = 256`, `seed = 1` | importance-sampling check, `FALSE` skips | -A quadrature fit holds `stageTrace` (per rebuild: stage level, value, Newton decrement, -resolution, highest level, node count), `etaCov` (posterior covariance -$\hat M_i - \hat m_i \hat m_i^\top$ per group) and `certificate`. `plotTrace(fit)` draws the trace, -`plotRandomEffects(fit)` histograms and QQ plots of conditional draws, or with `type = "modes"` of -the modes, against the fitted $\mathcal{N}(0, \Omega_{kk})$ (see [Model diagnostics](#model-diagnostics)). +The fit holds `stageTrace`, `etaCov` (posterior covariance per group) and `certificate`; +`plotTrace(fit)` draws the trace. ## Laplace EM -`method = "laplaceEM"` runs expectation conditional maximization on the Laplace approximation and -reports the quadrature of level $K + 2$. Settings in `control$quadrature`: convergence tolerance -`epsEcm` (default `1e-5`), iterations `maxEcm` (default 200), and of the quadrature above -`cm1Control`, `maxCm1Iter`, `pruneTol` and `maxLevel`; the levels are $K + 1$ and $K + 2$, and the -fit has no certificate. Details: [Methods > Laplace EM](methods-nlme.html#laplace-em). +`method = "laplaceEM"`: expectation conditional maximization on the Laplace approximation, +reporting the quadrature of level $K + 2$, without certificate. `control$quadrature` takes `epsEcm` +(default `1e-5`), `maxEcm` (default 200) and `cm1Control`, `maxCm1Iter`, `pruneTol`, `maxLevel`. +[Methods > Laplace EM](methods-nlme.html#laplace-em). ## Stochastic approximation EM (SAEM) -`method = "saem"` draws the random effects from the posterior and averages over iterations, after -a burn-in with falling step sizes; suited to many random effects and skewed, heavy-tailed or -multimodal posteriors. `set.seed()` reproduces a fit. `em()` reports the quadrature of level -$K + 2$ at the estimate, with standard errors from the Hessian of that quadrature. Details: [Methods > SAEM](methods-nlme.html#saem). +`method = "saem"` samples the random effects from the posterior and averages over iterations after +a burn-in; `set.seed()` reproduces a fit. Value and standard errors come from the quadrature of +level $K + 2$. [Methods > SAEM](methods-nlme.html#saem). | entry of `control$saem` | default | controls | |---|---|---| @@ -226,23 +203,19 @@ laplaceEM <- chapter$laplaceEM round(c(laplaceEM$argument[names(fit$argument)], minus2logL = laplaceEM$value), 3) ``` -Estimates agree within their standard errors. Each $-2 \log L$ approximates the same integral; -Laplace EM and SAEM report the quadrature. FOCEI may lie below it: Laplace's method is no bound, -and a lower value is approximation error, not a better fit. Stage trace and certificate of the -quadrature fit: +Estimates agree within their standard errors. FOCEI may lie below the quadrature: Laplace's method +is no bound. ```{r} fits$quadrature$stageTrace[, c("level", "ecmIter", "OFV", "decrement", "resolution", "maxLevel", "nodes")] fits$quadrature$certificate ``` -`r q <- fits$quadrature$stageTrace; if (nrow(q) == 1 && q$decrement[1] < q$resolution[1]) "Here one rebuild ends the fit: the Newton decrement on the rebuilt nodes lies below what the nodes resolve, so the estimate of FOCEI stands, with the value of the quadrature." else sprintf("Here the fit takes %d rebuilds.", nrow(q))` `r flagged <- sum(fits$quadrature$certificate$flag); if (flagged == 0) "No group is flagged." else sprintf("%d of %d groups are flagged.", flagged, nrow(fits$quadrature$certificate))` `plotTrace()` draws the trace of a fit with -several rebuilds. +`r q <- fits$quadrature$stageTrace; if (nrow(q) == 1 && q$decrement[1] < q$resolution[1]) "Here one rebuild ends the fit: the Newton decrement on the rebuilt nodes lies below what the nodes resolve, so the estimate of FOCEI stands, with the value of the quadrature." else sprintf("Here the fit takes %d rebuilds.", nrow(q))` `r flagged <- sum(fits$quadrature$certificate$flag); if (flagged == 0) "No group is flagged." else sprintf("%d of %d groups are flagged.", flagged, nrow(fits$quadrature$certificate))` ## Model diagnostics -`plotCombined()` draws each subject with individual (IPRED, random effects at the modes) and -population prediction (PRED, random effects 0): +Individual (IPRED, random effects at the modes) and population prediction (PRED, random effects 0): ```{r, fig.height = 6.5} plotCombined(fit, ncol = 4) + @@ -250,28 +223,25 @@ plotCombined(fit, ncol = 4) + ``` Conditional weighted residuals (CWRES) linearize around the modes; normalized prediction -distribution errors (NPDE) come from simulations, decorrelated per subject, without -linearization. Both should look like standard normal noise against prediction and time. +distribution errors (NPDE) come from simulations. Both should be standard normal. ```{r, fig.height = 6} plotResiduals(fit, type = c("CWRES", "NPDE"), nsim = 200, seed = 1) ``` -The visual predictive check compares data percentiles with simulated prediction intervals per -time bin. +Visual predictive check: ```{r, fig.height = 3.5} plotVPC(fit, nsim = 200, bins = 8, seed = 1) ``` -Histograms and QQ plots of draws from the conditional distributions of the random effects -against the fitted $\mathcal{N}(0, \Omega_{kk})$: +Conditional draws of the random effects against the fitted $\mathcal{N}(0, \Omega_{kk})$: ```{r, fig.height = 5} plotRandomEffects(fit) ``` -Against a covariate, random effects show whether it explains part of the variability: +Random effects against a covariate: ```{r, fig.height = 3.5} plotRandomEffects(fit, covariates = table["weight"]) @@ -279,8 +249,7 @@ plotRandomEffects(fit, covariates = table["weight"]) ## Covariate effects -Clearance and volume usually scale with body weight, entered as a fixed effect on a table column, -centered on log scale: +Body weight as a fixed effect on a table column, centered on log scale: ```{r covariates, eval = FALSE} ``` @@ -292,28 +261,27 @@ comparison ``` `anova()` compares nested fits by likelihood ratio. Weight lowers $-2 \log L$ by -`r round(comparison$chisq[2], 2)`, p-value `r round(comparison$p[2], 2)`: among twelve subjects of -similar weight it explains little clearance spread, and the simpler model stays. +`r round(comparison$chisq[2], 2)`, p-value `r round(comparison$p[2], 2)`; the simpler model stays. ## Nested and crossed groups -Further groupings, nested (occasions within subjects) or crossed (patients and centers), are -further formula terms. `em()` integrates them by FOCEI per connected component of the conditions; -the [pharmacometrics project](pharmacometrics.html) fits mavoglurant with between-occasion -variability this way: +Nested groupings (occasions within subjects) or crossed ones (patients and centers) are further +formula terms, integrated by FOCEI per connected component of the conditions. The +[pharmacometrics project](pharmacometrics.html) fits mavoglurant with between-occasion variability: ```r insert(trafo, Cl ~ 1 + (1 | ID) + (1 | ID:OCC)) ``` -Which groups differ at all, rather than by how much: [Sparse deviations](guide-sparse-deviations.html). +Which groups differ at all: [Sparse deviations](guide-sparse-deviations.html). ## Multistart optimization -`msem()` runs `em()` from `fits` starts, the first at `init`, the others perturbed around it with -standard deviation `sd`, and returns the best fit, all starts in `$multistart`. `theophyllineMultistart.R` of the project -`pharmacometrics` runs 200 starts each for FOCEI, quadrature and SAEM from the same draws: +`msem()` runs `em()` from `fits` starts, the first at `init`, the others perturbed with standard +deviation `sd`, and returns the best fit, all starts in `$multistart`. `theophyllineMultistart.R` +of the project `pharmacometrics` runs 200 starts each for FOCEI, quadrature and SAEM; the result is +loaded from `results/multistart.rds` of the project. ```{r, include = FALSE, purl = FALSE} project <- normalizePath("../../examples/pharmacometrics") @@ -331,21 +299,20 @@ wide <- diff(range(values, na.rm = TRUE)) > 50 lowest <- vapply(saved$multistart, function(t) sum(t$value < min(t$value, na.rm = TRUE) + 1, na.rm = TRUE), 0) ``` -FOCEI waterfall of all 200 starts: +FOCEI: ```{r, fig.height = 3.5} plotValues(saved$multistart$FOCEI, pseudoLog = wide) ``` -Quadrature and SAEM, both valued by the quadrature, so comparable: +Quadrature and SAEM, both valued by the quadrature: ```{r, fig.height = 3.5} plotValues(saved$multistart[c("quadrature", "SAEM")], pseudoLog = wide) ``` -All three methods find the same two optima, with method-specific $-2 \log L$. Most starts end on -the upper plateau, the fit above; about `r round(mean(lowest))` of -`r nrow(saved$multistart[[1]])` per method reach the lower one, the flip-flop solution: +All three methods find the same two optima. About `r round(mean(lowest))` of +`r nrow(saved$multistart[[1]])` starts per method reach the lower one, the flip-flop solution: ```{r} flipflop <- saved$best$FOCEI @@ -354,18 +321,16 @@ signif(rbind(fit = c(exp(fit$argument[c("Ka", "V", "Cl")]), minus2logL = fit$val minus2logL = min(saved$multistart$FOCEI$value, na.rm = TRUE))), 4) ``` -With one oral dose and no intravenous data, absorption and elimination can swap. In the flip-flop -solution absorption is the slow step, the volume shrinks to -`r round(exp(flipflop[["V"]]), 1)` L and the `Ka` random effect vanishes. The likelihood prefers it -by `r round(fit$value - min(saved$multistart$FOCEI$value, na.rm = TRUE), 1)`, but theophylline -spreads through the body water, about 0.5 L/kg, not a few liters; drug knowledge or a prior on `V` -selects the upper plateau. +With one oral dose, absorption and elimination can swap: absorption becomes the slow step, the +volume shrinks to `r round(exp(flipflop[["V"]]), 1)` L and the `Ka` random effect vanishes. The +likelihood prefers it by `r round(fit$value - min(saved$multistart$FOCEI$value, na.rm = TRUE), 1)`, +but theophylline spreads through the body water, about 0.5 L/kg; a prior on `V` selects the upper +plateau. ### Zero variance components -At the flip-flop solution the `Ka` variance runs to 0. `em()` returns the fit with that variance at -0 and names it in `fit$boundary`; `control$boundary` (default 0.1) is the accepted rise of -$-2 \log L$, `FALSE` switches it off +A variance that runs to 0 is returned at 0 and named in `fit$boundary`; `control$boundary` +(default 0.1) is the accepted rise of $-2 \log L$, `FALSE` switches it off ([Methods > Zero variance components](methods-nlme.html#variance-at-the-boundary)). On the lower plateau every method does so: @@ -374,8 +339,7 @@ sapply(saved$multistart, function(t) sum(t$boundary == "omega_Ka_Ka")) sapply(saved$best, function(b) signif(b[c("Ka", "V", "Cl")], 4)) ``` -`theophyllineMultistart.R` refits the best fit of each method by every other method from the -estimates of that fit: +`theophyllineMultistart.R` refits the best fit of each method by every other method: ```{r crosscheck, eval = FALSE} ``` @@ -392,15 +356,13 @@ saemGap <- max(abs(byMethod$SAEM - quadratureValue)) saemGap <- ceiling(saemGap / 10^floor(log10(saemGap))) * 10^floor(log10(saemGap)) ``` -From every start each method reaches the same estimates, with method-specific $-2 \log L$: FOCEI -about `r signif(quadratureValue - mean(byMethod$FOCEI), 2)` below the quadrature, which integrates -more accurately than Laplace's method; SAEM, valued by the quadrature of level $K + 2$ at the SAEM -estimate, within `r saemGap` of it. +Each method reaches the same estimates from every start. FOCEI lies about +`r signif(quadratureValue - mean(byMethod$FOCEI), 2)` below the quadrature, SAEM within +`r saemGap` of it. `msem()` draws all starts and seeds before spreading fits over `cores`, so `set.seed()` reproduces -a run; `cores = c(fits = , conditions = )` splits cores between parallel fits and threads, see -[Remote computing](guide-remote-computing.html#threads-and-processes). Every start runs to -convergence; `plotValues()` draws `$multistart` as a waterfall. +a run; `cores = c(fits = , conditions = )`: see +[Remote computing](guide-remote-computing.html#threads-and-processes). Reference: `randomEffects()`, `em()`, `msem()`, `anova()`, `plotResiduals()`, `plotVPC()`, `plotRandomEffects()`, `plotTrace()`, `plotValues()` diff --git a/vignettes/articles/guide-optimization.Rmd b/vignettes/articles/guide-optimization.Rmd index 296bb9b8..3cd1086f 100644 --- a/vignettes/articles/guide-optimization.Rmd +++ b/vignettes/articles/guide-optimization.Rmd @@ -17,10 +17,9 @@ knitr::read_chunk("../../examples/oppeltNPJSystBiolAppl2018/onefit.R") knitr::read_chunk("../../examples/oppeltNPJSystBiolAppl2018/plots.R") ``` -dMod2 [@kaschek2019dmod] minimizes $-2 \log L$, with a prior $-2 \log$ of the posterior, by a -trust-region method on the exact gradient, `trust()`, run from many starts by `mstrust()`. The -fits below use the model of [Setting up models](guide-model.html) with the gauge of -[Symmetries](guide-symmetries.html), by `fit.R`, `onefit.R` and `plots.R` of the project. +dMod2 [@kaschek2019dmod] minimizes $-2 \log L$ (with a prior, $-2 \log$ of the posterior) by the +trust-region method `trust()`, from many starts by `mstrust()`, here on the model of +[Setting up models](guide-model.html) with the gauge of [Symmetries](guide-symmetries.html). Derivations: [Methods > Trust-region optimization](methods-trust.html). ```{r setup, echo = FALSE} @@ -61,17 +60,14 @@ Derivations: [Methods > Trust-region optimization](methods-trust.html). ## Trust-region method -Each iteration minimizes a quadratic model of the objective inside a ball of radius $r$; the ratio -of actual to predicted decrease decides on the step and the radius. `rinit` is the first radius in -the units of the parameters, on the log scale `0.1` is ten percent of a rate. A trial point at -which the objective fails counts as rejected, so no bounds are needed to keep a fit where the -model can be evaluated. `stepControl$nonmonotone` in $(0, 1)$ also accepts steps that raise the -value; the result is then the best iterate. +Each iteration minimizes a quadratic model inside a ball of radius $r$, first `rinit`; the ratio +of actual to predicted decrease decides on step and radius. A trial point where the objective fails +counts as rejected. `stepControl$nonmonotone` in $(0, 1)$ also accepts rising steps and returns the +best iterate. `parlower` and `parupper` set bounds. `boundary = "reflective"` (default) keeps the iterates -strictly inside and reports the parameters held by a bound in `atBound`; `boundary = "clip"` takes -them out of the subproblem, runs a single Gauss-Newton phase, reads only `ftol` and `mtol` and stops -with `"fvalue"` or `"iterlim"`. +strictly inside and lists bound parameters in `atBound`; `boundary = "clip"` removes them from the +subproblem and runs Gauss-Newton only, with `ftol` and `mtol`. ### Termination criteria @@ -83,17 +79,15 @@ with `"fvalue"` or `"iterlim"`. | `"fvalue"` | an accepted step changed the value by less than `ftol` | `TRUE` | | `"preddiff"` | predicted decrease below `mtol` | `TRUE` | | `"step"` | step norm below `xtol` (default 0, off) | `TRUE` | -| `"stagnation"` | five rejected steps in a row, value flat within `ftol` | `TRUE` | +| `"stagnation"` | five rejected steps in a row, value flat within `ftol` | `TRUE` where the full Newton step predicts at most `mtol` | | `"radius"` | radius below `rmin`, or a step that no longer changes the parameters | `FALSE` | | `"objfun"` | three failed evaluations in a row | `FALSE` | | `"iterlim"` | `iterlim` iterations | `FALSE` | -Only `"gradient"` tests first-order optimality; the last quasi-Newton phase ignores the value, -model and step tests ([Hessian phases](#hessian-phases-and-reverse-sweep)). `"gradient"`, -`"fvalue"` and `"preddiff"` end a run of `trust()` or `trustL1()` only where the full Newton step also predicts a decrease of -at most `mtol` ([Methods > Termination criteria](methods-trust.html#termination-criteria)). `ftol` and `gtol` -belong at or above the numerical error of value and gradient; `model.R` defines them as -`tolerances`, which the fitting scripts pass as `tolControl`. +`"gradient"`, `"fvalue"` and `"preddiff"` stop only where the full Newton step also predicts at +most `mtol` ([Methods > Termination criteria](methods-trust.html#termination-criteria)). `ftol` +and `gtol` belong at or above the numerical error; `model.R` defines them as `tolerances`, passed +as `tolControl`. ## Model Hessian @@ -104,26 +98,27 @@ belong at or above the numerical error of value and gradient; `model.R` defines | `"bfgs"` | damped BFGS update, positive definite | value, gradient | | `"sr1"` | symmetric rank-one update, possibly indefinite | value, gradient | -The exact Hessian needs second-order sensitivities, `deriv2 = TRUE` or `derivMode = -"forward-reverse"` ([Sensitivities](guide-sensitivities.html)). The quasi-Newton settings are -entries of `qnControl`: +The default is the hybrid of Fides [@froehlich2022fides]: Gauss-Newton until the radius stayed the +same for 20 iterations, then BFGS +([Methods > Hessian phases](methods-trust.html#hessian-phases)). +The sparse path, multiple shooting and `boundary = "clip"` run Gauss-Newton. `"exact"` needs +`deriv2 = TRUE` or `derivMode = "forward-reverse"` ([Sensitivities](guide-sensitivities.html)). +Quasi-Newton settings, entries of `qnControl`: | entry | default | controls | |---|---|---| -| `hessianInit` | `"gn"` | seed: Gauss-Newton at the start, `"identity"`, or `"exact"` | -| `hessianReseed` | `"never"` | `"stall"`: reseed at the current iterate instead of stopping on stagnation or on a step that no longer moves it, where the iterate moved since the last reseed, at most eight times per phase | +| `hessianInit` | `"gn"` | seed: `"gn"`, `"identity"`, `"exact"`, or `"tracked"` (later phases) | +| `hessianReseed` | `"never"` | `"stall"`: reseed instead of stopping on stagnation, up to 8 times | | `qnMemory` | `0` | `0` accumulates all updates; $m > 0$ rebuilds from the last $m$ pairs | | `qnCautious` | `1e-8` | cautious test of BFGS; `0` turns it off | | `qnRejected` | `TRUE` for `"sr1"` | SR1 also updates from rejected trial points | -With `hessianInit = "identity"` the objective needs to return gradients only. - ### Hessian phases and reverse sweep -`phases` runs several sources in turn. Each phase is a list with `hessianMethod` and optionally -`iterlim`, `sweep` and `qnControl`. A phase ends on a value, model, step or stagnation stop or on -the `iterlim` of the phase and hands over to the next; `"gradient"` ends the run. `switches` bounds the -handovers (default: one fewer than phases). +`phases` runs several sources in turn, each a list with `hessianMethod` and optionally `iterlim`, +`radiusStall`, `sweep`, `keepRadius`, `onStop` and `qnControl`. A phase hands over on a stop other +than `"gradient"`, on `iterlim` or after `radiusStall` iterations at one radius; `switches` bounds +the handovers. ```{r, eval = FALSE} fit <- trust(obj, best, fixed = gauge, tolControl = tolerances, @@ -132,19 +127,13 @@ fit[c("phaseIterations", "evalBySource", "nSwitch", "stopReason")] ``` `sweep = "reverse"` computes the gradient of a quasi-Newton phase by one backward sweep, for models -built with `derivMode = c("forward", "reverse")`; by default a `"bfgs"` or `"sr1"` phase of -`phases` sweeps backwards where it can, while a run without `phases` sweeps only with -`sweep = "reverse"`. With `phases`, `phaseSweep` reports the sweep per phase. +built with `derivMode = c("forward", "reverse")`; a `"bfgs"` or `"sr1"` phase does so by default. ### Sparse Hessians -`sparse = TRUE` solves the subproblem on sparse Cholesky factors of the Hessian, for many -parameters that each act on few conditions; a part of the Hessian that couples many parameters at -once, such as the normalization of an alignment, comes as a low-rank part. The steps, phases, -bounds and stops are those of the dense path, so both reach the same fit. The default `"auto"` -selects the sparse path from 100 parameters on where a step on the sparse Hessian costs fewer -flops than one on the dense Hessian; `options(dMod2.sparseAuto = list(parameters = , fill = ))` -moves the lower bound or replaces the cost by an upper bound of the fill. +`sparse = TRUE` uses sparse Cholesky factors, plus a low-rank part, for many parameters that each +act on few conditions; it reaches the same fit as the dense path. `"auto"` (default) takes it from +100 parameters on where it costs fewer flops (`options(dMod2.sparseAuto = )`). ### Arguments and result @@ -152,7 +141,7 @@ moves the lower bound or replaces the cost by an upper bound of the fill. |---|---|---| | `rinit`, `rmax` | `0.1`, `10` | first and largest radius | | `iterlim` | `1000` | iterations over all phases | -| `hessianMethod` | `"gn"` | source of the model Hessian | +| `hessianMethod` | Gauss-Newton, then BFGS | source of the model Hessian | | `phases`, `switches` | none | several sources in turn | | `parlower`, `parupper`, `boundary` | none, `"reflective"` | bounds | | `tolControl` | `ftol`, `mtol`, `gtol` `1e-6`; `xtol`, `rmin` `0`; `ctol` `1e-6` | termination; `ctol` for multiple shooting | @@ -162,15 +151,13 @@ moves the lower bound or replaces the cost by an upper bound of the fill. | `sparse` | `"auto"` | sparse path | | `blather`, `printIter`, `traceFile` | `FALSE`, `FALSE`, none | trace in the result, printed values, CSV log | -Other arguments go to the objective, such as `fixed`. The result, a `trustfit`, holds `argument`, -`value`, `gradient`, `hessian`, `iterations`, `neval`, `converged`, `atBound` and `stopReason`; -with `blather = TRUE` also the path of iterates and trial points. `vcov(fit)` inverts half the -Hessian. +Other arguments go to the objective, such as `fixed`. The `trustfit` holds `argument`, `value`, +`gradient`, `hessian`, `iterations`, `converged`, `atBound` and `stopReason`. ## Single fit -`onefit.R` fits from one start drawn with standard deviation 0.5 around the best fit; -`mstrust()` draws again where the model cannot be evaluated: +`onefit.R` fits from one start drawn with standard deviation 0.5 around the best fit; the fit is +loaded from `results/onefit.rds`: ```{r onefit, eval = FALSE} ``` @@ -186,15 +173,14 @@ fit[c("value", "converged", "iterations", "stopReason")] ## Multistart fitting -`mstrust()` fits from many starts and returns a list of fits; `as.parframe()` sorts them by value. -`fit.R` draws 200 starts from the prior of [Setting up models](guide-model.html#likelihood-and-prior): +`mstrust()` fits from many starts; `as.parframe()` sorts the fits by value. `fit.R` draws 200 +starts from the prior of [Setting up models](guide-model.html#likelihood-and-prior): ```{r multistart, eval = FALSE} ``` -Arguments go by name to `trust()`, to the sampler (`sd` to `rnorm()`) or to the objective. All -starts are drawn before the fits are distributed, so `set.seed()` reproduces a run for any -`cores`. +Arguments go by name to `trust()`, the sampler or the objective; `set.seed()` reproduces a run for +any `cores`. | argument | default | controls | |---|---|---| @@ -205,12 +191,11 @@ starts are drawn before the fits are distributed, so `set.seed()` reproduces a r | `retry`, `nTries` | `TRUE`, `10` | a failed fit restarts from the next draw | | `cores` | `1` | parallel fits, or `c(fits = , conditions = )` | | `optmethod` | `"trust"` | optimizer, e.g. `"trustL1"` | -| `output`, `cautiousMode` | `FALSE` | `output` writes every fit to `resultPath/name/trial--/interRes/` while the run goes on and the parameter list at the end of the run; `cautiousMode` adds a deparsed `.R` copy of every fit, kept after the run | +| `output`, `cautiousMode` | `FALSE` | write fits to `resultPath` during the run | -`msParframe()` draws starts from a separate seed, so several runs can share them; `load.parlist()` -reads the fits in `interRes/` of a run that is still going or was aborted, since a finished run -removes them and leaves `parameterList.Rda`. `helix.R` runs the 200 fits as 100 array tasks -([Remote computing](guide-remote-computing.html)): +`msParframe()` draws shareable starts; `load.parlist()` reads the fits of a running or aborted +run. The fits of `fit.R` ([Remote computing](guide-remote-computing.html)) are loaded from +`results/fits.rds`: ```{r, echo = FALSE} invisible(stored("results/fits.rds", "fit.R")) @@ -224,19 +209,22 @@ c(fits = nrow(fits), converged = sum(fits$converged), best = min(fits$value), withinOne = sum(fits$value < min(fits$value) + 1)) ``` -The waterfall plot shows the sorted values; each plateau is a local optimum, the length of the plateau the size -of the basin of attraction: +Sorted values; each plateau is a local optimum: ```{r waterfall, fig.height = 3.5} ``` -The parameters that differ by more than 0.1 between the plateaus within 5 of the best: +Parameters that differ by more than 0.1 between the plateaus within 5 of the best: -```{r, fig.height = 3} +```{r} pl <- plotPars(fits, value < min(value) + 5) med <- with(pl$data, tapply(parvalue, list(name, step), median)) differ <- rownames(med)[apply(med, 1, function(m) diff(range(m, na.rm = TRUE))) > 0.1] -pl %+% subset(pl$data, name %in% differ) + +pl$data <- subset(pl$data, name %in% differ) +``` + +```{r, fig.height = 1 + 0.22 * length(differ)} +pl + coord_flip() + scale_x_discrete(limits = rev) + labs(x = NULL, y = "log value", color = "plateau") @@ -244,9 +232,8 @@ pl %+% subset(pl$data, name %in% differ) + ## Comparison of Hessian sources -`optimizers.R` fits from the same 100 starts with Gauss-Newton, BFGS and SR1 on the reverse -gradient, the exact Hessian, and Gauss-Newton followed by BFGS. `hits` counts the starts that end -within 5 of the best value: +`optimizers.R` fits from the same 100 starts with several Hessian sources, loaded from +`results/optimizers.rds`. `hits` counts the fits within 5 of the best value: ```{r, echo = FALSE} invisible(stored("results/optimizers.rds", "optimizers.R")) @@ -255,59 +242,28 @@ invisible(stored("results/optimizers.rds", "optimizers.R")) ```{r} opt <- readRDS("results/optimizers.rds") top <- min(opt$value, na.rm = TRUE) -tapply(opt$value < top + 5, factor(opt$method, unique(opt$method)), sum, na.rm = TRUE) +shown <- c("default (Fides hybrid)", "Gauss-Newton", "BFGS", "exact", "GN, then BFGS", "GN, then BFGS at stall 50", "SSR1, scaled", + "GNSBFGS") +opt <- opt[opt$method %in% shown, ] +method <- factor(opt$method, shown) +t(rbind(converged = tapply(opt$converged, method, sum), + hits = tapply(opt$value < top + 5, method, sum, na.rm = TRUE), + secondsPerHit = round(tapply(opt$elapsed, method, sum, na.rm = TRUE) / + tapply(opt$value < top + 5, method, sum, na.rm = TRUE)))) ``` -Costs and the full comparison: +The exact Hessian converges most often, scaled SR1 reaches the best plateaus most often, and +Gauss-Newton followed by BFGS on the reverse gradient needs the least time per hit. Details: [Methods > Forward and reverse derivatives on the Oppelt fit](methods-trust.html#forward-and-reverse-derivatives-on-the-oppelt-fit). ## L1 penalties `trustL1()` adds $\sum_i \lambda_i \lvert \theta_i - \mu_i \rvert$ for the parameters named in -`mu`, with strength `lambda`. A penalized parameter stays at the reference until the data pull -with a force above $\lambda_i$; a scan over `lambda` selects the parameters that differ. -`one.sided = TRUE` penalizes one side only, `gate` lets parameters leave upward only, `fuse` -penalizes differences within blocks of parameters. Bounds and tolerances are those of `trust()`; -`mstrust(optmethod = "trustL1")` runs it from many starts. Details: -[Methods > L1 penalties](methods-trust.html#l1-penalties). - -## Multiple shooting - -Multiple shooting integrates segments of the time axis from separate node values and makes -continuity a constraint, which helps for oscillating or spiking systems -([Methods > Multiple shooting](methods-multiple-shooting.html)). It is a control of the objective: - -```{r, eval = FALSE} -obj <- normL2(data, g * x * p, multipleShootingControl = TRUE) -fit <- trust(obj, start) -fit$multipleShooting$violation -controls(obj, "multipleShootingControl") <- NULL # single shooting again -``` - -The chain must be `g * x * p` with one `Xs()` built on `odemodel(..., includeTimeZero = FALSE)`. -Not available with it: `hessianMethod = "exact"`, `qnControl$hessianInit = "exact"`, several -phases, `switches`, `hessianReseed`, `qnMemory`, `nonmonotone`, `boundary = "clip"`, -`minimize = FALSE`, `traceFile`. - -| entry of `multipleShootingControl` | default | controls | -|---|---|---| -| `nodes` | `"auto"` | `"auto"`, `"transitions"`, or node times | -| `growth`, `misfit` | `10`, `3` | thresholds at which `"auto"` cuts a segment | -| `minPoints` | states + 1 | data points per half of a cut | -| `charts` | all linear | `"log10"`, `"linear"` or `"angle"` per state | -| `scale` | from the data | scale of the gaps and node steps | -| `init` | `"data"` | node values: `"data"`, `"spline"`, `"simulation"` or a list | -| `breaks` | none | node times without continuity | - -| entry of `stepControl` | default | controls | -|---|---|---| -| `acceptance` | `"filter"` | `"filter"`, `"merit"` or `"natural"` | -| `soc` | `TRUE` | second-order correction of a rejected step | -| `anneal` | `TRUE` | penalty on the gaps raised in stages | -| `twoPhase`, `restore`, `regularize` | off | further globalizations | +`mu`; a scan over `lambda` selects the parameters that differ from the reference. `one.sided`, +`gate` and `fuse` vary the penalty ([Methods > L1 penalties](methods-trust.html#l1-penalties)). -`converged = TRUE` requires the scaled gaps below `tolControl$ctol`. The result has a list -`multipleShooting` with `nodes`, `gaps`, `violation` and the counts of the globalization. +Multiple shooting for oscillating or spiking systems: +[Methods > Multiple shooting](methods-multiple-shooting.html). Reference: `trust()`, `mstrust()`, `trustL1()`, `msParframe()`, `as.parframe()`, `load.parlist()`, `plotValues()`, `plotPars()`, `normL2()` diff --git a/vignettes/articles/guide-petab.Rmd b/vignettes/articles/guide-petab.Rmd index ef74b2f7..d3e40043 100644 --- a/vignettes/articles/guide-petab.Rmd +++ b/vignettes/articles/guide-petab.Rmd @@ -13,11 +13,9 @@ knitr::read_chunk("../../examples/oppeltNPJSystBiolAppl2018/petab.R") ``` PEtab is the exchange format for ODE parameter estimation problems: an SBML model plus tables of -measurements, observables with noise models, conditions, and parameters with scales and bounds, -joined by a YAML file. This chapter writes the guide model at the best fit as a PEtab problem and -reads it back (`petab.R`); problems of the -[PEtab benchmark collection](https://github.com/Benchmarking-Initiative/Benchmark-Models-PEtab) -and other tools are read the same way. +measurements, observables, conditions and parameters, joined by a YAML file. `petab.R` writes the +guide model at the best fit as a PEtab problem and reads it back, as for problems of the +[PEtab benchmark collection](https://github.com/Benchmarking-Initiative/Benchmark-Models-PEtab). ```{r setup, echo = FALSE} ``` @@ -56,21 +54,16 @@ prd <- g * x * pSS * p ## PEtab export `exportPEtab()` writes reactions as SBML, observables, errors, data, and the transformation `p` -with scales, fixed values and values per condition. A parameter entering only as `exp()` is on -log scale. PEtab 2, the default, has no parameter scales: values are written on linear scale, with -a warning listing the log-scale parameters. The gauge of [Symmetries](guide-symmetries.html) -becomes fixed values, also linear. - -- **State at rest.** With `steadyState = pSS`, each condition starts with a pre-equilibration to - steady state before time 0. The totals of the conserved moieties (the `Pimpl()` parameters) - become initial-value parameters: one species per total starts at the total, here complex - `NfkIkb` for NFκB and unphosphorylated `Ikk` for IKK, all others at 0; the simulation preserves - the totals. Both conditions differ only in the dose, given by the event, and share one - pre-equilibration condition. -- **Event.** With `events = events`, the event at time 0 becomes the `TNF` value in the condition - table, set after pre-equilibration. -- **Errors.** Imaging readouts get their error model; the blots, outside the error model, get the - data standard deviations as noise parameters per measurement, as in `normL2()`. +with fixed values and values per condition. PEtab 2, the default, has no parameter scales: values +of parameters entering as `exp()` are written on linear scale, with a warning. The gauge of +[Symmetries](guide-symmetries.html) becomes fixed values. + +- **State at rest.** `steadyState = pSS` gives a pre-equilibration before time 0, shared by both + conditions. One species per conserved total starts at the total (`NfkIkb`, `Ikk`), all others + at 0. +- **Event.** `events = events` writes the event at time 0 as the `TNF` value of the condition. +- **Errors.** Imaging readouts get the error model, blots the data standard deviations as noise + parameters per measurement. ```{r, include = FALSE} invisible(stored("results/fits.rds", "fit.R", envir = new.env())) @@ -79,7 +72,8 @@ invisible(stored("results/fits.rds", "fit.R", envir = new.env())) ```{r petabexport, warning = FALSE} ``` -Each experiment starts with the pre-equilibration at $t = -\infty$, then the experiment condition at 0: +The export uses the best fit of `fit.R`, loaded from `results/fits.rds`. Each experiment starts +with the pre-equilibration at $t = -\infty$, then the experiment condition at 0: ```{r} read.delim("results/petab/experiments_oppelt.tsv") @@ -88,10 +82,9 @@ read.delim("results/petab/conditions_oppelt.tsv") ## PEtab import -`importPEtab()` builds `prdfn`, the `obsfn`s of observables and errors, the `parfn` with the -scales of the parameter table, data and `objfn`. A pre-equilibration becomes a `Pimpl()` with -totals from the initial values. `options` go to the solver; with `compile = FALSE`, `compile()` -builds the sources. +`importPEtab()` builds `prdfn`, the `obsfn`s of observables and errors, the `parfn`, data and +`objfn`; a pre-equilibration becomes a `Pimpl()`. With `compile = FALSE`, `compile()` builds the +sources. ```{r petabimport} ``` @@ -107,18 +100,15 @@ compile(g, x, pSS, p, e, petab$prd, petab$e, output = "oppelt_petab_guide", core ```{r petabcompare} ``` -The imported problem reproduces the data term of `model.R` at the best fit. `petab$bestfit` has -the nominal values on the problem scales, `petab$parlower` and `petab$parupper` the bounds; it is -fitted and profiled like any other. +The imported problem reproduces the data term of `model.R` at the best fit. `petab$bestfit` holds +the nominal values on the problem scales, `petab$parlower` and `petab$parupper` the bounds. ## SBML models -`exportSbml()` writes species with compartments and volumes, reactions with kinetic laws, -parameters and initial assignments, here one species per total set to that total. SBML kinetic -laws are amounts per time: `exportSbml()` multiplies concentration rates by the compartment -volume, `importSbml()` divides again. `importSbml()` returns a list: the equation list with -compartments and volumes in `reactions`, parameter values, initial values, observables, assignment -rules and events: +`exportSbml()` writes species with compartments, reactions, parameters and initial assignments; +concentration rates are multiplied by the compartment volume, `importSbml()` divides again. +`importSbml()` returns the equation list in `reactions`, parameter and initial values, +observables, assignment rules and events: ```{r} sbml <- importSbml("results/petab/oppelt.xml") @@ -133,8 +123,8 @@ identical(sort(sbml$reactions$states), sort(reactions$states)) - SBML and PEtab run through reticulate with `python-libsbml`; `DMOD_LIBSBML_PYTHON` selects the interpreter. -- PEtab 1 and 2 are read. `exportPEtab()` writes 2 by default, 1 with `formatVersion = "1"`, which - keeps scales but puts expressions into the condition table that only dMod2 reads. +- PEtab 1 and 2 are read. `exportPEtab(formatVersion = "1")` keeps scales but writes condition + expressions that only dMod2 reads. - `exportPEtab()` writes events at time 0 that replace a state and refuses others. Reference: `exportPEtab()`, `importPEtab()`, `exportSbml()`, `importSbml()` diff --git a/vignettes/articles/guide-prediction-uncertainty.Rmd b/vignettes/articles/guide-prediction-uncertainty.Rmd index 2026fdec..a69ffea2 100644 --- a/vignettes/articles/guide-prediction-uncertainty.Rmd +++ b/vignettes/articles/guide-prediction-uncertainty.Rmd @@ -18,11 +18,9 @@ inWords <- function(n) if (n %in% 1:12) c("one", "two", "three", "four", "five", "eight", "nine", "ten", "eleven", "twelve")[n] else format(n) ``` -The prediction profile likelihood [@kreutz2012likelihood] gives the confidence band of a model -prediction directly, without parameter intervals. This chapter computes the band of nuclear IκBα -after TNFα in the reduced model of [Profile likelihood](guide-profiles.html); nuclear IκBα is not -measured and decides when NFκB leaves the nucleus [@oppelt2018model, Fig. 5]. The code is -`prediction.R`. +The prediction profile likelihood [@kreutz2012likelihood] gives the confidence band of a +prediction, here of unmeasured nuclear IκBα after TNFα [@oppelt2018model, Fig. 5] in the reduced +model of [Profile likelihood](guide-profiles.html). Code: `prediction.R`. ```{r setup, echo = FALSE} ``` @@ -78,12 +76,10 @@ prdReduced <- gReduced * xReduced * pReduced ## Prediction profiles and validation data points -The prediction profile is the objective minimized over all parameters with the prediction held -at a value; the values within the $\chi^2_1$ threshold form the confidence interval. `datapointL2()` -turns the prediction into a parameter `v`, tied to the model by a validation data point of small -standard deviation; the profile of `v` is the prediction profile. `normL2()` predicts at the time -of the point (`times = t`); `attrName = "data"` adds the validation term to the data term, so -`stop = "data"` and `confint(val.column = "data")` leave the prior out +`datapointL2()` ties a parameter `v` to the prediction by a validation data point of small +standard deviation; the profile of `v` is the prediction profile, and the values within the +$\chi^2_1$ threshold form the confidence interval. `attrName = "data"` adds the validation term to +the data term, so `stop = "data"` and `confint(val.column = "data")` leave the prior out ([Methods > Prediction profiles](methods-profiles.html#prediction-profiles)). ## Prediction band @@ -99,11 +95,11 @@ band <- readRDS("results/prediction.rds")$band decades <- log10(range(band$value[band$value > 0])) ``` -`prediction.R` computes the profile in the stimulated condition at `r nrow(band)` times, densest -at the flanks of the pulse. The prediction spans `r inWords(floor(diff(decades)))` orders of -magnitude, so the validation point has standard deviation $0.01\,\hat v(t)$ and the steps are -fractions of $\hat v(t)$. The profiles run on the linear scale since the resting state holds no -nuclear IκBα; the times start at 2 minutes. +`prediction.R` computes the profile at `r nrow(band)` times of the stimulated condition, from 2 +minutes on; the results are loaded from `results/prediction.rds`. The prediction spans +`r inWords(floor(diff(decades)))` orders of magnitude, so the validation point has standard +deviation $0.01\,\hat v(t)$. The profiles run on linear scale, since the resting state holds no +nuclear IκBα. ```{r predictionsetup, eval = FALSE} ``` @@ -111,8 +107,6 @@ nuclear IκBα; the times start at 2 minutes. ```{r predictionprofiles, eval = FALSE} ``` -`confint()` reads the interval from the data term: - ```{r predictionband, eval = FALSE} ``` @@ -134,8 +128,7 @@ if (length(short)) paste(short, collapse = ", "))) ``` -Prediction profiles at three times; all times are in -[All prediction profiles](#all-prediction-profiles): +Profiles at three times, all in [All prediction profiles](#all-prediction-profiles): ```{r, fig.height = 3.5} times <- c(10, 70, 240) @@ -148,7 +141,7 @@ plotProfile(shown, mode == "data") + ggplot2::labs(x = "nuclear IκBα [total NFκB]") ``` -The band around the prediction of the best fit: +Band and prediction of the best fit: ```{r} controls(gReduced, name = "attachInput") <- TRUE @@ -165,14 +158,14 @@ ggplot2::ggplot(course, ggplot2::aes(time, value)) + ggplot2::scale_x_continuous(breaks = seq(0, 360, 60)) + ggplot2::scale_y_log10() + ggplot2::labs(x = "time [min]", y = "nuclear IκBα [total NFκB]") + - theme_dMod() + theme_dMod2() ``` -Concentrations are in units of total NFκB, set by the gauge of [Symmetries](guide-symmetries.html). +Units of total NFκB follow from the gauge of [Symmetries](guide-symmetries.html). ## All prediction profiles -The axis is in units of the prediction $\hat v(t)$ of the best fit: +In units of the prediction $\hat v(t)$ of the best fit: ```{r, fig.height = 16} relative <- Map(function(pr, v) { pr$v <- pr$v / v; pr }, saved$profiles, band$value) diff --git a/vignettes/articles/guide-profiles.Rmd b/vignettes/articles/guide-profiles.Rmd index 2e32edfe..0e4ace08 100644 --- a/vignettes/articles/guide-profiles.Rmd +++ b/vignettes/articles/guide-profiles.Rmd @@ -15,12 +15,12 @@ knitr::read_chunk("../../examples/oppeltNPJSystBiolAppl2018/model.R") knitr::read_chunk("../../examples/oppeltNPJSystBiolAppl2018/profiles.R") knitr::read_chunk("../../examples/oppeltNPJSystBiolAppl2018/reduced.R") knitr::read_chunk("../../examples/oppeltNPJSystBiolAppl2018/refit.R") +knitr::read_chunk("../../examples/oppeltNPJSystBiolAppl2018/fundamental.R") ``` -The profile likelihood [@raue2009structural] determines how well the data constrain each -parameter. This chapter profiles all parameters of the full model at the best fit of -[Optimization](guide-optimization.html), tests the core model of the publication, and fits a -reduced model, by `profiles.R`, `variants.R`, `reduced.R` and `refit.R`. +The profile likelihood [@raue2009structural] shows how well the data constrain each parameter. +This chapter profiles the full model at the best fit of [Optimization](guide-optimization.html), +tests the core model of the publication and fits a reduced model. ```{r setup, echo = FALSE} ``` @@ -60,21 +60,18 @@ reduced model, by `profiles.R`, `variants.R`, `reduced.R` and `refit.R`. ## Profile likelihood and confidence intervals -The profile likelihood of a parameter is the data term along the path on which the other -parameters minimize an objective with that parameter fixed. Here that objective is the one of the -multistart with the prior replaced by a prior of standard deviation 20 on the log scale at the best -fit, so that the data term, not the prior, shapes the profiles; the optimum of that objective is -the lowest point of every profile. Values of the data term -within the 95 % quantile of $\chi^2_1$, 3.84, of the minimum form the 95 % confidence interval +The profile of a parameter is the data term along the path on which the other parameters minimize +the objective with that parameter fixed. Here the objective has a prior of standard deviation 20 +on the log scale at the best fit, so that the data term shapes the profiles. Data terms within +3.84, the 95 % quantile of $\chi^2_1$, of the minimum form the 95 % confidence interval ([Methods > Profile likelihood](methods-profiles.html)). `stepControl = list(stop = "data")` ends a -profile there, `confint(val.column = "data")` reads the interval off, and `profileThreshold()` -gives other levels. A profile open towards $-\infty$ on the log scale means the -process can be switched off, towards $+\infty$ that it can be instantaneous -([Methods > Shapes](methods-profiles.html#shapes)). +profile there, `confint(val.column = "data")` reads the interval, `profileThreshold()` gives other +levels. A profile open towards $-\infty$ means the process can be switched off, towards +$+\infty$ that it can be instantaneous ([Methods > Shapes](methods-profiles.html#shapes)). `method = "integrate"` (default) follows the constrained optimum as a curve, with -`algoControl = list(reoptimize = TRUE)` corrected at every step by a `trust()` fit with the -settings of `optControl`; `method = "optimize"` refits at every step. +`algoControl = list(reoptimize = TRUE)` corrected by `trust()`; `method = "optimize"` refits at +every step. | entry of `stepControl` | `"integrate"` | `"optimize"` | controls | |---|---|---|---| @@ -84,18 +81,17 @@ settings of `optControl`; `method = "optimize"` refits at every step. | `limit` | `500` | `100` | steps per side | | `stop` | `"value"` | `"value"` | part of the objective compared with the threshold | -`limits` bounds the profiled parameter relative to the optimum, `side` profiles one side, `cores` -profiles parameters in parallel ([Remote computing](guide-remote-computing.html#threads-and-processes)). +`limits` bounds the profiled parameter, `side` profiles one side, `cores` profiles in parallel +([Remote computing](guide-remote-computing.html#threads-and-processes)). ## Profiles of the full model -`profiles.R` refits the best fit of the multistart to the tolerances of the profiles: +`profiles.R` refits the best fit of the multistart to the tolerances of the profiles, ```{r refit, eval = FALSE} ``` -and fits the objective of the profiles from there, the best of 20 fits from starts about the refit, -since a single fit can stop short of the floor of a flat valley: +fits the objective of the profiles once, ```{r profileprior, eval = FALSE} ``` @@ -105,9 +101,8 @@ invisible(stored("results/fits.rds", "fit.R")) invisible(stored("results/profiles.rds", "profiles.R")) ``` -Each side runs until the data term has risen by the threshold or the parameter has moved by 7 on -the log scale; a profile below the fit restarts the 20 fits about its lowest point. `helix.R` runs -one parameter per cluster task. +and profiles each side until the data term has risen by the threshold or the parameter has moved +by 7. The profiles are loaded from `results/profiles.rds`: ```{r profiles, eval = FALSE} ``` @@ -127,16 +122,13 @@ c(refit = dataTerm(refit$argument), profiles = dataTerm(fitProfile$argument)) ``` Without the prior of `model.R` the data term falls by -`r round(dataTerm(refit$argument) - dataTerm(fitProfile$argument), 2)`. - -No profile lies more than 0.01 below the fit, so the profiles start at the optimum: +`r round(dataTerm(refit$argument) - dataTerm(fitProfile$argument), 2)`. No profile lies below the +fit: ```{r} c(fit = fitProfile$value, lowest = min(profiles$value)) ``` -The intervals and their shapes: - ```{r} intervals <- confint(profiles, level = 0.95, val.column = "data") intervals$shape <- with(intervals, ifelse(is.finite(lower) & is.finite(upper), "finite", @@ -158,8 +150,7 @@ priorRise <- max(mapply(function(name, shape) { }, openSides$name, openSides$shape)) ``` -The open profiles, data term and prior separately; on an open side the data term stays below -3.84, and the prior rises by up to `r ceiling(10 * priorRise) / 10`: +The open profiles; on an open side the prior rises by up to `r ceiling(10 * priorRise) / 10`: ```{r} # panels wide enough for the parameter names, few ticks and the legend below @@ -178,10 +169,8 @@ plotProfile(profiles, mode %in% c("data", "prior"), name %in% open, ncol = 4) + ## Parameter paths `plotPaths()` shows how the other parameters compensate along a profile. Along `act_Ikb_Base`, -`eta_act_Ikb_Base_c_pNfkIkb` rises by the same amount: the data determine the product, the -phosphorylation of IκBα in the complex with pNFκB. `int_Nfk` trades in the same way against the -import factors of IκBα and pNFκB. Parameters with an open profile, such as `act_Ikk_Base`, drift -along without changing the data term. Shown are the parameters that move by more than 1: +`eta_act_Ikb_Base_c_pNfkIkb` rises by the same amount: the data determine the product. Shown are +the parameters that move by more than 1: ```{r, fig.height = 4} # the parameters that move along the profile of `par` by more than `by` on the log scale @@ -200,13 +189,9 @@ for (par in c("act_Ikb_Base", "int_Nfk")) ## Predictions along a profile -`plotArray()` predicts the model at points along one side of a profile, from the optimum to the -end, colored by the profiled parameter; `fixed` adds the gauge the profiles held fixed. Within the -threshold the measured readouts stay within the noise of the data, so the states show what a -profile leaves open. Along the upper side of `degrad_RnaA20`, which ends where the data term has -risen by the threshold, the last stage of the A20 transcript, `RnaA20`, falls by two orders of -magnitude and the delay stages before it rise, while A20, the protein that A20GFP reads out, stays -nearly the same: +`plotArray()` predicts along one side of a profile, colored by the profiled parameter; `fixed` +adds the gauge. Along the upper side of `degrad_RnaA20`, `RnaA20` falls by two orders of magnitude +while A20 stays nearly the same: ```{r, fig.height = 5} states <- x * pSS * p @@ -216,9 +201,8 @@ plotArray("degrad_RnaA20", profiles, states, minutes, name %in% chain, condition direction = "up", nSim = 5, fixed = gauge) ``` -Along the lower side of `ext_nNfkIkb`, a slower export of the complex of NFκB and IκBα from the -nucleus, the complex builds up to a few percent of total NFκB at the expense of free and -phosphorylated nuclear NFκB, so that their sum, which nucNFkB reads out, stays the same: +Along the lower side of `ext_nNfkIkb` the nuclear complex builds up at the expense of free and +phosphorylated nuclear NFκB; their sum, read out by nucNFkB, stays the same: ```{r, fig.height = 5} plotArray("ext_nNfkIkb", profiles, states, minutes, name %in% c("nNfk", "pnNfk", "nNfkIkb"), @@ -227,8 +211,8 @@ plotArray("ext_nNfkIkb", profiles, states, minutes, name %in% c("nNfk", "pnNfk", ## Core model of the publication -The publication reduced the full model to a core model of 29 reactions [@oppelt2018model, -Table S5] with fixed values (Tables S8 and S9). The settings on the log scale: +The core model of the publication has 29 reactions [@oppelt2018model, Table S5] and fixed values +(Tables S8 and S9), on the log scale: | setting of the core model | parameter of the full model | value | |---|---|---| @@ -268,9 +252,9 @@ deact <- settings[settings$name == "deact_pnNfk", ] Every setting but one lies in the 95 % interval; the data bound `deact_pnNfk` to `r signif(exp(deact$lower), 2)` to `r signif(exp(deact$upper), 2)` per minute, below the fixed -1000. A profile tests one setting with all others free; the likelihood ratio test takes them -together. `variants.R` fits the core model and the variants that release one setting, each with the -prior of `model.R`, and compares the data terms with the full model: +1000. No profile tests the single delay step, and the publication gives no reason for it. The +likelihood ratio test takes all settings together: `variants.R` fits the core model and the variants that release one setting, loaded from +`results/variants.rds`: ```{r, echo = FALSE} invisible(stored("results/variants.rds", "variants.R")) @@ -297,18 +281,14 @@ knitr::kable(data.frame(released = released[rownames(shown)], The core model lies `r round(variants["core", "difference"], 2)` above the full model, against the threshold `r round(variants["core", "threshold"], 2)` for `r variants["core", "removed"]` removed parameters, and is -`r if (variants["core", "difference"] < variants["core", "threshold"]) "accepted" else "rejected"`. A negative decrease means that the prior on -the released parameter costs more than the data gain. The two delay steps and the separate factor -lower the data term most; together they lower it by `r round(bothLower, 2)` at one added -parameter, more than the threshold 3.84 of one degree of freedom. `reduced.R` takes these two -deviations from the publication. In that model the scale `s_ipNFkB_ibNFkB` of the NFκB blot -after NFκB precipitation has a profile open below, compensated only by the offset; `reduced.R` -sets the scale to 0. +`r if (variants["core", "difference"] < variants["core", "threshold"]) "accepted" else "rejected"`. +The two delay steps and the separate factor together lower the data term by +`r round(bothLower, 2)` at one added parameter, more than 3.84; `reduced.R` takes both and sets the +scale `s_ipNFkB_ibNFkB`, whose profile is open below, to 0. ## Reduced model -The core model with the two delay steps and the separate factor for the release of pNFκB, and -the NFκB blot after NFκB precipitation reading the offset alone: +The core model with two delay steps, the separate factor and the scale `s_ipNFkB_ibNFkB` at 0: ```{r reducedreactions, eval = FALSE} ``` @@ -316,9 +296,8 @@ the NFκB blot after NFκB precipitation reading the offset alone: ```{r reducedobservables, eval = FALSE} ``` -Without basal activation the resting states form a continuum. As in the publication, all NFκB -rests in the complex with IκBα and all IKK is inactive, a steady state for every parameter value; -the reduced model needs neither `Pimpl()` nor a stability term: +As in the publication, all NFκB rests in the complex with IκBα and all IKK is inactive, a steady +state for every parameter value, so neither `Pimpl()` nor a stability term is needed: ```{r reducedmodel, eval = FALSE} ``` @@ -331,8 +310,8 @@ The prior of the full model on the remaining parameters: ```{r reducedobjective, eval = FALSE} ``` -`refit.R` fits from the full model and from 50 starts around that fit, then compares the data -terms: +`refit.R` fits from the full model and from 50 starts around that fit; the result is loaded from +`results/reduced.rds`: ```{r reducedfit, eval = FALSE} ``` @@ -351,12 +330,11 @@ saved$ratio With `r round(saved$ratio[["removed"]])` fewer parameters the data term is higher by `r signif(saved$ratio[["difference"]], 4)`, below the threshold -`r signif(saved$ratio[["threshold"]], 4)`: the reduced model is accepted. +`r signif(saved$ratio[["threshold"]], 4)`. ## Profiles of the reduced model -With the prior and the settings of the profiles of the full model, from the optimum of that -objective: +With the prior and settings of the profiles of the full model: ```{r reducedprofileprior, eval = FALSE} ``` @@ -385,8 +363,7 @@ fcLower <- intervalsReduced$lower[intervalsReduced$name == "form_complex"] / log All parameters are identifiable except `form_complex`, bounded below at `r signif(fcLower, 2)` on the log10 scale and open above on a plateau `r round(plateau, 2)` above the optimum; the publication reports (-0.21, 3.03). The profiles of `degrad_A20`, -`degrad_RnaA20` and `shuttle_RnaA20` have a second minimum inside the interval. The rate -constants: +`degrad_RnaA20` and `shuttle_RnaA20` have a second minimum inside the interval. The rate constants: ```{r} rates <- setdiff(intervalsReduced$name, grep("^(s|off|sigma|tau)_", intervalsReduced$name, value = TRUE)) @@ -397,6 +374,113 @@ intervalsReduced[intervalsReduced$name %in% rates, c("name", "value", "lower", " plotProfile(saved$profiles, mode %in% c("data", "prior"), name %in% rates, ncol = 4) + readable ``` +```{r, include = FALSE} +along <- as.data.frame(saved$profiles) +optimum <- saved$fitProfile$argument +# the fits of the multistart within 0.001 of the best, by side of the fixed set of the swap +fits <- as.data.frame(saved$fits) +best <- fits[fits$value < min(fits$value) + 1e-3, ] +below <- sum(best$degrad_A20 < best$degrad_RnaA20) +# the point of the profile of degrad_RnaA20 at the mirror image of the optimum +rna <- along[along$whichPar == "degrad_RnaA20", ] +mirror <- rna[which.min(abs(rna$degrad_RnaA20 - optimum[["degrad_A20"]])), ] +# the first local minimum of the lower side of the profile of shuttle_RnaA20, away from the optimum +shuttle <- along[along$whichPar == "shuttle_RnaA20" & + along$shuttle_RnaA20 < optimum[["shuttle_RnaA20"]] - 0.5, ] +shuttle <- shuttle[order(shuttle$shuttle_RnaA20), ] +second <- shuttle[which(diff(sign(diff(shuttle$data))) > 0)[1] + 1, ] +# the fits of the multistart at that point +atSecond <- sum(abs(fits$shuttle_RnaA20 - second$shuttle_RnaA20) < 0.1 & + abs(fits$degrad_A20 - fits$degrad_RnaA20) < 0.1) +``` + +Exchanging `degrad_A20` and `degrad_RnaA20` leaves every readout and the prior unchanged, a +discrete symmetry ([Symmetries > Discrete symmetries](guide-symmetries.html#discrete-symmetries)). +Of the `r nrow(best)` best fits of the multistart, `r below` lie on the side +`degrad_A20 < degrad_RnaA20` and `r nrow(best) - below` at the mirror image. The profile of +`degrad_RnaA20` passes through the mirror image of the optimum, within +`r format(signif(mirror$data - min(along$data), 1), scientific = FALSE)` +of the data term at the optimum. + +The second minimum of `shuttle_RnaA20` is another local optimum, close to the fixed set of the +swap: at `shuttle_RnaA20` = `r round(second$shuttle_RnaA20, 2)` the degradation rates are +`r round(second$degrad_A20, 2)` and `r round(second$degrad_RnaA20, 2)`, the data term +`r round(second$data - min(along$data), 2)` above the optimum, reached by `r atSecond` fits of the +multistart. The estimates of the publication, $-4.72$ and $-4.46$ [@oppelt2018model, Table S7], +also lie close to the fixed set. + +## Profiles in the fundamental domain + +The fundamental domain `degrad_A20 < degrad_RnaA20` holds the optimum and removes the swap. +`fundamental.R` fits the reduced model in the chart that +`symmetryReduction(branch = "degrad_A20 < degrad_RnaA20")` returns, with +`define("degrad_RnaA20 <- degrad_A20 + delta_RnaA20")` before `insert("x <- exp(x)")`; the fixed +set lies at `delta_RnaA20` $\to -\infty$. Only the parameter transformation is new: + +```{r fundamentaltrafo, eval = FALSE} +``` + +`delta_RnaA20` has the prior of `degrad_RnaA20`, mean $\log(1/60)$ and standard deviation 2: + +```{r fundamentalobjective, eval = FALSE} +``` + +One fit from the best fit of `refit.R`, loaded with the profiles from `results/fundamental.rds`: + +```{r fundamentalfit, eval = FALSE} +``` + +```{r, echo = FALSE} +invisible(stored("results/fundamental.rds", "fundamental.R")) +``` + +```{r} +fundamental <- readRDS("results/fundamental.rds") +fundamental$dataTerms +``` + +Profiles with the prior and settings of the reduced model: + +```{r fundamentalprofileprior, eval = FALSE} +``` + +```{r fundamentalprofiles, eval = FALSE} +``` + +```{r} +c(reduced = saved$fitProfile$value, fundamental = fundamental$fitProfile$value) +intervalsFundamental <- confint(fundamental$profiles, level = 0.95, val.column = "data") +rownames(intervalsFundamental) <- NULL +swapped <- c("degrad_A20", "delta_RnaA20", "shuttle_RnaA20") +intervalsFundamental[intervalsFundamental$name %in% swapped, c("name", "value", "lower", "upper")] +``` + +```{r, include = FALSE} +alongFundamental <- as.data.frame(fundamental$profiles) +# the data term at the lower end of the profile of delta_RnaA20, against the optimum +delta <- alongFundamental[alongFundamental$whichPar == "delta_RnaA20", ] +edge <- delta[which.min(delta$delta_RnaA20), ] +plateauDelta <- edge$data - min(alongFundamental$data) +upperA20 <- intervalsFundamental$upper[intervalsFundamental$name == "degrad_A20"] +upperA20Reduced <- intervalsReduced$upper[intervalsReduced$name == "degrad_A20"] +# the largest change of an interval bound of another parameter +both <- merge(intervalsFundamental, intervalsReduced, by = "name") +both <- both[!both$name %in% swapped, ] +moved <- max(abs(c(both$lower.x - both$lower.y, both$upper.x - both$upper.y)), na.rm = TRUE) +``` + +```{r, fig.height = 11} +ratesFundamental <- setdiff(intervalsFundamental$name, + grep("^(s|off|sigma|tau)_", intervalsFundamental$name, value = TRUE)) +plotProfile(fundamental$profiles, mode %in% c("data", "prior"), name %in% ratesFundamental, + ncol = 4) + readable +``` + +No profile crosses into the mirror image. The profile of `delta_RnaA20` is open below, leveling +off `r round(plateauDelta, 2)` above the optimum at the fixed set. The upper bound of `degrad_A20` +falls from `r round(upperA20Reduced, 2)` to `r round(upperA20, 2)`; the other intervals change by +at most `r format(signif(moved, 1), scientific = FALSE)`. + Reference: `profile()`, `profileThreshold()`, `confint()`, `plotProfile()`, `plotPaths()`, `plotArray()` diff --git a/vignettes/articles/guide-remote-computing.Rmd b/vignettes/articles/guide-remote-computing.Rmd index 40f0e045..4b4fc09e 100644 --- a/vignettes/articles/guide-remote-computing.Rmd +++ b/vignettes/articles/guide-remote-computing.Rmd @@ -12,26 +12,19 @@ knitr::opts_knit$set(root.dir = .work) .outdir <- options(dMod2.outdir = NULL) ``` -dMod2 parallelizes along two axes: conditions of one objective evaluation in threads, independent -fits and profiles in processes. `distributedComputing()` runs any R code as tasks in processes -detached from the session, locally, over ssh or as a SLURM array job. The local job below runs at -page build; commands for other machines are shown, not run. +Conditions of one evaluation run in threads, independent fits and profiles in processes. +`distributedComputing()` runs R code as tasks in detached processes, locally, over ssh or as a +SLURM array job. Only the local job below runs at page build. ## Threads and processes `options(dMod2.cores = n)`, or `obj(pars, cores = n)` for one call, solves the conditions of an -evaluation in `n` threads of an OpenMP team inside cppDE, constant in size within a session. The -guide model has two conditions, so this axis uses at most two threads; many conditions, or `em()` -with many groups, gain in proportion. A single condition never uses it. Predictions do not pass -through forked processes: sending back the arrays of states and sensitivities costs more than -computing them. - -`mstrust()`, `msem()` and `profile()` run independent fits as processes through `cores`. With one -number, fits are forks of the session, each solving conditions in one thread: a forked child never -starts the thread team, and BLAS and OpenMP stay at one thread across the fork. -`cores = c(fits = 4, conditions = 2)` runs four fits with two threads each in fresh R processes (a -PSOCK cluster), as always on Windows. Each process holds a copy of the predictions, so memory -grows with the process count; keep the product of both below the core count. +evaluation in `n` OpenMP threads inside cppDE; a single condition uses one. + +`mstrust()`, `msem()` and `profile()` run fits as processes through `cores`. With one number, fits +are forks of the session with one thread each. `cores = c(fits = 4, conditions = 2)` runs four fits +with two threads each in fresh R processes (a PSOCK cluster, always on Windows). Memory grows with +the process count; keep the product of both below the core count. | where | argument | axis | |---|---|---| @@ -60,12 +53,10 @@ data frame with one row per task. Inside `expr`: `parallel::mclapply(mc.cores = cores)` or `options(dMod2.cores = cores)`, - `jobname`: the job name. -`input` names the session objects the code reads, functions included, by default all objects of -the calling environment. The process attaches dMod2 and the R defaults; other packages are loaded -by the code, and session options such as `dMod2.cores` do not reach it. +`input` names the session objects the code reads, by default all objects of the calling +environment. The process attaches dMod2 and the R defaults; session options do not reach it. -Example: coverage of the 95% t interval for the mean of exponential samples, one task per sample -size, on the local machine: +Example: coverage of the 95% t interval for exponential samples, one task per sample size: ```{r coverage, eval = TRUE} interval <- function(y) t.test(y)$conf.int @@ -84,8 +75,7 @@ job <- distributedComputing( job ``` -The call returns once tasks have started. `job` is a list of functions: `check()` reports task -states, `wait()` polls until none runs, `get()` joins the results, here into one data frame. +The call returns once tasks have started. `job` is a list of functions: ```{r follow, eval = TRUE} job$check() @@ -93,15 +83,12 @@ job$wait(interval = 1) job$get() ``` -Task `i` uses seed `seed + i`, independent of worker and order; without `seed` one is drawn. A -task that errors returns the `try-error`, the others go on. +Task `i` uses seed `seed + i`. A task that errors returns the `try-error`, the others go on. ## Job folder layout -At submission the job files go into a temporary stage, copied to every node as one `tar` stream -over ssh into `_folder/` of the home directory, `k` the node number. On `"localhost"` -the folder is in the working directory and no ssh is used. The local `_folder` also holds -the manifest `job.rds`. After the local job: +The job files go to `_folder/` in the home directory of node `k`, on `"localhost"` +in the working directory. The local `_folder` also holds the manifest `job.rds`: ```{r folder, eval = TRUE} list.files("coverage_folder", recursive = TRUE) @@ -118,16 +105,14 @@ list.files("coverage_folder", recursive = TRUE) | `job.sh`, `env.sh` | SLURM only: job script from the template, job environment | | `task_.out`, `task_.rds` | output and result of task `i` | -`job.R` is the same for every task, called as `Rscript job.R ` with output in -`task_.out`: +Every task runs `Rscript job.R `: ```{r jobscript, eval = TRUE} writeLines(readLines("coverage_folder/1/job.R")) ``` -It attaches dMod2, loads workspace and shared objects, reads the task, sets the seed and evaluates -the code in `try()`, writing `task_.rds` for `get()`. Tasks share nothing but files. The -code runs in the job folder of the node; files written there come back with `get(all = TRUE)`. +The code runs in the job folder of the node; files written there come back with +`get(all = TRUE)`. ## Nodes and workers @@ -143,51 +128,37 @@ on <- sshNodes(c("localhost", "server1")) # the local machine and on <- slurmCluster("mycluster", cores = 8, walltime = "12:00:00") ``` -A node is an ssh destination (`"host"`, `"user@host"`) with key authentication, since no terminal -takes a password. `"localhost"` runs without ssh, in the session shell and working directory, with -the R and library paths of the session, so no second dMod2 install is needed; -`localNode()` is `sshNodes("localhost")`. - -Each node is one worker. Task `i` goes to worker `(i - 1) %% W + 1` of `W`; a worker runs the assigned tasks -in sequence, each with the `cores` of the node. `tasks = NULL`, the default, gives one task per -worker. +A node is an ssh destination (`"host"`, `"user@host"`) with key authentication. `"localhost"` +runs without ssh, with the R and library paths of the session; `localNode()` is +`sshNodes("localhost")`. -`cores` per task is one number, a vector named by node, or `NULL` for the free cores at -submission. `detectFreeCores()` counts cores minus the one-minute load average, on a local -Windows machine minus the processor load since the previous call, at least 1, locally or over ssh; a node gets at most the free cores, with a warning if given more. +Each node is one worker. Task `i` goes to worker `(i - 1) %% W + 1` of `W`; a worker runs the +assigned tasks in sequence with the `cores` of the node. `tasks = NULL`, the default, gives one +task per worker. `cores` is one number, a vector named by node, or `NULL` for the free cores, +which `detectFreeCores()` counts as cores minus the load average. ```{r} detectFreeCores(c("localhost", "server1", "server2")) ``` -On each node `slot_.sh` calls `Rscript job.R` for each task of the node in turn, started as -`nohup setsid sh slot_.sh &`, so it survives the end of the ssh connection or the session. -Tasks run with `OMP_NUM_THREADS=1` and `MKL_NUM_THREADS=1`, so BLAS and OpenMP start only threads -the code asks for, and with `libs` first in the library paths. +Tasks survive the end of the ssh connection and the session, and run with +`OMP_NUM_THREADS=1`, `MKL_NUM_THREADS=1` and `libs` first in the library paths. ## Model files and builds -The model files of a job are those of the model objects in `input` (`obsfn`, `parfn`, `prdfn`, -objectives), found through their sources; without any, all model files of -`getOption("dMod2.outdir")`, else of the working directory. `build` sets how they reach the nodes: +The model files of a job are those of the model objects in `input`; without any, all model +files of `getOption("dMod2.outdir")`, else of the working directory. `build`: -- `"compile"`: sources are copied and `build.sh` compiles them into one shared object against the - cppDE installed on the node, with cppDE headers, SUNDIALS, KLU, the model `-D` switches and - `-O2`. `buildCores` compilers run at once, by default the node cores, at most 16. Past the - command-line limit objects go through a static archive, `buildBundle` sources per translation - unit. +- `"compile"`: sources are compiled on the node into one shared object against the cppDE + installed there, with `buildCores` compilers (default the node cores, at most 16) and + `buildBundle` sources per translation unit. - `"link"`: object files are copied and linked, which needs a compatible compiler on the node. - `"copy"`: shared objects are copied, which needs a compatible node. - `"auto"`, the default: `"copy"` when all nodes are `"localhost"`, else `"compile"`. -The build runs once per node before the first task; `job.R` points every model object of the -workspace at the one shared object (`modelname()`). On SLURM it runs once on the login node for all -array tasks. Output goes to `build.log`; a failed build stops the submission and shows the end of -the log. `libs` prepends library paths on the nodes for build and tasks, expanded remotely, so `~` -is the remote home. - -The coverage job has no model files: no model object in `input`, no shared object in the working -directory. +The build runs once per node, on SLURM once on the login node. A failed build stops the +submission and shows the end of `build.log`. `libs` prepends library paths on the nodes; `~` is the +remote home. ## Job monitoring and recovery @@ -200,13 +171,10 @@ directory. | `purge(local = FALSE)` | deletes the job folders on the nodes, on `"localhost"` the local `_folder/`, with `local = TRUE` also local folder and registry entry | | `terminate()` | stops the tasks | -A task is done when the result file exists, running while the worker runs (also while waiting), -failed when the worker ended without a result. `get()` copies remote results over ssh into the +A task is failed when the worker ended without a result. `get()` copies remote results into the local `_folder/`, with `all = TRUE` all files. It joins parlists with `c()` and data -frames, parameter frames included, with `rbind()`, which merges the two sides of a profile; other -results come as a list. Missing results are dropped with a warning. `get(combine = FALSE)` returns -one entry per task, named like `tasks`: `NULL` if not done, the `try-error` if failed. -`terminate()` ends the process group of every slot, on SLURM the job by `scancel`. +frames with `rbind()`, which merges the two sides of a profile; other results come as a list. +`get(combine = FALSE)` returns one entry per task: `NULL` if not done, the `try-error` if failed. Output of the second task, then deletion: @@ -218,14 +186,11 @@ job$purge(local = TRUE) `distributedComputing(wait = TRUE)` waits, returns `get()` and deletes the job; a job with failed tasks is kept for `log()`. -A job outlives the session. The manifest is in the local `_folder`, in the -`_folder` of every remote node until `purge()`, and in the registry -`tools::R_user_dir("dMod2", "data")` until `purge(local = TRUE)`; -`dMod2Jobs()` lists registered jobs. `recover = TRUE` with a job name returns the job functions -without resubmitting, from the manifest in the working directory, else the registry, else, with -`on`, the remote node folders, which recovers a job from another machine. A new job of the same -name is an error while the old one runs where the new one would replace the old folders: in the same -working directory or on the same remote nodes, also from another machine. +A job outlives the session. The manifest is in the local and remote `_folder` and in +the registry `tools::R_user_dir("dMod2", "data")`; `dMod2Jobs()` lists registered jobs. +`recover = TRUE` with a job name returns the job functions without resubmitting, from the working +directory, the registry or, with `on`, the remote nodes, also for a job from another machine. A +new job of the same name is an error while the old one runs in the same folders. ```{r} dMod2Jobs() @@ -236,22 +201,16 @@ job <- distributedComputing(jobname = "fits", on = sshNodes(c("server1", "server ## SLURM clusters -`slurmCluster()` names the login node, reached by ssh, and the resources per array task: `cores`, -`walltime`, `memPerCore` in GB. Workers are the `array` array tasks, by default one per task; -array task `j` runs tasks `j`, `j + array`, `j + 2 * array`, ... in sequence. The stage goes to -`~/_folder/1` on the login node, where the template environment is set up, the model -files are built once, and `sbatch` submits from that folder, so compute nodes must see the -login-node home directory. `partition`, `account`, `maxRunning` (array tasks at once) and `sbatch` -(further options such as `"--constraint=ib"`) override the `#SBATCH` lines of the template. The -start reports the job ID; `check()` reads `squeue`, `terminate()` calls `scancel`. - -`slurmTemplate()` sets up the job script template once per login node, stored in -`tools::R_user_dir("dMod2", "config")`. A template is a cluster job script with placeholders -`{{ jobname }}`, `{{ ntasks }}` (array tasks), `{{ cores }}`, `{{ memPerCore }}`, -`{{ walltime }}`, and one line `{{ run }}` that runs the tasks. Non-comment lines before -`{{ run }}` set up the environment, e.g. `module load`, also for the build on the login node. A -placeholder without value is an error, so `{{ walltime }}` needs `walltime`. The shipped template -for the bwForCluster Helix: +`slurmCluster()` names the login node and the resources per array task: `cores`, `walltime`, +`memPerCore` in GB. Workers are the `array` array tasks, by default one per task. The job folder +is `~/_folder/1` on the login node, where the model files are built once and `sbatch` +submits, so compute nodes must see that home directory. `partition`, `account`, `maxRunning` and +`sbatch` (further options) override the `#SBATCH` lines of the template. + +`slurmTemplate()` sets up the job script template once per login node. A template is a job +script with placeholders `{{ jobname }}`, `{{ ntasks }}`, `{{ cores }}`, `{{ memPerCore }}`, +`{{ walltime }}` and one line `{{ run }}`; lines before `{{ run }}` set up the environment, also +for the build. The shipped template for the bwForCluster Helix: ```{r template, eval = TRUE} writeLines(readLines(system.file("slurm", "helix.sh", package = "dMod2"))) @@ -268,9 +227,7 @@ cluster <- slurmCluster("helix", cores = 1, walltime = "12:00:00") ## Fits and profiles of the guide project -A cluster starts many small tasks sooner than one large one, so these jobs use one core per task. -The 200 fits of `fit.R` ([Optimization](guide-optimization.html)) as 200 one-fit tasks, each start -drawn from the task seed: +The 200 fits of [Optimization](guide-optimization.html) as 200 one-fit tasks: ```{r} free <- setdiff(names(mu), names(gauge)) @@ -284,14 +241,14 @@ fits <- as.parframe(fitsJob$get()) fitsJob$purge(local = TRUE) ``` -The sources of `obj` compile once on the login node. `get()` joins the parlists, `as.parframe()` -sorts by value. A later session, also on another day, takes up the job by name: +A later session takes up the job by name: ```{r} fitsJob <- distributedComputing(jobname = "oppelt_fits", recover = TRUE) ``` -The profiles of [Profile likelihood](guide-profiles.html), one side of one parameter per task: +The profiles of [Profile likelihood](guide-profiles.html), one side of one parameter per task; +`get()` binds both sides into one profile: ```{r} sides <- expand.grid(par = names(best), side = c("left", "right"), stringsAsFactors = FALSE) @@ -306,26 +263,20 @@ profilesJob$wait(interval = 60) profiles <- profilesJob$get() ``` -`get()` binds both sides of each parameter into one profile. - An `msem()` multistart splits by `which`: every task draws all starts from the same seed and fits -those it names. The 200 starts of [Sparse deviations](guide-sparse-deviations.html), two per task: +those it names. The 200 starts of [Sparse deviations](guide-sparse-deviations.html): ```{r} -compoundsJob <- distributedComputing({ +dcfJob <- distributedComputing({ set.seed(3) - msem(objCompounds + priorCompounds, random, init, fixed = gaugeReduced, fits = 200, - sd = sdStart, keepFits = TRUE, which = task) -}, tasks = split(1:200, rep(1:100, each = 2)), on = cluster, jobname = "oppelt_compounds", -input = c("objCompounds", "priorCompounds", "random", "init", "gaugeReduced", "sdStart")) -fitCompounds <- compoundsJob$get() + msem(objSS, randomSS, c(initDCF, prob_compound = 0.2, tau_compound = 0.5), + fixed = gaugeReduced, fits = 200, sd = 0.5, keepFits = TRUE, which = task) +}, tasks = as.list(1:200), on = cluster, jobname = "oppelt_dcf", +input = c("objSS", "randomSS", "initDCF", "gaugeReduced")) +fitDCF <- dcfJob$get() ``` -`get()` returns one `msem()` fit, the best, with table and fits of all starts. `helix.R` of the -project runs the other expensive guide scripts the same way. - -Without SLURM, as many tasks run at once as there are nodes. One task per node, the default, with -ten fits per node core: +`get()` returns the best `msem()` fit with all starts. Over ssh, one task per node: ```{r} fitsJob <- distributedComputing( diff --git a/vignettes/articles/guide-sensitivities.Rmd b/vignettes/articles/guide-sensitivities.Rmd index ae83a988..f684152c 100644 --- a/vignettes/articles/guide-sensitivities.Rmd +++ b/vignettes/articles/guide-sensitivities.Rmd @@ -16,42 +16,33 @@ source("results/stored.R") s <- stored("results/sensitivities.rds", "sensitivities.R") ``` -Fits, profiles and mixed-effects models need derivatives of the objective. dMod2 computes them -exactly from the ODE sensitivities, propagated by the chain rule through every function object, -without finite differences. This chapter covers forward, forward over forward, reverse and forward -over reverse, the backends of `odemodel()`, and their costs on the guide model (`sensitivities.R` -of the project). Details: [Methods > Sensitivities and Hessians](methods-sensitivities.html). +dMod2 computes derivatives of the objective exactly from the ODE sensitivities and the chain rule +through every function object. Code: `sensitivities.R`; details: +[Methods > Sensitivities and Hessians](methods-sensitivities.html). ## Forward sensitivities -The default. `Xs()` integrates the sensitivities $\partial x / \partial \theta$ with the states, -and every function object of `g*x*p` multiplies them by the Jacobian of that object. The objective returns -gradient and Gauss-Newton Hessian for one solve with a tangent per parameter. `sensErrCon` in -`optionsSens` of `Xs()` sets whether sensitivities enter the error test, by default yes. With fixed -standard deviations the Gauss-Newton Hessian is positive semidefinite, with an error model it can -be indefinite +The default: `Xs()` integrates $\partial x / \partial \theta$ with the states, the objective +returns gradient and Gauss-Newton Hessian. `sensErrCon` in `optionsSens` sets whether +sensitivities enter the error test (default `TRUE`). With an error model the Gauss-Newton Hessian +can be indefinite ([Methods > Gauss-Newton with an error model](methods-sensitivities.html#gauss-newton-with-an-error-model)). ## Forward over forward -`deriv2 = TRUE` in `odemodel()`, `Y()`, `P()` and `Pimpl()` builds second-order sensitivities; the objective -called with `deriv2 = TRUE` and the forward sweep returns the exact Hessian. The equation count -grows with the square of the parameters, so this suits small models such as those of -[Nonlinear mixed-effects models](guide-nlme.html). The guide model with -`r nrow(s$gradients)` -parameters uses it once below to show the cost. +`deriv2 = TRUE` in `odemodel()`, `Y()`, `P()` and `Pimpl()` gives the exact Hessian from +second-order sensitivities. The equation count grows with the square of the parameters +(guide model: `r nrow(s$gradients)`); it suits small models such as those of +[Nonlinear mixed-effects models](guide-nlme.html). ## Reverse sweep -The gradient alone comes from one backward sweep of the adjoint system, at a cost independent of -the parameter count -([Methods > Reverse sweep](methods-sensitivities.html#reverse-sweep)). Every function object but -`Pimpl()`, which passes the sweep through the Jacobian of the root, is built with -`derivMode = c("forward", "reverse")`, and the model is called with `sweep = "reverse"`. Both -passes use the solver `options` alone; solves with sensitivities use `optionsSens` merged over -`options`. - -In `trust()` the sweep is set per phase: +One backward sweep of the adjoint system gives the gradient at a cost independent of the +parameter count ([Methods > Reverse sweep](methods-sensitivities.html#reverse-sweep)). Build with +`derivMode = c("forward", "reverse")` (`Pimpl()` passes the sweep through the Jacobian of the +root), call with `sweep = "reverse"`. Both passes solve with `options` alone; solves with +sensitivities use `optionsSens` merged over `options`. In +`trust()` the sweep is set per phase: ```{r, eval = FALSE} fit <- trust(obj, start, @@ -60,16 +51,11 @@ fit <- trust(obj, start, fit$phaseSweep ``` -Without `sweep`, `"bfgs"` and `"sr1"` phases sweep backwards if the objective allows it at the -start, otherwise forwards. Gauss-Newton always runs forwards, since $J^\top J$ needs forward -sensitivities; a `"gn"` phase with `sweep = "reverse"` is an error, and the objective called with -`sweep = "reverse"` returns no Gauss-Newton Hessian, with a warning where `hessian = TRUE` asks for -one. `"exact"` runs -forwards by default and backwards with `sweep = "reverse"`, where `deriv2 = TRUE` gives the exact -Hessian by forward over reverse. A change of sweep between phases evaluates the current iterate -once more. [Optimization](guide-optimization.html) compares the Hessian sources on the guide model. +Without `sweep`, `"bfgs"` and `"sr1"` phases sweep backwards if the objective allows it. +Gauss-Newton needs forward sensitivities: a `"gn"` phase with `sweep = "reverse"` is an error. +`"exact"` with `sweep = "reverse"` and `deriv2 = TRUE` uses forward over reverse. -The backward sweep follows the step grid of the value pass by default. On the cppDE backend, +The backward sweep follows the step grid of the value pass by default; on the cppDE backend `optionsReverse` of `Xs()` sets the accuracy, see `cppDE::adjointControl()`: ```{r, eval = FALSE} @@ -83,22 +69,21 @@ controls(x, name = "optionsReverse") <- list(refine = FALSE) # the grid of the | `refine` | `TRUE`: each sweep step passes the error test of the solve, else is redone in substeps | | `gradtol` | absolute tolerance for the share of each step in the gradient | -Under `refine`, value and `chi2` of the reverse objective include the change from the computed to -the refined trajectory, the attribute `correction` +Under `refine`, value and `chi2` include the change to the refined trajectory, attribute +`correction` ([Methods > Accuracy of a reverse gradient](methods-sensitivities.html#accuracy-of-a-reverse-gradient)). ## Forward over reverse -The exact Hessian without second-order sensitivities, one column per parameter from the backward -sweep ([Methods > Forward over reverse](methods-sensitivities.html#forward-over-reverse)). Build with -`derivMode = c("forward", "reverse", "forward-reverse")` and call with +The exact Hessian without second-order sensitivities, one column per parameter +([Methods > Forward over reverse](methods-sensitivities.html#forward-over-reverse)). Build with +`derivMode = c("forward", "reverse", "forward-reverse")`, call with `sweep = "reverse", deriv2 = TRUE`. FOCEI in [Nonlinear mixed-effects models](guide-nlme.html) -uses the same sweeps for directional second derivatives. +uses it for directional second derivatives. ## ODE backends -`odemodel(backend = )` selects the solver; the function objects above are the same, `Xs()` -dispatches on the model class. +`odemodel(backend = )` selects the solver: | backend | solver | forward | fwd/fwd | reverse | fwd/rev | use | |---|---|---|---|---|---|---| @@ -106,14 +91,15 @@ dispatches on the model class. | `"Sundials"` | CVODES, `cppDE::cvode()` | CVODES | no | CVODES ASA | no | first-order derivatives | | `"deSolve"` | `lsodes`, cOde | sens. equations | no | no | no | dMod models | -See cppDE on [stepping](https://dmodverse.github.io/cppDE/articles/methods-stepping.html), +cppDE on [stepping](https://dmodverse.github.io/cppDE/articles/methods-stepping.html), [CVODES](https://dmodverse.github.io/cppDE/articles/methods-cvode.html) and [benchmarks](https://dmodverse.github.io/cppDE/articles/benchmarks.html) against CVODES. ## Costs on the guide model -`sensitivities.R` rebuilds the chain of [Setting up models](guide-model.html) with all directions -and evaluates the data term at the best fit of [Optimization](guide-optimization.html): +`sensitivities.R` evaluates the data term of [Setting up models](guide-model.html) at the best +fit of [Optimization](guide-optimization.html); the results are loaded from +`results/sensitivities.rds`. ```{r reversechain, eval = FALSE} ``` @@ -122,7 +108,7 @@ and evaluates the data term at the best fit of [Optimization](guide-optimization s <- readRDS("results/sensitivities.rds") ``` -Reverse and forward gradients agree: +Relative difference of reverse and forward gradient: ```{r gradients, eval = FALSE} ``` @@ -131,8 +117,7 @@ Reverse and forward gradients agree: max(abs(s$gradients$forward - s$gradients$reverse)) / max(abs(s$gradients$forward)) ``` -within the solver tolerances, since the sweep without `refine` runs on the grid of the value -pass. Seconds per evaluation, minimum of ten: +Seconds per evaluation, minimum of ten: ```{r cost, eval = FALSE} ``` @@ -141,10 +126,9 @@ pass. Seconds per evaluation, minimum of ten: s$timing ``` -A reverse gradient costs a few values, a forward gradient one solve with a tangent per -parameter, forward over reverse about -`r round(s$timing[["forward-reverse"]] / s$timing[["forward"]], 1)` forward -gradients. Forward over forward, measured once: +Forward over reverse costs about +`r round(s$timing[["forward-reverse"]] / s$timing[["forward"]], 1)` forward gradients; forward over +forward, once: ```{r forwardforward, eval = FALSE} ``` @@ -160,9 +144,8 @@ peakText <- if (s$memory[["forwardForward"]] > s$memory[["before"]] + 0.05) { } else sprintf("leaves the peak memory of the process at %.1f GB", s$memory[["before"]]) ``` -It takes `r round(s$forwardForward / s$timing[["forward-reverse"]])` -times as long as forward over reverse and `r peakText`; -for this model it is a check, not a method. Both Hessians agree up to the solver error: +It takes `r round(s$forwardForward / s$timing[["forward-reverse"]])` times as long as forward +over reverse and `r peakText`. Relative difference of the two Hessians: ```{r hessians, eval = FALSE} ``` @@ -182,16 +165,11 @@ ggplot2::ggplot(eig, ggplot2::aes(rank, value, color = Hessian)) + ggplot2::scale_y_continuous(trans = scales::pseudo_log_trans(sigma = 1e-3, base = 10), breaks = c(-1e-1, 0, 1e-2, 1, 1e2, 1e4)) + ggplot2::labs(x = "rank", y = "eigenvalue") + - theme_dMod() + theme_dMod2() ``` -They agree in the large eigenvalues, the well-determined directions. The smallest eigenvalue is -`r signif(min(s$hessians$exact), 2)` for the exact Hessian and -`r signif(min(s$hessians$gaussNewton), 2)` for Gauss-Newton. The model estimates the standard -deviations of the imaging readouts, and with an error model Gauss-Newton can be indefinite -([Gauss-Newton with an error model](methods-sensitivities.html#gauss-newton-with-an-error-model)). -In the flat directions the Hessian sources of [Optimization](guide-optimization.html) take -different steps. +The smallest eigenvalue is `r signif(min(s$hessians$exact), 2)` for the exact Hessian and +`r signif(min(s$hessians$gaussNewton), 2)` for Gauss-Newton. Reference: `odemodel()`, `Xs()`, `Y()`, `P()`, `Pimpl()`, `normL2()`, `controls()`, `trust()` diff --git a/vignettes/articles/guide-sparse-deviations.Rmd b/vignettes/articles/guide-sparse-deviations.Rmd index 9e1cc4c5..8c8e2264 100644 --- a/vignettes/articles/guide-sparse-deviations.Rmd +++ b/vignettes/articles/guide-sparse-deviations.Rmd @@ -13,25 +13,22 @@ knitr::opts_knit$set(root.dir = project) source("results/stored.R") knitr::read_chunk("../../examples/oppeltNPJSystBiolAppl2018/model.R") knitr::read_chunk("../../examples/oppeltNPJSystBiolAppl2018/reduced.R") -knitr::read_chunk("../../examples/oppeltNPJSystBiolAppl2018/compounds.R") +knitr::read_chunk("../../examples/oppeltNPJSystBiolAppl2018/dcf.R") # "a", "a and b", "a, b and c" enumerate <- function(x) if (length(x) < 2) paste(x) else paste(paste(x[-length(x)], collapse = ", "), "and", x[length(x)]) ``` -Oppelt et al. [@oppelt2018model] also measured the TNFα response under drugs causing liver -injury: diclofenac (DCF) with the imaging and blots of the first chapters, and amiodarone (AMD), -paracetamol (APAP), fialuridine (FIAU) and ximelagatran (XIM) with four blots. Which pathway -processes does each compound change? The publication answered this for DCF with an L1 penalty on -the differences of all rate constants between treated and untreated cells, scanned over the -penalty strength. Here all five compounds are the groups of a spike-and-slab random effect: a -compound leaves a rate constant unchanged or changes it by a normal draw, with probability and -spread of changes estimated from all compounds together. Code: `compounds.R`, on the reduced model -of [Profile likelihood](guide-profiles.html); random effects and `em()` are introduced in -[Nonlinear mixed-effects models](guide-nlme.html). +Oppelt et al. [@oppelt2018model] also measured the TNFα response of HepG2 cells under diclofenac +(DCF). Which rate constants does DCF change? The publication selected differences by an L1 scan and +a likelihood ratio test [@steiert2016l1]. This chapter repeats the scan and answers the same +question with spike-and-slab random effects. Model: the reduced model of +[Profile likelihood](guide-profiles.html); random effects and `em()`: +[Nonlinear mixed-effects models](guide-nlme.html). `dcf.R` computed the fits; the chapter loads +them. -The second part lists the sparse random-effect distributions (spike-and-slab, Dirichlet-process) -and what their fits report; derivations are in [Methods > Sparsity priors](methods-sparsity-priors.html). +The second part lists the sparse random-effect distributions and what their fits report; +derivations: [Methods > Sparsity priors](methods-sparsity-priors.html). ```{r setup, echo = FALSE} ``` @@ -39,282 +36,450 @@ and what their fits report; derivations are in [Methods > Sparsity priors](metho ```{r data, echo = FALSE} ``` -```{r reducedreactions, echo = FALSE} +```{r reactions, include = FALSE} ``` -## Compound data +```{r observables, include = FALSE} +``` -Each compound has a separate control: DCF on the blots and imaging of the first chapters, the other -four on a third blot set with their own untreated, stimulated control. A condition without compound -belongs to no group (`NA` in column `compound`). +```{r errors, include = FALSE} +``` -```{r compounddata} +```{r odemodel, include = FALSE} ``` -```{r} -covariates(dataCompounds) +```{r gauge, include = FALSE} +``` + +```{r reducedreactions, include = FALSE} +``` + +```{r reducedobservables, include = FALSE} +``` + +```{r reducedmodel, include = FALSE} ``` -## Spike-and-slab random effects +## Data and model -With $\theta_k$ the log rate constant $k$ and $\eta_{ik}$ the change by compound $i$, a condition -with compound $i$ uses $\theta_k + \eta_{ik}$, one without uses $\theta_k$. The spike-and-slab -distribution [@mitchell1988bayesian; @george1993variable] of a change is +TNFα-stimulated cells of the first blot scale, without (`TNF_none`) and with DCF (`TNF_DCF`). -$$p(\eta_{ik}) = (1 - \rho)\, \delta(\eta_{ik}) + \rho\, \mathcal{N}(\eta_{ik};\, 0, \tau^2),$$ +```{r dcfdata} +``` -a spike at 0 with weight $1 - \rho$ and a normal slab of standard deviation $\tau$ with weight -$\rho$. Changes are independent across compounds and rate constants; $\rho$, $\tau$ are shared. -`em()` estimates $\theta$, $\rho$ and $\tau$ from the likelihood with the changes integrated out, a -sum over the subsets of changed rate constants -([Methods > Sparsity priors](methods-sparsity-priors.html#approximate-marginal)). The -posterior spike probability $p_0 = \Pr(\eta_{ik} = 0 \mid y)$ near 0 means a change, near the prior -$1 - \rho$ no evidence, above it evidence against a change. +With DCF an estimated rate constant $k$ becomes $\log k + \Delta_k$. `insert()` with +`x ~ 1 + (1 | gr(compound, dist = spikeSlab()))` writes each $\Delta_k$ as a random effect +`eta__DCF`, 0 without compound; the L1 scan treats the same symbols as parameters. 24 +differences, as in the publication: + +```{r dcfmodel, results = "hide"} +``` ```{r, include = FALSE} -fit <- stored("results/compounds.rds", "compounds.R", envir = new.env()) -rateConstants <- length(unique(fit$random$eta)) +# the fixed values of the reduced model on the parameters of the DCF model +fixedDCF <- gauge[intersect(names(gauge), getParameters(prdDCF))] +changesDCF <- unique(na.omit(unlist(randomEffects(pDCF)$etas))) +# the prediction of both conditions at `pars`, the changes not in `pars` at 0, as a data frame +predictionOf <- function(prd, pars, changes) { + off <- setdiff(changes, names(pars)) + data <- as.data.frame(dataDCF) + times <- sort(unique(c(seq(0, max(data$time), length.out = 200), data$time))) + as.data.frame(prd(times, pars, fixed = c(fixedDCF, setNames(numeric(length(off)), off)))) +} +dataFrameDCF <- as.data.frame(dataDCF) +onceDCF <- names(which(tapply(dataFrameDCF$time, dataFrameDCF$name, function(t) length(unique(t))) == 1L)) +# against the data, each observable up to the last time it was measured, without those measured once +fitPlot <- function(prd, pars, changes) { + pred <- predictionOf(prd, pars, changes) + data <- dataFrameDCF[!dataFrameDCF$name %in% onceDCF, ] + last <- tapply(data$time, data$name, max) + pred <- pred[pred$name %in% names(last), ] + pred <- pred[pred$time <= last[as.character(pred$name)], ] + ggplot2::ggplot(data, ggplot2::aes(time, value, color = condition)) + + ggplot2::geom_line(data = pred) + + ggplot2::geom_errorbar(ggplot2::aes(ymin = value - sigma, ymax = value + sigma), width = 0, + na.rm = TRUE) + + ggplot2::geom_point(size = 1.2) + + ggplot2::facet_wrap(~ name, scales = "free") + + scale_color_dMod2() + + ggplot2::labs(x = "time [min]", y = "log signal", color = NULL) + + theme_dMod2() +} +# the observables measured at one time: data and prediction per condition +fitOnce <- function(prd, pars, changes) { + pred <- predictionOf(prd, pars, changes) + data <- dataFrameDCF[dataFrameDCF$name %in% onceDCF, c("name", "time", "condition", "value", "sigma")] + pred <- unique(merge(pred[pred$name %in% onceDCF, c("name", "time", "condition", "value")], + unique(data[c("name", "time")]))) + names(pred)[names(pred) == "value"] <- "prediction" + out <- merge(pred, data) + out[c("prediction", "value", "sigma")] <- lapply(out[c("prediction", "value", "sigma")], round, 2) + out +} ``` -Each compound has `r rateConstants` candidate rate constants, and the subset sum is exact; beyond -a term budget `em()` uses the expectation consistent (EC) approximation -([Methods > Spike and slab](methods-sparsity-priors.html#spike-and-slab)). Comparison with the -L1 penalty: [Methods > Selection of deviations](methods-sparsity-priors.html#selection-of-deviations). +## L1 scan -## Compound model +The penalty $\lambda \sum_k \lvert \Delta_k \rvert$ [@tibshirani1996regression; @steiert2016l1] is +added to $-2 \log L$; `trustL1()` sets differences exactly to 0 +([L1 penalties](guide-optimization.html#l1-penalties)). -The reduced model of [Profile likelihood](guide-profiles.html) with second derivatives for `em()`. -The resting state of the reduced model (all NFκB bound to IκBα, all IKK inactive) holds for all -rate constants, so a compound changes the dynamics only from TNFα on: +Four rate constants enter the data only as a product with a partner: `uptake` with +`act_Ikk_by_TNF`, `prod_Ikb` with `prod_mIkb_by_nNfk`, `build_RnaA20` with `build_A20`, and +`split_NfkIkb` with `eta_split_pNfkpIkb`. The reduced model fixes the four as gauge +([Symmetries](guide-symmetries.html)), so their differences are 0, and both methods share the +other 20 candidates. The publication penalized all 24 and set partners aside after the scan. -```{r reactions, include = FALSE} +Each $\lambda$, 0 and 31 values from $10^{-2}$ to $10^4$ evenly on the log scale, runs 1000 starts +around the reduced fit, then starts from the best fits of the other $\lambda$ until none improves. +`dcf.R` runs the fits through `fitTasks()` ([Remote computing](guide-remote-computing.html)): + +```{r dcfL1, eval = FALSE} ``` -```{r observables, include = FALSE} +```{r dcfL1continue, eval = FALSE} ``` -```{r errors, include = FALSE} +```{r} +dcfL1 <- stored("results/dcfL1.rds", "dcf.R", envir = new.env()) ``` -```{r odemodel, include = FALSE} +Waterfall of the best 200 values of $-2 \log L$ of the data, without the penalty, per $\lambda$, +the y axis shared within a row: + +```{r, fig.width = 11, fig.height = 13} +objectiveL1 <- dcfL1$penalized +lambdaL1 <- sort(unique(objectiveL1$lambda)) +# the best 200 fits per lambda, six lambdas per row, the y axis shared within a row +best200 <- function(x) { + x <- head(x[order(x$value), ], 200) + x$rank <- seq_len(nrow(x)) + x +} +waterL1 <- do.call(rbind, lapply(seq_along(lambdaL1), function(i) + cbind(best200(objectiveL1[objectiveL1$lambda == lambdaL1[i], ]), row = (i - 1) %/% 6, + col = (i - 1) %% 6, label = sprintf("lambda == %s", format(signif(lambdaL1[i], 3)))))) +ggplot2::ggplot(waterL1, ggplot2::aes(rank, value)) + + ggplot2::geom_point(ggplot2::aes(color = converged), size = 0.8) + + ggplot2::geom_text(data = unique(waterL1[c("row", "col", "label")]), + ggplot2::aes(x = 100, y = Inf, label = label), parse = TRUE, vjust = 1.4, + inherit.aes = FALSE) + + ggplot2::facet_grid(row ~ col, scales = "free_y") + + ggplot2::scale_color_manual(values = c(`TRUE` = "black", `FALSE` = dMod2_colors[2]), + labels = c(`TRUE` = "converged", `FALSE` = "not converged"), + name = NULL) + + ggplot2::scale_y_continuous(expand = ggplot2::expansion(mult = c(0.05, 0.25))) + + ggplot2::labs(x = "fit rank", y = "-2 log L of the data") + + theme_dMod2() + + ggplot2::theme(strip.text = ggplot2::element_blank(), legend.position = "bottom") ``` -```{r gauge, include = FALSE} +```{r, include = FALSE} +penalizedAll <- dcfL1$penalized +penalizedAll$objective <- penalizedAll$value + penalizedAll$lambda * penalizedAll$L1 +reachedL1 <- tapply(penalizedAll$objective, penalizedAll$lambda, function(v) sum(v < min(v) + 0.1)) +waterText <- sprintf(paste( + "Of at least %d fits per $\\lambda$, %d to %d reach the best penalized value within 0.1, a median %.0f; most", + "others end at local optima or crawl and stop short."), + min(table(penalizedAll$lambda)), min(reachedL1), max(reachedL1), median(reachedL1)) ``` -```{r reducedobservables, include = FALSE} +`r waterText` + +Differences over $\lambda$ (Fig. 2a of the publication), in color those kept at the selected +$\lambda$ (dashed): + +```{r, fig.width = 8, fig.height = 4.5} +paths <- data.frame(lambda = rep(as.numeric(rownames(dcfL1$path)), ncol(dcfL1$path)), + difference = rep(sub("^eta_(.*)_DCF$", "\\1", colnames(dcfL1$path)), + each = nrow(dcfL1$path)), + value = as.vector(dcfL1$path)) +paths <- paths[paths$lambda > 0, ] +kept <- sub("^eta_(.*)_DCF$", "\\1", dcfL1$selected) +ggplot2::ggplot(paths, ggplot2::aes(lambda, value, group = difference)) + + ggplot2::geom_vline(xintercept = dcfL1$lambda, linetype = 2, color = "gray50") + + ggplot2::geom_line(data = paths[!paths$difference %in% kept, ], color = "gray75") + + ggplot2::geom_line(data = paths[paths$difference %in% kept, ], ggplot2::aes(color = difference)) + + ggplot2::scale_x_log10(breaks = 10^(-2:4), labels = trimws(format(10^(-2:4), scientific = FALSE, drop0trailing = TRUE))) + + ggplot2::labs(x = expression(lambda), y = expression(Delta ~ "[log]"), color = NULL) + + theme_dMod2() ``` -```{r reducedmodel, include = FALSE} +Over $\lambda$ (Fig. 2b): $-2 \log L$ of the data (black), plus penalty (red, penalty gray), and +the number of nonzero differences: + +```{r, fig.width = 8, fig.height = 5} +scan <- dcfL1$scan[dcfL1$scan$lambda > 0, ] +curves <- rbind(data.frame(lambda = scan$lambda, value = scan$data, panel = "-2 log L", curve = "data"), + data.frame(lambda = scan$lambda, value = scan$data + scan$penalty, panel = "-2 log L", + curve = "data + penalty"), + data.frame(lambda = scan$lambda, value = scan$changes, panel = "nonzero differences", + curve = "count")) +ggplot2::ggplot(curves, ggplot2::aes(lambda, value)) + + ggplot2::geom_ribbon(data = data.frame(lambda = scan$lambda, lo = scan$data, + hi = scan$data + scan$penalty, panel = "-2 log L"), + ggplot2::aes(x = lambda, ymin = lo, ymax = hi), inherit.aes = FALSE, + fill = "gray85") + + ggplot2::geom_vline(xintercept = dcfL1$lambda, linetype = 2, color = "gray50") + + ggplot2::geom_line(ggplot2::aes(color = curve)) + + ggplot2::scale_color_manual(values = c(data = "black", `data + penalty` = "#b2182b", + count = "#2166ac"), guide = "none") + + ggplot2::scale_x_log10(breaks = 10^(-2:4), labels = trimws(format(10^(-2:4), scientific = FALSE, drop0trailing = TRUE))) + + ggplot2::facet_wrap(~ panel, ncol = 1, scales = "free_y") + + ggplot2::labs(x = expression(lambda), y = NULL) + + theme_dMod2() ``` -```{r compoundmodel} +The differences kept at each $\lambda$ are refitted without penalty, the others at 0, from the +best penalized fits and from 300 or more starts around the reduced fit. Selected is the largest +$\lambda$ whose refit the likelihood ratio test against all 20 candidates does not reject at +$p < 0.001$, as in the publication: + +```{r dcfL1select, eval = FALSE} ``` -`x ~ 1 + (1 | gr(compound, dist = spikeSlab()))` in `insert()` replaces rate constant `x` by a -fixed effect plus a compound random effect. Candidates are the rate constants the reduced model -estimates, all but gauge and fixed values of the publication. Scales and offsets of the third blot -set are separate parameters, except `off_IkBa`, fixed at 0 by the reduced model. +```{r, include = FALSE} +fullScan <- dcfL1$scan +rejected <- fullScan[!is.na(fullScan$p) & fullScan$p < 0.001 & fullScan$lambda > dcfL1$lambda, ][1, ] +selectedRow <- fullScan[fullScan$lambda == dcfL1$lambda, ] +scanText <- sprintf(paste( + "The test rejects from $\\lambda = %.3g$ on, with %d differences and %.0f in $-2 \\log L$", + "above the refit with all 20; the publication, with 24 candidates, rejected from $\\lambda = 10$", + "on, with 11 differences and 34. Kept at $\\lambda = %.3g$ are %d differences: %s."), + rejected$lambda, rejected$changes, rejected$refit - dcfL1$all$value, dcfL1$lambda, + selectedRow$changes, enumerate(paste0("`", sort(kept), "`"))) +``` -```{r compoundeffects, warning = FALSE} +`r scanText` + +Of the 11 differences at $\lambda = 10$ the publication kept seven as independent +[@oppelt2018model]: it dropped `uptake`, `prod_Ikb`, `eta_int_pNfk` and `act_Nfk_by_Ikk` and took +`shuttle_RnaA20` in place of `build_A20`. The seven refitted alone, against the estimates and 95 % +intervals of the publication: + +```{r} +publicationDCF <- dcfL1$publication +publicationDCF$refit <- unname(dcfL1$refitPublication$argument[paste0("eta_", publicationDCF$rate, "_DCF")]) +publicationDCF ``` -## Joint fit of all compounds +```{r, include = FALSE} +inside <- with(publicationDCF, refit >= lower & refit <= upper) +candidates <- ncol(dcfL1$path) +inSelected <- all(paste0("eta_", publicationDCF$rate, "_DCF") %in% dcfL1$selected) +publicationText <- sprintf(paste( + "%s lie in the intervals of the publication. Against the refit with all %d candidates the seven", + "give %.0f more in $-2 \\log L$ with %d fewer parameters, $p = %.2f$.%s"), + if (all(inside)) "All seven estimates" else sprintf("%d of the seven estimates, all but %s,", + sum(inside), enumerate(sprintf("`%s` (%.2f)", publicationDCF$rate[!inside], publicationDCF$refit[!inside]))), + candidates, dcfL1$refitPublication$value - dcfL1$all$value, candidates - nrow(publicationDCF), + pchisq(dcfL1$refitPublication$value - dcfL1$all$value, candidates - nrow(publicationDCF), lower.tail = FALSE), + if (!inSelected) "" else sprintf(paste( + " All seven are among the %d kept by the scan, against which they give %.0f more with %d fewer", + "parameters, $p = %.2f$."), length(dcfL1$selected), + dcfL1$refitPublication$value - dcfL1$refitSelected$value, length(dcfL1$selected) - nrow(publicationDCF), + pchisq(dcfL1$refitPublication$value - dcfL1$refitSelected$value, + length(dcfL1$selected) - nrow(publicationDCF), lower.tail = FALSE))) +``` -`em()` estimates fixed effects, change modes, $\rho$ and $\tau$ together. `compounds.R` runs 200 -starts, the reduced optimum with changes at 0 and 199 around it, redrawing failed starts; `helix.R` -splits them into `distributedComputing()` tasks by `msem(which = )` -([Remote computing](guide-remote-computing.html)): +`r publicationText` The model with the seven differences against the data (Fig. 2c); observables +measured once in the table: -```{r compoundfit, eval = FALSE} +```{r, fig.width = 10, fig.height = 8} +fitPlot(prdDCF, dcfL1$refitPublication$argument, changesDCF) +fitOnce(prdDCF, dcfL1$refitPublication$argument, changesDCF) ``` -The best fit is saved with a table of all starts: +## Spike and slab + +With $\theta_k$ the log rate constant $k$, cells with DCF use $\theta_k + \Delta_k$. The +spike-and-slab distribution [@mitchell1988bayesian; @george1993variable] of a difference is + +$$p(\Delta_k) = (1 - \rho)\, \delta(\Delta_k) + \rho\, \mathcal{N}(\Delta_k;\, 0, \tau^2),$$ -```{r compoundsave, eval = FALSE} +with inclusion probability $\rho$ (`prob_compound`) and slab standard deviation $\tau$ +(`tau_compound`, log scale). `em()` estimates $\theta$, $\rho$ and $\tau$ from the likelihood with +the differences integrated out, a sum over subsets +([Methods > Sparsity priors](methods-sparsity-priors.html#approximate-marginal)). +$p_0 = \Pr(\Delta_k = 0 \mid y)$ is the posterior spike probability. + +The candidates are the same 20 as in the L1 scan; with both partners of a product as candidates, +neither would reach a probability of one half. `dcf.R` runs 1000 starts of `msem()` around the +reduced fit, then 200 around the best. Waterfall of the 200: + +```{r dcfspikeslab, eval = FALSE} ``` -```{r} -fit <- readRDS("results/compounds.rds") -c(value = fit$value, converged = fit$converged, iterations = fit$iterations) -fit$argument[c("prob_compound", "tau_compound")] -fit$coupling +```{r dcfspikeslabmore, eval = FALSE} +``` + +```{r, fig.height = 3.5} +dcfSS <- stored("results/dcf.rds", "dcf.R", envir = new.env()) +plotValues(dcfSS, round == 2) +dcfSS$argument[c("prob_compound", "tau_compound")] ``` ```{r, include = FALSE} -couplingText <- switch(fit$coupling %||% "none", - expectationConsistent = "the expectation consistent (EC) approximation", - none = "none: every compound is integrated exactly") +first <- dcfSS$multistart[dcfSS$multistart$round == 1, ] +second <- dcfSS$multistart[dcfSS$multistart$round == 2, ] +plateau <- c(sum(first$value < dcfSS$value + 0.1), sum(second$value < dcfSS$value + 0.1)) +hyperText <- sprintf( + "%d of the %d starts around the reduced fit and %d of the %d around the best end within 0.1 of the best value. With $\\rho = %.2f$ a difference is expected for %.0f of the 20 rate constants; with $\\tau = %.2f$ a difference is typically a factor of %.1f.", + plateau[1], nrow(first), plateau[2], nrow(second), dcfSS$argument[["prob_compound"]], + 20 * dcfSS$argument[["prob_compound"]], dcfSS$argument[["tau_compound"]], + exp(dcfSS$argument[["tau_compound"]])) ``` -`value` is $-2 \log L$ of the approximate marginal, `iterations` the steps of the joint trust -region of fixed effects and hyperparameters, `coupling` the integral over coupled changes, here -`r couplingText`. +`r hyperText` Probability of a difference, $1 - p_0$, labeled with the difference in the most +probable subset; crosses mark the seven of the publication: + +```{r, fig.width = 8, fig.height = 5} +probability <- dcfSS$random[, c("eta", "mode", "p0")] +probability$eta <- factor(probability$eta, levels = rev(probability$eta)) +probability$publication <- probability$eta %in% publicationDCF$rate +ggplot2::ggplot(probability, ggplot2::aes(1 - p0, eta)) + + ggplot2::geom_col(fill = "#2166ac") + + ggplot2::geom_vline(xintercept = 0.5, linetype = 2, color = "gray50") + + ggplot2::geom_text(data = probability[probability$mode != 0, ], + ggplot2::aes(label = sprintf("%.2f", mode)), hjust = -0.2, size = 3) + + ggplot2::geom_point(data = probability[probability$publication, ], ggplot2::aes(x = -0.04), + shape = 4, size = 2.5) + + ggplot2::scale_x_continuous(limits = c(-0.06, 1.15), breaks = seq(0, 1, 0.25)) + + ggplot2::labs(x = "probability of a difference", y = NULL) + + theme_dMod2() +``` -## Multistart optimization +```{r, include = FALSE} +ssSet <- as.character(probability$eta[probability$mode != 0]) +sharedSS <- intersect(ssSet, publicationDCF$rate) +sameSign <- all(sign(dcfSS$random$mode[match(sharedSS, dcfSS$random$eta)]) == + sign(publicationDCF$value[match(sharedSS, publicationDCF$rate)])) +missing <- setdiff(publicationDCF$rate, ssSet) +extra <- setdiff(ssSet, publicationDCF$rate) +ssText <- sprintf(paste( + "The most probable subset holds %d differences, %d of them among the seven of the publication,", + if (sameSign) "with the same signs." else "not all with the same signs.", "%s%s", + "Refitted without the slab, the subset gives %.0f more in $-2 \\log L$ than all 20 candidates,", + "the seven of the publication %.0f."), + length(ssSet), length(sharedSS), + if (length(missing)) sprintf("Not in it: %s. ", enumerate(sprintf("`%s` ($p_0 = %.2f$)", missing, + dcfSS$random$p0[match(missing, dcfSS$random$eta)]))) else "", + if (length(extra)) sprintf("In addition: %s. ", enumerate(sprintf("`%s`", extra))) else "", + dcfL1$refitSpikeSlab$value - dcfL1$all$value, dcfL1$refitPublication$value - dcfL1$all$value) +# the likelihood ratio test of the subset against the seven of the publication, where it lies in them +if (all(ssSet %in% publicationDCF$rate)) { + gainPub <- dcfL1$refitSpikeSlab$value - dcfL1$refitPublication$value + dfPub <- nrow(publicationDCF) - length(ssSet) + ssText <- paste(ssText, sprintf(paste( + "Against the seven, the subset gives %.2f more in $-2 \\log L$ with %d %s fewer, $p = %.2f$."), + gainPub, dfPub, if (dfPub == 1L) "parameter" else "parameters", + pchisq(gainPub, dfPub, lower.tail = FALSE))) +} +``` -The objective has local optima. `msem()` redraws a start whose fit fails, e.g. where EC does not -converge. `$multistart` has per start `value`, `converged`, `iterations`, attempts (`tries`) and the -`error` of a start that failed every attempt. The waterfall shows the best 100 starts; a plateau is -one optimum. +`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: + +```{r, fig.width = 8, fig.height = 3} +rho <- dcfSS$argument[["prob_compound"]] +tau <- dcfSS$argument[["tau_compound"]] +nonzero <- dcfSS$random$mode[dcfSS$random$mode != 0] +slab <- data.frame(x = seq(-4, 4, length.out = 401)) +slab$density <- 20 * rho * dnorm(slab$x, 0, tau) +ggplot2::ggplot() + + ggplot2::geom_line(data = slab, ggplot2::aes(x, density)) + + ggplot2::geom_rug(data = data.frame(x = nonzero), ggplot2::aes(x), sides = "b", linewidth = 0.8, + length = grid::unit(0.08, "npc")) + + ggplot2::geom_segment(ggplot2::aes(x = 0, xend = 0, y = 0, yend = sum(dcfSS$random$mode == 0)), + linewidth = 2, color = dMod2_colors[2]) + + ggplot2::geom_point(ggplot2::aes(x = 0, y = 20 * (1 - rho)), shape = 4, size = 3) + + ggplot2::labs(x = expression(Delta ~ "[log]"), y = "differences per unit") + + theme_dMod2() +``` -```{r, fig.height = 3.5} -plotValues(fit, rank(value, ties.method = "first") <= 100) +The model at the spike-and-slab estimates against the data: + +```{r, fig.width = 10, fig.height = 8} +parsSS <- c(dcfSS$argument[setdiff(names(dcfSS$argument), c("prob_compound", "tau_compound"))], + setNames(dcfSS$random$mode, paste0("eta_", dcfSS$random$eta, "_DCF"))) +fitPlot(gDCF * xDCF * pSS, parsSS, unique(na.omit(unlist(randomEffects(pSS)$etas)))) +fitOnce(gDCF * xDCF * pSS, parsSS, unique(na.omit(unlist(randomEffects(pSS)$etas)))) ``` ```{r, include = FALSE} -ms <- fit$multistart -best <- min(ms$value, na.rm = TRUE) -multistartText <- sprintf( - "Of the %d starts, %d end within 1 of the best -2 log L, %d did not converge and %d failed.", - nrow(ms), sum(ms$value < best + 1, na.rm = TRUE), sum(!ms$converged & !is.na(ms$value)), - sum(is.na(ms$value))) -retriedText <- if (is.null(ms$tries) || !any(ms$tries > 1)) "" else - sprintf("%d of the starts were drawn again, %d times in all.", sum(ms$tries > 1), sum(ms$tries - 1)) +# bias: the kept differences at the penalized estimates against their refit without penalty, and +# the spike-and-slab values against the refit of the same subset +keptNames <- dcfL1$selected +shrinkL1 <- abs(dcfL1$refitSelected$argument[keptNames]) - abs(dcfL1$penalizedSelected[keptNames]) +ssNames <- paste0("eta_", ssSet, "_DCF") +shiftSS <- abs(dcfSS$random$mode[match(ssSet, dcfSS$random$eta)]) - abs(dcfL1$refitSpikeSlab$argument[ssNames]) +ssInL1 <- all(ssNames %in% dcfL1$selected) +compareText <- sprintf(paste( + "It needs one multistart, no scan over $\\lambda$ and no refits. The penalty shrinks every kept", + "difference toward 0, at the selected $\\lambda$ by a median %.2f on the log scale against the", + "refit without the penalty, more at larger $\\lambda$; the spike and slab leaves the size of a", + "difference to the slab, and the spike-and-slab differences lie a median %.2f from the refit of", + "the same subset.%s"), + median(shrinkL1), median(abs(shiftSS)), + if (!ssInL1) "" else sprintf(paste( + " The most probable subset lies within the %d differences the scan keeps and fits the data", + "not worse than they do, $p = %.2f$ for the %d others."), length(dcfL1$selected), + pchisq(dcfL1$refitSpikeSlab$value - dcfL1$refitSelected$value, + length(dcfL1$selected) - length(ssNames), lower.tail = FALSE), + length(dcfL1$selected) - length(ssNames))) ``` -`r multistartText` `r retriedText` - -## Changes by compound +## L1 scan and spike and slab -Changes with $p_0 < 0.05$, with log-scale modes: +Both methods see the same data, model, prior and 20 candidates: -```{r} -changes <- fit$random[fit$random$p0 < 0.05, c("group", "eta", "mode", "se", "p0")] -changes <- changes[order(changes$group, changes$p0), ] -rownames(changes) <- NULL -changes +```{r, echo = FALSE} +allValue <- dcfL1$all$value +row <- function(method, set, value) data.frame(method = method, differences = length(set), + `-2 log L` = round(value, 2), `p against all 20` = signif(pchisq(value - allValue, 20 - length(set), + lower.tail = FALSE), 2), check.names = FALSE) +knitr::kable(rbind(row("L1 scan and test", dcfL1$selected, dcfL1$refitSelected$value), + row("spike and slab", ssNames, dcfL1$refitSpikeSlab$value), + row("publication", publicationDCF$rate, dcfL1$refitPublication$value), + row("all candidates", seq_len(20), allValue))) ``` +The spike and slab is faster and free of shrinkage. `r compareText` The L1 scan +only tests subsets that are the penalized optimum at some $\lambda$; the spike and slab weighs every +subset ([Methods > Selection of deviations](methods-sparsity-priors.html#selection-of-deviations)). +The fit reports the most probable subset; the differences with $p_0 < 0.5$, the median probability +model, which predicts best under broad conditions [@barbieri2004optimal], +`r medianSS <- as.character(dcfSS$random$eta[dcfSS$random$p0 < 0.5]); if (setequal(medianSS, ssSet)) "are the same here" else sprintf("are %s here", enumerate(paste0("\x60", sort(medianSS), "\x60")))`. + ```{r, include = FALSE} -compounds <- sort(unique(fit$random$group)) -rates <- unique(fit$random$eta) -counts <- table(factor(changes$group, levels = compounds)) -others <- setdiff(compounds, "DCF") -changesText <- sprintf( - "DCF changes %d of the %d rate constants, %s. The probability of a change is %.2f, and a change has a spread of %.2f on the log scale, a factor of about %.1f.", - counts[["DCF"]], length(rates), enumerate(sprintf("%s %d", others, counts[others])), - fit$argument[["prob_compound"]], fit$argument[["tau_compound"]], exp(fit$argument[["tau_compound"]])) -# the seven rate constants the L1 scan of the publication selected for DCF, by reaction -publication <- c(act_Ikk_by_TNF = "IKK activation by TNFα", trigger_iIkk = "IKK recovery", - act_pIkk = "IKK phosphorylation", act_Ikb_by_Ikk = "IκBα phosphorylation by pIKK", - prod_mIkb_by_nNfk = "IκBα transcription", degrad_mIkb = "IκBα transcript degradation", - build_A20 = "A20 translation") -reactions <- c(publication, shuttle_RnaA20 = "the delay of the A20 transcript") -named <- function(x) ifelse(x %in% names(reactions), paste0(reactions[x], " (`", x, "`)"), paste0("`", x, "`")) -dcf <- changes$eta[changes$group == "DCF"] -shared <- intersect(names(publication), dcf) -publicationText <- paste0( - sprintf("Of the %d rate constants the L1 scan of the publication selected for DCF, the spike and slab finds %d: %s", - length(publication), length(shared), enumerate(named(shared))), - if (length(setdiff(names(publication), dcf))) - sprintf("; not %s", enumerate(named(setdiff(names(publication), dcf)))), - if (length(setdiff(dcf, names(publication)))) - sprintf(", but %s", enumerate(named(setdiff(dcf, names(publication))))), - ".") -``` - -`r changesText` `r publicationText` [@oppelt2018model] - -```{r, fig.height = 5.5} -shown <- fit$random -shown$eta <- factor(shown$eta, levels = unique(shown$eta)) -shown$evidence <- -log10(pmax(shown$p0, 1e-6)) -ggplot2::ggplot(shown, ggplot2::aes(group, eta)) + - ggplot2::geom_tile(ggplot2::aes(fill = mode, alpha = evidence), color = "white") + - ggplot2::geom_point(data = shown[shown$p0 < 0.05, ], ggplot2::aes(shape = "p0 < 0.05"), - fill = "white") + - ggplot2::scale_y_discrete(limits = rev) + - ggplot2::scale_fill_gradient2(low = "#2166ac", mid = "white", high = "#b2182b") + - ggplot2::scale_alpha(range = c(0.1, 1), limits = c(0, 6), breaks = 1:3, - labels = c("1, p0 = 0.1", "2, p0 = 0.01", "3, p0 = 0.001"), - guide = ggplot2::guide_legend(override.aes = list(fill = "gray30"))) + - ggplot2::scale_shape_manual(values = 21) + - ggplot2::labs(x = NULL, y = NULL, fill = "change [log]", alpha = "evidence, -log10 p0", shape = NULL) + - theme_dMod() -``` - -Each tile is one $\eta_{ik}$; rate constants follow the pathway from IKK (top) to A20 (bottom). -Color is the log-scale mode of the most probable structure: red increase, blue decrease, white no -change (wherever the spike is more probable than the slab); $-0.7$ halves a rate constant. Opacity -is the evidence $-\log_{10} p_0$, full from 6 on ($p_0 < 10^{-6}$). A pale tile is a small change, -or $p_0$ near or above $1 - \rho$; circles mark $p_0 < 0.05$, the table above. A colored tile without -circle has $p_0$ between 0.05 and 0.5. - -## Data and fit by compound - -Prediction per compound at the estimated fixed effects and changes against the compound data, each -point with the measured standard deviation, which the blots have in place of an error model; gray: -the untreated, stimulated control of the same blots at the fixed effects alone. DCF blots span six -hours, the others 50 minutes: - -::: {.wide} -```{r, fig.width = 12, fig.height = 8.5} -outer <- getParameters(prdCompounds) -estimates <- c(fit$argument, fit$fixed, setNames(fit$random$mode, fit$random$parameter)) -pars <- setNames(numeric(length(outer)), outer) -pars[intersect(outer, names(estimates))] <- estimates[intersect(outer, names(estimates))] - -treated <- grep("^TNF_[A-Z]", names(dataCompounds), value = TRUE) -controls <- sub("^TNF_[A-Z]+_", "TNF_none_", treated) -observed <- as.data.frame(dataCompounds) -times <- sort(unique(c(seq(0, 60, length.out = 200), seq(0, max(observed$time), length.out = 200)))) -prediction <- as.data.frame(prdCompounds(times, pars, deriv = FALSE, conditions = union(treated, controls))) - -# every compound with the untreated control on the same blots -blots <- c("IkBa", "pIkBa", "pIKK", "pNFkB") -byCompound <- function(frame) do.call(rbind, Map(function(cond, ctl) { - rows <- frame[frame$condition %in% c(cond, ctl) & frame$name %in% blots, - c("time", "name", "value", "sigma", "condition")] - rows$compound <- sub("^TNF_([A-Z]+)_.*", "\\1", cond) - rows$treatment <- ifelse(rows$condition == cond, "compound", "control") - rows -}, treated, controls)) -points <- byCompound(observed) -# the curves over the time range of the data of the compound -curves <- byCompound(prediction) -curves <- curves[curves$time <= tapply(points$time, points$compound, max)[curves$compound], ] -colors <- c(compound = "#b2182b", control = "gray55") -ggplot2::ggplot(mapping = ggplot2::aes(time, value, color = treatment)) + - ggplot2::geom_line(data = curves) + - ggplot2::geom_errorbar(data = points, ggplot2::aes(ymin = value - sigma, ymax = value + sigma), - width = 0) + - ggplot2::geom_point(data = points) + - ggplot2::facet_grid(name ~ compound, scales = "free") + - ggplot2::scale_x_continuous(breaks = scales::breaks_pretty(n = 3)) + - ggplot2::scale_color_manual(values = colors) + - ggplot2::labs(x = "time [min]", y = "log signal [a.u.]", color = NULL) + - theme_dMod() + - ggplot2::theme(legend.position = "bottom") -``` -::: +seText <- if (is.null(tryCatch(vcov(dcfSS), error = function(e) NULL))) + "has one group, too few for the empirical information, and the intervals are missing" else + "the conditions without DCF and the prior complete the one group" +``` ## Sparse random-effect distributions -`gr(group, dist = )` sets the random-effect distribution of a term. Besides `normal()`, two have -deviations exactly zero unless the data need them: +`gr(group, dist = )` sets the random-effect distribution. Besides `normal()`, two give deviations +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_` | | `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, numbered `_1`, `_2`, ... for several terms -of one grouping, and estimated with the fixed effects unless given, as in `spikeSlab(tau = 0.5)`. -A spike-and-slab deviation is zero with a probability reported per group. Under the Dirichlet process groups share deviations in clusters with the population -value, see [Dirichlet-process random effects](#dirichlet-process-random-effects). Normal and sparse -random effects of one grouping combine; `em(method = "focei")` fits all, Dirichlet-process ones -also `method = "saem"`. +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. ## Fitting sparse random effects -`em(method = "focei")` integrates sparse random effects on the Laplace approximation of the data -term at the joint mode of a group, exactly where possible, the spike-and-slab effects of a group -jointly even where the data couple them, and by EC where the data link a Dirichlet-process effect -to another factor or the subset sum leaves the budget. Fixed -effects and hyperparameters move in one trust region: no EM iteration count, no random numbers. -`fit$coupling` is `"expectationConsistent"` if a group needed EC, `NULL` if all are exact. Integral, -gradient and hyperparameter steps: +`em(method = "focei")` integrates sparse random effects by the Laplace approximation at the joint +mode of a group, exactly where possible, and by expectation consistent (EC) approximation where the +data link a Dirichlet-process effect to another factor or the subset sum exceeds the budget. Fixed +effects and hyperparameters move in one trust region. `fit$coupling` is `"expectationConsistent"` +if a group needed EC, else `NULL`. Methods: [Methods > Approximate marginal](methods-sparsity-priors.html#approximate-marginal), [Methods > Expectation consistent approximation](methods-sparsity-priors.html#expectation-consistent-approximation) and @@ -325,16 +490,16 @@ approximation](methods-sparsity-priors.html#expectation-consistent-approximation | `maxOuter` | `200` | joint trust-region iterations, all runs | | `trustControl` | `rinit = 1`, `rmax = 10`, `ftol = 1e-10`, `mtol = 1e-5` | joint trust region, as `trust()` | -Other entries are an error. The compound fit passes the `tolerances` of -[Setting up models](guide-model.html) in `trustControl`, above the solver error in value and gradient. A run stopping -short of `mtol` restarts while runs lower $-2 \log L$ by more than `mtol`. `msem()` perturbs -concentrations and slab standard deviations on log scale, slab probabilities on logit scale. +Other entries are an error. The DCF fit passes the `tolerances` of +[Setting up models](guide-model.html) in `trustControl`. A run stopping short of `mtol` restarts +while runs lower $-2 \log L$ by more than `mtol`. `msem()` perturbs concentrations and slab +standard deviations on log scale, probabilities on logit scale. ## Reported structure -The fit reports the most probable structure: subset of deviations (spike and slab) or partition -(Dirichlet process). Spike deviations are exactly zero, slab deviations the posterior mean given -the structure ([Methods > Reported structure](methods-sparsity-priors.html#reported-structure)). +The fit reports the most probable subset (spike and slab) or partition (Dirichlet process): spike +deviations exactly zero, slab deviations the posterior mean given the structure +([Methods > Reported structure](methods-sparsity-priors.html#reported-structure)). `fit$random` has a row per group and random effect: - `mode`, this value; @@ -343,40 +508,38 @@ the structure ([Methods > Reported structure](methods-sparsity-priors.html#repor deviating groups or clusters in group order, and `p0`, posterior probability of zero deviation; - `data`, whether the random effect reaches data of the group, where some do not. -A sparse random effect reaching no data of the group (through transformations, ODE, observables, -error model) rests at 0 with the prior standard deviation and, for spike and slab, -$p_0 = 1 - \rho$. `fit$slab` lists probabilities, concentrations and slab standard deviations, -each with term symbols, estimate and whether fixed. +A sparse random effect reaching no data of the group rests at 0 with the prior standard deviation +and, for spike and slab, $p_0 = 1 - \rho$. `fit$slab` lists probabilities, concentrations and slab +standard deviations, each with term symbols, estimate and whether fixed. ## Standard errors -With spike-and-slab random effects `fit$hessian` is `NULL`; `vcov()` inverts -`fit$information`, the empirical information from the group scores. It needs more groups than -parameters, or conditions without random effects plus priors for the other directions; otherwise -`vcov()` is an error and standard errors are `NA`. In the compound fit the conditions without -compound and the prior complete the five compounds. `dirichletProcess()` fits have neither; -`confint(method = "profile")` gives intervals. Details: [Methods > Standard errors](methods-sparsity-priors.html#standard-errors). +With spike-and-slab random effects `fit$hessian` is `NULL`; `vcov()` inverts `fit$information`, +the empirical information of the group scores plus the expected information of the conditions +without random effects and the priors (`hessian = "expected"`). It needs more groups than +parameters, or those terms for the other directions; otherwise `vcov()` is an error and standard +errors are `NA`. `fit$information` is not a Hessian of the marginal and does not detect saddle +points. The DCF fit `r seText`. `dirichletProcess()` fits have neither; +`confint(method = "profile")` gives intervals. +Details: [Methods > Standard errors](methods-sparsity-priors.html#standard-errors). ## Dirichlet-process random effects With `gr(group, dist = dirichletProcess())` groups and population value form clusters; the concentration $\alpha$ sets how readily a group opens a new one. The population cluster has -deviation zero, every other cluster one common deviation from $\mathcal{N}(0, \tau^2)$. $\alpha$ and -$\tau$ are estimated by marginal maximum likelihood in one fit, with no penalty to scan. The -reported structure is that of spike and slab with clusters in place of single deviations; the -compounds here are fitted without it. +deviation zero, every other cluster one common deviation from $\mathcal{N}(0, \tau^2)$. $\alpha$ +and $\tau$ are estimated by marginal maximum likelihood in one fit. `method = "focei"` sums exactly over partitions of up to 14 groups. `method = "saem"` draws -partitions, allowing normal random effects alongside but no other sparse ones, and reports the most -frequent partition of the late draws, from `window` iterations after burn-in, with standard error -`valueSE` of $-2 \log L$. -`control$saem$particles` sets the importance-sampling particles, default 500; `converged` says -whether burn-in ended by the drift test. An SAEM fit has no gradient, Hessian or empirical -information. Details: +partitions, allows normal but no other sparse random effects alongside, and reports the most +frequent partition of the last `window` iterations after burn-in, with standard error `valueSE` of +$-2 \log L$. `control$saem$particles` sets the importance-sampling particles, default 500; +`converged` says whether burn-in ended by the drift test. An SAEM fit has no gradient, Hessian or +empirical information. Details: [Methods > Sparsity priors](methods-sparsity-priors.html#dirichlet-process-random-effects). Reference: `randomEffects()`, `spikeSlab()`, `dirichletProcess()`, `em()`, `msem()`, -`plotValues()` +`plotValues()`, `plotTrace()`, `plotRandomEffects()`, `plotPars()` [← 7. Nonlinear mixed-effects models](guide-nlme.html) | [9. Alignment of relative data measurements →](guide-alignment.html) diff --git a/vignettes/articles/guide-symmetries.Rmd b/vignettes/articles/guide-symmetries.Rmd index 6fb754c4..66a35cb6 100644 --- a/vignettes/articles/guide-symmetries.Rmd +++ b/vignettes/articles/guide-symmetries.Rmd @@ -13,20 +13,16 @@ knitr::opts_knit$set(root.dir = project) source("results/stored.R") knitr::read_chunk("../../examples/oppeltNPJSystBiolAppl2018/model.R") knitr::read_chunk("../../examples/oppeltNPJSystBiolAppl2018/symmetries.R") -# through do.call: the resource scan of rmarkdown purls the article elsewhere and runs -# every literal read_chunk() call there -articles <- getwd() -do.call(knitr::read_chunk, list(file.path("results", "guide-symmetries.R"))) +knitr::read_chunk("../../examples/oppeltNPJSystBiolAppl2018/discrete.R") # a count as the text writes it inWords <- function(n) if (n %in% 1:12) c("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve")[n] else format(n) ``` -If a continuous family of parameter values gives the same prediction for every observable, no -data of these observables can tell the members apart. `symmetryDetection()`, through the Python -package [symident](https://dmodverse.github.io/symident/), finds such families in the model of -[Setting up models](guide-model.html); they are removed before the fit. Code: `symmetries.R` and -the end of `model.R`. +`symmetryDetection()`, through the Python package +[symident](https://dmodverse.github.io/symident/), finds continuous families of parameter values +with identical observables in the model of [Setting up models](guide-model.html). Code: +`symmetries.R` and the end of `model.R`. ```{r setup, echo = FALSE} ``` @@ -60,26 +56,19 @@ the end of `model.R`. ## Lie symmetries and detection -Such a family is the orbit of a Lie symmetry with a generator, a vector field on the parameters. -Most symmetries of reaction networks are scalings: the moved parameters are multiplied by powers -of one factor, and on log scale an orbit is a straight line. symident obtains the generators as -the kernel of the observability-identifiability matrix, built from the Lie derivatives of the -observables, and proves scalings exactly; see -[Methods > Structural identifiability and Lie symmetries](methods-symmetries.html). +Each family is the orbit of a Lie symmetry. symident obtains the generators as the kernel of the +observability-identifiability matrix and proves scalings exactly +([Methods > Structural identifiability and Lie symmetries](methods-symmetries.html)). ## Detection settings -- `equilibrate = TRUE`: the cells start at the steady state without TNFα, so initial values are - functions of the parameters. -- `reduceCQ = TRUE`: one species per conserved moiety is eliminated, symmetries act on the totals, - the parameters of `Pimpl()`. -- `forcings = "TNF"`: TNFα is an input state, 0 at rest and set by the event at time 0. -- `conditions`: the two doses; a direction is non-identifiable only if it is so in both. +- `equilibrate = TRUE`: initial values are the steady state without TNFα. +- `reduceCQ = TRUE`: symmetries act on the conserved totals, the parameters of `Pimpl()`. +- `forcings = "TNF"`: TNFα is an input state, set by the event at time 0. +- `conditions`: a direction is non-identifiable only if it is so in both doses. -The imaging readouts bleach, $y = \log(s x + o) - \tau t$; $e^{-\tau t}$ is no function of the -states of a model at rest. In the control the states are constant and the slope of an imaging -readout is $-\tau$ alone, so the bleaching rates are in no symmetry, and `symmetries.R` drops the -bleaching terms. +The imaging readouts bleach, $y = \log(s x + o) - \tau t$. In the control the states are constant, +so the bleaching rates are in no symmetry, and `symmetries.R` drops the bleaching terms. ## Symmetries of the full model @@ -88,6 +77,8 @@ invisible(stored("results/symmetries.rds", "symmetries.R")) invisible(stored("results/reduction.rds", "symmetries.R")) ``` +Computed by `symmetries.R`, loaded from `results/symmetries.rds`: + ```{r symmetries, eval = FALSE} ``` @@ -100,34 +91,23 @@ symmetries types <- vapply(symmetries$symmetries, `[[`, "", "type") ``` -The rank of the observability-identifiability matrix is `r symmetries$rank` of -`r symmetries$dim` coordinates, proven; the kernel is spanned by -`r inWords(length(types))` scalings, each proven over the rationals. The `r inWords(length(types))` printed generators -are one basis, sums of them are symmetries too. Up to such sums there are four kinds. - -- **Unobserved intermediates.** Active receptor `TNFR`, IκBα transcript `mIkb`, A20 transcript and - A20 protein are unmeasured, A20 only up to a scale. Each acts through the product of level and - driven rate constant: level and production rate times $\lambda$, driven rate divided by - $\lambda$. $X_1$: receptor (`uptake`, `act_Ikk_by_TNF`); $X_4$: IκBα transcript - (`prod_mIkb_by_nNfk`, `prod_Ikb`); $X_6$: A20 transcript (`build_RnaA20`, `build_A20`). $X_7$ - moves A20 with the A20 production, the IKK inhibition constant `inh_Ikk` (entering as - `A20 / inh_Ikk`) and the scale of the A20 imaging readout. -- **Relative measurements.** Blots and imaging give no absolute amounts. $X_2$ divides the IKK - total and every IKK form by $\lambda$ and multiplies the IKK-catalyzed phosphorylation rates and - the pIKK blot scale by $\lambda$; the IKK cycle is linear in IKK. NFκB and IκBα scale together: - every form times $\lambda$; complex formation (second order), the readout scales and the A20 - transcription driven by nuclear NFκB divided by $\lambda$. The printed $X_3$ is this direction - plus $X_4$ and $X_5$, hence it also moves nuclear volume and IκBα production. -- **Nuclear volume.** In $X_5$ `Vnuc` grows at fixed amounts, nuclear concentrations fall, and the - rates reading them (transcription of IκBα and A20, nuclear complex formation) and the scale of - nuclear NFκB grow to compensate. -- **A product.** `split_NfkIkb` appears only multiplied by `eta_split_pNfkpIkb` ($X_8$). +The rank is `r symmetries$rank` of `r symmetries$dim` coordinates, proven; the kernel is spanned +by `r inWords(length(types))` scalings, each proven over the rationals. The generators are one +basis; up to sums there are four kinds. + +- **Unobserved intermediates**, level against driven rate: receptor $X_1$, IκBα transcript $X_4$, + A20 transcript $X_6$, A20 $X_7$ (with `inh_Ikk` and the A20 imaging scale). +- **Relative measurements**: IKK $X_2$; NFκB and IκBα together, printed as $X_3$ plus $X_4$ and + $X_5$. +- **Nuclear volume** `Vnuc` against the rates reading nuclear concentrations, $X_5$. +- **A product**: `split_NfkIkb` appears only times `eta_split_pNfkpIkb`, $X_8$. ## Symmetry reduction -`symmetryReduction()` returns in `$trafo` a parameter transformation that removes the directions, for scalings +`symmetryReduction()` returns in `$trafo` a transformation without the directions, for scalings by fixing one coordinate per direction -([Methods > Gauge and reduction](methods-symmetries.html#gauge-and-reduction)). +([Methods > Gauge and reduction](methods-symmetries.html#gauge-and-reduction)). Loaded from +`results/reduction.rds`: ```{r reduction, eval = FALSE} ``` @@ -139,9 +119,7 @@ reduction ## Gauge fixing -The objective is flat along every orbit, so the fit fixes one moved coordinate per symmetry, the -gauge. This chooses units and leaves the fit unchanged. `model.R` fixes one parameter per scaling -at 1, 0 on log scale: +`model.R` fixes one moved parameter per scaling at 1, 0 on log scale, the gauge: ```{r gauge} ``` @@ -158,40 +136,56 @@ W det(W) ``` -This is the gauge of Oppelt et al. [@oppelt2018model]: NFκB and IKK totals and nuclear volume set -the concentration units, so a concentration is a fraction of the moiety total; receptor and A20 -transcript are in units of their production rates, the IκBα transcript in units of the translation -it drives, A20 in units of the A20 imaging scale. The reduction fixes other coordinates, a -different choice of units. [Optimization](guide-optimization.html) fits the remaining +This is the gauge of Oppelt et al. [@oppelt2018model]: concentrations are fractions of the NFκB +and IKK totals, receptor and transcripts are in units of the rates they drive, A20 in units of +the A20 imaging scale. [Optimization](guide-optimization.html) fits the remaining `r length(setdiff(getParameters(p), names(gauge)))` parameters, [Profile likelihood](guide-profiles.html) checks which the data determine. ## Discrete symmetries -A locally identifiable model can still give the output of a parameter value at other, isolated -values: a discrete symmetry. `symmetryDetection(discrete = TRUE)`, or `discreteSymmetries()` on a -result, counts these values in the domain and reconstructs the maps between them where they are -rational functions of the coordinates; the search needs msolve and a model with one condition -and no events. In the two-compartment model of Godfrey [@godfrey1983compartmental], with the -amounts $x_1$ and $x_2$, an input $u$ into the first compartment and the second observed, +A discrete symmetry maps a parameter value to isolated other values with the same output. +`symmetryDetection(mode = "global")` counts these values and reconstructs rational maps between +them (requires msolve). `discrete.R` applies it to the reduced model of +[Profile likelihood](guide-profiles.html#reduced-model), passed as `trafo`; loaded from +`results/discrete.rds`: -```{r godfrey, eval = FALSE} +```{r discrete, eval = FALSE} ``` ```{r, echo = FALSE} -compartments <- stored(file.path(articles, "results", "guide-symmetries.rds"), - file.path(articles, "results", "guide-symmetries.R")) +invisible(stored("results/discrete.rds", "discrete.R")) +``` + +```{r} +saved <- readRDS("results/discrete.rds") +discrete <- saved$discrete +discrete$info$discrete[c("count", "countFinal", "fundamentalDomain")] +swap <- discrete$discreteSymmetries[[1]] +swap[c("map", "level", "stateMaps")] +``` + +There are `r inWords(discrete$info$discrete$count)` values with the output of a generic one; the +map exchanges the degradation rates of the A20 transcript and of A20, `exact` means proven by the +map of the states. The map moves no coordinate of the scalings and holds in the original +coordinates as well. + +The publication does not name the swap and reports both rates with the same 95 % interval, +$-5.97$ to $-3.32$ on log scale [@oppelt2018model, Table S7], the union of the two images. +`symmetryReduction(branch = )` gives a chart of the fundamental domain +`degrad_A20 < degrad_RnaA20`: + +```{r fundamental, eval = FALSE} ``` ```{r} -compartments +fundamental <- saved$fundamental +fundamental$trafo[c("degrad_A20", "degrad_RnaA20")] ``` -the map exchanges the elimination rate $k_{01}$ and the return rate $k_{12}$ and moves the -initial value of $x_1$, so the model is locally but not globally identifiable. `exact` means -proven by a map of the states. The fundamental domain $k_{01} < k_{12}$ keeps one of the two -points; a fit restricted to it has a unique optimum. A model with directions is reduced first, -and the maps are stated in the coordinates of the reduced model. +`delta` is the positive difference of the two rates; in this chart a fit has one optimum instead +of two +([Profile likelihood > Profiles in the fundamental domain](guide-profiles.html#profiles-in-the-fundamental-domain)). Reference: `symmetryDetection()`, `symmetryReduction()`, `discreteSymmetries()` diff --git a/vignettes/articles/methods-multiple-shooting.Rmd b/vignettes/articles/methods-multiple-shooting.Rmd index 3c7b8cb6..35afe7a0 100644 --- a/vignettes/articles/methods-multiple-shooting.Rmd +++ b/vignettes/articles/methods-multiple-shooting.Rmd @@ -25,8 +25,43 @@ inFraction <- function(x) if (round(1 / x) %in% 2:10) c("half", "a third", "a qu Single shooting integrates from the initial state over the whole time axis. For oscillating or spiking systems the objective is rugged: a parameter change shifts every later period, and a peak moved by more than the peak width leaves the residuals without direction, so few starts reach the -narrow valleys. `trust()` offers multiple shooting instead -([switching it on](guide-optimization.html#multiple-shooting), [trust region](methods-trust.html)). +narrow valleys. `trust()` offers multiple shooting instead ([trust region](methods-trust.html)). + +## Usage + +Multiple shooting is a control of the objective: + +```{r, eval = FALSE} +obj <- normL2(data, g * x * p, multipleShootingControl = TRUE) +fit <- trust(obj, start) +fit$multipleShooting$violation +controls(obj, "multipleShootingControl") <- NULL # single shooting again +``` + +The chain must be `g * x * p` with one `Xs()` built on `odemodel(..., includeTimeZero = FALSE)`. +Not available with it: `hessianMethod = "exact"`, `qnControl$hessianInit = "exact"`, several +phases, `switches`, `hessianReseed`, `qnMemory`, `nonmonotone`, `boundary = "clip"`, +`minimize = FALSE`, `traceFile`. + +| entry of `multipleShootingControl` | default | controls | +|---|---|---| +| `nodes` | `"auto"` | `"auto"`, `"transitions"`, or node times | +| `growth`, `misfit` | `10`, `3` | thresholds at which `"auto"` cuts a segment | +| `minPoints` | states + 1 | data points per half of a cut | +| `charts` | all linear | `"log10"`, `"linear"` or `"angle"` per state | +| `scale` | from the data | scale of the gaps and node steps | +| `init` | `"data"` | node values: `"data"`, `"spline"`, `"simulation"` or a list | +| `breaks` | none | node times without continuity | + +| entry of `stepControl` | default | controls | +|---|---|---| +| `acceptance` | `"filter"` | `"filter"`, `"merit"` or `"natural"` | +| `soc` | `TRUE` | second-order correction of a rejected step | +| `anneal` | `TRUE` | penalty on the gaps raised in stages | +| `twoPhase`, `restore`, `regularize` | off | further globalizations | + +`converged = TRUE` requires the scaled gaps below `tolControl$ctol`. The result has a list +`multipleShooting` with `nodes`, `gaps`, `violation` and the counts of the globalization. ## Segments and gaps diff --git a/vignettes/articles/methods-nlme.Rmd b/vignettes/articles/methods-nlme.Rmd index 4af60292..38e13866 100644 --- a/vignettes/articles/methods-nlme.Rmd +++ b/vignettes/articles/methods-nlme.Rmd @@ -87,8 +87,27 @@ Each evaluation, in C++: with second-order sensitivities, plus SR1 from the last three accepted gradients. - **Stop.** Model gain below `trustControl$mtol` in the region `rmax`, or five rejected trials flat within `ftol`. +- **Hessian source.** With several groupings the outer loop is `trust()`, and `trustControl` takes + the arguments of `trust()`, `phases` among them. A handover from Gauss-Newton to BFGS, after 20 + iterations or at a stalled radius ([Methods > Trust region](methods-trust.html#hessian-phases)), + reaches the optima of Gauss-Newton on the theophylline, warfarin and mavoglurant fits of + `bench/nlme/` with more iterations and time: the evaluation builds the Gauss-Newton Hessian for + the modes and the volume term anyway, so a BFGS step costs as much as a Gauss-Newton step. - **Sparsity.** `sparse = TRUE`: the same outer loop on sparse outer Hessians, Schur complement and volume term of a group local to the parameters of the group, or, where the $n_g$ entries of $\psi$ a group couples satisfy $n_g^2 > k\, n_\psi$ with $n_\psi$ the number of entries of $\psi$, as a low-rank part of rank $k$: $k = K$ for the Schur complement, $k = 2K + K^2$ for the volume term. +### Group kernel + +One C++ kernel evaluates all groups at once: the modes, the local model of each group and the +integral on it. At the mode, +$\Phi_i(\hat\eta_i + \delta) \approx \Phi_i(\hat\eta_i) + g_i^\top \delta + \tfrac12 \delta^\top H_i \delta$, +$g_i$ the gradient the inner search leaves. The block $H_{NN}$ of the normal random effects is +factored once; eliminating it gives the outer model, $\Phi_i^{\psi\psi} - \Phi_i^{\psi N} H_{NN}^{-1} +\Phi_i^{N\psi}$, and the curvature $H_{LL} - H_{LN} H_{NN}^{-1} H_{NL}$ left on the other coordinates +$L$. An integrator maps the local model to the term $-2 \log L_i - \Phi_i(\hat\eta_i)$ and to the +derivative $W_i$ of the term in $H_i$, which the volume derivative (5) contracts with +$\mathrm{d} H_i / \mathrm{d}\psi$. FOCEI is Laplace on the normal block: the term +$\log \lvert H_{NN}/2 \rvert$ and $W_i = H_{NN}^{-1}$. + ### Volume term For Gauss-Newton $H_i$, from second-order sensitivities, @@ -129,13 +148,20 @@ 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 next level - changes $-2 \log L_i$ by at most `tol` over the number of groups. +- **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$. - **Step.** Trust region over all parameters on frozen nodes. For mu-referenced fixed effects, $\phi_i = D_i \beta + \eta_i$, nodes are frozen in $\phi$, need no sensitivities and hold over larger steps. -- **Stop.** A Newton step on the rebuilt nodes would gain less than `tolDecrement` or less than the - nodes resolve. +- **Stop.** A Newton step on the rebuilt nodes would gain less than `tolDecrement`, or + $-2 \log L$ rose after a step on unchanged levels, so the step lies below what the levels + resolve. Either way the fit is stationary at the levels reached, capped ones included; it returns + the iterate of lowest $-2 \log L$ on the highest levels, and the stage trace records the + levels, errors and caps per group. At the estimate, importance sampling ($t_5$ proposal at the mode, shifted lattice points) flags groups whose two estimates differ by more than three standard errors plus the level error, or with Pareto shape @@ -166,12 +192,52 @@ step has the marginal score as fixed point. | phase | rule | |---|---| | draws | few random-walk Metropolis steps and independence proposals from $\mathcal{N}(\hat\eta_i, 1.5 \cdot 2 H_i^{-1})$ [@kuhn2004coupling]; `set.seed()` reproduces | -| burn-in | $\gamma_k = 1$, variances shrink at most 5 % per iteration [@lavielle2014mixed]; ends when no parameter drifts over `window` | -| averaging | $\gamma_k = k^{-0.7}$, $k$ counted from the end of burn-in, mean of iterates [@polyak1992acceleration]; ends when the expected Monte Carlo rise of $-2 \log L$ is below `mcTol` | +| burn-in | $\gamma_k = 1$, variances shrink at most 5 % per iteration; ends when no parameter drifts over `window` | +| averaging | $\gamma_k = k^{-0.7}$, $k$ counted from the end of burn-in, mean of iterates [@kushner2003stochastic]; ends when the expected Monte Carlo rise of $-2 \log L$ is below `mcTol` | SAEM neither forms $\ell$ nor raises it in every iteration; `em()` reports the quadrature of level $K + 2$ with standard errors from the quadrature Hessian. SAEM suits many random effects and skewed, -heavy-tailed or multimodal posteriors [@kuhn2005maximum]. +heavy-tailed or multimodal posteriors [@kuhn2004coupling]. + +### Spike-and-slab random effects + +A spike-and-slab random effect $\eta_{ij} = z_{ij} v_{ij}$ has an indicator $z_{ij}$ with +$\Pr(z_{ij} = 1) = p$ and a slab value $v_{ij} \sim \mathcal{N}(0, \tau^2)$ +[@mitchell1988bayesian; @george1993variable]. Per iteration, after the normal random effects: + +- **Local model.** Per group the quadratic model of the data term in the slab values, with the + curvature clipped to be positive semidefinite, refreshed at the mean of the slab-only Gaussian. +- **Collapsed indicator moves.** Each indicator of a group once per sweep, in random order, all + groups at once. The other slab values of the group move with $v_{ij}$ along the regression of + the local model, $v_o = b_o + x\,u_o$, so the state $b$ with $z_{ij} = 0$ and the line stay + fixed. On this line the slab mass $I = \int f(x)\,dx$, $f$ the joint density of data and + prior, is a Gauss-Hermite sum on the local Gaussian $\mathcal{N}(m, s^2)$ with the exact data + term at `nodes` (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}$$ + + The proposal draws $z_{ij}$ with probability $0.01 + 0.98\,\hat\pi_{ij}$ and $x$ from + $\mathcal{N}(m, 1.5\,s^2)$, independently of the current state; an independence Metropolis-Hastings + step [@tierney1994markov] on $(z_{ij}, x)$ against the model leaves the exact posterior invariant, + whatever the error of the sum. +- **Slab values.** `nMcmc` joint random-walk Metropolis steps of the slab values of every group in + the slab, scaled by the conditional standard deviations of the local model. +- **A-step and M-steps.** $p$ and $\tau$ follow from Robbins-Monro averages of + $\sum \hat\pi_{ij}$ and $\sum \hat\pi_{ij}\,\mathbb{E}(x^2 \mid z_{ij} = 1)$, the + Rao-Blackwellized statistics [@casella1996rao] of the sweep, in place of the drawn indicators. An + effect the data do not inform has $\hat\pi_{ij} = p$ and second moment $\tau^2$ and leaves both + unchanged; counts of drawn indicators would instead let $p$ wander to 1 in burn-in, where + $\gamma_k = 1$. In burn-in the odds $p / (1 - p)$ and $\tau$ change by a factor in + $[0.95, 1.25]$ per iteration. + +$p_0$ is one minus the mean of $\hat\pi_{ij}$ over the late sweeps, an effect selected where it +is below 1/2. An `em` fit as `init` starts the chain at the selected values of that fit, the +indicators set where they are not 0, which checks a FOCEI optimum by SAEM. $-2 \log L$ at the +estimate is that of `method = "focei"`; with Dirichlet-process random effects beside on more than +14 groups, or with `integral = "importance"`, it comes from sequential importance sampling over the +partitions ([Sparsity priors](methods-sparsity-priors.html#importance-sampling)), each group summing over +the subsets of the spike-and-slab effects that reach the group data. ## Zero variance components {#variance-at-the-boundary} diff --git a/vignettes/articles/methods-sensitivities.Rmd b/vignettes/articles/methods-sensitivities.Rmd index 36a3ff5a..c3c8090e 100644 --- a/vignettes/articles/methods-sensitivities.Rmd +++ b/vignettes/articles/methods-sensitivities.Rmd @@ -103,7 +103,7 @@ By default the adjoint follows the step grid of the states without error control | `gradtol` | the share of each step in the gradient added to that test as absolute tolerance | A trust region converges with a gradient whose error is small relative to the gradient -[@carter1991global; @conn2000trust]. `gradtol` bounds the error of every step in absolute terms, +[@carter1991global; @nocedal2006numerical]. `gradtol` bounds the error of every step in absolute terms, and the errors of the steps add up over the sweep; near the optimum, where the gradient vanishes, a fixed `gradtol` does not keep the relative error small ([checking the sweep](https://dmodverse.github.io/cppDE/articles/methods-reverse-checks.html)). diff --git a/vignettes/articles/methods-sparsity-priors.Rmd b/vignettes/articles/methods-sparsity-priors.Rmd index 09d3b1b2..a4bf9895 100644 --- a/vignettes/articles/methods-sparsity-priors.Rmd +++ b/vignettes/articles/methods-sparsity-priors.Rmd @@ -402,7 +402,7 @@ pair with $s^\top y \le 0$, or an update that would make the model indefinite, d correction. Far from the optimum a step is an EM step in the hyperparameters and a Gauss-Newton step in the fixed parameters, at one marginal evaluation; near it the model approaches the marginal Hessian and convergence is superlinear. -Gradient and bounded Hessian suffice for convergence [@conn2000trust], and no number of EM +Gradient and bounded Hessian suffice for convergence [@nocedal2006numerical], and no number of EM iterations is chosen. The trust region stops at a predicted reduction below `mtol`; a run ending short of it restarts with @@ -454,7 +454,8 @@ coordinate depends on which others are free and, for coupled coordinates, on the An L1 penalty $\lambda \sum \lvert \eta \rvert$ [@tibshirani1996regression], as in `trustL1()`, sets small deviations to 0, shrinks every selected one by the same amount, and compensates by selecting more small ones. Of coordinates the data tie together it keeps one, unstably, since the lasso -condition for the right set fails for such correlations. It gives no probability of a deviation. +condition for the right set fails for such correlations. It gives no probability of a deviation. Both on +one data set: [Sparse deviations > L1 scan](guide-sparse-deviations.html#l1-scan). The spike and slab separates decision and size: a deviation is 0 or from the slab, which shrinks little, and (7) weighs every structure by the marginal likelihood, with $\rho$ and $\tau$ estimated @@ -503,7 +504,7 @@ clusters for deviations. The guide compounds are fitted without it. ### Ewens prior The partitions $\mathcal{C}$ of the $G$ groups and the anchor follow the Ewens distribution -[@ewens1972sampling] of the Chinese restaurant process, anchor seated first: a group joins a +[@pitman2006combinatorial] of the Chinese restaurant process, anchor seated first: a group joins a cluster with probability proportional to the size, anchor counted, or opens one with probability proportional to $\alpha$, diff --git a/vignettes/articles/methods-steady-states.Rmd b/vignettes/articles/methods-steady-states.Rmd index 7975f3c2..161ab5ef 100644 --- a/vignettes/articles/methods-steady-states.Rmd +++ b/vignettes/articles/methods-steady-states.Rmd @@ -77,13 +77,13 @@ of the residuals $$\rho_k = \sqrt{\kappa} \begin{cases} r_k^{3/2}, & r_k \le 1, \\ 1 + \tfrac{3}{2}(r_k - 1), & r_k > 1, \end{cases} \qquad r_k = \frac{\max\bigl(0,\ \mathrm{Re}\,\lambda_k - \lambda_0\bigr)}{\lambda_{tol} - \lambda_0}, - \qquad \lambda_0 = \lambda_{tol} - m s, + \qquad \lambda_0 = \lambda_{tol} - \max(d, m s), \tag{5}$$ -with weight $\kappa$ and the relative width $m$ of the ramp, `stabilityMargin` with default -$10^{-6}$. The term is zero on a root whose leading real part lies more than $m s$ below -$\lambda_{tol}$, however slowly a perturbation decays there; it does not depend on the time the -data span. Each eigenvalue whose real part reaches $\lambda_{tol}$ adds $\kappa$, +with weight $\kappa$ and the width $\max(d, m s)$ of the ramp: at least the absolute `width` $d$, +default 0, and at least the `margin` $m$ relative to the scale, default $10^{-6}$, the precision of +the eigenvalues. The term is zero on a root whose leading real part lies below $\lambda_0$, +however slowly a perturbation decays there. Each eigenvalue whose real part reaches $\lambda_{tol}$ adds $\kappa$, and beyond, the term grows quadratically. Steady states that agree in the parameters, resting states and start values they read count once. For a simple eigenvalue with right and left eigenvectors $u_k$, $v_k$ of $J$, $v_k^{\mathsf H} u_k \ne 0$, and (4), @@ -97,8 +97,13 @@ $$ and $s = |\lambda_m|$, $\lambda_m$ the eigenvalue of largest modulus, has the derivative $\mathrm{Re}(\bar\lambda_m\, \mathrm{d}\lambda_m / \mathrm{d}p) / s$ by (6), continuous except -where the eigenvalue of largest modulus changes. Both need `Pimpl(deriv2 = TRUE)`. The term is a -model assumption, not data: profiles with `stop = "data"` and likelihood ratios leave it out. +where the eigenvalue of largest modulus changes. Eigenvalues that coincide within the error of +the eigenvalues, as a defective double eigenvalue of a chain of states with equal rates, have no +derivative each; each takes the mean $\mathrm{tr}(P\, \mathrm{d}J/\mathrm{d}p) / n_c$ over the +cluster of $n_c$ eigenvalues with spectral projector $P$, which is (6) for a simple eigenvalue and +exact for a cluster that stays degenerate. Where two real eigenvalues on the ramp meet and become a +complex pair, the derivatives of both diverge and the gradient of (5) has a kink. Both need +`Pimpl(deriv2 = TRUE)`. The term is a model assumption, not data: profiles with `stop = "data"` and likelihood ratios leave it out. The Gauss-Newton Hessian of (5), @@ -107,21 +112,39 @@ $$2 \sum_{k \,:\, \mathrm{Re}\,\lambda_k > \lambda_0} \qquad \frac{\mathrm{d} \rho_k}{\mathrm{d}p} = \frac{3}{2} \sqrt{\kappa}\, \min(r_k, 1)^{1/2}\, \frac{\mathrm{d} r_k}{\mathrm{d}p}, \tag{7}$$ -vanishes at the onset with the term and the gradient and is continuous at $r_k = 1$. The ramp is -$m s$ wide, so $r_k$ is as accurate as the root relative to that width. The eigenvalues above -the onset, their conditions, half-lives and the states with the largest entries of the right +vanishes at the onset with the term and the gradient and is continuous at $r_k = 1$. Outside the +ramp the term and (7) vanish, so the model of a trust-region step sees the boundary only from +within the ramp; on a ramp narrow against the change of $\mathrm{Re}\,\lambda_k$ over a step, +the steps cross it and are rejected, and the iterates creep along the boundary. A `width` +$d$ in the units of the rates, wide against that change, avoids it and leaves a resting state +untouched whose slowest mode decays faster than $d$; the ramp then does not move with $s$. A ramp +$m s$ wide gives $r_k$ as accurate as the root relative to that width. The eigenvalues above the +onset, their conditions, half-lives and the states with the largest entries of the right eigenvectors are the attribute `"eigenvalues"` of a call of the term. ## Analytical steady-state constraints `steadyStates()` solves $f(x, p) = 0$ in closed form [@rosenblatt2016customized; @kaschek2019dmod]. -Each unknown, a state or a kinetic parameter, is solved from a combination of balances such that -the solution is a ratio of sums of positive terms. The solution is thus positive for positive +The balances are taken in amounts, so that a quantity conserved across compartments is a dependent +balance. First, a state whose balance is linear in the state, with all terms of the state on one +side, is solved from that balance, influx over outflux rate, unless the rate constants of the +solution leave a cycle of the graph of states without a cut; the states of conserved quantities are +left to the cuts. Then the cycles are cut, each at a state of a conserved quantity, which stays +free, or at a state whose balance is solved for a rate constant common to the flux terms of one +side. The cuts are ranked as by @rosenblatt2016customized: conserved quantities first, then sides +whose flux terms occur in no other balance, fewer balances changed, fewer terms, more cycles +through the state. Then each unknown, a state or a kinetic parameter, is solved from a combination +of balances such that the solution is a ratio of sums of positive terms. The solution is thus positive for positive parameters, also with `solveQuadratic = TRUE`, which takes the positive root of a balance quadratic in the state. A state whose balance is spent on a kinetic parameter stays free, as the parameter of the steady-state value of the state. States that are zero in every steady state are set to 0. A conserved quantity keeps one state free. Volumes are never solved for. +Only if no solution of this form exists, a side whose flux terms have separate rate constants +$k_0, \dots, k_m$ is a cut as well. The fluxes $v_j$ of the side get free ratios +$r_{x,j} = v_j / v_0 > 0$, named `r__`; $k_0$ is solved, each $k_j$ follows from +$r_{x,j}$ and $k_0$. The ratios are new parameters of the transformation. + The result, one equation per solved unknown, replaces identity entries of a parameter transformation: @@ -149,8 +172,7 @@ Without a solution of this form, `steadyStates()` returns `0`. The solver is a P convergence failure, no solver tolerance in the objective, one parameter less per solved equation. Rosenblatt et al. report more reliable and faster optimization than with common numerical implementations [@rosenblatt2016customized]. `steadyStates()` does not test stability; `Pimpl()` -does ([Stability](#stability)). `Pimpl()` is needed where no closed form of positive sums exists, -as for the network of the guide. +does ([Stability](#stability)). `Pimpl()` is needed where no closed form of positive sums exists. Reference: `conservedQuantities()`, `Pimpl()`, `steadyStates()`, `constraintStability()` diff --git a/vignettes/articles/methods-trust.Rmd b/vignettes/articles/methods-trust.Rmd index c49143ec..01004bdd 100644 --- a/vignettes/articles/methods-trust.Rmd +++ b/vignettes/articles/methods-trust.Rmd @@ -87,7 +87,8 @@ The result is the best iterate visited; the termination tests read $\mathcal{J}$ ### Bound constraints -`boundary = "reflective"` is the interior method of Coleman and Li [@coleman1996interior]. With +`boundary = "reflective"` is the interior method of Coleman and Li [@coleman1994convergence]. +With $v_i$ the signed distance to the bound in the descent direction $-b_i$ (1 if infinite), $D = \operatorname{diag}(\lvert v \rvert^{1/2})$ and $J^v$ the diagonal of $\partial \lvert v \rvert / \partial \theta$, the subproblem is solved in the scaled variables @@ -119,8 +120,12 @@ small gradient along a flat direction does not mean a value close to the minimum excess. On the [sparse path](#sparse-hessians) the Cholesky factors give (8) where $\hat B$ is positive definite, the dense eigendecomposition of $\hat B$ elsewhere; `trustL1()` evaluates (8) on the model of the coordinates not held at a kink ([L1 penalties](#l1-penalties)). A run that fails -(8) goes on, within `iterlim`; `mtol = 0` drops the condition. While further phases follow, the -value, model and step tests hand over to the next one ([Hessian phases](#hessian-phases)); the last quasi-Newton phase therefore +(8) goes on, within `iterlim`; `mtol = 0` drops the condition. Stagnation, five rejected steps in a +row that leave the value within `ftol`, ends the run, with `converged = TRUE` only where (8) holds: +where the noise of the value exceeds the decrease a step predicts, a non-stationary point +stagnates as well. While further phases follow, the +value, model and step tests hand over to the next one, unless the phase ends the run on them +([Hessian phases](#hessian-phases)); the last quasi-Newton phase therefore ends only on the gradient, stagnation, the radius, `iterlim` or a failing objective [@nocedal2006numerical]. For an ODE integrated at relative tolerance $\epsilon$ a weighted residual $r_j$ of a prediction $g_j$ has an error of about $\epsilon g_j / \sigma_j$, so the value has one of about @@ -167,8 +172,7 @@ the update is $$B_{k+1} = B_k - \frac{B_k s\, s^\top B_k}{s^\top B_k s} + \frac{\tilde y\, \tilde y^\top}{s^\top \tilde y}. \tag{11}$$ Then $s^\top \tilde y \ge 0.2\, s^\top B s > 0$. `qnCautious` skips pairs with -$s^\top y \le c \lVert s \rVert \lVert y \rVert$ (counted in `qnSkipped`), a cautious update in -the sense of [@li2001global], whose test scales with the gradient instead. BFGS updates from +$s^\top y \le c \lVert s \rVert \lVert y \rVert$ (counted in `qnSkipped`). BFGS updates from accepted steps only. ### SR1 update @@ -181,6 +185,77 @@ skipped when $\lvert w^\top s \rvert \le 10^{-8} \lVert s \rVert \lVert w \rVert the true Hessian, indefinite regions included. Rejected trial points also give valid pairs [@nocedal2006numerical]; `qnRejected` (default for `"sr1"`) uses them. +### Structured secant updates + +The data term of `normL2()` is a sum of row losses $\ell_i(m_i)$ in the prediction and sigma +$m_i$ of a data point, $\ell_i = r_i^2$ in the simplest case. With the Jacobian $J$ of all $m_i$ +and the derivatives $u_i = \partial \ell_i / \partial m_i$, the gradient is $J^\top u$ and the +Hessian is the Gauss-Newton Hessian $G = J^\top L J$, $L$ the Hessian of the losses in $m$, which +the objective returns, plus $C = \sum_i u_i^\top \nabla^2 m_i$. The structured methods keep $G$ +at every iterate and learn only $A \approx C$ from the steps. The secant of Dennis, Martínez and +Tapia [@dennis1989convergence] is $(J_{k+1} - J_k)^\top u_{k+1}$ for the data term, of +Gauss-Newton Hessian $G^{\rm LS}$; the other terms of a sum, such as a prior, take the secant of +their gradient and Hessian: + +$$B_k = G_k + A_k, \qquad +y^\#_k = y_k - J_k^\top (u_{k+1} - u_k) - \left(G_{k+1} - G^{\rm LS}_{k+1}\right) s_k , \tag{13}$$ + +$s_k$ and $y_k$ from (9). For $\ell_i = r_i^2$, $u = 2 r$ and the data part is +$2 (J_{k+1} - J_k)^\top r_{k+1}$, as in Fides [@froehlich2022fides]. It equals +$C(\theta_{k+1}) s_k$ up to $O(\lVert s_k \rVert^2)$ and takes nothing from the linearization +error of $G$, which grows with the step where the residuals are nonlinear. A Gaussian prior, +whose Hessian is constant and part of $G$, adds nothing. Asked for `hessian = "structured"`, an +objective returns $J$, $u$ and $G^{\rm LS}$ (see `objlist()`); an objective without them has +$J = 0$ and $G^{\rm LS} = 0$ in (13). + +`"sbfgs"` applies the BFGS update (11) with $\tilde y = y$ to $G_{k+1} + A_k$ with the pair +$(s_k, G_{k+1} s_k + y^\#_k)$ and keeps the difference to $G_{k+1}$, + +$$A_{k+1} = \operatorname{BFGS}(G_{k+1} + A_k;\ s_k, G_{k+1} s_k + y^\#_k) - G_{k+1}, \tag{14}$$ + +after accepted steps and with the test of `qnCautious`. The update is not damped: $G_{k+1}$ +changes from iterate to iterate, so $G_{k+1} + A_k$ need not be positive definite along $s_k$, +and the update then still restores the secant equation. `"ssr1"` applies (12) to the correction, + +$$A_{k+1} = A_k + \frac{w\, w^\top}{w^\top s_k}, \qquad w = y^\#_k - A_k s_k, \tag{15}$$ + +skipped when $\lvert w^\top s_k \rvert \le 10^{-8} \lVert s_k \rVert \lVert w \rVert$. $A$ stays +indefinite where $C$ is, and rejected trial points update it under `qnRejected`. Both start at +$A_0 = 0$, so the first step is a Gauss-Newton step; a handover or a reseed starts there again. +A pair that leaves $A$ unchanged counts in `qnSkipped`. + +`qnScaling = "residual"` is the totally structured secant method of Huschens +[@yabe1998quadratic]. With the residual norm $\rho = \lVert u \rVert$, which is $2 \lVert r \rVert$ +for $\ell_i = r_i^2$, and $\rho = \sqrt{\mathcal{J}}$ for an objective without data rows, + +$$B_k = G_k + \rho_k A_k, \qquad z_k = \frac{\rho_{k+1}}{\rho_k}\, y^\#_k , \tag{16}$$ + +(14) or (15) act on $\rho_{k+1} A_k$ with $z_k$ in place of $y^\#_k$, and $A_{k+1}$ is the +result divided by $\rho_{k+1}$. The correction vanishes with the residuals: convergence is +quadratic for a zero residual and superlinear otherwise. $\rho = 0$ leaves $A$ unchanged. + +`"gnsbfgs"` is the hybrid Gauss-Newton structured BFGS method of Zhou and Chen +[@zhou2010global]. After every accepted step, with $z_k$ from (16), + +$$B_{k+1} = \begin{cases} +G_{k+1} + A_{k+1}, \quad A_{k+1} = \operatorname{BFGS}(A_k;\ s_k, z_k), + & z_k^\top s_k \ge \epsilon\, s_k^\top s_k , \\ +G_{k+1}, \quad A_{k+1} = A_k, & \text{otherwise,} +\end{cases} \tag{17}$$ + +with $\epsilon$ = `qnHybridTol`, default $10^{-6}$ as in the paper, the undamped update (11) and +$A_0 = 0$. The ratio $z^\top s / s^\top s$ tends to zero for a zero residual, where the run becomes +Gauss-Newton with quadratic convergence, and stays above a positive bound where $C$ is positive +definite at the minimum, where the run is structured BFGS with superlinear convergence. The +Gauss-Newton branch is $G$ alone, since the trust region regularizes; `qnHybridShift = TRUE` adds +the term $\rho\, I$ of the paper, with the residual norm $\rho$ of (16), which keeps the matrix of +the line search positive definite there. Where $C$ is +indefinite at the minimum the ratio of a step can stay negative and the run then stays +Gauss-Newton. `"gnssr1"` uses (15) with $z_k$ and the test +$\lvert z_k^\top s_k \rvert \ge \epsilon\, s_k^\top s_k$, so it takes negative curvature into the +correction as well. In the trace `hessianSource` is `"gn"` for the iterations on the Gauss-Newton +branch, `hybridGN` counts the steps that chose it. + ### Seed and memory Far from the optimum $J^\top J$ is large and ill-conditioned; BFGS corrects a seed that is wrong @@ -193,8 +268,26 @@ directions [@gutenkunst2007universally]. ### Hessian phases A phase hands over to the next where a value, model, step or stagnation stop or the `iterlim` of the phase -would end the run; `"gradient"` ends the run. A handover resets the radius to `rinit` and seeds a -quasi-Newton phase with the Gauss-Newton Hessian, as in Fides [@froehlich2022fides]. +would end the run; `"gradient"` ends the run, and with `onStop = "end"` the value, model, step and +stagnation stops end it as well. A phase with `radiusStall` $= n$ also hands over after $n$ +consecutive iterations that leave the radius unchanged, an accepted step inside the region or one +that the region at `rmax` bounds. A handover resets the radius to `rinit`, or keeps it with +`keepRadius = TRUE`, and seeds a quasi-Newton phase with the Gauss-Newton Hessian at the iterate of +the handover. With `hessianInit = "tracked"` a BFGS phase starts instead from a matrix kept over the +whole run: the Hessian of the first phase at $\theta_0$, with the absolute values of the +eigenvalues where it is indefinite, updated by (10) and (11) with the pair (9) of every accepted step of the +phases before, under the same tests as the update in the phase. + +The default of `trust()` is the hybrid method of Fides [@froehlich2022fides]: Gauss-Newton with +`radiusStall = 20` and `onStop = "end"`, then BFGS, tracked from the Gauss-Newton Hessian at +$\theta_0$, at the radius of the switch, which happens at most once. Where the residuals at the +minimum are large, the Gauss-Newton model misses the second term of the Hessian, and the +Gauss-Newton steps converge linearly, inside the region: the radius no longer changes, and the +BFGS matrix, which has taken up the curvature along the path, takes over. A run +that converges before 20 iterations at an unchanged radius stays Gauss-Newton throughout. The BFGS +phase evaluates the gradient forward, so the switch costs no evaluation. Multiple shooting, +`boundary = "clip"` and the [sparse path](#sparse-hessians) run Gauss-Newton alone, as +`hessianMethod = "gn"` does. ### Sparse Hessians @@ -211,26 +304,52 @@ to $-\lambda_{\min}$. `sparse = "auto"` compares the flops of a step, about eigh with $m + 2$ solves each from the symbolic analysis, with the $4 n_\theta^3$ of the eigendecomposition. +A BFGS phase on the sparse path, `"bfgs"` with `hessianInit = "gn"`, is limited-memory BFGS on the +Hessian $B_0 = S_0 + U_0 D_0 U_0^\top$ of the objective at the start of the phase. It keeps the last +$m$ pairs (9), $m$ = `qnMemory` or 10 where that is 0, each damped by (10) against the model it +updates and skipped by the same tests as the dense update. In the compact representation +[@byrd1994representations] + +$$B = B_0 - W M^{-1} W^\top, \qquad W = (B_0 S,\ Y), \qquad +M = \begin{pmatrix} S^\top B_0 S & L \\ L^\top & -E \end{pmatrix}, \tag{18}$$ + +$S$ and $Y$ hold the pairs as columns, $L$ the strict lower triangle of $S^\top Y$ and $E$ the +diagonal. With $M = P \Theta P^\top$ the correction joins the low-rank part as the $2m$ columns of +$W P$ with the diagonal $-\Theta^{-1}$, which has entries of both signs, so the sparse factor is that +of $S_0$ throughout the phase. $B_0$ stays fixed: the phase evaluates value and gradient only, and a +Hessian at every iterate would cost what the phase saves. A BFGS update keeps the inertia of the +matrix it starts from, so an indefinite $B_0$, the Gauss-Newton Hessian of an error model that +depends on the parameters for one, would keep the directions of negative curvature for the whole +phase. Where the factorization of $B_0$ shows it is not positive definite, $B_0$ takes $\tau I$ +added, $\tau$ the smallest of $10^{-8}, 10^{-7}, \ldots$ times a bound of $\lVert B_0 \rVert$ that +makes it definite, refined by bisection [@nocedal2006numerical, Algorithm 3.3]; the dense phase +takes the absolute values of the eigenvalues instead. On a simulated alignment of 200 gels with +721 parameters (`bench/sparse/alignment.R`), 20 Gauss-Newton iterations followed by the +limited-memory phase reach the optimum of Gauss-Newton from every start, at 20 to 70 times the +median time of Gauss-Newton: with $B_0$ fixed the phase converges linearly, and every step solves with $2m$ more low-rank +columns. Gauss-Newton stays the source of a sparse fit; the BFGS phase is for objectives whose +Gauss-Newton Hessian misses curvature that matters. + ## L1 penalties `trustL1()` minimizes the objective plus an L1 penalty on some of the parameters [@tibshirani1996regression], -$$\mathcal{J}(\theta) + \sum_{i \in P} \lambda_i \lvert \theta_i - \mu_i \rvert , \tag{13}$$ +$$\mathcal{J}(\theta) + \sum_{i \in P} \lambda_i \lvert \theta_i - \mu_i \rvert , \tag{19}$$ with penalized parameters $P$, references $\mu_i$ and strengths $\lambda_i$. `trustL1()` runs the trust region with the Gauss-Newton Hessian and two changes: a parameter on the kink is removed from (1) while $\lvert \partial \mathcal{J} / \partial \theta_i \rvert \le \lambda_i$, and a step across the kink is cut back onto $\mu_i$, so zero differences are exact. Further penalties are a one-sided one, -$$\lambda_i \max(0,\, \mu_i - \theta_i) , \tag{14}$$ +$$\lambda_i \max(0,\, \mu_i - \theta_i) , \tag{20}$$ which keeps a parameter on the kink while $0 \le \partial \mathcal{J} / \partial \theta_i \le \lambda_i$; a gate $\lambda_i (\theta_i - \mu_i)$ with $\theta_i \ge \mu_i$, which keeps it there while $\partial \mathcal{J} / \partial \theta_i \ge -\lambda_i$; and a fused block $B$, the clustered lasso [@hauber2023uncovering] in the L1 form (Hauber et al. favor the exponent 0.8), -$$\lambda \sum_{p < q \in B} w_{pq}\, \lvert \theta_p - \theta_q \rvert , \tag{15}$$ +$$\lambda \sum_{p < q \in B} w_{pq}\, \lvert \theta_p - \theta_q \rvert , \tag{21}$$ optionally with an anchor; equal parameters move as one until the data split them. @@ -256,8 +375,11 @@ timing <- readRDS(file.path(oppelt, "results", "sensitivities.rds"))$timing timing ``` -`optimizers.R` fits from the same 100 prior draws with Gauss-Newton, BFGS and SR1 on the reverse -gradient from the identity, the exact Hessian, and 20 Gauss-Newton iterations followed by BFGS: +`optimizers.R` fits from the same 100 prior draws with the default of `trust()`, Gauss-Newton, BFGS and SR1 on the reverse +gradient from the identity, the exact Hessian, 20 Gauss-Newton iterations followed by BFGS, and the +structured methods of [Structured secant updates](#structured-secant-updates), with and without +residual scaling and the shift of the hybrids; a draw without a stable resting state is replaced +by one with, and a task runs at most 30 minutes: ```{r optimizers, eval = FALSE} ``` @@ -280,23 +402,72 @@ summary ``` Medians over starts; a hit ends within 5 of the best value; `iterlim` counts the runs stopped by -the iteration limit; `failed` counts starts without result: +the iteration limit; `failed` counts runs without result, which the time limit of a task ended. The stops by method, with a +stagnation that ends away from a stationary point of the model counted apart: + +```{r} +stop <- ifelse(is.na(opt$stopReason), "failed", opt$stopReason) +stop[stop == "stagnation" & !opt$converged] <- "stagnation, not converged" +stops <- c("gradient", "fvalue", "preddiff", "stagnation", "stagnation, not converged", "radius", + "iterlim", "failed") +table(opt$method, factor(stop, stops)) +``` -```{r, fig.height = 4} +```{r, fig.height = 4, fig.width = 11} plotValues(split(opt, opt$method), pseudoLog = TRUE) + ggplot2::theme(legend.position = "bottom") ``` ```{r, include = FALSE} best <- function(column, fun = which.max) rownames(summary)[fun(summary[[column]])] +iterationsSR1 <- median(opt$iterations[opt$method == "SR1" & opt$converged]) ``` A reverse gradient costs about 1/`r round(timing[["forward"]] / timing[["reverse"]])` of the forward sensitivities, an exact Hessian by forward over reverse about `r round(timing[["forward-reverse"]] / timing[["forward"]])` times. `r best("hits")` reaches the lowest plateaus most often, `r best("converged")` converges most often, and -`r best("secondsPerHit", which.min)` needs the least time per hit. Gauss-Newton followed by BFGS -stops at the iteration limit in `r summary["GN, then BFGS", "iterlim"]` runs: the BFGS phase starts -from the Gauss-Newton Hessian far from the optimum ([Seed and memory](#seed-and-memory)). +`r best("secondsPerHit", which.min)` needs the least time per hit. + +The switch to BFGS once the radius stays unchanged for 25 or 50 iterations +([Hessian phases](#hessian-phases)) reaches as many low plateaus as the switch after 20 Gauss-Newton +iterations, at almost twice the time per hit: on this objective the radius seldom stays unchanged +that long, and the Gauss-Newton phase, with forward sensitivities on every step, does most of the +descent. + +The default, the hybrid of Fides with the switch at 20 iterations of unchanged radius, converges +from more starts than Gauss-Newton and reaches as many low plateaus, at about the same time per +hit. Half of the default runs end in the Gauss-Newton phase on the value stop, which +`onStop = "end"` makes final, and the BFGS phase takes the forward gradient of the Gauss-Newton phase. + +The structured methods spend a forward Gauss-Newton Hessian on every step. `"gnsbfgs"` needs the +fewest iterations of all methods, and SR1 on the residual-scaled correction converges from more +starts than any method but the exact Hessian. The shift of the hybrids by +$\rho\, I$ helps nowhere here: far from the minimum $\rho$ is large, the shifted Gauss-Newton +branch of `"gnsbfgs"` takes short steps, and most runs end at the iteration limit; +`"gnssr1"` ends where it ends without the shift. + +The runs that do not converge have three causes: + +- The Gauss-Newton runs at the iteration limit end on plateaus 100 to 1000 above the best value, + with a slow oscillating mode at the onset of the stability ramp. There the Gauss-Newton model of + the data term, which lacks the curvature of the residuals, predicts about 1.5 times the decrease + that follows: steps are accepted, the radius stays between `1e-4` and `5e-3`, and the value + falls by about `2e-4` per step. The exact Hessian and the BFGS phase after 20 Gauss-Newton + iterations converge from 13 of these 15 starts. +- SR1 from the identity builds the curvature of a Hessian whose eigenvalues span six orders of + magnitude over hundreds of rejected and accepted steps; a converged SR1 run takes a median of + `r iterationsSR1` iterations, so `iterlim = 1000` ends the slower runs before convergence. +- On poor plateaus the value of the Oppelt objective scatters by about `2e-4` with the step-size + control of the ODE solver, above `ftol`. A run there ends on stagnation, five rejected steps in a + row, and counts as converged only where the full Newton step of the model predicts at most + `mtol` ([Termination criteria](#termination-criteria)). + +The stability term rises on a ramp a tenth of the inverse time span of the data wide, about +`2.8e-4` per minute (`model.R`). On a ramp of $10^{-6}$ times +the largest eigenvalue modulus, about `2e-5` here, the model of a step sees the boundary only after +the step crosses it, and the runs creep along the boundary between rejected steps +([Methods > Steady states](methods-steady-states.html#stability)). The Hessian of the stability term is the +Gauss-Newton one for every source, also for the exact Hessian. ## Stored results diff --git a/vignettes/articles/refs.bib b/vignettes/articles/refs.bib index db1d7355..8e7e4a0c 100644 --- a/vignettes/articles/refs.bib +++ b/vignettes/articles/refs.bib @@ -1,5 +1,5 @@ @article{kaschek2019dmod, - title = {{dMod}: {{Efficient}} Parameter Estimation and Uncertainty Analysis for Dynamic Models}, + title = {Dynamic Modeling, Parameter Estimation, and Uncertainty Analysis in {{R}}}, author = {Kaschek, Daniel and Mader, Wolfgang and Fehling-Kaschek, Mirjam and Rosenblatt, Marcus and Timmer, Jens}, date = {2019}, journaltitle = {Journal of Statistical Software}, @@ -9,28 +9,6 @@ @article{kaschek2019dmod doi = {10.18637/jss.v088.i10}, } -@article{boehm2014identification, - title = {Identification of Isoform-Specific Dynamics in Phosphorylation-Dependent {{STAT5}} Dimerization by Quantitative Mass Spectrometry and Mathematical Modeling}, - author = {Boehm, Martin E. and Adlung, Lorenz and Schilling, Marcel and Roth, Susanne and Klingmüller, Ursula and Lehmann, Wolf D.}, - date = {2014}, - journaltitle = {Journal of Proteome Research}, - volume = {13}, - number = {12}, - pages = {5685--5694}, - doi = {10.1021/pr5006923}, -} - -@article{coleman1996interior, - title = {An Interior Trust Region Approach for Nonlinear Minimization Subject to Bounds}, - author = {Coleman, Thomas F. and Li, Yuying}, - date = {1996}, - journaltitle = {SIAM Journal on Optimization}, - volume = {6}, - number = {2}, - pages = {418--445}, - doi = {10.1137/0806023}, -} - @article{froehlich2022fides, title = {Fides: {{Reliable}} Trust-Region Optimization for Parameter Estimation of {{ODE}} Models}, author = {Fröhlich, Fabian and Sorger, Peter K.}, @@ -42,6 +20,17 @@ @article{froehlich2022fides doi = {10.1371/journal.pcbi.1010322}, } +@article{byrd1994representations, + title = {Representations of Quasi-{{Newton}} Matrices and Their Use in Limited Memory Methods}, + author = {Byrd, Richard H. and Nocedal, Jorge and Schnabel, Robert B.}, + date = {1994}, + journaltitle = {Mathematical Programming}, + volume = {63}, + number = {1--3}, + pages = {129--156}, + doi = {10.1007/BF01582063}, +} + @article{more1983computing, title = {Computing a Trust Region Step}, author = {Moré, Jorge J. and Sorensen, D. C.}, @@ -64,17 +53,6 @@ @article{liu1994ecme doi = {10.1093/biomet/81.4.633}, } -@article{li2001global, - title = {On the Global Convergence of the {{BFGS}} Method for Nonconvex Unconstrained Optimization Problems}, - author = {Li, Dong-Hui and Fukushima, Masao}, - date = {2001}, - journaltitle = {SIAM Journal on Optimization}, - volume = {11}, - number = {4}, - pages = {1054--1064}, - doi = {10.1137/S1052623499354242}, -} - @article{shanno1978matrix, title = {Matrix Conditioning and Nonlinear Optimization}, author = {Shanno, David F. and Phua, Kang-Hoh}, @@ -91,7 +69,9 @@ @book{nocedal2006numerical author = {Nocedal, Jorge and Wright, Stephen J.}, date = {2006}, edition = {2}, + series = {Springer Series in Operations Research and Financial Engineering}, publisher = {Springer}, + location = {New York}, doi = {10.1007/978-0-387-40065-5}, } @@ -106,13 +86,17 @@ @article{gutenkunst2007universally doi = {10.1371/journal.pcbi.0030189}, } -@article{powell1978fast, +@incollection{powell1978fast, title = {A Fast Algorithm for Nonlinearly Constrained Optimization Calculations}, author = {Powell, M. J. D.}, date = {1978}, - journaltitle = {Lecture Notes in Mathematics}, + booktitle = {Numerical Analysis}, + editor = {Watson, G. Alistair}, + series = {Lecture Notes in Mathematics}, volume = {630}, pages = {144--157}, + publisher = {Springer}, + location = {Berlin, Heidelberg}, doi = {10.1007/BFb0067703}, } @@ -127,28 +111,6 @@ @article{zhang2004nonmonotone doi = {10.1137/S1052623403428208}, } -@article{bachmann2011division, - title = {Division of Labor by Dual Feedback Regulators Controls {{JAK2}}/{{STAT5}} Signaling over Broad Ligand Range}, - author = {Bachmann, Julie and Raue, Andreas and Schilling, Marcel and Böhm, Martin E. and Kreutz, Clemens and Kaschek, Daniel and Busch, Hauke and Gretz, Norbert and Lehmann, Wolf D. and Timmer, Jens and Klingmüller, Ursula}, - date = {2011}, - journaltitle = {Molecular Systems Biology}, - volume = {7}, - number = {1}, - pages = {516}, - doi = {10.1038/msb.2011.50}, -} - -@article{hass2019benchmark, - title = {Benchmark Problems for Dynamic Modeling of Intracellular Processes}, - author = {Hass, Helge and Loos, Carolin and Raimúndez-Álvarez, Elba and Timmer, Jens and Hasenauer, Jan and Kreutz, Clemens}, - date = {2019}, - journaltitle = {Bioinformatics}, - volume = {35}, - number = {17}, - pages = {3073--3082}, - doi = {10.1093/bioinformatics/btz020}, -} - @incollection{bock1983recent, title = {Recent Advances in Parameter Identification Techniques for {{O.D.E.}}}, author = {Bock, Hans Georg}, @@ -157,9 +119,10 @@ @incollection{bock1983recent editor = {Deuflhard, Peter and Hairer, Ernst}, series = {Progress in Scientific Computing}, volume = {2}, + pages = {95--121}, publisher = {Birkhäuser}, location = {Boston}, - pages = {95--121}, + doi = {10.1007/978-1-4684-7324-7_7}, } @article{fletcher2002nonlinear, @@ -206,16 +169,6 @@ @article{ye2015improved doi = {10.5194/npg-22-205-2015}, } -@article{toth2011dynamical, - title = {Dynamical Estimation of Neuron and Network Properties {{I}}: {{Variational}} Methods}, - author = {Toth, Bryan A. and Kostuk, Mark and Meliza, C. Daniel and Margoliash, Daniel and Abarbanel, Henry D. I.}, - date = {2011}, - journaltitle = {Biological Cybernetics}, - volume = {105}, - number = {3--4}, - pages = {217--237}, -} - @article{fitzhugh1961impulses, title = {Impulses and Physiological States in Theoretical Models of Nerve Membrane}, author = {FitzHugh, Richard}, @@ -227,17 +180,6 @@ @article{fitzhugh1961impulses doi = {10.1016/S0006-3495(61)86902-6}, } -@article{butera1999models, - title = {Models of Respiratory Rhythm Generation in the Pre-{{Bötzinger}} Complex. {{I}}. {{Bursting}} Pacemaker Neurons}, - author = {Butera, Robert J. and Rinzel, John and Smith, Jeffrey C.}, - date = {1999}, - journaltitle = {Journal of Neurophysiology}, - volume = {82}, - number = {1}, - pages = {382--397}, - doi = {10.1152/jn.1999.82.1.382}, -} - @article{peifer2007parameter, title = {Parameter Estimation in Ordinary Differential Equations for Biochemical Processes Using the Method of Multiple Shooting}, author = {Peifer, Martin and Timmer, Jens}, @@ -247,6 +189,7 @@ @article{peifer2007parameter number = {2}, pages = {78--88}, doi = {10.1049/iet-syb:20060067}, + url = {https://www.fdm.uni-freiburg.de/publications-preprints/papers/04140671/at_download/file}, } @article{horbelt2002parameter, @@ -257,6 +200,8 @@ @article{horbelt2002parameter volume = {299}, number = {5--6}, pages = {513--521}, + doi = {10.1016/S0375-9601(02)00748-X}, + url = {https://www.fdm.uni-freiburg.de/publications-preprints/papers/horbelt02pla.pdf/at_download/file}, } @article{voss2004nonlinear, @@ -281,15 +226,6 @@ @article{carter1991global doi = {10.1137/0728014}, } -@book{conn2000trust, - title = {Trust-Region Methods}, - author = {Conn, Andrew R. and Gould, Nicholas I. M. and Toint, Philippe L.}, - date = {2000}, - publisher = {SIAM}, - location = {Philadelphia}, - doi = {10.1137/1.9780898719857}, -} - @article{wang2007derivation, title = {Derivation of Various {{NONMEM}} Estimation Methods}, author = {Wang, Yaning}, @@ -312,22 +248,16 @@ @article{pinheiro1995approximations doi = {10.1080/10618600.1995.10474663}, } -@book{pinheiro2000mixed, - title = {Mixed-Effects Models in {{S}} and {{S-PLUS}}}, - author = {Pinheiro, José C. and Bates, Douglas M.}, - date = {2000}, - publisher = {Springer}, - location = {New York}, - doi = {10.1007/b98882}, -} - @article{smolyak1963quadrature, title = {Quadrature and Interpolation Formulas for Tensor Products of Certain Classes of Functions}, author = {Smolyak, Sergey A.}, date = {1963}, - journaltitle = {Soviet Mathematics Doklady}, - volume = {4}, - pages = {240--243}, + journaltitle = {Doklady Akademii Nauk SSSR}, + volume = {148}, + number = {5}, + pages = {1042--1045}, + langid = {russian}, + url = {https://www.mathnet.ru/eng/dan27586}, } @article{heiss2008likelihood, @@ -357,16 +287,8 @@ @inproceedings{clausen2009maximum author = {Clausen, William H. O. and Rønn, Birgitte B. and Skovgaard, Ib M.}, date = {2009}, booktitle = {Population Approach Group in Europe ({{PAGE}}) 18}, - pages = {Abstract 1607}, -} - -@book{lavielle2014mixed, - title = {Mixed Effects Models for the Population Approach: Models, Tasks, Methods and Tools}, - author = {Lavielle, Marc}, - date = {2014}, - publisher = {Chapman and Hall/CRC}, - location = {Boca Raton}, - doi = {10.1201/b17203}, + pages = {Abstract 1584}, + url = {https://www.page-meeting.org/?abstract=1584}, } @article{meng1993maximum, @@ -423,28 +345,6 @@ @article{kuhn2004coupling doi = {10.1051/ps:2004007}, } -@article{kuhn2005maximum, - title = {Maximum Likelihood Estimation in Nonlinear Mixed Effects Models}, - author = {Kuhn, Estelle and Lavielle, Marc}, - date = {2005}, - journaltitle = {Computational Statistics \& Data Analysis}, - volume = {49}, - number = {4}, - pages = {1020--1038}, - doi = {10.1016/j.csda.2004.07.002}, -} - -@article{polyak1992acceleration, - title = {Acceleration of Stochastic Approximation by Averaging}, - author = {Polyak, Boris T. and Juditsky, Anatoli B.}, - date = {1992}, - journaltitle = {SIAM Journal on Control and Optimization}, - volume = {30}, - number = {4}, - pages = {838--855}, - doi = {10.1137/0330046}, -} - @article{vehtari2024pareto, title = {Pareto Smoothed Importance Sampling}, author = {Vehtari, Aki and Simpson, Daniel and Gelman, Andrew and Yao, Yuling and Gabry, Jonah}, @@ -453,6 +353,7 @@ @article{vehtari2024pareto volume = {25}, number = {72}, pages = {1--58}, + url = {https://jmlr.org/papers/v25/19-556.html}, } @article{oppelt2018model, @@ -461,6 +362,7 @@ @article{oppelt2018model date = {2018}, journaltitle = {npj Systems Biology and Applications}, volume = {4}, + number = {1}, pages = {23}, doi = {10.1038/s41540-018-0058-z}, } @@ -476,6 +378,17 @@ @article{mitchell1988bayesian doi = {10.1080/01621459.1988.10478694}, } +@article{barbieri2004optimal, + title = {Optimal Predictive Model Selection}, + author = {Barbieri, Maria Maddalena and Berger, James O.}, + date = {2004}, + journaltitle = {The Annals of Statistics}, + volume = {32}, + number = {3}, + pages = {870--897}, + doi = {10.1214/009053604000000238}, +} + @article{george1993variable, title = {Variable Selection via {{Gibbs}} Sampling}, author = {George, Edward I. and McCulloch, Robert E.}, @@ -487,6 +400,17 @@ @article{george1993variable doi = {10.1080/01621459.1993.10476353}, } +@article{steiert2016l1, + title = {{{L1}} Regularization Facilitates Detection of Cell Type-Specific Parameters in Dynamical Systems}, + author = {Steiert, Bernhard and Timmer, Jens and Kreutz, Clemens}, + date = {2016}, + journaltitle = {Bioinformatics}, + volume = {32}, + number = {17}, + pages = {i718--i726}, + doi = {10.1093/bioinformatics/btw461}, +} + @article{tibshirani1996regression, title = {Regression Shrinkage and Selection via the Lasso}, author = {Tibshirani, Robert}, @@ -505,6 +429,7 @@ @article{opper2005expectation journaltitle = {Journal of Machine Learning Research}, volume = {6}, pages = {2177--2204}, + url = {https://jmlr.org/papers/v6/opper05a.html}, } @article{lange1995quasi, @@ -515,6 +440,7 @@ @article{lange1995quasi volume = {5}, number = {1}, pages = {1--18}, + url = {https://www3.stat.sinica.edu.tw/statistica/j5n1/j5n11/j5n11.htm}, } @article{jamshidian1997acceleration, @@ -528,17 +454,6 @@ @article{jamshidian1997acceleration doi = {10.1111/1467-9868.00083}, } -@article{ewens1972sampling, - title = {The Sampling Theory of Selectively Neutral Alleles}, - author = {Ewens, Warren J.}, - date = {1972}, - journaltitle = {Theoretical Population Biology}, - volume = {3}, - number = {1}, - pages = {87--112}, - doi = {10.1016/0040-5809(72)90035-4}, -} - @article{neal2000markov, title = {Markov Chain Sampling Methods for {{Dirichlet}} Process Mixture Models}, author = {Neal, Radford M.}, @@ -566,6 +481,8 @@ @article{heskes2005approximate author = {Heskes, Tom and Opper, Manfred and Wiegerinck, Wim and Winther, Ole and Zoeter, Onno}, date = {2005}, journaltitle = {Journal of Statistical Mechanics: Theory and Experiment}, + volume = {2005}, + number = {11}, pages = {P11015}, doi = {10.1088/1742-5468/2005/11/P11015}, } @@ -581,7 +498,6 @@ @article{hauber2023uncovering doi = {10.1371/journal.pcbi.1010867}, } - @article{merkt2015higher, title = {Higher-Order {{Lie}} Symmetries in Identifiability and Predictability Analysis of Dynamic Models}, author = {Merkt, Benjamin and Timmer, Jens and Kaschek, Daniel}, @@ -621,6 +537,7 @@ @article{kreutz2012likelihood date = {2012}, journaltitle = {BMC Systems Biology}, volume = {6}, + number = {1}, pages = {120}, doi = {10.1186/1752-0509-6-120}, } @@ -635,10 +552,102 @@ @article{rosenblatt2016customized doi = {10.3389/fcell.2016.00041}, } -@book{godfrey1983compartmental, - author = {Godfrey, Keith}, - title = {Compartmental Models and Their Application}, - publisher = {Academic Press}, - address = {London}, - year = {1983} +@article{dennis1989convergence, + title = {Convergence Theory for the Structured {{BFGS}} Secant Method with an Application to Nonlinear Least Squares}, + author = {Dennis, J. E. and Martínez, H. J. and Tapia, R. A.}, + date = {1989}, + journaltitle = {Journal of Optimization Theory and Applications}, + volume = {61}, + number = {2}, + pages = {161--178}, + doi = {10.1007/BF00962795}, +} + +@article{zhou2010global, + title = {Global Convergence of a New Hybrid {{Gauss-Newton}} Structured {{BFGS}} Method for Nonlinear Least Squares Problems}, + author = {Zhou, Weijun and Chen, Xiaojun}, + date = {2010}, + journaltitle = {SIAM Journal on Optimization}, + volume = {20}, + number = {5}, + pages = {2422--2441}, + doi = {10.1137/090748470}, +} + +@article{liu1994collapsed, + title = {The Collapsed {{Gibbs}} Sampler in {{Bayesian}} Computations with Applications to a Gene Regulation Problem}, + author = {Liu, Jun S.}, + date = {1994}, + journaltitle = {Journal of the American Statistical Association}, + volume = {89}, + number = {427}, + pages = {958--966}, + doi = {10.1080/01621459.1994.10476829}, +} + +@article{tierney1994markov, + title = {{{Markov}} Chains for Exploring Posterior Distributions}, + author = {Tierney, Luke}, + date = {1994}, + journaltitle = {The Annals of Statistics}, + volume = {22}, + number = {4}, + pages = {1701--1728}, + doi = {10.1214/aos/1176325750}, +} + +@article{casella1996rao, + title = {{{Rao-Blackwellisation}} of Sampling Schemes}, + author = {Casella, George and Robert, Christian P.}, + date = {1996}, + journaltitle = {Biometrika}, + volume = {83}, + number = {1}, + pages = {81--94}, + doi = {10.1093/biomet/83.1.81}, +} + +@article{coleman1994convergence, + title = {On the Convergence of Interior-Reflective {{Newton}} Methods for Nonlinear Minimization Subject to Bounds}, + author = {Coleman, Thomas F. and Li, Yuying}, + date = {1994}, + journaltitle = {Mathematical Programming}, + volume = {67}, + number = {1--3}, + pages = {189--224}, + doi = {10.1007/BF01582221}, +} + +@article{yabe1998quadratic, + title = {Quadratic and Superlinear Convergence of the {{Huschens}} Method for Nonlinear Least Squares Problems}, + author = {Yabe, Hiroshi and Ogasawara, Hideho}, + date = {1998}, + journaltitle = {Computational Optimization and Applications}, + volume = {10}, + number = {1}, + pages = {79--103}, + doi = {10.1023/A:1018391917880}, +} + +@book{kushner2003stochastic, + title = {Stochastic Approximation and Recursive Algorithms and Applications}, + author = {Kushner, Harold J. and Yin, G. George}, + date = {2003}, + edition = {2}, + series = {Stochastic Modelling and Applied Probability}, + volume = {35}, + publisher = {Springer}, + location = {New York}, + doi = {10.1007/b97441}, +} + +@book{pitman2006combinatorial, + title = {Combinatorial Stochastic Processes}, + author = {Pitman, Jim}, + date = {2006}, + series = {Lecture Notes in Mathematics}, + volume = {1875}, + publisher = {Springer}, + location = {Berlin, Heidelberg}, + doi = {10.1007/b11601500}, } diff --git a/vignettes/articles/results/guide-symmetries.R b/vignettes/articles/results/guide-symmetries.R deleted file mode 100644 index 3e30c62e..00000000 --- a/vignettes/articles/results/guide-symmetries.R +++ /dev/null @@ -1,15 +0,0 @@ -# The discrete symmetries of the two-compartment model of Godfrey, for guide chapter 2, -# guide-symmetries.Rmd, which shows the labeled part and reads the result from -# guide-symmetries.rds. The search needs msolve. Run in this folder. - -library(dMod2) - -## ---- godfrey -f <- eqnvec(x1 = "-(k21 + k01)*x1 + k12*x2 + u", x2 = "k21*x1 - k12*x2") -compartments <- symmetryDetection(f, eqnvec(y = "x2"), knownInputs = "u", discrete = TRUE) - -## ---- save -# the md5 of the script, which the article checks on reading -attr(compartments, "stamp") <- list(md5 = tools::md5sum("guide-symmetries.R"), - dMod2 = packageVersion("dMod2")) -saveRDS(compartments, "guide-symmetries.rds") diff --git a/vignettes/articles/results/guide-symmetries.rds b/vignettes/articles/results/guide-symmetries.rds deleted file mode 100644 index 4314fd9f..00000000 Binary files a/vignettes/articles/results/guide-symmetries.rds and /dev/null differ