diff --git a/.github/workflows/R-CMD-check.yaml b/.github/workflows/R-CMD-check.yaml index e3e86dfb..190a1e63 100644 --- a/.github/workflows/R-CMD-check.yaml +++ b/.github/workflows/R-CMD-check.yaml @@ -33,7 +33,23 @@ name: R-CMD-check permissions: read-all jobs: + # a tree that already passed this workflow, e.g. a pull request merged by fast-forward, is not + # checked again; the skipped jobs count as passed + pre: + runs-on: ubuntu-latest + outputs: + should_skip: ${{ steps.skip.outputs.should_skip }} + steps: + - id: skip + uses: fkirc/skip-duplicate-actions@v5 + with: + skip_after_successful_duplicate: 'true' + concurrent_skipping: 'never' + do_not_skip: '["workflow_dispatch", "schedule"]' + R-CMD-check: + needs: pre + if: needs.pre.outputs.should_skip != 'true' runs-on: ${{ matrix.config.os }} name: ${{ matrix.config.os }} (${{ matrix.config.r }}) @@ -106,6 +122,8 @@ jobs: # gcc, FlexiBLAS and the hardening flags differ from Ubuntu's. No RSPM binaries # here, so dependencies build from source. fedora: + needs: pre + if: needs.pre.outputs.should_skip != 'true' runs-on: ubuntu-latest container: fedora:latest name: fedora (R release, gcc/FlexiBLAS) diff --git a/DESCRIPTION b/DESCRIPTION index e54966da..9e87eff3 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Package: dMod2 Type: Package Title: Parameter Estimation in Dynamical Models -Version: 0.16.0 +Version: 0.16.1 Date: 2026-11-16 Authors@R: c( person("Simon", "Beyer", email = "simon.beyer@fdm.uni-freiburg.de", diff --git a/NEWS.md b/NEWS.md index c695733e..b0a5a05f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,19 @@ +# dMod2 0.16.1 + +* `derivMode` alone selects the derivatives a constructor builds: `odemodel()`, `Y()`, `P()`, + `Pexpl()`, `Pimpl()` and `importPEtab()` take one or more of `"forward"` (default), + `"reverse"`, `"forward-forward"` and `"forward-reverse"`, or `"none"`. The build arguments + `deriv` and `deriv2` are removed: `deriv2 = TRUE` is `derivMode = "forward-forward"`, + `deriv = FALSE` is `derivMode = "none"`. Passing `deriv` or `deriv2` is an error. +* A second-order direction, `"forward-forward"` or `"forward-reverse"`, builds `"forward"` as + well. `"none"` combines with no other direction. `odemodel(derivMode = "reverse")` builds no + forward sensitivities. `Pimpl()` obtains the reverse directions from the forward ones. +* `deriv`, `deriv2` and `sweep` of a call keep their meaning. A call that asks for a derivative + the function object was built without is an error that names the missing `derivMode` + direction; `Y()`, `Pexpl()` and `Pimpl()` built without first derivatives no longer return + values alone on `deriv = TRUE`. +* The `odemodel` object holds the built directions in `attr(, "derivMode")`. + # dMod2 0.16.0 * The plotting theme and color helpers are named after the package: `theme_dMod2()`, diff --git a/R/EM.R b/R/EM.R index ef78e70b..c0598dd6 100644 --- a/R/EM.R +++ b/R/EM.R @@ -85,9 +85,9 @@ #' default `TRUE`.} #' \item{`derivMode`}{how FOCEI gets the second derivatives of the volume #' term: `"forward-reverse"` (default), sweeps for models built with -#' `derivMode = c("forward", "reverse", "forward-reverse")`, or +#' `derivMode = c("reverse", "forward-reverse")`, or #' `"forward-forward"`, the second-order sensitivities of models built -#' with `deriv2 = TRUE`. Without the mode asked for the fit takes the +#' with `derivMode = "forward-forward"`. Without the mode asked for the fit takes the #' other, with a message.} #' \item{`boundary`}{the largest rise of -2 log L at which a variance is #' set to 0, default 0.1, `FALSE` for none. With one grouping and several diff --git a/R/PEtabInterface.R b/R/PEtabInterface.R index 77ed6d76..79b22898 100644 --- a/R/PEtabInterface.R +++ b/R/PEtabInterface.R @@ -1366,7 +1366,8 @@ readPEtabTables <- function(yamlPath) { # sub-conditions with this preequilibration condition. eq_of[sub] <- peq if (is.null(eq_model[[peq]]) && length(peq_reactions$states)) - eq_model[[peq]] <- Pimpl(peq_reactions, condition = NULL, deriv2 = stability, + eq_model[[peq]] <- Pimpl(peq_reactions, condition = NULL, + derivMode = if (stability) "forward-forward" else "forward", compile = FALSE, outdir = outdir, modelname = paste(modelname, sanitizeConditions(peq), @@ -1545,7 +1546,7 @@ readPEtabTables <- function(yamlPath) { events = NULL, options = NULL, optionsSens = NULL, sparse = NULL, - deriv = TRUE, derivMode = "forward", + derivMode = "forward", outdir = .dmodOutdir()) { # No species means no dynamics: Xt() supplies the time axis and the # observables are evaluated from parameters alone. @@ -1557,7 +1558,7 @@ readPEtabTables <- function(yamlPath) { # which would apply the initial values there instead. args <- list(reactions, modelname = modelname, backend = backend, events = events, compile = FALSE, includeTimeZero = FALSE, - deriv = deriv, derivMode = derivMode, outdir = outdir) + derivMode = derivMode, outdir = outdir) if (!is.null(sparse) && backend != "deSolve") args$sparse <- sparse m <- do.call(odemodel, args) opts <- list(m) @@ -1648,7 +1649,7 @@ readPEtabTables <- function(yamlPath) { switches = NULL, options = NULL, optionsSens = NULL, sparse = NULL, - deriv = TRUE, derivMode = "forward", cores = 1L, + derivMode = "forward", cores = 1L, outdir = .dmodOutdir(), stability = TRUE) { # `importSbml` renames ids that R cannot parse or C++ reserves; the PEtab @@ -1791,7 +1792,7 @@ readPEtabTables <- function(yamlPath) { options = options, optionsSens = optionsSens, sparse = sparse, - deriv = deriv, derivMode = derivMode, + derivMode = derivMode, outdir = outdir) g <- .petab_build_observation_fn(obs_meta$obs, obs_meta$obs_trafo, sbml$reactions, @@ -1958,12 +1959,11 @@ readPEtabTables <- function(yamlPath) { #' Default `1`. #' @param modelname Base name of the generated files. Default `NULL`, the base #' name of the YAML file. -#' @param deriv Logical. If `FALSE`, the model is built without sensitivities, -#' which needs `backend = "cppDE"` or `"Sundials"`; the objective then has to -#' be called with `deriv = FALSE`. Default `TRUE`. -#' @param derivMode Derivative directions to build, passed to [odemodel()]: -#' `"forward"` (default), `"reverse"` or `c("forward", "reverse")`. -#' `"reverse"` needs `backend = "cppDE"` or `"Sundials"`. First order only. +#' @param derivMode Derivative directions to build, passed to [odemodel()], +#' [Y()] and [P()]: `"forward"` (default), `"reverse"`, +#' `c("forward", "reverse")` or `"none"`. `"reverse"` and `"none"` need +#' `backend = "cppDE"` or `"Sundials"`; with `"none"` the objective has to be +#' called with `deriv = FALSE`. First order only. #' @param options,optionsSens Lists passed to [Xs()]: the solver options of #' every solve and their overrides for the solves with sensitivities. #' Default `NULL`, the backend's defaults. @@ -2011,7 +2011,7 @@ readPEtabTables <- function(yamlPath) { #' @export importPEtab <- function(yamlPath, backend, compile = TRUE, cores = 1L, modelname = NULL, - deriv = TRUE, derivMode = "forward", + derivMode = "forward", options = NULL, optionsSens = NULL, sparse = NULL, stability = TRUE, outdir = .dmodOutdir()) { @@ -2025,6 +2025,8 @@ importPEtab <- function(yamlPath, backend, "\"Sundials\").") backend <- match.arg(backend, c("deSolve", "cppDE", "Sundials")) derivMode <- .matchDerivMode(derivMode, c("forward", "reverse")) + if (identical(derivMode, "none") && backend == "deSolve") + stop("derivMode = \"none\" needs backend = 'cppDE' or 'Sundials'.", call. = FALSE) if ("reverse" %in% derivMode && backend == "deSolve") stop("derivMode = \"reverse\" needs backend = 'cppDE' or 'Sundials'; ", "the deSolve backend goes forward only.", call. = FALSE) @@ -2120,7 +2122,6 @@ importPEtab <- function(yamlPath, backend, options = options, optionsSens = optionsSens, sparse = sparse, - deriv = deriv, derivMode = derivMode, cores = cores, outdir = outdir, diff --git a/R/constraintStability.R b/R/constraintStability.R index 44a13234..c08edfc9 100644 --- a/R/constraintStability.R +++ b/R/constraintStability.R @@ -36,7 +36,7 @@ #' with other terms keeps the value only, so the attribute is read from a call #' of the term itself. #' -#' @param pSS A parfn of [Pimpl()], built with `deriv2 = TRUE`. +#' @param pSS A parfn of [Pimpl()], built with `derivMode = "forward-forward"`. #' @param p The parfn whose output `pSS` reads, or `NULL` where `pSS` reads the #' parameters of the objective. #' @param weight \eqn{w}, the value of the term where the real part of an diff --git a/R/emResults.R b/R/emResults.R index 2bacb067..12f2e002 100644 --- a/R/emResults.R +++ b/R/emResults.R @@ -314,7 +314,7 @@ print.summary.em <- function(x, digits = 4, ...) { if (identical(x$seMethod, "none")) cat("No standard errors; confint(method = \"profile\") gives intervals\n") if (isTRUE(x$partialCurvature)) cat("Standard errors without the curvature of the prediction in the random effects within the volume term", - "(forward over reverse; deriv2 = TRUE gives the full one)\n") + "(forward over reverse; derivMode = \"forward-forward\" gives the full one)\n") if (!is.null(x$omega)) { cat("\nRandom effects:\n") om <- x$omega diff --git a/R/nlmeFocei.R b/R/nlmeFocei.R index df786c35..ec1b7e2d 100644 --- a/R/nlmeFocei.R +++ b/R/nlmeFocei.R @@ -285,7 +285,7 @@ .volumeFrames <- function(design, cn, pred, fixed, deriv2 = TRUE) { if (deriv2 && (is.null(attr(pred, "deriv")) || is.null(attr(pred, "deriv2")))) stop("em: the prediction of condition ", cn, " has no second derivatives; build the ", - "model with deriv2 = TRUE.", call. = FALSE) + "model with derivMode = \"forward-forward\".", call. = FALSE) if (is.null(design$errfn)) return(list(pred = pred, err = NULL)) inner <- getParameters(pred) fixedInner <- as.parvec(inner[attr(inner, "fixed")], deriv = FALSE, deriv2 = FALSE) @@ -300,7 +300,7 @@ for (cn in conds) if (deriv2 && (is.null(attr(preds[[cn]], "deriv")) || is.null(attr(preds[[cn]], "deriv2")))) stop("em: the prediction of condition ", cn, " has no second derivatives; build the ", - "model with deriv2 = TRUE.", call. = FALSE) + "model with derivMode = \"forward-forward\".", call. = FALSE) node <- if (!is.null(design$errfn)) .fnNode(design$errfn) if (is.null(node)) return(setNames(lapply(conds, function(cn) .volumeFrames(design, cn, preds[[cn]], fixed, deriv2)), conds)) @@ -361,7 +361,7 @@ if (is.null(e1)) return(rows) if (is.null(e2) && any(eta %in% dimnames(e1)[[3]])) stop("FOCEI with a random effect in the error model needs the second derivatives of the error model: ", - "build the error model with deriv2 = TRUE.", call. = FALSE) + "build the error model with derivMode = \"forward-forward\".", call. = FALSE) # rows whose observable has no error-model derivative keep zero derivatives ie <- te + (match(d$name, dimnames(e1)[[2]]) - 1L) * nrow(err) none <- is.na(ie) | !model @@ -759,11 +759,11 @@ .derivModeMessage(if (!is.null(control$derivMode)) paste0("FOCEI: the chain has no ", want, " second derivatives; it takes ", other, ".") else paste0("em: second derivatives forward over forward; models built with derivMode = ", - "c(\"forward\", \"reverse\", \"forward-reverse\") give them forward over reverse, which is faster.")) + "c(\"reverse\", \"forward-reverse\") give them forward over reverse, which is faster.")) return(other) } stop("FOCEI needs second derivatives of the prediction and the error model: build the models ", - "with derivMode = c(\"forward\", \"reverse\", \"forward-reverse\") or with deriv2 = TRUE, ", + "with derivMode = c(\"reverse\", \"forward-reverse\") or \"forward-forward\", ", "or set control = list(secondOrderCorrection = FALSE), which biases the estimates.", call. = FALSE) } diff --git a/R/odeClass.R b/R/odeClass.R index eaab7b25..227860a3 100644 --- a/R/odeClass.R +++ b/R/odeClass.R @@ -27,13 +27,13 @@ print.odemodel <- function(x, ...) { if (!is.null(extended)) { cat(" Sens1: ", as.character(extended), "\n", sep = "") } else { - cat(" Sens1: not compiled (deriv = FALSE)\n", sep = "") + cat(" Sens1: not built (derivMode without \"forward\")\n", sep = "") } if (isCppDE) { if (!is.null(extended2)) { cat(" Sens2: ", as.character(extended2), "\n", sep = "") } else { - cat(" Sens2: not compiled (deriv2 = FALSE)\n", sep = "") + cat(" Sens2: not built (derivMode without \"forward-forward\")\n", sep = "") } if (!is.null(reversed)) cat(" Adjoint: ", as.character(reversed), "\n", sep = "") @@ -68,23 +68,20 @@ print.odemodel <- function(x, ...) { #' @param f Named character vector, [eqnvec] or [eqnlist] with the right-hand #' sides; the names are the states. The functions and operators an equation #' may use are listed in [cppDE::expressions]. -#' @param deriv logical, build first-order sensitivities. Default `TRUE`. -#' `FALSE` builds the states alone, for [Xf()], and `derivMode` has no -#' effect. -#' @param deriv2 logical, build second-order sensitivities. Default `FALSE`. -#' `TRUE` is the same as adding `"forward-forward"` to `derivMode`, needs -#' `backend = "cppDE"` and implies `deriv = TRUE`. #' @param derivMode character, the derivative directions to build, one or #' more of: -#' * `"forward"` (default): sensitivity equations. `deriv = TRUE` builds them -#' also when `derivMode` leaves out `"forward"`. +#' * `"forward"` (default): first-order sensitivities. #' * `"reverse"`: adjoint gradient, needed for `obj(..., sweep = "reverse")`. #' Not available on `backend = "deSolve"`. -#' * `"forward-forward"`: second-order sensitivities. +#' * `"forward-forward"`: second-order sensitivities, needed for +#' `deriv2 = TRUE` in a call. `backend = "cppDE"` only. #' * `"forward-reverse"`: adjoint Hessian, needed for #' `obj(..., sweep = "reverse", deriv2 = TRUE)`. `backend = "cppDE"` only. +#' * `"none"`: the states alone, for [Xf()]. #' -#' Each direction is compiled separately. +#' Each direction is compiled separately. The two second-order directions +#' build `"forward"` as well. A call that asks for a derivative not built is +#' an error. #' @param forcings character, the names of the forcings in `f`. Default #' `NULL`. Their data are given to [Xs()] or [Xf()]. #' @param events an [eventlist], or a `data.frame` accepted by @@ -134,40 +131,29 @@ print.odemodel <- function(x, ...) { #' #' @example inst/examples/odemodel.R #' @export -odemodel <- function(f, deriv = TRUE, deriv2 = FALSE, derivMode = "forward", +odemodel <- function(f, derivMode = "forward", forcings=NULL, events = NULL, fixed = NULL, modelname = "odemodel", backend = c("cppDE", "Sundials", "deSolve"), verbose = FALSE, outdir = .dmodOutdir(), ...) { f <- as.eqnvec(f) backend <- match.arg(backend) - derivMode <- .matchDerivMode(derivMode, c("forward", "reverse", - "forward-forward", "forward-reverse")) - # without derivatives there is no direction to build - if (!deriv && !deriv2) derivMode <- "forward" + dots <- list(...) + .rejectBuildDeriv("odemodel", dots) + derivMode <- .matchDerivMode(derivMode) + deriv <- "forward" %in% derivMode + deriv2 <- "forward-forward" %in% derivMode reverse <- "reverse" %in% derivMode reverse2 <- "forward-reverse" %in% derivMode - # The two spellings of forward over forward name the same build product. - if ("forward-forward" %in% derivMode) deriv2 <- TRUE if (reverse && backend == "deSolve") stop("derivMode = \"reverse\" needs backend = 'cppDE' or 'Sundials'.", call. = FALSE) if (reverse2 && backend != "cppDE") stop("derivMode = \"forward-reverse\" needs backend = 'cppDE'.", call. = FALSE) - - if (deriv2 && !deriv) { - warning("`deriv2 = TRUE` implies `deriv = TRUE`. Setting deriv = TRUE.", - call. = FALSE) - deriv <- TRUE - } - - dots <- list(...) - - if (deriv2 && backend == "deSolve") - stop("Second-order sensitivities require backend = 'cppDE'.") - if (deriv2 && backend == "Sundials") - stop("Second-order sensitivities are not available with CVODE; use backend = 'cppDE'.") + if (deriv2 && backend != "cppDE") + stop("derivMode = \"forward-forward\" needs backend = 'cppDE'.", + call. = FALSE) # cOde::funC has no outdir and always writes to the working directory, so a # non-default outdir would be silently ignored under the deSolve backend. @@ -334,5 +320,6 @@ odemodel <- function(f, deriv = TRUE, deriv2 = FALSE, derivMode = "forward", attr(out, "compileInfo") <- .collectCompileInfo(out$func, out$extended, out$extended2, out$reversed, out$reversed2) + attr(out, "derivMode") <- derivMode return(out) } diff --git a/R/parameters.R b/R/parameters.R index e2ad82b7..3f222d93 100644 --- a/R/parameters.R +++ b/R/parameters.R @@ -22,9 +22,10 @@ #' @param cores Number of parallel jobs generating and compiling the sources of #' a list; on Windows the sources are generated one after the other. `NULL` #' (default) uses [detectFreeCores()]. -#' @param deriv,deriv2 Build first and second derivatives, default `TRUE` and -#' `FALSE`. `deriv2` requires `deriv = TRUE`. -#' @param ... Further arguments of [Pexpl()] (`attachInput`, `derivMode`, +#' @param derivMode The derivatives to build, one or more of `"forward"` +#' (default), `"reverse"`, `"forward-forward"` and `"forward-reverse"`, or +#' `"none"`, passed to [Pexpl()] or [Pimpl()]. +#' @param ... Further arguments of [Pexpl()] (`attachInput`, #' `outdir`) or [Pimpl()] (`forcings`, `keepRoot`, `flow`, `controlsPTC`, #' `outdir`), as `method` selects. #' @@ -38,11 +39,11 @@ P <- function(trafo = NULL, parameters = NULL, condition = NULL, compile = FALSE, modelname = NULL, method = NULL, cores = NULL, verbose = FALSE, - deriv = TRUE, deriv2 = FALSE, ...) { + derivMode = "forward", ...) { + .rejectBuildDeriv("P", list(...)) if (is.null(trafo)) return() - if (isTRUE(deriv2) && !isTRUE(deriv)) - stop("P(deriv2 = TRUE) requires deriv = TRUE.", call. = FALSE) + derivMode <- .matchDerivMode(derivMode) if (!is.list(trafo) || inherits(trafo, "eqnlist") || inherits(trafo, "eqnvec")) { trafo_list <- list(trafo); names(trafo_list) <- condition @@ -61,10 +62,10 @@ P <- function(trafo = NULL, parameters = NULL, condition = NULL, switch(m, explicit = Pexpl(as.eqnvec(tr), parameters = parameters, condition = cond, compile = FALSE, modelname = modelname, verbose = verbose, - deriv = deriv, deriv2 = deriv2, ...), + derivMode = derivMode, ...), implicit = Pimpl(trafo = tr, parameters = parameters, condition = cond, compile = FALSE, modelname = modelname, verbose = verbose, - deriv = deriv, deriv2 = deriv2, ...)) + derivMode = derivMode, ...)) }, mc.cores = if (.Platform$OS.type == "windows") 1L else cores)) if (compile) compile(result, cores = cores, output = modelname, verbose = verbose) @@ -79,9 +80,8 @@ P <- function(trafo = NULL, parameters = NULL, condition = NULL, .Pexpl_p2p <- function(st, pars, fixed = NULL, deriv = TRUE, deriv2 = FALSE, .ad_out = NULL, attach.input = FALSE) { - if (deriv2 && !st$emit_d2) - stop("Pexpl was built with deriv2 = FALSE; rebuild with deriv2 = TRUE.", call. = FALSE) - if (!st$emit_d1) deriv <- FALSE + if (deriv2 && !st$emit_d2) .notBuilt("Pexpl()", "forward-forward") + if (deriv && !st$use_ad) .notBuilt("Pexpl()", "forward") if (deriv2 && !deriv) deriv <- TRUE p <- c(pars, fixed) @@ -300,9 +300,7 @@ P <- function(trafo = NULL, parameters = NULL, condition = NULL, # attach.input the passed-through outer parameters add their own cotangent. .Pexpl_vjp <- function(st, pars, fixed = NULL, cotangent, attach.input = FALSE) { if (is.null(st$vjp)) - stop("Pexpl(): the reverse mode needs a vector-Jacobian product; rebuild ", - "with derivMode = c(\"forward\", \"reverse\") and compile = TRUE.", - call. = FALSE) + .notBuilt("Pexpl()", "reverse") w <- .asCtPars(cotangent) K <- .ctK(w) b <- .ctBlocks(K) @@ -369,14 +367,15 @@ P <- function(trafo = NULL, parameters = NULL, condition = NULL, #' @param modelname Base name of the generated files, default `NULL`, which #' is `"expl_parfn"`, followed by `_`. #' @param verbose Logical. Print the compiler output, default `FALSE`. -#' @param deriv,deriv2 Build the first derivatives, `attr(, "deriv")`, -#' `[inner, outer]`, and the second, `attr(, "deriv2")`, -#' `[inner, outer, outer]`. Default `TRUE` and `FALSE`; `deriv2` needs -#' `deriv = TRUE`. -#' @param derivMode Which derivative code to build, any of `"forward"` -#' (default), `"reverse"` and `"forward-reverse"`. `"reverse"` is needed for -#' `sweep = "reverse"`, `"forward-reverse"` for `sweep = "reverse"` with -#' `deriv2 = TRUE`. +#' @param derivMode The derivatives to build, one or more of `"forward"` +#' (default), `"reverse"`, `"forward-forward"` and `"forward-reverse"`, or +#' `"none"`, as in [odemodel()]. `"forward"` builds the Jacobian, +#' `attr(, "deriv")`, `[inner, outer]`, `"forward-forward"` the second +#' derivatives, `attr(, "deriv2")`, `[inner, outer, outer]`; `"reverse"` is +#' needed for `sweep = "reverse"`, `"forward-reverse"` for +#' `sweep = "reverse"` with `deriv2 = TRUE`. The second-order directions +#' build `"forward"` as well. A call that asks for a derivative not built is +#' an error. #' @param outdir Directory for the generated source and shared object, #' default `getOption("dMod2.outdir")`, else the working directory. #' @@ -389,15 +388,11 @@ P <- function(trafo = NULL, parameters = NULL, condition = NULL, #' @export Pexpl <- function(trafo, parameters = NULL, attachInput = FALSE, condition = NULL, compile = FALSE, modelname = NULL, verbose = FALSE, - deriv = TRUE, deriv2 = FALSE, - derivMode = "forward", - outdir = .dmodOutdir()) { + derivMode = "forward", outdir = .dmodOutdir()) { - derivMode <- .matchDerivMode(derivMode, c("forward", "reverse", "forward-reverse")) - emit_d1 <- isTRUE(deriv) - emit_d2 <- isTRUE(deriv2) - if (emit_d2 && !emit_d1) - stop("Pexpl(deriv2 = TRUE) requires deriv = TRUE.", call. = FALSE) + derivMode <- .matchDerivMode(derivMode) + emit_d1 <- !identical(derivMode, "none") + emit_d2 <- "forward-forward" %in% derivMode if (is.null(parameters)) { parameters <- getSymbols(trafo) @@ -414,7 +409,7 @@ Pexpl <- function(trafo, parameters = NULL, attachInput = FALSE, condition = NUL PEval <- suppressWarnings(cppDE::cppFUN( unclass(trafo), variables = NULL, parameters = parameters, fixed = NULL, compile = compile, modelname = modelname, outdir = outdir, - verbose = verbose, convenient = FALSE, derivMode = derivMode, + verbose = verbose, convenient = FALSE, derivMode = .cppFUNMode(derivMode), deriv = emit_d1, deriv2 = emit_d2)) fun <- PEval$func; jac <- PEval$jac; hess <- PEval$hess; evaluate <- PEval$evaluate @@ -807,8 +802,12 @@ Pexpl <- function(trafo, parameters = NULL, attachInput = FALSE, condition = NUL #' @param modelname Base name of the generated files, default `NULL`, which #' is `"impl_parfn"`, followed by `_`. #' @param verbose Logical. Print the compiler output, default `FALSE`. -#' @param deriv,deriv2 Build first and second derivatives, default `TRUE` and -#' `FALSE`. `deriv2` requires `deriv = TRUE`. +#' @param derivMode The derivatives to build, one or more of `"forward"` +#' (default), `"reverse"`, `"forward-forward"` and `"forward-reverse"`, or +#' `"none"`, as in [odemodel()]. The reverse directions come from the +#' forward ones: `"reverse"` builds the Jacobian, `"forward-reverse"` the +#' second derivatives, as `"forward-forward"` does. A call that asks for a +#' derivative not built is an error. #' @param controlsPTC Named list of solver controls; an entry not given keeps #' the default, an unknown entry is an error: #' \describe{ @@ -867,14 +866,13 @@ Pexpl <- function(trafo, parameters = NULL, attachInput = FALSE, condition = NUL Pimpl <- function(trafo, parameters = NULL, forcings = NULL, condition = NULL, keepRoot = TRUE, flow = inherits(trafo, "eqnlist"), compile = FALSE, modelname = NULL, verbose = FALSE, - deriv = TRUE, deriv2 = FALSE, controlsPTC = list(), + derivMode = "forward", controlsPTC = list(), outdir = .dmodOutdir()) { flow <- isTRUE(flow) - emit_d1 <- isTRUE(deriv) - emit_d2 <- isTRUE(deriv2) - if (emit_d2 && !emit_d1) - stop("Pimpl(deriv2 = TRUE) requires deriv = TRUE.", call. = FALSE) + derivMode <- .matchDerivMode(derivMode) + emit_d1 <- !identical(derivMode, "none") + emit_d2 <- any(c("forward-forward", "forward-reverse") %in% derivMode) .pimplPTC(controlsPTC) norm <- .normalize_ss_inputs(trafo, parameters, forcings) @@ -998,9 +996,8 @@ Pimpl <- function(trafo, parameters = NULL, forcings = NULL, condition = NULL, } p2p <- function(pars, fixed = NULL, deriv = TRUE, deriv2 = FALSE, condition = NULL) { - if (deriv2 && !emit_d2) - stop("Pimpl was built with deriv2 = FALSE; rebuild with deriv2 = TRUE.", call. = FALSE) - if (!emit_d1) deriv <- FALSE + if (deriv2 && !emit_d2) .notBuilt("Pimpl()", "forward-forward") + if (deriv && !emit_d1) .notBuilt("Pimpl()", "forward") if (deriv2 && !deriv) deriv <- TRUE p <- pars diff --git a/R/prediction.R b/R/prediction.R index 32cc6918..47a40c72 100644 --- a/R/prediction.R +++ b/R/prediction.R @@ -26,10 +26,11 @@ #' * `fixed`: named numeric vector of parameters that enter the evaluation #' without derivatives. Default `NULL`. #' * `deriv`: `TRUE` (default) returns first derivatives with respect to -#' `pars`. +#' `pars`. Every function of the chain has to be built with +#' `derivMode = "forward"`, see [odemodel()], [Y()] and [P()]. #' * `deriv2`: `TRUE` returns second derivatives as well. Default `FALSE`. -#' Every function of the chain has to be built for them, see the arguments -#' `deriv2` and `derivMode` of [odemodel()], [Y()] and [P()]. +#' Every function of the chain has to be built with +#' `derivMode = "forward-forward"`. #' * `hessian`: objective functions only, see the table below. Default #' `NULL`. #' * `sweep`: objective functions only. `"forward"` (default) propagates the @@ -193,7 +194,7 @@ NULL #' `attr(, "deriv")`, `[time, state, parameter]`, when `deriv = TRUE`, and #' the second-order sensitivities in `attr(, "deriv2")`, #' `[time, state, parameter, parameter]`, when `deriv2 = TRUE` (`cppDE` -#' backend, model built with `deriv2 = TRUE`). +#' backend, model built with `derivMode = "forward-forward"`). #' #' @inheritSection dModfn Calling a dMod function #' @seealso [Xf()] for predictions without sensitivities, [controls()], @@ -240,7 +241,7 @@ Xs.deSolve <- function(odemodel, forcings = NULL, events = NULL, names = NULL, c func <- odemodel$func extended <- odemodel$extended if (is.null(extended)) - stop("Xs: the odemodel is built without sensitivities; use Xf() or odemodel(deriv = TRUE).", + stop("Xs: the odemodel was built without derivMode = \"forward\"; use Xf() or rebuild.", call. = FALSE) myforcings <- forcings @@ -483,7 +484,6 @@ Xs.cppDE <- function(odemodel, forcings = NULL, events = NULL, names = NULL, con extended2 <- odemodel$extended2 reversed <- odemodel$reversed reversed2 <- odemodel$reversed2 - if (is.null(extended)) warning("Element 'extended' empty. ODE model does not contain sensitivities.") # Extract metadata paramNames <- c(attr(func, "variables"), attr(func, "parameters")) @@ -640,14 +640,14 @@ Xs.cppDE <- function(odemodel, forcings = NULL, events = NULL, names = NULL, con # sensErrCon of a forward solve. sensSec <- function() isTRUE(sensOpts()$sensErrCon) - # Second order forward exists only where it was built, and only on cppDE. + # Each derivative order exists only where odemodel() built it. pickModel <- function(deriv, deriv2) { if (!deriv) return(func) + if (is.null(extended)) .notBuilt("Xs: the odemodel", "forward") if (!deriv2) return(extended) if (is.null(extended2)) - stop("an exact Hessian forward needs the forward-over-forward object; ", - "rebuild via odemodel(..., deriv2 = TRUE), which needs ", - "backend = \"cppDE\". Backwards it is ", + stop("Xs: the odemodel was built without derivMode = \"forward-forward\", which an ", + "exact Hessian forward needs (backend = \"cppDE\"). Backwards it is ", "derivMode = \"forward-reverse\" instead.", call. = FALSE) extended2 } @@ -655,8 +655,7 @@ Xs.cppDE <- function(odemodel, forcings = NULL, events = NULL, names = NULL, con P2X <- function(times, pars, fixed = NULL, deriv = TRUE, deriv2 = FALSE, keepStore = FALSE) { - if (deriv2 && !has_deriv2) - stop("Xs.cppDE: model was compiled without deriv2; rebuild via odemodel(..., deriv2 = TRUE).") + if (deriv || deriv2) pickModel(TRUE, deriv2) if (deriv2 && !deriv) deriv <- TRUE forcs <- forcsOf(controls$forcings) @@ -713,8 +712,7 @@ Xs.cppDE <- function(odemodel, forcings = NULL, events = NULL, names = NULL, con P2Xbatch <- function(times, parsList, fixedList, deriv, deriv2, cores, keepStore = FALSE) { - if (deriv2 && !has_deriv2) - stop("Xs.cppDE: model was compiled without deriv2; rebuild via odemodel(..., deriv2 = TRUE).") + if (deriv || deriv2) pickModel(TRUE, deriv2) if (deriv2 && !deriv) deriv <- TRUE forcs <- forcsOf(controls$forcings) @@ -1393,21 +1391,20 @@ Xd <- function(data, condition = NULL) { #' @param cores Number of parallel jobs used to generate and compile the sources #' when `g` is a list, on Windows only to compile them; `NULL` auto-detects. #' Ignored for a single observation function, which is one source either way. -#' @param derivMode Which derivative code to build, any of `"forward"` -#' (default), `"reverse"` and `"forward-reverse"`. -#' * `"forward"`: the Jacobian; without it the function returns no `deriv` -#' attribute. -#' * `"reverse"`: needed for `sweep = "reverse"`. +#' @param derivMode The derivatives to build, one or more of `"forward"` +#' (default), `"reverse"`, `"forward-forward"` and `"forward-reverse"`, or +#' `"none"`, as in [odemodel()]. +#' * `"forward"`: the Jacobian, `attr(, "deriv")`, +#' `[time, observable, parameter]`. +#' * `"reverse"`: the vector-Jacobian product of `sweep = "reverse"`. +#' * `"forward-forward"`: the second derivatives, `attr(, "deriv2")`, +#' `[time, observable, parameter, parameter]`, for `deriv2 = TRUE`. #' * `"forward-reverse"`: needed for `sweep = "reverse"` with #' `deriv2 = TRUE`. -#' @param deriv Logical. If `TRUE` (default), build the first derivatives, -#' returned as `attr(, "deriv")`, `[time, observable, parameter]`, when the -#' call has `deriv = TRUE` and `derivMode` contains `"forward"`. `FALSE` -#' returns none, whatever the call asks. -#' @param deriv2 Logical. If `TRUE`, build the second derivatives, returned -#' as `attr(, "deriv2")`, `[time, observable, parameter, parameter]`, when -#' the call has `deriv2 = TRUE`; on a function built without them that call -#' is an error. Requires `deriv = TRUE`. Default `FALSE`. +#' * `"none"`: values only. +#' +#' The second-order directions build `"forward"` as well. A call that asks +#' for a derivative not built is an error. #' @param outdir Character. Directory for the generated C++ source and the #' shared object, default `getOption("dMod2.outdir")`, else the working #' directory. @@ -1427,10 +1424,9 @@ Xd <- function(data, condition = NULL) { Y <- function(g, f = NULL, states = NULL, parameters = NULL, condition = NULL, attachInput = FALSE, compile = FALSE, modelname = NULL, verbose = FALSE, - cores = NULL, deriv = TRUE, deriv2 = FALSE, - derivMode = "forward", outdir = .dmodOutdir()) { + cores = NULL, derivMode = "forward", outdir = .dmodOutdir()) { - derivMode <- .matchDerivMode(derivMode, c("forward", "reverse", "forward-reverse")) + derivMode <- .matchDerivMode(derivMode) # A named list of observable sets builds one obsfn per condition, generated # in parallel and compiled once, the way `P()` handles a trafo list. @@ -1443,17 +1439,15 @@ Y <- function(g, f = NULL, states = NULL, parameters = NULL, Y(g[[i]], f = f, states = states, parameters = parameters, condition = names(g)[i], attachInput = attachInput, compile = FALSE, modelname = modelname, verbose = verbose, - deriv = deriv, deriv2 = deriv2, derivMode = derivMode, outdir = outdir), + derivMode = derivMode, outdir = outdir), mc.cores = if (.Platform$OS.type == "windows") 1L else cores)) if (compile) compile(result, cores = cores, output = modelname, verbose = verbose) return(result) } - emit_d1 <- isTRUE(deriv) - emit_d2 <- isTRUE(deriv2) - if (emit_d2 && !emit_d1) - stop("Y(deriv2 = TRUE) requires deriv = TRUE.", call. = FALSE) + emit_d1 <- !identical(derivMode, "none") + emit_d2 <- "forward-forward" %in% derivMode if (is.null(f) && is.null(states) && is.null(parameters)) stop("Not all three arguments f, states and parameters can be NULL") @@ -1503,7 +1497,7 @@ Y <- function(g, f = NULL, states = NULL, parameters = NULL, outdir = outdir, verbose = verbose, convenient = FALSE, - derivMode = derivMode, + derivMode = .cppFUNMode(derivMode), deriv = emit_d1, deriv2 = emit_d2 ) @@ -1531,9 +1525,8 @@ Y <- function(g, f = NULL, states = NULL, parameters = NULL, .ad_out = NULL, .fixedObs = NULL) { needStates(out) - if (deriv2 && !emit_d2) - stop("Y() was built with deriv2 = FALSE; rebuild Y() with deriv2 = TRUE.", call. = FALSE) - if (!emit_d1) deriv <- FALSE + if (deriv2 && !emit_d2) .notBuilt("Y()", "forward-forward") + if (deriv && !use_ad) .notBuilt("Y()", "forward") if (deriv2 && !deriv) deriv <- TRUE attachInput <- controls$attachInput @@ -1677,9 +1670,7 @@ Y <- function(g, f = NULL, states = NULL, parameters = NULL, needStates(out) w <- .asCtOut(cotangent) if (is.null(gEval$vjp)) - stop("Y(): the reverse mode needs a vector-Jacobian product; rebuild ", - "with Y(..., derivMode = c(\"forward\", \"reverse\"), ", - "compile = TRUE).", call. = FALSE) + .notBuilt("Y()", "reverse") params <- c(unclass(pars), unclass(fixed)) fixedObsParams <- .intersectU(c(attr(pars, "fixed"), names(fixed)), obsParams) diff --git a/R/reverse.R b/R/reverse.R index 17ab4a59..5cf52b84 100644 --- a/R/reverse.R +++ b/R/reverse.R @@ -59,7 +59,7 @@ if (b$D == 0L) return(u) if (is.null(res$curvature)) stop("a second-order cotangent needs a model built with ", - "derivMode = \"forward-reverse\"", call. = FALSE) + "derivMode = \"forward-reverse\".", call. = FALSE) for (s in seq_len(b$S)) u[, b$rest[, s]] <- matrix(res$curvature[, seq_len(b$D), s], nrow = nrow(u)) u @@ -143,12 +143,11 @@ # second order and needs the forward-over-reverse object. .requireReverse <- function(has_reverse, has_reverse2, K) { if (K > 1L && !has_reverse2) - stop("the reverse mode propagates directions here, which needs the ", - "forward-over-reverse object; rebuild via odemodel(..., derivMode = ", - "c(\"forward\", \"forward-reverse\")).", call. = FALSE) + stop("Xs: the odemodel was built without derivMode = \"forward-reverse\", which a ", + "reverse sweep with deriv2 = TRUE needs.", call. = FALSE) if (K == 1L && !has_reverse) - stop("the model has no reverse object; rebuild via odemodel(..., ", - "derivMode = c(\"forward\", \"reverse\")).", call. = FALSE) + stop("Xs: the odemodel was built without derivMode = \"reverse\", which a reverse ", + "sweep needs.", call. = FALSE) invisible(NULL) } @@ -301,7 +300,7 @@ H <- attr(v, "deriv2") if (is.null(H)) stop("a second-order cotangent needs this transformation's own second ", - "derivatives, and it returned none; rebuild it with deriv2 = TRUE.", + "derivatives, and it returned none; build it with derivMode = \"forward-reverse\".", call. = FALSE) # w' H, the node's curvature seen through each seed, times the # tangents that arrived: the second half of d/dv (J' w). diff --git a/R/trust.R b/R/trust.R index 49921f7c..d593aa44 100644 --- a/R/trust.R +++ b/R/trust.R @@ -231,7 +231,7 @@ #' \code{"identity"} the identity matrix, after which the objective is #' asked for gradients only until a reseed; \code{"exact"} the true #' Hessian at \code{parinit}, then gradients only. \code{"exact"} needs -#' \code{deriv2}, see \code{derivMode} in [odemodel()]. In a first phase +#' \code{deriv2 = TRUE} in a call, see \code{derivMode} in [odemodel()]. In a first phase #' of source \code{"gn"}, \code{"exact"} makes the first step use the #' exact Hessian at \code{parinit}.} #' \item{\code{hessianReseed}}{\code{"never"} (default): a stalled diff --git a/R/utils.R b/R/utils.R index 73a76d28..99c82cb4 100644 --- a/R/utils.R +++ b/R/utils.R @@ -57,20 +57,51 @@ attrs <- function(x, which = NULL, keep = TRUE) { -# Match a `derivMode` argument against what an entry point supports. Mirrors -# cppDE's helper of the same shape: "forward" and "reverse" are separate build -# products and combine. -.matchDerivMode <- function(x, choices) { +# The derivative directions a constructor builds, in the order of `choices`. +# "none" stands alone; a second-order direction adds "forward", which it runs on. +.matchDerivMode <- function(x, choices = .derivModes) { if ("symbolic" %in% x) stop('derivMode = "symbolic" is gone: every derivative is generated by ', 'AD at code-generation time. Use "forward".', call. = FALSE) - x <- unique(match.arg(x, choices, several.ok = TRUE)) - if (!length(x)) - stop("'derivMode' must name at least one of ", + choices <- c("none", choices) + if (is.logical(x)) + stop("derivMode is logical: `deriv` and `deriv2` are not build arguments; derivMode selects ", + "the derivatives to build, \"none\" for none, \"forward-forward\" for second order.", + call. = FALSE) + if (!is.character(x) || !length(x) || anyNA(x)) + stop("'derivMode' must name one or more of ", paste0('"', choices, '"', collapse = ", "), call. = FALSE) + x <- unique(match.arg(x, choices, several.ok = TRUE)) + if ("none" %in% x && length(x) > 1L) + stop('derivMode = "none" builds no derivatives and combines with no other ', + "direction.", call. = FALSE) + if (any(c("forward-forward", "forward-reverse") %in% x)) x <- c(x, "forward") choices[choices %in% x] } +.derivModes <- c("forward", "reverse", "forward-forward", "forward-reverse") + +# `deriv` and `deriv2` passed to a constructor that has `...`: an error that names derivMode. +.rejectBuildDeriv <- function(who, dots) { + old <- intersect(c("deriv", "deriv2"), names(dots)) + if (!length(old)) return(invisible(NULL)) + stop(who, "(): ", paste0("`", old, "`", collapse = " and "), + if (length(old) > 1L) " are not arguments; " else " is not an argument; ", + "derivMode selects the derivatives to build, \"none\" for none, ", + "\"forward-forward\" for second order.", call. = FALSE) +} + +# The directions of cppFUN(), which builds forward over forward as `deriv2`. +.cppFUNMode <- function(derivMode) { + m <- .setdiff(derivMode, c("none", "forward-forward")) + if (length(m)) m else "forward" +} + +# The error of a call that asks for a derivative direction the object was built without. +.notBuilt <- function(who, mode) + stop(who, " was built without derivMode = \"", mode, "\"; this call needs it.", + call. = FALSE) + # x with empty or missing names replaced by the prefix and the position .fillNames <- function(x, prefix) { diff --git a/bench/gradient/reverseAD.R b/bench/gradient/reverseAD.R index 488aa9d0..9a6c8625 100644 --- a/bench/gradient/reverseAD.R +++ b/bench/gradient/reverseAD.R @@ -20,7 +20,7 @@ reactions <- eqnlist() |> # 1. The solver alone --------------------------------------------------------- # One value solve with checkpoints, then one backward sweep from a cotangent on # the prediction to one on the model parameters; the oracle is w' S from forward. -model <- odemodel(reactions, modelname = "rev_ode", deriv = TRUE, deriv2 = TRUE, +model <- odemodel(reactions, modelname = "rev_ode", derivMode = c("forward", "reverse", "forward-forward", "forward-reverse"), outdir = .outdir, compile = TRUE) @@ -47,11 +47,11 @@ cat("1. solver max |difference| =", # 2. The whole chain, g * x * p ----------------------------------------------- # normL2 seeds the residual cotangent and pushes it back through g, x and p in # one pass. -g <- Y(c(obsA = "s*A", obsB = "s*B"), reactions, compile = TRUE, deriv2 = TRUE, +g <- Y(c(obsA = "s*A", obsB = "s*B"), reactions, compile = TRUE, derivMode = "forward-forward", modelname = "rev_obs", outdir = .outdir) p <- P(c(A = "exp(logA)", B = "0", k1 = "exp(logk1)", k2 = "exp(logk2)", s = "exp(logs)"), - condition = "C1", compile = TRUE, deriv2 = TRUE, + condition = "C1", compile = TRUE, derivMode = "forward-forward", modelname = "rev_p", outdir = .outdir) pars <- c(logA = log(2), logk1 = log(0.6), logk2 = log(0.3), logs = log(1.5)) @@ -155,7 +155,7 @@ cat("\n5. the gap tracks the tolerance over eight decades, so it is the\n", # applied it; the reverse pass only reads back which events fired and when. ev <- eventlist(var = "A", time = "t_dose", value = "d_amt", method = "add") model_ev <- odemodel(reactions, events = ev, modelname = "rev_ev", - deriv = TRUE, derivMode = c("forward", "reverse"), outdir = .outdir, + derivMode = c("forward", "reverse"), outdir = .outdir, compile = TRUE) x_ev <- Xs(model_ev, options = tight) p_ev <- P(c(A = "exp(logA)", B = "0", k1 = "exp(logk1)", k2 = "exp(logk2)", @@ -186,7 +186,7 @@ cat(" with", length(pars), "parameters. The ratio is what falls as they grow.\ # 8. The exact Hessian -------------------------------------------------------- # `sweep` picks forward over forward or forward over reverse; the model needs the -# matching `derivMode` entries, and g and p need `deriv2 = TRUE`. +# matching `derivMode` entries, g and p need "forward-forward". hf <- obj(pars, deriv2 = TRUE) hr <- obj(pars, sweep = "reverse", deriv2 = TRUE) cat(sprintf("8. exact Hessian forward vs reverse: max|difference| %.2e\n", diff --git a/bench/hessian/hessianSourceSettings.R b/bench/hessian/hessianSourceSettings.R index 79a99ec6..e1382a59 100644 --- a/bench/hessian/hessianSourceSettings.R +++ b/bench/hessian/hessianSourceSettings.R @@ -50,7 +50,7 @@ hessianSourceSettings <- list( # a descent on gradients that cost a fraction of a forward one. `sweep` rides # in the same list and reaches the objective through trust()'s dots. Needs a # model built with derivMode = c("forward", "forward-reverse") and an - # observation and transformation chain built with deriv2 = TRUE. + # observation and transformation chain built with derivMode = "forward-forward". sr1_ex_rev = list(hessianMethod = "sr1", sweep = "reverse", qnControl = list(hessianInit = "exact")), # The same, and a stalled phase fetches a fresh curvature rather than ending. diff --git a/bench/nlme/derivMode.R b/bench/nlme/derivMode.R index ab4e566a..eee671b9 100644 --- a/bench/nlme/derivMode.R +++ b/bench/nlme/derivMode.R @@ -8,7 +8,7 @@ options(dMod2.outdir = file.path(tempdir(), "derivModeBench")) dir.create(getOption("dMod2.outdir"), showWarnings = FALSE) reps <- 3 modes <- c("forward-forward", "forward-reverse") -dm <- c("forward", "reverse", "forward-reverse") +dm <- c("forward", "reverse", "forward-forward", "forward-reverse") ## Theophylline --------------------------------------------------------------------------- data(Theoph, package = "datasets") @@ -19,9 +19,9 @@ reactions <- eqnlist() reactions <- addReaction(reactions, "Ag", "", "Ka * Ag", "absorption") reactions <- addReaction(reactions, "", "Cc", "Ka * Ag / V", "appearance") reactions <- addReaction(reactions, "Cc", "", "Cl/V * Cc", "elimination") -x <- Xs(odemodel(reactions, modelname = "dmTheoph", compile = FALSE, deriv2 = TRUE, derivMode = dm)) -g <- Y(c(y = "Cc"), x, modelname = "dmTheoph_obs", compile = FALSE, deriv2 = TRUE, derivMode = dm) -err <- Y(c(y = "sigma_add"), g, attachInput = FALSE, compile = FALSE, deriv2 = TRUE, derivMode = dm, +x <- Xs(odemodel(reactions, modelname = "dmTheoph", compile = FALSE, derivMode = dm)) +g <- Y(c(y = "Cc"), x, modelname = "dmTheoph_obs", compile = FALSE, derivMode = dm) +err <- Y(c(y = "sigma_add"), g, attachInput = FALSE, compile = FALSE, derivMode = dm, modelname = "dmTheoph_err") subjects <- sort(unique(Theoph$Subject)) covariates <- data.frame(ID = subjects, dose = tapply(Theoph$Dose * Theoph$Wt, Theoph$Subject, `[`, 1)[subjects], @@ -31,7 +31,7 @@ trafo <- insert(trafo, "Ag <- dose", dose = dose) trafo <- insert(trafo, "Cc <- 0") trafo <- insert(trafo, "x <- exp(x)", x = c("Ka", "V", "Cl", "sigma_add")) trafo <- insert(trafo, Ka + V + Cl ~ 1 + (1 | ID)) -p <- P(trafo, method = "explicit", compile = FALSE, modelname = "dmTheoph_p", deriv2 = TRUE, derivMode = dm) +p <- P(trafo, method = "explicit", compile = FALSE, modelname = "dmTheoph_p", derivMode = dm) compile(x, g, err, p, output = "dmTheoph") obj <- normL2(data, g * x * p, errmodel = err) init <- c(Ka = 0, V = 3, Cl = 0.7, sigma_add = log(0.5)) @@ -64,15 +64,15 @@ stat5 <- eqnlist() |> addReaction("nucpApB", "STAT5A + STAT5B", "k_exp_hetero*nucpApB", "export AB", compartment = "nuc") |> addReaction("nucpBpB", "2*STAT5B", "k_exp_homo*nucpBpB", "export BB", compartment = "nuc") |> setCompartmentVolume(cyt = "1.4") -sx <- Xs(odemodel(stat5, modelname = "dmStat5", compile = FALSE, deriv2 = TRUE, derivMode = dm), +sx <- Xs(odemodel(stat5, modelname = "dmStat5", compile = FALSE, derivMode = dm), options = list(atol = 1e-8, rtol = 1e-6, maxattempts = 100L, maxsteps = 1e6)) obs5 <- eqnvec( pSTAT5A_rel = "(100*pApB + 200*pApA*specC17)/(pApB + STAT5A*specC17 + 2*pApA*specC17)", pSTAT5B_rel = "-(100*pApB - 200*pBpB*(specC17 - 1))/((STAT5B*(specC17 - 1) - pApB) + 2*pBpB*(specC17 - 1))", rSTAT5A_rel = "(100*pApB + 100*STAT5A*specC17 + 200*pApA*specC17)/(2*pApB + STAT5A*specC17 + 2*pApA*specC17 - STAT5B*(specC17 - 1) - 2*pBpB*(specC17 - 1))") -sg <- Y(obs5, sx, modelname = "dmStat5_obs", compile = FALSE, deriv2 = TRUE, derivMode = dm) +sg <- Y(obs5, sx, modelname = "dmStat5_obs", compile = FALSE, derivMode = dm) serr <- Y(c(pSTAT5A_rel = "sd_pA", pSTAT5B_rel = "sd_pB", rSTAT5A_rel = "sd_rA"), sg, attachInput = FALSE, - compile = FALSE, deriv2 = TRUE, derivMode = dm, modelname = "dmStat5_err") + compile = FALSE, derivMode = dm, modelname = "dmStat5_err") lines <- paste0("L", 1:10) rates <- c("Epo_degradation_BaF3", "k_exp_hetero", "k_exp_homo", "k_imp_hetero", "k_imp_homo", "k_phos", "sd_pA", "sd_pB", "sd_rA", "STAT5tot") @@ -84,7 +84,7 @@ str5 <- insert(str5, "specC17 <- 0.107") str5 <- insert(str5, "x <- exp10(x)", x = rates) str5 <- insert(str5, "ratio <- 1/(1 + exp(-ratio))") str5 <- insert(str5, x ~ 1 + (1 | line), x = c("STAT5tot", "ratio", "k_exp_homo", "k_imp_hetero")) -sp <- P(str5, method = "explicit", compile = FALSE, modelname = "dmStat5_p", deriv2 = TRUE, derivMode = dm) +sp <- P(str5, method = "explicit", compile = FALSE, modelname = "dmStat5_p", derivMode = dm) compile(sx, sg, serr, sp, output = "dmStat5") published <- c(log10(c(Epo_degradation_BaF3 = 0.02698, k_exp_hetero = 1.0007e-05, k_exp_homo = 0.006170, k_imp_hetero = 0.01637, k_imp_homo = 97749, k_phos = 15767, sd_pA = 3.853, diff --git a/bench/nlme/mavoglurant.R b/bench/nlme/mavoglurant.R index 412dae72..c2edeab1 100644 --- a/bench/nlme/mavoglurant.R +++ b/bench/nlme/mavoglurant.R @@ -10,7 +10,7 @@ dir.create(getOption("dMod2.outdir"), showWarnings = FALSE) reps <- 3 nstart <- 100 cores <- max(1L, min(20L, parallel::detectCores() - 2L)) -dm <- c("forward", "reverse", "forward-reverse") +dm <- c("forward", "reverse", "forward-forward", "forward-reverse") ## dMod2 --------------------------------------------------------------------------------- data(mavoglurant) @@ -25,11 +25,11 @@ net <- eqnlist() |> addReaction("C1", "C2", "Q * C1", "distribution", rateCompartment = "unit") |> addReaction("C2", "C1", "Q * C2", "redistribution", rateCompartment = "unit") # solver tolerances 1e-10, as in the demo -x <- Xs(odemodel(net, modelname = "mavoBench", compile = FALSE, deriv2 = TRUE, derivMode = dm), +x <- Xs(odemodel(net, modelname = "mavoBench", compile = FALSE, derivMode = dm), options = list(atol = 1e-10, rtol = 1e-10)) -g <- Y(c(cp = "1000 * C1"), x, modelname = "mavoBench_g", compile = FALSE, deriv2 = TRUE, derivMode = dm) +g <- Y(c(cp = "1000 * C1"), x, modelname = "mavoBench_g", compile = FALSE, derivMode = dm) e <- Y(c(cp = "sqrt(sigma_abs^2 + (sigma_rel * cp)^2)"), g, attachInput = FALSE, modelname = "mavoBench_e", - compile = FALSE, deriv2 = TRUE, derivMode = dm) + compile = FALSE, derivMode = dm) table <- attr(data, "condition.grid") table$ID <- as.character(table$ID) trafo <- branch(define(NULL, "x <- x", x = c("CL", "V1", "Q", "V2", "C1", "C2", "dose", "duration", "sigma_abs", @@ -44,8 +44,8 @@ trafo1 <- insert(trafo, CL ~ 1 + (1 | ID)) trafo1 <- insert(trafo1, V1 + Q + V2 ~ 1 + (1 | ID)) trafo <- insert(trafo, CL ~ 1 + (1 | ID) + (1 | ID:OCC)) trafo <- insert(trafo, V1 + Q + V2 ~ 1 + (1 | ID)) -p <- P(trafo, method = "explicit", modelname = "mavoBench_p", compile = FALSE, deriv2 = TRUE, derivMode = dm) -p1 <- P(trafo1, method = "explicit", modelname = "mavoBench_p1", compile = FALSE, deriv2 = TRUE, derivMode = dm) +p <- P(trafo, method = "explicit", modelname = "mavoBench_p", compile = FALSE, derivMode = dm) +p1 <- P(trafo1, method = "explicit", modelname = "mavoBench_p1", compile = FALSE, derivMode = dm) compileSeconds <- system.time(compile(x, g, e, p, p1, output = "mavoBench"))[["elapsed"]] obj <- normL2(data, g * x * p, errmodel = e) obj1 <- normL2(data, g * x * p1, errmodel = e) diff --git a/bench/nlme/theoph.R b/bench/nlme/theoph.R index 381e0ee2..0a0288bf 100644 --- a/bench/nlme/theoph.R +++ b/bench/nlme/theoph.R @@ -15,9 +15,9 @@ reactions <- eqnlist() reactions <- addReaction(reactions, "Ag", "", "Ka * Ag", "absorption") reactions <- addReaction(reactions, "", "Cc", "Ka * Ag / V", "appearance") reactions <- addReaction(reactions, "Cc", "", "Cl/V * Cc", "elimination") -x <- Xs(odemodel(reactions, modelname = "theophBench", compile = FALSE, deriv2 = TRUE)) -g <- Y(c(y = "Cc"), x, modelname = "theophBench_obs", compile = FALSE, deriv2 = TRUE) -err <- Y(c(y = "sigma_add"), g, attachInput = FALSE, compile = FALSE, deriv2 = TRUE, +x <- Xs(odemodel(reactions, modelname = "theophBench", compile = FALSE, derivMode = "forward-forward")) +g <- Y(c(y = "Cc"), x, modelname = "theophBench_obs", compile = FALSE, derivMode = "forward-forward") +err <- Y(c(y = "sigma_add"), g, attachInput = FALSE, compile = FALSE, derivMode = "forward-forward", modelname = "theophBench_err") subjects <- sort(unique(Theoph$Subject)) covariates <- data.frame(ID = subjects, dose = tapply(Theoph$Dose * Theoph$Wt, Theoph$Subject, `[`, 1)[subjects], @@ -27,7 +27,7 @@ trafo <- insert(trafo, "Ag <- dose", dose = dose) trafo <- insert(trafo, "Cc <- 0") trafo <- insert(trafo, "x <- exp(x)", x = c("Ka", "V", "Cl", "sigma_add")) trafo <- insert(trafo, Ka + V + Cl ~ 1 + (1 | ID)) -p <- P(trafo, method = "explicit", compile = FALSE, modelname = "theophBench_p", deriv2 = TRUE) +p <- P(trafo, method = "explicit", compile = FALSE, modelname = "theophBench_p", derivMode = "forward-forward") compile(x, g, err, p, output = "theophBench") obj <- normL2(data, g * x * p, errmodel = err) init <- c(Ka = 0, V = 3, Cl = 0.7, sigma_add = log(0.5)) diff --git a/bench/nlme/tmdd.R b/bench/nlme/tmdd.R index 3dd89bae..01a01315 100644 --- a/bench/nlme/tmdd.R +++ b/bench/nlme/tmdd.R @@ -9,7 +9,7 @@ dir.create(getOption("dMod2.outdir"), showWarnings = FALSE) nsets <- 20 nstart <- 100 cores <- max(1L, min(20L, parallel::detectCores() - 2L)) -dm <- c("forward", "reverse", "forward-reverse") +dm <- c("forward", "reverse", "forward-forward", "forward-reverse") ## Model and design ---------------------------------------------------------------------- net <- eqnlist() |> @@ -37,9 +37,9 @@ subjects <- sprintf("S%02d", 1:45) table <- data.frame(ID = subjects, dose = rep(doses, each = 9), row.names = subjects) # the free drug in log10 coordinates and the solver tolerances 1e-10, as in the demo x <- Xs(odemodel(log10Transform(as.eqnvec(net), states = "C"), modelname = "tmddBench", compile = FALSE, - deriv2 = TRUE, derivMode = dm), options = list(atol = 1e-10, rtol = 1e-10)) -g <- Y(c(lcp = "log(10) * C_l10"), x, modelname = "tmddBench_g", compile = FALSE, deriv2 = TRUE, derivMode = dm) -e <- Y(c(lcp = "sigma"), g, attachInput = FALSE, modelname = "tmddBench_e", compile = FALSE, deriv2 = TRUE, derivMode = dm) + derivMode = dm), options = list(atol = 1e-10, rtol = 1e-10)) +g <- Y(c(lcp = "log(10) * C_l10"), x, modelname = "tmddBench_g", compile = FALSE, derivMode = dm) +e <- Y(c(lcp = "sigma"), g, attachInput = FALSE, modelname = "tmddBench_e", compile = FALSE, derivMode = dm) trafo <- branch(define(NULL, "x <- x", x = c("CL", "V", "Q", "Vp", "kon", "koff", "kint", "ksyn", "kdeg", "C_l10", "Cp", "R", "RC", "sigma")), table = table) trafo <- insert(trafo, "x <- y", x = c("C_l10", "Cp", "RC"), y = c("log10(dose / V)", "0", "0")) @@ -48,7 +48,7 @@ trafo <- insert(trafo, "ksyn <- kdeg * R0") trafo <- insert(trafo, "dose <- d", d = dose) trafo <- insert(trafo, "x <- exp(x)", x = c(names(truth), "sigma")) trafo <- insert(trafo, CL + V + R0 ~ 1 + (1 | ID)) -p <- P(trafo, method = "explicit", modelname = "tmddBench_p", compile = FALSE, deriv2 = TRUE, derivMode = dm) +p <- P(trafo, method = "explicit", modelname = "tmddBench_p", compile = FALSE, derivMode = dm) compile(x, g, e, p, output = "tmddBench") random <- randomEffects(p) # second derivatives forward over forward; quadrature up to level 5 diff --git a/bench/nlme/warfarin.R b/bench/nlme/warfarin.R index b5b68488..381d81ba 100644 --- a/bench/nlme/warfarin.R +++ b/bench/nlme/warfarin.R @@ -9,7 +9,7 @@ dir.create(getOption("dMod2.outdir"), showWarnings = FALSE) reps <- 3 nstart <- 100 cores <- max(1L, min(20L, parallel::detectCores() - 2L)) -dm <- c("forward", "reverse", "forward-reverse") +dm <- c("forward", "reverse", "forward-forward", "forward-reverse") ## dMod2 --------------------------------------------------------------------------------- data(warfarin) @@ -23,10 +23,10 @@ net <- eqnlist() |> addReaction("Cc", "", "Cl * Cc", "elimination", rateCompartment = "unit") |> addReaction("", "PCA", "kout * pca0 * IC50 / (IC50 + Cc)", "synthesis") |> addReaction("PCA", "", "kout * PCA", "degradation") -x <- Xs(odemodel(net, modelname = "warfBench", compile = FALSE, deriv2 = TRUE, derivMode = dm)) -g <- Y(c(cp = "Cc", pca = "PCA"), x, modelname = "warfBench_g", compile = FALSE, deriv2 = TRUE, derivMode = dm) +x <- Xs(odemodel(net, modelname = "warfBench", compile = FALSE, derivMode = dm)) +g <- Y(c(cp = "Cc", pca = "PCA"), x, modelname = "warfBench_g", compile = FALSE, derivMode = dm) e <- Y(c(cp = "sqrt(sigma_cp_abs^2 + (sigma_cp_rel * cp)^2)", pca = "sigma_pca"), g, attachInput = FALSE, - modelname = "warfBench_e", compile = FALSE, deriv2 = TRUE, derivMode = dm) + modelname = "warfBench_e", compile = FALSE, derivMode = dm) table <- attr(data, "condition.grid") table$ID <- rownames(table) trafo <- branch(define(NULL, "x <- x", x = c("Ka", "V", "Cl", "IC50", "kout", "pca0", "Ag", "Cc", "PCA", "sigma_cp_abs", @@ -37,7 +37,7 @@ trafo <- insert(trafo, "PCA <- pca0") trafo <- insert(trafo, "x <- exp(x)", x = c("Ka", "V", "Cl", "IC50", "kout", "pca0", "sigma_cp_abs", "sigma_cp_rel", "sigma_pca")) trafo <- insert(trafo, V + Cl + pca0 + kout ~ 1 + (1 | ID)) -p <- P(trafo, method = "explicit", modelname = "warfBench_p", compile = FALSE, deriv2 = TRUE, derivMode = dm) +p <- P(trafo, method = "explicit", modelname = "warfBench_p", compile = FALSE, derivMode = dm) compileSeconds <- system.time(compile(x, g, e, p, output = "warfBench"))[["elapsed"]] obj <- normL2(data, g * x * p, errmodel = e) random <- randomEffects(p) diff --git a/bench/structureSelection/becker.R b/bench/structureSelection/becker.R index 63a4814b..3326315d 100644 --- a/bench/structureSelection/becker.R +++ b/bench/structureSelection/becker.R @@ -24,12 +24,12 @@ reactions <- addReaction(reactions, "Epo_EpoR", "Epo_EpoR_i", "Epo_EpoR * ke", " reactions <- addReaction(reactions, "Epo_EpoR_i", "Epo + EpoR", "Epo_EpoR_i * kex", "recycling") reactions <- addReaction(reactions, "Epo_EpoR_i", "dEpo_i", "Epo_EpoR_i * kdi", "intra degr.") reactions <- addReaction(reactions, "Epo_EpoR_i", "dEpo_e", "Epo_EpoR_i * kde", "extra degr.") -x <- Xs(odemodel(reactions, modelname = "becker", compile = FALSE, deriv2 = TRUE)) +x <- Xs(odemodel(reactions, modelname = "becker", compile = FALSE, derivMode = "forward-forward")) g <- Y(eqnvec(y_ext = "log(Epo + dEpo_e + 1)", y_mem = "log(Epo_EpoR + 1)", y_int = "log(Epo_EpoR_i + dEpo_i + 1)"), - x, modelname = "becker_obs", compile = FALSE, attachInput = FALSE, deriv2 = TRUE) + x, modelname = "becker_obs", compile = FALSE, attachInput = FALSE, derivMode = "forward-forward") e <- Y(eqnvec(y_ext = "sigma", y_mem = "sigma", y_int = "sigma"), g, modelname = "becker_err", - compile = FALSE, attachInput = FALSE, deriv2 = TRUE) + compile = FALSE, attachInput = FALSE, derivMode = "forward-forward") dose <- 1347.49 lines <- c("A", "B", "C", "D", "E", "F") @@ -49,11 +49,11 @@ base <- function() { trH <- base() for (l in lines[-1]) for (pp in cand) trH <- insert(trH, paste0(pp, " <- ", pp, " + r_", pp, "_", l), conditionMatch = paste0("^", l, "$")) -pH <- P(trH, method = "explicit", modelname = "becker_h", compile = FALSE, deriv2 = TRUE) +pH <- P(trH, method = "explicit", modelname = "becker_h", compile = FALSE, derivMode = "forward-forward") # EM: per line and candidate a deviation from the population value, shared by clusters of lines pS <- P(insert(base(), x ~ 1 + (1 | gr(line, dist = dirichletProcess())), x = cand), method = "explicit", - modelname = "becker_s", compile = FALSE, deriv2 = TRUE) + modelname = "becker_s", compile = FALSE, derivMode = "forward-forward") compile(g, x, e, pH, pS, output = "becker") ## Truth and the parameters held fixed --------------------------------------------------- diff --git a/bench/structureSelection/toy.R b/bench/structureSelection/toy.R index 9be62671..9b05dec8 100644 --- a/bench/structureSelection/toy.R +++ b/bench/structureSelection/toy.R @@ -13,8 +13,8 @@ alpha <- 0.05 fitsPath <- 4 ## Model ---------------------------------------------------------------------------------- -x <- Xs(odemodel(eqnvec(x = "-p * x"), modelname = "toySel", compile = FALSE, deriv2 = TRUE)) -g <- Y(eqnvec(y = "x"), x, modelname = "toySel_obs", compile = FALSE, attachInput = FALSE, deriv2 = TRUE) +x <- Xs(odemodel(eqnvec(x = "-p * x"), modelname = "toySel", compile = FALSE, derivMode = "forward-forward")) +g <- Y(eqnvec(y = "x"), x, modelname = "toySel_obs", compile = FALSE, attachInput = FALSE, derivMode = "forward-forward") types <- c("c1", "c2", "c3") tab <- data.frame(type = types, row.names = types) base <- function() insert(branch(define(NULL, "x <- x", x = c("x", "p")), table = tab), "x <- 1") @@ -22,11 +22,11 @@ base <- function() insert(branch(define(NULL, "x <- x", x = c("x", "p")), table # Hauber et al.: fold changes r_c2, r_c3 to the reference c1 trH <- insert(base(), "p <- 10^lp") for (ct in types[-1]) trH <- insert(trH, paste0("lp <- lp + r_", ct), conditionMatch = paste0("^", ct, "$")) -pH <- P(trH, method = "explicit", modelname = "toySel_h", compile = FALSE, deriv2 = TRUE) +pH <- P(trH, method = "explicit", modelname = "toySel_h", compile = FALSE, derivMode = "forward-forward") # EM: a deviation of lp per type, shared by clusters of types trS <- insert(base(), "p <- 10^lp") pS <- P(insert(trS, lp ~ 1 + (1 | gr(type, dist = dirichletProcess()))), method = "explicit", - modelname = "toySel_s", compile = FALSE, deriv2 = TRUE) + modelname = "toySel_s", compile = FALSE, derivMode = "forward-forward") compile(g, x, pH, pS, output = "toySel") truth <- c(lp = -1.5, r_c2 = 0.2, r_c3 = 0.3) diff --git a/bench/symmetry/AB.R b/bench/symmetry/AB.R index 4be061d6..8fc0ae87 100644 --- a/bench/symmetry/AB.R +++ b/bench/symmetry/AB.R @@ -98,7 +98,7 @@ p.red <- eqnvec() |> flow <- lapply(seq_along(res$symmetries), function(i) { fl <- log10Transform(res$symmetries[[i]]$completeGenerator) Xf(odemodel(as.eqnvec(setNames(paste0("sgn*(", fl, ")"), names(fl))), - deriv = FALSE, modelname = paste0("AB_flow", i), compile = FALSE, + derivMode = "none", modelname = paste0("AB_flow", i), compile = FALSE, outdir = .outdir), condition = "flow", options = list(atol = 1e-12, rtol = 1e-12, maxsteps = 1e7)) diff --git a/bench/symmetry/battery.R b/bench/symmetry/battery.R index c1cb8842..02348347 100644 --- a/bench/symmetry/battery.R +++ b/bench/symmetry/battery.R @@ -119,7 +119,7 @@ p.red <- eqnvec() |> flow <- lapply(seq_along(res$symmetries), function(i) { fl <- log10Transform(res$symmetries[[i]]$completeGenerator) Xf(odemodel(as.eqnvec(setNames(paste0("sgn*(", fl, ")"), names(fl))), - deriv = FALSE, modelname = paste0("battery_flow", i), compile = FALSE, + derivMode = "none", modelname = paste0("battery_flow", i), compile = FALSE, outdir = .outdir), condition = "flow", options = list(atol = 1e-12, rtol = 1e-12, maxsteps = 1e7)) diff --git a/bench/symmetry/macrospin_mtj_switching.R b/bench/symmetry/macrospin_mtj_switching.R index 8d915098..712b2f2a 100644 --- a/bench/symmetry/macrospin_mtj_switching.R +++ b/bench/symmetry/macrospin_mtj_switching.R @@ -106,7 +106,7 @@ p <- Reduce(`+`, lapply(rownames(fields), function(cn) { # flow dz/deps = sgn*xi(z) along the easy-axis direction, in log10 coordinates fl <- log10Transform(dir.easy$completeGenerator) flow <- Xf(odemodel(as.eqnvec(setNames(paste0("sgn*(", fl, ")"), names(fl))), - deriv = FALSE, modelname = "macrospin_flow", compile = FALSE, + derivMode = "none", modelname = "macrospin_flow", compile = FALSE, outdir = .outdir), condition = "flow", options = list(atol = 1e-12, rtol = 1e-12, maxsteps = 1e7)) @@ -321,7 +321,7 @@ dirs.stt <- res.stt$symmetries flows.stt <- lapply(seq_along(dirs.stt), function(i) { gen <- dirs.stt[[i]]$completeGenerator Xf(odemodel(as.eqnvec(setNames(paste0("sgn*(", gen, ")"), names(gen))), - deriv = FALSE, modelname = paste0("mtj_flow", i), compile = FALSE, + derivMode = "none", modelname = paste0("mtj_flow", i), compile = FALSE, outdir = .outdir), condition = paste0("flow", i), options = list(atol = 1e-12, rtol = 1e-12, maxsteps = 1e7)) diff --git a/bench/symmetry/preBotC.R b/bench/symmetry/preBotC.R index ee7e5709..70bbd349 100644 --- a/bench/symmetry/preBotC.R +++ b/bench/symmetry/preBotC.R @@ -147,7 +147,7 @@ flowEq <- lapply(res$symmetries, function(s) { }) flow <- lapply(seq_along(flowEq), function(i) - Xf(odemodel(flowEq[[i]], deriv = FALSE, modelname = paste0("preBotC_flow", i), + Xf(odemodel(flowEq[[i]], derivMode = "none", modelname = paste0("preBotC_flow", i), compile = FALSE, outdir = .outdir), condition = "flow", options = myOptions)) diff --git a/examples/TMDD/analysis.R b/examples/TMDD/analysis.R index 6ac21824..40c7b12f 100644 --- a/examples/TMDD/analysis.R +++ b/examples/TMDD/analysis.R @@ -35,7 +35,7 @@ cachedEm <- function(key, obj, random, start, control = list(), ...) { f } -dm <- c("forward", "reverse", "forward-reverse") +dm <- c("forward", "reverse", "forward-forward", "forward-reverse") # Model ---- # @@ -94,10 +94,10 @@ ode <- log10Transform(as.eqnvec(net), states = "C") ode # solver tolerances 1e-10: at the defaults the solver error moves -2 log L by about 1e-4, more than # FOCEI resolves, and the fit stalls short of the optimum -x <- Xs(odemodel(ode, modelname = "tmdd", compile = FALSE, deriv2 = TRUE, derivMode = dm), +x <- Xs(odemodel(ode, modelname = "tmdd", compile = FALSE, derivMode = dm), options = list(atol = 1e-10, rtol = 1e-10)) -g <- Y(c(lcp = "log(10) * C_l10"), x, modelname = "tmdd_g", compile = FALSE, deriv2 = TRUE, derivMode = dm) -e <- Y(c(lcp = "sigma"), g, attachInput = FALSE, modelname = "tmdd_e", compile = FALSE, deriv2 = TRUE, derivMode = dm) +g <- Y(c(lcp = "log(10) * C_l10"), x, modelname = "tmdd_g", compile = FALSE, derivMode = dm) +e <- Y(c(lcp = "sigma"), g, attachInput = FALSE, modelname = "tmdd_e", compile = FALSE, derivMode = dm) trafo <- branch(define(NULL, "x <- x", x = c("CL", "V", "Q", "Vp", "kon", "koff", "kint", "ksyn", "kdeg", "C_l10", "Cp", "R", "RC", "sigma")), table = table) trafo <- insert(trafo, "x <- y", x = c("C_l10", "Cp", "RC"), y = c("log10(dose / V)", "0", "0")) @@ -106,7 +106,7 @@ trafo <- insert(trafo, "ksyn <- kdeg * R0") trafo <- insert(trafo, "dose <- d", d = dose) trafo <- insert(trafo, "x <- exp(x)", x = c(parameters, "sigma")) trafo <- insert(trafo, CL + V + R0 ~ 1 + (1 | ID)) -p <- P(trafo, method = "explicit", modelname = "tmdd_p", compile = FALSE, deriv2 = TRUE, derivMode = dm) +p <- P(trafo, method = "explicit", modelname = "tmdd_p", compile = FALSE, derivMode = dm) compile(x, g, e, p, output = "tmdd_all") random <- randomEffects(p) diff --git a/examples/oppeltNPJSystBiolAppl2018/model.R b/examples/oppeltNPJSystBiolAppl2018/model.R index 07b5d5b1..ddb6d32a 100644 --- a/examples/oppeltNPJSystBiolAppl2018/model.R +++ b/examples/oppeltNPJSystBiolAppl2018/model.R @@ -138,8 +138,8 @@ errors <- eqnvec(nucNFkB = "sigma_nucNFkB", cytNFkB = "sigma_cytNFkB", A20GFP = ## ---- steadystate # the cells rest before TNFα is added: a steady state with the amounts of NFκB and IKK conserved; # an unstable one is returned rather than refused, the objective below keeps it stable -pSS <- Pimpl(reactions, modelname = "oppelt_ss", compile = FALSE, deriv2 = TRUE, - controlsPTC = list(stability = FALSE)) +pSS <- Pimpl(reactions, modelname = "oppelt_ss", compile = FALSE, + derivMode = "forward-forward", controlsPTC = list(stability = FALSE)) ## ---- odemodel diff --git a/examples/oppeltNPJSystBiolAppl2018/results/dcf.rds b/examples/oppeltNPJSystBiolAppl2018/results/dcf.rds index 0a99aca1..dd19db46 100644 Binary files a/examples/oppeltNPJSystBiolAppl2018/results/dcf.rds and b/examples/oppeltNPJSystBiolAppl2018/results/dcf.rds differ diff --git a/examples/oppeltNPJSystBiolAppl2018/results/dcfL1.rds b/examples/oppeltNPJSystBiolAppl2018/results/dcfL1.rds index 34eb2992..ce82b9d9 100644 Binary files a/examples/oppeltNPJSystBiolAppl2018/results/dcfL1.rds and b/examples/oppeltNPJSystBiolAppl2018/results/dcfL1.rds differ diff --git a/examples/oppeltNPJSystBiolAppl2018/results/discrete.rds b/examples/oppeltNPJSystBiolAppl2018/results/discrete.rds index cb782410..13d59422 100644 Binary files a/examples/oppeltNPJSystBiolAppl2018/results/discrete.rds and b/examples/oppeltNPJSystBiolAppl2018/results/discrete.rds differ diff --git a/examples/oppeltNPJSystBiolAppl2018/results/fits.rds b/examples/oppeltNPJSystBiolAppl2018/results/fits.rds index b433a1df..64d17775 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 index eb7e9a91..563ec090 100644 Binary files a/examples/oppeltNPJSystBiolAppl2018/results/fundamental.rds and b/examples/oppeltNPJSystBiolAppl2018/results/fundamental.rds differ diff --git a/examples/oppeltNPJSystBiolAppl2018/results/onefit.rds b/examples/oppeltNPJSystBiolAppl2018/results/onefit.rds index 473c9b53..94d66175 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 77d1e1f6..8444ba24 100644 Binary files a/examples/oppeltNPJSystBiolAppl2018/results/optimizers.rds and b/examples/oppeltNPJSystBiolAppl2018/results/optimizers.rds differ diff --git a/examples/oppeltNPJSystBiolAppl2018/results/prediction.rds b/examples/oppeltNPJSystBiolAppl2018/results/prediction.rds index 3d4c9f88..498ac450 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 00833728..6a7bc069 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 5c29d72e..334596f7 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 39df6880..97b98cc2 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 eca29cc8..0fdbbc88 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 7d0b596b..bbc17dba 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 6166e750..e11b1a6e 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 658b53be..93f6d76c 100644 --- a/examples/oppeltNPJSystBiolAppl2018/sensitivities.R +++ b/examples/oppeltNPJSystBiolAppl2018/sensitivities.R @@ -8,15 +8,15 @@ if (!exists("obj")) source("model.R") ## ---- reversechain # the chain and objective of model.R once more, every function object with the reverse sweep and # second derivatives; Pimpl() passes the reverse sweep through the Jacobian of the root -dm <- c("forward", "reverse", "forward-reverse") -modelR <- odemodel(reactions, events = events, modelname = "oppelt_rev_ode", deriv2 = TRUE, +dm <- c("forward", "reverse", "forward-forward", "forward-reverse") +modelR <- odemodel(reactions, events = events, modelname = "oppelt_rev_ode", derivMode = dm, compile = FALSE) xR <- Xs(modelR, options = list(atol = 1e-10, rtol = 1e-8)) -gR <- Y(observables, xR, modelname = "oppelt_rev_obs", compile = FALSE, deriv2 = TRUE, derivMode = dm) -eR <- Y(errors, gR, modelname = "oppelt_rev_err", compile = FALSE, deriv2 = TRUE, derivMode = dm) -pSSR <- Pimpl(reactions, modelname = "oppelt_rev_ss", compile = FALSE, deriv2 = TRUE, - controlsPTC = list(stability = FALSE)) -pR <- P(trafo, modelname = "oppelt_rev_par", compile = FALSE, deriv2 = TRUE, derivMode = dm) +gR <- Y(observables, xR, modelname = "oppelt_rev_obs", compile = FALSE, derivMode = dm) +eR <- Y(errors, gR, modelname = "oppelt_rev_err", compile = FALSE, derivMode = dm) +pSSR <- Pimpl(reactions, modelname = "oppelt_rev_ss", compile = FALSE, + derivMode = "forward-forward", controlsPTC = list(stability = FALSE)) +pR <- P(trafo, modelname = "oppelt_rev_par", compile = FALSE, 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, width = rampWidth) diff --git a/examples/pharmacometrics/analysis.R b/examples/pharmacometrics/analysis.R index 922f745f..845ef850 100644 --- a/examples/pharmacometrics/analysis.R +++ b/examples/pharmacometrics/analysis.R @@ -10,7 +10,7 @@ options(dMod2.outdir = "build") cores <- max(1L, min(20L, parallel::detectCores() - 2L)) nstart <- 100L # second derivatives forward over reverse for FOCEI, forward over forward for the reported Hessian -dm <- c("forward", "reverse", "forward-reverse") +dm <- c("forward", "reverse", "forward-forward", "forward-reverse") # fits are saved in results/cache.rds under a key and read from there when present; delete the # file to fit everything again @@ -112,9 +112,9 @@ theoNet <- eqnlist() |> addReaction("Ag", "Cc", "Ka * Ag", "absorption") |> addReaction("Cc", "", "Cl * Cc", "elimination", rateCompartment = "unit") theoNet -theoX <- Xs(odemodel(theoNet, modelname = "pm_theoph", compile = FALSE, deriv2 = TRUE, derivMode = dm)) -theoG <- Y(c(cp = "Cc"), theoX, modelname = "pm_theoph_g", compile = FALSE, deriv2 = TRUE, derivMode = dm) -theoE <- Y(c(cp = "sigma"), theoG, attachInput = FALSE, modelname = "pm_theoph_e", compile = FALSE, deriv2 = TRUE, +theoX <- Xs(odemodel(theoNet, modelname = "pm_theoph", compile = FALSE, derivMode = dm)) +theoG <- Y(c(cp = "Cc"), theoX, modelname = "pm_theoph_g", compile = FALSE, derivMode = dm) +theoE <- Y(c(cp = "sigma"), theoG, attachInput = FALSE, modelname = "pm_theoph_e", compile = FALSE, derivMode = dm) subjects <- sort(unique(Theoph$Subject)) theoTable <- data.frame(ID = subjects, dose = tapply(Theoph$Dose * Theoph$Wt, Theoph$Subject, `[`, 1)[subjects], @@ -124,7 +124,7 @@ theoTrafo <- insert(theoTrafo, "Ag <- dose", dose = dose) theoTrafo <- insert(theoTrafo, "Cc <- 0") theoTrafo <- insert(theoTrafo, "x <- exp(x)", x = c("Ka", "V", "Cl", "sigma")) theoTrafo <- insert(theoTrafo, Ka + V + Cl ~ 1 + (1 | ID)) -theoP <- P(theoTrafo, method = "explicit", modelname = "pm_theoph_p", compile = FALSE, deriv2 = TRUE, derivMode = dm) +theoP <- P(theoTrafo, method = "explicit", modelname = "pm_theoph_p", compile = FALSE, derivMode = dm) compileSeconds <- c(theophylline = system.time(compile(theoX, theoG, theoE, theoP, output = "pm_theoph_all"))[["elapsed"]]) theoObj <- normL2(theoData, theoG * theoX * theoP, errmodel = theoE) @@ -167,13 +167,13 @@ warfNet <- eqnlist() |> addReaction("", "PCA", "kout * pca0 * IC50 / (IC50 + Cc)", "synthesis") |> addReaction("PCA", "", "kout * PCA", "degradation") warfNet -warfX <- Xs(odemodel(warfNet, modelname = "pm_warf", compile = FALSE, deriv2 = TRUE, derivMode = dm)) -warfG <- Y(c(cp = "Cc", pca = "PCA"), warfX, modelname = "pm_warf_g", compile = FALSE, deriv2 = TRUE, +warfX <- Xs(odemodel(warfNet, modelname = "pm_warf", compile = FALSE, derivMode = dm)) +warfG <- Y(c(cp = "Cc", pca = "PCA"), warfX, modelname = "pm_warf_g", compile = FALSE, derivMode = dm) # the error of cp combined from an absolute and a relative part, positive also where the solver # leaves cp at or below 0 warfE <- Y(c(cp = "sqrt(sigma_cp_abs^2 + (sigma_cp_rel * cp)^2)", pca = "sigma_pca"), warfG, - attachInput = FALSE, modelname = "pm_warf_e", compile = FALSE, deriv2 = TRUE, derivMode = dm) + attachInput = FALSE, modelname = "pm_warf_e", compile = FALSE, derivMode = dm) warfTable <- attr(warfData, "condition.grid") warfTable$ID <- rownames(warfTable) warfTrafo <- branch(define(NULL, "x <- x", x = c("Ka", "V", "Cl", "IC50", "kout", "pca0", "Ag", "Cc", "PCA", @@ -184,7 +184,7 @@ warfTrafo <- insert(warfTrafo, "PCA <- pca0") warfTrafo <- insert(warfTrafo, "x <- exp(x)", x = c("Ka", "V", "Cl", "IC50", "kout", "pca0", "sigma_cp_abs", "sigma_cp_rel", "sigma_pca")) warfTrafo <- insert(warfTrafo, V + Cl + pca0 + kout ~ 1 + (1 | ID)) -warfP <- P(warfTrafo, method = "explicit", modelname = "pm_warf_p", compile = FALSE, deriv2 = TRUE, derivMode = dm) +warfP <- P(warfTrafo, method = "explicit", modelname = "pm_warf_p", compile = FALSE, derivMode = dm) compileSeconds["warfarin"] <- system.time(compile(warfX, warfG, warfE, warfP, output = "pm_warf_all"))[["elapsed"]] warfObj <- normL2(warfData, warfG * warfX * warfP, errmodel = warfE) warfRandom <- randomEffects(warfP) @@ -234,12 +234,12 @@ mavoNet <- eqnlist() |> mavoNet # solver tolerances 1e-10: at the defaults the solver error, absolute in mg/L, moves -2 log L by # about 1e-3, more than the fit resolves -mavoX <- Xs(odemodel(mavoNet, modelname = "pm_mavo", compile = FALSE, deriv2 = TRUE, derivMode = dm), +mavoX <- Xs(odemodel(mavoNet, modelname = "pm_mavo", compile = FALSE, derivMode = dm), options = list(atol = 1e-10, rtol = 1e-10)) # the dose in mg, the concentration in ng/mL -mavoG <- Y(c(cp = "1000 * C1"), mavoX, modelname = "pm_mavo_g", compile = FALSE, deriv2 = TRUE, derivMode = dm) +mavoG <- Y(c(cp = "1000 * C1"), mavoX, modelname = "pm_mavo_g", compile = FALSE, derivMode = dm) mavoE <- Y(c(cp = "sqrt(sigma_abs^2 + (sigma_rel * cp)^2)"), mavoG, attachInput = FALSE, modelname = "pm_mavo_e", - compile = FALSE, deriv2 = TRUE, derivMode = dm) + compile = FALSE, derivMode = dm) mavoTable <- attr(mavoData, "condition.grid") mavoTable$ID <- as.character(mavoTable$ID) mavoTrafo <- function(between) { @@ -255,9 +255,9 @@ mavoTrafo <- function(between) { if (between) tr <- insert(tr, CL ~ 1 + (1 | ID) + (1 | ID:OCC)) else tr <- insert(tr, CL ~ 1 + (1 | ID)) insert(tr, V1 + Q + V2 ~ 1 + (1 | ID)) } -mavoP <- P(mavoTrafo(TRUE), method = "explicit", modelname = "pm_mavo_p", compile = FALSE, deriv2 = TRUE, +mavoP <- P(mavoTrafo(TRUE), method = "explicit", modelname = "pm_mavo_p", compile = FALSE, derivMode = dm) -mavoP1 <- P(mavoTrafo(FALSE), method = "explicit", modelname = "pm_mavo_p1", compile = FALSE, deriv2 = TRUE, +mavoP1 <- P(mavoTrafo(FALSE), method = "explicit", modelname = "pm_mavo_p1", compile = FALSE, derivMode = dm) compileSeconds["mavoglurant"] <- system.time(compile(mavoX, mavoG, mavoE, mavoP, mavoP1, output = "pm_mavo_all"))[["elapsed"]] diff --git a/examples/pharmacometrics/results/multistart.rds b/examples/pharmacometrics/results/multistart.rds index 7f8e8904..0d621433 100644 Binary files a/examples/pharmacometrics/results/multistart.rds and b/examples/pharmacometrics/results/multistart.rds differ diff --git a/examples/pharmacometrics/theophyllineMultistart.R b/examples/pharmacometrics/theophyllineMultistart.R index 573703f4..65713a81 100644 --- a/examples/pharmacometrics/theophyllineMultistart.R +++ b/examples/pharmacometrics/theophyllineMultistart.R @@ -11,10 +11,10 @@ reactions <- eqnlist() |> setCompartmentVolume(unit = "1") |> addReaction("Ag", "Cc", "Ka * Ag", "absorption") |> addReaction("Cc", "", "Cl * Cc", "elimination", rateCompartment = "unit") -dm <- c("forward", "reverse", "forward-reverse") -x <- Xs(odemodel(reactions, modelname = "theo", compile = FALSE, deriv2 = TRUE, derivMode = dm)) -g <- Y(c(cp = "Cc"), x, modelname = "theo_g", compile = FALSE, deriv2 = TRUE, derivMode = dm) -e <- Y(c(cp = "sigma"), g, attachInput = FALSE, modelname = "theo_e", compile = FALSE, deriv2 = TRUE, +dm <- c("forward", "reverse", "forward-forward", "forward-reverse") +x <- Xs(odemodel(reactions, modelname = "theo", compile = FALSE, derivMode = dm)) +g <- Y(c(cp = "Cc"), x, modelname = "theo_g", compile = FALSE, derivMode = dm) +e <- Y(c(cp = "sigma"), g, attachInput = FALSE, modelname = "theo_e", compile = FALSE, derivMode = dm) data(Theoph, package = "datasets") Theoph$Subject <- as.character(Theoph$Subject) @@ -28,7 +28,7 @@ trafo <- branch(define(NULL, "x <- x", x = c("Ka", "V", "Cl", "Ag", "Cc", "sigma insert("Cc <- 0") |> insert("x <- exp(x)", x = c("Ka", "V", "Cl", "sigma")) |> insert(Ka + V + Cl ~ 1 + (1 | ID)) -p <- P(trafo, method = "explicit", modelname = "theo_p", compile = FALSE, deriv2 = TRUE, derivMode = dm) +p <- P(trafo, method = "explicit", modelname = "theo_p", compile = FALSE, derivMode = dm) compile(x, g, e, p, output = "theo") random <- randomEffects(p) obj <- normL2(data, g * x * p, errmodel = e) diff --git a/inst/examples/constraintStability.R b/inst/examples/constraintStability.R index 1b78833d..9dae4fff 100644 --- a/inst/examples/constraintStability.R +++ b/inst/examples/constraintStability.R @@ -2,7 +2,7 @@ # The Brusselator rests at x = a, y = b / a, stable while b < 1 + a^2 f <- c(x = "a - (b + 1) * x + x^2 * y", y = "b * x - x^2 * y") old <- setwd(tempdir()) -pSS <- Pimpl(f, deriv2 = TRUE, modelname = "brusselator_ss") +pSS <- Pimpl(f, derivMode = "forward-forward", modelname = "brusselator_ss") p <- P(c(a = "exp(la)", b = "exp(lb)"), modelname = "brusselator_p") compile(pSS, p, output = "brusselator") stab <- constraintStability(pSS, p, weight = 10) diff --git a/man/P.Rd b/man/P.Rd index 65099e42..3a2c5635 100644 --- a/man/P.Rd +++ b/man/P.Rd @@ -13,8 +13,7 @@ P( method = NULL, cores = NULL, verbose = FALSE, - deriv = TRUE, - deriv2 = FALSE, + derivMode = "forward", ... ) } @@ -45,10 +44,11 @@ a list; on Windows the sources are generated one after the other. \code{NULL} \item{verbose}{Logical. Print the compiler output, default \code{FALSE}.} -\item{deriv, deriv2}{Build first and second derivatives, default \code{TRUE} and -\code{FALSE}. \code{deriv2} requires \code{deriv = TRUE}.} +\item{derivMode}{The derivatives to build, one or more of \code{"forward"} +(default), \code{"reverse"}, \code{"forward-forward"} and \code{"forward-reverse"}, or +\code{"none"}, passed to \code{\link[=Pexpl]{Pexpl()}} or \code{\link[=Pimpl]{Pimpl()}}.} -\item{...}{Further arguments of \code{\link[=Pexpl]{Pexpl()}} (\code{attachInput}, \code{derivMode}, +\item{...}{Further arguments of \code{\link[=Pexpl]{Pexpl()}} (\code{attachInput}, \code{outdir}) or \code{\link[=Pimpl]{Pimpl()}} (\code{forcings}, \code{keepRoot}, \code{flow}, \code{controlsPTC}, \code{outdir}), as \code{method} selects.} } @@ -84,10 +84,11 @@ The other arguments are named: \item \code{fixed}: named numeric vector of parameters that enter the evaluation without derivatives. Default \code{NULL}. \item \code{deriv}: \code{TRUE} (default) returns first derivatives with respect to -\code{pars}. +\code{pars}. Every function of the chain has to be built with +\code{derivMode = "forward"}, see \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. \item \code{deriv2}: \code{TRUE} returns second derivatives as well. Default \code{FALSE}. -Every function of the chain has to be built for them, see the arguments -\code{deriv2} and \code{derivMode} of \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. +Every function of the chain has to be built with +\code{derivMode = "forward-forward"}. \item \code{hessian}: objective functions only, see the table below. Default \code{NULL}. \item \code{sweep}: objective functions only. \code{"forward"} (default) propagates the diff --git a/man/Pexpl.Rd b/man/Pexpl.Rd index 5ddde2f5..0e093509 100644 --- a/man/Pexpl.Rd +++ b/man/Pexpl.Rd @@ -12,8 +12,6 @@ Pexpl( compile = FALSE, modelname = NULL, verbose = FALSE, - deriv = TRUE, - deriv2 = FALSE, derivMode = "forward", outdir = .dmodOutdir() ) @@ -42,15 +40,15 @@ is \code{"expl_parfn"}, followed by \verb{_}.} \item{verbose}{Logical. Print the compiler output, default \code{FALSE}.} -\item{deriv, deriv2}{Build the first derivatives, \code{attr(, "deriv")}, -\verb{[inner, outer]}, and the second, \code{attr(, "deriv2")}, -\verb{[inner, outer, outer]}. Default \code{TRUE} and \code{FALSE}; \code{deriv2} needs -\code{deriv = TRUE}.} - -\item{derivMode}{Which derivative code to build, any of \code{"forward"} -(default), \code{"reverse"} and \code{"forward-reverse"}. \code{"reverse"} is needed for -\code{sweep = "reverse"}, \code{"forward-reverse"} for \code{sweep = "reverse"} with -\code{deriv2 = TRUE}.} +\item{derivMode}{The derivatives to build, one or more of \code{"forward"} +(default), \code{"reverse"}, \code{"forward-forward"} and \code{"forward-reverse"}, or +\code{"none"}, as in \code{\link[=odemodel]{odemodel()}}. \code{"forward"} builds the Jacobian, +\code{attr(, "deriv")}, \verb{[inner, outer]}, \code{"forward-forward"} the second +derivatives, \code{attr(, "deriv2")}, \verb{[inner, outer, outer]}; \code{"reverse"} is +needed for \code{sweep = "reverse"}, \code{"forward-reverse"} for +\code{sweep = "reverse"} with \code{deriv2 = TRUE}. The second-order directions +build \code{"forward"} as well. A call that asks for a derivative not built is +an error.} \item{outdir}{Directory for the generated source and shared object, default \code{getOption("dMod2.outdir")}, else the working directory.} @@ -88,10 +86,11 @@ The other arguments are named: \item \code{fixed}: named numeric vector of parameters that enter the evaluation without derivatives. Default \code{NULL}. \item \code{deriv}: \code{TRUE} (default) returns first derivatives with respect to -\code{pars}. +\code{pars}. Every function of the chain has to be built with +\code{derivMode = "forward"}, see \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. \item \code{deriv2}: \code{TRUE} returns second derivatives as well. Default \code{FALSE}. -Every function of the chain has to be built for them, see the arguments -\code{deriv2} and \code{derivMode} of \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. +Every function of the chain has to be built with +\code{derivMode = "forward-forward"}. \item \code{hessian}: objective functions only, see the table below. Default \code{NULL}. \item \code{sweep}: objective functions only. \code{"forward"} (default) propagates the diff --git a/man/Pimpl.Rd b/man/Pimpl.Rd index 0394b509..6acc66c5 100644 --- a/man/Pimpl.Rd +++ b/man/Pimpl.Rd @@ -14,8 +14,7 @@ Pimpl( compile = FALSE, modelname = NULL, verbose = FALSE, - deriv = TRUE, - deriv2 = FALSE, + derivMode = "forward", controlsPTC = list(), outdir = .dmodOutdir() ) @@ -49,8 +48,12 @@ is \code{"impl_parfn"}, followed by \verb{_}.} \item{verbose}{Logical. Print the compiler output, default \code{FALSE}.} -\item{deriv, deriv2}{Build first and second derivatives, default \code{TRUE} and -\code{FALSE}. \code{deriv2} requires \code{deriv = TRUE}.} +\item{derivMode}{The derivatives to build, one or more of \code{"forward"} +(default), \code{"reverse"}, \code{"forward-forward"} and \code{"forward-reverse"}, or +\code{"none"}, as in \code{\link[=odemodel]{odemodel()}}. The reverse directions come from the +forward ones: \code{"reverse"} builds the Jacobian, \code{"forward-reverse"} the +second derivatives, as \code{"forward-forward"} does. A call that asks for a +derivative not built is an error.} \item{controlsPTC}{Named list of solver controls; an entry not given keeps the default, an unknown entry is an error: @@ -133,10 +136,11 @@ The other arguments are named: \item \code{fixed}: named numeric vector of parameters that enter the evaluation without derivatives. Default \code{NULL}. \item \code{deriv}: \code{TRUE} (default) returns first derivatives with respect to -\code{pars}. +\code{pars}. Every function of the chain has to be built with +\code{derivMode = "forward"}, see \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. \item \code{deriv2}: \code{TRUE} returns second derivatives as well. Default \code{FALSE}. -Every function of the chain has to be built for them, see the arguments -\code{deriv2} and \code{derivMode} of \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. +Every function of the chain has to be built with +\code{derivMode = "forward-forward"}. \item \code{hessian}: objective functions only, see the table below. Default \code{NULL}. \item \code{sweep}: objective functions only. \code{"forward"} (default) propagates the diff --git a/man/Xd.Rd b/man/Xd.Rd index 27fd5f7d..4e1d8476 100644 --- a/man/Xd.Rd +++ b/man/Xd.Rd @@ -48,10 +48,11 @@ The other arguments are named: \item \code{fixed}: named numeric vector of parameters that enter the evaluation without derivatives. Default \code{NULL}. \item \code{deriv}: \code{TRUE} (default) returns first derivatives with respect to -\code{pars}. +\code{pars}. Every function of the chain has to be built with +\code{derivMode = "forward"}, see \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. \item \code{deriv2}: \code{TRUE} returns second derivatives as well. Default \code{FALSE}. -Every function of the chain has to be built for them, see the arguments -\code{deriv2} and \code{derivMode} of \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. +Every function of the chain has to be built with +\code{derivMode = "forward-forward"}. \item \code{hessian}: objective functions only, see the table below. Default \code{NULL}. \item \code{sweep}: objective functions only. \code{"forward"} (default) propagates the diff --git a/man/Xf.Rd b/man/Xf.Rd index f4167886..2a1b99b7 100644 --- a/man/Xf.Rd +++ b/man/Xf.Rd @@ -77,10 +77,11 @@ The other arguments are named: \item \code{fixed}: named numeric vector of parameters that enter the evaluation without derivatives. Default \code{NULL}. \item \code{deriv}: \code{TRUE} (default) returns first derivatives with respect to -\code{pars}. +\code{pars}. Every function of the chain has to be built with +\code{derivMode = "forward"}, see \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. \item \code{deriv2}: \code{TRUE} returns second derivatives as well. Default \code{FALSE}. -Every function of the chain has to be built for them, see the arguments -\code{deriv2} and \code{derivMode} of \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. +Every function of the chain has to be built with +\code{derivMode = "forward-forward"}. \item \code{hessian}: objective functions only, see the table below. Default \code{NULL}. \item \code{sweep}: objective functions only. \code{"forward"} (default) propagates the diff --git a/man/Xs.Rd b/man/Xs.Rd index 35cd92f8..8e345d00 100644 --- a/man/Xs.Rd +++ b/man/Xs.Rd @@ -90,7 +90,7 @@ condition: the states over \code{times}, with the sensitivities in \code{attr(, "deriv")}, \verb{[time, state, parameter]}, when \code{deriv = TRUE}, and the second-order sensitivities in \code{attr(, "deriv2")}, \verb{[time, state, parameter, parameter]}, when \code{deriv2 = TRUE} (\code{cppDE} -backend, model built with \code{deriv2 = TRUE}). +backend, model built with \code{derivMode = "forward-forward"}). } \description{ Turns an \code{\link[=odemodel]{odemodel()}} into a prediction function that @@ -190,10 +190,11 @@ The other arguments are named: \item \code{fixed}: named numeric vector of parameters that enter the evaluation without derivatives. Default \code{NULL}. \item \code{deriv}: \code{TRUE} (default) returns first derivatives with respect to -\code{pars}. +\code{pars}. Every function of the chain has to be built with +\code{derivMode = "forward"}, see \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. \item \code{deriv2}: \code{TRUE} returns second derivatives as well. Default \code{FALSE}. -Every function of the chain has to be built for them, see the arguments -\code{deriv2} and \code{derivMode} of \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. +Every function of the chain has to be built with +\code{derivMode = "forward-forward"}. \item \code{hessian}: objective functions only, see the table below. Default \code{NULL}. \item \code{sweep}: objective functions only. \code{"forward"} (default) propagates the diff --git a/man/Xt.Rd b/man/Xt.Rd index 3db03a3d..b4325224 100644 --- a/man/Xt.Rd +++ b/man/Xt.Rd @@ -43,10 +43,11 @@ The other arguments are named: \item \code{fixed}: named numeric vector of parameters that enter the evaluation without derivatives. Default \code{NULL}. \item \code{deriv}: \code{TRUE} (default) returns first derivatives with respect to -\code{pars}. +\code{pars}. Every function of the chain has to be built with +\code{derivMode = "forward"}, see \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. \item \code{deriv2}: \code{TRUE} returns second derivatives as well. Default \code{FALSE}. -Every function of the chain has to be built for them, see the arguments -\code{deriv2} and \code{derivMode} of \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. +Every function of the chain has to be built with +\code{derivMode = "forward-forward"}. \item \code{hessian}: objective functions only, see the table below. Default \code{NULL}. \item \code{sweep}: objective functions only. \code{"forward"} (default) propagates the diff --git a/man/Y.Rd b/man/Y.Rd index ab38e60c..3b401e74 100644 --- a/man/Y.Rd +++ b/man/Y.Rd @@ -15,8 +15,6 @@ Y( modelname = NULL, verbose = FALSE, cores = NULL, - deriv = TRUE, - deriv2 = FALSE, derivMode = "forward", outdir = .dmodOutdir() ) @@ -57,25 +55,22 @@ shared object. Default \code{NULL}, which is \code{"obsfn"}, followed by when \code{g} is a list, on Windows only to compile them; \code{NULL} auto-detects. Ignored for a single observation function, which is one source either way.} -\item{deriv}{Logical. If \code{TRUE} (default), build the first derivatives, -returned as \code{attr(, "deriv")}, \verb{[time, observable, parameter]}, when the -call has \code{deriv = TRUE} and \code{derivMode} contains \code{"forward"}. \code{FALSE} -returns none, whatever the call asks.} - -\item{deriv2}{Logical. If \code{TRUE}, build the second derivatives, returned -as \code{attr(, "deriv2")}, \verb{[time, observable, parameter, parameter]}, when -the call has \code{deriv2 = TRUE}; on a function built without them that call -is an error. Requires \code{deriv = TRUE}. Default \code{FALSE}.} - -\item{derivMode}{Which derivative code to build, any of \code{"forward"} -(default), \code{"reverse"} and \code{"forward-reverse"}. +\item{derivMode}{The derivatives to build, one or more of \code{"forward"} +(default), \code{"reverse"}, \code{"forward-forward"} and \code{"forward-reverse"}, or +\code{"none"}, as in \code{\link[=odemodel]{odemodel()}}. \itemize{ -\item \code{"forward"}: the Jacobian; without it the function returns no \code{deriv} -attribute. -\item \code{"reverse"}: needed for \code{sweep = "reverse"}. +\item \code{"forward"}: the Jacobian, \code{attr(, "deriv")}, +\verb{[time, observable, parameter]}. +\item \code{"reverse"}: the vector-Jacobian product of \code{sweep = "reverse"}. +\item \code{"forward-forward"}: the second derivatives, \code{attr(, "deriv2")}, +\verb{[time, observable, parameter, parameter]}, for \code{deriv2 = TRUE}. \item \code{"forward-reverse"}: needed for \code{sweep = "reverse"} with \code{deriv2 = TRUE}. -}} +\item \code{"none"}: values only. +} + +The second-order directions build \code{"forward"} as well. A call that asks +for a derivative not built is an error.} \item{outdir}{Character. Directory for the generated C++ source and the shared object, default \code{getOption("dMod2.outdir")}, else the working @@ -114,10 +109,11 @@ The other arguments are named: \item \code{fixed}: named numeric vector of parameters that enter the evaluation without derivatives. Default \code{NULL}. \item \code{deriv}: \code{TRUE} (default) returns first derivatives with respect to -\code{pars}. +\code{pars}. Every function of the chain has to be built with +\code{derivMode = "forward"}, see \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. \item \code{deriv2}: \code{TRUE} returns second derivatives as well. Default \code{FALSE}. -Every function of the chain has to be built for them, see the arguments -\code{deriv2} and \code{derivMode} of \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. +Every function of the chain has to be built with +\code{derivMode = "forward-forward"}. \item \code{hessian}: objective functions only, see the table below. Default \code{NULL}. \item \code{sweep}: objective functions only. \code{"forward"} (default) propagates the diff --git a/man/constraintL2.Rd b/man/constraintL2.Rd index c8661c5d..de0aa0cd 100644 --- a/man/constraintL2.Rd +++ b/man/constraintL2.Rd @@ -66,10 +66,11 @@ The other arguments are named: \item \code{fixed}: named numeric vector of parameters that enter the evaluation without derivatives. Default \code{NULL}. \item \code{deriv}: \code{TRUE} (default) returns first derivatives with respect to -\code{pars}. +\code{pars}. Every function of the chain has to be built with +\code{derivMode = "forward"}, see \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. \item \code{deriv2}: \code{TRUE} returns second derivatives as well. Default \code{FALSE}. -Every function of the chain has to be built for them, see the arguments -\code{deriv2} and \code{derivMode} of \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. +Every function of the chain has to be built with +\code{derivMode = "forward-forward"}. \item \code{hessian}: objective functions only, see the table below. Default \code{NULL}. \item \code{sweep}: objective functions only. \code{"forward"} (default) propagates the diff --git a/man/constraintStability.Rd b/man/constraintStability.Rd index de70b4bd..2c97dd35 100644 --- a/man/constraintStability.Rd +++ b/man/constraintStability.Rd @@ -14,7 +14,7 @@ constraintStability( ) } \arguments{ -\item{pSS}{A parfn of \code{\link[=Pimpl]{Pimpl()}}, built with \code{deriv2 = TRUE}.} +\item{pSS}{A parfn of \code{\link[=Pimpl]{Pimpl()}}, built with \code{derivMode = "forward-forward"}.} \item{p}{The parfn whose output \code{pSS} reads, or \code{NULL} where \code{pSS} reads the parameters of the objective.} @@ -82,7 +82,7 @@ of the term itself. # The Brusselator rests at x = a, y = b / a, stable while b < 1 + a^2 f <- c(x = "a - (b + 1) * x + x^2 * y", y = "b * x - x^2 * y") old <- setwd(tempdir()) -pSS <- Pimpl(f, deriv2 = TRUE, modelname = "brusselator_ss") +pSS <- Pimpl(f, derivMode = "forward-forward", modelname = "brusselator_ss") p <- P(c(a = "exp(la)", b = "exp(lb)"), modelname = "brusselator_p") compile(pSS, p, output = "brusselator") stab <- constraintStability(pSS, p, weight = 10) diff --git a/man/dModfn.Rd b/man/dModfn.Rd index d7d307fd..d3cfb423 100644 --- a/man/dModfn.Rd +++ b/man/dModfn.Rd @@ -33,10 +33,11 @@ The other arguments are named: \item \code{fixed}: named numeric vector of parameters that enter the evaluation without derivatives. Default \code{NULL}. \item \code{deriv}: \code{TRUE} (default) returns first derivatives with respect to -\code{pars}. +\code{pars}. Every function of the chain has to be built with +\code{derivMode = "forward"}, see \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. \item \code{deriv2}: \code{TRUE} returns second derivatives as well. Default \code{FALSE}. -Every function of the chain has to be built for them, see the arguments -\code{deriv2} and \code{derivMode} of \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. +Every function of the chain has to be built with +\code{derivMode = "forward-forward"}. \item \code{hessian}: objective functions only, see the table below. Default \code{NULL}. \item \code{sweep}: objective functions only. \code{"forward"} (default) propagates the diff --git a/man/datapointL2.Rd b/man/datapointL2.Rd index dd78da71..f090c744 100644 --- a/man/datapointL2.Rd +++ b/man/datapointL2.Rd @@ -73,10 +73,11 @@ The other arguments are named: \item \code{fixed}: named numeric vector of parameters that enter the evaluation without derivatives. Default \code{NULL}. \item \code{deriv}: \code{TRUE} (default) returns first derivatives with respect to -\code{pars}. +\code{pars}. Every function of the chain has to be built with +\code{derivMode = "forward"}, see \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. \item \code{deriv2}: \code{TRUE} returns second derivatives as well. Default \code{FALSE}. -Every function of the chain has to be built for them, see the arguments -\code{deriv2} and \code{derivMode} of \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. +Every function of the chain has to be built with +\code{derivMode = "forward-forward"}. \item \code{hessian}: objective functions only, see the table below. Default \code{NULL}. \item \code{sweep}: objective functions only. \code{"forward"} (default) propagates the diff --git a/man/em.Rd b/man/em.Rd index a4e8b5ff..4630d82f 100644 --- a/man/em.Rd +++ b/man/em.Rd @@ -74,9 +74,9 @@ every argument of \code{\link[=trust]{trust()}} passes, \code{hessianMethod}, \c default \code{TRUE}.} \item{\code{derivMode}}{how FOCEI gets the second derivatives of the volume term: \code{"forward-reverse"} (default), sweeps for models built with -\code{derivMode = c("forward", "reverse", "forward-reverse")}, or +\code{derivMode = c("reverse", "forward-reverse")}, or \code{"forward-forward"}, the second-order sensitivities of models built -with \code{deriv2 = TRUE}. Without the mode asked for the fit takes the +with \code{derivMode = "forward-forward"}. Without the mode asked for the fit takes the other, with a message.} \item{\code{boundary}}{the largest rise of -2 log L at which a variance is set to 0, default 0.1, \code{FALSE} for none. With one grouping and several diff --git a/man/importPEtab.Rd b/man/importPEtab.Rd index 3c67d0d3..6fc82a3b 100644 --- a/man/importPEtab.Rd +++ b/man/importPEtab.Rd @@ -10,7 +10,6 @@ importPEtab( compile = TRUE, cores = 1L, modelname = NULL, - deriv = TRUE, derivMode = "forward", options = NULL, optionsSens = NULL, @@ -34,13 +33,11 @@ Default \code{1}.} \item{modelname}{Base name of the generated files. Default \code{NULL}, the base name of the YAML file.} -\item{deriv}{Logical. If \code{FALSE}, the model is built without sensitivities, -which needs \code{backend = "cppDE"} or \code{"Sundials"}; the objective then has to -be called with \code{deriv = FALSE}. Default \code{TRUE}.} - -\item{derivMode}{Derivative directions to build, passed to \code{\link[=odemodel]{odemodel()}}: -\code{"forward"} (default), \code{"reverse"} or \code{c("forward", "reverse")}. -\code{"reverse"} needs \code{backend = "cppDE"} or \code{"Sundials"}. First order only.} +\item{derivMode}{Derivative directions to build, passed to \code{\link[=odemodel]{odemodel()}}, +\code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}: \code{"forward"} (default), \code{"reverse"}, +\code{c("forward", "reverse")} or \code{"none"}. \code{"reverse"} and \code{"none"} need +\code{backend = "cppDE"} or \code{"Sundials"}; with \code{"none"} the objective has to be +called with \code{deriv = FALSE}. First order only.} \item{options, optionsSens}{Lists passed to \code{\link[=Xs]{Xs()}}: the solver options of every solve and their overrides for the solves with sensitivities. diff --git a/man/msem.Rd b/man/msem.Rd index 4d87b28a..5bf27eab 100644 --- a/man/msem.Rd +++ b/man/msem.Rd @@ -80,9 +80,9 @@ every argument of \code{\link[=trust]{trust()}} passes, \code{hessianMethod}, \c default \code{TRUE}.} \item{\code{derivMode}}{how FOCEI gets the second derivatives of the volume term: \code{"forward-reverse"} (default), sweeps for models built with -\code{derivMode = c("forward", "reverse", "forward-reverse")}, or +\code{derivMode = c("reverse", "forward-reverse")}, or \code{"forward-forward"}, the second-order sensitivities of models built -with \code{deriv2 = TRUE}. Without the mode asked for the fit takes the +with \code{derivMode = "forward-forward"}. Without the mode asked for the fit takes the other, with a message.} \item{\code{boundary}}{the largest rise of -2 log L at which a variance is set to 0, default 0.1, \code{FALSE} for none. With one grouping and several diff --git a/man/normL2.Rd b/man/normL2.Rd index ce0bac51..04d3e460 100644 --- a/man/normL2.Rd +++ b/man/normL2.Rd @@ -127,10 +127,11 @@ The other arguments are named: \item \code{fixed}: named numeric vector of parameters that enter the evaluation without derivatives. Default \code{NULL}. \item \code{deriv}: \code{TRUE} (default) returns first derivatives with respect to -\code{pars}. +\code{pars}. Every function of the chain has to be built with +\code{derivMode = "forward"}, see \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. \item \code{deriv2}: \code{TRUE} returns second derivatives as well. Default \code{FALSE}. -Every function of the chain has to be built for them, see the arguments -\code{deriv2} and \code{derivMode} of \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. +Every function of the chain has to be built with +\code{derivMode = "forward-forward"}. \item \code{hessian}: objective functions only, see the table below. Default \code{NULL}. \item \code{sweep}: objective functions only. \code{"forward"} (default) propagates the diff --git a/man/obsfn.Rd b/man/obsfn.Rd index 56aeb229..1b9dbac0 100644 --- a/man/obsfn.Rd +++ b/man/obsfn.Rd @@ -53,10 +53,11 @@ The other arguments are named: \item \code{fixed}: named numeric vector of parameters that enter the evaluation without derivatives. Default \code{NULL}. \item \code{deriv}: \code{TRUE} (default) returns first derivatives with respect to -\code{pars}. +\code{pars}. Every function of the chain has to be built with +\code{derivMode = "forward"}, see \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. \item \code{deriv2}: \code{TRUE} returns second derivatives as well. Default \code{FALSE}. -Every function of the chain has to be built for them, see the arguments -\code{deriv2} and \code{derivMode} of \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. +Every function of the chain has to be built with +\code{derivMode = "forward-forward"}. \item \code{hessian}: objective functions only, see the table below. Default \code{NULL}. \item \code{sweep}: objective functions only. \code{"forward"} (default) propagates the diff --git a/man/odemodel.Rd b/man/odemodel.Rd index f6b16bd8..3b725546 100644 --- a/man/odemodel.Rd +++ b/man/odemodel.Rd @@ -6,8 +6,6 @@ \usage{ odemodel( f, - deriv = TRUE, - deriv2 = FALSE, derivMode = "forward", forcings = NULL, events = NULL, @@ -24,27 +22,22 @@ odemodel( sides; the names are the states. The functions and operators an equation may use are listed in \link[cppDE:expressions]{cppDE::expressions}.} -\item{deriv}{logical, build first-order sensitivities. Default \code{TRUE}. -\code{FALSE} builds the states alone, for \code{\link[=Xf]{Xf()}}, and \code{derivMode} has no -effect.} - -\item{deriv2}{logical, build second-order sensitivities. Default \code{FALSE}. -\code{TRUE} is the same as adding \code{"forward-forward"} to \code{derivMode}, needs -\code{backend = "cppDE"} and implies \code{deriv = TRUE}.} - \item{derivMode}{character, the derivative directions to build, one or more of: \itemize{ -\item \code{"forward"} (default): sensitivity equations. \code{deriv = TRUE} builds them -also when \code{derivMode} leaves out \code{"forward"}. +\item \code{"forward"} (default): first-order sensitivities. \item \code{"reverse"}: adjoint gradient, needed for \code{obj(..., sweep = "reverse")}. Not available on \code{backend = "deSolve"}. -\item \code{"forward-forward"}: second-order sensitivities. +\item \code{"forward-forward"}: second-order sensitivities, needed for +\code{deriv2 = TRUE} in a call. \code{backend = "cppDE"} only. \item \code{"forward-reverse"}: adjoint Hessian, needed for \code{obj(..., sweep = "reverse", deriv2 = TRUE)}. \code{backend = "cppDE"} only. +\item \code{"none"}: the states alone, for \code{\link[=Xf]{Xf()}}. } -Each direction is compiled separately.} +Each direction is compiled separately. The two second-order directions +build \code{"forward"} as well. A call that asks for a derivative not built is +an error.} \item{forcings}{character, the names of the forcings in \code{f}. Default \code{NULL}. Their data are given to \code{\link[=Xs]{Xs()}} or \code{\link[=Xf]{Xf()}}.} diff --git a/man/parfn.Rd b/man/parfn.Rd index 5414b99f..e65e6c39 100644 --- a/man/parfn.Rd +++ b/man/parfn.Rd @@ -57,10 +57,11 @@ The other arguments are named: \item \code{fixed}: named numeric vector of parameters that enter the evaluation without derivatives. Default \code{NULL}. \item \code{deriv}: \code{TRUE} (default) returns first derivatives with respect to -\code{pars}. +\code{pars}. Every function of the chain has to be built with +\code{derivMode = "forward"}, see \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. \item \code{deriv2}: \code{TRUE} returns second derivatives as well. Default \code{FALSE}. -Every function of the chain has to be built for them, see the arguments -\code{deriv2} and \code{derivMode} of \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. +Every function of the chain has to be built with +\code{derivMode = "forward-forward"}. \item \code{hessian}: objective functions only, see the table below. Default \code{NULL}. \item \code{sweep}: objective functions only. \code{"forward"} (default) propagates the diff --git a/man/prdfn.Rd b/man/prdfn.Rd index d6283b46..7870a283 100644 --- a/man/prdfn.Rd +++ b/man/prdfn.Rd @@ -53,10 +53,11 @@ The other arguments are named: \item \code{fixed}: named numeric vector of parameters that enter the evaluation without derivatives. Default \code{NULL}. \item \code{deriv}: \code{TRUE} (default) returns first derivatives with respect to -\code{pars}. +\code{pars}. Every function of the chain has to be built with +\code{derivMode = "forward"}, see \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. \item \code{deriv2}: \code{TRUE} returns second derivatives as well. Default \code{FALSE}. -Every function of the chain has to be built for them, see the arguments -\code{deriv2} and \code{derivMode} of \code{\link[=odemodel]{odemodel()}}, \code{\link[=Y]{Y()}} and \code{\link[=P]{P()}}. +Every function of the chain has to be built with +\code{derivMode = "forward-forward"}. \item \code{hessian}: objective functions only, see the table below. Default \code{NULL}. \item \code{sweep}: objective functions only. \code{"forward"} (default) propagates the diff --git a/man/trust.Rd b/man/trust.Rd index e554464f..149f6d71 100644 --- a/man/trust.Rd +++ b/man/trust.Rd @@ -185,7 +185,7 @@ a first phase of source \code{"gn"}. A structured phase takes \code{"identity"} the identity matrix, after which the objective is asked for gradients only until a reseed; \code{"exact"} the true Hessian at \code{parinit}, then gradients only. \code{"exact"} needs -\code{deriv2}, see \code{derivMode} in \code{\link[=odemodel]{odemodel()}}. In a first phase +\code{deriv2 = TRUE} in a call, see \code{derivMode} in \code{\link[=odemodel]{odemodel()}}. In a first phase of source \code{"gn"}, \code{"exact"} makes the first step use the exact Hessian at \code{parinit}.} \item{\code{hessianReseed}}{\code{"never"} (default): a stalled diff --git a/tests/testthat/test-EM.R b/tests/testthat/test-EM.R index d7caadf9..0f91e93b 100644 --- a/tests/testthat/test-EM.R +++ b/tests/testthat/test-EM.R @@ -19,22 +19,22 @@ define(tr, "dose <- d", d = dose) } # second derivatives forward over forward and forward over reverse - dm <- c("forward", "reverse", "forward-reverse") + dm <- c("forward", "reverse", "forward-forward", "forward-reverse") g <- Y(c(y = "a + b * dose"), f = NULL, parameters = c("a", "b", "dose"), compile = FALSE, - modelname = "nlmefit_lin_g", deriv2 = TRUE, derivMode = dm) - p <- P(trafo(c("a", "b")), method = "explicit", compile = FALSE, modelname = "nlmefit_lin_p", deriv2 = TRUE, + modelname = "nlmefit_lin_g", derivMode = dm) + p <- P(trafo(c("a", "b")), method = "explicit", compile = FALSE, modelname = "nlmefit_lin_p", derivMode = dm) # with the parameter s of an error model sigma = exp(s) ps <- P(trafo(c("a", "b", "s")), method = "explicit", compile = FALSE, modelname = "nlmefit_lin_ps", - deriv2 = TRUE, derivMode = dm) + derivMode = dm) err <- Y(c(y = "exp(s)"), g, attachInput = FALSE, compile = FALSE, modelname = "nlmefit_lin_err", - deriv2 = TRUE, derivMode = dm) + derivMode = dm) # second derivatives forward over forward only - pf <- P(trafo(c("a", "b")), method = "explicit", compile = FALSE, modelname = "nlmefit_lin_pf", deriv2 = TRUE) + pf <- P(trafo(c("a", "b")), method = "explicit", compile = FALSE, modelname = "nlmefit_lin_pf", derivMode = "forward-forward") # uncorrelated random effects pu <- P(define(insert(branch(define(NULL, "x <- x", x = c("a", "b")), table = tab), a + b ~ 1 + (1 | ID), conditionMatch = "^s"), "dose <- d", d = dose), - method = "explicit", compile = FALSE, modelname = "nlmefit_lin_pu", deriv2 = TRUE, derivMode = dm) + method = "explicit", compile = FALSE, modelname = "nlmefit_lin_pu", derivMode = dm) compile(g, p, ps, err, pf, pu, output = "nlmefit_lin", cores = 2) # random effects at quantiles and noise of mean 0 in every condition: the means of the # conditions, and with them the maximum likelihood of Omega, are the same for any draw and in @@ -573,19 +573,19 @@ test_that("anova tests nested fits and simulate draws data that refit to the est rownames(tab) <- paste(tab$ID, tab$center, sep = "_") tr <- branch(define(NULL, "x <- x", x = "a"), table = tab) tr <- insert(tr, a ~ 1 + (1 | ID) + (1 | center)) - dm <- c("forward", "reverse", "forward-reverse") - g <- Y(c(y = "a"), f = NULL, parameters = "a", compile = FALSE, modelname = "crossed_g", deriv2 = TRUE, + dm <- c("forward", "reverse", "forward-forward", "forward-reverse") + g <- Y(c(y = "a"), f = NULL, parameters = "a", compile = FALSE, modelname = "crossed_g", derivMode = dm) - p <- P(tr, method = "explicit", compile = FALSE, modelname = "crossed_p", deriv2 = TRUE, derivMode = dm) + p <- P(tr, method = "explicit", compile = FALSE, modelname = "crossed_p", derivMode = dm) # the same groupings, nonlinear in the random effects with a proportional error trn <- branch(define(NULL, "x <- x", x = c("a", "s")), table = tab) trn <- insert(trn, "s <- exp(s)") trn <- insert(trn, a ~ 1 + (1 | ID) + (1 | center)) - gn <- Y(c(y = "exp(a)"), f = NULL, parameters = "a", compile = FALSE, modelname = "crossed_gn", deriv2 = TRUE, + gn <- Y(c(y = "exp(a)"), f = NULL, parameters = "a", compile = FALSE, modelname = "crossed_gn", derivMode = dm) - en <- Y(c(y = "s * y"), gn, attachInput = FALSE, compile = FALSE, modelname = "crossed_en", deriv2 = TRUE, + en <- Y(c(y = "s * y"), gn, attachInput = FALSE, compile = FALSE, modelname = "crossed_en", derivMode = dm) - pn <- P(trn, method = "explicit", compile = FALSE, modelname = "crossed_pn", deriv2 = TRUE, derivMode = dm) + pn <- P(trn, method = "explicit", compile = FALSE, modelname = "crossed_pn", derivMode = dm) compile(g, p, gn, en, pn, output = "nlmefit_crossed", cores = 2) # the effects of the three centers spread by construction: three drawn ones leave the maximum # likelihood of their variance at 0 in about one draw of ten diff --git a/tests/testthat/test-EMsparse.R b/tests/testthat/test-EMsparse.R index 792e8485..0e9166f8 100644 --- a/tests/testthat/test-EMsparse.R +++ b/tests/testthat/test-EMsparse.R @@ -23,7 +23,7 @@ dir.create(dir, showWarnings = FALSE) withr::local_dir(dir) # second derivatives forward over forward and forward over reverse - .dm <- c("forward", "reverse", "forward-reverse") + .dm <- c("forward", "reverse", "forward-forward", "forward-reverse") 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"))) @@ -33,52 +33,52 @@ insert(tr, "x <- exp(x)", x = c("k", "A", "s")) } g <- Y(c(y = "A * exp(-k * dose)"), f = NULL, parameters = c("A", "k", "dose"), compile = FALSE, - modelname = "sp_g", deriv2 = TRUE, derivMode = .dm) - err <- Y(c(y = "s"), g, attachInput = FALSE, compile = FALSE, modelname = "sp_err", deriv2 = TRUE, derivMode = .dm) + modelname = "sp_g", derivMode = .dm) + err <- Y(c(y = "s"), g, attachInput = FALSE, compile = FALSE, modelname = "sp_err", derivMode = .dm) pn <- P(insert(base(), A ~ 1 + (1 | ID)), method = "explicit", compile = FALSE, modelname = "sp_normal", - deriv2 = TRUE, derivMode = .dm) + derivMode = .dm) pks <- P(insert(base(), k ~ 1 + (1 | gr(ID, dist = spikeSlab()))), method = "explicit", compile = FALSE, - modelname = "sp_konly", deriv2 = TRUE, derivMode = .dm) + modelname = "sp_konly", derivMode = .dm) ps <- P(insert(base(), k + A ~ 1 + (1 | gr(ID, dist = spikeSlab()))), method = "explicit", - compile = FALSE, modelname = "sp_slab", deriv2 = TRUE, derivMode = .dm) + compile = FALSE, modelname = "sp_slab", derivMode = .dm) psk <- P(insert(base(), k ~ 1 + (1 | gr(ID, dist = dirichletProcess()))), method = "explicit", - compile = FALSE, modelname = "sp_dpcenter", deriv2 = TRUE, derivMode = .dm) + compile = FALSE, modelname = "sp_dpcenter", derivMode = .dm) psm <- P(insert(base(), k ~ 1 + (1 | gr(ID, dist = spikeSlab())), A ~ 1 + (1 | ID)), method = "explicit", - compile = FALSE, modelname = "sp_slabmixed", deriv2 = TRUE, derivMode = .dm) + compile = FALSE, modelname = "sp_slabmixed", derivMode = .dm) pskm <- P(insert(base(), k ~ 1 + (1 | gr(ID, dist = dirichletProcess())), A ~ 1 + (1 | ID)), - method = "explicit", compile = FALSE, modelname = "sp_slabclmixed", deriv2 = TRUE, derivMode = .dm) + method = "explicit", compile = FALSE, modelname = "sp_slabclmixed", derivMode = .dm) psk2 <- P(insert(base(), k + A ~ 1 + (1 | gr(ID, dist = dirichletProcess()))), method = "explicit", - compile = FALSE, modelname = "sp_slabcltwo", deriv2 = TRUE, derivMode = .dm) + compile = FALSE, modelname = "sp_slabcltwo", derivMode = .dm) linear <- function(dist, a = a ~ 1 + (1 | ID)) { tr <- branch(define(NULL, "x <- x", x = c("a", "b")), table = tab) tr <- define(tr, "dose <- d", d = dose) insert(tr, a, b ~ 1 + (1 | gr(ID, dist = dist))) } gl <- Y(c(y = "a + b * dose"), f = NULL, parameters = c("a", "b", "dose"), compile = FALSE, - modelname = "sp_glin", deriv2 = TRUE, derivMode = .dm) - pls <- P(linear(spikeSlab()), method = "explicit", compile = FALSE, modelname = "sp_linslab", deriv2 = TRUE, derivMode = .dm) - pld <- P(linear(dirichletProcess()), method = "explicit", compile = FALSE, modelname = "sp_lindp", deriv2 = TRUE, derivMode = .dm) + modelname = "sp_glin", derivMode = .dm) + pls <- P(linear(spikeSlab()), method = "explicit", compile = FALSE, modelname = "sp_linslab", derivMode = .dm) + pld <- P(linear(dirichletProcess()), method = "explicit", compile = FALSE, modelname = "sp_lindp", derivMode = .dm) # a second observable z = b + c that only the first two groups measure gz <- Y(c(y = "a + b * dose", z = "b + c"), f = NULL, parameters = c("a", "b", "c", "dose"), compile = FALSE, - modelname = "sp_gz", deriv2 = TRUE, derivMode = .dm) + modelname = "sp_gz", derivMode = .dm) reachP <- function(dist, name) { tr <- branch(define(NULL, "x <- x", x = c("a", "b", "c")), table = tab) tr <- define(tr, "dose <- d", d = dose) P(insert(tr, a ~ 1 + (1 | ID), b + c ~ 1 + (1 | gr(ID, dist = dist))), method = "explicit", compile = FALSE, - modelname = name, deriv2 = TRUE, derivMode = .dm) + modelname = name, derivMode = .dm) } pz <- list(spikeSlab = reachP(spikeSlab(), "sp_zslab"), dirichletProcess = reachP(dirichletProcess(), "sp_zdp")) # a state X that a stimulus u drives from 0, u = 0 in the groups L1 and L2, read with a drift w # that only a state at 0 multiplies tabu <- cbind(tab, u = ifelse(tab$ID %in% c("L1", "L2"), 0, 1)) xu <- Xs(odemodel(eqnvec(X = "s * u - dg * X", W = "w * X - dg * W"), modelname = "sp_xu", compile = FALSE, - deriv2 = TRUE, derivMode = .dm)) - gu <- Y(c(y = "X + W + c0"), xu, compile = FALSE, modelname = "sp_gu", deriv2 = TRUE, derivMode = .dm) + derivMode = .dm)) + gu <- Y(c(y = "X + W + c0"), xu, compile = FALSE, modelname = "sp_gu", derivMode = .dm) tru <- branch(define(NULL, "x <- x", x = c("s", "w", "dg", "c0", "u", "X", "W")), table = tabu) tru <- define(tru, "u <- v", v = u) tru <- insert(insert(tru, "X <- 0"), "W <- 0") pu <- P(insert(tru, c0 ~ 1 + (1 | ID), s + w ~ 1 + (1 | gr(ID, dist = spikeSlab()))), method = "explicit", - compile = FALSE, modelname = "sp_pu", deriv2 = TRUE, derivMode = .dm) + compile = FALSE, modelname = "sp_pu", derivMode = .dm) compile(g, err, pn, pks, ps, psk, psm, pskm, psk2, gl, pls, pld, gz, pz$spikeSlab, pz$dirichletProcess, xu, gu, pu, output = "emsparse_models", cores = 2) set.seed(4) diff --git a/tests/testthat/test-Pexpl.R b/tests/testthat/test-Pexpl.R index 86d4e02f..263ed4ff 100644 --- a/tests/testthat/test-Pexpl.R +++ b/tests/testthat/test-Pexpl.R @@ -24,7 +24,7 @@ skip_if_no_compile <- function() { modelname = "test_P_dm_fwd", compile = FALSE) const <- c(A = "1.0", B = "2.5") - p_const_val <- Pexpl(const, deriv = FALSE, compile = FALSE, + p_const_val <- Pexpl(const, derivMode = "none", compile = FALSE, modelname = "noparam_pexpl_val") p_const_fwd <- Pexpl(const, derivMode = "forward", compile = FALSE, modelname = "noparam_pexpl_fwd") @@ -42,13 +42,13 @@ skip_if_no_compile <- function() { # The mixed trafo again, passing every input it does not map through. p_thru <- P(eqnvec(A = "a^2", k = "a * b"), condition = "C1", - attachInput = TRUE, deriv2 = TRUE, + attachInput = TRUE, derivMode = "forward-forward", modelname = "test_P_thru", compile = FALSE) # outputs whose first derivative vanishes at b = 0 while the second does not - p_kink <- Pexpl(c(a = "b^2", c = "exp(b)*d"), deriv2 = TRUE, + p_kink <- Pexpl(c(a = "b^2", c = "exp(b)*d"), derivMode = "forward-forward", modelname = "test_P_kink", compile = FALSE) - p_ksum <- Pexpl(c(y = "a + c"), deriv2 = TRUE, + p_ksum <- Pexpl(c(y = "a + c"), derivMode = "forward-forward", modelname = "test_P_ksum", compile = FALSE) compile(p_mix, p_rev, p_fwd, p_const_val, p_const_fwd, x_full, p_full, g_full, @@ -124,9 +124,10 @@ test_that("Pexpl derivMode 'reverse' and 'forward' agree on the value", { pfn_fwd <- fx$p_fwd outer <- c(a = 0.3, b = -0.5) - i_rev <- pfn_rev(outer, deriv = TRUE)$C1 + i_rev <- pfn_rev(outer, deriv = FALSE)$C1 i_fwd <- pfn_fwd(outer, deriv = TRUE)$C1 expect_equal(as.numeric(i_rev), as.numeric(i_fwd), tolerance = 1e-12) + expect_error(pfn_rev(outer), "Pexpl\\(\\) was built without derivMode = \"forward\"") J <- attr(i_fwd, "deriv") expect_equal(unname(J[c("A", "k"), c("a", "b")]), diag(exp(c(0.3, -0.5))), tolerance = 1e-12) @@ -250,7 +251,7 @@ test_that("getParameters(Y * Xs * P) equals getParameters(P) (outer-pars view)", test_that("Pexpl with pure-numeric trafo evaluates (values and forward)", { fx <- .pexpl_fx() - out_val <- fx$p_const_val(c(dummy = 1.0)) + out_val <- fx$p_const_val(c(dummy = 1.0), deriv = FALSE) expect_equal(unclass(out_val[[1]])[c("A", "B")], c(A = 1.0, B = 2.5)) out_fwd <- fx$p_const_fwd(c(dummy = 1.0)) diff --git a/tests/testthat/test-Pimpl.R b/tests/testthat/test-Pimpl.R index 15b4b31a..10d212d1 100644 --- a/tests/testthat/test-Pimpl.R +++ b/tests/testthat/test-Pimpl.R @@ -68,17 +68,17 @@ pp_models <- function() { lin <- Pimpl(c(x = "x - a"), parameters = "a", modelname = mn("lin"), verbose = FALSE) d2 <- Pimpl(c(C = "k1*(totA - C)*(totB - C) - km*C"), - parameters = c("k1","km","totA","totB"), deriv2 = TRUE, + parameters = c("k1","km","totA","totB"), derivMode = "forward-forward", modelname = mn("d2"), verbose = FALSE, controlsPTC = list(reltol = 1e-13)) d2_2 <- Pimpl(c(x1 = "a*x1 - b*x2 - 1", x2 = "x1*x2 - c"), - parameters = c("a","b","c"), deriv2 = TRUE, + parameters = c("a","b","c"), derivMode = "forward-forward", modelname = mn("d2_2"), verbose = FALSE, controlsPTC = list(reltol = 1e-13)) el_AB <- eqnlist() |> addReaction("A", "B", "k*A") |> addReaction("B", "A", "km*B") - d2_cq <- Pimpl(el_AB, parameters = c("k","km"), deriv2 = TRUE, + d2_cq <- Pimpl(el_AB, parameters = c("k","km"), derivMode = "forward-forward", modelname = mn("d2_cq"), verbose = FALSE, controlsPTC = list(reltol = 1e-13)) moiety2_im <- Pimpl(el_2moiety, modelname = mn("2moiety_im")) @@ -93,7 +93,7 @@ pp_models <- function() { recycle <- Pimpl(el_recycle, modelname = mn("recycle")) sing <- Pimpl(c(x1 = "x1 + x2 - s", x2 = "x1 + x2 - s"), parameters = "s", - deriv2 = FALSE, modelname = mn("sing"), verbose = FALSE, + modelname = mn("sing"), verbose = FALSE, controlsPTC = list(positive = FALSE)) noroot <- Pimpl(c(x = "x*x + 1"), parameters = character(0), @@ -114,7 +114,7 @@ pp_models <- function() { modelname = mn("px_same"), verbose = FALSE) # a root whose first derivative vanishes at a = 1 while the second does not - kink <- Pimpl(c(x = "(a-1)^2 + 1 - x"), parameters = "a", deriv2 = TRUE, + kink <- Pimpl(c(x = "(a-1)^2 + 1 - x"), parameters = "a", derivMode = "forward-forward", modelname = mn("kink"), verbose = FALSE, controlsPTC = list(positive = FALSE)) @@ -128,7 +128,7 @@ pp_models <- function() { el_vol <- eqnlist() |> assignCompartment(B = "nuc", volume = "V") |> addReaction("A", "B", "k1*A") |> addReaction("B", "A", "k2*B") - vol <- Pimpl(el_vol, modelname = mn("vol"), deriv2 = TRUE, verbose = FALSE) + vol <- Pimpl(el_vol, modelname = mn("vol"), derivMode = "forward-forward", verbose = FALSE) # a conserved cycle driven by a species that is structurally zero at the steady state el_rest <- eqnlist() |> @@ -146,21 +146,21 @@ pp_models <- function() { # the Brusselator: x = a, y = b / a, with eigenvalues of real part (b - 1 - a^2) / 2 while complex bruss <- Pimpl(c(x = "a - (b + 1) * x + x^2 * y", y = "b * x - x^2 * y"), modelname = mn("bruss"), - deriv2 = TRUE, verbose = FALSE) + derivMode = "forward-forward", verbose = FALSE) bruss_p <- P(c(a = "exp(la)", b = "exp(lb)"), modelname = mn("bruss_p")) # a real eigenvalue through 0 where two roots exchange stability, next to a mode that stays trans <- Pimpl(c(x = "x * (q - x)", y = "x - y"), parameters = "q", modelname = mn("trans"), - deriv2 = TRUE, verbose = FALSE, controlsPTC = list(positive = FALSE)) + derivMode = "forward-forward", verbose = FALSE, controlsPTC = list(positive = FALSE)) # the same steady state as a flow with a stable root required, passing a parameter on, which # differs between two conditions bruss_s <- Pimpl(c(x = "a - (b + 1) * x + x^2 * y", y = "b * x - x^2 * y"), parameters = c("a", "b", "s"), - flow = TRUE, modelname = mn("bruss_s"), deriv2 = TRUE, verbose = FALSE) + flow = TRUE, modelname = mn("bruss_s"), derivMode = "forward-forward", 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) + derivMode = "forward-forward", 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, @@ -723,7 +723,7 @@ test_that("Pimpl solves a network whose R-Smad rows barely turn over", { fx <- readRDS(test_path("fixtures", "pimpl_smad_row.rds")) oldwd <- setwd(.dmod_fx_workdir()); on.exit(setwd(oldwd), add = TRUE) mn <- paste0("test_pp_smadrow_", as.integer(Sys.time())) - pf <- Pimpl(fx$reactions, forcings = fx$forcings, deriv = FALSE, modelname = mn, + pf <- Pimpl(fx$reactions, forcings = fx$forcings, derivMode = "none", modelname = mn, controlsPTC = list(nStarts = 0L)) compile(pf, output = mn, cores = test_cores()) out <- pf(fx$pv, deriv = FALSE)[[1]] diff --git a/tests/testthat/test-Y.R b/tests/testthat/test-Y.R index b1e04774..6bab1c72 100644 --- a/tests/testthat/test-Y.R +++ b/tests/testthat/test-Y.R @@ -89,13 +89,13 @@ test_that("Y derivMode 'reverse' and 'forward' agree on a nonlinear observable", times <- c(0, 1, 2, 5) pars <- c(A = 1.4, k = 0.3) - o_sym <- prd_sym (times = times, pars = pars, deriv = TRUE) - o_dual <- prd_dual(times = times, pars = pars, deriv = TRUE) + o_sym <- prd_sym (times = times, pars = pars, deriv = FALSE) + o_dual <- prd_dual(times = times, pars = pars, deriv = FALSE) expect_equal(o_sym$C1[, "y"], o_dual$C1[, "y"], tolerance = 1e-12) # The reverse build has no forward entries, the forward one does. - expect_null(attr(o_sym$C1, "deriv")) - expect_false(is.null(attr(o_dual$C1, "deriv"))) + expect_error(prd_sym(times = times, pars = pars), "Y\\(\\) was built without derivMode = \"forward\"") + expect_false(is.null(attr(prd_dual(times = times, pars = pars)$C1, "deriv"))) }) diff --git a/tests/testthat/test-constructor-deriv-flag.R b/tests/testthat/test-constructor-deriv-flag.R index 42ee4f29..f2b4903b 100644 --- a/tests/testthat/test-constructor-deriv-flag.R +++ b/tests/testthat/test-constructor-deriv-flag.R @@ -1,6 +1,5 @@ -# Constructor-level `deriv` gating for P, Pexpl, Pimpl and Y, as for `deriv2`: -# the constructor decides whether first-order sensitivities exist, and a call -# asking for what was not built errors. +# derivMode selects what a constructor builds; deriv, deriv2 and sweep of a call +# select what the call computes, and a call that asks for what was not built errors. skip_if_no_compile <- function() { testthat::skip_if_not_installed("cppDE") @@ -18,79 +17,114 @@ ctor_models <- local({ withr::local_dir(dir) nm <- function(x) paste0(x, "_", as.integer(Sys.time())) - pexpl <- Pexpl(c(A = "a * x", B = "b + y"), deriv = FALSE, - modelname = nm("test_pexpl_nod1"), derivMode = "forward", - verbose = FALSE) - pimpl <- Pimpl(c(x = "x - a"), parameters = "a", deriv = FALSE, + pexpl <- Pexpl(c(A = "a * x", B = "b + y"), modelname = nm("test_pexpl_nod1"), + derivMode = "none", verbose = FALSE) + pimpl <- Pimpl(c(x = "x - a"), parameters = "a", derivMode = "none", modelname = nm("test_pimpl_nod1"), verbose = FALSE) gfn <- Y(c(obs = "k * A"), states = c("A", "time"), parameters = "k", - deriv = FALSE, modelname = nm("test_y_nod1"), - derivMode = "forward", verbose = FALSE, attachInput = FALSE) - pdisp <- P(c(A = "a * x"), method = "explicit", deriv = FALSE, + modelname = nm("test_y_nod1"), derivMode = "none", verbose = FALSE, + attachInput = FALSE) + pdisp <- P(c(A = "a * x"), method = "explicit", derivMode = "none", modelname = nm("test_P_nod1"), verbose = FALSE) - compile(pexpl, pimpl, gfn, pdisp, output = nm("ctor_models"), - cores = test_cores()) - - cache <<- list(pexpl = pexpl, pimpl = pimpl, gfn = gfn, - pdisp = pdisp) + f <- eqnvec(A = "-k1*A", B = "k1*A - k2*B") + mff <- odemodel(f, modelname = nm("dm_ode"), derivMode = "forward-forward", + compile = FALSE) + mrev <- odemodel(f, modelname = nm("dm_rev"), derivMode = "reverse", compile = FALSE) + gff <- Y(c(obsB = "s*B"), f, modelname = nm("dm_obs"), derivMode = "forward-forward") + tr <- c(A = "exp(lA)", B = "0", k1 = "exp(lk1)", k2 = "exp(lk2)", s = "exp(ls)") + pff <- P(tr, condition = "C1", modelname = nm("dm_p"), derivMode = "forward-forward") + pfw <- P(tr, condition = "C1", modelname = nm("dm_pf")) + xff <- Xs(mff, options = list(atol = 1e-10, rtol = 1e-10)) + xrev <- Xs(mrev) + + compile(pexpl, pimpl, gfn, pdisp, xff, xrev, gff, pff, pfw, + output = nm("ctor_models"), cores = test_cores()) + + data <- as.datalist(data.frame(name = "obsB", time = c(0.5, 1, 2, 4), + value = c(0.8, 1.1, 0.9, 0.5), sigma = 0.1, + condition = "C1")) + cache <<- list(pexpl = pexpl, pimpl = pimpl, gfn = gfn, pdisp = pdisp, + xff = xff, xrev = xrev, gff = gff, pff = pff, pfw = pfw, data = data, + pars = c(lA = log(2), lk1 = log(0.6), lk2 = log(0.3), ls = log(1.5))) cache } }) -test_that("Pexpl(deriv = FALSE) yields a parvec without deriv attribute", { - skip_if_no_compile() - pf <- ctor_models()$pexpl - out <- pf(c(a = 2, b = 3, x = 4, y = 5)) - expect_null(attr(out[[1]], "deriv")) - # Default runtime deriv = TRUE is silently capped by the constructor: - # no error, just no deriv attribute on the result. - out2 <- pf(c(a = 2, b = 3, x = 4, y = 5), deriv = TRUE) - expect_null(attr(out2[[1]], "deriv")) +test_that("constructors reject deriv and deriv2 as build arguments", { + expect_error(odemodel(eqnvec(A = "-k*A"), deriv = FALSE, compile = FALSE), + "are not build arguments; derivMode selects") + expect_error(P(c(A = "k"), method = "explicit", deriv2 = TRUE), + "`deriv2` is not an argument; derivMode selects") + expect_error(P(c(A = "k"), method = "implicit", deriv = FALSE), + "are not build arguments; derivMode selects") + expect_error(Pexpl(c(A = "x"), deriv2 = TRUE), "unused argument") + expect_error(Y(c(obs = "A"), states = c("A", "time"), deriv2 = TRUE), "unused argument") + # `deriv` matches derivMode partially, a logical value names the change + expect_error(Pimpl(c(x = "x - a"), parameters = "a", deriv = FALSE), + "`deriv` and `deriv2` are not build arguments") + expect_error(Y(c(obs = "A"), states = c("A", "time"), deriv = TRUE), + "`deriv` and `deriv2` are not build arguments") }) -test_that("Pimpl(deriv = FALSE) drops the IFT chain rule from output", { - skip_if_no_compile() - pf <- ctor_models()$pimpl - out <- pf(c(a = 1.5, x = 0.5)) - expect_null(attr(out[[1]], "deriv")) +test_that("derivMode = \"none\" combines with no other direction", { + expect_error(Pexpl(c(A = "x"), derivMode = c("none", "forward")), "none") + expect_error(Y(c(obs = "A"), states = c("A", "time"), derivMode = c("reverse", "none")), + "none") + expect_error(P(c(A = "k"), method = "explicit", derivMode = character(0)), "derivMode") }) -test_that("Y(deriv = FALSE) produces output without deriv attribute", { +test_that("functions built with derivMode = \"none\" return values and refuse derivatives", { skip_if_no_compile() - gfn <- ctor_models()$gfn + m <- ctor_models() + pars <- c(a = 2, b = 3, x = 4, y = 5) + out <- m$pexpl(pars, deriv = FALSE) + expect_equal(unname(unclass(out[[1]])[c("A", "B")]), c(8, 8)) + expect_null(attr(out[[1]], "deriv")) + expect_error(m$pexpl(pars), "Pexpl\\(\\) was built without derivMode = \"forward\"") - prd <- structure( - cbind(time = c(0, 1), A = c(1, 2)), - parameters = structure(c(k = 1.5), fixed = NULL), - class = c("prdframe", "matrix", "array")) + expect_equal(unname(unclass(m$pimpl(c(a = 1.5, x = 0.5), deriv = FALSE)[[1]])["x"]), 1.5) + expect_error(m$pimpl(c(a = 1.5, x = 0.5)), "Pimpl\\(\\) was built without derivMode = \"forward\"") - res <- gfn(out = prd, pars = c(k = 1.5)) - expect_null(attr(res[[1]], "deriv")) -}) + expect_null(attr(m$pdisp(c(a = 2, x = 3), deriv = FALSE)[[1]], "deriv")) + expect_error(m$pdisp(c(a = 2, x = 3)), "derivMode = \"forward\"") + prd <- structure(cbind(time = c(0, 1), A = c(1, 2)), + parameters = structure(c(k = 1.5), fixed = NULL), + class = c("prdframe", "matrix", "array")) + res <- m$gfn(out = prd, pars = c(k = 1.5), deriv = FALSE) + expect_equal(unname(res[[1]][, "obs"]), c(1.5, 3)) + expect_error(m$gfn(out = prd, pars = c(k = 1.5)), "Y\\(\\) was built without derivMode = \"forward\"") +}) -test_that("Constructors reject deriv = FALSE combined with deriv2 = TRUE", { - expect_error(Pexpl(c(A = "x"), deriv = FALSE, deriv2 = TRUE, compile = FALSE), - "requires deriv = TRUE") - expect_error(Pimpl(c(x = "x - a"), parameters = "a", deriv = FALSE, deriv2 = TRUE), - "requires deriv = TRUE") - expect_error(Y(c(obs = "A"), states = c("A", "time"), - deriv = FALSE, deriv2 = TRUE), - "requires deriv = TRUE") - expect_error(P(c(A = "k"), method = "explicit", - deriv = FALSE, deriv2 = TRUE), - "requires deriv = TRUE") +test_that("a call asking for an unbuilt direction names the missing derivMode", { + skip_if_no_compile() + m <- ctor_models() + times <- c(0, 1, 2) + inner <- c(A = 2, B = 0, k1 = 0.6, k2 = 0.3) + expect_error(m$xrev(times, inner), "derivMode = \"forward\"") + expect_null(attr(m$xrev(times, inner, deriv = FALSE)[[1]], "deriv")) + expect_error(m$pfw(m$pars, deriv2 = TRUE), "derivMode = \"forward-forward\"") + obj <- normL2(m$data, m$gff * m$xff * m$pff) + expect_error(obj(m$pars, sweep = "reverse"), "derivMode = \"reverse\"") }) -test_that("P() dispatcher forwards deriv to each method", { +test_that("derivMode = \"forward-forward\" gives the Hessian of deriv2 = TRUE in dMod2 0.16.0", { skip_if_no_compile() - pf <- ctor_models()$pdisp - out <- pf(c(a = 2, x = 3)) - expect_null(attr(out[[1]], "deriv")) + m <- ctor_models() + obj <- normL2(m$data, m$gff * m$xff * m$pff) + out <- obj(m$pars, deriv2 = TRUE) + # value and exact Hessian of the same objective built with deriv2 = TRUE in dMod2 0.16.0 + ref <- matrix(c(1496.45262699787, 577.328918012139, -620.715428312784, 1496.45262699787, + 577.328918012139, 164.606366756938, -196.700167236959, 577.328918012139, + -620.715428312784, -196.700167236959, 167.720578617145, -620.715428312784, + 1496.45262699787, 577.328918012139, -620.715428312784, 1496.45262699787), + 4, 4, dimnames = rep(list(c("lA", "lk1", "lk2", "ls")), 2)) + expect_equal(out$value, 82.3524114951828, tolerance = 1e-10) + expect_equal(out$hessian[rownames(ref), colnames(ref)], ref, tolerance = 1e-10) }) diff --git a/tests/testthat/test-deriv2.R b/tests/testthat/test-deriv2.R index ab6e6ee3..127a4384 100644 --- a/tests/testthat/test-deriv2.R +++ b/tests/testthat/test-deriv2.R @@ -19,40 +19,40 @@ d2_models <- local({ decay <- nm("d2_decay") equil <- nm("d2_equil") - m <- odemodel(f, modelname = decay, backend = "cppDE", deriv2 = TRUE, + m <- odemodel(f, modelname = decay, backend = "cppDE", derivMode = "forward-forward", verbose = FALSE, compile = FALSE) xdes <- Xs(odemodel(f, modelname = nm("d2_decay_des"), backend = "deSolve", verbose = FALSE, compile = FALSE)) yfwd <- Y(c(y = "a*x^2 + b*x"), states = "x", parameters = c("a", "b"), - modelname = nm("d2_obs_fwd"), deriv2 = TRUE, - derivMode = "forward", attachInput = FALSE) + modelname = nm("d2_obs_fwd"), + derivMode = "forward-forward", attachInput = FALSE) yobs <- Y(c(y = "a*x^2 + b*x"), f = f, parameters = c("a", "b"), - modelname = nm("d2_obs"), deriv2 = TRUE, attachInput = FALSE) + modelname = nm("d2_obs"), derivMode = "forward-forward", attachInput = FALSE) pabc <- Pexpl(c(a = "exp(la)", b = "la^2 + lb", c = "la*lb"), parameters = NULL, modelname = nm("d2_pexpl"), - deriv2 = TRUE, derivMode = "forward") + derivMode = "forward-forward") ppass <- Pexpl(c(a = "exp(la)", b = "la^2 + lb"), parameters = c("la", "lb"), - modelname = nm("d2_pexpl_pass"), deriv2 = TRUE, - derivMode = "forward") + modelname = nm("d2_pexpl_pass"), + derivMode = "forward-forward") pnod2 <- Pexpl(c(a = "exp(la)"), parameters = NULL, - modelname = nm("d2_pexpl_nod2"), deriv2 = FALSE, + modelname = nm("d2_pexpl_nod2"), derivMode = "forward") plog <- Pexpl(c(x = "exp(lx)", k = "exp(lk)", a = "la", b = "lb"), parameters = NULL, modelname = nm("d2_pexpl_log"), - deriv2 = TRUE, derivMode = "forward", condition = "C1") + derivMode = "forward-forward", condition = "C1") pid <- Pexpl(c(x = "x", k = "k", a = "a", b = "b"), parameters = NULL, - modelname = nm("d2_pexpl_id"), deriv2 = TRUE, - derivMode = "forward", condition = "C1") + modelname = nm("d2_pexpl_id"), + derivMode = "forward-forward", condition = "C1") pcon <- Pexpl(c(a = "exp(la)"), parameters = NULL, - modelname = nm("d2_pexpl_con"), deriv2 = TRUE, - derivMode = "forward") + modelname = nm("d2_pexpl_con"), + derivMode = "forward-forward") peq <- Pimpl(c(x = "-k * x + s"), parameters = c("k", "s"), flow = TRUE, - modelname = equil, deriv2 = TRUE, verbose = FALSE) + modelname = equil, derivMode = "forward-forward", verbose = FALSE) peq_nod2 <- Pimpl(c(x = "-k * x + s"), parameters = c("k", "s"), flow = TRUE, - modelname = nm("d2_equil_nod2"), deriv2 = FALSE, verbose = FALSE) + modelname = nm("d2_equil_nod2"), verbose = FALSE) compile(m, xdes, yfwd, yobs, pabc, ppass, pnod2, plog, pid, pcon, peq, peq_nod2, output = nm("deriv2_models"), cores = test_cores()) @@ -94,7 +94,7 @@ test_that("Xs.cppDE deriv2 reproduces linear-decay analytical Hessian", { expect_equal(d2[, "x", "k", "x"], unname(ref_H_xk), tolerance = 1e-7) }) -test_that("odemodel(deriv2 = TRUE) emits , _s, _s2 and Xs.cppDE dispatches", { +test_that("odemodel(derivMode = \"forward-forward\") emits , _s, _s2 and Xs.cppDE dispatches", { d <- d2_models() m <- d$m src <- file.path(d$dir, d$decay) @@ -219,10 +219,10 @@ test_that("[.parvec and c.parvec propagate deriv2 attributes", { tolerance = 1e-12) }) -test_that("Pexpl(deriv2 = FALSE) refuses deriv2 = TRUE at call time", { +test_that("Pexpl(derivMode = \"forward\") refuses deriv2 = TRUE at call time", { p <- d2_models()$pnod2 expect_error(p(c(la = 0.1), deriv2 = TRUE), - "deriv2 = FALSE") + "derivMode = \"forward-forward\"") }) @@ -252,7 +252,7 @@ test_that("Pimpl deriv2 reproduces analytical equilibrium Hessian", { H_ref, tolerance = 1e-10) }) -test_that("Pimpl(deriv2 = TRUE) returns the Hessian only when asked", { +test_that("Pimpl(derivMode = \"forward-forward\") returns the Hessian only when asked", { p <- d2_models()$peq pars <- c(k = 0.5, s = 2.0, x = 1.0) r1 <- p(pars, deriv = TRUE, deriv2 = FALSE)[[1]] @@ -263,10 +263,10 @@ test_that("Pimpl(deriv2 = TRUE) returns the Hessian only when asked", { expect_equal(attr(r1, "deriv"), attr(r2, "deriv"), tolerance = 1e-6) }) -test_that("Pimpl(deriv2 = FALSE) refuses deriv2 = TRUE at call time", { +test_that("Pimpl(derivMode = \"forward\") refuses deriv2 = TRUE at call time", { p <- d2_models()$peq_nod2 expect_error(p(c(k = 0.5, s = 2, x = 1), deriv2 = TRUE), - "deriv2 = TRUE") + "derivMode = \"forward-forward\"") }) diff --git a/tests/testthat/test-fn-composition-protocol.R b/tests/testthat/test-fn-composition-protocol.R index 1bc77e45..83777e75 100644 --- a/tests/testthat/test-fn-composition-protocol.R +++ b/tests/testthat/test-fn-composition-protocol.R @@ -241,8 +241,8 @@ test_that("deriv2 and cores survive a sum of objectives", { # deriv2 reaches the chain, which was built without it and says so, rather # than the sum returning the Gauss-Newton Hessian. - expect_error((obj + pri)(p, deriv = TRUE, deriv2 = TRUE), "deriv2") - expect_error(obj(p, deriv = TRUE, deriv2 = TRUE), "deriv2") + expect_error((obj + pri)(p, deriv = TRUE, deriv2 = TRUE), "derivMode = \"forward-forward\"") + expect_error(obj(p, deriv = TRUE, deriv2 = TRUE), "derivMode = \"forward-forward\"") # cores reaches the operands the same way expect_equal((obj + pri)(p, cores = 2L)$value, (obj + pri)(p)$value, diff --git a/tests/testthat/test-fnBehaviour.R b/tests/testthat/test-fnBehaviour.R index c3b300e4..5c36cf02 100644 --- a/tests/testthat/test-fnBehaviour.R +++ b/tests/testthat/test-fnBehaviour.R @@ -79,7 +79,7 @@ test_that("Xs on deSolve reports events given outside the odemodel", { test_that("Xf on deSolve starts states missing from pars at zero", { withr::local_dir(tempdir()) f <- eqnlist() |> addReaction("A", "B", "k*A") |> addReaction("", "C", "1") - m <- odemodel(f, modelname = "fnb_xf", backend = "deSolve", deriv = FALSE, + m <- odemodel(f, modelname = "fnb_xf", backend = "deSolve", derivMode = "none", compile = FALSE) x <- Xf(m) compile(x) diff --git a/tests/testthat/test-focei.R b/tests/testthat/test-focei.R index ee2fbd88..0ec3298d 100644 --- a/tests/testthat/test-focei.R +++ b/tests/testthat/test-focei.R @@ -16,7 +16,7 @@ withr::local_dir(dir) trafo <- function(pars, tab) branch(define(NULL, "x <- x", x = pars), table = tab) # second derivatives forward over forward and forward over reverse - dm <- c("forward", "reverse", "forward-reverse") + dm <- c("forward", "reverse", "forward-forward", "forward-reverse") # one-compartment model with first-order absorption, dose per subject th <- datasets::Theoph @@ -28,9 +28,9 @@ reactions <- addReaction(reactions, "", "Cc", "Ka * Ag / V", "appearance") reactions <- addReaction(reactions, "Cc", "", "Cl/V * Cc", "elimination") th_x <- Xs(odemodel(reactions, modelname = "theoph_cppreg", compile = FALSE, - backend = "cppDE", deriv2 = TRUE, derivMode = c(dm, "forward-forward"))) - th_g <- Y(c(y = "Cc"), th_x, modelname = "theoph_cppreg_obs", compile = FALSE, deriv2 = TRUE, derivMode = dm) - th_err <- Y(eqnvec(y = "sigma_add"), th_g, attachInput = FALSE, compile = FALSE, deriv2 = TRUE, + backend = "cppDE", derivMode = dm)) + th_g <- Y(c(y = "Cc"), th_x, modelname = "theoph_cppreg_obs", compile = FALSE, derivMode = dm) + th_err <- Y(eqnvec(y = "sigma_add"), th_g, attachInput = FALSE, compile = FALSE, modelname = "theoph_cppreg_err", derivMode = dm) th_tr <- trafo(c("Ka", "V", "Cl", "Ag", "Cc", "sigma_add"), data.frame(ID = th_subj, dose = doses, row.names = th_subj)) @@ -38,35 +38,35 @@ th_tr <- insert(th_tr, "Cc <- 0") th_tr <- insert(th_tr, "x <- exp(x)", x = c("Ka", "V", "Cl", "sigma_add")) th_tr <- insert(th_tr, Ka + V + Cl ~ 1 + (1 | ID)) - th_p <- P(th_tr, method = "explicit", compile = FALSE, modelname = "theoph_formula_p", deriv2 = TRUE, + th_p <- P(th_tr, method = "explicit", compile = FALSE, modelname = "theoph_formula_p", derivMode = dm) # one-compartment iv bolus with proportional error, three subjects se_subj <- c("A", "B", "C") reactions <- addReaction(eqnlist(), "Cc", "", "Cl/V * Cc", "elimination") se_ode <- odemodel(reactions, modelname = "sigeta_ode", compile = FALSE, backend = "cppDE", - deriv2 = TRUE, derivMode = c(dm, "forward-forward")) + derivMode = dm) se_x <- Xs(se_ode) - se_g <- Y(c(y = "Cc"), se_x, modelname = "sigeta_obs", compile = FALSE, deriv2 = TRUE, derivMode = dm) + se_g <- Y(c(y = "Cc"), se_x, modelname = "sigeta_obs", compile = FALSE, derivMode = dm) se_err <- Y(eqnvec(y = "sigma_prop * y"), se_g, attachInput = FALSE, compile = FALSE, - deriv2 = TRUE, modelname = "sigeta_err", derivMode = dm) + modelname = "sigeta_err", derivMode = dm) se_tr <- trafo(c("V", "Cl", "Cc", "sigma_prop"), data.frame(ID = se_subj, dose = 100, row.names = se_subj)) se_tr <- insert(se_tr, "Cc <- dose / V", dose = dose) se_tr <- insert(se_tr, "x <- exp(x)", x = c("V", "Cl", "sigma_prop")) se_tr <- insert(se_tr, V ~ 1 + (1 | ID)) - se_p <- P(se_tr, method = "explicit", compile = FALSE, modelname = "sigeta_p", deriv2 = TRUE, derivMode = dm) + se_p <- P(se_tr, method = "explicit", compile = FALSE, modelname = "sigeta_p", derivMode = dm) # the same with an observable and an error model that read the time - se_gt <- Y(c(y = "Cc * exp(-b_t * time)"), se_x, modelname = "sigeta_obs_t", compile = FALSE, deriv2 = TRUE, + se_gt <- Y(c(y = "Cc * exp(-b_t * time)"), se_x, modelname = "sigeta_obs_t", compile = FALSE, derivMode = dm) se_errt <- Y(eqnvec(y = "sigma_prop * y + s_t * time"), se_gt, attachInput = FALSE, compile = FALSE, - deriv2 = TRUE, modelname = "sigeta_err_t", derivMode = dm) + modelname = "sigeta_err_t", derivMode = dm) se_trt <- trafo(c("V", "Cl", "Cc", "sigma_prop", "b_t", "s_t"), data.frame(ID = se_subj, dose = 100, row.names = se_subj)) se_trt <- insert(se_trt, "Cc <- dose / V", dose = dose) se_trt <- insert(se_trt, "x <- exp(x)", x = c("V", "Cl", "sigma_prop", "b_t", "s_t")) se_trt <- insert(se_trt, V ~ 1 + (1 | ID)) - se_pt <- P(se_trt, method = "explicit", compile = FALSE, modelname = "sigeta_p_t", deriv2 = TRUE, + se_pt <- P(se_trt, method = "explicit", compile = FALSE, modelname = "sigeta_p_t", derivMode = dm) # parent / metabolite chain A -> B -> 0, both observed, three subjects @@ -74,9 +74,8 @@ reactions <- eqnlist() reactions <- addReaction(reactions, "A", "B", "ka * A", "absorption") reactions <- addReaction(reactions, "B", "", "ke * B", "elimination") - mo_x <- Xs(odemodel(reactions, modelname = "mo_ode", compile = FALSE, backend = "cppDE", - deriv2 = FALSE)) - mo_g <- Y(c(yA = "A", yB = "B"), mo_x, modelname = "mo_obs", compile = FALSE, deriv2 = FALSE) + mo_x <- Xs(odemodel(reactions, modelname = "mo_ode", compile = FALSE, backend = "cppDE")) + mo_g <- Y(c(yA = "A", yB = "B"), mo_x, modelname = "mo_obs", compile = FALSE) mo_err <- Y(eqnvec(yA = "sigA", yB = "sigB"), mo_g, attachInput = FALSE, compile = FALSE, modelname = "mo_err") mo_tr <- trafo(c("ka", "ke", "A", "B", "sigA", "sigB"), @@ -85,7 +84,7 @@ mo_tr <- insert(mo_tr, "B <- 0") mo_tr <- insert(mo_tr, "x <- exp(x)", x = c("ka", "ke", "sigA", "sigB")) mo_tr <- insert(mo_tr, ka + ke ~ 1 + (1 | ID)) - mo_p <- P(mo_tr, method = "explicit", compile = FALSE, modelname = "mo_p", deriv2 = FALSE) + mo_p <- P(mo_tr, method = "explicit", compile = FALSE, modelname = "mo_p") compile(th_x, th_g, th_err, th_p, se_x, se_g, se_err, se_p, se_gt, se_errt, se_pt, mo_x, mo_g, mo_err, mo_p, output = "focei_models", cores = 2) diff --git a/tests/testthat/test-odemodel.R b/tests/testthat/test-odemodel.R index b88a544a..466c85d8 100644 --- a/tests/testthat/test-odemodel.R +++ b/tests/testthat/test-odemodel.R @@ -46,18 +46,41 @@ test_that("Xs and Xf on deSolve check their arguments and return the requested t x3 <- Xs(model, options = list(maxsteps = 3)) expect_warning(x3(0:2, pars, deriv = FALSE), "stopped") expect_warning(x3(0:2, pars), "stopped") - m0 <- odemodel(f, modelname = "desolve_noderiv", backend = "deSolve", deriv = FALSE, + m0 <- odemodel(f, modelname = "desolve_noderiv", backend = "deSolve", derivMode = "none", compile = FALSE) - expect_error(Xs(m0), "sensitivities") + expect_error(Xs(m0), "derivMode = \"forward\"") }) -test_that("odemodel(deriv = FALSE) builds no derivative directions", { - m <- odemodel(eqnvec(A = "-k*A"), deriv = FALSE, derivMode = c("forward", "reverse"), - modelname = "test_om_noderiv_r", compile = FALSE) +test_that("odemodel() builds the directions derivMode names and no other", { + withr::local_dir(tempdir()) + f <- eqnvec(A = "-k*A") + m <- odemodel(f, derivMode = "none", modelname = "test_om_none", compile = FALSE) + expect_null(m$extended) + expect_null(m$extended2) expect_null(m$reversed) - m2 <- odemodel(eqnvec(A = "-k*A"), deriv = FALSE, - derivMode = c("forward", "forward-forward"), - modelname = "test_om_noderiv_ff", compile = FALSE) - expect_null(m2$extended) + expect_null(m$reversed2) + # a second-order direction builds the first order it runs on + m2 <- odemodel(f, derivMode = "forward-reverse", modelname = "test_om_fr", compile = FALSE) + expect_false(is.null(m2$extended)) + expect_false(is.null(m2$reversed2)) + expect_null(m2$reversed) expect_null(m2$extended2) + expect_identical(attr(m2, "derivMode"), c("forward", "forward-reverse")) + m3 <- odemodel(f, derivMode = "reverse", modelname = "test_om_r", compile = FALSE) + expect_null(m3$extended) + expect_false(is.null(m3$reversed)) +}) + +test_that("odemodel() rejects deriv, deriv2 and inconsistent derivMode", { + withr::local_dir(tempdir()) + f <- eqnvec(A = "-k*A") + expect_error(odemodel(f, deriv = FALSE, derivMode = "forward-reverse", compile = FALSE), + "derivMode") + expect_error(odemodel(f, deriv2 = TRUE, compile = FALSE), "`deriv2` is not an argument") + expect_error(odemodel(f, derivMode = c("none", "forward"), compile = FALSE), "none") + expect_error(odemodel(f, derivMode = "backward", compile = FALSE)) + expect_error(odemodel(f, derivMode = "forward-forward", backend = "Sundials", compile = FALSE), + "forward-forward") + expect_error(odemodel(f, derivMode = "reverse", backend = "deSolve", compile = FALSE), + "reverse") }) diff --git a/tests/testthat/test-quadrature.R b/tests/testthat/test-quadrature.R index 86221ad4..9d68a4e5 100644 --- a/tests/testthat/test-quadrature.R +++ b/tests/testthat/test-quadrature.R @@ -64,20 +64,20 @@ test_that("the nodes integrate a normal of the posterior precision exactly", { dir.create(dir, showWarnings = FALSE, recursive = TRUE) withr::local_dir(dir) g <- Y(c(y = "intercept"), f = NULL, parameters = "intercept", compile = FALSE, - modelname = "quad_obs", deriv2 = TRUE) + modelname = "quad_obs", derivMode = "forward-forward") groups <- c("s1", "s2", "s3") tab <- data.frame(ID = rep(groups, each = 2), w = rep(c(-1, 0, 1.5), each = 2), row.names = paste0(rep(groups, each = 2), c("a", "b"))) tr <- branch(define(NULL, "intercept <- exp(mu)"), table = tab) tr <- insert(tr, mu ~ 1 + (1 | ID)) - p <- P(tr, method = "explicit", compile = FALSE, modelname = "quad_p", deriv2 = TRUE) + p <- P(tr, method = "explicit", compile = FALSE, modelname = "quad_p", derivMode = "forward-forward") # a group covariate on mu and the parameter s of an error model sigma = exp(s) tw <- branch(define(NULL, "x <- x", x = c("intercept", "s")), table = tab) tw <- insert(tw, "intercept <- exp(mu)") tw <- insert(tw, mu ~ w + (1 | ID)) - pw <- P(tw, method = "explicit", compile = FALSE, modelname = "quad_pw", deriv2 = TRUE) + pw <- P(tw, method = "explicit", compile = FALSE, modelname = "quad_pw", derivMode = "forward-forward") err <- Y(c(y = "exp(s)"), g, attachInput = FALSE, compile = FALSE, modelname = "quad_err", - deriv2 = TRUE) + derivMode = "forward-forward") compile(g, p, pw, err, output = "quadrature_models", cores = 2) values <- c(2.0, 2.3, 1.6, 1.5, 2.6, 2.4) data <- as.datalist(data.frame(name = "y", time = 0, sigma = 0.3, value = values, diff --git a/tests/testthat/test-reverse.R b/tests/testthat/test-reverse.R index a89c3af0..3791af0b 100644 --- a/tests/testthat/test-reverse.R +++ b/tests/testthat/test-reverse.R @@ -31,7 +31,7 @@ skip_on_cran() tr <- c(A = "exp(logA)", B = "0", k1 = "exp(logk1)", k2 = "exp(logk2)", s = "exp(logs)") - m <- odemodel(re, modelname = "rv_ode", deriv = TRUE, derivMode = fr, + m <- odemodel(re, modelname = "rv_ode", derivMode = fr, outdir = d, compile = FALSE) g <- Y(c(obsA = "s*A", obsB = "s*B"), re, derivMode = fr, modelname = "rv_obs", outdir = d) @@ -47,15 +47,15 @@ skip_on_cran() modelname = paste0("rv_p2_", cn), outdir = d))) ev <- eventlist(var = "A", time = "t_dose", value = "d_amt", method = "add") - mev <- odemodel(re, events = ev, modelname = "rv_ev", deriv = TRUE, + mev <- odemodel(re, events = ev, modelname = "rv_ev", derivMode = fr, outdir = d, compile = FALSE) pev <- P(c(tr, t_dose = "3", d_amt = "exp(logdose)"), condition = "C1", derivMode = fr, modelname = "rv_pev", outdir = d) - mnr <- odemodel(re, modelname = "rv_noRev", deriv = TRUE, outdir = d, + mnr <- odemodel(re, modelname = "rv_noRev", outdir = d, compile = FALSE) pq <- Pimpl(c(A = "k_in - k_out * A"), parameters = c("k_in", "k_out"), - flow = TRUE, modelname = "rv_equil", deriv = TRUE, + flow = TRUE, modelname = "rv_equil", outdir = d, verbose = FALSE) pl <- P(c(k_in = "exp(logkin)", k_out = "exp(logkout)", B = "0", k1 = "exp(logk1)", k2 = "exp(logk2)", s = "exp(logs)"), @@ -65,49 +65,49 @@ skip_on_cran() condition = "C2", derivMode = fr, modelname = "rv_pq2", outdir = d) sun <- if (isTRUE(cppDE:::cvodeConfig$available)) - odemodel(re, modelname = "rv_sun", deriv = TRUE, backend = "Sundials", + odemodel(re, modelname = "rv_sun", backend = "Sundials", derivMode = fr, outdir = d, compile = FALSE) sunev <- if (isTRUE(cppDE:::cvodeConfig$available)) - odemodel(re, events = ev, modelname = "rv_sun_ev", deriv = TRUE, + odemodel(re, events = ev, modelname = "rv_sun_ev", backend = "Sundials", derivMode = fr, outdir = d, compile = FALSE) - m2 <- odemodel(re, modelname = "rv2_ode", deriv = TRUE, deriv2 = TRUE, + m2 <- odemodel(re, modelname = "rv2_ode", outdir = d, compile = FALSE, derivMode = c(fr, "forward-forward", "forward-reverse")) - g2 <- Y(c(obsA = "s*A", obsB = "s*B"), re, deriv2 = TRUE, derivMode = c(fr, "forward-reverse"), + g2 <- Y(c(obsA = "s*A", obsB = "s*B"), re, derivMode = c(fr, "forward-reverse", "forward-forward"), modelname = "rv2_obs", outdir = d) - q <- P(tr, condition = "C1", deriv2 = TRUE, derivMode = c(fr, "forward-reverse"), + q <- P(tr, condition = "C1", derivMode = c(fr, "forward-reverse", "forward-forward"), modelname = "rv2_p", outdir = d) # A second condition on the same ODE. The batched backward path only # engages with more than one live condition. - q2 <- q + P(tr, condition = "C2", deriv2 = TRUE, derivMode = c(fr, "forward-reverse"), + q2 <- q + P(tr, condition = "C2", derivMode = c(fr, "forward-reverse", "forward-forward"), modelname = "rv2_p2", outdir = d) # k2 and s reach the prediction only through attach.input. qt hands them on # at the head of the chain. qh maps k2 per condition and hands s on, and qb # hands both on behind it, for two conditions in one batched call. tr_ab <- tr[c("A", "B", "k1")] - qt <- P(tr_ab, condition = "C1", attachInput = TRUE, deriv2 = TRUE, - derivMode = c(fr, "forward-reverse"), modelname = "rv2_pt", outdir = d) + qt <- P(tr_ab, condition = "C1", attachInput = TRUE, + derivMode = c(fr, "forward-reverse", "forward-forward"), modelname = "rv2_pt", outdir = d) qh <- P(list(C1 = c(k2 = "exp(logk2)"), C2 = c(k2 = "2*exp(logk2)")), - attachInput = TRUE, deriv2 = TRUE, derivMode = c(fr, "forward-reverse"), + attachInput = TRUE, derivMode = c(fr, "forward-reverse", "forward-forward"), modelname = "rv2_ph", outdir = d) - qb <- P(tr_ab, attachInput = TRUE, deriv2 = TRUE, - derivMode = c(fr, "forward-reverse"), modelname = "rv2_pb", outdir = d) + qb <- P(tr_ab, attachInput = TRUE, + derivMode = c(fr, "forward-reverse", "forward-forward"), modelname = "rv2_pb", outdir = d) # An estimated error model on two conditions, as one Y() and as a sum per condition. fr2 <- c(fr, "forward-reverse") errs <- c(obsA = "sd_rel*obsA + sd_abs", obsB = "sd_rel*obsB + sd_abs") - e2 <- Y(errs, g2, states = c("obsA", "obsB"), parameters = c("sd_rel", "sd_abs"), deriv2 = TRUE, - derivMode = fr2, modelname = "rv2_err", outdir = d) + e2 <- Y(errs, g2, states = c("obsA", "obsB"), parameters = c("sd_rel", "sd_abs"), + derivMode = c(fr2, "forward-forward"), modelname = "rv2_err", outdir = d) e2c <- Reduce("+", lapply(c("C1", "C2"), function(cn) Y(errs, g2, states = c("obsA", "obsB"), parameters = c("sd_rel", "sd_abs"), condition = cn, - deriv2 = TRUE, derivMode = fr2, modelname = paste0("rv2_err_", cn), outdir = d))) + derivMode = c(fr2, "forward-forward"), modelname = paste0("rv2_err_", cn), outdir = d))) qe <- Reduce("+", lapply(c("C1", "C2"), function(cn) - P(c(tr, sd_rel = "exp(logsdrel)", sd_abs = "exp(logsdabs)"), condition = cn, deriv2 = TRUE, - derivMode = fr2, modelname = paste0("rv2_pe_", cn), outdir = d))) + P(c(tr, sd_rel = "exp(logsdrel)", sd_abs = "exp(logsdabs)"), condition = cn, + derivMode = c(fr2, "forward-forward"), modelname = paste0("rv2_pe_", cn), outdir = d))) # observables of time alone, for Xt() gt <- Y(c(obsA = "s * exp(-k1 * time)", obsB = "s * k1 * time"), f = NULL, parameters = c("s", "k1"), - deriv2 = TRUE, derivMode = fr2, modelname = "rv2_obst", outdir = d) + derivMode = c(fr2, "forward-forward"), modelname = "rv2_obst", outdir = d) compile(m, g, e, p, pe, pc, mev, pev, mnr, pq, pl, pl2, sun, sunev, m2, g2, q, q2, qt, qh, qb, e2, e2c, qe, gt, output = "rv_all", cores = test_cores()) @@ -382,7 +382,7 @@ test_that("a model without a reverse object says so", { prd <- fx$g * xf * fx$p obj <- normL2(.rev_data(fx, fx$g * fx$x * fx$p, fx$pars), prd) expect_error(obj(fx$pars, deriv = TRUE, sweep = "reverse"), - "no reverse object") + "derivMode = \"reverse\"") expect_error(odemodel(.rev_reactions(), modelname = "rv_deSolve", derivMode = c("forward", "reverse"), backend = "deSolve", outdir = d), "cppDE") @@ -423,7 +423,7 @@ test_that("a quasi-Newton phase runs backwards when the chain can and forwards w expect_identical(trust(nobj, start, phases = list(gn, sr1))$phaseSweep[["sr1"]], "forward") expect_error(trust(nobj, start, phases = list(gn, c(sr1, sweep = "reverse"))), - "no reverse object") + "derivMode = \"reverse\"") }) @@ -537,7 +537,7 @@ test_that("odemodel builds the forward-reverse object and names it", { expect_false(is.null(m$reversed2)) expect_identical(attr(m$reversed2, "derivMode"), "forward-reverse") - # forward-forward is deriv2 = TRUE under a separate name. + # forward-forward builds the second-order sensitivities. m2 <- odemodel(.rev_reactions(), modelname = "rv_ffm", outdir = d, derivMode = c("forward", "forward-forward"), compile = FALSE) expect_false(is.null(m2$extended2)) diff --git a/vignettes/articles/guide-model.Rmd b/vignettes/articles/guide-model.Rmd index 37c33749..bdc25d79 100644 --- a/vignettes/articles/guide-model.Rmd +++ b/vignettes/articles/guide-model.Rmd @@ -219,7 +219,7 @@ and standard deviation 4 by default, narrower where the magnitude is known: `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)` +stability boundary, and needs `Pimpl(derivMode = "forward-forward")` ([Methods > Steady states](methods-steady-states.html#stability)). ```{r objective} diff --git a/vignettes/articles/guide-nlme.Rmd b/vignettes/articles/guide-nlme.Rmd index 7e71ec74..a72785c3 100644 --- a/vignettes/articles/guide-nlme.Rmd +++ b/vignettes/articles/guide-nlme.Rmd @@ -28,7 +28,8 @@ Depot, central compartment of volume $V$, clearance $\mathrm{Cl}$ (volume per ti ```{r reactions} ``` -`em()` needs second derivatives: `deriv2 = TRUE` and the forward-over-reverse derivative modes. +`em()` needs second derivatives: `derivMode` with `"forward-forward"` and the forward-over-reverse +directions. ```{r model} ``` @@ -135,7 +136,8 @@ holds `Omega`, `omega`, `random`, `etaModes`, `etaSE` and `shrinkage`. Methods: | `derivMode` | `"forward-reverse"` | volume-term second derivatives, or `"forward-forward"` | | `secondOrderCorrection` | `TRUE` | derivative of the volume term | -`"forward-forward"` needs `deriv2 = TRUE`. `secondOrderCorrection = FALSE` biases the estimates +`"forward-forward"` needs models built with `derivMode = "forward-forward"`. +`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). diff --git a/vignettes/articles/guide-optimization.Rmd b/vignettes/articles/guide-optimization.Rmd index 3cd1086f..6b56ac28 100644 --- a/vignettes/articles/guide-optimization.Rmd +++ b/vignettes/articles/guide-optimization.Rmd @@ -101,8 +101,11 @@ as `tolControl`. 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)). +The sparse path, multiple shooting and `boundary = "clip"` run Gauss-Newton. 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)). +`"exact"` needs a chain built with `derivMode = "forward-forward"` or `"forward-reverse"` +([Sensitivities](guide-sensitivities.html)). Quasi-Newton settings, entries of `qnControl`: | entry | default | controls | diff --git a/vignettes/articles/guide-sensitivities.Rmd b/vignettes/articles/guide-sensitivities.Rmd index f684152c..ccba3991 100644 --- a/vignettes/articles/guide-sensitivities.Rmd +++ b/vignettes/articles/guide-sensitivities.Rmd @@ -20,19 +20,23 @@ dMod2 computes derivatives of the objective exactly from the ODE sensitivities a through every function object. Code: `sensitivities.R`; details: [Methods > Sensitivities and Hessians](methods-sensitivities.html). +`derivMode` of `odemodel()`, `Y()`, `P()` and `Pimpl()` selects the derivatives a function +object is built with: `"forward"`, `"reverse"`, `"forward-forward"`, `"forward-reverse"`, or +`"none"`. The arguments `deriv`, `deriv2` and `sweep` of a call select what the call computes; a +call that asks for a derivative not built is an error. + ## Forward sensitivities -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)). +The default, `derivMode = "forward"`: `Xs()` integrates $\partial x / \partial \theta$ with the +states, the objective returns gradient and Gauss-Newton Hessian. `sensErrCon` in `optionsSens` +sets whether sensitivities enter the error test (default `TRUE`). ## Forward over forward -`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 +`derivMode = "forward-forward"` in `odemodel()`, `Y()`, `P()` and `Pimpl()` builds second-order +sensitivities, and a call with `deriv2 = TRUE` returns the exact Hessian from them. The equation +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 @@ -87,7 +91,7 @@ uses it for directional second derivatives. | backend | solver | forward | fwd/fwd | reverse | fwd/rev | use | |---|---|---|---|---|---|---| -| `"cppDE"` (default) | C++: BDF/NDF, Adams, Rosenbrock, Tsitouras | duals | `deriv2` | discrete adjoint | yes | all models | +| `"cppDE"` (default) | C++: BDF/NDF, Adams, Rosenbrock, Tsitouras | duals | duals | discrete adjoint | yes | all models | | `"Sundials"` | CVODES, `cppDE::cvode()` | CVODES | no | CVODES ASA | no | first-order derivatives | | `"deSolve"` | `lsodes`, cOde | sens. equations | no | no | no | dMod models | diff --git a/vignettes/articles/methods-nlme.Rmd b/vignettes/articles/methods-nlme.Rmd index 38e13866..28015ce2 100644 --- a/vignettes/articles/methods-nlme.Rmd +++ b/vignettes/articles/methods-nlme.Rmd @@ -120,10 +120,10 @@ $$\frac{\mathrm{d} \log \lvert H_i \rvert}{\mathrm{d} \psi_k} | `control` | volume term | |---|---| | `derivMode = "forward-reverse"` (default) | traces from one forward pass and a backward sweep ([Sensitivities](guide-sensitivities.html)); exact gradient, curvature by SR1 | -| `derivMode = "forward-forward"` | `deriv2 = TRUE` sensitivities; exact gradient, curvature without third-order terms | +| `derivMode = "forward-forward"` | second-order sensitivities; exact gradient, curvature without third-order terms | | `secondOrderCorrection = FALSE` | derivative dropped; biased estimates | -Where the model has `deriv2`, the reported Hessian has the exact Schur complement and the +Where the model is built with `"forward-forward"`, the reported Hessian has the exact Schur complement and the curvature of the volume term without third-order sensitivities, as `summary()` states. For $\sigma$ depending on $\eta$, quadrature gives better standard errors of $\Omega$. ## Adaptive sparse-grid quadrature @@ -143,7 +143,7 @@ FOCEI Gaussian $\mathcal{N}(\hat\eta_i, 2 H_i^{-1})$ and moves with $\psi$ [@cla Negative weights make $\log L_i$ a signed log-sum-exp; a nonpositive sum, an unresolved posterior, fails the evaluation, naming the group. The gradient is the quadrature of the exact gradient of $\log L_i$ on the current nodes (Fisher's identity), the Hessian follows by Louis' identity from -data Hessians per node that are exact where the model has `deriv2` and Gauss-Newton otherwise; the +data Hessians per node that are exact where the model is built with `"forward-forward"` and Gauss-Newton otherwise; the move of the grid with $\psi$ is not differentiated. `method = "quadrature"` starts from the converged FOCEI fit and alternates: diff --git a/vignettes/articles/methods-steady-states.Rmd b/vignettes/articles/methods-steady-states.Rmd index 161ab5ef..67cb6208 100644 --- a/vignettes/articles/methods-steady-states.Rmd +++ b/vignettes/articles/methods-steady-states.Rmd @@ -55,7 +55,7 @@ $$\frac{\partial G}{\partial x}\, \frac{\partial x}{\partial p} = -\frac{\partia regular where $J = \partial f / \partial x$ restricted to the conservation manifold, $N^\top J N$ for a basis $N$ of $\ker C$, is nonsingular; such a root is isolated in the conservation class. Where the matrix is singular, `Pimpl()` takes the pseudo-inverse and warns. -Differentiating (4) again gives the second derivatives, `Pimpl(deriv2 = TRUE)`, with the same +Differentiating (4) again gives the second derivatives, `Pimpl(derivMode = "forward-forward")`, with the same matrix. A reverse sweep applies the transpose of the solution $\partial x / \partial p$ of (4) ([Sensitivities and Hessians](methods-sensitivities.html#reverse-sweep)). @@ -103,7 +103,7 @@ derivative each; each takes the mean $\mathrm{tr}(P\, \mathrm{d}J/\mathrm{d}p) / 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. +`Pimpl(derivMode = "forward-forward")`. The term is a model assumption, not data: profiles with `stop = "data"` and likelihood ratios leave it out. The Gauss-Newton Hessian of (5), diff --git a/vignettes/articles/migrating.Rmd b/vignettes/articles/migrating.Rmd index 3caa780b..79a4ee33 100644 --- a/vignettes/articles/migrating.Rmd +++ b/vignettes/articles/migrating.Rmd @@ -85,7 +85,8 @@ Files go to `outdir`, default `getOption("dMod2.outdir")`, else the working dire | `odemodel(outputs = , estimate = , gridpoints = )` | `...`, deSolve only | | `Xs(optionsOde = , optionsSens = )` | `Xs(options = , optionsSens = )`, see `cppDE::solveODE()` | | `Xs(fcontrol = )` | deSolve only | -| none | `deriv2 = TRUE` in `odemodel()`, `Y()`, `P()`: exact second derivatives | +| `odemodel(deriv = FALSE)` | `odemodel(derivMode = "none")` | +| none | `derivMode = "forward-forward"` in `odemodel()`, `Y()`, `P()`: exact second derivatives | ## Renamed arguments @@ -128,7 +129,7 @@ Dotted argument names are lowerCamelCase. | `stepControl = list(stop = "data")` | `stop`: also any numeric attribute of the objective | | threshold `qchisq(1 - alpha, 1)` | `delta = `, e.g. `profileThreshold(method = "F", n = , p = )` | | both sides | `side = c("both", "left", "right")` | -| `algoControl = list(W = "hessian")`: Gauss-Newton | exact Hessian with `deriv2 = TRUE` | +| `algoControl = list(W = "hessian")`: Gauss-Newton | exact Hessian with `derivMode = "forward-forward"` | | `cores = ` over parameters | `cores = n`, or `c(pars = , conditions = )` | | none | attribute `"ends"`: steps and stop reason per side | | none | `sparse = "auto"`: sparse Hessian where available | diff --git a/vignettes/articles/results/guide-nlme.R b/vignettes/articles/results/guide-nlme.R index d8181787..e7c63b73 100644 --- a/vignettes/articles/results/guide-nlme.R +++ b/vignettes/articles/results/guide-nlme.R @@ -16,10 +16,10 @@ reactions <- eqnlist() |> as.eqnvec(reactions) ## ---- model -dm <- c("forward", "reverse", "forward-reverse") -x <- Xs(odemodel(reactions, modelname = "theo", compile = FALSE, deriv2 = TRUE, derivMode = dm)) -g <- Y(c(cp = "Cc"), x, modelname = "theo_g", compile = FALSE, deriv2 = TRUE, derivMode = dm) -e <- Y(c(cp = "sigma"), g, attachInput = FALSE, modelname = "theo_e", compile = FALSE, deriv2 = TRUE, +dm <- c("forward", "reverse", "forward-forward", "forward-reverse") +x <- Xs(odemodel(reactions, modelname = "theo", compile = FALSE, derivMode = dm)) +g <- Y(c(cp = "Cc"), x, modelname = "theo_g", compile = FALSE, derivMode = dm) +e <- Y(c(cp = "sigma"), g, attachInput = FALSE, modelname = "theo_e", compile = FALSE, derivMode = dm) ## ---- data @@ -39,7 +39,7 @@ trafo <- eqnvec() |> insert("Cc <- 0") |> insert("x <- exp(x)", x = c("Ka", "V", "Cl", "sigma")) |> insert(Ka + V + Cl ~ 1 + (1 | ID)) -p <- P(trafo, method = "explicit", modelname = "theo_p", compile = FALSE, deriv2 = TRUE, derivMode = dm) +p <- P(trafo, method = "explicit", modelname = "theo_p", compile = FALSE, derivMode = dm) compile(x, g, e, p, output = "theo", cores = 6) random <- randomEffects(p) random @@ -71,7 +71,7 @@ trafo2 <- eqnvec() |> insert("x <- exp(x)", x = c("Ka", "V", "Cl", "sigma")) |> insert(Ka + V ~ 1 + (1 | ID)) |> insert(Cl ~ 1 + logWeight + (1 | ID)) -p2 <- P(trafo2, method = "explicit", modelname = "theo_p2", compile = FALSE, deriv2 = TRUE, derivMode = dm) +p2 <- P(trafo2, method = "explicit", modelname = "theo_p2", compile = FALSE, derivMode = dm) compile(p2, output = "theo2", cores = 6) fit2 <- em(normL2(data, g * x * p2, errmodel = e), randomEffects(p2), init, verbose = FALSE) comparison <- anova(fit, fit2)