The hardware and bandwidth for this mirror is donated by METANET, the Webhosting and Full Service-Cloud Provider.
If you wish to report a bug, or if you are interested in having us mirror your free-software or open-source project, please feel free to contact us at mirror[@]metanet.ch.

Package {nlmixr2est}


Type: Package
Title: Nonlinear Mixed Effects Models in Population PK/PD, Estimation Routines
Version: 7.0.2
Maintainer: Matthew Fidler <matthew.fidler@gmail.com>
Description: Fit and compare nonlinear mixed-effects models in differential equations with flexible dosing information commonly seen in pharmacokinetics and pharmacodynamics (Almquist, Leander, and Jirstrand 2015 <doi:10.1007/s10928-015-9409-1>). Differential equation solving is by compiled C code provided in the 'rxode2' package (Wang, Hallow, and James 2015 <doi:10.1002/psp4.12052>).
License: GPL (≥ 3)
URL: https://github.com/nlmixr2/nlmixr2est, https://nlmixr2.github.io/nlmixr2est/
Depends: nlmixr2data, R (≥ 4.1.0)
Imports: backports, checkmate, cli, graphics, knitr, L0Learn, lbfgsb3c, lotri, Matrix, methods, minqa, n1qn1 (≥ 6.0.1-12), nlme, Rcpp, rex, rxode2 (≥ 5.1.5), stats, symengine, utils
Suggests: broom.mixed, callr, crayon, data.table, devtools, digest, dplyr (≥ 1.1.0), generics, nloptr, sys, testthat, tibble, withr, xgxr, sfsmisc, minpack.lm, remotes, fastGHQuad, rmarkdown, rlang, numDeriv, rstan, loo
LinkingTo: BH, n1qn1 (≥ 6.0.1-12), lbfgsb3c (≥ 2024-3.5), lotri (≥ 0.5.0), Rcpp, RcppArmadillo (≥ 0.11.2.3.1), RcppEigen, rxode2 (≥ 5.1.5)
Biarch: true
Config/testthat/edition: 3
Encoding: UTF-8
Language: en-US
NeedsCompilation: yes
LazyData: true
Config/roxygen2/version: 8.0.0
Packaged: 2026-08-04 18:32:19 UTC; matt-fidler
Author: Matthew Fidler ORCID iD [aut, cre], Wenping Wang [aut], Audrey Lavenu [ctb], Ben Goodrich [ctb], David Ardia [cph], Dirk Eddelbuettel [cph], Elizabeth Eskow [ctb], Emmanuelle Comets [ctb], Hadley Wickham [ctb], Hajar Besbassi [ctb], Hidde van de Beek [ctb], Johannes Pfeifer [ctb], Justin Wilkins ORCID iD [aut], Katharine Mullen [cph], Mahmoud Abdelwahab [ctb], Marc Lavielle [ctb], Mason McComb ORCID iD [ctb], Mirjam Trame [ctb], Richard Hooijmaijers [aut], Rik Schoemaker ORCID iD [aut], Robert B. Schnabel [ctb], Robert Leary [ctb], Teun Post [ctb], Vipul Mann [aut], Yuan Xiong [aut]
Repository: CRAN
Date/Publication: 2026-08-04 20:50:09 UTC

Wrap scalar or list arguments into an iterPrintControl object

Description

Absorbs the scalar 'print'/'printNcol'/'useColor' arguments into a single [iterPrintControl()] object, or passes through an already pre-built one.

Usage

.absorbIterPrintControl(
  print = 1L,
  printNcol = NULL,
  useColor = NULL,
  iterPrintControl = NULL
)

Arguments

print

Either an integer print-frequency or an 'iterPrintControl' object.

printNcol, useColor

Scalar '*Control()' arguments forwarded to [iterPrintControl()] only when 'print' is a scalar.

iterPrintControl

Optional pre-built [iterPrintControl()] object. Wins over 'print' and the other scalars when supplied.

Value

An 'iterPrintControl' list.


Adds a package to the nlmixr2's $sessioninfo inside the fit

Description

Adds a package to the nlmixr2's $sessioninfo inside the fit

Usage

.addPkgNlmixr2(pkg)

Arguments

pkg

character vector of the package to add

Value

nothing, called for side effects

Author(s)

Matthew L. Fidler

Examples

.addPkgNlmixr2("nlmixr2") # already present

Get the adaptive Gauss-Hermite quadrature points and weights

Description

Get the adaptive Gauss-Hermite quadrature points and weights

Usage

.agq(neta = 2, nAGQ = 3)

Arguments

neta

number of eta parameters in the model

nAGQ

number of adaptive quadrature points to use

Value

A list with the following elements:

x

A matrix of quadrature points, one row per point.

w

A matrix of quadrature weights, one row per point.

n

The number of quadrature points.

neta

The number of eta parameters.

nAQD

The number of adaptive quadrature points.

first

A logical indicating if the first point is zero.

Author(s)

Matthew L. Fidler

Examples

.agq(neta=2, nAGQ=3)

Augment Prediction for Ipred Model

Description

This function augments the prediction for an individual prediction (Ipred) model. It retrieves the simulation model from the fit object and evaluates the model variables.

Usage

.augPredIpredModel(fit)

Arguments

fit

The fitted model object from which to retrieve the simulation model.

Details

The function performs the following steps:

- Retrieves the simulation model from the provided 'fit' object using '.getSimModel' with 'hideIpred' and 'tad' set to 'FALSE'.

- Evaluates the model variables using 'rxModelVars'.

Value

The evaluated model variables for the Ipred model.


Collect warnings and just warn once.

Description

Collect warnings and just warn once.

Usage

.collectWarn(expr, lst = FALSE, collectErr = FALSE)

Arguments

expr

R expression

lst

When TRUE return a list with list(object,warnings) instead of issuing the warnings. Otherwise, when FALSE issue the warnings and return the object.

collectErr

When TRUE, errors raised during evaluation of expr are recorded in addition to warnings. A calling handler captures every error message as it is signalled, then lets the condition continue to propagate so that inner try()/tryCatch() blocks in expr keep working as usual. An outer tryCatch() catches errors that escape all inner handling, so the call always returns instead of stopping. If expr evaluated to a result (i.e. no error escaped), the recorded errors were caught by inner handlers and are discarded. If an error did escape, every message observed along the error chain (including follow-up errors raised by on.exit handlers, see issue 607) is returned in the error element of the result list (when lst = TRUE) or re-raised joined by newlines (when lst = FALSE). When FALSE (the default) errors propagate normally and es is always NULL. This is used by nlmixr2Est0() so that all errors from a failed estimation run are reported together rather than only the last one.

Value

The value of the expression, or when lst = TRUE a list of the form list(object, warning = ws, error = es) where ws and es are character vectors of unique warning and error messages (es is always NULL when collectErr = FALSE, and is also NULL when the expression evaluated successfully under collectErr = TRUE).

Author(s)

Matthew L. Fidler


Identify Differences Between Standard and New Objects but used in rxUiDeparse

Description

Compares elements of a standard object against a new one so 'rxUiDeparse' only shows values that differ from the default.

Usage

.deparseDifferent(standard, new, internal = character(0))

Arguments

standard

The standard object used for comparison. (for example 'foceiControl()')

new

The new object to be compared against the standard. This would be what the user supplide like 'foceiControl(outerOpt="bobyqa")'

internal

A character vector of element names to be ignored during the comparison. Default is an empty character vector. These are for internal items of the list that flag certain properties like if the 'rxControl()' was generated by the 'foceiControl()' procedure or not.

Value

A vector of indices indicating which elements of the standard object differ from the new object.

Author(s)

Matthew L. Fidler

Examples

standard <- list(a = 1, b = 2, c = 3)
new <- list(a = 1, b = 3, c = 3)
.deparseDifferent(standard, new)

Deparse finalize a control or related object into a language object

Description

Deparses an object into a language expression, optionally using a custom function for specific elements.

Usage

.deparseFinal(default, object, w, var, fun = NULL)

Arguments

default

A default object used for comparison; This is the estimation control procedure. It should have a class matching the function that created it.

object

The object to be deparsed into a language exression

w

A vector of indices indicating which elements are different and need to be deparsed. This likely comes from '.deparseDifferent()'

var

A string representing the variable name to be assigned in the deparsed expression.

fun

An optional custom function to handle specific elements during deparsing. Default is NULL. This handles things that are specific to an estimation control and is used by functions like 'rxUiDeparse.saemControl()'

Value

A language object representing the deparsed expression.

Author(s)

Matthew L. Fidler


This downgrades the UI for any of the zero etas in the model

Description

This downgrades the UI for any of the zero etas in the model

Usage

.downgradeEtas(ui, zeroEtas = character(0))

Arguments

ui

rxode2 User interface function

zeroEtas

The names of the zero etas in the model

Value

New rxode2 ui with the zero etas removed

Author(s)

Matthew L. Fidler


This function process the data for use in focei

Description

The $origData is the data that is fed into the focei before modification The $dataSav is the data saved for focei

Usage

.foceiPreProcessData(data, env, ui, rxControl = NULL)

Arguments

data

Input dataset

env

focei environment where focei family is run

ui

rxode2 ui

rxControl

is the rxode2 control that is used to translate to the modeling dataset

Value

Nothing, called for side effects

Author(s)

Matthew L. Fidler


Initialize S3 methods

Description

Initialize S3 methods

Usage

.iniS3()

Value

nothing, called for side effects

Author(s)

Matthew L. Fidler

Examples


# Lets tools like nlmixr2shiny import S3 registration without
# depending on nlmixr2est

.iniS3() # run to register S3 methods


Load a model into a symengine environment

Description

Load a model into a symengine environment

Usage

.loadSymengine(newmod, promoteLinSens = TRUE, fullModel = FALSE)

Arguments

newmod

model text (normalized rxode2 model, e.g. from a prune)

promoteLinSens

when 'TRUE', promote 'linCmt()' to the sensitivity-based solved system

fullModel

when 'TRUE', change the printed message to indicate the full model is being loaded

Value

symengine environment from 'rxode2::rxS()' with 'rx_r_' coerced to a symengine object when needed

Author(s)

Matthew L. Fidler


Adjust covariance matrix based on scaling parameters

Description

Adjust covariance matrix based on scaling parameters

Usage

.nlmAdjustCov(cov, parScaled)

Arguments

cov

Covariance of scaled parameters

parScaled

The final scaled parameter value

Value

The adjusted covariance matrix based on the scaling

Author(s)

Matthew L. Fidler


Adjust nlm and family output environment

Description

Will take information like '$censInformation', '$parHistData', '$cov' and '$covMethod' from the ret[[str]] and put it directly in the environment 'ret'

Usage

.nlmFamilyAdjustOutput(ret, str)

Arguments

ret

environment for fit output that needs to be adjusted

str

string for the fit output

Value

updated environment

Author(s)

Matthew L. Fidler


Shared control setup for the nlm-family estimation methods

Description

Shared control setup for the nlm-family estimation methods

Usage

.nlmFamilyControlGeneric(env, controlFn, controlClass)

Arguments

env

dispatch environment (provides 'ui' and 'control')

controlFn

the method's '*Control()' constructor (e.g. 'nlmControl')

controlClass

the control object's S3 class (e.g. '"nlmControl"')

Value

Nothing; assigns the resolved control onto 'env$ui'

Author(s)

Matthew L. Fidler


Shared fit driver for the nlm-family estimation methods

Description

Shared fit driver for the nlm-family estimation methods

Usage

.nlmFamilyFitGeneric(
  env,
  method,
  fitModel,
  getTheta,
  controlToFocei,
  returnFlag,
  objective = NULL,
  message = function(fit) fit$message,
  emitFitWarnings = FALSE,
  extra = "",
  adjustOutput = TRUE,
  postSetup = NULL
)

Arguments

env

dispatch environment (provides 'ui', 'control', 'data', 'table')

method

estimation-method string; also the slot the raw fit is stored under (e.g. '"nlm"' -> '.ret[["nlm"]]')

fitModel

'function(ui, dataSav)' running the optimizer

getTheta

'function(fit, ui)' returning the full theta vector

controlToFocei

'function(env)' translating the control to a focei-style control for output assembly

returnFlag

rxode2 control flag name that short-circuits and returns the raw optimizer result (e.g. '"returnNlm"')

objective

optional 'function(fit)' returning the raw objective; when 'NULL' the driver does not set '$objective' (a 'postSetup' closure did)

message

'function(fit)' returning the '$message' (default 'fit$message')

emitFitWarnings

when TRUE, re-emit the warnings collected from 'fitModel' via 'warning()' (nlm does this; the others do not)

extra

'$extra' print string, or a 'function(control)' returning it

adjustOutput

when TRUE, run '.nlmFamilyAdjustOutput()'

postSetup

optional 'function(ret, ui, fitList)' returning a modified 'ret', run right after the raw fit is stored and before '.nlmFamilyAdjustOutput()' (for methods that set cov/covMethod/objective with custom values)

Value

the assembled nlmixr2 fit (or the raw optimizer result if 'returnFlag')

Author(s)

Matthew L. Fidler


Finalizes output list

Description

Finalizes output list

Usage

.nlmFinalizeList(env, lst, par = "par", printLine = TRUE, hessianCov = TRUE)

Arguments

env

nlm environment

lst

output list

par

parameter name of final estimate in output

printLine

Print the final line when print is nonzero

hessianCov

boolean indicating a hessian should be used/calculated for covariance

Value

modified list with '$cov'

Author(s)

Matthew L. Fidler


Frees nlm environment

Description

Frees nlm environment

Usage

.nlmFreeEnv()

Value

Nothing, called for side effects

Author(s)

Matthew L. Fidler


Setup a nonlinear system for optimization

Description

Setup a nonlinear system for optimization

Usage

.nlmSetupEnv(par, ui, data, modelInfo, control, lower = NULL, upper = NULL)

Arguments

par

A named vector of initial estimates to setup the nonlinear model solving environment. The names of the parameter should match the names of the model to run (not 'THETA[#]' as required in the 'modelInfo' argument)

ui

rxode2 ui model

data

rxode2 compatible data for solving/setting up

modelInfo

A list with 'predOnly' (predictions-only model in terms of 'THETA[#]'/'DV'), 'eventTheta' (0/1 per THETA flagging event-related parameters that need Shi2021 finite differences, same length as 'par'), and 'thetaGrad' (needed when solveType != 1; gives value/gradient per THETA). See 'ui$nlmSensModel' or 'ui$nlmRxModel' for examples.

control

control structure; required: 'rxControl', 'stickyRecalcN', 'maxOdeRecalc', 'odeRecalcFactor'. Optional: 'solveType', 'eventType', 'shi21maxFD', 'shiErr', 'optimHessType', 'shi21maxHess', 'hessErr', 'useColor', 'printNcol', 'print', 'normType', 'scaleType', 'scaleCmin', 'scaleCmax', 'scaleTo', 'scaleC', 'gradTo' (default 0 if missing).

lower

lower bounds, will be scaled if present

upper

upper bounds, will be scaled if present

Details

No rxode2 solving should occur between setup calls; prints the solving header if 'print != 0'.

Value

nlm solve environment; key fields: '$par.ini', '$lower', '$upper' (all scaled), and '$.ctl' (control structure).

Author(s)

Matthew Fidler


Get non mu referenced names from mu referenced theta

Description

Get non mu referenced names from mu referenced theta

Usage

.nlmeGetNonMuRefNames(names, ui)

Arguments

names

Names to translate

ui

rxode2 ui

Value

non mu referenced names

Author(s)

Matthew L. Fidler


Preprocess Covariates needed (or other data items)

Description

Preprocess Covariates needed (or other data items)

Usage

.nlmixr0preProcessCovariatesPresent(ui, est, data, control)

Arguments

ui

rxode2 ui

est

estimation method (all methods are shown by 'nlmixr2AllEst()'). Methods can be added for other tools

data

nlmixr data

control

The estimation control object. These are expected to be different for each type of estimation method

Value

list with the ui (possibly modified)

Author(s)

Matthew L. Fidler


Preprocessing hook: mu-expand non-mu structural fixed-effect thetas for the nonparametric engines, before the rest of the pipeline builds on the ui. Doing it here (rather than mutating the ui mid-setup) keeps the injected pseudo-etas consistent through covariate/mu processing and model compilation. Off when control$muExpand is FALSE.

Description

Preprocessing hook: mu-expand non-mu structural fixed-effect thetas for the nonparametric engines, before the rest of the pipeline builds on the ui. Doing it here (rather than mutating the ui mid-setup) keeps the injected pseudo-etas consistent through covariate/mu processing and model compilation. Off when control$muExpand is FALSE.

Usage

.nlmixr0preProcessNpMuExpand(ui, est, data, control)

Arguments

ui

rxode2 ui

est

estimation method (all methods are shown by 'nlmixr2AllEst()'). Methods can be added for other tools

data

nlmixr data

control

The estimation control object. These are expected to be different for each type of estimation method

Value

list(ui=) when the model was expanded, else NULL

Author(s)

Matthew L. Fidler


Update model to have final parameter estimates for piping and save orig data

Description

Update model to have final parameter estimates for piping and save orig data

Usage

.nlmixr2FitUpdateParams(x)

Arguments

x

Data to fix

Value

Nothing, called for side effects


Get the least prediction simulation information for VPC

Description

Get the least prediction simulation information for VPC

Usage

.nlmixr2estLastPredSimulationInfo()

Value

The last prediction simulation from the 'vpcSim' function (data.frame)


Allows external methods (like those in nlmixr2) to assign object name

Description

Allows external methods (like those in nlmixr2) to assign object name

Usage

.nlmixr2objectNameAssign(x)

Arguments

x

String or null for assigning a nlmixr object name

Value

nothing called for side effects

Author(s)

Matthew L. Fidler


A surrogate function for nlm to call for ode solving

Description

A surrogate function for nlm to call for ode solving

Usage

.nlmixrNlmFunC(pars)

Arguments

pars

Parameters that will be estimated

Details

This is an internal function and should not be called directly.

Value

Predictions

Author(s)

Matthew L. Fidler


A surrogate function for nlme to call for ode solving

Description

A surrogate function for nlme to call for ode solving

Usage

.nlmixrNlmeFun(pars, id)

Arguments

pars

Parameters that will be estimated

id

The patient identifiers for the estimated data.

Details

This is an internal function and should not be called directly.

Value

Predictions

Author(s)

Matthew L. Fidler


A surrogate function for nlminb to call for ode solving

Description

A surrogate function for nlminb to call for ode solving

Usage

.nlmixrNlminbFunC(pars)

.nlmixrNlminbGradC(pars)

.nlmixrNlminbHessC(pars)

Arguments

pars

Parameters that will be estimated

Details

This is an internal function and should not be called directly.

Value

Predictions

Author(s)

Matthew L. Fidler


Returns the data currently setup to run nls

Description

Returns the data currently setup to run nls

Usage

.nlmixrNlsData()

Details

This is an internal function and should not be called directly.

Value

Returns the data currently setup to run nls

Author(s)

Matthew L. Fidler


A surrogate function for nls to call for ode solving

Description

A surrogate function for nls to call for ode solving

Usage

.nlmixrNlsFun(DV, ...)

.nlmixrNlsFunValGrad(DV, ...)

Arguments

DV

dependent variable

...

Other parameters fed to prediction function

Details

This is an internal function and should not be called directly.

Value

Predictions

Author(s)

Matthew L. Fidler


Internal nls functions for minpack.lm

Description

Internal nls functions for minpack.lm

Usage

.nlmixrNlsFunVal(x)

.nlmixrNlsFunGrad(x)

Arguments

x

Parameter for estimate


A surrogate function for optim to call for ode solving

Description

A surrogate function for optim to call for ode solving

Usage

.nlmixrOptimFunC(pars)

.nlmixrOptimGradC(pars)

Arguments

pars

Parameters that will be estimated

Details

This is an internal function and should not be called directly.

Value

Predictions

Author(s)

Matthew L. Fidler


This literally fixes parameters in the model

Description

Whenever there is a fixed parameter in the model, the parameter is replaced with the literal value inside of the model and dropped from the 'ini' block. This only occurs when the 'control$literalFix=TRUE'.

Usage

.nlmixrPreprocessLiteralFix(ui, est, data, control)

Arguments

ui

model function/object

est

estimation method (all methods are shown by 'nlmixr2AllEst()'). Methods can be added for other tools

data

nlmixr data

control

The estimation control object. These are expected to be different for each type of estimation method

Value

list with possibly updated ui

Author(s)

Matthew L. Fidler


Preprocess the zero omegas

Description

Preprocess the zero omegas

Usage

.preProcessDataUi(ui, est, data, control)

Arguments

ui

rxode2 ui

est

estimation method (all methods are shown by 'nlmixr2AllEst()'). Methods can be added for other tools

data

nlmixr data

control

The estimation control object. These are expected to be different for each type of estimation method

Value

list with the ui (possibly modified)

Author(s)

Matthew L. Fidler


Translate a mixed 'linCmt()'/ODE model to all-ODEs

Description

rxode2 requires the 'linCmt()' compartments to be the last states of the solve ('op$linOffset = neq - numLin - numLinSens'), so their compartment number is one past the ODE states. The FOCEi inner model adds an ODE state per eta, and the nlm family one per theta, which pushes depot/central past the compartment numbers the data was translated against ('.foceiPreProcessData()' uses the plain model). A dose then silently lands in a sensitivity state – every prediction comes back 0. Solving the linear part as ODEs removes the 'linCmt()' block, so the numbering agrees again. SAEM builds no sensitivity states and is left alone.

Usage

.preProcessLinCmtOde(ui, est, data, control)

Arguments

ui

rxode2 ui

est

estimation method (all methods are shown by 'nlmixr2AllEst()'). Methods can be added for other tools

data

nlmixr data

control

The estimation control object. These are expected to be different for each type of estimation method

Value

list with the translated ui, or 'NULL' when nothing to do

Author(s)

Matthew L. Fidler


VAE preprocessing hook: inject etas for non-mu-referenced thetas per vaeControl(nonMuTheta=).

Description

VAE preprocessing hook: inject etas for non-mu-referenced thetas per vaeControl(nonMuTheta=).

Usage

.preProcessVaeNonMuTheta(ui, est, data, control)

Arguments

ui

rxode2 ui

est

estimation method (all methods are shown by 'nlmixr2AllEst()'). Methods can be added for other tools

data

nlmixr data

control

The estimation control object. These are expected to be different for each type of estimation method

Value

list(ui=) possibly with injected etas

Author(s)

Matthew L. Fidler


Preprocess the zero omegas

Description

Preprocess the zero omegas

Usage

.preProcessZeroOmega(ui, est, data, control)

Arguments

ui

rxode2 ui model

est

estimation method (all methods are shown by 'nlmixr2AllEst()'). Methods can be added for other tools

data

nlmixr data

control

The estimation control object. These are expected to be different for each type of estimation method

Value

list with the ui (possibly modified)

Author(s)

Matthew L. Fidler


Nudge exactly-zero theta initial estimates off zero (FOCEi family)

Description

FOCEi scales a linear parameter by its native magnitude '|init|', which is '0' (no scale) when a population parameter is initialized at exactly '0' (the parameter then freezes). This hook moves every estimated, non-fixed 'theta' whose initial estimate is exactly '0' to '+zeroTheta' when that is within its bounds, otherwise '-zeroTheta'; if neither is within the bounds it errors. Only runs for the FOCEi family (a 'foceiControl'), and runs before '.preProcessBoundedTransform' so the nudged value is what gets transformed.

Usage

.preProcessZeroTheta(ui, est, data, control)

Arguments

ui

rxode2 ui model

est

estimation method (all methods are shown by 'nlmixr2AllEst()'). Methods can be added for other tools

data

nlmixr data

control

The estimation control object. These are expected to be different for each type of estimation method

Value

list with the ui (possibly modified)

Author(s)

Matthew L. Fidler


Get the DV transformation

Description

Get the DV transformation

Usage

.rxGetDVFTransform(env, pred1, yj)

Arguments

env

Environment for the parsed model

pred1

The 'data.frame' of the current error

yj

The transformation number for the current error

Value

The transformation expression

Author(s)

Matthew Fidler


Drop mu referenced etas and covariates

Description

Drop mu referenced etas and covariates

Usage

.saemDropMuRefFromModel(ui, noCovs = FALSE, keepEtas = FALSE)

Arguments

ui

rxode2 ui

noCovs

Do not look for covariates

keepEtas

Keep the mu-referenced etas

Value

model line expression with mu referenced information dropped.

Author(s)

Matthew L. Fidler


Calculate d(state)/d(eta) or d(state)/d(theta) sensitivities

Description

Calculate d(state)/d(eta) or d(state)/d(theta) sensitivities

Usage

.sensEtaOrTheta(s, theta = FALSE)

Arguments

s

symengine environment (from '.loadSymengine()')

theta

when 'TRUE' calculate the sensitivities with respect to 'THETA[#]'; otherwise with respect to 'ETA[#]'

Value

the symengine environment 's' augmented with the sensitivity equations ('..sens', '..ddt', '..stateInfo', ...)

Author(s)

Matthew L. Fidler


This is an internal function for modifying the UI to apply mu2 referencing

Description

mu2 referencing is algebraic mu-referencing by converting to the transformation to a single value in the original dataset, and moving that around

Usage

.uiApplyMu2(env)

.uiApplyMu2hook(ui, est, data, control)

Arguments

ui

the ui for the model

est

the estimation method

data

the data provided

control

the control object

Value

Either the original model() block (if changed) or NULL if not changed

Author(s)

Matthew L. Fidler


This is an internal function for replacing the ui with original model and dropping artificial data in output

Description

This is an internal function for replacing the ui with original model and dropping artificial data in output

Usage

.uiFinalizeMu2(ret, model)

Arguments

ret

The object that would be returned, without modification

Value

modified fit updated to show the original model and without the internal transformations

Author(s)

Matthew L. Fidler


This function is to set the number of threads to 2

Description

In general it is a CRAN requirement that packages not use more than 2 threads. This function is to set the number of threads to 2 for CRAN testing. It is not intended for general use.

Usage

aaaCranNlmixrThreads()

Details

When testing with devtools::test() or testthat::test_package(), the NOT_CRAN environment variable is set to "true", so the number of threads will not be limited to 2.

Value

nothing, called for side effect of setting the number of threads to 2 for CRAN testing

Author(s)

Matthew L. Fidler

Examples


# Set the number of threads to 2 for CRAN testing
aaaCranNlmixrThreads()


Add CWRES

Description

This returns a new fit object with CWRES attached

Usage

addCwres(fit, focei = TRUE, updateObject = TRUE, envir = parent.frame(1))

Arguments

fit

nlmixr2 fit without WRES/CWRES

focei

Boolean indicating if the focei objective function is added. If not the foce objective function is added.

updateObject

Boolean indicating if the original fit object should be updated. By default this is true.

envir

Environment that should be checked for object to update. By default this is the global environment.

Value

fit with CWRES

Author(s)

Matthew L. Fidler

Examples




one.cmt <- function() {
  ini({
    ## You may label each parameter with a comment
    tka <- 0.45 # Log Ka
    tcl <- log(c(0, 2.7, 100)) # Log Cl
    ## This works with interactive models
    ## You may also label the preceding line with label("label text")
    tv <- 3.45; label("log V")
    ## the label("Label name") works with all models
    eta.ka ~ 0.6
    eta.cl ~ 0.3
    eta.v ~ 0.1
    add.sd <- 0.7
  })
  model({
    ka <- exp(tka + eta.ka)
    cl <- exp(tcl + eta.cl)
    v <- exp(tv + eta.v)
    linCmt() ~ add(add.sd)
  })
}

f <- try(nlmixr2(one.cmt, theo_sd, "saem"))

print(f)

# even though you may have forgotten to add the cwres, you can add it to the data.frame:

if (!inherits(f, "try-error")) {
  f <- try(addCwres(f))
  print(f)
}

# Note this also adds the FOCEi objective function


NPDE calculation for nlmixr2

Description

NPDE calculation for nlmixr2

Usage

addNpde(
  object,
  updateObject = TRUE,
  table = tableControl(),
  ...,
  envir = parent.frame(1)
)

Arguments

object

nlmixr2 fit object

updateObject

Boolean indicating if original object should be updated. By default this is TRUE.

table

'tableControl()' list of options

...

Other ignored parameters.

envir

Environment that should be checked for object to update. By default this is the global environment.

Value

New nlmixr2 fit object

Author(s)

Matthew L. Fidler

Examples




one.cmt <- function() {
  ini({
    ## You may label each parameter with a comment
    tka <- 0.45 # Log Ka
    tcl <- log(c(0, 2.7, 100)) # Log Cl
    ## This works with interactive models
    ## You may also label the preceding line with label("label text")
    tv <- 3.45; label("log V")
    ## the label("Label name") works with all models
    eta.ka ~ 0.6
    eta.cl ~ 0.3
    eta.v ~ 0.1
    add.sd <- 0.7
  })
  model({
    ka <- exp(tka + eta.ka)
    cl <- exp(tcl + eta.cl)
    v <- exp(tv + eta.v)
    linCmt() ~ add(add.sd)
  })
}

f <- nlmixr2(one.cmt, theo_sd, "saem")

# even though you may have forgotten to add the NPDE, you can add it to the data.frame:

f <- addNpde(f)



Add table information to nlmixr2 fit object without tables

Description

Add table information to nlmixr2 fit object without tables

Usage

addTable(
  object,
  updateObject = FALSE,
  data = object$dataSav,
  thetaEtaParameters = object$foceiThetaEtaParameters,
  table = tableControl(),
  keep = NULL,
  drop = NULL,
  envir = parent.frame(1)
)

Arguments

object

nlmixr2 family of objects

updateObject

Update the object (default FALSE)

data

Saved data from

thetaEtaParameters

Internal theta/eta parameters

table

a 'tableControl()' list of options

keep

Character Vector of items to keep

drop

Character Vector of items to drop or NULL

envir

Environment to search for updating

Value

Fit with table information attached

Author(s)

Matthew Fidler

Examples




one.cmt <- function() {
  ini({
    ## You may label each parameter with a comment
    tka <- 0.45 # Log Ka
    tcl <- log(c(0, 2.7, 100)) # Log Cl
    ## This works with interactive models
    ## You may also label the preceding line with label("label text")
    tv <- 3.45; label("log V")
    ## the label("Label name") works with all models
    eta.ka ~ 0.6
    eta.cl ~ 0.3
    eta.v ~ 0.1
    add.sd <- 0.7
  })
  model({
    ka <- exp(tka + eta.ka)
    cl <- exp(tcl + eta.cl)
    v <- exp(tv + eta.v)
    linCmt() ~ add(add.sd)
  })
}

# run without tables step
f <- nlmixr2(one.cmt, theo_sd, "saem", control=list(calcTables=FALSE))

print(f)

# Now add the tables

f <- addTable(f)

print(f)



Control options for the agq estimation method

Description

This is the control options for the adaptive Gauss-Hermite quadrature for the likelihood. Note that nAGQ=1 is the same as the Laplace method.

Usage

agqControl(
  sigdig = 3,
  nAGQ = 2,
  ...,
  interaction = TRUE,
  agqLow = -Inf,
  agqHi = Inf
)

Arguments

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

nAGQ

Number of Gauss-Hermite adaptive quadrature points. '0' disables AGQ; '1' is equivalent to Laplace. Cost grows quickly with ETAs: once the EBE is found, expect 'nAGQ^neta' (even 'nAGQ') or '(nAGQ^neta)-1' (odd 'nAGQ') additional evaluations per subject.

...

Parameters used in the default 'foceiControl()'

interaction

boolean, Interaction term for the model, in this case the default is 'TRUE'; For adaptive quadrature, with normal distribution the Hessian is calculated with the foce(i) approximation

agqLow

The lower bound for adaptive quadrature log-likelihood. By default this is -Inf; in the original nlmixr's gnlmm it was -700.

agqHi

The upper bound for adaptive quadrature log-likelihood. By default this is Inf; in the original nlmixr's gnlmm was 400.

Value

agqControl object

Author(s)

Matthew L. Fidler

Examples




agqControl()

# Use adaptive quadrature

# x =  Litter size after 21 days, and the modeled value

r <- rats
r$dv <- r$x

# Time is not used in this model, but it is required in nlmixr2
# currently, add a dummy value

r$time <- 0

f <- function() {
  ini({
    t1 <- 1
    t2 <- 1
    t3 <- 1
    eta1 ~ 1
  })
  model({
    lp <- t1 * x1 + t2 * x2 + (x1 + x2*t3) * eta1
    p <- pnorm(lp)
    m1 <- m # need to add outside of model specification
    x ~ dbinom(m1, p)
  })
}

fit <- nlmixr(f, r, est="agq")


p <- pump

p$dv <- p$y
p$time <- 0 # dummy time

f <- function() {
  ini({
    t1 <- 1
    t2 <- 1
    t3 <- 1
    t4 <- 1
    eta1 ~ 1
  })
  model({
    if (group == 1) {
       lp <- t1 + t2 * logtstd
    } else {
       lp <- t3 + t4 * logtstd
    }
    lp <- lp + eta1
    lam <- exp(lp)
    y ~ dpois(lam)
  })
}

fit <- nlmixr(f, p, est="agq", control=agqControl(nAGQ=5))

one.cmt <- function() {
  ini({
    ## You may label each parameter with a comment
    tka <- 0.45 # Log Ka
    tcl <- log(c(0, 2.7, 100)) # Log Cl
    ## This works with interactive models
    ## You may also label the preceding line with label("label text")
    tv <- 3.45; label("log V")
    ## the label("Label name") works with all models
    eta.ka ~ 0.6
    eta.cl ~ 0.3
    eta.v ~ 0.1
    add.sd <- 0.7
 })
 model({
   ka <- exp(tka + eta.ka)
   cl <- exp(tcl + eta.cl)
   v <- exp(tv + eta.v)
   linCmt() ~ add(add.sd)
 })
}

fit <- nlmixr(one.cmt, theo_sd, est="agq")




Assert that this is a nlmixr2 fit object

Description

Will error without nlmixr2 fit object

Usage

assertNlmixrFit(fit)

Arguments

fit

Fit object

Value

Nothing

Author(s)

Matthew L. Fidler

Examples

## Not run: 

f <- 4
assertNlmixrFit(f) # throw error


## End(Not run)

Assert that this is a nlmixr2 fit data object

Description

Will error without nlmixr2 fit data object

Usage

assertNlmixrFitData(fit)

Arguments

fit

Fit object

Value

Nothing

Author(s)

Matthew L. Fidler

Examples

## Not run: 

f <- 4
assertNlmixrFitData(f) # throw errors


## End(Not run)

Control for bobyqa estimation method in nlmixr2

Description

Control for bobyqa estimation method in nlmixr2

Usage

bobyqaControl(
  npt = NULL,
  rhobeg = NULL,
  rhoend = NULL,
  iprint = 0L,
  maxfun = 100000L,
  returnBobyqa = FALSE,
  stickyRecalcN = 4,
  maxOdeRecalc = 5,
  odeRecalcFactor = 10^(0.5),
  indTolRelax = TRUE,
  useColor = NULL,
  printNcol = NULL,
  print = 1L,
  normType = c("rescale2", "mean", "rescale", "std", "len", "constant"),
  scaleType = c("nlmixr2", "norm", "mult", "multAdd"),
  scaleCmax = 1e+05,
  scaleCmin = 1e-05,
  scaleC = NULL,
  scaleTo = 1,
  rxControl = NULL,
  optExpression = TRUE,
  sumProd = FALSE,
  literalFix = TRUE,
  literalFixRes = TRUE,
  addProp = c("combined2", "combined1"),
  calcTables = TRUE,
  compress = FALSE,
  covMethod = c("r", ""),
  adjObf = TRUE,
  ci = 0.95,
  sigdig = 3,
  sigdigTable = NULL,
  eventSens = c("jump", "fd"),
  ...
)

Arguments

npt

Number of points for the quadratic approximation to the objective; must be in '[n+2, (n+1)(n+2)/2]'. Defaults to 'min(n*2, n+2)'.

rhobeg

Initial trust region radius (with 'rhoend', must satisfy '0 < rhoend < rhobeg'). Defaults to 'min(0.95, 0.2*max(abs(par)))'; adjusted upward if smaller than 'abs(upper-lower)/2'.

rhoend

Final trust region radius. When 'NULL' (default) it is derived from 'sigdig' the way 'foceiControl()' does ('10^(-sigdig)'); otherwise the minqa '1e-6*rhobeg' default applies.

iprint

Controls amount of printing ('0'=none, '1'=start/end only, '2'=each new rho, '3'=every function evaluation, '>3'=every 'iprint' evaluations). Default '0'.

maxfun

The maximum allowed number of function evaluations. If this is exceeded, the method will terminate.

returnBobyqa

return the bobyqa output instead of the nlmixr2 fit

stickyRecalcN

The number of bad ODE solves before reducing the atol/rtol for the rest of the problem.

maxOdeRecalc

Maximum number of times to reduce the ODE tolerances and try to resolve the system if there was a bad ODE solve.

odeRecalcFactor

The ODE recalculation factor when ODE solving goes bad, this is the factor the rtol/atol is reduced

indTolRelax

When 'TRUE' (default), only subjects whose ODE solve produced NaN/Inf have their tolerances relaxed, and the relaxed tolerance persists across optimizer calls (sticky). When 'FALSE', all subjects have their tolerances relaxed on each retry and tolerances are reset afterward.

useColor

Logical (or 'NULL') emit ANSI bold/color escapes in the iteration print. 'NULL' (default) defers to [crayon::has_color()].

printNcol

Integer (or 'NULL') parameter columns per row before wrapping. 'NULL' (default) uses 'floor((getOption("width") - 23) / 12)'.

print

Either a scalar print-frequency ('0' = suppress, '1' (default) = every evaluation, 'N' = every Nth), OR a pre-built [iterPrintControl()] object. Equivalent to 'iterPrintControl(every = print, ncol = printNcol, useColor = useColor)'.

normType

Parameter normalization/scaling used to get scaled initial values for scaleType, of the form Vscaled = (Vunscaled-C1)/C2 (see Feature Scaling; rescale2 follows the OptdesX manual): "rescale2" scales all parameters to (-1, 1); "rescale" (min-max) scales to (0, 1); "mean" centers on the mean with range (0, 1); "std" standardizes by mean/sd; "len" scales to unit (Euclidean) length; "constant" performs no normalization (C1=0, C2=1).

scaleType

The scaling scheme for nlmixr2: "nlmixr2" (default) scales as (current-init)*scaleC[i] + scaleTo, with scaleTo from normType and scales from scaleC; "norm" uses the simple scaling from normType; "mult" scales multiplicatively as current/init*scaleTo; "multAdd" scales linearly ((current-init)+scaleTo) for parameters in an exponential block (e.g. exp(theta)) and multiplicatively otherwise.

scaleCmax

Maximum value of the scaleC to prevent overflow.

scaleCmin

Minimum value of the scaleC to prevent underflow.

scaleC

Scaling constant used with scaleType="nlmixr2"; when not specified, chosen by parameter type to keep gradient sizes similar on a log scale: '1' for exp()-transformed/power/boxCox/ yeoJohnson parameters, '0.5*abs(est)' for additive/proportional/ lognormal error parameters, 'abs(1/digamma(est+1))' for factorials, and 'log(abs(est))*abs(est)' for log-scale parameters. May be set explicitly per parameter if these defaults don't apply well.

scaleTo

Scale the initial parameter estimate to this value. By default this is 1. When zero or below, no scaling is performed.

rxControl

'rxode2' ODE solving options during fitting, created with 'rxControl()'

optExpression

Optimize the rxode2 expression to speed up calculation. By default this is turned on.

sumProd

Is a boolean indicating if the model should change multiplication to high precision multiplication and sums to high precision sums using the PreciseSums package. By default this is FALSE.

literalFix

boolean, substitute fixed population values as literals and re-adjust ui and parameter estimates after optimization; Default is 'TRUE'.

literalFixRes

boolean, substitute fixed population values as literals and re-adjust ui and parameter estimates after optimization; Default is 'TRUE'.

addProp

Type of additive-plus-proportional error: '"combined1"', where standard deviations add:

y = f + (a + b\times f^c) \times \varepsilon

; or '"combined2"', where variances add:

y = f + \sqrt{a^2 + b^2\times f^{2\times c}} \times \varepsilon

. Here y = observed, f = predicted, a = additive sd, b = proportional/power sd, c = power exponent (1 in the proportional case).

calcTables

This boolean is to determine if the foceiFit will calculate tables. By default this is TRUE

compress

Should the object have compressed items

covMethod

Method for calculating the covariance. "r" (the default) uses nlmixr2's nlmixr2Hess() Hessian; "" skips the covariance step.

adjObf

is a boolean to indicate if the objective function should be adjusted to be closer to NONMEM's default objective function. By default this is TRUE

ci

Confidence level for some tables. By default this is 0.95 or 95% confidence.

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

sigdigTable

Significant digits in the final output table. If not specified, then it matches the significant digits in the 'sigdig' optimization algorithm. If 'sigdig' is NULL, use 3.

eventSens

Controls how dosing/event-parameter ('alag', 'F', 'rate', 'dur') sensitivities are computed for THETA/ETA gradients: ‘"jump"' (default) uses rxode2’s analytic event sensitivities; '"fd"' uses the legacy finite-difference behavior.

...

Ignored parameters

Value

bobqya control structure

Author(s)

Matthew L. Fidler

Examples



# A logit regression example with emax model

dsn <- data.frame(i=1:1000)
dsn$time <- exp(rnorm(1000))
dsn$DV=rbinom(1000,1,exp(-1+dsn$time)/(1+exp(-1+dsn$time)))

mod <- function() {
 ini({
   E0 <- 0.5
   Em <- 0.5
   E50 <- 2
   g <- fix(2)
 })
 model({
   v <- E0+Em*time^g/(E50^g+time^g)
   ll(bin) ~ DV * v - log(1 + exp(v))
 })
}

fit2 <- nlmixr(mod, dsn, est="bobyqa")

print(fit2)

# you can also get the bobyqa output with

fit2$bobyqa


Cox Box, Yeo Johnson and inverse transformation

Description

Cox Box, Yeo Johnson and inverse transformation

Usage

boxCox(x, lambda = 1)

iBoxCox(x, lambda = 1)

yeoJohnson(x, lambda = 1)

iYeoJohnson(x, lambda = 1)

Arguments

x

data to transform

lambda

Cox-box lambda parameter

Value

Cox-Box Transformed Data

Author(s)

Matthew L. Fidler

Examples


boxCox(1:3,1) ## Normal
iBoxCox(boxCox(1:3,1))

boxCox(1:3,0) ## Log-Normal
iBoxCox(boxCox(1:3,0),0)

boxCox(1:3,0.5) ## lambda=0.5
iBoxCox(boxCox(1:3,0.5),0.5)

yeoJohnson(seq(-3,3),1) ## Normal
iYeoJohnson(yeoJohnson(seq(-3,3),1))

yeoJohnson(seq(-3,3),0)
iYeoJohnson(yeoJohnson(seq(-3,3),0),0)

Generalized Cholesky Matrix Decomposition

Description

Performs a (modified) Cholesky factorization of the form

Usage

cholSE(matrix, tol = (.Machine$double.eps)^(1/3))

Arguments

matrix

Matrix to be Factorized.

tol

Tolerance; Algorithm suggests (.Machine$double.eps) ^ (1 / 3), default

Details

t(P) %*% A %*% P + E = t(R) %*% R

As detailed in Schnabel/Eskow (1990)

Value

Generalized Cholesky decomposed matrix.

Note

This version does not pivot or return the E matrix

Author(s)

Matthew L. Fidler (translation), Johannes Pfeifer, Robert B. Schnabel and Elizabeth Eskow

References

matlab source: http://www.dynare.org/dynare-matlab-m2html/matlab/chol_SE.html; Slightly different return values

Robert B. Schnabel and Elizabeth Eskow. 1990. "A New Modified Cholesky Factorization," SIAM Journal of Scientific Statistical Computing, 11, 6: 1136-58.

Elizabeth Eskow and Robert B. Schnabel 1991. "Algorithm 695 - Software for a New Modified Cholesky Factorization," ACM Transactions on Mathematical Software, Vol 17, No 3: 306-312


Control for the variational inference methods emvi and fbvi in nlmixr2

Description

Variational-inference NLME estimation in the style of Kucukelbir et al. (2017): the latent variables are transformed to an unconstrained real coordinate space, a Gaussian variational family is posited there, and the ELBO is maximized by stochastic gradient ascent using the reparameterization trick.

Usage

emviControl(
  seed = 42L,
  iters = 300L,
  nMc = 1L,
  viFamily = c("fullRank", "meanField"),
  pointEstimate = NULL,
  optim = c("advi", "adam"),
  adaptEta = TRUE,
  perNoCor = 0.75,
  etaCandidates = c(0.01, 0.025, 0.05, 0.1, 0.25),
  tau = 1,
  alpha = 0.1,
  tol = NULL,
  evalElbo = 100L,
  klWarmup = 0L,
  temperInit = 10,
  likelihood = c("focei", "foce", "focep", "laplace"),
  returnVi = FALSE,
  resume = NULL,
  print = 1L,
  useColor = NULL,
  printNcol = NULL,
  covMethod = c("vi", "analytic", "r,s", "r", "s", ""),
  optExpression = TRUE,
  sumProd = FALSE,
  literalFix = TRUE,
  literalFixRes = TRUE,
  addProp = c("combined2", "combined1"),
  calcTables = TRUE,
  compress = FALSE,
  adjObf = TRUE,
  ci = 0.95,
  sigdig = 3,
  sigdigTable = NULL,
  stickyRecalcN = 4,
  maxOdeRecalc = 5,
  odeRecalcFactor = 10^(0.5),
  indTolRelax = TRUE,
  eventSens = c("jump", "fd"),
  rxControl = NULL,
  ...
)

Arguments

seed

Random seed for the variational optimization (reparameterization sampling); default 42. The Monte-Carlo gradient is stochastic, so a fixed seed makes every fit reproducible. Reparameterization noise is drawn from a counter-based stream keyed by the global iteration index, so a shorter run is a bit-for-bit prefix of a longer one and results are independent of the number of cores.

iters

Total number of stochastic gradient ascent iterations.

nMc

Number of Monte-Carlo samples used to approximate the ELBO gradient at each iteration (the paper's 'M'; typically 1-10).

viFamily

Variational family in the unconstrained space. '"fullRank"' (default) uses a block full-rank Gaussian: a dense 'neta x neta' Cholesky factor per subject plus a dense block over the population vector (mean-field across blocks). '"meanField"' uses a fully factorized (diagonal) Gaussian. Mean-field is faster but is known to underestimate marginal variances.

pointEstimate

Which of the two methods to run, normally left at its 'NULL' default so it follows 'est': 'est="emvi"' implies 'TRUE' and 'est="fbvi"' implies 'FALSE'. 'est' wins over a contradicting value, and says so – it has to, because re-estimating a fit with the other method pipes the completed fit's control forward. 'TRUE' runs the variational-EM hybrid: the variational posterior covers the per-subject etas only, and the population parameters (thetas / omega / residual error) are point estimates maximized by the ELBO gradient; output semantics match FOCEi/SAEM. 'FALSE' runs full Bayes: the variational posterior also covers the unconstrained population vector, with flat priors.

Two things about "flat" are worth being explicit about, because they define the prior rather than merely describe the implementation. (1) A BOUNDED theta is fitted on its unconstrained scale, and the log-determinant of that constraining transform IS added to the full-Bayes objective, so the flat prior is flat on the NATURAL parameter, as in Stan. It is deliberately NOT added when 'pointEstimate=TRUE': a maximum-likelihood estimate has to stay invariant to reparameterization, which is why Stan's own 'optimize' defaults to 'jacobian=0'. (2) The between-subject variances are carried as per-eta LOG-variances and no Jacobian is applied to them, so the prior is flat on 'log(omega)' – the conventional weakly-informative choice for a scale parameter, but a choice, not an accident: it is not flat on 'omega'.

These point estimates maximize the ELBO, NOT the likelihood, and the difference is not merely cosmetic. Since 'ELBO = log p(y|theta) - KL(q || p(eta|y,theta))', any dependence of that KL on 'theta' displaces the maximizer from the MLE – "variational maximum likelihood". For VARIANCE components the displacement has a known direction: a variational family that understates posterior spread makes the omega M-step, ‘Omega = mean_i(mu_i mu_i’ + Sigma_i)', inherit that understatement, so between-subject variability is biased DOWNWARD. The bias is worst for 'viFamily="meanField"', which cannot represent within-subject posterior correlation at all; '"fullRank"' can, which is why it is the default. Structural (typical-value) parameters are far less affected. If the between-subject variances are themselves the quantity of interest, prefer '"fullRank"' and cross-check against 'est="focei"' or 'est="saem"'.

optim

Stochastic optimizer. '"advi"' (default) uses the adaptive step-size sequence from the ADVI paper (Eqs 10-11) – the value keeps that name because the step-size rule really is the published one, even though the surrounding method is not; '"adam"' uses Adam.

adaptEta

When 'TRUE' (default) adaptively choose the step-size scale 'eta' by a short search over 'etaCandidates' before the main loop; when 'FALSE' use a fixed 'eta' (the first 'etaCandidates' entry).

perNoCor

Fraction of the run over which a declared correlated 'omega' block is held at zero correlation, letting the population variances settle before the correlations are estimated. This is saemControl()'s 'perNoCor' rule (0.75 there as well); it has no effect on a model with no declared off-diagonals.

Held at ZERO, following saem, not at the 'ini()' value: retaining an initial covariance while the variances shrink around it can leave the block non-positive-definite. A 'fixed()' covariance is exempt – it is not being estimated, so it keeps its value through the hold and out the other side. When the correlations are released the off-diagonal gain restarts rather than continuing the decayed schedule, so they are still estimable at the point they are unfrozen. This is needed here and not in vaeControl(): there the fraction is of the EM phase, where the gain is still 1 at release, whereas this run has no such phase and the fraction lands in the decayed schedule.

A value greater than 1 is an ABSOLUTE iteration count rather than a fraction, and must be a whole number. The resolved absolute iteration is stored with the fit and reused by 'resume=', so a resumed run releases the correlations at the same global iteration a single long run would – recomputing the fraction from the resumed call's 'iters' would re-apply a hold the original run had passed. Only 'est="emvi"' estimates the block at all; 'est="fbvi"' carries 'omega' as per-eta log-variances and errors on a correlated model rather than dropping the off-diagonal.

etaCandidates

Candidate step-size scales searched when 'adaptEta' is ‘TRUE'. The default is narrower and smaller-valued than the paper’s 'c(0.01, 0.1, 1, 10, 100)' because these gradients come from FOCEi sensitivities on the model's own scale rather than from AD through a Stan program, so the useful step sizes sit lower; the paper's grid can be passed verbatim if wanted. Each candidate costs 'min(iters, 75)' iterations (a diverging one aborts early and is cheap), so the search is a substantial share of a fit – widen it deliberately. When the search selects the largest or smallest candidate the grid may be the binding constraint, and the fit says so in '$runInfo'; '$etaScores' reports the per-candidate scores behind the choice.

tau

Stabilizing constant 'tau > 0' in the step-size denominator (paper Eq 10); the step-size is insensitive to it.

alpha

Weighting 'alpha' in (0, 1) of new vs old gradient information in the step-size memory recursion (paper Eq 11).

tol

Convergence tolerance on the relative change in the ELBO: the loop stops early once the change falls below this. 'NULL' (default) derives it from 'sigdig' as '10^(-sigdig)', the same rule 'saemControl()' and 'foceiControl()' use for their optimizer tolerances, so it tightens with 'sigdig' instead of staying pinned. '0' disables early stopping (run all 'iters'). Because the per-iteration ELBO is an 'nMc'-sample Monte-Carlo estimate and therefore noisy, the test compares the MEAN over the last 'evalElbo' iterations against the mean over the window before it, rather than consecutive iterations. The 'adaptEta' step-size search never stops early on this criterion (its scorer reads a short run as divergence).

evalElbo

Window length, in iterations, for the 'tol' convergence test. Stan's ADVI re-evaluates the ELBO every 100 iterations with fresh draws; averaging the draws already taken is the cheaper equivalent. Shrunk automatically on a short run so 'iters' well below 'evalElbo' can still trigger the check.

klWarmup

Number of iterations of PRIOR TEMPERING (0, the default, disables it). During the warm-up the population prior is inflated by a factor ramping geometrically from 'temperInit' down to 1, which down-weights the prior term of the ELBO and keeps the per-subject variational posterior from collapsing before it is informative. This is the variational analogue of saemControl()'s 'perSa' simulated-annealing phase (true simulated annealing does not transfer: variational inference has no MCMC kernel to keep wide).

It CHANGES THE OBJECTIVE FUNCTION MID-RUN. Early iterations maximize a tempered surrogate rather than the ELBO, so the convergence theory for the ELBO does not cover the warm-up, the reported ELBO trace is not comparable across the boundary, and the 'tol' early-stopping test is suppressed until tempering ends. The 'adaptEta' step-size search also scores candidates on the untempered objective. Off by default for those reasons; turn it on for a model where the variational scale collapses early.

temperInit

Initial prior inflation factor for 'klWarmup' tempering (default 10); ignored when 'klWarmup = 0'.

likelihood

Inner likelihood used for the per-subject objective and gradient, run through the FOCEi inner interface: '"focei"' (default), '"foce"', '"focep"', or '"laplace"'.

returnVi

When 'TRUE' return the raw variational optimization object instead of the nlmixr2 fit.

resume

Optional warm-resume state: a previous 'emvi'/'fbvi' fit (or its '$env$viState'). The optimization continues from that state for 'iters' more iterations, bit-for-bit identical to a single fresh run of the combined length (the counter-based RNG is keyed by the global iteration index).

That equivalence requires every schedule point to be an ABSOLUTE iteration. A FRACTIONAL 'perNoCor' cannot provide it, and not because of any bookkeeping that could be fixed: 'perNoCor = 0.75' of one 120-iteration run releases the correlations at iteration 90, while 0.75 of a first 60-iteration leg releases at 45. Those are different schedules, and the resulting correlation estimates genuinely differ. Pin the schedule ('perNoCor = 90') whenever a fit may be resumed; the resolved value is then stored with the fit and reused.

print

Either a scalar print-frequency ('0' = suppress, '1' (default) = every evaluation, 'N' = every Nth), OR a pre-built [iterPrintControl()] object. Equivalent to 'iterPrintControl(every = print, ncol = printNcol, useColor = useColor)'.

useColor

Logical (or 'NULL') emit ANSI bold/color escapes in the iteration print. 'NULL' (default) defers to [crayon::has_color()].

printNcol

Integer (or 'NULL') parameter columns per row before wrapping. 'NULL' (default) uses 'floor((getOption("width") - 23) / 12)'.

covMethod

Method for calculating covariance. In this discussion, R is the Hessian matrix of the objective function. The S matrix is the sum of each individual's gradient cross-product (evaluated at the individual empirical Bayes estimates).

"sa" (default) Use the stochastic-approximation Fisher Information Matrix. After estimation, a dedicated covariance phase (nSaCov iterations) holds the parameters at the converged estimate and keeps resimulating the individual parameters, Monte-Carlo averaging the Louis observed-information integrand into a converged FIM decoupled from the cooling schedule (the approach used by Monolix; Kuhn & Lavielle 2005). Always includes every estimated population parameter (theta, the Omega diagonal variances, and residual).

"analytic" Compute the FOCEI analytic observed-information covariance at the converged SAEM estimates. When the model is out of analytic-covariance scope (e.g. linCmt(), a non-normal likelihood, or a non-SD IOV parameterization) or the result is not positive definite, it falls back to the linearized Fisher information (linFim) with a message.

"linFim" Use the Linearized Fisher Information Matrix to calculate the covariance.

"fim" Use the Fisher Information Matrix accumulated during SAEM estimation to calculate the covariance. Like sa it inverts the observed information to a full theta + Omega diagonal + residual covariance, but uses the (noisier) estimation-phase matrix rather than a dedicated cov phase.

For both fim and sa the simulation-based Fisher information covers the structural theta, the Omega diagonal variances, and additive residual error. Off-diagonal Omega covariances and proportional/combined residual error are not estimated reliably by the simulation FIM (the complete-data correction is unstable when between-subject variability dominates the residual), so those variance-block standard errors are spliced in from the linearized FIM (linFim).

"r,s" Uses the sandwich matrix to calculate the covariance, that is: R^-1 \times S \times R^-1

"r" Uses the Hessian matrix to calculate the covariance as 2\times R^-1

"s" Uses the crossproduct matrix to calculate the covariance as 4\times S^-1

"" Does not calculate the covariance step.

optExpression

Optimize the rxode2 expression to speed up calculation. By default this is turned on.

sumProd

Is a boolean indicating if the model should change multiplication to high precision multiplication and sums to high precision sums using the PreciseSums package. By default this is FALSE.

literalFix

boolean, substitute fixed population values as literals and re-adjust ui and parameter estimates after optimization; Default is 'TRUE'.

literalFixRes

boolean, substitute fixed population values as literals and re-adjust ui and parameter estimates after optimization; Default is 'TRUE'.

addProp

Type of additive-plus-proportional error: '"combined1"', where standard deviations add:

y = f + (a + b\times f^c) \times \varepsilon

; or '"combined2"', where variances add:

y = f + \sqrt{a^2 + b^2\times f^{2\times c}} \times \varepsilon

. Here y = observed, f = predicted, a = additive sd, b = proportional/power sd, c = power exponent (1 in the proportional case).

calcTables

This boolean is to determine if the foceiFit will calculate tables. By default this is TRUE

compress

Should the object have compressed items

adjObf

is a boolean to indicate if the objective function should be adjusted to be closer to NONMEM's default objective function. By default this is TRUE

ci

Confidence level for some tables. By default this is 0.95 or 95% confidence.

sigdig

Specifies the "significant digits" that the ODE solving requests. This is NULL by default, and while it is NULL it has no effect at all: rxSolve() uses the standard atol/rtol (and the standard sensitivity and steady-state tolerances). sigdig only changes a tolerance when you ask for it explicitly.

When it is supplied, the tolerances are derived with one solver-independent formula – the same for stiff, non-stiff and auto-switching solvers. The rtol exponent IS sigdig and atol sits three orders below it:

  • rtol = 10^(-sigdig), atol = 10^(-sigdig-3)

  • the sensitivity tolerances match the main solve, so rtolSens = rtol and atolSens = atol (gradients and covariances are built from them)

  • the steady-state tolerances run one order looser than the corresponding main tolerance, so ssRtol = ssRtolSens = 10*rtol and ssAtol = ssAtolSens = 10*atol

Each of these is set only when you did not pass that tolerance yourself; a tolerance you supply always wins. Because they are resolved independently, an explicit atol/rtol overrides the main solve but does not propagate to the sensitivity or steady-state tolerances – set those directly if you need them changed too.

This mapping matches how nlmixr2est derives solver tolerances from its optimization sigdig, so a sigdig used for estimation and the same sigdig used for a plain rxSolve() mean the same thing. Note it is keyed to sigdig as a request for that many significant digits, and is looser than the atol/rtol defaults for small sigdig – at sigdig = 4 it gives rtol = 1e-4 against a default rtol = 1e-6. Raise sigdig, or set atol/rtol directly, when you want a tighter solve.

sigdigTable

Significant digits in the final output table. If not specified, then it matches the significant digits in the 'sigdig' optimization algorithm. If 'sigdig' is NULL, use 3.

stickyRecalcN

The number of bad ODE solves before reducing the atol/rtol for the rest of the problem.

maxOdeRecalc

Maximum number of times to reduce the ODE tolerances and try to resolve the system if there was a bad ODE solve.

odeRecalcFactor

The ODE recalculation factor when ODE solving goes bad, this is the factor the rtol/atol is reduced

indTolRelax

When 'TRUE' (default), only subjects whose ODE solve produced NaN/Inf have their tolerances relaxed, and the relaxed tolerance persists across optimizer calls (sticky). When 'FALSE', all subjects have their tolerances relaxed on each retry and tolerances are reset afterward.

eventSens

Controls how dosing/event-parameter ('alag', 'F', 'rate', 'dur') sensitivities are computed for THETA/ETA gradients: ‘"jump"' (default) uses rxode2’s analytic event sensitivities; '"fd"' uses the legacy finite-difference behavior.

rxControl

'rxode2' ODE solving options during fitting, created with 'rxControl()'

...

Other arguments to control SAEM.

Details

One control serves both methods, which differ only in what the variational posterior covers:

'pointEstimate' is the switch between them and defaults to whichever the chosen 'est' implies. 'est' decides: a control that contradicts it is overridden, with a message saying so.

Neither method is the published ADVI algorithm, which is why neither is named for it. Two deviations matter. First, even 'fbvi' parameterizes the between-subject omega as per-eta log-variances rather than freely, so a full-rank family does not yield the joint posterior covariance over the whole parameter vector that published ADVI gives. Second, the gradient of the log-joint comes from the FOCEi forward sensitivities (inner per-subject eta gradient plus the outer population sensitivity contraction) rather than from automatic differentiation – there is no AD in this implementation, which is why "advi" would misname it. Results should therefore not be read as reproducing a Stan 'vb()' fit except on models where the two objectives coincide. The whole optimization loop runs in C++.

Value

variational-inference control structure (class 'emviControl')

Author(s)

Matthew L. Fidler


Control for the fbvi (full-Bayes variational inference) method

Description

A convenience wrapper around [emviControl()] with 'pointEstimate = FALSE', i.e. the variational posterior covers the unconstrained population vector (under flat priors) as well as the per-subject etas, rather than point-estimating the population parameters by an M-step. See [emviControl()] for the full parameter list.

Usage

fbviControl(..., pointEstimate = FALSE)

Arguments

...

Parameters passed to [emviControl()].

pointEstimate

Which of the two methods to run, normally left at its 'NULL' default so it follows 'est': 'est="emvi"' implies 'TRUE' and 'est="fbvi"' implies 'FALSE'. 'est' wins over a contradicting value, and says so – it has to, because re-estimating a fit with the other method pipes the completed fit's control forward. 'TRUE' runs the variational-EM hybrid: the variational posterior covers the per-subject etas only, and the population parameters (thetas / omega / residual error) are point estimates maximized by the ELBO gradient; output semantics match FOCEi/SAEM. 'FALSE' runs full Bayes: the variational posterior also covers the unconstrained population vector, with flat priors.

Two things about "flat" are worth being explicit about, because they define the prior rather than merely describe the implementation. (1) A BOUNDED theta is fitted on its unconstrained scale, and the log-determinant of that constraining transform IS added to the full-Bayes objective, so the flat prior is flat on the NATURAL parameter, as in Stan. It is deliberately NOT added when 'pointEstimate=TRUE': a maximum-likelihood estimate has to stay invariant to reparameterization, which is why Stan's own 'optimize' defaults to 'jacobian=0'. (2) The between-subject variances are carried as per-eta LOG-variances and no Jacobian is applied to them, so the prior is flat on 'log(omega)' – the conventional weakly-informative choice for a scale parameter, but a choice, not an accident: it is not flat on 'omega'.

These point estimates maximize the ELBO, NOT the likelihood, and the difference is not merely cosmetic. Since 'ELBO = log p(y|theta) - KL(q || p(eta|y,theta))', any dependence of that KL on 'theta' displaces the maximizer from the MLE – "variational maximum likelihood". For VARIANCE components the displacement has a known direction: a variational family that understates posterior spread makes the omega M-step, ‘Omega = mean_i(mu_i mu_i’ + Sigma_i)', inherit that understatement, so between-subject variability is biased DOWNWARD. The bias is worst for 'viFamily="meanField"', which cannot represent within-subject posterior correlation at all; '"fullRank"' can, which is why it is the default. Structural (typical-value) parameters are far less affected. If the between-subject variances are themselves the quantity of interest, prefer '"fullRank"' and cross-check against 'est="focei"' or 'est="saem"'.

Value

An 'emviControl' object with 'pointEstimate = FALSE'.

Author(s)

Matthew L. Fidler

Examples


fbviControl()

Control options for the FO estimation method

Description

This is related to the focei methods and uses most of their control options. Some are ignored, 'posthoc' is an extra parameter

Usage

foControl(sigdig = 3, ..., posthoc = TRUE, interaction = NULL, fo = NULL)

Arguments

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

...

Parameters used in the default 'foceiConrol()'

posthoc

Logical indicating if the estimation method should calculate 'foce' posthoc predicted parameters.

interaction

Interaction term for the model; ignored by fo

fo

Logical indicating if the estimation method is FO (first order), but this is controlled by the estimation method so this is ignored.

Value

foControl object

Author(s)

Matthew L. Fidler

Examples


foControl()

Control options for the foce estimation method

Description

This is the first order option without the interaction between residuals and etas.

Usage

foceControl(sigdig = 3, ..., interaction = FALSE)

Arguments

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

...

Parameters used in the default 'foceiControl()'

interaction

Interaction term for the model, in this case the default is 'FALSE'; it cannot be changed, use 'focei' instead

Value

foceControl object

Author(s)

Matthew L. Fidler

Examples


foceControl()

Control Options for FOCEi

Description

Control Options for FOCEi

Usage

foceiControl(
  sigdig = 3,
  ...,
  epsilon = NULL,
  maxInnerIterations = 1000,
  maxOuterIterations = 5000,
  n1qn1nsim = NULL,
  print = 1L,
  printNcol = NULL,
  scaleTo = 1,
  scaleObjective = 0,
  normType = c("rescale2", "mean", "rescale", "std", "len", "constant"),
  scaleType = c("nlmixr2", "norm", "mult", "multAdd"),
  scaleCmax = 1e+05,
  scaleCmin = 1e-05,
  scaleCband = c(0.1, 10),
  scaleC = NULL,
  scaleC0 = 1e+05,
  derivEps = rep(20 * sqrt(.Machine$double.eps), 2),
  derivMethod = c("switch", "forward", "central"),
  derivSwitchTol = NULL,
  covDerivMethod = c("central", "forward"),
  covMethod = c("r,s", "analytic", "r", "s", "sa", "imp", ""),
  covSolveTol = NULL,
  covFull = TRUE,
  fast = FALSE,
  fdChartrand = TRUE,
  foceEbeTol = NULL,
  hessEps = (.Machine$double.eps)^(1/3),
  hessEpsLlik = (.Machine$double.eps)^(1/3),
  optimHessType = c("central", "forward"),
  optimHessCovType = c("central", "forward"),
  censOption = c("gauss", "laplace"),
  eventType = c("central", "forward"),
  eventSens = c("jump", "fd"),
  centralDerivEps = rep(20 * sqrt(.Machine$double.eps), 2),
  lbfgsLmm = 7L,
  lbfgsPgtol = 0,
  lbfgsFactr = NULL,
  eigen = TRUE,
  diagXform = c("sqrt", "log", "identity"),
  iovXform = c("sd", "var", "logsd", "logvar"),
  sumProd = FALSE,
  optExpression = TRUE,
  literalFix = TRUE,
  literalFixRes = TRUE,
  ci = 0.95,
  useColor = NULL,
  boundTol = NULL,
  calcTables = TRUE,
  noAbort = TRUE,
  interaction = TRUE,
  foce = c("nonmem", "foce+"),
  cholSEtol = (.Machine$double.eps)^(1/3),
  cholAccept = 0.001,
  resetEtaP = 0.15,
  resetThetaP = 0,
  resetThetaFinalP = 0,
  diagOmegaBoundUpper = 5,
  diagOmegaBoundLower = 100,
  cholSEOpt = FALSE,
  cholSECov = FALSE,
  fo = FALSE,
  covTryHarder = FALSE,
  outerOpt = c("bobyqa", "nlminb", "lbfgsb3c", "L-BFGS-B", "mma", "lbfgsbLG", "slsqp",
    "uobyqa", "newuoa"),
  innerOpt = c("n1qn1", "BFGS"),
  rhobeg = 0.2,
  rhoend = NULL,
  npt = NULL,
  rel.tol = NULL,
  x.tol = NULL,
  eval.max = 4000,
  iter.max = 2000,
  abstol = NULL,
  reltol = NULL,
  resetHessianAndEta = FALSE,
  muModel = c("none", "irls", "lin"),
  muRefCovAlg = TRUE,
  muModelTol = 1e-05,
  muModelMaxCycles = 20L,
  muModelClampRetries = 10L,
  stateTrim = Inf,
  shi21maxOuter = 0L,
  shi21maxInner = 20L,
  shi21maxInnerCov = 20L,
  shi21maxFD = 20L,
  shi21hMax = 2,
  shi21hMin = 1e-04,
  gillK = 10L,
  gillStep = 4,
  gillFtol = 0,
  gillRtol = sqrt(.Machine$double.eps),
  gillKcov = 10L,
  gillKcovLlik = 10L,
  gillStepCovLlik = 4.5,
  gillStepCov = 2,
  gillFtolCov = 0,
  gillFtolCovLlik = 0,
  rmatNorm = TRUE,
  rmatNormLlik = TRUE,
  smatNorm = TRUE,
  smatNormLlik = TRUE,
  covGillF = TRUE,
  optGillF = TRUE,
  covSmall = 1e-05,
  adjLik = TRUE,
  gradTrim = Inf,
  maxOdeRecalc = 5,
  odeRecalcFactor = 10^(0.5),
  gradCalcCentralSmall = 1e-04,
  gradCalcCentralLarge = 10000,
  etaNudge = qnorm(1 - 0.05/2)/sqrt(3),
  etaNudge2 = qnorm(1 - 0.05/2) * sqrt(3/5),
  nRetries = 3,
  seed = 42,
  resetThetaCheckPer = 0.1,
  etaMat = NULL,
  repeatGillMax = 1,
  stickyRecalcN = 4,
  outerMaxOdeRecalc = 5,
  outerOdeRecalcFactor = 10^(0.5),
  outerStickyRecalcN = 4,
  indTolRelax = TRUE,
  gradProgressOfvTime = 10,
  addProp = c("combined2", "combined1"),
  badSolveObjfAdj = 100,
  compress = FALSE,
  rxControl = NULL,
  sigdigTable = NULL,
  fallbackFD = FALSE,
  smatPer = 0.6,
  sdLowerFact = 0.001,
  zeroGradFirstReset = TRUE,
  zeroGradRunReset = TRUE,
  zeroGradBobyqa = TRUE,
  mceta = -2L,
  warm = c("calc", "save"),
  nAGQ = 0,
  agqLow = -Inf,
  agqHi = Inf,
  sensMethod = c("default", "forward"),
  zeroTheta = 0.001,
  boundedTransform = TRUE
)

Arguments

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

...

Ignored parameters

epsilon

Precision of estimate for n1qn1 optimization.

maxInnerIterations

Number of iterations for n1qn1 optimization.

maxOuterIterations

Maximum number of L-BFGS-B optimization for outer problem.

n1qn1nsim

Number of function evaluations for n1qn1 optimization.

print

Either a scalar print-frequency ('0' = suppress, '1' (default) = every evaluation, 'N' = every Nth), OR a pre-built [iterPrintControl()] object. Equivalent to 'iterPrintControl(every = print, ncol = printNcol, useColor = useColor)'.

printNcol

Integer (or 'NULL') parameter columns per row before wrapping. 'NULL' (default) uses 'floor((getOption("width") - 23) / 12)'.

scaleTo

Scale the initial parameter estimate to this value. By default this is 1. When zero or below, no scaling is performed.

scaleObjective

Scale the initial objective function to this value. By default this is 0 (meaning do not scale)

normType

Parameter normalization/scaling used to get scaled initial values for scaleType, of the form Vscaled = (Vunscaled-C1)/C2 (see Feature Scaling; rescale2 follows the OptdesX manual): "rescale2" scales all parameters to (-1, 1); "rescale" (min-max) scales to (0, 1); "mean" centers on the mean with range (0, 1); "std" standardizes by mean/sd; "len" scales to unit (Euclidean) length; "constant" performs no normalization (C1=0, C2=1).

scaleType

The scaling scheme for nlmixr2: "nlmixr2" (default) scales as (current-init)*scaleC[i] + scaleTo, with scaleTo from normType and scales from scaleC; "norm" uses the simple scaling from normType; "mult" scales multiplicatively as current/init*scaleTo; "multAdd" scales linearly ((current-init)+scaleTo) for parameters in an exponential block (e.g. exp(theta)) and multiplicatively otherwise.

scaleCmax

Maximum value of the scaleC to prevent overflow.

scaleCmin

Minimum value of the scaleC to prevent underflow.

scaleCband

Length-2 increasing pair 'c(low, high)' (default ‘c(0.1, 10)'). Each 'theta'’s derivative-based scaling constant ('1/|init|' for a linear parameter, or the transform-specific formula) is kept when it lands inside this band, and otherwise replaced by the parameter's native magnitude '|init|'. This catches the singular cases – '1/|init|' blowing up for a small covariate initial estimate, 'log()' at init '1', 'logit' at the interval midpoint, 'factorial'/'gamma' at a digamma zero – while leaving the well-scaled common case (and its results) untouched.

scaleC

Scaling constant used with scaleType="nlmixr2"; when not specified, chosen by parameter type to keep gradient sizes similar on a log scale: '1' for exp()-transformed/power/boxCox/ yeoJohnson parameters, '0.5*abs(est)' for additive/proportional/ lognormal error parameters, 'abs(1/digamma(est+1))' for factorials, and 'log(abs(est))*abs(est)' for log-scale parameters. May be set explicitly per parameter if these defaults don't apply well.

scaleC0

Number to adjust the scaling factor by if the initial gradient is zero.

derivEps

Forward difference tolerances (relative, absolute); step size h = abs(x)*derivEps[1] + derivEps[2].

derivMethod

Derivative method for the outer problem: "switch", "central", or "forward". "switch" starts forward and toggles to central when abs(delta(OFV)) <= derivSwitchTol.

derivSwitchTol

The tolerance to switch forward to central differences.

covDerivMethod

indicates the method for calculating the derivatives while calculating the covariance components (Hessian and S).

covMethod

Method for calculating the covariance. "r,s" (the default) is the sandwich estimator (see below). "analytic" uses the exact analytic observed-information R-matrix (reported as R^{-1}) and additionally returns the residual and Omega standard errors; it covers FOCEI/FOCE fits with additive, proportional, or combined error, mu-referenced/covariate/other structural parameters (and non-mu-referenced etas), and SD-scale inter-occasion variability, and emits a message and falls back to the finite-difference Hessian for anything out of scope (FO, nAGQ > 1, censoring, DV-transformed error, bounded-parameter transforms, a structural theta shared by two etas, non-SD iovXform, or a pure-proportional variance that vanishes at a near-zero prediction). The finite-difference methods use R (the Hessian) and S (the sum of individual gradient cross-products at the empirical Bayes estimates): "r,s" sandwich (solve(R)%*%S%*%solve(R)), "r" Hessian-based (solve(R)), "s" cross-product-based (solve(S)), or "" to skip the covariance step. "sa" (SAEM Louis stochastic-approximation FIM) and "imp" (importance-sampling Monte-Carlo observed information) are also accepted for any method; they are computed post-fit at the converged estimates by the decoupled recompute engine.

covSolveTol

absolute/relative ODE tolerance for the covariance solves – the augmented-sensitivity solves behind covMethod="analytic" and the perturbed solves behind the finite-difference methods. NULL (default) derives a tight tolerance from sigdig; supply a number to override it.

covFull

shape of fit$cov. TRUE (default) installs the full theta + residual sigma + Omega covariance (assembled analytically for covMethod="analytic", or by central finite differences over the same parameter set otherwise). For the finite-difference methods it follows covMethod: "r,s" is the full sandwich solve(Rfull) %*% Sfull %*% solve(Rfull), "s" is solve(Sfull), "r" is solve(Rfull). FALSE installs only the structural-theta block (the historical shape).

fast

When TRUE, compute the outer (population) gradient analytically from Almquist (2015) sensitivity equations instead of by finite differences, and use the Eq-48 random-effect extrapolation for the next inner-problem starting values. Requires an analytic-scope model. Conditionally Gaussian endpoints route through the general (f,R) assembler, which covers more than the plain add/prop case – multiple endpoints, combined and power error, both-sides transforms and a single estimated boxCox/yeoJohnson lambda. A single non-Gaussian (ll()/generalized) endpoint instead differentiates the log-density directly, giving an exact inner Hessian and analytic outer gradient. Out of scope are linCmt(), fo, IOV, more than one estimated lambda, a theta mu-referenced by several random effects, and (for the non-Gaussian path) multiple endpoints, censoring or nAGQ > 1; those fall back to the finite-difference gradient with a message (linCmt() and out-of-scope log-likelihood models downgrade to fast=FALSE up front). When unspecified, the outer optimizer defaults to "lbfgsb3c" (vs "nlminb" for fast=FALSE); pairing fast=TRUE with a derivative-free outerOpt reverts to fast=FALSE. The *f methods (e.g. foceif) default this to TRUE.

fdChartrand

Refine finite-difference slopes that the robust outlier test flags (default TRUE). When a subject's per-parameter slope sits far outside the modified z-score interval of the others, its central difference is suspect; those slopes – and only those – are recomputed with a total-variation regularized derivative (Chartrand) on a wide interval. Set FALSE to keep the plain central difference.

On by default because the outlier test is itself the gate: a well-behaved problem flags nothing and pays nothing, so the cost falls only on the complex fits where a slope really is an outlier – exactly where you would want the refinement, and where a user is least likely to know to ask for it. fit$env$nFdOutlier reports flagged parameters and refined slopes, so you can see whether it engaged for a given fit.

Worth knowing when judging it: the measurements that originally motivated this refinement were taken while the likelihood and the Shi step selection were both faulty, so they do not evidence its value on current code, and it has not been observed to trigger on ordinary fits.

foceEbeTol

Convergence tolerance on the score of the FOCE frozen-variance EBE re-solve, which the analytic outer gradient (fast=TRUE, interaction=FALSE) needs because FOCE's mode is not the inner problem's mode. NULL (default) uses 1e-9; the first iteration uses a looser 1e-3 so an already-stationary eta is returned untouched. Unlike the solver and optimizer tolerances this is not derived from sigdig – it is a convergence target on an inner Newton rather than a precision request. Set it explicitly to test whether a fit's finite-difference fallbacks are tolerance-driven.

hessEps

is a double value representing the epsilon for the Hessian calculation. This is used for the R matrix calculation.

hessEpsLlik

is a double value representing the epsilon for the Hessian calculation when doing focei generalized log-likelihood estimation. This is used for the R matrix calculation.

optimHessType

Hessian type for numeric-difference individual Hessians in generalized log-likelihood estimation: "central" (matches R's 'optimHess()', default) or "forward" (faster).

optimHessCovType

Hessian type for numeric-difference individual Hessians used for the covariance step/final likelihood: "central" (more accurate, used here) or "forward".

censOption

Treatment of the second derivative for censored (M2/M3/M4/BLQ) observations in the FOCEI family. "gauss" (the default) keeps the historic uncensored Gauss-Newton curvature, matching common PMx tools; "laplace" uses the exact censored second derivative of the objective (a proper Laplace inner Hessian and analytic covariance). Accepted by saemControl/nlmControl for a uniform interface but inert there – SAEM (stochastic EM) has no Laplace inner Hessian, and NLM uses a finite-difference Hessian that already reflects censoring exactly.

eventType

Event gradient type for dosing events; Can be "central" or "forward"

eventSens

Controls how dosing/event-parameter ('alag', 'F', 'rate', 'dur') sensitivities are computed for THETA/ETA gradients: ‘"jump"' (default) uses rxode2’s analytic event sensitivities; '"fd"' uses the legacy finite-difference behavior.

centralDerivEps

Central difference tolerances (relative, absolute); step size h = abs(x)*derivEps[1] + derivEps[2].

lbfgsLmm

An integer giving the number of BFGS updates retained in the "L-BFGS-B" method, It defaults to 7.

lbfgsPgtol

Projected-gradient convergence tolerance for "L-BFGS-B": iteration stops when max(| proj g_i |) <= lbfgsPgtol. Defaults to '0' (check suppressed).

lbfgsFactr

Convergence factor for "L-BFGS-B": converges when the objective reduction is within lbfgsFactr * .Machine$double.eps. Derived from sigdig as 10^-sigdig / .Machine$double.eps, so the objective reduction target IS 10^-sigdig.

eigen

A boolean indicating if eigenvectors are calculated to include a condition number calculation.

diagXform

Transformation used on the diagonal of chol(solve(omega)) (the FOCEi-estimated parameters): one of "sqrt" (default), "log", or "identity".

iovXform

Transformation used on the diagonal of the IOV: one of "sd", "var", "logsd", or "logvar".

sumProd

Is a boolean indicating if the model should change multiplication to high precision multiplication and sums to high precision sums using the PreciseSums package. By default this is FALSE.

optExpression

Optimize the rxode2 expression to speed up calculation. By default this is turned on.

literalFix

boolean, substitute fixed population values as literals and re-adjust ui and parameter estimates after optimization; Default is 'TRUE'.

literalFixRes

boolean, substitute fixed population values as literals and re-adjust ui and parameter estimates after optimization; Default is 'TRUE'.

ci

Confidence level for some tables. By default this is 0.95 or 95% confidence.

useColor

Logical (or 'NULL') emit ANSI bold/color escapes in the iteration print. 'NULL' (default) defers to [crayon::has_color()].

boundTol

Tolerance for boundary issues.

calcTables

This boolean is to determine if the foceiFit will calculate tables. By default this is TRUE

noAbort

Boolean to indicate if you should abort the FOCEi evaluation if it runs into troubles. (default TRUE)

interaction

Boolean indicate FOCEi should be used (TRUE) instead of FOCE (FALSE)

foce

Controls how FOCE (interaction = FALSE) evaluates the residual variance R in the inner objective; ignored for FOCEi. Either "nonmem" (default) or "foce+":

  • "nonmem" freezes R at the eta = 0 population prediction and holds it constant across the inner optimization, matching NONMEM's FOCE. Advantage: reproduces NONMEM FOCE objective and standard errors, and an ODE model agrees with its closed-form (linCmt) equivalent. Disadvantage: R ignores the individual (conditional) heteroscedasticity, so it can be slightly less accurate than "foce+" for proportional/combined error.

  • "foce+" evaluates R at the current conditional eta (the live variance), keeping the truncated FOCE inner gradient. Advantage: uses the conditional variance and is a bit more accurate than NONMEM's FOCE in some cases. Disadvantage: does not match NONMEM FOCE. This was the FOCE behavior in nlmixr2est 6.0.1 and earlier. This does not use the gradient of eta like the full focei method, so it is not as accurate as focei.

cholSEtol

tolerance for Generalized Cholesky Decomposition. Defaults to suggested (.Machine$double.eps)^(1/3)

cholAccept

Tolerance to accept a Generalized Cholesky Decomposition for a R or S matrix.

resetEtaP

P-value for resetting an individual ETA to 0 during optimization, based on a z-test of chol(omega^-1) %*% eta or eta/sd(allEtas). '0' = never reset, '1' = always reset.

resetThetaP

P-value for resetting mu-referenced THETAs based on ETA drift, checked at the start and near a local minimum (see resetThetaCheckPer). '0' = never reset (the default); '1' is not allowed. Defaults to off: when the etas cannot re-center the reset repeats without progress and can error the fit out, and where it converges it reaches a worse optimum than leaving it off.

resetThetaFinalP

represents the p-value for reseting the population mu-referenced THETA parameters based on ETA drift during optimization, and resetting the optimization one final time. '0' = never reset (the default); see resetThetaP.

diagOmegaBoundUpper

Upper bound of the diagonal omega matrix, as diag(omega)*diagOmegaBoundUpper. '1' = no upper bound.

diagOmegaBoundLower

Lower bound of the diagonal omega matrix, as diag(omega)/diagOmegaBoundLower. '1' = no lower bound.

cholSEOpt

Boolean indicating if the generalized Cholesky should be used while optimizing.

cholSECov

Boolean indicating if the generalized Cholesky should be used while calculating the Covariance Matrix.

fo

is a boolean indicating if this is a FO approximation routine.

covTryHarder

If the R matrix is non-positive definite and cannot be corrected to be non-positive definite try estimating the Hessian on the unscaled parameter space.

outerOpt

optimization method for the outer problem

innerOpt

optimization method for the inner problem (not implemented yet.)

rhobeg

Initial trust region radius for the bobyqa outer optimizer (with 'rhoend', must satisfy '0 < rhoend < rhobeg'). Default '0.2' (20 'abs(upper-lower)/2'. (bobyqa)

rhoend

Final trust region radius. If not defined, '10^(-sigdig)' is used. (bobyqa)

npt

Number of points for bobyqa's quadratic approximation to the objective; must be in '[n+2, (n+1)(n+2)/2]'. Defaults to '2*n + 1'. (bobyqa)

rel.tol

Relative tolerance before nlminb stops (nlmimb).

x.tol

X tolerance for nlmixr2 optimizer

eval.max

Number of maximum evaluations of the objective function (nlmimb)

iter.max

Maximum number of iterations allowed (nlmimb)

abstol

Absolute tolerance for nlmixr2 optimizer (BFGS)

reltol

tolerance for nlmixr2 (BFGS)

resetHessianAndEta

is a boolean representing if the individual Hessian is reset when ETAs are reset using the option resetEtaP.

muModel

Mu-referenced-FOCEI-family regression variant: "none" (default, ordinary FOCEI); "lin" (mfocei/mfoce/magq/mlaplace) profiles mu-referenced population thetas and covariate coefficients out of the outer optimizer via closed-form OLS regression of each subject's back-calculated value on the covariates (muModelTol/ muModelMaxCycles); "irls" (ifocei/ifoce/iagq/ilaplace) reweights that by inner-optimization curvature. Bounded mu parameters are regression-updated with a clamped step (muModelClampRetries); a user-fixed (fix()) mu theta is never updated.

muRefCovAlg

When 'TRUE' (default), algebraic expressions that can be mu-referenced are internally rewritten as mu-referenced covariates and restored after optimization. Mirrors saemControl(muRefCovAlg=)/nlmeControl(muRefCovAlg=); for foceiControl() only takes effect when muModel != "none".

muModelTol

Convergence tolerance for the mu-referenced-FOCEI-family "re-optimize etas, then regress" cycle (muModel != "none"): repeats until the max mu-group theta change drops below this value or muModelMaxCycles is reached.

muModelMaxCycles

Maximum number of "re-optimize etas, regress" cycles per outer iteration (see muModel, muModelTol).

muModelClampRetries

Maximum number of active-set re-solve passes per group per regression update when a bounded mu-referenced parameter must be clamped to its bound (see muModel); on hitting the cap the current clamped-feasible solution is used.

stateTrim

Trim state amounts/concentrations to this value.

shi21maxOuter

The maximum number of steps for the optimization of the forward-difference step size. When not zero, use this instead of Gill differences.

shi21maxInner

The maximum number of steps for the optimization of the individual Hessian matrices in the generalized likelihood problem. When 0, un-optimized finite differences are used.

shi21maxInnerCov

The maximum number of steps for the optimization of the individual Hessian matrices in the generalized likelihood problem for the covariance step. When 0, un-optimized finite differences are used.

shi21maxFD

The maximum number of steps for the optimization of the forward difference step size when using dosing events (lag time, modeled duration/rate and bioavailability)

shi21hMax

Upper bound on the adaptive shi21 finite-difference step size for FOCEi gradients (both the inner eta and outer theta/covariate finite differences). The step-size search never probes a parameter by more than this on its estimation scale; a larger value lets the gradient of a flat, small-magnitude parameter (e.g. a covariate coefficient near 0) clear the ODE-solver noise floor, at the cost of risking a degenerate solve at the probe.

shi21hMin

Lower bound on the adaptive shi21 finite-difference step size for FOCEi gradients. The floor is limited by the ODE solver tolerance (atol/rtol), not machine precision; below it the finite difference is dominated by solver noise.

gillK

Max steps to determine the optimal forward/central difference step size per parameter (Gill 1983). '0' = no optimal step size determined.

gillStep

When looking for the optimal forward difference step size, this is This is the step size to increase the initial estimate by. So each iteration the new step size = (prior step size)*gillStep

gillFtol

The gillFtol is the gradient error tolerance that is acceptable before issuing a warning/error about the gradient estimates.

gillRtol

The relative tolerance used for Gill 1983 determination of optimal step size.

gillKcov

Max steps to determine the optimal forward/central difference step size per parameter (Gill 1983) during the covariance step. '0' = no optimal step size determined.

gillKcovLlik

Same as gillK but for the generalized focei log-likelihood method (Gill 1986).

gillStepCovLlik

Same as above but during generalized focei log-likelihood

gillStepCov

When looking for the optimal forward difference step size, this is This is the step size to increase the initial estimate by. So each iteration during the covariance step is equal to the new step size = (prior step size)*gillStepCov

gillFtolCov

The gillFtol is the gradient error tolerance that is acceptable before issuing a warning/error about the gradient estimates during the covariance step.

gillFtolCovLlik

Same as above but applied during generalized log-likelihood estimation.

rmatNorm

A parameter to normalize gradient step size by the parameter value during the calculation of the R matrix

rmatNormLlik

A parameter to normalize gradient step size by the parameter value during the calculation of the R matrix if you are using generalized log-likelihood Hessian matrix.

smatNorm

A parameter to normalize gradient step size by the parameter value during the calculation of the S matrix

smatNormLlik

A parameter to normalize gradient step size by the parameter value during the calculation of the S matrix if you are using the generalized log-likelihood.

covGillF

Use the Gill calculated optimal Forward difference step size for the instead of the central difference step size during the central difference gradient calculation.

optGillF

Use the Gill calculated optimal Forward difference step size for the instead of the central difference step size during the central differences for optimization.

covSmall

Small number used to compare covariance estimates (sandwich vs R/S matrix) before rejecting one as too small to be the final covariance estimate.

adjLik

When 'TRUE', adjusts the likelihood by the 2*pi constant nlmixr2's objective function otherwise omits (to match NONMEM), more closely matching nlme/SAS likelihood approximations. The objective function itself always matches NONMEM regardless.

gradTrim

The parameter to adjust the gradient to if the |gradient| is very large.

maxOdeRecalc

Maximum number of times to reduce the ODE tolerances and try to resolve the system if there was a bad ODE solve.

odeRecalcFactor

The ODE recalculation factor when ODE solving goes bad, this is the factor the rtol/atol is reduced

gradCalcCentralSmall

A small number that represents the value where |grad| < gradCalcCentralSmall where forward differences switch to central differences.

gradCalcCentralLarge

A large number that represents the value where |grad| > gradCalcCentralLarge where forward differences switch to central differences.

etaNudge

When n1qn1 optimization of an ETA (starting at zero) misbehaves, reset the Hessian and nudge the ETA up by this value, then down if it still doesn't move. Defaults to 'qnorm(1-0.05/2)*1/sqrt(3)'. Falls back to etaNudge2, then to zero (stop optimizing) if unsuccessful.

etaNudge2

This is the second eta nudge. By default it is qnorm(1-0.05/2)*sqrt(3/5), which is the n=3 quadrature point (excluding zero) times by the 0.95% normal region

nRetries

If FOCEi doesn't fit with the current parameter estimates, randomly sample new parameter estimates and restart the problem. This is similar to 'PsN' resampling.

seed

Integer seed (default '42') used to make a FOCEi fit reproducible and self-contained. The fit (including the 'mceta' Monte-Carlo initial-ETA draws, which pull from rxode2's threefry engine) runs inside [rxode2::rxWithSeed()], so it neither depends on the ambient RNG state nor advances/leaks it – repeated fits in the same session, and fits following other estimation methods, give identical results.

resetThetaCheckPer

represents objective function % percentage below which resetThetaP is checked.

etaMat

Initial (or final) ETA estimates; can also be a prior fit, whose final ETAs are then used as initial values. By default, uses the last fit's ETAs if supplied, else all ETAs start at zero ('NULL'). 'NA' disables reuse from a prior fit.

repeatGillMax

If the tolerances were reduced when calculating the initial Gill differences, the Gill difference is repeated up to a maximum number of times defined by this parameter.

stickyRecalcN

The number of bad ODE solves before reducing the atol/rtol for the rest of the problem.

outerMaxOdeRecalc

Maximum number of times to reduce the ODE tolerances for a single subject and retry when the analytic outer (augmented sensitivity) solve fails. Tracked separately from 'maxOdeRecalc', which governs the inner problem. A subject that solves after loosening still contributes an analytic gradient instead of dropping the whole gradient to finite differences.

outerOdeRecalcFactor

The factor the atol/rtol is loosened by on each analytic outer retry; the outer counterpart of 'odeRecalcFactor'.

outerStickyRecalcN

The number of bad analytic outer solves for a subject before its loosened tolerance is kept for the rest of the problem; the outer counterpart of 'stickyRecalcN'.

indTolRelax

When 'TRUE' (default), only subjects whose ODE solve produced NaN/Inf have their tolerances relaxed, and the relaxed tolerance persists across optimizer calls (sticky). When 'FALSE', all subjects have their tolerances relaxed on each retry and tolerances are reset afterward.

gradProgressOfvTime

This is the time for a single objective function evaluation (in seconds) to start progress bars on gradient evaluations

addProp

Type of additive-plus-proportional error: '"combined1"', where standard deviations add:

y = f + (a + b\times f^c) \times \varepsilon

; or '"combined2"', where variances add:

y = f + \sqrt{a^2 + b^2\times f^{2\times c}} \times \varepsilon

. Here y = observed, f = predicted, a = additive sd, b = proportional/power sd, c = power exponent (1 in the proportional case).

badSolveObjfAdj

The objective function adjustment when the ODE system cannot be solved. It is based on each individual bad solve.

compress

Should the object have compressed items

rxControl

'rxode2' ODE solving options during fitting, created with 'rxControl()'

sigdigTable

Significant digits in the final output table. If not specified, then it matches the significant digits in the 'sigdig' optimization algorithm. If 'sigdig' is NULL, use 3.

fallbackFD

Fallback to the finite differences if the sensitivity equations do not solve.

smatPer

Percentage of failed per-individual parameter gradients (replaced with the overall parameter gradient) out of the total ('ntheta*nsub') above which the S matrix is considered bad.

sdLowerFact

Factor multiplying the estimate when the lower bound is zero for a standard-deviation error parameter (add.sd, prop.sd, etc); e.g. estimate 0.15 with lower bound 0 assumes a lower bound of 0.00015. '0' disables this.

zeroGradFirstReset

When 'TRUE' (default), reset a zero first gradient to 'sqrt(.Machine$double.eps)' instead of erroring; 'FALSE' errors; 'NA' ignores it only on the last reset attempt.

zeroGradRunReset

When 'TRUE' (default), reset a zero gradient encountered mid-run to 'sqrt(.Machine$double.eps)' instead of erroring.

zeroGradBobyqa

When 'TRUE' (default), a zero-gradient reset switches to the gradient-free bobyqa method; 'NA' only does so for the first zero gradient.

mceta

Monte Carlo sampling for the best initial ETA estimate (based on 'omega'): '-2' (default) uses the Almquist (2015) Eq-48 extrapolation 'eta^0 = eta* + (d eta*/d theta)(theta_new - theta_old)' when the analytic gradient supplies 'd eta*/d theta' ('fast = TRUE'), accepting the extrapolated eta only when it is within the standardized-eta reset bound (else keeping the last eta, or resetting to 0 when that is also out of bound); '-1' jumps between the extrapolated eta and eta=0, keeping the better; both '-2' and '-1' fall back to keeping the last eta when no analytic 'd eta*/d theta' is available ('fast = FALSE'). '0' uses eta=0 for each inner optimization; for 'n>0', the last eta, eta=0, and n-1 etas sampled from omega are each evaluated and the best (by inner objective) is used.

warm

Seeding of the n1qn1 inner-optimization Hessian: '"calc"' (default) warm-starts each inner problem with the eta Hessian calculated at the starting eta and the current theta; since theta moves between outer evaluations it is always recalculated, never reused from an earlier round. '"save"' uses the classic self-initialized Hessian.

nAGQ

Number of Gauss-Hermite adaptive quadrature points. '0' disables AGQ; '1' is equivalent to Laplace. Cost grows quickly with ETAs: once the EBE is found, expect 'nAGQ^neta' (even 'nAGQ') or '(nAGQ^neta)-1' (odd 'nAGQ') additional evaluations per subject.

agqLow

The lower bound for adaptive quadrature log-likelihood. By default this is -Inf; in the original nlmixr's gnlmm it was -700.

agqHi

The upper bound for adaptive quadrature log-likelihood. By default this is Inf; in the original nlmixr's gnlmm was 400.

sensMethod

Method used to compute the ODE parameter sensitivities. '"forward"' uses the classic variational (forward) sensitivity ODEs; '"default"' is the same thing.

zeroTheta

Positive magnitude (default '0.001') used to nudge a population parameter ('theta') whose initial estimate is exactly '0' off zero before estimation. FOCEi scales a linear parameter by its native magnitude '|init|', which is '0' (no scale) for a zero initial estimate, so the parameter is moved to '+zeroTheta' when it is within the parameter's bounds, otherwise '-zeroTheta'; if neither is within the bounds an error is raised. Fixed parameters (including those fixed at '0') are left untouched.

boundedTransform

When 'TRUE' (default), bounded parameters are transformed for unbounded optimization methods and back-transformed for final estimates. 'FALSE' optimizes on the original scale with bounds passed to the optimizer. 'NA' transforms for optimization but skips the final back-transform.

Details

Uses R's L-BFGS-B (optim) for the outer problem and BFGS n1qn1 (restoring the prior individual Hessian) for the inner problem, which is left unscaled since eta estimates start near zero. The covariance step is performed on the unscaled problem, so its condition number may differ from the scaled problem's.

Value

The control object that changes the options for the FOCEi family of estimation methods

Author(s)

Matthew L. Fidler

References

Gill, P.E., Murray, W., Saunders, M.A., & Wright, M.H. (1983). Computing Forward-Difference Intervals for Numerical Optimization. Siam Journal on Scientific and Statistical Computing, 4, 310-321.

Shi, H.M., Xie, Y., Xuan, M.Q., & Nocedal, J. (2021). Adaptive Finite-Difference Interval Estimation for Noisy Derivative-Free Optimization.

See Also

optim

n1qn1

rxSolve

Other Estimation control: nlmixr2NlmeControl(), saemControl()


Fit/Evaluate FOCEi

Description

This shouldn't be called directly.

Usage

foceiFitCpp_(e)

Arguments

e

Environment

Value

A focei fit object


Analytic outer gradient at a caller-supplied theta / eta / omega

Description

The same C++ core the fit's own gradient uses ('gradPooledCore'), but with the point passed in rather than read out of 'op_focei'. 'est="vae"' with 'nonMuTheta="grad"' needs exactly this: its M-step evaluates the gradient at a theta and an encoder eta matrix that are not the inner problem's, and at an omega that changes every step. Requires 'foceiGradPooledSetupLoad_()' first, and a live FOCEi inner problem (the shared pool, 'rxVaeOuter', and the theta/eta par_ptr maps all come from it).

Usage

foceiGradPooledDirect_(thVals, ebes, Oi, dOiEst, tr28, cores)

Arguments

thVals

natural-scale theta, in ntheta order

ebes

nsub x neta matrix of etas to take the gradient at

Oi

inverse of the current Omega

dOiEst

list of d(Omega^-1)/d(estimation-scale omega element)

tr28

the matching trace terms

cores

thread count

Value

natural-scale gradient (thetas, sigmas, omegas), or NULL if it declined


Install the pooled analytic-gradient setup for a non-focei caller

Description

'est="vae"' with 'nonMuTheta="grad"' evaluates the analytic outer gradient once per M-step, at its own theta/eta/omega, and has no fit env to hang the setup on. This installs the setup once so 'foceiGradPooledDirect_()' can be called repeatedly.

Usage

foceiGradPooledSetupLoad_(st)

Arguments

st

setup list from '.foceiGradPooledSetup()'

Value

TRUE if the setup describes a shape the C++ gradient handles


Load a general FOCE-family likelihood into memory

Description

Compiles the inner (FOCEi sensitivity) model from an rxode2 UI model, preprocesses the data, and sets up the FOCEi inner problem in memory so that individual log-likelihoods can be evaluated repeatedly (in parallel per subject) at supplied etas without recompiling – the setup used internally by 'est="emvi"'/'est="fbvi"', 'est="vae"' and the f-SAEM fast kernel, exposed here for MCMC/SAMBA-style callers (issue #414).

Usage

foceiLikLoad(
  object,
  data,
  likelihood = c("focei", "focep", "foce"),
  rxControl = rxode2::rxControl(),
  ...
)

Arguments

object

An 'rxode2'/'nlmixr2' UI model (a model function or its compiled UI).

data

The estimation data (a data frame with the usual nlmixr2 columns).

likelihood

The individual likelihood type: '"focei"' (FOCE with interaction), '"focep"' (FOCE+, interaction off with the residual variance at the conditional eta) or '"foce"' (NONMEM-style FOCE, residual variance frozen at eta=0).

rxControl

An [rxode2::rxControl()] object for the ODE solving options.

...

Additional solving/model options passed to '.foceiLikControl' (e.g. 'optExpression', 'addProp', 'eventSens').

Details

Only one likelihood system may be loaded at a time; loading errors if one is already loaded. Use [foceiLikRun()] to evaluate and [foceiLikUnload()] to free.

Value

Invisibly, a handle list with the loaded system's dimensions: ‘initPar' (the estimation-scale parameter vector at the model’s initial estimates, a ready 'theta' for [foceiLikRun()]), 'npars', 'ntheta', 'neta', 'nid', 'thetaNames', 'etaNames', 'idLvl' and 'likelihood'.

Author(s)

Matthew L. Fidler

See Also

[foceiLikRun()], [foceiLikUnload()]

Examples




one.cmt <- function() {
  ini({
    tka <- 0.45
    tcl <- 1
    tv <- 3.45
    add.sd <- 0.7
    eta.ka ~ 0.6
    eta.cl ~ 0.3
    eta.v ~ 0.1
  })
  model({
    ka <- exp(tka + eta.ka)
    cl <- exp(tcl + eta.cl)
    v <- exp(tv + eta.v)
    linCmt() ~ add(add.sd)
  })
}

# Set the likelihood up in memory once; only one may be loaded at a time
h <- foceiLikLoad(one.cmt, theo_sd, "focei")

# The handle carries the dimensions and a ready starting parameter vector
h$nid
h$neta
h$initPar

# Individual joint log-likelihood at eta = 0, one value per subject
eta <- matrix(0, h$nid, h$neta)
foceiLikRun(h$initPar, eta)

# Free it when done (loading again before this errors)
foceiLikUnload()


Evaluate a loaded general FOCE-family likelihood at supplied etas

Description

Writes the population parameter vector into the loaded system and returns the per-subject log-likelihood at the supplied etas, computed in parallel over subjects. Requires a system loaded by [foceiLikLoad()].

Usage

foceiLikRun(
  theta,
  eta,
  type = c("joint", "cond"),
  cores = rxode2::getRxThreads()
)

Arguments

theta

The estimation-scale parameter vector (length 'handle$npars'), matching the FOCEi optimizer parameterization: population thetas followed by the estimated Omega elements. 'handle$initPar' from [foceiLikLoad()] is a ready starting value.

eta

A 'nid' by 'neta' matrix of random effects (one row per subject, in the loaded system's subject order).

type

'"joint"' (default) returns the individual joint log density 'log p(y_i, eta_i)'; '"cond"' returns the conditional data log-likelihood 'log p(y_i | eta_i)' alone. See Details.

cores

Number of threads for the parallel per-subject evaluation.

Details

Both types are evaluated at the etas you supply, so both use each subject's individual predictions; neither is a population (eta = 0) quantity. They differ only by the random-effect prior term:

- '"cond"' is the conditional data log-likelihood 'log p(y_i | eta_i)', the observation contribution alone. - '"joint"' is 'log p(y_i, eta_i) = log p(y_i | eta_i) + log p(eta_i)', which adds the Gaussian random-effect prior ‘log p(eta_i) = -0.5 eta_i’ Omega^-1 eta_i + 0.5 log|Omega^-1| - neta/2 log(2 pi)'.

So '"joint"' minus '"cond"' is exactly 'log p(eta_i)'. '"joint"' is the default because it is the usual target for MCMC/SAMBA-style samplers: as a function of ‘eta_i' it is the individual’s posterior kernel, and it is the quantity the FOCEi inner problem optimizes over the etas. Use '"cond"' when you supply the random-effect density yourself, or when you need the observation contribution separately.

The prior is built from the loaded system's own 'Omega^-1' and its log determinant – the same Omega the inner likelihood uses – so '"joint"' stays internally consistent with the engine rather than with the nominal 'ini()' values (the two differ by a small amount through Omega's internal 'rxSymInv' representation).

For Gaussian endpoints the observation contribution follows nlmixr2's internal residual-likelihood convention, '-0.5 err^2/r - 0.5 log(r)', which omits the additive '-0.5 log(2 pi)' per observation; general log-likelihood (‘ll()') endpoints contribute the user’s log density as written. The eta prior above is fully normalized. Both types are therefore proper log densities up to a fixed per-observation constant that does not depend on 'theta' or 'eta', so likelihood ratios, and any sampler that uses them, are unaffected.

Value

A named numeric vector (length 'nid', named by subject id) of per-subject log-likelihoods.

Author(s)

Matthew L. Fidler

See Also

[foceiLikLoad()], [foceiLikUnload()]

Examples




one.cmt <- function() {
  ini({
    tka <- 0.45
    tcl <- 1
    tv <- 3.45
    add.sd <- 0.7
    eta.ka ~ 0.6
    eta.cl ~ 0.3
    eta.v ~ 0.1
  })
  model({
    ka <- exp(tka + eta.ka)
    cl <- exp(tcl + eta.cl)
    v <- exp(tv + eta.v)
    linCmt() ~ add(add.sd)
  })
}

h <- foceiLikLoad(one.cmt, theo_sd, "focei")

eta <- matrix(0, h$nid, h$neta)

# The individual joint log density log p(y_i, eta_i) (the default)
foceiLikRun(h$initPar, eta)

# The conditional data log-likelihood log p(y_i | eta_i) alone; the two
# differ by the Gaussian eta prior
foceiLikRun(h$initPar, eta, type = "cond")

# Non-zero etas
set.seed(42)
foceiLikRun(h$initPar, matrix(stats::rnorm(h$nid * h$neta, 0, 0.1), h$nid, h$neta))

# A new population parameter vector needs no reload
theta <- h$initPar
theta[1] <- theta[1] + 0.1
foceiLikRun(theta, eta)

foceiLikUnload()


Unload the general FOCE-family likelihood from memory

Description

Frees the FOCEi inner problem set up by [foceiLikLoad()]. A no-op (returns 'FALSE') if nothing is loaded.

Usage

foceiLikUnload()

Value

Invisibly 'TRUE' if a system was freed, 'FALSE' if none was loaded.

Author(s)

Matthew L. Fidler

See Also

[foceiLikLoad()], [foceiLikRun()]


Control options for the focep (FOCE+) estimation method

Description

This is the first order conditional estimation without eta/residual interaction, but keeping the live conditional residual variance R (the 'foce = "foce+"' option of [foceiControl()]). It is the 'foce' method with 'foce = "foce+"' forced; use 'foce' (est = "foce") for the NONMEM-matching frozen-R behavior.

Usage

focepControl(sigdig = 3, ..., interaction = FALSE, foce = "foce+")

Arguments

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

...

Parameters used in the default 'foceiControl()'

interaction

Interaction term for the model, in this case the default is 'FALSE'; it cannot be changed, use 'focei' instead

foce

FOCE residual-variance mode; for 'focepControl()' this is always '"foce+"' and cannot be changed – use 'foceControl()' for '"nonmem"'

Value

focepControl object

Author(s)

Matthew L. Fidler

Examples


focepControl()

Control options foir the FOI estimation method

Description

This is related to the focei methods and uses most of their control options. Some are ignored, 'posthoc' is an extra parameter

Usage

foiControl(sigdig = 3, ..., posthoc = TRUE, interaction = NULL, fo = NULL)

Arguments

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

...

Parameters used in the default 'foceiConrol()'

posthoc

Logical indicating if the estimation method should calculate 'foce' posthoc predicted parameters.

interaction

Interaction term for the model; ignored by fo

fo

Logical indicating if the estimation method is FO (first order), but this is controlled by the estimation method so this is ignored.

Value

foiControl object

Author(s)

Matthew L. Fidler

Examples


foiControl()

Format numeric values to minimize the printing width

Description

Special values ('NaN', 'Inf', '-Inf', '0') are shown as-is; 'NA' uses 'naValue'.

Usage

formatMinWidth(x, digits = 3, naValue = "NA")

Arguments

x

The numeric vector to convert

digits

The number of significant digits to show

naValue

The value to return if 'is.na(x)'

Value

A character vector converting the numbers with minimum width


Method for getting simulation rxode2 classic models based on fits

Description

Method for getting simulation rxode2 classic models based on fits

Usage

getBaseSimModelFit(x)

## S3 method for class 'focei'
getBaseSimModelFit(x)

## S3 method for class 'foce'
getBaseSimModelFit(x)

## S3 method for class 'focep'
getBaseSimModelFit(x)

## S3 method for class 'fo'
getBaseSimModelFit(x)

## S3 method for class 'foi'
getBaseSimModelFit(x)

## S3 method for class 'posthoc'
getBaseSimModelFit(x)

## Default S3 method:
getBaseSimModelFit(x)

Arguments

x

list where first element is the fit. The class represents the estimation method.

Value

model for fit$simulationModel

Author(s)

Matthew L. Fidler


Get valid nlmixr control object

Description

Get valid nlmixr control object

Usage

## S3 method for class 'agq'
getValidNlmixrCtl(control)

## S3 method for class 'bobyqa'
getValidNlmixrCtl(control)

## S3 method for class 'emvi'
getValidNlmixrCtl(control)

## S3 method for class 'fbvi'
getValidNlmixrCtl(control)

## S3 method for class 'fo'
getValidNlmixrCtl(control)

## S3 method for class 'foce'
getValidNlmixrCtl(control)

## S3 method for class 'foceif'
getValidNlmixrCtl(control)

## S3 method for class 'focef'
getValidNlmixrCtl(control)

## S3 method for class 'focepf'
getValidNlmixrCtl(control)

## S3 method for class 'mfoceif'
getValidNlmixrCtl(control)

## S3 method for class 'mfocef'
getValidNlmixrCtl(control)

## S3 method for class 'mfocepf'
getValidNlmixrCtl(control)

## S3 method for class 'ifoceif'
getValidNlmixrCtl(control)

## S3 method for class 'ifocef'
getValidNlmixrCtl(control)

## S3 method for class 'ifocepf'
getValidNlmixrCtl(control)

## S3 method for class 'agqf'
getValidNlmixrCtl(control)

## S3 method for class 'magqf'
getValidNlmixrCtl(control)

## S3 method for class 'iagqf'
getValidNlmixrCtl(control)

## S3 method for class 'focep'
getValidNlmixrCtl(control)

## S3 method for class 'foi'
getValidNlmixrCtl(control)

## S3 method for class 'ifocep'
getValidNlmixrCtl(control)

## S3 method for class 'imp'
getValidNlmixrCtl(control)

## S3 method for class 'impmap'
getValidNlmixrCtl(control)

## S3 method for class 'laplace'
getValidNlmixrCtl(control)

## S3 method for class 'lbfgsb3c'
getValidNlmixrCtl(control)

## S3 method for class 'mfocep'
getValidNlmixrCtl(control)

## S3 method for class 'mfocei'
getValidNlmixrCtl(control)

## S3 method for class 'ifocei'
getValidNlmixrCtl(control)

## S3 method for class 'mfoce'
getValidNlmixrCtl(control)

## S3 method for class 'ifoce'
getValidNlmixrCtl(control)

## S3 method for class 'magq'
getValidNlmixrCtl(control)

## S3 method for class 'iagq'
getValidNlmixrCtl(control)

## S3 method for class 'mlaplace'
getValidNlmixrCtl(control)

## S3 method for class 'ilaplace'
getValidNlmixrCtl(control)

## S3 method for class 'n1qn1'
getValidNlmixrCtl(control)

## S3 method for class 'newuoa'
getValidNlmixrCtl(control)

## S3 method for class 'nlm'
getValidNlmixrCtl(control)

## S3 method for class 'nlminb'
getValidNlmixrCtl(control)

## S3 method for class 'nls'
getValidNlmixrCtl(control)

## S3 method for class 'mnpag'
getValidNlmixrCtl(control)

## S3 method for class 'inpag'
getValidNlmixrCtl(control)

## S3 method for class 'mnpb'
getValidNlmixrCtl(control)

## S3 method for class 'inpb'
getValidNlmixrCtl(control)

## S3 method for class 'npag'
getValidNlmixrCtl(control)

## S3 method for class 'npb'
getValidNlmixrCtl(control)

## S3 method for class 'optim'
getValidNlmixrCtl(control)

## S3 method for class 'neldermead'
getValidNlmixrCtl(control)

## S3 method for class 'bfgs'
getValidNlmixrCtl(control)

## S3 method for class 'cg'
getValidNlmixrCtl(control)

## S3 method for class 'lbfgsb'
getValidNlmixrCtl(control)

## S3 method for class 'sann'
getValidNlmixrCtl(control)

## S3 method for class 'brent'
getValidNlmixrCtl(control)

## S3 method for class 'posthoc'
getValidNlmixrCtl(control)

## S3 method for class 'qrpem'
getValidNlmixrCtl(control)

getValidNlmixrControl(control, est)

getValidNlmixrCtl(control)

## S3 method for class 'focei'
getValidNlmixrCtl(control)

## S3 method for class 'nlme'
getValidNlmixrCtl(control)

## S3 method for class 'saem'
getValidNlmixrCtl(control)

## S3 method for class 'rxSolve'
getValidNlmixrCtl(control)

## S3 method for class 'simulate'
getValidNlmixrCtl(control)

## S3 method for class 'simulation'
getValidNlmixrCtl(control)

## S3 method for class 'predict'
getValidNlmixrCtl(control)

## S3 method for class 'tableControl'
getValidNlmixrCtl(control)

## Default S3 method:
getValidNlmixrCtl(control)

## S3 method for class 'uobyqa'
getValidNlmixrCtl(control)

## S3 method for class 'vae'
getValidNlmixrCtl(control)

Arguments

control

nlmixr control object

est

Estimation routine

Details

This is based on running the S3 method 'getValidNlmixrCtl()' the 'control' object is put into a list and the class of this new list is 'c(est, "getValidNlmixrControl")'

Value

Valid control object based on estimation method run.


Control options for the iagq estimation method

Description

Mu-referenced-FOCEI-family reweighted-regression ('"irls"') variant of adaptive Gauss-Hermite quadrature; see 'foceiControl(muModel=)'.

Usage

iagqControl(
  sigdig = 3,
  nAGQ = 2,
  ...,
  interaction = TRUE,
  agqLow = -Inf,
  agqHi = Inf,
  muModel = c("irls", "lin", "none")
)

Arguments

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

nAGQ

Number of Gauss-Hermite adaptive quadrature points. '0' disables AGQ; '1' is equivalent to Laplace. Cost grows quickly with ETAs: once the EBE is found, expect 'nAGQ^neta' (even 'nAGQ') or '(nAGQ^neta)-1' (odd 'nAGQ') additional evaluations per subject.

...

Parameters used in the default 'foceiControl()'

interaction

boolean, Interaction term for the model, in this case the default is 'TRUE'; For adaptive quadrature, with normal distribution the Hessian is calculated with the foce(i) approximation

agqLow

The lower bound for adaptive quadrature log-likelihood. By default this is -Inf; in the original nlmixr's gnlmm it was -700.

agqHi

The upper bound for adaptive quadrature log-likelihood. By default this is Inf; in the original nlmixr's gnlmm was 400.

muModel

Selects the regression variant; for 'iagqControl()' this is always '"irls"' and cannot be changed – use 'magqControl()' for the closed-form OLS variant.

Value

iagqControl object

Author(s)

Matthew L. Fidler

Examples


iagqControl()

Control options for the ifoce estimation method

Description

Mu-referenced-FOCEI-family reweighted-regression ('"irls"') variant of FOCE (no interaction); see 'foceiControl(muModel=)'.

Usage

ifoceControl(
  sigdig = 3,
  ...,
  interaction = FALSE,
  muModel = c("irls", "lin", "none")
)

Arguments

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

...

Parameters used in the default 'foceiControl()'

interaction

Interaction term for the model, in this case the default is 'FALSE'; it cannot be changed, use 'ifocei' instead

muModel

Selects the regression variant; for 'ifoceControl()' this is always '"irls"' and cannot be changed – use 'mfoceControl()' for the closed-form OLS variant.

Value

ifoceControl object

Difference from 'focei'

The 'mfocei'/'ifocei' (and related) methods apply the mu2+ covariate hooks, which expand algebraic mu-referenced covariate expressions (e.g. 'cl.wt*log(WT/70)') into estimable mu-referenced parameters and split covariates into non-time-varying (absorbed into the phi term) and time-varying (kept as 'beta' regressors). Calling 'focei' directly does NOT apply these hooks, so these methods can estimate more mu-referenced models than plain 'focei' – there is a genuine difference between calling e.g. 'est="mfocei"' and 'est="focei"'.

All mu-referenced population thetas – with or without covariates – are profiled out of the outer optimizer by the in-C++ regression (intercept-only for covariate-free pairs), so outer gradients are only calculated for the non-mu-referenced parameters (residual errors, omegas, non-mu thetas). Bounded mu-referenced parameters are regression-updated with the update clamped to the bounds (a clamp is reported once as a fit note); user-fixed ('fix()') mu thetas stay out of the regression.

Author(s)

Matthew L. Fidler

Examples


ifoceControl()

Control options for the ifocei estimation method

Description

Mu-referenced-FOCEI-family reweighted-regression ('"irls"') variant of FOCEI; see 'foceiControl(muModel=)'.

Usage

ifoceiControl(sigdig = 3, ..., muModel = c("irls", "lin", "none"))

Arguments

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

...

Parameters used in the default 'foceiControl()'

muModel

Selects the regression variant; for 'ifoceiControl()' this is always '"irls"' and cannot be changed – use 'mfoceiControl()' for the closed-form OLS variant.

Value

ifoceiControl object

Difference from 'focei'

The 'mfocei'/'ifocei' (and related) methods apply the mu2+ covariate hooks, which expand algebraic mu-referenced covariate expressions (e.g. 'cl.wt*log(WT/70)') into estimable mu-referenced parameters and split covariates into non-time-varying (absorbed into the phi term) and time-varying (kept as 'beta' regressors). Calling 'focei' directly does NOT apply these hooks, so these methods can estimate more mu-referenced models than plain 'focei' – there is a genuine difference between calling e.g. 'est="mfocei"' and 'est="focei"'.

All mu-referenced population thetas – with or without covariates – are profiled out of the outer optimizer by the in-C++ regression (intercept-only for covariate-free pairs), so outer gradients are only calculated for the non-mu-referenced parameters (residual errors, omegas, non-mu thetas). Bounded mu-referenced parameters are regression-updated with the update clamped to the bounds (a clamp is reported once as a fit note); user-fixed ('fix()') mu thetas stay out of the regression.

Author(s)

Matthew L. Fidler

Examples


ifoceiControl()

Control options for the ifocep (IRLS FOCE+) estimation method

Description

Mu-referenced-FOCEI-family reweighted-regression ('"irls"') variant of FOCE+ (no interaction, live conditional residual variance R); it is 'ifoce' with 'foce = "foce+"' forced (see 'foceiControl(foce=)').

Usage

ifocepControl(
  sigdig = 3,
  ...,
  interaction = FALSE,
  muModel = c("irls", "lin", "none"),
  foce = "foce+"
)

Arguments

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

...

Parameters used in the default 'foceiControl()'

interaction

Interaction term for the model, in this case the default is 'FALSE'; it cannot be changed, use 'ifocei' instead

muModel

Selects the regression variant; for 'ifocepControl()' this is always '"irls"' and cannot be changed – use 'mfocepControl()' for the closed-form OLS variant.

foce

FOCE residual-variance mode; for 'ifocepControl()' this is always '"foce+"' and cannot be changed – use 'ifoceControl()' for '"nonmem"'

Value

ifocepControl object

Difference from 'focei'

The 'mfocei'/'ifocei' (and related) methods apply the mu2+ covariate hooks, which expand algebraic mu-referenced covariate expressions (e.g. 'cl.wt*log(WT/70)') into estimable mu-referenced parameters and split covariates into non-time-varying (absorbed into the phi term) and time-varying (kept as 'beta' regressors). Calling 'focei' directly does NOT apply these hooks, so these methods can estimate more mu-referenced models than plain 'focei' – there is a genuine difference between calling e.g. 'est="mfocei"' and 'est="focei"'.

All mu-referenced population thetas – with or without covariates – are profiled out of the outer optimizer by the in-C++ regression (intercept-only for covariate-free pairs), so outer gradients are only calculated for the non-mu-referenced parameters (residual errors, omegas, non-mu thetas). Bounded mu-referenced parameters are regression-updated with the update clamped to the bounds (a clamp is reported once as a fit note); user-fixed ('fix()') mu thetas stay out of the regression.

Author(s)

Matthew L. Fidler

Examples


ifocepControl()

Control options for the ilaplace estimation method

Description

Mu-referenced-FOCEI-family reweighted-regression ('"irls"') variant of the Laplace method ('nAGQ=1'); see 'foceiControl(muModel=)'.

Usage

ilaplaceControl(sigdig = 3, ..., nAGQ = 1, muModel = c("irls", "lin", "none"))

Arguments

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

...

Parameters used in the default 'foceiControl()'

nAGQ

Number of Gauss-Hermite adaptive quadrature points. '0' disables AGQ; '1' is equivalent to Laplace. Cost grows quickly with ETAs: once the EBE is found, expect 'nAGQ^neta' (even 'nAGQ') or '(nAGQ^neta)-1' (odd 'nAGQ') additional evaluations per subject.

muModel

Selects the regression variant; for 'ilaplaceControl()' this is always '"irls"' and cannot be changed – use 'mlaplaceControl()' for the closed-form OLS variant.

Value

ilaplaceControl object

Author(s)

Matthew L. Fidler

Examples


ilaplaceControl()

Control for the imp (importance-sampling EM without MAP search) method

Description

A convenience wrapper around [impmapControl()] with 'mapIter = 0', i.e. the importance-sampling proposal is centered at the running conditional mean rather than re-optimized to the MAP mode each iteration (NONMEM METHOD=IMP). See [impmapControl()] for the full parameter list.

Usage

impControl(...)

Arguments

...

Parameters passed to [impmapControl()].

Value

An 'impmapControl' object with 'mapIter = 0'.

Author(s)

Matthew L. Fidler

Examples


impControl()

Control options for the impmap (importance-sampling EM) estimation method

Description

A NONMEM-style Monte Carlo importance-sampling EM built on the mu-referenced FOCEI MAP. The proposal density for each subject is centered at the MAP mode ('muModel="lin"'); mu-referenced population parameters are updated by the EM gradient, while non-mu parameters (structural and residual error) are updated by a symbolic-sensitivity Newton step – the importance-sampling-weighted score and Gauss-Newton information built from the analytic 'd(f)/d(theta)' and 'd(V)/d(theta)' (exact censored partials for BLQ/M2/M3/M4 points).

Usage

impmapControl(
  sigdig = 3,
  ...,
  isample = 300L,
  nIter = 100L,
  mapIter = 1L,
  gamma = 1,
  gammaMethod = c("auto", "global", "individual"),
  gammaRule = c("target", "floor"),
  df = 0,
  auto = TRUE,
  autoNonmemSparse = FALSE,
  autoDfPatience = 2L,
  iscaleMin = 0.1,
  iscaleMax = 10,
  iaccept = 0.4,
  ctol = NULL,
  nConvWindow = 10L,
  impSeed = 42L,
  covMethod = c("imp", "analytic", "r,s", "r", "s", "sa", ""),
  qr = FALSE,
  qrShift = TRUE,
  qrRefresh = TRUE,
  sir = FALSE,
  sirSample = NULL,
  muModel = c("lin", "none")
)

Arguments

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

...

Parameters used in the default 'foceiControl()'

isample

Number of importance samples drawn per subject per iteration (NONMEM ISAMPLE). Either a single count used for every subject, or a vector of length 'nsub' giving a count **per subject**.

Per-subject counts are the NM7 Technical Guide's own remedy for poor coverage (its derivation is Gaussian throughout and never mentions a t proposal): a subject whose weights are badly behaved can be given more samples without charging every other subject for them. Note this treats the symptom rather than the cause – more draws from a proposal whose tails are too light still gives weights with infinite variance, which 'fit$env$impPsisK' will show. See 'df' for the shape-based remedy.

nIter

Maximum number of importance-sampling EM iterations.

mapIter

Number of MAP re-centering iterations per EM step; '> 0' re-centers the proposal at the MAP mode each iteration.

gamma

Initial proposal-variance inflation factor (NONMEM ISCALE); the proposal covariance is 'gamma' times the inverse of the inner information matrix at the mode.

gammaMethod

How the proposal scale 'gamma' is adapted during the EM.

'"auto"' (default) picks per model: '"individual"' when the model is not transformably normal – a general log-likelihood ('ll()') endpoint, or a count/categorical/time-to-event distribution – and '"global"' otherwise. That is the split the hypothesis actually rests on: 'gamma = 1' is already the efficient proposal when the individual posterior is close to Gaussian, so a normal model gains nothing from per-subject adaptation and would only pay for it in effective sample size, while a general-likelihood model is exactly where the posteriors go non-Gaussian and per-subject coverage starts to vary. The test is 'all(ui$predDf$distribution == "norm")', the same line [rxode2::assertRxUiTransformNormal()] draws. The resolved value is reported in the fit's '$runInfo'.

'"global"' keeps one scale shared by every subject, inflated (never relaxed) only when the *mean* Kish effective-sample fraction falls below 'iaccept'. It leaves 'gamma' at its efficient starting value while coverage is healthy, which is the right behaviour when the individual posteriors are close to Gaussian.

'"individual"' gives every subject its own 'gamma_i' and adapts it two-sided toward a target on that subject's 'xi_i', clamped to ‘[iscaleMin, iscaleMax]'. This follows NONMEM’s *objective* – the NM7 Technical Guide states that 'gamma' is per-subject (eq. 1.90) and is "continually adjusted so that xi_i approximates IACCEPT" (note after eq. 1.76), bounded by 'ISCALE_MIN'/'ISCALE_MAX' – but the guide publishes no update formula, so the functional form used here is nlmixr2's own. Prefer this when the individual posteriors are heavy-tailed or the design is heterogeneous: a global scale is driven by the mean, so a handful of badly-covered subjects never trip it and their likelihood and 'Omega' contributions end up carried by a few samples.

The two modes report *different* efficiency statistics – '"individual"' targets ‘xi' (the mean normalized importance weight, NONMEM’s 'IACCEPT' quantity) while '"global"' targets the Kish effective-sample fraction. These are not comparable; the fit's '$runInfo' says which is in force.

gammaRule

How the SHARED ('gammaMethod="global"') proposal scale is adapted. Ignored for 'gammaMethod="individual"', which always follows NONMEM's two-sided per-subject rule.

'"floor"' treats 'iaccept' as a one-sided FLOOR on the mean Kish effective-sample fraction: 'gamma' stays at its efficient starting value while coverage is healthy and is inflated only when coverage drops below the floor. It never comes back down.

'"target"' (default) follows the NM7 Technical Guide, which says 'gamma' is "continually adjusted so that xi_i approximates IACCEPT" – adapted BOTH ways, on 'xi' rather than the Kish fraction, using the same analytic inversion as the per-subject controller ('gamma * (xi/iaccept)^(2/neta)', capped 1.25x each way and clamped to '[iscaleMin, iscaleMax]').

The two rules settle at different operating points, so they are not interchangeable, and constants tuned against one do not carry over to the other.

**Measured trade-off** (theophylline, 6 seeds, 'isample = 300', RMSE against an 'isample = 6000' reference):

  • 3 ETAs – '"floor"': theta RMSE 0.00185, 'Omega' RMSE 0.00298, max Pareto k-hat 0.604, 0.33 subjects above 0.7, converged 100 '"target"': theta RMSE 0.00257, 'Omega' RMSE 0.00378, max k-hat -0.491, 0 subjects above 0.7, converged 0

  • 8 ETAs – '"floor"' never adapts at all ('gamma' pinned at 1.0 with 'xi' 1.35, i.e. a proposal far too narrow), because it watches the mean Kish fraction, which stays healthy while 'xi' says the proposal is wrong. '"target"' moves 'gamma' to 1.25 and puts 'xi' on 0.41.

So '"target"' fixes the tail and is the only rule that reacts at high ETA dimension, but it pays for it: putting 'xi' on 'iaccept' deliberately widens the proposal ('gamma' 1.79 on the 3-ETA fixture), which costs effective sample size (0.96 to 0.70) and adds Monte-Carlo noise to the objective – enough that the fit often does not meet 'ctol' within 'nIter'.

'"target"' is the default: tuned against tuned, it wins every column at 3 ETAs and is the only rule that adapts at all at 8 ETAs. Its cost is on the 1-ETA fixture, where it roughly doubles theta RMSE (0.00113 to 0.00224) and takes about twice as many iterations. That trade follows the same weighting 'auto' uses: weights with infinite variance are a correctness problem whose error is unbounded, while the extra Monte-Carlo noise is bounded and measurable.

Choose '"floor"' for the previous behaviour – a proposal left at its efficient starting value while coverage is healthy. It is also what the tail-machinery tests pin, because '"target"' repairs the tail itself and leaves the 'df' ladder nothing to fix.

**The tuned constants travel with the rule.** Selecting a rule also selects its tuned defaults ('nConvWindow' 20 for '"target"', 10 for '"floor"'), so switching to the NONMEM method does not silently run NONMEM's law on the other rule's tuning. An explicitly supplied value always wins.

df

Degrees of freedom of the importance-sampling proposal (NONMEM 'DF'). '0' (default) uses a multivariate **normal** proposal; any value '> 0' uses a multivariate **t** with that many degrees of freedom.

This changes the proposal's SHAPE rather than its width, and that is the distinction that matters. 'gamma' can only make a Gaussian proposal wider; it cannot give it heavier tails. When the target posterior has heavier tails than the proposal, the importance weights have infinite variance – and neither 'xi' nor the Kish effective sample size can detect it, because the offending mass lies where the proposal rarely lands. The Pareto k-hat diagnostic ('fit$env$impPsisK') does detect it: 'k > 0.7' means that subject's weights are unreliable. A t proposal has polynomial tails that dominate a Gaussian target's, which bounds the weights.

NONMEM's guidance (Bauer, *NONMEM Tutorial Part II*) is to set a nonzero 'DF' when there are fewer data points than etas, or for categorical data. Small values (3-8) are heavy; large values approach the Gaussian.

auto

NONMEM 'AUTO=1' equivalent: adapt the proposal degrees of freedom, the sample count and the acceptance target **per subject** rather than applying one global setting to everybody.

* **'df'** – any subject gets a heavy-tailed t proposal when the model is not transformably normal, and any subject whose Pareto k-hat reports tail failure gets one on that evidence. The tutorial's other trigger, "fewer data points than there are ETAs", is **not** applied on its own – see 'autoNonmemSparse'. An escalation that fails to improve k-hat over two iterations is withdrawn, since a heavy tail the data creates is not repairable by proposal shape. * **'isample'** – the total sample budget ('isample * nsub') is reallocated toward subjects whose effective-sample fraction is lowest, the tutorial's "many ETAs or ... large stochastic fluctuations". It is load-balancing, not a cost increase. Note sample count is deliberately *not* driven by Pareto k-hat: a heavy tail is not repairable by more draws (see 'df'). * **'iaccept'** – lowered to 0.2 for the same sparse/categorical subjects, per the tutorial.

The concrete values (the 'df' ladder, the k-hat thresholds, the budget reallocation rule) are **nlmixr2's choices**. NONMEM does not publish what 'AUTO=1' picks internally; only the triggers and 'IACCEPT ~ 0.2' are documented. Unlike NONMEM's AUTO, which its own tutorial warns "may result in lack of stochastic reproducibility", this remains seeded and thread-count independent.

Per-subject values are reported in 'fit$env$impDfInd', 'fit$env$impNsampleInd' and 'fit$env$impIacceptInd'.

**Measured trade-off.** 'auto = TRUE' (the default) improves the *tail* behaviour of the importance weights and the accuracy of 'Omega', at some cost in Monte-Carlo noise on the objective. On theophylline with three ETAs – a one-ETA model has no tail failure to fix, so it shows nothing either way – against a reference computed at 'isample = 8000', over 8 seeds:

  • 'auto = FALSE': max Pareto k-hat 0.941, 2.38 subjects above 0.7; objective RMSE 0.0113, 'Omega' RMSE 0.00406

  • 'auto = TRUE': max Pareto k-hat 0.571, 0.25 subjects above 0.7; objective RMSE 0.0165, 'Omega' RMSE 0.00301

So 'auto' removes the tail failure and estimates 'Omega' about 26 accurately, for about 46 on by default because weights with infinite variance are a correctness problem – their error is unbounded in the worst case – whereas the extra noise is a bounded, measurable cost. Setting 'df' globally gives a better objective still on a model that is uniformly heavy-tailed, but costs 75 more objective RMSE on one that is not, which is why it is not the default.

Set 'auto = FALSE' to recover the previous behaviour exactly (that path remains bit-identical to earlier versions), which is worth doing when you want the tightest possible objective on a model whose 'fit$env$impPsisK' values are already comfortably below 0.7.

autoNonmemSparse

Apply the NONMEM tutorial's 'nobs < neta' trigger unconditionally, so a subject with fewer observations than random effects always gets a t proposal. 'FALSE' (default) leaves such subjects to the Pareto k-hat evidence like any other, and withdraws an escalation that does not improve k-hat within two iterations.

The default diverges from the tutorial deliberately, on measurement. On a fixture built to the tutorial's own definition of sparse (2 observations, 3 etas), 8 seeds against an 'isample = 8000' reference, applying the rule made every number worse – objective RMSE 0.1517 -> 0.2059, 'Omega' RMSE 0.02379 -> 0.03163, and *more* failing subjects (3.88 -> 4.88). With fewer observations than random effects the individual posterior is not identified, so the heavy tail is structural and no proposal shape repairs it; the reference itself still reads max k-hat 0.794.

Set ‘TRUE' to get the documented NONMEM rule anyway. NONMEM’s own testing is not published and was not done on these models, so someone who measures the opposite on their own problem should be able to have it.

autoDfPatience

Number of consecutive iterations an escalated 'df' may fail to improve Pareto k-hat before that escalation is withdrawn and the subject returned to the proposal it had without it. '0' never withdraws. Withdrawal is final, so escalation and withdrawal cannot oscillate, and it never goes below the 'df' the model itself requires – a non-normal endpoint keeps its t proposal.

A rung is judged against what the subject manages WITHOUT any escalation, measured while it sits there, so deterioration that happens before any escalation is tracked and an escalation is never credited for it.

iscaleMin, iscaleMax

Lower/upper bounds for the adapted 'gamma' (NONMEM ISCALE_MIN / ISCALE_MAX). Both bounds are reachable under 'gammaRule="target"'; under '"floor"' 'gamma' only ever moves up, so only 'iscaleMax' can bind.

iaccept

Minimum importance-sampling effective-sample fraction (NONMEM IACCEPT). The proposal scale 'gamma' is kept at its efficient starting value while the achieved fraction stays at or above 'iaccept', and is inflated (toward 'iscaleMax') only when it drops below this floor.

ctol

Convergence tolerance on the windowed objective-function change; 'NULL' derives it from 'sigdig'.

nConvWindow

Length of the trailing iteration window used to average the objective-function change for convergence (NONMEM-style CTYPE).

impSeed

Base seed for the per-subject thread-safe (threefry) RNG streams; results are reproducible and independent of the thread count.

covMethod

Covariance method. '"imp"' (default) computes the Monte-Carlo importance-sampling observed-information covariance for the estimated thetas and Omega parameters (a finite-difference Hessian of the importance-sampling objective over fixed common-random-number samples), stashed as '$impCov' / '$impSe' and installed as the fit covariance; the theta standard errors match the Hessian-based FOCEI covariance, though the variance of a tightly-determined random effect (an Omega diagonal) can be over-estimated because the fixed samples barely span its prior variation. '"analytic"', '"r,s"', '"r"', '"s"' instead compute the FOCEI covariance post-fit at the converged estimates (see [foceiControl()]); '""' skips the covariance step.

qr

When 'TRUE', draw quasi-random (Sobol low-discrepancy) importance samples instead of pseudo-random Gaussian samples (QRPEM, Leary & Dunlavey PAGE 2012); the E-step integrals converge at O(1/N) instead of O(1/sqrt(N)).

qrShift

Only used with 'qr=TRUE'. When 'TRUE' each (iteration, subject) applies a random Cranley-Patterson shift to the Sobol points (seeded, thread-count independent); 'FALSE' reuses one fixed Sobol point set everywhere (fully deterministic E-step, no RNG in the draw).

qrRefresh

Only used with 'qr=TRUE' and 'qrShift=TRUE'. When 'TRUE' the shift is redrawn each iteration so residual quasi-random error averages out over the EM; 'FALSE' draws one shift per subject at the fit start, making each EM iteration a deterministic map (smoothest objective trace).

sir

When 'TRUE', accelerate the non-mu / residual-error M-step by SIR (sampling-importance-resampling): the theta-sensitivity Newton step uses 'sirSample' equal-weight resampled points per subject instead of all 'isample' weighted samples.

sirSample

Number of SIR resampled points per subject; 'NULL' uses 'max(25, ceiling(isample/10))'. Must be at most 'isample'.

muModel

Mu-referencing variant for the MAP inner problem; for 'impmapControl()' this is always '"lin"' and cannot be changed.

Value

impmapControl object

Author(s)

Matthew L. Fidler

Examples


impmapControl()

Control iteration-time print formatting

Description

Bundles the options controlling the iteration progress output emitted by 'nlmixr2' estimators. Pass as the 'print' argument to any '*Control()' function; the scalar form ('print = N') still works and is wrapped into an 'iterPrintControl()' internally.

Usage

iterPrintControl(
  every = 1L,
  ncol = NULL,
  headerEvery = NULL,
  useColor = NULL,
  simple = FALSE
)

Arguments

every

Integer. Print one iteration row every 'every' parameter evaluations; '0' suppresses output. Defaults to '1L'.

ncol

Integer or 'NULL'. Parameter columns per row before wrapping. 'NULL' (default) uses 'floor((getOption("width") - 23) / 12)'.

headerEvery

Integer or 'NULL'. Re-emit the column header every 'headerEvery' parameter-print events; '0' prints it once at fit start. 'NULL' (default) uses '10L'.

useColor

Logical (or 'NULL') emit ANSI bold/color escapes in the iteration print. 'NULL' (default) defers to [crayon::has_color()].

simple

Logical. When 'TRUE', print a single row per iteration, suppressing the unscaled ('U') / back-transformed ('X') rows. Defaults to 'FALSE'.

Value

A list with the validated, defaulted iteration-print options. Has class '"iterPrintControl"' so the outer '*Control()' functions can distinguish a pre-built object from a scalar 'print = N'.

Author(s)

Bill Denney, Matthew L. Fidler

Examples

iterPrintControl()
iterPrintControl(every = 5, headerEvery = 0)

Iteration-print configuration parameters (documentation stub)

Description

Shared '@param' docs for iteration-print formatting, used by both the scalar '*Control()' arguments and [iterPrintControl()] via '@inheritParams'.

Arguments

print

Either a scalar print-frequency ('0' = suppress, '1' (default) = every evaluation, 'N' = every Nth), OR a pre-built [iterPrintControl()] object. Equivalent to 'iterPrintControl(every = print, ncol = printNcol, useColor = useColor)'.

printNcol

Integer (or 'NULL') parameter columns per row before wrapping. 'NULL' (default) uses 'floor((getOption("width") - 23) / 12)'.

every

Integer. Print one iteration row every 'every' parameter evaluations; '0' suppresses output. Defaults to '1L'.

ncol

Integer or 'NULL'. Parameter columns per row before wrapping. 'NULL' (default) uses 'floor((getOption("width") - 23) / 12)'.

headerEvery

Integer or 'NULL'. Re-emit the column header every 'headerEvery' parameter-print events; '0' prints it once at fit start. 'NULL' (default) uses '10L'.

useColor

Logical (or 'NULL') emit ANSI bold/color escapes in the iteration print. 'NULL' (default) defers to [crayon::has_color()].

simple

Logical. When 'TRUE', print a single row per iteration, suppressing the unscaled ('U') / back-transformed ('X') rows. Defaults to 'FALSE'.

Value

Nothing; this is a documentation-only helper.


Control options for the Laplace estimation method

Description

This is the control options for the adaptive Gauss-Hermite quadrature for the likelihood. Note that nAGQ=1 is the same as the Laplace method.

Usage

laplaceControl(sigdig = 3, ..., nAGQ = 1)

Arguments

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

...

Parameters used in the default 'foceiControl()'

nAGQ

Number of Gauss-Hermite adaptive quadrature points. '0' disables AGQ; '1' is equivalent to Laplace. Cost grows quickly with ETAs: once the EBE is found, expect 'nAGQ^neta' (even 'nAGQ') or '(nAGQ^neta)-1' (odd 'nAGQ') additional evaluations per subject.

Details

This method can be made to more closely matches NONMEM-style Laplace estimation by requesting the log-likelihood from STAN as well as numerically calculated Hessian matrix. This is done with adding '+dnorm()' to the model for any normal end-points.

Value

laplaceControl object

Author(s)

Matthew L. Fidler

Examples




laplaceControl()

# Use adaptive quadrature

# x =  Litter size after 21 days, and the modeled value

r <- rats
r$dv <- r$x

# Time is not used in this model, but it is required in nlmixr2
# currently, add a dummy value

r$time <- 0

f <- function() {
  ini({
    t1 <- 1
    t2 <- 1
    t3 <- 1
    eta1 ~ 1
  })
  model({
    lp <- t1 * x1 + t2 * x2 + (x1 + x2*t3) * eta1
    p <- pnorm(lp)
    m1 <- m # need to add outside of model specification
    x ~ dbinom(m1, p)
  })
}

fit <- nlmixr(f, r, est="laplace")


p <- pump

p$dv <- p$y
p$time <- 0 # dummy time

f <- function() {
  ini({
    t1 <- 1
    t2 <- 1
    t3 <- 1
    t4 <- 1
    eta1 ~ 1
  })
  model({
    if (group == 1) {
       lp <- t1 + t2 * logtstd
    } else {
       lp <- t3 + t4 * logtstd
    }
    lp <- lp + eta1
    lam <- exp(lp)
    y ~ dpois(lam)
  })
}

fit <- nlmixr(f, p, est="laplace")




Control for lbfgsb3c estimation method in nlmixr2

Description

Control for lbfgsb3c estimation method in nlmixr2

Usage

lbfgsb3cControl(
  trace = 0,
  factr = NULL,
  pgtol = 0,
  abstol = 0,
  reltol = 0,
  lmm = 5L,
  maxit = 10000L,
  returnLbfgsb3c = FALSE,
  stickyRecalcN = 4,
  maxOdeRecalc = 5,
  odeRecalcFactor = 10^(0.5),
  indTolRelax = TRUE,
  useColor = NULL,
  printNcol = NULL,
  print = 1L,
  normType = c("rescale2", "mean", "rescale", "std", "len", "constant"),
  scaleType = c("nlmixr2", "norm", "mult", "multAdd"),
  scaleCmax = 1e+05,
  scaleCmin = 1e-05,
  scaleC = NULL,
  scaleTo = 1,
  gradTo = 1,
  rxControl = NULL,
  optExpression = TRUE,
  sumProd = FALSE,
  literalFix = TRUE,
  literalFixRes = TRUE,
  addProp = c("combined2", "combined1"),
  eventSens = c("jump", "fd"),
  sensMethod = c("default", "forward"),
  calcTables = TRUE,
  compress = FALSE,
  covMethod = c("r", ""),
  adjObf = TRUE,
  ci = 0.95,
  sigdig = 3,
  sigdigTable = NULL,
  ...
)

Arguments

trace

If positive, print tracing information; higher values give more detail (see source for "L-BFGS-B" trace levels).

factr

Convergence tolerance factor for "L-BFGS-B"; converges when the objective reduction is within this factor of machine tolerance (default 1e7, i.e. ~1e-8).

pgtol

Tolerance on the projected gradient for "L-BFGS-B"; 0 (default) suppresses the check.

abstol

Absolute x-value tolerance for "L-BFGS-B"; 0 (default) suppresses the check.

reltol

Relative x-value tolerance for "L-BFGS-B"; 0 (default) suppresses the check.

lmm

Number of BFGS updates retained in "L-BFGS-B" (default 5).

maxit

maximum number of iterations.

returnLbfgsb3c

return the lbfgsb3c output instead of the nlmixr2 fit

stickyRecalcN

The number of bad ODE solves before reducing the atol/rtol for the rest of the problem.

maxOdeRecalc

Maximum number of times to reduce the ODE tolerances and try to resolve the system if there was a bad ODE solve.

odeRecalcFactor

The ODE recalculation factor when ODE solving goes bad, this is the factor the rtol/atol is reduced

indTolRelax

When 'TRUE' (default), only subjects whose ODE solve produced NaN/Inf have their tolerances relaxed, and the relaxed tolerance persists across optimizer calls (sticky). When 'FALSE', all subjects have their tolerances relaxed on each retry and tolerances are reset afterward.

useColor

Logical (or 'NULL') emit ANSI bold/color escapes in the iteration print. 'NULL' (default) defers to [crayon::has_color()].

printNcol

Integer (or 'NULL') parameter columns per row before wrapping. 'NULL' (default) uses 'floor((getOption("width") - 23) / 12)'.

print

Either a scalar print-frequency ('0' = suppress, '1' (default) = every evaluation, 'N' = every Nth), OR a pre-built [iterPrintControl()] object. Equivalent to 'iterPrintControl(every = print, ncol = printNcol, useColor = useColor)'.

normType

Parameter normalization/scaling used to get scaled initial values for scaleType, of the form Vscaled = (Vunscaled-C1)/C2 (see Feature Scaling; rescale2 follows the OptdesX manual): "rescale2" scales all parameters to (-1, 1); "rescale" (min-max) scales to (0, 1); "mean" centers on the mean with range (0, 1); "std" standardizes by mean/sd; "len" scales to unit (Euclidean) length; "constant" performs no normalization (C1=0, C2=1).

scaleType

The scaling scheme for nlmixr2: "nlmixr2" (default) scales as (current-init)*scaleC[i] + scaleTo, with scaleTo from normType and scales from scaleC; "norm" uses the simple scaling from normType; "mult" scales multiplicatively as current/init*scaleTo; "multAdd" scales linearly ((current-init)+scaleTo) for parameters in an exponential block (e.g. exp(theta)) and multiplicatively otherwise.

scaleCmax

Maximum value of the scaleC to prevent overflow.

scaleCmin

Minimum value of the scaleC to prevent underflow.

scaleC

Scaling constant used with scaleType="nlmixr2"; when not specified, chosen by parameter type to keep gradient sizes similar on a log scale: '1' for exp()-transformed/power/boxCox/ yeoJohnson parameters, '0.5*abs(est)' for additive/proportional/ lognormal error parameters, 'abs(1/digamma(est+1))' for factorials, and 'log(abs(est))*abs(est)' for log-scale parameters. May be set explicitly per parameter if these defaults don't apply well.

scaleTo

Scale the initial parameter estimate to this value. By default this is 1. When zero or below, no scaling is performed.

gradTo

this is the factor that the gradient is scaled to before optimizing. This only works with scaleType="nlmixr2".

rxControl

'rxode2' ODE solving options during fitting, created with 'rxControl()'

optExpression

Optimize the rxode2 expression to speed up calculation. By default this is turned on.

sumProd

Is a boolean indicating if the model should change multiplication to high precision multiplication and sums to high precision sums using the PreciseSums package. By default this is FALSE.

literalFix

boolean, substitute fixed population values as literals and re-adjust ui and parameter estimates after optimization; Default is 'TRUE'.

literalFixRes

boolean, substitute fixed population values as literals and re-adjust ui and parameter estimates after optimization; Default is 'TRUE'.

addProp

Type of additive-plus-proportional error: '"combined1"', where standard deviations add:

y = f + (a + b\times f^c) \times \varepsilon

; or '"combined2"', where variances add:

y = f + \sqrt{a^2 + b^2\times f^{2\times c}} \times \varepsilon

. Here y = observed, f = predicted, a = additive sd, b = proportional/power sd, c = power exponent (1 in the proportional case).

eventSens

Controls how dosing/event-parameter ('alag', 'F', 'rate', 'dur') sensitivities are computed for THETA/ETA gradients: ‘"jump"' (default) uses rxode2’s analytic event sensitivities; '"fd"' uses the legacy finite-difference behavior.

sensMethod

Method used to compute the ODE parameter sensitivities. '"forward"' uses the classic variational (forward) sensitivity ODEs; '"default"' is the same thing.

calcTables

This boolean is to determine if the foceiFit will calculate tables. By default this is TRUE

compress

Should the object have compressed items

covMethod

Method for calculating the covariance. "r" (the default) uses nlmixr2's nlmixr2Hess() Hessian; "" skips the covariance step.

adjObf

is a boolean to indicate if the objective function should be adjusted to be closer to NONMEM's default objective function. By default this is TRUE

ci

Confidence level for some tables. By default this is 0.95 or 95% confidence.

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

sigdigTable

Significant digits in the final output table. If not specified, then it matches the significant digits in the 'sigdig' optimization algorithm. If 'sigdig' is NULL, use 3.

...

Ignored parameters

Value

bobqya control structure

Author(s)

Matthew L. Fidler

Examples



# A logit regression example with emax model

dsn <- data.frame(i=1:1000)
dsn$time <- exp(rnorm(1000))
dsn$DV=rbinom(1000,1,exp(-1+dsn$time)/(1+exp(-1+dsn$time)))

mod <- function() {
 ini({
   E0 <- 0.5
   Em <- 0.5
   E50 <- 2
   g <- fix(2)
 })
 model({
   v <- E0+Em*time^g/(E50^g+time^g)
   ll(bin) ~ DV * v - log(1 + exp(v))
 })
}

fit2 <- nlmixr(mod, dsn, est="lbfgsb3c")

print(fit2)

# you can also get the nlm output with fit2$lbfgsb3c

fit2$lbfgsb3c

# The nlm control has been modified slightly to include
# extra components and name the parameters


Control options for the magq estimation method

Description

Mu-referenced-FOCEI-family closed-form-regression ('"lin"') variant of adaptive Gauss-Hermite quadrature; see 'foceiControl(muModel=)'.

Usage

magqControl(
  sigdig = 3,
  nAGQ = 2,
  ...,
  interaction = TRUE,
  agqLow = -Inf,
  agqHi = Inf,
  muModel = c("lin", "irls", "none")
)

Arguments

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

nAGQ

Number of Gauss-Hermite adaptive quadrature points. '0' disables AGQ; '1' is equivalent to Laplace. Cost grows quickly with ETAs: once the EBE is found, expect 'nAGQ^neta' (even 'nAGQ') or '(nAGQ^neta)-1' (odd 'nAGQ') additional evaluations per subject.

...

Parameters used in the default 'foceiControl()'

interaction

boolean, Interaction term for the model, in this case the default is 'TRUE'; For adaptive quadrature, with normal distribution the Hessian is calculated with the foce(i) approximation

agqLow

The lower bound for adaptive quadrature log-likelihood. By default this is -Inf; in the original nlmixr's gnlmm it was -700.

agqHi

The upper bound for adaptive quadrature log-likelihood. By default this is Inf; in the original nlmixr's gnlmm was 400.

muModel

Selects the regression variant; for 'magqControl()' this is always '"lin"' and cannot be changed – use 'iagqControl()' for the IRLS variant.

Value

magqControl object

Author(s)

Matthew L. Fidler

Examples


magqControl()

Control options for the mfoce estimation method

Description

Mu-referenced-FOCEI-family closed-form-regression ('"lin"') variant of FOCE (no interaction); see 'foceiControl(muModel=)'.

Usage

mfoceControl(
  sigdig = 3,
  ...,
  interaction = FALSE,
  muModel = c("lin", "irls", "none")
)

Arguments

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

...

Parameters used in the default 'foceiControl()'

interaction

Interaction term for the model, in this case the default is 'FALSE'; it cannot be changed, use 'mfocei' instead

muModel

Selects the regression variant; for 'mfoceControl()' this is always '"lin"' and cannot be changed – use 'ifoceControl()' for the IRLS variant.

Value

mfoceControl object

Difference from 'focei'

The 'mfocei'/'ifocei' (and related) methods apply the mu2+ covariate hooks, which expand algebraic mu-referenced covariate expressions (e.g. 'cl.wt*log(WT/70)') into estimable mu-referenced parameters and split covariates into non-time-varying (absorbed into the phi term) and time-varying (kept as 'beta' regressors). Calling 'focei' directly does NOT apply these hooks, so these methods can estimate more mu-referenced models than plain 'focei' – there is a genuine difference between calling e.g. 'est="mfocei"' and 'est="focei"'.

All mu-referenced population thetas – with or without covariates – are profiled out of the outer optimizer by the in-C++ regression (intercept-only for covariate-free pairs), so outer gradients are only calculated for the non-mu-referenced parameters (residual errors, omegas, non-mu thetas). Bounded mu-referenced parameters are regression-updated with the update clamped to the bounds (a clamp is reported once as a fit note); user-fixed ('fix()') mu thetas stay out of the regression.

Author(s)

Matthew L. Fidler

Examples


mfoceControl()

Control options for the mfocei estimation method

Description

Mu-referenced-FOCEI-family closed-form-regression ('"lin"') variant of FOCEI; see 'foceiControl(muModel=)'.

Usage

mfoceiControl(sigdig = 3, ..., muModel = c("lin", "irls", "none"))

Arguments

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

...

Parameters used in the default 'foceiControl()'

muModel

Selects the regression variant; for 'mfoceiControl()' this is always '"lin"' and cannot be changed – use 'ifoceiControl()' for the IRLS variant.

Value

mfoceiControl object

Difference from 'focei'

The 'mfocei'/'ifocei' (and related) methods apply the mu2+ covariate hooks, which expand algebraic mu-referenced covariate expressions (e.g. 'cl.wt*log(WT/70)') into estimable mu-referenced parameters and split covariates into non-time-varying (absorbed into the phi term) and time-varying (kept as 'beta' regressors). Calling 'focei' directly does NOT apply these hooks, so these methods can estimate more mu-referenced models than plain 'focei' – there is a genuine difference between calling e.g. 'est="mfocei"' and 'est="focei"'.

All mu-referenced population thetas – with or without covariates – are profiled out of the outer optimizer by the in-C++ regression (intercept-only for covariate-free pairs), so outer gradients are only calculated for the non-mu-referenced parameters (residual errors, omegas, non-mu thetas). Bounded mu-referenced parameters are regression-updated with the update clamped to the bounds (a clamp is reported once as a fit note); user-fixed ('fix()') mu thetas stay out of the regression.

Author(s)

Matthew L. Fidler

Examples


mfoceiControl()

Control options for the mfocep (mu-referenced FOCE+) estimation method

Description

Mu-referenced-FOCEI-family closed-form-regression ('"lin"') variant of FOCE+ (no interaction, live conditional residual variance R); it is 'mfoce' with 'foce = "foce+"' forced (see 'foceiControl(foce=)').

Usage

mfocepControl(
  sigdig = 3,
  ...,
  interaction = FALSE,
  muModel = c("lin", "irls", "none"),
  foce = "foce+"
)

Arguments

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

...

Parameters used in the default 'foceiControl()'

interaction

Interaction term for the model, in this case the default is 'FALSE'; it cannot be changed, use 'mfocei' instead

muModel

Selects the regression variant; for 'mfocepControl()' this is always '"lin"' and cannot be changed – use 'ifocepControl()' for the IRLS variant.

foce

FOCE residual-variance mode; for 'mfocepControl()' this is always '"foce+"' and cannot be changed – use 'mfoceControl()' for '"nonmem"'

Value

mfocepControl object

Difference from 'focei'

The 'mfocei'/'ifocei' (and related) methods apply the mu2+ covariate hooks, which expand algebraic mu-referenced covariate expressions (e.g. 'cl.wt*log(WT/70)') into estimable mu-referenced parameters and split covariates into non-time-varying (absorbed into the phi term) and time-varying (kept as 'beta' regressors). Calling 'focei' directly does NOT apply these hooks, so these methods can estimate more mu-referenced models than plain 'focei' – there is a genuine difference between calling e.g. 'est="mfocei"' and 'est="focei"'.

All mu-referenced population thetas – with or without covariates – are profiled out of the outer optimizer by the in-C++ regression (intercept-only for covariate-free pairs), so outer gradients are only calculated for the non-mu-referenced parameters (residual errors, omegas, non-mu thetas). Bounded mu-referenced parameters are regression-updated with the update clamped to the bounds (a clamp is reported once as a fit note); user-fixed ('fix()') mu thetas stay out of the regression.

Author(s)

Matthew L. Fidler

Examples


mfocepControl()

Control options for the mlaplace estimation method

Description

Mu-referenced-FOCEI-family closed-form-regression ('"lin"') variant of the Laplace method ('nAGQ=1'); see 'foceiControl(muModel=)'.

Usage

mlaplaceControl(sigdig = 3, ..., nAGQ = 1, muModel = c("lin", "irls", "none"))

Arguments

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

...

Parameters used in the default 'foceiControl()'

nAGQ

Number of Gauss-Hermite adaptive quadrature points. '0' disables AGQ; '1' is equivalent to Laplace. Cost grows quickly with ETAs: once the EBE is found, expect 'nAGQ^neta' (even 'nAGQ') or '(nAGQ^neta)-1' (odd 'nAGQ') additional evaluations per subject.

muModel

Selects the regression variant; for 'mlaplaceControl()' this is always '"lin"' and cannot be changed – use 'ilaplaceControl()' for the IRLS variant.

Value

mlaplaceControl object

Author(s)

Matthew L. Fidler

Examples


mlaplaceControl()

Control for n1qn1 estimation method in nlmixr2

Description

Control for n1qn1 estimation method in nlmixr2

Usage

n1qn1Control(
  epsilon = NULL,
  max_iterations = 10000,
  nsim = 10000,
  imp = 0,
  print.functions = FALSE,
  returnN1qn1 = FALSE,
  stickyRecalcN = 4,
  maxOdeRecalc = 5,
  odeRecalcFactor = 10^(0.5),
  indTolRelax = TRUE,
  useColor = NULL,
  printNcol = NULL,
  print = 1L,
  normType = c("rescale2", "mean", "rescale", "std", "len", "constant"),
  scaleType = c("nlmixr2", "norm", "mult", "multAdd"),
  scaleCmax = 1e+05,
  scaleCmin = 1e-05,
  scaleC = NULL,
  scaleTo = 1,
  gradTo = 1,
  rxControl = NULL,
  optExpression = TRUE,
  sumProd = FALSE,
  literalFix = TRUE,
  literalFixRes = TRUE,
  addProp = c("combined2", "combined1"),
  eventSens = c("jump", "fd"),
  sensMethod = c("default", "forward"),
  calcTables = TRUE,
  compress = FALSE,
  covMethod = c("r", "n1qn1", ""),
  adjObf = TRUE,
  ci = 0.95,
  sigdig = 3,
  sigdigTable = NULL,
  boundedTransform = TRUE,
  ...
)

Arguments

epsilon

Precision of estimate for n1qn1 optimization.

max_iterations

Number of iterations

nsim

Number of function evaluations

imp

Verbosity of messages.

print.functions

Boolean to control if the function value and parameter estimates are echoed every time a function is called.

returnN1qn1

return the n1qn1 output instead of the nlmixr2 fit

stickyRecalcN

The number of bad ODE solves before reducing the atol/rtol for the rest of the problem.

maxOdeRecalc

Maximum number of times to reduce the ODE tolerances and try to resolve the system if there was a bad ODE solve.

odeRecalcFactor

The ODE recalculation factor when ODE solving goes bad, this is the factor the rtol/atol is reduced

indTolRelax

When 'TRUE' (default), only subjects whose ODE solve produced NaN/Inf have their tolerances relaxed, and the relaxed tolerance persists across optimizer calls (sticky). When 'FALSE', all subjects have their tolerances relaxed on each retry and tolerances are reset afterward.

useColor

Logical (or 'NULL') emit ANSI bold/color escapes in the iteration print. 'NULL' (default) defers to [crayon::has_color()].

printNcol

Integer (or 'NULL') parameter columns per row before wrapping. 'NULL' (default) uses 'floor((getOption("width") - 23) / 12)'.

print

Either a scalar print-frequency ('0' = suppress, '1' (default) = every evaluation, 'N' = every Nth), OR a pre-built [iterPrintControl()] object. Equivalent to 'iterPrintControl(every = print, ncol = printNcol, useColor = useColor)'.

normType

Parameter normalization/scaling used to get scaled initial values for scaleType, of the form Vscaled = (Vunscaled-C1)/C2 (see Feature Scaling; rescale2 follows the OptdesX manual): "rescale2" scales all parameters to (-1, 1); "rescale" (min-max) scales to (0, 1); "mean" centers on the mean with range (0, 1); "std" standardizes by mean/sd; "len" scales to unit (Euclidean) length; "constant" performs no normalization (C1=0, C2=1).

scaleType

The scaling scheme for nlmixr2: "nlmixr2" (default) scales as (current-init)*scaleC[i] + scaleTo, with scaleTo from normType and scales from scaleC; "norm" uses the simple scaling from normType; "mult" scales multiplicatively as current/init*scaleTo; "multAdd" scales linearly ((current-init)+scaleTo) for parameters in an exponential block (e.g. exp(theta)) and multiplicatively otherwise.

scaleCmax

Maximum value of the scaleC to prevent overflow.

scaleCmin

Minimum value of the scaleC to prevent underflow.

scaleC

Scaling constant used with scaleType="nlmixr2"; when not specified, chosen by parameter type to keep gradient sizes similar on a log scale: '1' for exp()-transformed/power/boxCox/ yeoJohnson parameters, '0.5*abs(est)' for additive/proportional/ lognormal error parameters, 'abs(1/digamma(est+1))' for factorials, and 'log(abs(est))*abs(est)' for log-scale parameters. May be set explicitly per parameter if these defaults don't apply well.

scaleTo

Scale the initial parameter estimate to this value. By default this is 1. When zero or below, no scaling is performed.

gradTo

this is the factor that the gradient is scaled to before optimizing. This only works with scaleType="nlmixr2".

rxControl

'rxode2' ODE solving options during fitting, created with 'rxControl()'

optExpression

Optimize the rxode2 expression to speed up calculation. By default this is turned on.

sumProd

Is a boolean indicating if the model should change multiplication to high precision multiplication and sums to high precision sums using the PreciseSums package. By default this is FALSE.

literalFix

boolean, substitute fixed population values as literals and re-adjust ui and parameter estimates after optimization; Default is 'TRUE'.

literalFixRes

boolean, substitute fixed population values as literals and re-adjust ui and parameter estimates after optimization; Default is 'TRUE'.

addProp

Type of additive-plus-proportional error: '"combined1"', where standard deviations add:

y = f + (a + b\times f^c) \times \varepsilon

; or '"combined2"', where variances add:

y = f + \sqrt{a^2 + b^2\times f^{2\times c}} \times \varepsilon

. Here y = observed, f = predicted, a = additive sd, b = proportional/power sd, c = power exponent (1 in the proportional case).

eventSens

Controls how dosing/event-parameter ('alag', 'F', 'rate', 'dur') sensitivities are computed for THETA/ETA gradients: ‘"jump"' (default) uses rxode2’s analytic event sensitivities; '"fd"' uses the legacy finite-difference behavior.

sensMethod

Method used to compute the ODE parameter sensitivities. '"forward"' uses the classic variational (forward) sensitivity ODEs; '"default"' is the same thing.

calcTables

This boolean is to determine if the foceiFit will calculate tables. By default this is TRUE

compress

Should the object have compressed items

covMethod

Method for calculating the covariance. "r" (the default) uses nlmixr2's nlmixr2Hess() Hessian; "n1qn1" uses the optimizer's own Hessian; "" skips the covariance step.

adjObf

is a boolean to indicate if the objective function should be adjusted to be closer to NONMEM's default objective function. By default this is TRUE

ci

Confidence level for some tables. By default this is 0.95 or 95% confidence.

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

sigdigTable

Significant digits in the final output table. If not specified, then it matches the significant digits in the 'sigdig' optimization algorithm. If 'sigdig' is NULL, use 3.

boundedTransform

When 'TRUE' (default), bounded parameters are transformed for unbounded optimization methods and back-transformed for final estimates. 'FALSE' optimizes on the original scale with bounds passed to the optimizer. 'NA' transforms for optimization but skips the final back-transform.

...

Ignored parameters

Value

bobqya control structure

Author(s)

Matthew L. Fidler

Examples



# A logit regression example with emax model

dsn <- data.frame(i=1:1000)
dsn$time <- exp(rnorm(1000))
dsn$DV=rbinom(1000,1,exp(-1+dsn$time)/(1+exp(-1+dsn$time)))

mod <- function() {
 ini({
   E0 <- 0.5
   Em <- 0.5
   E50 <- 2
   g <- fix(2)
 })
 model({
   v <- E0+Em*time^g/(E50^g+time^g)
   ll(bin) ~ DV * v - log(1 + exp(v))
 })
}

fit2 <- nlmixr(mod, dsn, est="n1qn1")

print(fit2)

# you can also get the nlm output with fit2$n1qn1

fit2$n1qn1

# The nlm control has been modified slightly to include
# extra components and name the parameters


Control for newuoa estimation method in nlmixr2

Description

Control for newuoa estimation method in nlmixr2

Usage

newuoaControl(
  npt = NULL,
  rhobeg = NULL,
  rhoend = NULL,
  iprint = 0L,
  maxfun = 100000L,
  returnNewuoa = FALSE,
  stickyRecalcN = 4,
  maxOdeRecalc = 5,
  odeRecalcFactor = 10^(0.5),
  indTolRelax = TRUE,
  useColor = NULL,
  printNcol = NULL,
  print = 1L,
  normType = c("rescale2", "mean", "rescale", "std", "len", "constant"),
  scaleType = c("nlmixr2", "norm", "mult", "multAdd"),
  scaleCmax = 1e+05,
  scaleCmin = 1e-05,
  scaleC = NULL,
  scaleTo = 1,
  rxControl = NULL,
  optExpression = TRUE,
  sumProd = FALSE,
  literalFix = TRUE,
  literalFixRes = TRUE,
  addProp = c("combined2", "combined1"),
  calcTables = TRUE,
  compress = FALSE,
  covMethod = c("r", ""),
  adjObf = TRUE,
  ci = 0.95,
  sigdig = 3,
  sigdigTable = NULL,
  boundedTransform = TRUE,
  eventSens = c("jump", "fd"),
  ...
)

Arguments

npt

Number of points for bobyqa's quadratic approximation to the objective; must be in '[n+2, (n+1)(n+2)/2]'. Defaults to '2*n + 1'. (bobyqa)

rhobeg

Initial trust region radius for the bobyqa outer optimizer (with 'rhoend', must satisfy '0 < rhoend < rhobeg'). Default '0.2' (20 'abs(upper-lower)/2'. (bobyqa)

rhoend

Final trust region radius. If not defined, '10^(-sigdig)' is used. (bobyqa)

iprint

Controls amount of printing ('0'=none, '1'=start/end only, '2'=each new rho, '3'=every function evaluation, '>3'=every 'iprint' evaluations). Default '0'.

maxfun

The maximum allowed number of function evaluations. If this is exceeded, the method will terminate.

returnNewuoa

return the newuoa output instead of the nlmixr2 fit

stickyRecalcN

The number of bad ODE solves before reducing the atol/rtol for the rest of the problem.

maxOdeRecalc

Maximum number of times to reduce the ODE tolerances and try to resolve the system if there was a bad ODE solve.

odeRecalcFactor

The ODE recalculation factor when ODE solving goes bad, this is the factor the rtol/atol is reduced

indTolRelax

When 'TRUE' (default), only subjects whose ODE solve produced NaN/Inf have their tolerances relaxed, and the relaxed tolerance persists across optimizer calls (sticky). When 'FALSE', all subjects have their tolerances relaxed on each retry and tolerances are reset afterward.

useColor

Logical (or 'NULL') emit ANSI bold/color escapes in the iteration print. 'NULL' (default) defers to [crayon::has_color()].

printNcol

Integer (or 'NULL') parameter columns per row before wrapping. 'NULL' (default) uses 'floor((getOption("width") - 23) / 12)'.

print

Either a scalar print-frequency ('0' = suppress, '1' (default) = every evaluation, 'N' = every Nth), OR a pre-built [iterPrintControl()] object. Equivalent to 'iterPrintControl(every = print, ncol = printNcol, useColor = useColor)'.

normType

Parameter normalization/scaling used to get scaled initial values for scaleType, of the form Vscaled = (Vunscaled-C1)/C2 (see Feature Scaling; rescale2 follows the OptdesX manual): "rescale2" scales all parameters to (-1, 1); "rescale" (min-max) scales to (0, 1); "mean" centers on the mean with range (0, 1); "std" standardizes by mean/sd; "len" scales to unit (Euclidean) length; "constant" performs no normalization (C1=0, C2=1).

scaleType

The scaling scheme for nlmixr2: "nlmixr2" (default) scales as (current-init)*scaleC[i] + scaleTo, with scaleTo from normType and scales from scaleC; "norm" uses the simple scaling from normType; "mult" scales multiplicatively as current/init*scaleTo; "multAdd" scales linearly ((current-init)+scaleTo) for parameters in an exponential block (e.g. exp(theta)) and multiplicatively otherwise.

scaleCmax

Maximum value of the scaleC to prevent overflow.

scaleCmin

Minimum value of the scaleC to prevent underflow.

scaleC

Scaling constant used with scaleType="nlmixr2"; when not specified, chosen by parameter type to keep gradient sizes similar on a log scale: '1' for exp()-transformed/power/boxCox/ yeoJohnson parameters, '0.5*abs(est)' for additive/proportional/ lognormal error parameters, 'abs(1/digamma(est+1))' for factorials, and 'log(abs(est))*abs(est)' for log-scale parameters. May be set explicitly per parameter if these defaults don't apply well.

scaleTo

Scale the initial parameter estimate to this value. By default this is 1. When zero or below, no scaling is performed.

rxControl

'rxode2' ODE solving options during fitting, created with 'rxControl()'

optExpression

Optimize the rxode2 expression to speed up calculation. By default this is turned on.

sumProd

Is a boolean indicating if the model should change multiplication to high precision multiplication and sums to high precision sums using the PreciseSums package. By default this is FALSE.

literalFix

boolean, substitute fixed population values as literals and re-adjust ui and parameter estimates after optimization; Default is 'TRUE'.

literalFixRes

boolean, substitute fixed population values as literals and re-adjust ui and parameter estimates after optimization; Default is 'TRUE'.

addProp

Type of additive-plus-proportional error: '"combined1"', where standard deviations add:

y = f + (a + b\times f^c) \times \varepsilon

; or '"combined2"', where variances add:

y = f + \sqrt{a^2 + b^2\times f^{2\times c}} \times \varepsilon

. Here y = observed, f = predicted, a = additive sd, b = proportional/power sd, c = power exponent (1 in the proportional case).

calcTables

This boolean is to determine if the foceiFit will calculate tables. By default this is TRUE

compress

Should the object have compressed items

covMethod

Method for calculating the covariance. "r" (the default) uses nlmixr2's nlmixr2Hess() Hessian; "" skips the covariance step.

adjObf

is a boolean to indicate if the objective function should be adjusted to be closer to NONMEM's default objective function. By default this is TRUE

ci

Confidence level for some tables. By default this is 0.95 or 95% confidence.

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

sigdigTable

Significant digits in the final output table. If not specified, then it matches the significant digits in the 'sigdig' optimization algorithm. If 'sigdig' is NULL, use 3.

boundedTransform

When 'TRUE' (default), bounded parameters are transformed for unbounded optimization methods and back-transformed for final estimates. 'FALSE' optimizes on the original scale with bounds passed to the optimizer. 'NA' transforms for optimization but skips the final back-transform.

eventSens

Controls how dosing/event-parameter ('alag', 'F', 'rate', 'dur') sensitivities are computed for THETA/ETA gradients: ‘"jump"' (default) uses rxode2’s analytic event sensitivities; '"fd"' uses the legacy finite-difference behavior.

...

Ignored parameters

Value

newuoa control structure

Author(s)

Matthew L. Fidler

Examples



# A logit regression example with emax model

dsn <- data.frame(i=1:1000)
dsn$time <- exp(rnorm(1000))
dsn$DV=rbinom(1000,1,exp(-1+dsn$time)/(1+exp(-1+dsn$time)))

mod <- function() {
 ini({
   E0 <- 0.5
   Em <- 0.5
   E50 <- 2
   g <- fix(2)
 })
 model({
   v <- E0+Em*time^g/(E50^g+time^g)
   ll(bin) ~ DV * v - log(1 + exp(v))
 })
}

fit2 <- nlmixr(mod, dsn, est="newuoa")

print(fit2)

# you can also get the nlm output with

fit2$newuoa

# The nlm control has been modified slightly to include
# extra components and name the parameters


nlmixr2 defaults controls for nlm

Description

nlmixr2 defaults controls for nlm

Usage

nlmControl(
  typsize = NULL,
  fscale = 1,
  print.level = 0,
  ndigit = NULL,
  gradtol = NULL,
  stepmax = NULL,
  steptol = NULL,
  iterlim = 10000,
  check.analyticals = FALSE,
  returnNlm = FALSE,
  solveType = c("hessian", "grad", "fun"),
  stickyRecalcN = 4,
  maxOdeRecalc = 5,
  odeRecalcFactor = 10^(0.5),
  indTolRelax = TRUE,
  eventType = c("central", "forward"),
  shiErr = (.Machine$double.eps)^(1/3),
  shi21maxFD = 20L,
  optimHessType = c("central", "forward"),
  hessErr = (.Machine$double.eps)^(1/3),
  shi21maxHess = 20L,
  censOption = c("gauss", "laplace"),
  eventSens = c("jump", "fd"),
  sensMethod = c("default", "forward"),
  useColor = NULL,
  printNcol = NULL,
  print = 1L,
  normType = c("rescale2", "mean", "rescale", "std", "len", "constant"),
  scaleType = c("nlmixr2", "norm", "mult", "multAdd"),
  scaleCmax = 1e+05,
  scaleCmin = 1e-05,
  scaleC = NULL,
  scaleTo = 1,
  gradTo = 1,
  rxControl = NULL,
  optExpression = TRUE,
  sumProd = FALSE,
  literalFix = TRUE,
  literalFixRes = TRUE,
  addProp = c("combined2", "combined1"),
  calcTables = TRUE,
  compress = FALSE,
  covMethod = c("r", "nlm", ""),
  adjObf = TRUE,
  ci = 0.95,
  sigdig = 3,
  sigdigTable = NULL,
  boundedTransform = TRUE,
  ...
)

Arguments

typsize

an estimate of the size of each parameter at the minimum.

fscale

an estimate of the size of f at the minimum.

print.level

this argument determines the level of printing which is done during the minimization process. The default value of 0 means that no printing occurs, a value of 1 means that initial and final details are printed and a value of 2 means that full tracing information is printed.

ndigit

the number of significant digits in the function f.

gradtol

a positive scalar giving the tolerance at which the scaled gradient is considered close enough to zero to terminate the algorithm. The scaled gradient is a measure of the relative change in f in each direction p[i] divided by the relative change in p[i].

stepmax

a positive scalar which gives the maximum allowable scaled step length. stepmax is used to prevent steps which would cause the optimization function to overflow, to prevent the algorithm from leaving the area of interest in parameter space, or to detect divergence in the algorithm. stepmax would be chosen small enough to prevent the first two of these occurrences, but should be larger than any anticipated reasonable step.

steptol

A positive scalar providing the minimum allowable relative step length.

iterlim

a positive integer specifying the maximum number of iterations to be performed before the program is terminated.

check.analyticals

a logical scalar specifying whether the analytic gradients and Hessians, if they are supplied, should be checked against numerical derivatives at the initial parameter values. This can help detect incorrectly formulated gradients or Hessians.

returnNlm

is a logical that allows a return of the 'nlm' object

solveType

controls whether ‘nlm' uses nlmixr2’s analytical gradients (event-related parameters like lag time/duration/rate/F use Shi2021 finite differences instead): '"hessian"' builds a Hessian from the analytical gradient via finite differences, '"gradient"' supplies the gradient and lets 'nlm' compute the finite-difference Hessian, and '"fun"' lets 'nlm' compute both by finite differences.

stickyRecalcN

The number of bad ODE solves before reducing the atol/rtol for the rest of the problem.

maxOdeRecalc

Maximum number of times to reduce the ODE tolerances and try to resolve the system if there was a bad ODE solve.

odeRecalcFactor

The ODE recalculation factor when ODE solving goes bad, this is the factor the rtol/atol is reduced

indTolRelax

When 'TRUE' (default), only subjects whose ODE solve produced NaN/Inf have their tolerances relaxed, and the relaxed tolerance persists across optimizer calls (sticky). When 'FALSE', all subjects have their tolerances relaxed on each retry and tolerances are reset afterward.

eventType

Event gradient type for dosing events; Can be "central" or "forward"

shiErr

This represents the epsilon when optimizing the ideal step size for numeric differentiation using the Shi2021 method

shi21maxFD

The maximum number of steps for the optimization of the forward difference step size when using dosing events (lag time, modeled duration/rate and bioavailability)

optimHessType

Hessian type for numeric-difference individual Hessians in generalized log-likelihood estimation: "central" (matches R's 'optimHess()', default) or "forward" (faster).

hessErr

This represents the epsilon when optimizing the Hessian step size using the Shi2021 method.

shi21maxHess

Maximum number of times to optimize the best step size for the hessian calculation

censOption

Treatment of the second derivative for censored (M2/M3/M4/BLQ) observations in the FOCEI family. "gauss" (the default) keeps the historic uncensored Gauss-Newton curvature, matching common PMx tools; "laplace" uses the exact censored second derivative of the objective (a proper Laplace inner Hessian and analytic covariance). Accepted by saemControl/nlmControl for a uniform interface but inert there – SAEM (stochastic EM) has no Laplace inner Hessian, and NLM uses a finite-difference Hessian that already reflects censoring exactly.

eventSens

Controls how dosing/event-parameter ('alag', 'F', 'rate', 'dur') sensitivities are computed for THETA/ETA gradients: ‘"jump"' (default) uses rxode2’s analytic event sensitivities; '"fd"' uses the legacy finite-difference behavior.

sensMethod

Method used to compute the ODE parameter sensitivities. '"forward"' uses the classic variational (forward) sensitivity ODEs; '"default"' is the same thing.

useColor

Logical (or 'NULL') emit ANSI bold/color escapes in the iteration print. 'NULL' (default) defers to [crayon::has_color()].

printNcol

Integer (or 'NULL') parameter columns per row before wrapping. 'NULL' (default) uses 'floor((getOption("width") - 23) / 12)'.

print

Either a scalar print-frequency ('0' = suppress, '1' (default) = every evaluation, 'N' = every Nth), OR a pre-built [iterPrintControl()] object. Equivalent to 'iterPrintControl(every = print, ncol = printNcol, useColor = useColor)'.

normType

Parameter normalization/scaling used to get scaled initial values for scaleType, of the form Vscaled = (Vunscaled-C1)/C2 (see Feature Scaling; rescale2 follows the OptdesX manual): "rescale2" scales all parameters to (-1, 1); "rescale" (min-max) scales to (0, 1); "mean" centers on the mean with range (0, 1); "std" standardizes by mean/sd; "len" scales to unit (Euclidean) length; "constant" performs no normalization (C1=0, C2=1).

scaleType

The scaling scheme for nlmixr2: "nlmixr2" (default) scales as (current-init)*scaleC[i] + scaleTo, with scaleTo from normType and scales from scaleC; "norm" uses the simple scaling from normType; "mult" scales multiplicatively as current/init*scaleTo; "multAdd" scales linearly ((current-init)+scaleTo) for parameters in an exponential block (e.g. exp(theta)) and multiplicatively otherwise.

scaleCmax

Maximum value of the scaleC to prevent overflow.

scaleCmin

Minimum value of the scaleC to prevent underflow.

scaleC

Scaling constant used with scaleType="nlmixr2"; when not specified, chosen by parameter type to keep gradient sizes similar on a log scale: '1' for exp()-transformed/power/boxCox/ yeoJohnson parameters, '0.5*abs(est)' for additive/proportional/ lognormal error parameters, 'abs(1/digamma(est+1))' for factorials, and 'log(abs(est))*abs(est)' for log-scale parameters. May be set explicitly per parameter if these defaults don't apply well.

scaleTo

Scale the initial parameter estimate to this value. By default this is 1. When zero or below, no scaling is performed.

gradTo

this is the factor that the gradient is scaled to before optimizing. This only works with scaleType="nlmixr2".

rxControl

'rxode2' ODE solving options during fitting, created with 'rxControl()'

optExpression

Optimize the rxode2 expression to speed up calculation. By default this is turned on.

sumProd

Is a boolean indicating if the model should change multiplication to high precision multiplication and sums to high precision sums using the PreciseSums package. By default this is FALSE.

literalFix

boolean, substitute fixed population values as literals and re-adjust ui and parameter estimates after optimization; Default is 'TRUE'.

literalFixRes

boolean, substitute fixed population values as literals and re-adjust ui and parameter estimates after optimization; Default is 'TRUE'.

addProp

Type of additive-plus-proportional error: '"combined1"', where standard deviations add:

y = f + (a + b\times f^c) \times \varepsilon

; or '"combined2"', where variances add:

y = f + \sqrt{a^2 + b^2\times f^{2\times c}} \times \varepsilon

. Here y = observed, f = predicted, a = additive sd, b = proportional/power sd, c = power exponent (1 in the proportional case).

calcTables

This boolean is to determine if the foceiFit will calculate tables. By default this is TRUE

compress

Should the object have compressed items

covMethod

"r" uses nlmixr2's 'nlmixr2Hess()' for the hessian, or "nlm" uses the hessian from 'stats::nlm(.., hessian=TRUE)'; defaults to "nlm" when using nlmixr2's hessian/gradient for solving.

adjObf

is a boolean to indicate if the objective function should be adjusted to be closer to NONMEM's default objective function. By default this is TRUE

ci

Confidence level for some tables. By default this is 0.95 or 95% confidence.

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

sigdigTable

Significant digits in the final output table. If not specified, then it matches the significant digits in the 'sigdig' optimization algorithm. If 'sigdig' is NULL, use 3.

boundedTransform

When 'TRUE' (default), bounded parameters are transformed for unbounded optimization methods and back-transformed for final estimates. 'FALSE' optimizes on the original scale with bounds passed to the optimizer. 'NA' transforms for optimization but skips the final back-transform.

...

additional arguments to be passed to f.

Value

nlm control object

Author(s)

Matthew L. Fidler

Examples



# A logit regression example with emax model

dsn <- data.frame(i=1:1000)
dsn$time <- exp(rnorm(1000))
dsn$DV=rbinom(1000,1,exp(-1+dsn$time)/(1+exp(-1+dsn$time)))

mod <- function() {
 ini({
   E0 <- 0.5
   Em <- 0.5
   E50 <- 2
   g <- fix(2)
 })
 model({
   v <- E0+Em*time^g/(E50^g+time^g)
   ll(bin) ~ DV * v - log(1 + exp(v))
 })
}

fit2 <- nlmixr(mod, dsn, est="nlm")

print(fit2)

# you can also get the nlm output with fit2$nlm

fit2$nlm

# The nlm control has been modified slightly to include
# extra components and name the parameters


Recover and finalize the resident nlm parameter history

Description

Returns the parameter history accumulated in the resident nlm scaling struct (one row per iteration type per recorded evaluation) as a data frame, and stops further recording/printing (save and every are reset to 0). Must be called while .nlmSetupEnv() is still loaded – i.e. before .nlmFreeEnv(). Used by .nlmFinalizeList for the standard nlm-family estimators and directly by externally-optimized engines such as babelmixr2's nlmer.

Usage

nlmGetParHist(p = TRUE)

Arguments

p

When TRUE (default) also print the final iteration line.

Details

This is an internal function and should not be called directly.

Value

A data frame of the recorded parameter history.

Author(s)

Matthew L. Fidler


Per-subject prediction and Jacobian for mixed-effects engines

Description

Like the population gradient solver but takes a per-subject nsub x ntheta parameter matrix (phi = beta + b, as supplied by lme4::nlmer) instead of one shared theta. Requires .nlmSetupEnv() to already be loaded.

Usage

nlmerSolveGrad(thetaMat, record = FALSE)

Arguments

thetaMat

A nsub x ntheta matrix of per-subject parameter values. Row id is solved against subject id (in the loaded etTrans order).

record

When TRUE, record this evaluation's population parameter estimate – the per-subject mean of thetaMat's columns (phi = beta + b averaged over subjects, which equals the fixed effect exactly for parameters without a random effect) – into the resident nlm parameter history via the shared scale machinery. This is how an external optimizer (e.g. lme4::nlmer) populates the iteration print and the history recovered by nlmGetParHist(). No objective value is recorded (the scale's showOfv is expected to be 0 for these engines). Defaults to FALSE.

Details

This is an internal function and should not be called directly.

Value

A nobsTot x (ntheta+1) matrix in the loaded (etTrans) observation order: column 1 is the prediction (rx_pred_) and columns 2..(ntheta+1) are d(pred)/d(THETA[i]).

Author(s)

Matthew L. Fidler


nlmixr2 nlminb defaults

Description

nlmixr2 nlminb defaults

Usage

nlminbControl(
  eval.max = 200,
  iter.max = 150,
  trace = 0,
  abs.tol = 0,
  rel.tol = NULL,
  x.tol = NULL,
  xf.tol = 2.2e-14,
  step.min = 1,
  step.max = 1,
  sing.tol = rel.tol,
  scale = 1,
  scale.init = NULL,
  diff.g = NULL,
  rxControl = NULL,
  optExpression = TRUE,
  sumProd = FALSE,
  literalFix = TRUE,
  literalFixRes = TRUE,
  returnNlminb = FALSE,
  solveType = c("hessian", "grad", "fun"),
  stickyRecalcN = 4,
  maxOdeRecalc = 5,
  odeRecalcFactor = 10^(0.5),
  indTolRelax = TRUE,
  eventType = c("central", "forward"),
  shiErr = (.Machine$double.eps)^(1/3),
  shi21maxFD = 20L,
  optimHessType = c("central", "forward"),
  hessErr = (.Machine$double.eps)^(1/3),
  shi21maxHess = 20L,
  useColor = NULL,
  printNcol = NULL,
  print = 1L,
  normType = c("rescale2", "mean", "rescale", "std", "len", "constant"),
  scaleType = c("nlmixr2", "norm", "mult", "multAdd"),
  scaleCmax = 1e+05,
  scaleCmin = 1e-05,
  scaleC = NULL,
  scaleTo = 1,
  gradTo = 1,
  addProp = c("combined2", "combined1"),
  eventSens = c("jump", "fd"),
  sensMethod = c("default", "forward"),
  calcTables = TRUE,
  compress = TRUE,
  covMethod = c("r", "nlminb", ""),
  adjObf = TRUE,
  ci = 0.95,
  sigdig = 3,
  sigdigTable = NULL,
  ...
)

Arguments

eval.max

Maximum number of evaluations of the objective function allowed. Defaults to 200.

iter.max

Maximum number of iterations allowed. Defaults to 150.

trace

The value of the objective function and the parameters is printed every trace'th iteration. When 0 no trace information is to be printed

abs.tol

Absolute tolerance. Defaults to 0 so the absolute convergence test is not used. If the objective function is known to be non-negative, the previous default of '1e-20' would be more appropriate

rel.tol

Relative tolerance. When 'NULL' (default) it is derived from 'sigdig' the way 'foceiControl()' does ('10^(-sigdig)').

x.tol

X tolerance. When 'NULL' (default) it is derived from 'sigdig' ('10^(-sigdig)').

xf.tol

false convergence tolerance. Defaults to '2.2e-14'.

step.min

Minimum step size. Default to '1.'.

step.max

Maximum step size. Default to '1.'.

sing.tol

singular convergence tolerance; defaults to 'rel.tol;.

scale

See PORT documentation (or leave alone).

scale.init

... probably need to check PORT documentation

diff.g

an estimated bound on the relative error in the objective function value

rxControl

'rxode2' ODE solving options during fitting, created with 'rxControl()'

optExpression

Optimize the rxode2 expression to speed up calculation. By default this is turned on.

sumProd

Is a boolean indicating if the model should change multiplication to high precision multiplication and sums to high precision sums using the PreciseSums package. By default this is FALSE.

literalFix

boolean, substitute fixed population values as literals and re-adjust ui and parameter estimates after optimization; Default is 'TRUE'.

literalFixRes

boolean, substitute fixed population values as literals and re-adjust ui and parameter estimates after optimization; Default is 'TRUE'.

returnNlminb

logical; when TRUE this will return the nlminb result instead of the nlmixr2 fit object

solveType

controls whether ‘nlm' uses nlmixr2’s analytical gradients (event-related parameters like lag time/duration/rate/F use Shi2021 finite differences instead): '"hessian"' builds a Hessian from the analytical gradient via finite differences, '"gradient"' supplies the gradient and lets 'nlm' compute the finite-difference Hessian, and '"fun"' lets 'nlm' compute both by finite differences.

stickyRecalcN

The number of bad ODE solves before reducing the atol/rtol for the rest of the problem.

maxOdeRecalc

Maximum number of times to reduce the ODE tolerances and try to resolve the system if there was a bad ODE solve.

odeRecalcFactor

The ODE recalculation factor when ODE solving goes bad, this is the factor the rtol/atol is reduced

indTolRelax

When 'TRUE' (default), only subjects whose ODE solve produced NaN/Inf have their tolerances relaxed, and the relaxed tolerance persists across optimizer calls (sticky). When 'FALSE', all subjects have their tolerances relaxed on each retry and tolerances are reset afterward.

eventType

Event gradient type for dosing events; Can be "central" or "forward"

shiErr

This represents the epsilon when optimizing the ideal step size for numeric differentiation using the Shi2021 method

shi21maxFD

The maximum number of steps for the optimization of the forward difference step size when using dosing events (lag time, modeled duration/rate and bioavailability)

optimHessType

Hessian type for numeric-difference individual Hessians in generalized log-likelihood estimation: "central" (matches R's 'optimHess()', default) or "forward" (faster).

hessErr

This represents the epsilon when optimizing the Hessian step size using the Shi2021 method.

shi21maxHess

Maximum number of times to optimize the best step size for the hessian calculation

useColor

Logical (or 'NULL') emit ANSI bold/color escapes in the iteration print. 'NULL' (default) defers to [crayon::has_color()].

printNcol

Integer (or 'NULL') parameter columns per row before wrapping. 'NULL' (default) uses 'floor((getOption("width") - 23) / 12)'.

print

Either a scalar print-frequency ('0' = suppress, '1' (default) = every evaluation, 'N' = every Nth), OR a pre-built [iterPrintControl()] object. Equivalent to 'iterPrintControl(every = print, ncol = printNcol, useColor = useColor)'.

normType

Parameter normalization/scaling used to get scaled initial values for scaleType, of the form Vscaled = (Vunscaled-C1)/C2 (see Feature Scaling; rescale2 follows the OptdesX manual): "rescale2" scales all parameters to (-1, 1); "rescale" (min-max) scales to (0, 1); "mean" centers on the mean with range (0, 1); "std" standardizes by mean/sd; "len" scales to unit (Euclidean) length; "constant" performs no normalization (C1=0, C2=1).

scaleType

The scaling scheme for nlmixr2: "nlmixr2" (default) scales as (current-init)*scaleC[i] + scaleTo, with scaleTo from normType and scales from scaleC; "norm" uses the simple scaling from normType; "mult" scales multiplicatively as current/init*scaleTo; "multAdd" scales linearly ((current-init)+scaleTo) for parameters in an exponential block (e.g. exp(theta)) and multiplicatively otherwise.

scaleCmax

Maximum value of the scaleC to prevent overflow.

scaleCmin

Minimum value of the scaleC to prevent underflow.

scaleC

Scaling constant used with scaleType="nlmixr2"; when not specified, chosen by parameter type to keep gradient sizes similar on a log scale: '1' for exp()-transformed/power/boxCox/ yeoJohnson parameters, '0.5*abs(est)' for additive/proportional/ lognormal error parameters, 'abs(1/digamma(est+1))' for factorials, and 'log(abs(est))*abs(est)' for log-scale parameters. May be set explicitly per parameter if these defaults don't apply well.

scaleTo

Scale the initial parameter estimate to this value. By default this is 1. When zero or below, no scaling is performed.

gradTo

this is the factor that the gradient is scaled to before optimizing. This only works with scaleType="nlmixr2".

addProp

Type of additive-plus-proportional error: '"combined1"', where standard deviations add:

y = f + (a + b\times f^c) \times \varepsilon

; or '"combined2"', where variances add:

y = f + \sqrt{a^2 + b^2\times f^{2\times c}} \times \varepsilon

. Here y = observed, f = predicted, a = additive sd, b = proportional/power sd, c = power exponent (1 in the proportional case).

eventSens

Controls how dosing/event-parameter ('alag', 'F', 'rate', 'dur') sensitivities are computed for THETA/ETA gradients: ‘"jump"' (default) uses rxode2’s analytic event sensitivities; '"fd"' uses the legacy finite-difference behavior.

sensMethod

Method used to compute the ODE parameter sensitivities. '"forward"' uses the classic variational (forward) sensitivity ODEs; '"default"' is the same thing.

calcTables

This boolean is to determine if the foceiFit will calculate tables. By default this is TRUE

compress

Should the object have compressed items

covMethod

Method for calculating the covariance. "r" (the default) uses nlmixr2's nlmixr2Hess() Hessian; "nlminb" uses the optimizer's own Hessian; "" skips the covariance step.

adjObf

is a boolean to indicate if the objective function should be adjusted to be closer to NONMEM's default objective function. By default this is TRUE

ci

Confidence level for some tables. By default this is 0.95 or 95% confidence.

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

sigdigTable

Significant digits in the final output table. If not specified, then it matches the significant digits in the 'sigdig' optimization algorithm. If 'sigdig' is NULL, use 3.

...

Further arguments to be supplied to objective.

Author(s)

Matthew L. Fidler

Examples


# A logit regression example with emax model

dsn <- data.frame(i=1:1000)
dsn$time <- exp(rnorm(1000))
dsn$DV=rbinom(1000,1,exp(-1+dsn$time)/(1+exp(-1+dsn$time)))

mod <- function() {
 ini({
   E0 <- 0.5
   Em <- 0.5
   E50 <- 2
   g <- fix(2)
 })
 model({
   v <- E0+Em*time^g/(E50^g+time^g)
   ll(bin) ~ DV * v - log(1 + exp(v))
 })
}

fit2 <- nlmixr(mod, dsn, est="nlminb")

print(fit2)

# you can also get the nlm output with fit2$nlminb

fit2$nlminb


nlmixr2 fits population PK and PKPD non-linear mixed effects models.

Description

nlmixr2 is an R package for fitting population pharmacokinetic (PK) and pharmacokinetic-pharmacodynamic (PKPD) models.

Usage

nlmixr2(
  object,
  data,
  est = NULL,
  control = list(),
  table = tableControl(),
  ...,
  save = NULL,
  envir = parent.frame()
)

nlmixr(
  object,
  data,
  est = NULL,
  control = list(),
  table = tableControl(),
  ...,
  save = NULL,
  envir = parent.frame()
)

## S3 method for class ''function''
nlmixr2(
  object,
  data = NULL,
  est = NULL,
  control = NULL,
  table = tableControl(),
  ...,
  save = NULL,
  envir = parent.frame()
)

## S3 method for class 'rxUi'
nlmixr2(
  object,
  data = NULL,
  est = NULL,
  control = NULL,
  table = tableControl(),
  ...,
  save = NULL,
  envir = parent.frame()
)

## S3 method for class 'nlmixr2FitCore'
nlmixr2(
  object,
  data = NULL,
  est = NULL,
  control = NULL,
  table = tableControl(),
  ...,
  save = NULL,
  envir = parent.frame()
)

## S3 method for class 'nlmixr2FitData'
nlmixr2(
  object,
  data = NULL,
  est = NULL,
  control = NULL,
  table = tableControl(),
  ...,
  save = NULL,
  envir = parent.frame()
)

## S3 method for class 'nlmixr2FitCoreSilent'
nlmixr2(
  object,
  data = NULL,
  est = NULL,
  control = NULL,
  table = tableControl(),
  ...,
  save = NULL,
  envir = parent.frame()
)

Arguments

object

Fitted object or function specifying the model.

data

nlmixr data

est

estimation method (all methods are shown by 'nlmixr2AllEst()'). Methods can be added for other tools

control

The estimation control object. These are expected to be different for each type of estimation method

table

The output table control object (like 'tableControl()')

...

Other parameters

save

Boolean to save a nlmixr2 object in a rds file in the working directory. If NULL, uses option "nlmixr2.save"

envir

Environment where the nlmixr object/function is evaluated before running the estimation routine.

Details

The nlmixr2 generalized function allows common access to the nlmixr2 estimation routines.

The nlmixr object has the following fields:

Field Note Description
censInfo Gives the censorng information abot the fit (the type of censoring that was seend and handled in the dataset)
conditionNumber Condition number, that is the highest divided by the lowest eigenvalue in the population covariance matrix
cor Correlation matrix
cov Variance-covariance matrix
covMethod Method used to calculate covariance of the fixed effects
dataLloq Gives the lloq from the dataset (average) when cesoring has occured; Requires the fit to have a table step
dataMergeFull Full data merge with the fit output and the original dataset; Also includes nlmixrLlikObs which includes the individual observation contribution to the likelihood
dataMergeInner Inner data merge with the fit output and the original dataset; Also includes nlmixrLlikObs which includes the individual observation contribution to the likelihood
dataMergeLeft Left data merge with the fit output and the original dataset; Also includes nlmixrLlikObs which includes the individual observation contribution to the likelihood
dataMergeRight Right data merge with the fit output and the original dataset; Also includes nlmixrLlikObs which includes the individual observation contribution to the likelihood
dataUloq Gives the uloq from the dataset (average) when censoring has occured; requires the fit to have a table step
env This is the environment where all the information for the fit is stored outside of the data-frame. It is an R environment hence $env
runInfo This returns a list of all the warnings or fit information
rxControl Integration options used to control rxode2
scaleInfo The scaling factors used for nlmixr2 estimation in focei; The can be changed by foceiControl(scaleC=…) if you think these are unreasonable. It also tells the Gill83 outcome of trying to find the best step size (High gradient error, bad gradient etc)
seed This is the initial seed used for saem
shrink This is a table of shrinkages for all the individual ETAs as well as the variance shrinkage as well as summary statistics for the ETAs and Residual Error
simInfo This returns a list of all the fit information used for a traditional rxode2 simulation, which you can tweak yourself if you wish
table These are the table options that were used when generating the table output (were CWRES included, etc
theta Estimates for eta for each individual
time Duration of different parts of the analysis (e.g. setup, optimization, calculation of covariance, etc.)
ui Final estimates for the model
atol n2r Absolute tolerance that NONMEM specified; will be used when solving
dfObs n2r Degrees of freedom by observation
dfSub n2r Degrees of freedom by subject
etaData n2r Subject level IIV values
ipredAtol n2r Absolute tolerance difference between NONMEM and rxode2 individual predictions
ipredCompare n2r Data frame with ipred values
ipredRtol n2r Relative tolerance difference between NONMEM and rxode2 individual predictions
nonmemData n2r Original dataset used for NONMEM analysis
predAtol n2r Absolute tolerance difference between NONMEM and rxode2 population predictions
predCompare n2r Data frame with pred values
predRtol n2r Relative tolerance difference between NONMEM and rxode2 population predictions
rtol n2r Relative tolerance that NONMEM specified; will be used when solving
sigma n2r Error model matrix
ssAtol n2r Steady state absolute tolerance that NONMEM specified; will be used for solving.
ssRtol n2r Steady state relative tolerance that NONMEM specified will be used for solving
thetaMat n2r Covariance Matrix (matches rxSolve(thetaMat=)

n2r - These fields are added when a NONMEM model is imported using nonmem2rx()

Value

Either a nlmixr2 model or a nlmixr2 fit object

nlmixr modeling mini-language

Rationale

nlmixr estimation routines each have their own way of specifying models. Often the models are specified in ways that are most intuitive for one estimation routine, but do not make sense for another estimation routine. Sometimes, legacy estimation routines like nlme have their own syntax that is outside of the control of the nlmixr package.

The unique syntax of each routine makes the routines themselves easier to maintain and expand, and allows interfacing with existing packages that are outside of nlmixr (like nlme). However, a model definition language that is common between estimation methods, and an output object that is uniform, will make it easier to switch between estimation routines and will facilitate interfacing output with external packages like Xpose.

The nlmixr mini-modeling language, attempts to address this issue by incorporating a common language. This language is inspired by both R and NONMEM, since these languages are familiar to many pharmacometricians.

Initial Estimates and boundaries for population parameters

nlmixr models are contained in a R function with two blocks: ini and model. This R function can be named anything, but is not meant to be called directly from R. In fact if you try you will likely get an error such as Error: could not find function "ini".

The ini model block is meant to hold the initial estimates for the model, and the boundaries of the parameters for estimation routines that support boundaries (note nlmixr's saem and nlme do not currently support parameter boundaries).

To explain how these initial estimates are specified we will start with an annotated example:

f <- function(){ ## Note the arguments to the function are currently
                 ## ignored by nlmixr
    ini({
        ## Initial conditions for population parameters (sometimes
        ## called theta parameters) are defined by either `<-` or '='
        lCl <- 1.6      #log Cl (L/hr)
        ## Note that simple expressions that evaluate to a number are
        ## OK for defining initial conditions (like in R)
        lVc = log(90)  #log V (L)
        ## Also a comment on a parameter is captured as a parameter label
        lKa <- 1 #log Ka (1/hr)
        ## Bounds may be specified by c(lower, est, upper), like NONMEM:
        ## Residuals errors are assumed to be population parameters
        prop.err <- c(0, 0.2, 1)
    })
    ## The model block will be discussed later
    model({})
}

As shown in the above examples:

These parameters can be named almost any R compatible name. Please note that:

Initial Estimates for between subject error distribution (NONMEM's $OMEGA)

In mixture models, multivariate normal individual deviations from the population parameters are estimated (in NONMEM these are called eta parameters). Additionally the variance/covariance matrix of these deviations is also estimated (in NONMEM this is the OMEGA matrix). These also have initial estimates. In nlmixr these are specified by the '~' operator that is typically used in R for "modeled by", and was chosen to distinguish these estimates from the population and residual error parameters.

Continuing the prior example, we can annotate the estimates for the between subject error distribution

f <- function(){
    ini({
        lCl <- 1.6      #log Cl (L/hr)
        lVc = log(90)  #log V (L)
        lKa <- 1 #log Ka (1/hr)
        prop.err <- c(0, 0.2, 1)
        ## Initial estimate for ka IIV variance
        ## Labels work for single parameters
        eta.ka ~ 0.1 # BSV Ka

        ## For correlated parameters, you specify the names of each
        ## correlated parameter separated by a addition operator `+`
        ## and the left handed side specifies the lower triangular
        ## matrix initial of the covariance matrix.
        eta.cl + eta.vc ~ c(0.1,
                            0.005, 0.1)
        ## Note that labels do not currently work for correlated
        ## parameters.  Also do not put comments inside the lower
        ## triangular matrix as this will currently break the model.
    })
    ## The model block will be discussed later
    model({})
}

As shown in the above examples:

Currently the model syntax does not allow comments inside the lower triangular matrix.

Model Syntax for ODE based models (NONMEM's $PK, $PRED, $DES and $ERROR)

Once the initialization block has been defined, you can define a model in terms of the defined variables in the ini block. You can also mix in RxODE blocks into the model.

The current method of defining a nlmixr model is to specify the parameters, and then possibly the RxODE lines:

Continuing describing the syntax with an annotated example:

f <- function(){
    ini({
        lCl <- 1.6      #log Cl (L/hr)
        lVc <- log(90)   #log Vc (L)
        lKA <- 0.1      #log Ka (1/hr)
        prop.err <- c(0, 0.2, 1)
        eta.Cl ~ 0.1 ## BSV Cl
        eta.Vc ~ 0.1 ## BSV Vc
        eta.KA ~ 0.1 ## BSV Ka
    })
    model({
        ## First parameters are defined in terms of the initial estimates
        ## parameter names.
        Cl <- exp(lCl + eta.Cl)
        Vc = exp(lVc + eta.Vc)
        KA <- exp(lKA + eta.KA)
        ## After the differential equations are defined
        kel <- Cl / Vc;
        d/dt(depot)    = -KA*depot;
        d/dt(centr)  =  KA*depot-kel*centr;
        ## And the concentration is then calculated
        cp = centr / Vc;
        ## Last, nlmixr is told that the plasma concentration follows
        ## a proportional error (estimated by the parameter prop.err)
        cp ~ prop(prop.err)
    })
}

A few points to note:

Model Syntax for solved PK systems

Solved PK systems are also currently supported by nlmixr with the 'linCmt()' pseudo-function. An annotated example of a solved system is below:

##'

f <- function(){
    ini({
        lCl <- 1.6      #log Cl (L/hr)
        lVc <- log(90)   #log Vc (L)
        lKA <- 0.1      #log Ka (1/hr)
        prop.err <- c(0, 0.2, 1)
        eta.Cl ~ 0.1 ## BSV Cl
        eta.Vc ~ 0.1 ## BSV Vc
        eta.KA ~ 0.1 ## BSV Ka
    })
    model({
        Cl <- exp(lCl + eta.Cl)
        Vc = exp(lVc + eta.Vc)
        KA <- exp(lKA + eta.KA)
        ## Instead of specifying the ODEs, you can use
        ## the linCmt() function to use the solved system.
        ##
        ## This function determines the type of PK solved system
        ## to use by the parameters that are defined.  In this case
        ## it knows that this is a one-compartment model with first-order
        ## absorption.
        linCmt() ~ prop(prop.err)
    })
}

A few things to keep in mind:

Checking model syntax

After specifying the model syntax you can check that nlmixr is interpreting it correctly by using the nlmixr function on it.

Using the above function we can get:

> nlmixr(f)
## 1-compartment model with first-order absorption in terms of Cl
## Initialization:
################################################################################
Fixed Effects ($theta):
    lCl     lVc     lKA
1.60000 4.49981 0.10000

Omega ($omega):
     [,1] [,2] [,3]
[1,]  0.1  0.0  0.0
[2,]  0.0  0.1  0.0
[3,]  0.0  0.0  0.1

## Model:
################################################################################
Cl <- exp(lCl + eta.Cl)
Vc = exp(lVc + eta.Vc)
KA <- exp(lKA + eta.KA)
## Instead of specifying the ODEs, you can use
## the linCmt() function to use the solved system.
##
## This function determines the type of PK solved system
## to use by the parameters that are defined.  In this case
## it knows that this is a one-compartment model with first-order
## absorption.
linCmt() ~ prop(prop.err)

In general this gives you information about the model (what type of solved system/RxODE), initial estimates as well as the code for the model block.

Using the model syntax for estimating a model

Once the model function has been created, you can use it and a dataset to estimate the parameters for a model given a dataset.

This dataset has to have RxODE compatible events IDs. Both Monolix and NONMEM use a a very similar standard to what nlmixr can support.

Once the data has been converted to the appropriate format, you can use the nlmixr function to run the appropriate code.

The method to estimate the model is:

fit <- nlmixr(model.function, dataset, est="est", control=estControl(options))

Currently nlme and saem are implemented. For example, to run the above model with saem, we could have the following:

> f <- function(){
    ini({
        lCl <- 1.6      #log Cl (L/hr)
        lVc <- log(90)   #log Vc (L)
        lKA <- 0.1      #log Ka (1/hr)
        prop.err <- c(0, 0.2, 1)
        eta.Cl ~ 0.1 ## BSV Cl
        eta.Vc ~ 0.1 ## BSV Vc
        eta.KA ~ 0.1 ## BSV Ka
    })
    model({
        ## First parameters are defined in terms of the initial estimates
        ## parameter names.
        Cl <- exp(lCl + eta.Cl)
        Vc = exp(lVc + eta.Vc)
        KA <- exp(lKA + eta.KA)
        ## After the differential equations are defined
        kel <- Cl / Vc;
        d/dt(depot)    = -KA*depot;
        d/dt(centr)  =  KA*depot-kel*centr;
        ## And the concentration is then calculated
        cp = centr / Vc;
        ## Last, nlmixr is told that the plasma concentration follows
        ## a proportional error (estimated by the parameter prop.err)
        cp ~ prop(prop.err)
    })
}
> fit.s <- nlmixr(f,d,est="saem",control=saemControl(n.burn=50,n.em=100,print=50));
Compiling RxODE differential equations...done.
c:/Rtools/mingw_64/bin/g++  -I"c:/R/R-34~1.1/include" -DNDEBUG     -I"d:/Compiler/gcc-4.9.3/local330/include"  -Ic:/nlmixr/inst/include -Ic:/R/R-34~1.1/library/STANHE~1/include -Ic:/R/R-34~1.1/library/Rcpp/include -Ic:/R/R-34~1.1/library/RCPPAR~1/include -Ic:/R/R-34~1.1/library/RCPPEI~1/include -Ic:/R/R-34~1.1/library/BH/include   -O2 -Wall  -mtune=core2 -c saem3090757b4bd1x64.cpp -o saem3090757b4bd1x64.o
In file included from c:/R/R-34~1.1/library/RCPPAR~1/include/armadillo:52:0,
                 from c:/R/R-34~1.1/library/RCPPAR~1/include/RcppArmadilloForward.h:46,
                 from c:/R/R-34~1.1/library/RCPPAR~1/include/RcppArmadillo.h:31,
                 from saem3090757b4bd1x64.cpp:1:
c:/R/R-34~1.1/library/RCPPAR~1/include/armadillo_bits/compiler_setup.hpp:474:96: note: #pragma message: WARNING: use of OpenMP disabled; this compiler doesn't support OpenMP 3.0+
   #pragma message ("WARNING: use of OpenMP disabled; this compiler doesn't support OpenMP 3.0+")
                                                                                                ^
c:/Rtools/mingw_64/bin/g++ -shared -s -static-libgcc -o saem3090757b4bd1x64.dll tmp.def saem3090757b4bd1x64.o c:/nlmixr/R/rx_855815def56a50f0e7a80e48811d947c_x64.dll -Lc:/R/R-34~1.1/bin/x64 -lRblas -Lc:/R/R-34~1.1/bin/x64 -lRlapack -lgfortran -lm -lquadmath -Ld:/Compiler/gcc-4.9.3/local330/lib/x64 -Ld:/Compiler/gcc-4.9.3/local330/lib -Lc:/R/R-34~1.1/bin/x64 -lR
done.
1:    1.8174   4.6328   0.0553   0.0950   0.0950   0.0950   0.6357
50:    1.3900   4.2039   0.0001   0.0679   0.0784   0.1082   0.1992
100:    1.3894   4.2054   0.0107   0.0686   0.0777   0.1111   0.1981
150:    1.3885   4.2041   0.0089   0.0683   0.0778   0.1117   0.1980
Using sympy via SnakeCharmR
## Calculate ETA-based prediction and error derivatives:
Calculate Jacobian...................done.
Calculate sensitivities.......
done.
## Calculate d(f)/d(eta)
## ...
## done
## ...
## done
The model-based sensitivities have been calculated
Calculating Table Variables...
done

The options for saem are controlled by saemControl. You may wish to make sure the minimization is complete in the case of saem. You can do that with traceplot which shows the iteration history with the divided by burn-in and EM phases. In this case, the burn in seems reasonable; you may wish to increase the number of iterations in the EM phase of the estimation. Overall it is probably a semi-reasonable solution.

nlmixr output objects

In addition to unifying the modeling language sent to each of the estimation routines, the outputs currently have a unified structure.

You can see the fit object by typing the object name:

> fit.s
 -- nlmixr SAEM fit (ODE); OBJF calculated from FOCEi approximation -------------
      OBJF      AIC      BIC Log-likelihood Condition Number
  62337.09 62351.09 62399.01      -31168.55          82.6086

 -- Time (sec; fit.s$time): -----------------------------------------------------
           saem setup Likelihood Calculation covariance table
 elapsed 430.25 31.64                   1.19          0  3.44

 -- Parameters (fit.s$par.fixed): -----------------------------------------------
              Parameter Estimate     SE  
 lCl      log Cl (L/hr)     1.39 0.0240  1.73       4.01 (3.83, 4.20)    26.6
 lVc         log Vc (L)     4.20 0.0256 0.608       67.0 (63.7, 70.4)    28.5
 lKA      log Ka (1/hr)  0.00924 0.0323  349.      1.01 (0.947, 1.08)    34.3
 prop.err      prop.err    0.198                             19.8
          Shrink(SD)
 lCl          0.248
 lVc           1.09
 lKA           4.19
 prop.err      1.81

   No correlations in between subject variability (BSV) matrix
   Full BSV covariance (fit.s$omega) or correlation (fit.s$omega.R; diagonals=SDs)
   Distribution stats (mean/skewness/kurtosis/p-value) available in fit.s$shrink

 -- Fit Data (object fit.s is a modified data.frame): ---------------------------
 # A tibble: 6,947 x 22
   ID     TIME    DV  PRED    RES    WRES IPRED  IRES  IWRES CPRED   CRES
 * <fct> <dbl> <dbl> <dbl>  <dbl>   <dbl> <dbl> <dbl>  <dbl> <dbl>  <dbl>
 1 1      0.25  205.  198.   6.60  0.0741  189.  16.2  0.434  198.   6.78
 2 1      0.5   311.  349. -38.7  -0.261   330. -19.0 -0.291  349. -38.3
 3 1      0.75  389.  464. -74.5  -0.398   434. -45.2 -0.526  463. -73.9
 # ... with 6,944 more rows, and 11 more variables: CWRES <dbl>, eta.Cl <dbl>,
 #   eta.Vc <dbl>, eta.KA <dbl>, depot <dbl>, centr <dbl>, Cl <dbl>, Vc <dbl>,
 #   KA <dbl>, kel <dbl>, cp <dbl>

This example shows what is typical printout of a nlmixr fit object. The elements of the fit are:

In addition to the above properties of the fit object, there are a few additional that may be helpful for the modeler:

Author(s)

Matthew L. Fidler

Examples




one.cmt <- function() {
 ini({
   ## You may label each parameter with a comment
   tka <- 0.45 # Ka
   tcl <- log(c(0, 2.7, 100)) # Log Cl
   ## This works with interactive models
   ## You may also label the preceding line with label("label text")
   tv <- 3.45; label("log V")
   ## the label("Label name") works with all models
   eta.ka ~ 0.6
   eta.cl ~ 0.3
   eta.v ~ 0.1
   add.sd <- 0.7
   prop.sd <- 0.01
 })
 model({
   ka <- exp(tka + eta.ka)
   cl <- exp(tcl + eta.cl)
   v <- exp(tv + eta.v)
   linCmt() ~ add(add.sd) + prop(prop.sd)
 })
}

# fitF <- nlmixr(one.cmt, theo_sd, "focei")

fitS <- nlmixr(one.cmt, theo_sd, "saem")




Show all the current estimation methods

Description

Show all the current estimation methods

Usage

nlmixr2AllEst()

Value

List of supported nlmixr2 estimation options (est=...)

Examples

nlmixr2AllEst()

Tagged list of the available nlmixr2 estimation methods

Description

Returns the built-in (and any attribute-tagged third-party) 'est=' methods grouped by their estimation category, as used when an unsupported method is requested.

Usage

nlmixr2AllEstType()

Value

data.frame with columns 'est', 'type' and 'description'

Examples

nlmixr2AllEstType()

Augmented Prediction for nlmixr2 fit

Description

Augmented Prediction for nlmixr2 fit

Usage

nlmixr2AugPredSolve(
  fit,
  covsInterpolation = c("locf", "nocb", "linear", "midpoint"),
  minimum = NULL,
  maximum = NULL,
  length.out = 51L,
  ...
)

## S3 method for class 'nlmixr2FitData'
augPred(
  object,
  primary = NULL,
  minimum = NULL,
  maximum = NULL,
  length.out = 51,
  ...
)

Arguments

fit

Nlmixr2 fit object

covsInterpolation

specifies the interpolation method for time-varying covariates. When solving ODEs it often samples times outside the sampling time specified in events. When this happens, the time varying covariates are interpolated. Currently this can be:

  • "linear" interpolation, which interpolates the covariate by solving the line between the observed covariates and extrapolating the new covariate value.

  • "locf" – Last observation carried forward (the default).

  • "nocb" – Next Observation Carried Backward. This is the same method that NONMEM uses.

  • "midpoint" Last observation carried forward to midpoint; Next observation carried backward to midpoint.

    For time-varying covariates where a missing value is present, the interpolation method will use either "locf" or "nocb" throughout if they are the type of covariate interpolation that is selected.

    When using the linear or midpoint interpolation, the lower point in the interpolation will use locf to interpolate missing covariates and the upper point will use the nocb to interpolate missing covariates.

minimum

an optional lower limit for the primary covariate. Defaults to min(primary).

maximum

an optional upper limit for the primary covariate. Defaults to max(primary).

length.out

an optional integer with the number of primary covariate values at which to evaluate the predictions. Defaults to 51.

...

some methods for the generic may require additional arguments.

object

a fitted model object from which predictions can be extracted, using a predict method.

primary

an optional one-sided formula specifying the primary covariate to be used to generate the augmented predictions. By default, if a covariate can be extracted from the data used to generate object (using getCovariate), it will be used as primary.

Value

Stacked data.frame with observations, individual/population predictions.

Author(s)

Matthew L. Fidler


Create nlmixr output from the UI

Description

Create nlmixr output from the UI

Usage

nlmixr2CreateOutputFromUi(
  ui,
  data = NULL,
  control = NULL,
  table = NULL,
  env = NULL,
  est = "none"
)

Arguments

ui

This is the UI that will be used for the translation

data

This has the data

control

focei control for data creation

table

Table options

env

Environment setup which needs the following: - '$table' for table options - '$origData' – Original Data - '$dataSav' – Processed data from .foceiPreProcessData - '$idLvl' – Level information for ID factor added - '$covLvl' – Level information for items to convert to factor - '$ui' for ui object - '$fullTheta' Full theta information - '$etaObf' data frame with ID, etas and OBJI - '$cov' For covariance - '$covMethod' for the method of calculating the covariance - '$adjObf' Should the objective function value be adjusted - '$objective' objective function value - '$extra' Extra print information - '$method' Estimation method (for printing) - '$omega' Omega matrix - '$theta' Is a theta data frame - '$model' a list of model information for table generation. Needs a 'predOnly' model - '$message' Message for display - '$est' estimation method - '$ofvType' (optional) tells the type of ofv is currently being use

There are some more details that need to be described here

est

Estimation method

Value

nlmixr fit object

Author(s)

Matthew L. Fidler


Generic for nlmixr2 estimation methods

Description

Generic for nlmixr2 estimation methods

Usage

## S3 method for class 'agq'
nlmixr2Est(env, ...)

## S3 method for class 'bobyqa'
nlmixr2Est(env, ...)

## S3 method for class 'emvi'
nlmixr2Est(env, ...)

## S3 method for class 'fbvi'
nlmixr2Est(env, ...)

## S3 method for class 'fo'
nlmixr2Est(env, ...)

## S3 method for class 'foce'
nlmixr2Est(env, ...)

## S3 method for class 'focei'
nlmixr2Est(env, ...)

## S3 method for class 'output'
nlmixr2Est(env, ...)

## S3 method for class 'foceif'
nlmixr2Est(env, ...)

## S3 method for class 'focef'
nlmixr2Est(env, ...)

## S3 method for class 'focepf'
nlmixr2Est(env, ...)

## S3 method for class 'mfoceif'
nlmixr2Est(env, ...)

## S3 method for class 'mfocef'
nlmixr2Est(env, ...)

## S3 method for class 'mfocepf'
nlmixr2Est(env, ...)

## S3 method for class 'ifoceif'
nlmixr2Est(env, ...)

## S3 method for class 'ifocef'
nlmixr2Est(env, ...)

## S3 method for class 'ifocepf'
nlmixr2Est(env, ...)

## S3 method for class 'agqf'
nlmixr2Est(env, ...)

## S3 method for class 'magqf'
nlmixr2Est(env, ...)

## S3 method for class 'iagqf'
nlmixr2Est(env, ...)

## S3 method for class 'focep'
nlmixr2Est(env, ...)

## S3 method for class 'foi'
nlmixr2Est(env, ...)

## S3 method for class 'iagq'
nlmixr2Est(env, ...)

## S3 method for class 'ifoce'
nlmixr2Est(env, ...)

## S3 method for class 'ifocei'
nlmixr2Est(env, ...)

## S3 method for class 'ifocep'
nlmixr2Est(env, ...)

## S3 method for class 'ilaplace'
nlmixr2Est(env, ...)

## S3 method for class 'imp'
nlmixr2Est(env, ...)

## S3 method for class 'impmap'
nlmixr2Est(env, ...)

## S3 method for class 'laplace'
nlmixr2Est(env, ...)

## S3 method for class 'lbfgsb3c'
nlmixr2Est(env, ...)

## S3 method for class 'magq'
nlmixr2Est(env, ...)

## S3 method for class 'mfoce'
nlmixr2Est(env, ...)

## S3 method for class 'mfocei'
nlmixr2Est(env, ...)

## S3 method for class 'mfocep'
nlmixr2Est(env, ...)

## S3 method for class 'mlaplace'
nlmixr2Est(env, ...)

## S3 method for class 'n1qn1'
nlmixr2Est(env, ...)

## S3 method for class 'newuoa'
nlmixr2Est(env, ...)

## S3 method for class 'nlm'
nlmixr2Est(env, ...)

## S3 method for class 'nlme'
nlmixr2Est(env, ...)

## S3 method for class 'nlminb'
nlmixr2Est(env, ...)

nlmixr2Est(env, ...)

## Default S3 method:
nlmixr2Est(env, ...)

## S3 method for class 'nls'
nlmixr2Est(env, ...)

## S3 method for class 'npag'
nlmixr2Est(env, ...)

## S3 method for class 'mnpag'
nlmixr2Est(env, ...)

## S3 method for class 'inpag'
nlmixr2Est(env, ...)

## S3 method for class 'npb'
nlmixr2Est(env, ...)

## S3 method for class 'mnpb'
nlmixr2Est(env, ...)

## S3 method for class 'inpb'
nlmixr2Est(env, ...)

## S3 method for class 'optim'
nlmixr2Est(env, ...)

## S3 method for class 'neldermead'
nlmixr2Est(env, ...)

## S3 method for class 'bfgs'
nlmixr2Est(env, ...)

## S3 method for class 'cg'
nlmixr2Est(env, ...)

## S3 method for class 'lbfgsb'
nlmixr2Est(env, ...)

## S3 method for class 'sann'
nlmixr2Est(env, ...)

## S3 method for class 'brent'
nlmixr2Est(env, ...)

## S3 method for class 'posthoc'
nlmixr2Est(env, ...)

## S3 method for class 'qrpem'
nlmixr2Est(env, ...)

## S3 method for class 'rxSolve'
nlmixr2Est(env, ...)

## S3 method for class 'simulate'
nlmixr2Est(env, ...)

## S3 method for class 'simulation'
nlmixr2Est(env, ...)

## S3 method for class 'predict'
nlmixr2Est(env, ...)

## S3 method for class 'saem'
nlmixr2Est(env, ...)

## S3 method for class 'uobyqa'
nlmixr2Est(env, ...)

## S3 method for class 'vae'
nlmixr2Est(env, ...)

Arguments

env

Environment for the nlmixr2 estimation routines.

This needs to have:

- rxode2 ui object in '$ui'

- data to fit in the estimation routine in '$data'

- control for the estimation routine's control options in '$ui'

...

Other arguments provided to 'nlmixr2Est()' provided for flexibility but not currently used inside nlmixr

Details

This is a S3 generic that allows others to use the nlmixr2 environment to do their own estimation routines

Value

nlmixr2 fit object

Author(s)

Matthew Fidler


Create a gradient function based on gill numerical differences

Description

Create a gradient function based on gill numerical differences

Usage

nlmixr2Eval_(theta, md5)

nlmixr2Unscaled_(theta, md5)

nlmixr2Grad_(theta, md5)

nlmixr2ParHist_(md5)

nlmixr2GradFun(
  what,
  envir = parent.frame(),
  which,
  thetaNames,
  gillRtol = sqrt(.Machine$double.eps),
  gillK = 10L,
  gillStep = 2,
  gillFtol = 0,
  useColor = crayon::has_color(),
  printNcol = floor((getOption("width") - 23)/12),
  print = 1
)

Arguments

theta

for the internal functions theta is the parameter values

md5

the md5 identifier for the internal gradient function information.

what

either a function or a non-empty character string naming the function to be called.

envir

an environment within which to evaluate the call. This will be most useful if what is a character string and the arguments are symbols or quoted expressions.

which

Which parameters to calculate the forward difference and optimal forward difference interval

thetaNames

Names for the theta parameters

gillRtol

The relative tolerance used for Gill 1983 determination of optimal step size.

gillK

Max steps to determine the optimal forward/central difference step size per parameter (Gill 1983). '0' = no optimal step size determined.

gillStep

When looking for the optimal forward difference step size, this is This is the step size to increase the initial estimate by. So each iteration the new step size = (prior step size)*gillStep

gillFtol

The gillFtol is the gradient error tolerance that is acceptable before issuing a warning/error about the gradient estimates.

useColor

Logical (or 'NULL') emit ANSI bold/color escapes in the iteration print. 'NULL' (default) defers to [crayon::has_color()].

printNcol

Integer (or 'NULL') parameter columns per row before wrapping. 'NULL' (default) uses 'floor((getOption("width") - 23) / 12)'.

print

Either a scalar print-frequency ('0' = suppress, '1' (default) = every evaluation, 'N' = every Nth), OR a pre-built [iterPrintControl()] object. Equivalent to 'iterPrintControl(every = print, ncol = printNcol, useColor = useColor)'.

Value

A list with 'eval', 'grad', 'hist' and 'unscaled' functions. This is an internal module used with dynmodel

Examples


func0 <- function(x){ sum(sin(x))  }

## This will printout every interation or when print=X
gf <- nlmixr2GradFun(func0)

## x
x <- (0:10)*2*pi/10;
gf$eval(x)
gf$grad(x)

## x2
x2 <- x+0.1
gf$eval(x2)
gf$grad(x2)

## Gives the parameter history as a data frame
gf$hist()


Get the optimal forward difference interval by Gill83 method

Description

Get the optimal forward difference interval by Gill83 method

Usage

nlmixr2Gill83(
  what,
  args,
  envir = parent.frame(),
  which,
  gillRtol = sqrt(.Machine$double.eps),
  gillK = 10L,
  gillStep = 2,
  gillFtol = 0
)

Arguments

what

either a function or a non-empty character string naming the function to be called.

args

a list of arguments to the function call. The names attribute of args gives the argument names.

envir

an environment within which to evaluate the call. This will be most useful if what is a character string and the arguments are symbols or quoted expressions.

which

Which parameters to calculate the forward difference and optimal forward difference interval

gillRtol

The relative tolerance used for Gill 1983 determination of optimal step size.

gillK

Max steps to determine the optimal forward/central difference step size per parameter (Gill 1983). '0' = no optimal step size determined.

gillStep

When looking for the optimal forward difference step size, this is This is the step size to increase the initial estimate by. So each iteration the new step size = (prior step size)*gillStep

gillFtol

The gillFtol is the gradient error tolerance that is acceptable before issuing a warning/error about the gradient estimates.

Value

A data frame with the following columns:

- info Gradient evaluation/forward difference information

- hf Forward difference final estimate

- df Derivative estimate

- df2 2nd Derivative Estimate

- err Error of the final estimate derivative

- aEps Absolute difference for forward numerical differences

- rEps Relative Difference for backward numerical differences

- aEpsC Absolute difference for central numerical differences

- rEpsC Relative difference for central numerical differences

The info returns one of the following:

- "Not Assessed" Gradient wasn't assessed

- "Good Success" in Estimating optimal forward difference interval

- "High Grad Error" Large error; Derivative estimate error fTol or more of the derivative

- "Constant Grad" Function constant or nearly constant for this parameter

- "Odd/Linear Grad" Function odd or nearly linear, df = K, df2 ~ 0

- "Grad changes quickly" df2 increases rapidly as h decreases

Author(s)

Matthew Fidler

Examples


## These are taken from the numDeriv's grad examples to show how
## simple gradients are assessed with nlmixr2Gill83

nlmixr2Gill83(sin, pi)

nlmixr2Gill83(sin, (0:10)*2*pi/10)

func0 <- function(x){ sum(sin(x))  }
nlmixr2Gill83(func0 , (0:10)*2*pi/10)

func1 <- function(x){ sin(10*x) - exp(-x) }
curve(func1,from=0,to=5)

x <- 2.04
numd1 <- nlmixr2Gill83(func1, x)
exact <- 10*cos(10*x) + exp(-x)
c(numd1$df, exact, (numd1$df - exact)/exact)

x <- c(1:10)
numd1 <- nlmixr2Gill83(func1, x)
exact <- 10*cos(10*x) + exp(-x)
cbind(numd1=numd1$df, exact, err=(numd1$df - exact)/exact)

sc2.f <- function(x){
  n <- length(x)
   sum((1:n) * (exp(x) - x)) / n
}

sc2.g <- function(x){
  n <- length(x)
  (1:n) * (exp(x) - 1) / n
}

x0 <- rnorm(100)
exact <- sc2.g(x0)

g <- nlmixr2Gill83(sc2.f, x0)

max(abs(exact - g$df)/(1 + abs(exact)))


Calculate Hessian

Description

Unlike 'stats::optimHess' which assumes the gradient is accurate, nlmixr2Hess does not make as strong an assumption that the gradient is accurate but takes more function evaluations to calculate the Hessian. In addition, this procedures optimizes the forward difference interval by nlmixr2Gill83

Usage

nlmixr2Hess(par, fn, ..., envir = parent.frame())

Arguments

par

Initial values for the parameters to be optimized over.

fn

A function to be minimized (or maximized), with first argument the vector of parameters over which minimization is to take place. It should return a scalar result.

...

Extra arguments sent to nlmixr2Gill83

envir

an environment within which to evaluate the call. This will be most useful if what is a character string and the arguments are symbols or quoted expressions.

Details

If you have an analytical gradient function, you should use 'stats::optimHess'

Value

Hessian matrix based on Gill83

Author(s)

Matthew Fidler

See Also

nlmixr2Gill83, optimHess

Examples

 func0 <- function(x){ sum(sin(x))  }
 x <- (0:10)*2*pi/10
 nlmixr2Hess(x, func0)

fr <- function(x) {   ## Rosenbrock Banana function
    x1 <- x[1]
    x2 <- x[2]
    100 * (x2 - x1 * x1)^2 + (1 - x1)^2
}
grr <- function(x) { ## Gradient of 'fr'
    x1 <- x[1]
    x2 <- x[2]
    c(-400 * x1 * (x2 - x1 * x1) - 2 * (1 - x1),
       200 *      (x2 - x1 * x1))
}

h1 <- optimHess(c(1.2,1.2), fr, grr)

h2 <- optimHess(c(1.2,1.2), fr)

## in this case h3 is closer to h1 where the gradient is known

h3 <- nlmixr2Hess(c(1.2,1.2), fr)

A list and description of the fields in the nlmxir2 object

Description

A list and description of the fields in the nlmxir2 object

Usage

nlmixr2Keywords

Format

A data frame with 2 columns and 40 or more rows

Field

Name of the field in the nlmixr2 object

Note

Note regarding the source of the field

Description

Description of the information in the field


Description

Messages the nlmixr2 logo...

Usage

nlmixr2Logo(str = "", version = sessionInfo()$otherPkgs$nlmixr2$Version)

Arguments

str

String to print

version

Version information (by default use package version)

Value

nothing; Called to display version information

Author(s)

Matthew L. Fidler


Control Values for nlme Fit with extra options for nlmixr

Description

The values supplied in the function call replace the defaults and a list with all possible arguments is returned. The returned list is used as the 'control' argument to the 'nlme' function.

Usage

nlmixr2NlmeControl(
  maxIter = 100,
  pnlsMaxIter = 100,
  msMaxIter = 100,
  minScale = 0.001,
  tolerance = NULL,
  niterEM = 25,
  pnlsTol = NULL,
  msTol = NULL,
  returnObject = FALSE,
  msVerbose = FALSE,
  msWarnNoConv = TRUE,
  gradHess = TRUE,
  apVar = TRUE,
  .relStep = .Machine$double.eps^(1/3),
  minAbsParApVar = 0.05,
  opt = c("nlminb", "nlm"),
  natural = TRUE,
  sigma = NULL,
  optExpression = TRUE,
  literalFix = TRUE,
  sumProd = FALSE,
  rxControl = NULL,
  method = c("ML", "REML"),
  random = NULL,
  fixed = NULL,
  weights = NULL,
  verbose = TRUE,
  returnNlme = FALSE,
  addProp = c("combined2", "combined1"),
  calcTables = TRUE,
  compress = TRUE,
  adjObf = TRUE,
  ci = 0.95,
  sigdig = 3,
  sigdigTable = NULL,
  muRefCovAlg = TRUE,
  eventSens = c("jump", "fd"),
  print = NULL,
  covMethod = c("nlme", "analytic", "r,s", "r", "s", "sa", "imp", ""),
  ...
)

nlmeControl(
  maxIter = 100,
  pnlsMaxIter = 100,
  msMaxIter = 100,
  minScale = 0.001,
  tolerance = NULL,
  niterEM = 25,
  pnlsTol = NULL,
  msTol = NULL,
  returnObject = FALSE,
  msVerbose = FALSE,
  msWarnNoConv = TRUE,
  gradHess = TRUE,
  apVar = TRUE,
  .relStep = .Machine$double.eps^(1/3),
  minAbsParApVar = 0.05,
  opt = c("nlminb", "nlm"),
  natural = TRUE,
  sigma = NULL,
  optExpression = TRUE,
  literalFix = TRUE,
  sumProd = FALSE,
  rxControl = NULL,
  method = c("ML", "REML"),
  random = NULL,
  fixed = NULL,
  weights = NULL,
  verbose = TRUE,
  returnNlme = FALSE,
  addProp = c("combined2", "combined1"),
  calcTables = TRUE,
  compress = TRUE,
  adjObf = TRUE,
  ci = 0.95,
  sigdig = 3,
  sigdigTable = NULL,
  muRefCovAlg = TRUE,
  eventSens = c("jump", "fd"),
  print = NULL,
  covMethod = c("nlme", "analytic", "r,s", "r", "s", "sa", "imp", ""),
  ...
)

Arguments

maxIter

maximum number of iterations for the nlme optimization algorithm. Default is 50.

pnlsMaxIter

maximum number of iterations for the PNLS optimization step inside the nlme optimization. Default is 7.

msMaxIter

maximum number of iterations for nlminb (iter.max) or the nlm (iterlim, from the 10-th step) optimization step inside the nlme optimization. Default is 50 (which may be too small for e.g. for overparametrized cases).

minScale

minimum factor by which to shrink the default step size in an attempt to decrease the sum of squares in the PNLS step. Default 0.001.

tolerance

tolerance for the convergence criterion in the nlme algorithm. Default is 1e-6.

niterEM

number of iterations for the EM algorithm used to refine the initial estimates of the random effects variance-covariance coefficients. Default is 25.

pnlsTol

tolerance for the convergence criterion in PNLS step. Default is 1e-3.

msTol

tolerance for the convergence criterion in nlm, passed as the gradtol argument to the function (see documentation on nlm). Default is 1e-7.

returnObject

a logical value indicating whether the fitted object should be returned when the maximum number of iterations is reached without convergence of the algorithm. Default is FALSE.

msVerbose

a logical value passed as the trace to nlminb(.., control= list(trace = *, ..)) or as argument print.level to nlm(). Default is FALSE.

msWarnNoConv

logical indicating if a warning should be signalled whenever the minimization (by opt) in the LME step does not converge; defaults to TRUE.

gradHess

a logical value indicating whether numerical gradient vectors and Hessian matrices of the log-likelihood function should be used in the nlm optimization. This option is only available when the correlation structure (corStruct) and the variance function structure (varFunc) have no "varying" parameters and the pdMat classes used in the random effects structure are pdSymm (general positive-definite), pdDiag (diagonal), pdIdent (multiple of the identity), or pdCompSymm (compound symmetry). Default is TRUE.

apVar

a logical value indicating whether the approximate covariance matrix of the variance-covariance parameters should be calculated. Default is TRUE.

.relStep

relative step for numerical derivatives calculations. Default is .Machine$double.eps^(1/3).

minAbsParApVar

numeric value - minimum absolute parameter value in the approximate variance calculation. The default is 0.05.

opt

the optimizer to be used, either "nlminb" (the default) or "nlm".

natural

a logical value indicating whether the pdNatural parametrization should be used for general positive-definite matrices (pdSymm) in reStruct, when the approximate covariance matrix of the estimators is calculated. Default is TRUE.

sigma

optionally a positive number to fix the residual error at. If NULL, as by default, or 0, sigma is estimated.

optExpression

Optimize the rxode2 expression to speed up calculation. By default this is turned on.

literalFix

boolean, substitute fixed population values as literals and re-adjust ui and parameter estimates after optimization; Default is 'TRUE'.

sumProd

Is a boolean indicating if the model should change multiplication to high precision multiplication and sums to high precision sums using the PreciseSums package. By default this is FALSE.

rxControl

'rxode2' ODE solving options during fitting, created with 'rxControl()'

method

a character string. If "REML" the model is fit by maximizing the restricted log-likelihood. If "ML" the log-likelihood is maximized. Defaults to "ML".

random

optionally, any of the following: (i) a two-sided formula of the form r1+...+rn~x1+...+xm | g1/.../gQ, with r1,...,rn naming parameters included on the right hand side of model, x1+...+xm specifying the random-effects model for these parameters and g1/.../gQ the grouping structure (Q may be equal to 1, in which case no / is required). The random effects formula will be repeated for all levels of grouping, in the case of multiple levels of grouping; (ii) a two-sided formula of the form r1+...+rn~x1+..+xm, a list of two-sided formulas of the form r1~x1+...+xm, with possibly different random-effects models for different parameters, a pdMat object with a two-sided formula, or list of two-sided formulas (i.e. a non-NULL value for formula(random)), or a list of pdMat objects with two-sided formulas, or lists of two-sided formulas. In this case, the grouping structure formula will be given in groups, or derived from the data used to fit the nonlinear mixed-effects model, which should inherit from class groupedData,; (iii) a named list of formulas, lists of formulas, or pdMat objects as in (ii), with the grouping factors as names. The order of nesting will be assumed the same as the order of the order of the elements in the list; (iv) an reStruct object. See the documentation on pdClasses for a description of the available pdMat classes. Defaults to fixed, resulting in all fixed effects having also random effects.

fixed

a two-sided linear formula of the form f1+...+fn~x1+...+xm, or a list of two-sided formulas of the form f1~x1+...+xm, with possibly different models for different parameters. The f1,...,fn are the names of parameters included on the right hand side of model and the x1+...+xm expressions define linear models for these parameters (when the left hand side of the formula contains several parameters, they all are assumed to follow the same linear model, described by the right hand side expression). A 1 on the right hand side of the formula(s) indicates a single fixed effects for the corresponding parameter(s).

weights

an optional varFunc object or one-sided formula describing the within-group heteroscedasticity structure. If given as a formula, it is used as the argument to varFixed, corresponding to fixed variance weights. See the documentation on varClasses for a description of the available varFunc classes. Defaults to NULL, corresponding to homoscedastic within-group errors.

verbose

an optional logical value. If TRUE information on the evolution of the iterative algorithm is printed. Default is FALSE.

returnNlme

Returns the nlme object instead of the nlmixr object (by default FALSE). If any of the nlme specific options of 'random', 'fixed', 'sens', the nlme object is returned

addProp

Type of additive-plus-proportional error: '"combined1"', where standard deviations add:

y = f + (a + b\times f^c) \times \varepsilon

; or '"combined2"', where variances add:

y = f + \sqrt{a^2 + b^2\times f^{2\times c}} \times \varepsilon

. Here y = observed, f = predicted, a = additive sd, b = proportional/power sd, c = power exponent (1 in the proportional case).

calcTables

This boolean is to determine if the foceiFit will calculate tables. By default this is TRUE

compress

Should the object have compressed items

adjObf

is a boolean to indicate if the objective function should be adjusted to be closer to NONMEM's default objective function. By default this is TRUE

ci

Confidence level for some tables. By default this is 0.95 or 95% confidence.

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

sigdigTable

Significant digits in the final output table. If not specified, then it matches the significant digits in the 'sigdig' optimization algorithm. If 'sigdig' is NULL, use 3.

muRefCovAlg

When 'TRUE' (default), algebraic expressions that can be mu-referenced are internally rewritten as mu-referenced covariates and restored after optimization. Mirrors saemControl(muRefCovAlg=)/nlmeControl(muRefCovAlg=); for foceiControl() only takes effect when muModel != "none".

eventSens

Controls how dosing/event-parameter ('alag', 'F', 'rate', 'dur') sensitivities are computed for THETA/ETA gradients: ‘"jump"' (default) uses rxode2’s analytic event sensitivities; '"fd"' uses the legacy finite-difference behavior.

print

Convenience alias for the shared nlmixr 'print' control. 'nlme' prints progress through its own 'verbose' option, so 'print' maps to it: 'print=0' runs quietly ('verbose=FALSE') and any positive value is verbose ('verbose=TRUE'). When 'print' is not supplied an explicit 'verbose' is used as given.

covMethod

Covariance method: '"analytic"' (default) computes the focei observed-information covariance at the converged nlme estimates post-fit (falling back to the finite-difference '"r,s"' -> '"r"'/'"s"' chain when out of analytic scope); '"r,s"', '"r"', '"s"' request the finite-difference forms directly; '"nlme"' and '""' skip the recompute and keep nlme's own standard errors. When the recompute fails the '"nlme"' covariance is kept.

...

Further, named control arguments to be passed to nlminb (apart from trace and iter.max mentioned above), where used (eval.max and those from abs.tol down).

Value

a nlmixr-nlme list

See Also

Other Estimation control: foceiControl(), saemControl()

Examples

nlmeControl()
nlmixr2NlmeControl()

Print x using the message facility

Description

Captures print() output and routes it through message() so suppressMessages() works on print functions.

Usage

nlmixr2Print(x, ...)

Arguments

x

object to print

...

Other things output

Value

Nothing, called for its side effects

Author(s)

Matthew L. Fidler


Validate nlmixr2

Description

This allows easy validation/qualification of nlmixr2 by running the testing suite on your system.

Usage

nlmixr2Validate(type = NULL, skipOnCran = TRUE)

nmTest(type = NULL, skipOnCran = TRUE)

Arguments

type

of test to be run

skipOnCran

when 'TRUE' skip the test on CRAN.

Value

Nothing, called for its side effects

Author(s)

Matthew L. Fidler


Display nlmixr2's version

Description

Display nlmixr2's version

Usage

nlmixr2Version()

Value

Nothing, called for its side effects

Author(s)

Matthew L. Fidler


Try to fix a nlmixr2 fit

Description

Re-evaluates the model function against the current version of rxode2, for fits created with an older nlmixr2/rxode2 version.

Usage

nlmixr2fix(fit)

Arguments

fit

nlmixr2 fit object from a different version of nlmixr2.

Value

A nlmixr2 fit that has been (possibly) adjusted to work with the current version of nlmixr2.

Author(s)

Matthew L. Fidler

Examples


## Not run: 
  # requires the qs package to read an older nlmixr2 v3 fit (qs is no
  # longer on CRAN); regenerates the rxode2 model so it works again
  # fit <- readRDS(system.file("testfit_nlmixr3.rds", package = "nlmixr2est"))
  # fit <- try(nlmixr2fix(fit))
  # if (!inherits(fit, "try-error")) rxSolve(fit)

## End(Not run)

Transform the estimated value to %CV for IOV

Description

Transform the estimated value to %CV for IOV

Usage

nlmixr2iovLogvarCv(val)

nlmixr2iovLogvarSd(val)

nlmixr2iovLogsdCv(val)

nlmixr2iovLogsdSd(val)

nlmixr2iovSdCv(val)

nlmixr2iovSdSd(val)

nlmixr2iovVarCv(val)

nlmixr2iovVarSd(val)

Arguments

val

estimated value

Value

IOV value

Author(s)

Matthew L. Fidler


Add objective function data frame to the current objective function

Description

Add objective function data frame to the current objective function

Usage

nlmixrAddObjectiveFunctionDataFrame(fit, objDf, type, etaObf = NULL)

Arguments

fit

nlmixr fit object

objDf

nlmixr objective function data frame which has column names "OBJF", "AIC", "BIC", "Log-likelihood" and "Condition#(Cov)" "Condition#(Cor)"

type

Objective Function Type

etaObf

Eta objective function table to add (with focei) to give focei objective function

Value

Nothing, called for side effects

Author(s)

Matthew L. Fidler


Manually add time to a nlmixr2 object

Description

Manually add time to a nlmixr2 object

Usage

nlmixrAddTiming(object, name, time)

Arguments

object

nlmixr2 object

name

string of the timing name

time

time (in seconds)

Value

Nothing, called for side effects

Author(s)

Matthew L. Fidler

Examples




one.cmt <- function() {
 ini({
   ## You may label each parameter with a comment
   tka <- 0.45 # Ka
   tcl <- log(c(0, 2.7, 100)) # Log Cl
   ## This works with interactive models
   ## You may also label the preceding line with label("label text")
   tv <- 3.45; label("log V")
   ## the label("Label name") works with all models
   eta.ka ~ 0.6
   eta.cl ~ 0.3
   eta.v ~ 0.1
   add.sd <- 0.7
 })
 model({
   ka <- exp(tka + eta.ka)
   cl <- exp(tcl + eta.cl)
   v <- exp(tv + eta.v)
   linCmt() ~ add(add.sd)
 })
}

fit <- nlmixr(one.cmt, theo_sd, est="saem")

# will add to the current setup
nlmixrAddTiming(fit, "setup", 3)

# Add a new item to the timing dataframe
nlmixrAddTiming(fit, "new", 3)




nlmixrCbind

Description

'cbind' for 'nlmixr' objects that preserve the fit information

Usage

nlmixrCbind(fit, extra)

Arguments

fit

nlmixr fit

extra

data to cbind to nlmixr fit

Value

fit expanded with extra values, without disturbing the fit information

Author(s)

Matthew L. Fidler


Clone nlmixr environment

Description

Clone nlmixr environment

Usage

nlmixrClone(x)

Arguments

x

nlmixr fit

Value

cloned nlmixr environment

Author(s)

Matthew L. Fidler

Examples

## Not run: 

one.cmt <- function() {
  ini({
    ## You may label each parameter with a comment
    tka <- 0.45 # Log Ka
    tcl <- log(c(0, 2.7, 100)) # Log Cl
    ## This works with interactive models
    ## You may also label the preceding line with label("label text")
    tv <- 3.45; label("log V")
    ## the label("Label name") works with all models
    eta.ka ~ 0.6
    eta.cl ~ 0.3
    eta.v ~ 0.1
    add.sd <- 0.7
  })
  model({
    ka <- exp(tka + eta.ka)
    cl <- exp(tcl + eta.cl)
    v <- exp(tv + eta.v)
    linCmt() ~ add(add.sd)
  })
}

f <- nlmixr2(one.cmt, theo_sd, "saem")

nlmixrClone(f)


## End(Not run)

Update the nlmixr2 object with new fit information

Description

Update the nlmixr2 object with new fit information

Usage

nlmixrUpdateObject(fit, objName, envir, origFitEnv = NULL)

Arguments

fit

nlmixr2 fit object to update in the environment

objName

Name of the object

envir

Environment to search

origFitEnv

Original fit$env to compare, otherwise simply use fit$env

Value

Nothing, called for side effects

Author(s)

Matthew L. Fidler


Time a part of a nlmixr operation and add to nlmixr object

Description

Time a part of a nlmixr operation and add to nlmixr object

Usage

nlmixrWithTiming(name, code, envir = NULL)

Arguments

name

Name of the timing to be integrated

code

Code to be evaluated and timed

envir

nlmixr2 fit data, fit environment, or NULL (timing is added when the fit is finalized); supply this if called after a fit already exists

Value

Result of code

Author(s)

Matthew L. Fidler

Examples




one.cmt <- function() {
 ini({
   ## You may label each parameter with a comment
   tka <- 0.45 # Ka
   tcl <- log(c(0, 2.7, 100)) # Log Cl
   ## This works with interactive models
   ## You may also label the preceding line with label("label text")
   tv <- 3.45; label("log V")
   ## the label("Label name") works with all models
   eta.ka ~ 0.6
   eta.cl ~ 0.3
   eta.v ~ 0.1
   add.sd <- 0.7
 })
 model({
   ka <- exp(tka + eta.ka)
   cl <- exp(tcl + eta.cl)
   v <- exp(tv + eta.v)
   linCmt() ~ add(add.sd)
 })
}
fit <- nlmixr(one.cmt, theo_sd, est="saem")

nlmixrWithTiming("time1", {
   Sys.sleep(1)
   # note this can be nested, time1 will exclude the timing from time2
   nlmixrWithTiming("time2", {
      Sys.sleep(1)
   }, envir=fit)
}, envir=fit)

print(fit)




nlmixr2 defaults controls for nls

Description

nlmixr2 defaults controls for nls

Usage

nlsControl(
  maxiter = 10000,
  tol = NULL,
  minFactor = 1/1024,
  printEval = FALSE,
  warnOnly = FALSE,
  scaleOffset = 0,
  nDcentral = FALSE,
  algorithm = c("LM", "default", "plinear", "port"),
  ftol = NULL,
  ptol = NULL,
  gtol = 0,
  diag = list(),
  epsfcn = 0,
  factor = 100,
  maxfev = integer(),
  nprint = 0,
  solveType = c("grad", "fun"),
  stickyRecalcN = 4,
  maxOdeRecalc = 5,
  odeRecalcFactor = 10^(0.5),
  indTolRelax = TRUE,
  eventType = c("central", "forward"),
  shiErr = (.Machine$double.eps)^(1/3),
  shi21maxFD = 20L,
  useColor = NULL,
  printNcol = NULL,
  print = 1L,
  normType = c("rescale2", "mean", "rescale", "std", "len", "constant"),
  scaleType = c("nlmixr2", "norm", "mult", "multAdd"),
  scaleCmax = 1e+05,
  scaleCmin = 1e-05,
  scaleC = NULL,
  scaleTo = 1,
  gradTo = 1,
  trace = FALSE,
  rxControl = NULL,
  optExpression = TRUE,
  sumProd = FALSE,
  literalFix = TRUE,
  returnNls = FALSE,
  addProp = c("combined2", "combined1"),
  eventSens = c("jump", "fd"),
  calcTables = TRUE,
  compress = TRUE,
  adjObf = TRUE,
  ci = 0.95,
  sigdig = 4,
  sigdigTable = NULL,
  boundedTransform = TRUE,
  ...
)

Arguments

maxiter

A positive integer specifying the maximum number of iterations allowed.

tol

A positive numeric value specifying the tolerance level for the relative offset convergence criterion.

minFactor

A positive numeric value specifying the minimum step-size factor allowed on any step in the iteration. The increment is calculated with a Gauss-Newton algorithm and successively halved until the residual sum of squares has been decreased or until the step-size factor has been reduced below this limit.

printEval

a logical specifying whether the number of evaluations (steps in the gradient direction taken each iteration) is printed.

warnOnly

a logical specifying whether nls() should return instead of signalling an error in the case of termination before convergence. Termination before convergence happens upon completion of maxiter iterations, in the case of a singular gradient, and in the case that the step-size factor is reduced below minFactor.

scaleOffset

a constant to be added to the denominator of the relative offset convergence criterion calculation to avoid a zero divide in the case where the fit of a model to data is very close. The default value of 0 keeps the legacy behaviour of nls(). A value such as 1 seems to work for problems of reasonable scale with very small residuals.

nDcentral

only when numerical derivatives are used: logical indicating if central differences should be employed, i.e., numericDeriv(*, central=TRUE) be used.

algorithm

character string specifying the algorithm to use. The default algorithm is a Gauss-Newton algorithm. Other possible values are "plinear" for the Golub-Pereyra algorithm for partially linear least-squares models and "port" for the ‘nl2sol’ algorithm from the Port library – see the references. Can be abbreviated.

ftol

non-negative numeric. Termination occurs when both the actual and predicted relative reductions in the sum of squares are at most ftol. Therefore, ftol measures the relative error desired in the sum of squares.

ptol

non-negative numeric. Termination occurs when the relative error between two consecutive iterates is at most ptol. Therefore, ptol measures the relative error desired in the approximate solution.

gtol

non-negative numeric. Termination occurs when the cosine of the angle between result of fn evaluation fvec and any column of the Jacobian is at most gtol in absolute value. Therefore, gtol measures the orthogonality desired between the function vector and the columns of the Jacobian.

diag

a list or numeric vector containing positive entries that serve as multiplicative scale factors for the parameters. Length of diag should be equal to that of par. If not, user-provided diag is ignored and diag is internally set.

epsfcn

(used if jac is not provided) is a numeric used in determining a suitable step for the forward-difference approximation. This approximation assumes that the relative errors in the functions are of the order of epsfcn. If epsfcn is less than the machine precision, it is assumed that the relative errors in the functions are of the order of the machine precision.

factor

positive numeric, used in determining the initial step bound. This bound is set to the product of factor and the |\code{diag}*\code{par}| if nonzero, or else to factor itself. In most cases factor should lie in the interval (0.1,100). 100 is a generally recommended value.

maxfev

integer; termination occurs when the number of calls to fn has reached maxfev. Note that nls.lm sets the value of maxfev to 100*(length(par) + 1) if maxfev = integer(), where par is the list or vector of parameters to be optimized.

nprint

is an integer; set nprint to be positive to enable printing of iterates

solveType

controls whether ‘nlm' uses nlmixr2’s analytical gradients (event-related parameters like lag time/duration/rate/F use Shi2021 finite differences instead): '"hessian"' builds a Hessian from the analytical gradient via finite differences, '"gradient"' supplies the gradient and lets 'nlm' compute the finite-difference Hessian, and '"fun"' lets 'nlm' compute both by finite differences.

stickyRecalcN

The number of bad ODE solves before reducing the atol/rtol for the rest of the problem.

maxOdeRecalc

Maximum number of times to reduce the ODE tolerances and try to resolve the system if there was a bad ODE solve.

odeRecalcFactor

The ODE recalculation factor when ODE solving goes bad, this is the factor the rtol/atol is reduced

indTolRelax

When 'TRUE' (default), only subjects whose ODE solve produced NaN/Inf have their tolerances relaxed, and the relaxed tolerance persists across optimizer calls (sticky). When 'FALSE', all subjects have their tolerances relaxed on each retry and tolerances are reset afterward.

eventType

Event gradient type for dosing events; Can be "central" or "forward"

shiErr

This represents the epsilon when optimizing the ideal step size for numeric differentiation using the Shi2021 method

shi21maxFD

The maximum number of steps for the optimization of the forward difference step size when using dosing events (lag time, modeled duration/rate and bioavailability)

useColor

Logical (or 'NULL') emit ANSI bold/color escapes in the iteration print. 'NULL' (default) defers to [crayon::has_color()].

printNcol

Integer (or 'NULL') parameter columns per row before wrapping. 'NULL' (default) uses 'floor((getOption("width") - 23) / 12)'.

print

Either a scalar print-frequency ('0' = suppress, '1' (default) = every evaluation, 'N' = every Nth), OR a pre-built [iterPrintControl()] object. Equivalent to 'iterPrintControl(every = print, ncol = printNcol, useColor = useColor)'.

normType

Parameter normalization/scaling used to get scaled initial values for scaleType, of the form Vscaled = (Vunscaled-C1)/C2 (see Feature Scaling; rescale2 follows the OptdesX manual): "rescale2" scales all parameters to (-1, 1); "rescale" (min-max) scales to (0, 1); "mean" centers on the mean with range (0, 1); "std" standardizes by mean/sd; "len" scales to unit (Euclidean) length; "constant" performs no normalization (C1=0, C2=1).

scaleType

The scaling scheme for nlmixr2: "nlmixr2" (default) scales as (current-init)*scaleC[i] + scaleTo, with scaleTo from normType and scales from scaleC; "norm" uses the simple scaling from normType; "mult" scales multiplicatively as current/init*scaleTo; "multAdd" scales linearly ((current-init)+scaleTo) for parameters in an exponential block (e.g. exp(theta)) and multiplicatively otherwise.

scaleCmax

Maximum value of the scaleC to prevent overflow.

scaleCmin

Minimum value of the scaleC to prevent underflow.

scaleC

Scaling constant used with scaleType="nlmixr2"; when not specified, chosen by parameter type to keep gradient sizes similar on a log scale: '1' for exp()-transformed/power/boxCox/ yeoJohnson parameters, '0.5*abs(est)' for additive/proportional/ lognormal error parameters, 'abs(1/digamma(est+1))' for factorials, and 'log(abs(est))*abs(est)' for log-scale parameters. May be set explicitly per parameter if these defaults don't apply well.

scaleTo

Scale the initial parameter estimate to this value. By default this is 1. When zero or below, no scaling is performed.

gradTo

this is the factor that the gradient is scaled to before optimizing. This only works with scaleType="nlmixr2".

trace

logical value indicating if a trace of the iteration progress should be printed. Default is FALSE. If TRUE the residual (weighted) sum-of-squares, the convergence criterion and the parameter values are printed at the conclusion of each iteration. Note that format() is used, so these mostly depend on getOption("digits"). When the "plinear" algorithm is used, the conditional estimates of the linear parameters are printed after the nonlinear parameters. When the "port" algorithm is used the objective function value printed is half the residual (weighted) sum-of-squares.

rxControl

'rxode2' ODE solving options during fitting, created with 'rxControl()'

optExpression

Optimize the rxode2 expression to speed up calculation. By default this is turned on.

sumProd

Is a boolean indicating if the model should change multiplication to high precision multiplication and sums to high precision sums using the PreciseSums package. By default this is FALSE.

literalFix

boolean, substitute fixed population values as literals and re-adjust ui and parameter estimates after optimization; Default is 'TRUE'.

returnNls

logical; when TRUE, will return the nls object instead of the nlmixr object

addProp

Type of additive-plus-proportional error: '"combined1"', where standard deviations add:

y = f + (a + b\times f^c) \times \varepsilon

; or '"combined2"', where variances add:

y = f + \sqrt{a^2 + b^2\times f^{2\times c}} \times \varepsilon

. Here y = observed, f = predicted, a = additive sd, b = proportional/power sd, c = power exponent (1 in the proportional case).

eventSens

Controls how dosing/event-parameter ('alag', 'F', 'rate', 'dur') sensitivities are computed for THETA/ETA gradients: ‘"jump"' (default) uses rxode2’s analytic event sensitivities; '"fd"' uses the legacy finite-difference behavior.

calcTables

This boolean is to determine if the foceiFit will calculate tables. By default this is TRUE

compress

Should the object have compressed items

adjObf

is a boolean to indicate if the objective function should be adjusted to be closer to NONMEM's default objective function. By default this is TRUE

ci

Confidence level for some tables. By default this is 0.95 or 95% confidence.

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

sigdigTable

Significant digits in the final output table. If not specified, then it matches the significant digits in the 'sigdig' optimization algorithm. If 'sigdig' is NULL, use 3.

boundedTransform

When 'TRUE' (default), bounded parameters are transformed for unbounded optimization methods and back-transformed for final estimates. 'FALSE' optimizes on the original scale with bounds passed to the optimizer. 'NA' transforms for optimization but skips the final back-transform.

...

Additional optional arguments. None are used at present.

Value

nls control object

Author(s)

Matthew L. Fidler

Examples



one.cmt <- function() {
  ini({
   tka <- 0.45
   tcl <- log(c(0, 2.7, 100))
   tv <- 3.45
   add.sd <- 0.7
 })
 model({
   ka <- exp(tka)
   cl <- exp(tcl)
   v <- exp(tv)
   linCmt() ~ add(add.sd)
 })
}

# Uses nlsLM from minpack.lm if available

fit1 <- nlmixr(one.cmt, nlmixr2data::theo_sd, est="nls", nlsControl(algorithm="LM"))

# Uses port and respect parameter boundaries
fit2 <- nlmixr(one.cmt, nlmixr2data::theo_sd, est="nls", nlsControl(algorithm="port"))

# You can access the underlying nls object with `$nls`
fit2$nls



This is a S3 method for getting the distribution lines for a base rxode2 saem problem

Description

This is a S3 method for getting the distribution lines for a base rxode2 saem problem

Usage

nmGetDistributionSaemLines(line)

## S3 method for class 'rxUi'
nmGetDistributionSaemLines(line)

## S3 method for class 'norm'
nmGetDistributionSaemLines(line)

## S3 method for class 't'
nmGetDistributionSaemLines(line)

## S3 method for class 'LL'
nmGetDistributionSaemLines(line)

Arguments

line

Parsed rxode2 model environment

Value

Lines for the estimation of saem

Author(s)

Matthew Fidler


C++ implementation of Matrix's nearPD

Description

With 'ensureSymmetry' it makes sure it is symmetric by applying 0.5*(t(x) + x) before using nmNearPD

Usage

nmNearPD(
  x,
  keepDiag = FALSE,
  do2eigen = TRUE,
  doDykstra = TRUE,
  only.values = FALSE,
  ensureSymmetry = !isSymmetric(x),
  eig.tol = 1e-06,
  conv.tol = 1e-07,
  posd.tol = 1e-08,
  maxit = 100L,
  trace = FALSE
)

Arguments

x

numeric n \times n approximately positive definite matrix, typically an approximation to a correlation or covariance matrix. If x is not symmetric (and ensureSymmetry is not false), symmpart(x) is used.

keepDiag

logical, generalizing corr: if TRUE, the resulting matrix should have the same diagonal (diag(x)) as the input matrix.

do2eigen

logical indicating if a posdefify() eigen step should be applied to the result of the Higham algorithm.

doDykstra

logical indicating if Dykstra's correction should be used; true by default. If false, the algorithm is basically the direct fixpoint iteration Y_k = P_U(P_S(Y_{k-1})).

only.values

logical; if TRUE, the result is just the vector of eigenvalues of the approximating matrix.

ensureSymmetry

logical; symmetrizes 'x' via symmpart unless already symmetric. Beware: setting FALSE for asymmetric input is typically nonsense.

eig.tol

defines relative positiveness of eigenvalues compared to largest one, \lambda_1. Eigenvalues \lambda_k are treated as if zero when \lambda_k / \lambda_1 \le eig.tol.

conv.tol

convergence tolerance for Higham algorithm.

posd.tol

tolerance for enforcing positive definiteness (in the final posdefify step when do2eigen is TRUE).

maxit

maximum number of iterations allowed.

trace

logical or integer specifying if convergence monitoring should be traced.

Details

This implements the algorithm of Higham (2002), and then (if do2eigen is true) forces positive definiteness using code from posdefify. The algorithm of Knol and ten Berge (1989) (not implemented here) is more general in that it allows constraints to (1) fix some rows (and columns) of the matrix and (2) force the smallest eigenvalue to have a certain value.

Note that setting corr = TRUE just sets diag(.) <- 1 within the algorithm.

Higham (2002) uses Dykstra's correction, but the version by Jens Oehlschlägel did not use it (accidentally), and still gave reasonable results; this simplification, now only used if doDykstra = FALSE, was active in nearPD() up to Matrix version 0.999375-40.

Value

unlike the matrix package, this simply returns the nearest positive definite matrix

Author(s)

Jens Oehlschlägel donated a first version. Subsequent changes by the Matrix package authors.

References

Cheng, Sheung Hun and Higham, Nick (1998) A Modified Cholesky Algorithm Based on a Symmetric Indefinite Factorization; SIAM J. Matrix Anal.\ Appl., 19, 1097–1110.

Knol DL, ten Berge JMF (1989) Least-squares approximation of an improper correlation matrix by a proper one. Psychometrika 54, 53–61.

Higham, Nick (2002) Computing the nearest correlation matrix - a problem from finance; IMA Journal of Numerical Analysis 22, 329–343.

See Also

A first version of this (with non-optional corr=TRUE) has been available as nearcor(); and more simple versions with a similar purpose posdefify(), both from package sfsmisc.

Examples


set.seed(27)
m <- matrix(round(rnorm(25),2), 5, 5)
m <- m + t(m)
diag(m) <- pmax(0, diag(m)) + 1
(m <- round(cov2cor(m), 2))

near.m <- nmNearPD(m)
round(near.m, 2)
norm(m - near.m) # 1.102 / 1.08

round(nmNearPD(m, only.values=TRUE), 9)

## A longer example, extended from Jens' original,
## showing the effects of some of the options:

pr <- matrix(c(1,     0.477, 0.644, 0.478, 0.651, 0.826,
               0.477, 1,     0.516, 0.233, 0.682, 0.75,
               0.644, 0.516, 1,     0.599, 0.581, 0.742,
               0.478, 0.233, 0.599, 1,     0.741, 0.8,
               0.651, 0.682, 0.581, 0.741, 1,     0.798,
               0.826, 0.75,  0.742, 0.8,   0.798, 1),
               nrow = 6, ncol = 6)

nc  <- nmNearPD(pr)


Get an item from a nlmixr core object

Description

Get an item from a nlmixr core object

Usage

nmObjGet(x, ...)

## Default S3 method:
nmObjGet(x, ...)

## S3 method for class 'modelName'
nmObjGet(x, ...)

## S3 method for class 'cor'
nmObjGet(x, ...)

## S3 method for class 'omegaR'
nmObjGet(x, ...)

## S3 method for class 'phiR'
nmObjGet(x, ...)

## S3 method for class 'phiSE'
nmObjGet(x, ...)

## S3 method for class 'phiRSE'
nmObjGet(x, ...)

## S3 method for class 'phiCI'
nmObjGet(x, ...)

## S3 method for class 'dataSav'
nmObjGet(x, ...)

## S3 method for class 'idLvl'
nmObjGet(x, ...)

## S3 method for class 'covLvl'
nmObjGet(x, ...)

## S3 method for class 'parHist'
nmObjGet(x, ...)

## S3 method for class 'parHistStacked'
nmObjGet(x, ...)

## S3 method for class 'md5'
nmObjGet(x, ...)

## S3 method for class 'notes'
nmObjGet(x, ...)

## S3 method for class 'sigma'
nmObjGet(x, ...)

## S3 method for class 'coefficients'
nmObjGet(x, ...)

## S3 method for class 'env'
nmObjGet(x, ...)

## S3 method for class 'condition'
nmObjGet(x, ...)

## S3 method for class 'simInfo'
nmObjGet(x, ...)

## S3 method for class 'seed'
nmObjGet(x, ...)

## S3 method for class 'saemCfg'
nmObjGet(x, ...)

## S3 method for class 'estimationModel'
nmObjGet(x, ...)

## S3 method for class 'atol'
nmObjGet(x, ...)

## S3 method for class 'rtol'
nmObjGet(x, ...)

## S3 method for class 'maxstepsOde'
nmObjGet(x, ...)

## S3 method for class 'hmin'
nmObjGet(x, ...)

## S3 method for class 'hmax'
nmObjGet(x, ...)

## S3 method for class 'hini'
nmObjGet(x, ...)

## S3 method for class 'maxordn'
nmObjGet(x, ...)

## S3 method for class 'maxords'
nmObjGet(x, ...)

## S3 method for class 'methodOde'
nmObjGet(x, ...)

## S3 method for class 'covsInterpolation'
nmObjGet(x, ...)

## S3 method for class 'control'
nmObjGet(x, ...)

## S3 method for class 'simulationModel'
nmObjGet(x, ...)

## S3 method for class 'rxControl'
nmObjGet(x, ...)

## S3 method for class 'mixList'
nmObjGet(x, ...)

## S3 method for class 'mixNum'
nmObjGet(x, ...)

## S3 method for class 'ranef'
nmObjGet(x, ...)

## S3 method for class 'eta'
nmObjGet(x, ...)

## S3 method for class 'rxControlWithVar'
nmObjGet(x, ...)

## S3 method for class 'saemDopredIpred'
nmObjGet(x, ...)

## S3 method for class 'saemDopredPred'
nmObjGet(x, ...)

Arguments

x

A specialized list with: - First argument is a nlmixrFitCore environment - Second argument is if the exact argument is requested - The class would be the requested argument name followed by the class "nmObjGet"

...

Other arguments

Value

Value of argument or NULL

Author(s)

Matthew L. Fidler


Get control object from fit

Description

Get control object from fit

Usage

## S3 method for class 'agq'
nmObjGetControl(x, ...)

## S3 method for class 'bobyqa'
nmObjGetControl(x, ...)

## S3 method for class 'emvi'
nmObjGetControl(x, ...)

## S3 method for class 'fbvi'
nmObjGetControl(x, ...)

## S3 method for class 'fo'
nmObjGetControl(x, ...)

## S3 method for class 'foce'
nmObjGetControl(x, ...)

## S3 method for class 'focep'
nmObjGetControl(x, ...)

## S3 method for class 'foi'
nmObjGetControl(x, ...)

## S3 method for class 'ifocep'
nmObjGetControl(x, ...)

## S3 method for class 'imp'
nmObjGetControl(x, ...)

## S3 method for class 'impmap'
nmObjGetControl(x, ...)

## S3 method for class 'laplace'
nmObjGetControl(x, ...)

## S3 method for class 'lbfgsb3c'
nmObjGetControl(x, ...)

## S3 method for class 'mfocep'
nmObjGetControl(x, ...)

## S3 method for class 'mfocei'
nmObjGetControl(x, ...)

## S3 method for class 'ifocei'
nmObjGetControl(x, ...)

## S3 method for class 'mfoce'
nmObjGetControl(x, ...)

## S3 method for class 'ifoce'
nmObjGetControl(x, ...)

## S3 method for class 'magq'
nmObjGetControl(x, ...)

## S3 method for class 'iagq'
nmObjGetControl(x, ...)

## S3 method for class 'mlaplace'
nmObjGetControl(x, ...)

## S3 method for class 'ilaplace'
nmObjGetControl(x, ...)

## S3 method for class 'n1qn1'
nmObjGetControl(x, ...)

## S3 method for class 'newuoa'
nmObjGetControl(x, ...)

## S3 method for class 'nlm'
nmObjGetControl(x, ...)

## S3 method for class 'nlme'
nmObjGetControl(x, ...)

## S3 method for class 'nlminb'
nmObjGetControl(x, ...)

## S3 method for class 'nls'
nmObjGetControl(x, ...)

nmObjGetControl(x, ...)

## S3 method for class 'focei'
nmObjGetControl(x, ...)

## S3 method for class 'saem'
nmObjGetControl(x, ...)

## Default S3 method:
nmObjGetControl(x, ...)

## S3 method for class 'mnpag'
nmObjGetControl(x, ...)

## S3 method for class 'inpag'
nmObjGetControl(x, ...)

## S3 method for class 'mnpb'
nmObjGetControl(x, ...)

## S3 method for class 'inpb'
nmObjGetControl(x, ...)

## S3 method for class 'npag'
nmObjGetControl(x, ...)

## S3 method for class 'npb'
nmObjGetControl(x, ...)

## S3 method for class 'optim'
nmObjGetControl(x, ...)

## S3 method for class 'posthoc'
nmObjGetControl(x, ...)

## S3 method for class 'qrpem'
nmObjGetControl(x, ...)

## S3 method for class 'uobyqa'
nmObjGetControl(x, ...)

## S3 method for class 'vae'
nmObjGetControl(x, ...)

Arguments

x

nlmixr fit object

...

Other parameters

Value

Control object of estimation method

Author(s)

Matthew L. Fidler


Get an item from a nlmixr2FitData object

Description

Get an item from a nlmixr2FitData object

Usage

## S3 method for class 'addCwres'
nmObjGetData(x, ...)

nmObjGetData(x, ...)

## S3 method for class 'dataMergeLeft'
nmObjGetData(x, ...)

## S3 method for class 'dataMergeRight'
nmObjGetData(x, ...)

## S3 method for class 'dataMergeInner'
nmObjGetData(x, ...)

## S3 method for class 'dataMergeFull'
nmObjGetData(x, ...)

## S3 method for class 'fitMergeLeft'
nmObjGetData(x, ...)

## S3 method for class 'fitMergeRight'
nmObjGetData(x, ...)

## S3 method for class 'fitMergeInner'
nmObjGetData(x, ...)

## S3 method for class 'fitMergeFull'
nmObjGetData(x, ...)

Arguments

x

A specialized list with: - First argument is a nlmixr2FitData object - Second argument is if the exact argument is requested - The class would be the requested argument name followed by the class "nmObjGet"

...

Other arguments

Value

Value of argument or NULL

Author(s)

Matthew L. Fidler


Get the estimation model for a fit object depending on the object type

Description

By default it gets the focei models if available.

Usage

nmObjGetEstimationModel(x)

Arguments

x

nlmixr fit object

Value

returns the estimation '$model' for the estimation type


Method for getting focei compatible control object from nlmixr object

Description

Method for getting focei compatible control object from nlmixr object

Usage

## S3 method for class 'agq'
nmObjGetFoceiControl(x, ...)

## S3 method for class 'foce'
nmObjGetFoceiControl(x, ...)

## S3 method for class 'focep'
nmObjGetFoceiControl(x, ...)

## S3 method for class 'ifocep'
nmObjGetFoceiControl(x, ...)

## S3 method for class 'imp'
nmObjGetFoceiControl(x, ...)

## S3 method for class 'impmap'
nmObjGetFoceiControl(x, ...)

## S3 method for class 'laplace'
nmObjGetFoceiControl(x, ...)

## S3 method for class 'mfocep'
nmObjGetFoceiControl(x, ...)

## S3 method for class 'mfocei'
nmObjGetFoceiControl(x, ...)

## S3 method for class 'ifocei'
nmObjGetFoceiControl(x, ...)

## S3 method for class 'mfoce'
nmObjGetFoceiControl(x, ...)

## S3 method for class 'ifoce'
nmObjGetFoceiControl(x, ...)

## S3 method for class 'magq'
nmObjGetFoceiControl(x, ...)

## S3 method for class 'iagq'
nmObjGetFoceiControl(x, ...)

## S3 method for class 'mlaplace'
nmObjGetFoceiControl(x, ...)

## S3 method for class 'ilaplace'
nmObjGetFoceiControl(x, ...)

## S3 method for class 'nlme'
nmObjGetFoceiControl(x, ...)

nmObjGetFoceiControl(x, ...)

## Default S3 method:
nmObjGetFoceiControl(x, ...)

## S3 method for class 'mnpag'
nmObjGetFoceiControl(x, ...)

## S3 method for class 'inpag'
nmObjGetFoceiControl(x, ...)

## S3 method for class 'mnpb'
nmObjGetFoceiControl(x, ...)

## S3 method for class 'inpb'
nmObjGetFoceiControl(x, ...)

## S3 method for class 'npag'
nmObjGetFoceiControl(x, ...)

## S3 method for class 'npb'
nmObjGetFoceiControl(x, ...)

## S3 method for class 'posthoc'
nmObjGetFoceiControl(x, ...)

## S3 method for class 'qrpem'
nmObjGetFoceiControl(x, ...)

## S3 method for class 'saem'
nmObjGetFoceiControl(x, ...)

Arguments

x

nlmixr composed fit object

...

Other parameters

Value

foceiControl translated from current control


Get the ipred model for a fit object depending on the object type

Description

By default it gets the focei models if available.

Usage

nmObjGetIpredModel(x)

## S3 method for class 'saem'
nmObjGetIpredModel(x)

## Default S3 method:
nmObjGetIpredModel(x)

## S3 method for class 'saem'
nmObjGetEstimationModel(x)

## Default S3 method:
nmObjGetEstimationModel(x)

Arguments

x

nlmixr fit object

Value

ipred 'rxode2' model


Get the pred-only model for a fit depending on the object type

Description

By default it gets the focei models if available

Usage

nmObjGetPredOnly(x)

## S3 method for class 'saem'
nmObjGetPredOnly(x)

## Default S3 method:
nmObjGetPredOnly(x)

Arguments

x

nlmixr fit object

Value

rxode2 pred-only model


Get an option for the estimation method

Description

By default it gets the focei models if available.

Usage

nmObjGetRxSolve(x, what)

## Default S3 method:
nmObjGetRxSolve(x, what)

Arguments

x

nlmixr fit object in a list. The class is the estimation method used.

what

What part of the rx solve are you attempting to get?

Value

The estimation option based on 'what', for example 'nlmixrObjGetRxSolve(x, "atol")' will get a double vector of absolute tolerances


Handle the control object

Description

Handle the control object

Usage

## S3 method for class 'agqControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'bobyqaControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'emviControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'foControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'foceControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'focepControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'foiControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'ifocepControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'impmapControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'laplaceControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'lbfgsb3cControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'mfocepControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'mfoceiControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'ifoceiControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'mfoceControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'ifoceControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'magqControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'iagqControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'mlaplaceControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'ilaplaceControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'n1qn1Control'
nmObjHandleControlObject(control, env)

## S3 method for class 'newuoaControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'nlmControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'nlmeControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'nlminbControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'nlsControl'
nmObjHandleControlObject(control, env)

nmObjHandleControlObject(control, env)

## S3 method for class 'foceiControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'saemControl'
nmObjHandleControlObject(control, env)

## Default S3 method:
nmObjHandleControlObject(control, env)

## S3 method for class 'optimControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'posthocControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'uobyqaControl'
nmObjHandleControlObject(control, env)

## S3 method for class 'vaeControl'
nmObjHandleControlObject(control, env)

Arguments

control

Control object

env

fit environment

Value

Nothing, called for side effects

Author(s)

Matthew L. Fidler


Handle Model Object

Description

Handle Model Object

Usage

nmObjHandleModelObject(model, env)

## S3 method for class 'saemModelList'
nmObjHandleModelObject(model, env)

## S3 method for class 'foceiModelList'
nmObjHandleModelObject(model, env)

## Default S3 method:
nmObjHandleModelObject(model, env)

Arguments

model

model list should have at least:

- 'predOnly' – this is the prediction model with all the left handed equations added so they will be added the table. The model should have 'rx_pred_', the model based prediction, as the first defined lhs component. The second component should be 'rx_r_', the variance of the prediction. These variables may change based on distribution type. In additional all interesting calculated variables should be included.

- 'predNoLhs' – This is the prediction model. It only has the prediction and no left handed equations.

env

Environment for the fit information

Value

This returns the '$model' object for a fit. It is a s3 method because it may be different between different model types


Set if the nlmixr2 object will return a compressed ui

Description

Set if the nlmixr2 object will return a compressed ui

Usage

nmObjUiSetCompressed(type)

Arguments

type

is a boolean indicating if the compressed ui will be returned ('TRUE') or not be returned ('FALSE')

Value

invisible logical type

Author(s)

Matthew L. Fidler

Examples


nmObjUiSetCompressed(FALSE) # now the $ui will return an environment
nmObjUiSetCompressed(TRUE) # now the $ui will return a compressed value


Respect suppress messages for nlmixr2 C functions

Description

Makes C-level 'REprintf' respect 'suppressMessages()', like R messages.

Usage

nmSuppressMsg()

Value

Nothing

Author(s)

Matthew Fidler

Examples


# Called automatically by nlmixr2(); other packages can call it too.

Nelder-Mead simplex search

Description

Nelder-Mead simplex search

Usage

nmsimplex(start, fr, rho = NULL, control = list())

Arguments

start

initials

fr

objective function

rho

evaluation environment

control

additional optimization options

Value

a list of ...


Build the nonparametric Psi (conditional-likelihood) matrix

Description

For an already set-up FOCEi inner problem (vaeInnerSetup_), evaluates psi[i, k] = p(y_i | support point k) for each subject i (rows) and support point k (columns), where each support point is an eta vector. Exposed for testing the conditional-likelihood primitive.

Usage

npBuildPsi(etaPoints, cores)

Arguments

etaPoints

Numeric matrix of support points, one per row (columns are etas).

cores

Number of OpenMP threads.

Value

Numeric matrix psi (subjects in rows, support points in columns).


Condense support points (nonparametric engines)

Description

Condense support points (nonparametric engines)

Usage

npCondense_(lambda, psi, ratio = 0.001, tol = 1e-08)

Arguments

lambda

Support-point weights.

psi

Conditional-likelihood matrix (subjects x support points).

ratio

Weight-threshold ratio (keep weight > max*ratio).

tol

QR rank-revealing tolerance.

Value

List with 1-based kept indices from the weight threshold (weightKeep) and from the subsequent QR pass (qrKeep).


Burke interior-point weight solver (nonparametric maximum likelihood)

Description

Solves the convex nonparametric-maximum-likelihood weight problem for a fixed set of support points: given the likelihood matrix psi (subjects in rows, support points in columns) it returns the maximum-likelihood mixing weights and the objective (log-likelihood). Exposed for testing the C++ interior-point routine against golden fixtures.

Usage

npIpmBurke(psi)

Arguments

psi

Numeric matrix, psi[i, k] = p(y_i | support point k), with subjects in rows and support points in columns.

Value

A list with weights (length ncol(psi), non-negative, summing to 1) and objective (the maximized log-likelihood).


Diagnostic: NPAG objective at a fixed grid and residual multiplier gamma

Description

Diagnostic: NPAG objective at a fixed grid and residual multiplier gamma

Usage

npObjAtGamma_(etaPoints, cores, gamma)

Arguments

etaPoints

support points, one per row

cores

threads

gamma

residual-error multiplier

Value

offset-corrected marginal log-likelihood


Sobol initial grid over a box (nonparametric engines)

Description

Sobol initial grid over a box (nonparametric engines)

Usage

npSobolGrid_(n, lower, upper)

Arguments

n

Number of support points.

lower, upper

Numeric vectors giving the per-dimension box bounds.

Value

Numeric matrix, one support point per row.


Control for the npag (nonparametric adaptive grid) method

Description

A wrapper around [impmapControl()] that reuses the shared FOCEI family plumbing for the nonparametric adaptive grid engine. The nonparametric support-point knobs are added in a later milestone.

Usage

npagControl(
  points = NULL,
  cycles = 100L,
  gammaOptimize = TRUE,
  residOptimize = c("alternate", "final", "none"),
  muExpand = FALSE,
  gridWidth = 4,
  gridBounds = c("auto", "ini", "both"),
  dfScan = -1L,
  cores = NULL,
  rhoend = 1e-04,
  gamma,
  df,
  ...
)

Arguments

points

Initial Sobol grid size (support points). 'NULL' (default) picks it automatically from the number of support-point dimensions (etas): 'max(2028, 512 * n_eta)' – a fixed grid (Pmetrics uses 2028) covers a low-dimensional model but grows sparse and can collapse in high dimensions, so the auto size floors at 2028 and scales up per added eta. Supply an integer to override.

cycles

Maximum adaptive-grid cycles.

gammaOptimize

Use a global assay-error multiplier as a per-cycle warm start for the overall residual magnitude, folded into the variance-scale coefficients ('add'/'prop'/'lnorm'). The per-endpoint values, the add/prop ratio, and the transform/autocorrelation parameters come from residOptimize. Only valid for normal endpoints; censoring and transform-both-sides are supported. Unrelated to [impmapControl()]'s ‘gamma', which inflates an importance-sampling proposal’s variance and has no meaning here.

residOptimize

How to estimate the residual-error thetas (every endpoint's 'add'/'prop'/'lnorm', each transform 'lambda', each 'ar') with the support points and weights held fixed, using bounded minqa::bobyqa on the EXTENDED LEAST SQUARES objective 'sum_obs((f-dv)^2/r + log(r))' at the posterior-mean etas. The 'log(r)' term keeps the residual from drifting to zero on a flexible support (which the marginal likelihood would reward), giving the saem/focei residual; each variance scale is warm-started from the per-endpoint moment (additive SD from 'sqrt(mean(err^2))', proportional from 'sqrt(mean((err/f)^2))', on the transform- both-sides scale). "alternate" (default) optimizes every cycle (block- coordinate ascent); "final" optimizes once at the converged support; "none" holds them at their initial values. Fixed residual parameters are always held. After the residual thetas converge, a final adaptive-grid pass re-optimizes the support with them held constant so the support remains the nonparametric MLE (D(F) ~ 0) for the fitted residual.

muExpand

how to estimate non-mu structural fixed-effect parameters (a theta with no eta, e.g. ‘ke <- exp(tke)'; npag’s grid otherwise covers only mu-referenced and residual/likelihood parameters). 'FALSE' (default) optimizes them directly as "regressors" in the residual step – 'bobyqa' moves them alongside the residual parameters, re-deriving the posterior-mean etas each candidate (so the eta grid cannot stale-absorb the structural shift) – which identifies them well (e.g. recovering a clearance from a poor start). Not available for mix() models (the ELS step is not mixture-aware; component parameters are held). 'TRUE' instead uses the saem-style mu-expansion: inject a pseudo-eta ('ke <- exp(tke + eta.tke)'), grid-estimate, and recover it as a fixed effect at finalization (support-mean folded into the theta, injected random effect collapsed). The regressor default usually identifies these parameters more sharply than the grid.

gridWidth

support-point box half-width, in initial-eta SDs, for the 'gridBounds="auto"' grid (default 4). A narrower box focuses the initial Sobol grid on the plausible region – useful for high-dimensional models where a wide box wastes points on near-zero-density support (which can collapse the fit).

gridBounds

how to set the initial support-point box: '"auto"' (default) uses '+/- gridWidth * initial eta SD'; '"ini"' uses each mu-referenced parameter's ini-block lower/upper bounds where finite (else auto); '"both"' uses the ini bounds when present and auto otherwise. For a high-dimensional model, bounded ini estimates + '"ini"' keep the grid in range.

dfScan

Size of the Sobol scan used for the D(F) global-optimality certificate: '-1' (default) auto-sizes it to 'max(2048, 2 * points)', '0' skips the certificate ('npagDF' is 'NA'), and a positive value sets an explicit scan size. The scan does not affect the fit, only the reported certificate; a smaller scan is faster.

cores

Number of threads used for the parallel per-subject conditional- likelihood solves. 'NULL' (default) uses the current 'rxode2' thread count ('rxode2::getRxThreads()'); an integer sets the thread count for the fit (restored afterwards). Results are independent of the thread count.

rhoend

Final trust-region radius ('rhoend') of the inner bounded 'bobyqa' that fits the residual-error thetas each cycle. A fixed default of '1e-4', matching the optimizer convergence tolerance '10^(-sigdig)' at 'sigdig = 4' (npag has no 'sigdig', so this is not derived from it).

gamma, df

Declared only so they are REJECTED rather than partially matched. 'gamma' is a prefix of 'gammaOptimize', so without an explicit formal R bound 'gamma = 2' to it and silently turned the assay-error optimisation off; 'df' is an importance-sampling proposal control a nonparametric engine never builds. Passing either is an error.

...

Parameters passed to [impmapControl()], for the shared FOCEI-family scaffolding only (the inner MAP problem, mu-referencing, the residual error model, threads). The importance-sampling controls are **rejected** rather than accepted: 'isample', 'df', 'auto', 'iaccept', 'gamma', 'qr', 'sir' and the rest configure a proposal density that a nonparametric engine never builds, so passing one is an error rather than a silent no-op. Where an np control does the job the message names it ('nIter' -> 'cycles', 'ctol' -> 'rhoend').

Note ‘gamma' is NOT 'gammaOptimize': 'gamma' is impmap’s proposal-variance inflation (NONMEM 'ISCALE'), while 'gammaOptimize' is a global assay-error multiplier on the residual magnitude. They are unrelated, and 'gamma' is a prefix of ‘gammaOptimize', so it is rejected explicitly to stop R’s partial matching from silently binding one to the other.

Details

Note: the npag objective is the nonparametric marginal log-likelihood and uses a different constant convention than NONMEM/FOCEI, so its '-2LL' is NOT comparable to nlmixr2's FOCEI/SAEM/FOCE '-2LL'. Compare npag runs to each other or to Pmetrics NPAG.

Note on residual error with a flexible support distribution: the residual parameters are estimated against the nonparametric objective (see residOptimize) with the support-point distribution held fixed. Because that distribution is flexible, it can absorb variability a parametric model (FOCEI/SAEM) would attribute to residual error – especially the additive term of a combined additive+proportional model at low concentrations. As a result the additive coefficient of a combined error model may be estimated smaller (sometimes toward zero) than the corresponding parametric fit, while the proportional term and per-endpoint magnitudes are recovered well. This is an expected property of nonparametric estimation, not a convergence failure; use residOptimize = "none" to hold the residual parameters at their initial values if a fixed error model is desired.

Value

An 'impmapControl' object tagged for the npag engine.

Author(s)

Matthew L. Fidler

Examples


npagControl()

Run the NPAG adaptive-grid cycle on a set-up inner problem

Description

Requires the FOCEi inner problem to be set up (.npInnerSetup). Runs the full Yamada adaptive-grid cycle (Sobol grid -> Psi -> Burke IPM -> condensation -> expansion -> convergence) and returns the discrete mixing distribution. Exposed for testing ahead of the full fit-object wiring.

Usage

npagCycle_(
  lower,
  upper,
  points = 2028L,
  cycles = 100L,
  cores = 1L,
  gammaOptimize = FALSE
)

Arguments

lower, upper

Numeric vectors, the per-eta support-point box.

points

Initial Sobol grid size.

cycles

Maximum cycles.

cores

OpenMP threads.

gammaOptimize

Optimize the residual-error magnitude (gamma) each cycle (only valid for uncensored normal endpoints).

Value

A list with support (support points, eta space; one per row), weights, objf (log-likelihood), gamma, cycles, and converged.


Control for the npb (nonparametric Bayes) method

Description

A wrapper around [impmapControl()] that reuses the shared FOCEI family plumbing for the nonparametric Bayes engine. The stick-breaking sampler knobs are added in a later milestone.

Usage

npbControl(
  points = 50L,
  alpha = 1,
  burnin = 500L,
  nsamp = 500L,
  nchains = 1L,
  propSd = 0.2,
  seed = 42L,
  residOptimize = c("alternate", "final", "none"),
  cycles = 100L,
  gammaOptimize = FALSE,
  muExpand = FALSE,
  cores = NULL,
  rhoend = 1e-04,
  gamma,
  df,
  ...
)

Arguments

points

Stick-breaking truncation level K (number of support points).

alpha

Dirichlet-process concentration parameter.

burnin

Number of burn-in Gibbs sweeps.

nsamp

Number of post-burn-in Gibbs samples collected.

nchains

Number of independent chains (Gelman-Rubin R-hat convergence is reported when nchains > 1).

propSd

Standard deviation of the Gaussian random-walk MH proposal for the support-point locations (eta space).

seed

Random seed for the sampler.

residOptimize

How to estimate the residual-error thetas (every endpoint's 'add'/'prop'/'lnorm', each transform 'lambda', each 'ar') and any non-mu structural "regressor" theta, with the sampled mixing distribution held fixed, using the bounded 'bobyqa' on the EXTENDED LEAST SQUARES objective (see [npagControl()]; the 'log(r)' term keeps the residual from collapsing to zero and the moment warm-start gives the saem-style SD). "alternate" (default) re-fits them during burn-in and then holds them fixed for the sampling phase (so every collected draw shares the converged residual scale); "final" holds them at their initial values through sampling and fits once at the converged draw; "none" holds them at their initial values throughout. Fixed residual parameters are always held. Unlike npag, npb does not optimize the assay-error multiplier (gamma); the residual thetas are fit directly.

cycles

Unused for npb (kept for control compatibility).

gammaOptimize

Unused for npb (kept for control compatibility).

muExpand

When 'TRUE', mu-expand non-mu structural fixed-effect thetas (a theta with no eta) into grid-estimable pseudo-etas before the fit; 'FALSE' (default) leaves them to the residual step.

cores

Number of threads used for the parallel per-subject conditional- likelihood solves in the Gibbs sweeps. 'NULL' (default) uses the current 'rxode2' thread count ('rxode2::getRxThreads()'); an integer sets the thread count for the fit (restored afterwards). With a fixed 'seed' the fit is bit-for-bit identical regardless of the thread count.

rhoend

Final trust-region radius ('rhoend') of the inner bounded 'bobyqa' that fits the residual-error thetas. A fixed default of '1e-4', matching the optimizer convergence tolerance '10^(-sigdig)' at 'sigdig = 4' (npb has no 'sigdig', so this is not derived from it).

gamma, df

Declared only so they are REJECTED rather than partially matched. 'gamma' is a prefix of 'gammaOptimize', so without an explicit formal R bound 'gamma = 2' to it and silently turned the assay-error optimisation off; 'df' is an importance-sampling proposal control a nonparametric engine never builds. Passing either is an error.

...

Parameters passed to [impmapControl()], for the shared FOCEI-family scaffolding only. The importance-sampling controls are **rejected** rather than accepted – see [npagControl()] – as are 'cycles' and 'gammaOptimize', which this signature carries but 'npb' does not use. 'impSeed' is rejected pointing at 'seed'.

Details

Note: the npb objective is the nonparametric marginal log-likelihood and uses a different constant convention than NONMEM/FOCEI, so its '-2LL' is NOT comparable to nlmixr2's FOCEI/SAEM/FOCE '-2LL'. Compare npb runs to each other or to Pmetrics NPAG.

Value

An 'impmapControl' object tagged for the npb engine.

Author(s)

Matthew L. Fidler

Examples


npbControl()

Return the objective function

Description

Return the objective function

Usage

ofv(x, type, ...)

Arguments

x

object to return objective function value

type

Objective function type value to retrieve or add.

  • focei For most models you can specify "focei" and it will add the focei objective function.

  • nlme This switches/chooses the nlme objective function if applicable. This objective function cannot be added if it isn't present.

  • fo FO objective function value. Cannot be generated

  • foce FOCE object function value. Cannot be generated

  • laplace# This adds/retrieves the Laplace objective function value. The # represents the number of standard deviations requested when expanding the Gaussian Quadrature. This can currently only be used with saem fits.

  • gauss#.# This adds/retrieves the Gaussian Quadrature approximation of the objective function. The first number is the number of nodes to use in the approximation. The second number is the number of standard deviations to expand upon.

...

Other arguments sent to ofv for other methods.

Value

Objective function value

Author(s)

Matthew Fidler


nlmixr2 optim defaults

Description

nlmixr2 optim defaults

Usage

optimControl(
  method = c("Nelder-Mead", "BFGS", "CG", "L-BFGS-B", "SANN", "Brent"),
  trace = 0,
  fnscale = 1,
  parscale = 1,
  ndeps = 0.001,
  maxit = 10000,
  abstol = NULL,
  reltol = NULL,
  alpha = 1,
  beta = 0.5,
  gamma = 2,
  REPORT = NULL,
  warn.1d.NelderMead = TRUE,
  type = NULL,
  lmm = 5,
  factr = NULL,
  pgtol = 0,
  temp = 10,
  tmax = 10,
  stickyRecalcN = 4,
  maxOdeRecalc = 5,
  odeRecalcFactor = 10^(0.5),
  indTolRelax = TRUE,
  eventType = c("central", "forward"),
  shiErr = (.Machine$double.eps)^(1/3),
  shi21maxFD = 20L,
  solveType = c("grad", "fun"),
  useColor = NULL,
  printNcol = NULL,
  print = 1L,
  normType = c("rescale2", "mean", "rescale", "std", "len", "constant"),
  scaleType = c("nlmixr2", "norm", "mult", "multAdd"),
  scaleCmax = 1e+05,
  scaleCmin = 1e-05,
  scaleC = NULL,
  scaleTo = 1,
  gradTo = 1,
  rxControl = NULL,
  optExpression = TRUE,
  sumProd = FALSE,
  literalFix = TRUE,
  literalFixRes = TRUE,
  returnOptim = FALSE,
  addProp = c("combined2", "combined1"),
  eventSens = c("jump", "fd"),
  sensMethod = c("default", "forward"),
  calcTables = TRUE,
  compress = FALSE,
  covMethod = c("r", "optim", ""),
  adjObf = TRUE,
  ci = 0.95,
  sigdig = 3,
  sigdigTable = NULL,
  boundedTransform = TRUE,
  ...
)

Arguments

method

The method to be used. See ‘Details’. Can be abbreviated.

trace

Non-negative integer. If positive, tracing information on the progress of the optimization is produced. Higher values may produce more tracing information: for method '"L-BFGS-B"', there are six levels of tracing. See 'optim()' for more information

fnscale

An overall scaling to be applied to the value of 'fn' and 'gr' during optimization. If negative, turns the problem into a maximization problem. Optimization is performed on 'fn(par)/fnscale'

parscale

A vector of scaling values for the parameters. Optimization is performed on 'par/parscale' and these should be comparable in the sense that a unit change in any element produces about a unit change in the scaled value. Not used (nor needed) for 'method = "Brent"'

ndeps

A vector of step sizes for the finite-difference approximation to the gradient, on 'par/parscale' scale. Defaults to '1e-3'

maxit

The maximum number of iterations. Defaults to '100' for the derivative-based methods, and '500' for '"Nelder-Mead"'.

abstol

The absolute convergence tolerance. Only useful for non-negative functions, as a tolerance for reaching zero.

reltol

Relative convergence tolerance. The algorithm stops if it is unable to reduce the value by a factor of 'reltol * (abs(val) + reltol)' at a step

alpha

Reflection factor for the '"Nelder-Mead"' method.

beta

Contraction factor for the '"Nelder-Mead"' method

gamma

Expansion factor for the '"Nelder-Mead"' method

REPORT

The frequency of reports for the '"BFGS"', '"L-BFGS-B"' and '"SANN"' methods if 'control$trace' is positive. Defaults to every 10 iterations for '"BFGS"' and '"L-BFGS-B"', or every 100 temperatures for '"SANN"'

warn.1d.NelderMead

a logical indicating if the (default) '"Nelder-Mead"' method should signal a warning when used for one-dimensional minimization. As the warning is sometimes inappropriate, you can suppress it by setting this option to 'FALSE'

type

for the conjugate-gradients method. Takes value '1' for the Fletcher-Reeves update, '2' for Polak-Ribiere and '3' for Beale-Sorenson.

lmm

is an integer giving the number of BFGS updates retained in the '"L-BFGS-B"' method, It defaults to '5'

factr

controls the convergence of the '"L-BFGS-B"' method. Convergence occurs when the reduction in the objective is within this factor of the machine tolerance. Default is '1e7', that is a tolerance of about '1e-8'.

pgtol

helps control the convergence of the '"L-BFGS-B"' method. It is a tolerance on the projected gradient in the current search direction. This defaults to zero, when the check is suppressed

temp

controls the '"SANN"' method. It is the starting temperature for the cooling schedule. Defaults to '10'.

tmax

is the number of function evaluations at each temperature for the '"SANN"' method. Defaults to '10'.

stickyRecalcN

The number of bad ODE solves before reducing the atol/rtol for the rest of the problem.

maxOdeRecalc

Maximum number of times to reduce the ODE tolerances and try to resolve the system if there was a bad ODE solve.

odeRecalcFactor

The ODE recalculation factor when ODE solving goes bad, this is the factor the rtol/atol is reduced

indTolRelax

When 'TRUE' (default), only subjects whose ODE solve produced NaN/Inf have their tolerances relaxed, and the relaxed tolerance persists across optimizer calls (sticky). When 'FALSE', all subjects have their tolerances relaxed on each retry and tolerances are reset afterward.

eventType

Event gradient type for dosing events; Can be "central" or "forward"

shiErr

This represents the epsilon when optimizing the ideal step size for numeric differentiation using the Shi2021 method

shi21maxFD

The maximum number of steps for the optimization of the forward difference step size when using dosing events (lag time, modeled duration/rate and bioavailability)

solveType

controls whether ‘optim' uses nlmixr2’s analytical gradients (event-related parameters like lag time/duration/rate/F use Shi2021 finite differences instead). '"gradient"' supplies the gradient and lets 'optim' compute the finite-difference Hessian; '"fun"' lets 'optim' compute both by finite differences. Only applies to the gradient-based methods: "BFGS", "CG", "L-BFGS-B".

useColor

Logical (or 'NULL') emit ANSI bold/color escapes in the iteration print. 'NULL' (default) defers to [crayon::has_color()].

printNcol

Integer (or 'NULL') parameter columns per row before wrapping. 'NULL' (default) uses 'floor((getOption("width") - 23) / 12)'.

print

Either a scalar print-frequency ('0' = suppress, '1' (default) = every evaluation, 'N' = every Nth), OR a pre-built [iterPrintControl()] object. Equivalent to 'iterPrintControl(every = print, ncol = printNcol, useColor = useColor)'.

normType

Parameter normalization/scaling used to get scaled initial values for scaleType, of the form Vscaled = (Vunscaled-C1)/C2 (see Feature Scaling; rescale2 follows the OptdesX manual): "rescale2" scales all parameters to (-1, 1); "rescale" (min-max) scales to (0, 1); "mean" centers on the mean with range (0, 1); "std" standardizes by mean/sd; "len" scales to unit (Euclidean) length; "constant" performs no normalization (C1=0, C2=1).

scaleType

The scaling scheme for nlmixr2: "nlmixr2" (default) scales as (current-init)*scaleC[i] + scaleTo, with scaleTo from normType and scales from scaleC; "norm" uses the simple scaling from normType; "mult" scales multiplicatively as current/init*scaleTo; "multAdd" scales linearly ((current-init)+scaleTo) for parameters in an exponential block (e.g. exp(theta)) and multiplicatively otherwise.

scaleCmax

Maximum value of the scaleC to prevent overflow.

scaleCmin

Minimum value of the scaleC to prevent underflow.

scaleC

Scaling constant used with scaleType="nlmixr2"; when not specified, chosen by parameter type to keep gradient sizes similar on a log scale: '1' for exp()-transformed/power/boxCox/ yeoJohnson parameters, '0.5*abs(est)' for additive/proportional/ lognormal error parameters, 'abs(1/digamma(est+1))' for factorials, and 'log(abs(est))*abs(est)' for log-scale parameters. May be set explicitly per parameter if these defaults don't apply well.

scaleTo

Scale the initial parameter estimate to this value. By default this is 1. When zero or below, no scaling is performed.

gradTo

this is the factor that the gradient is scaled to before optimizing. This only works with scaleType="nlmixr2".

rxControl

'rxode2' ODE solving options during fitting, created with 'rxControl()'

optExpression

Optimize the rxode2 expression to speed up calculation. By default this is turned on.

sumProd

Is a boolean indicating if the model should change multiplication to high precision multiplication and sums to high precision sums using the PreciseSums package. By default this is FALSE.

literalFix

boolean, substitute fixed population values as literals and re-adjust ui and parameter estimates after optimization; Default is 'TRUE'.

literalFixRes

boolean, substitute fixed population values as literals and re-adjust ui and parameter estimates after optimization; Default is 'TRUE'.

returnOptim

logical; when TRUE this will return the optim list instead of the nlmixr2 fit object

addProp

Type of additive-plus-proportional error: '"combined1"', where standard deviations add:

y = f + (a + b\times f^c) \times \varepsilon

; or '"combined2"', where variances add:

y = f + \sqrt{a^2 + b^2\times f^{2\times c}} \times \varepsilon

. Here y = observed, f = predicted, a = additive sd, b = proportional/power sd, c = power exponent (1 in the proportional case).

eventSens

Controls how dosing/event-parameter ('alag', 'F', 'rate', 'dur') sensitivities are computed for THETA/ETA gradients: ‘"jump"' (default) uses rxode2’s analytic event sensitivities; '"fd"' uses the legacy finite-difference behavior.

sensMethod

Method used to compute the ODE parameter sensitivities. '"forward"' uses the classic variational (forward) sensitivity ODEs; '"default"' is the same thing.

calcTables

This boolean is to determine if the foceiFit will calculate tables. By default this is TRUE

compress

Should the object have compressed items

covMethod

allows selection of "r", which uses nlmixr2's 'nlmixr2Hess()' for the hessian calculation or "optim" which uses the hessian from 'stats::optim(.., hessian=TRUE)'

adjObf

is a boolean to indicate if the objective function should be adjusted to be closer to NONMEM's default objective function. By default this is TRUE

ci

Confidence level for some tables. By default this is 0.95 or 95% confidence.

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

sigdigTable

Significant digits in the final output table. If not specified, then it matches the significant digits in the 'sigdig' optimization algorithm. If 'sigdig' is NULL, use 3.

boundedTransform

When 'TRUE' (default), bounded parameters are transformed for unbounded optimization methods and back-transformed for final estimates. 'FALSE' optimizes on the original scale with bounds passed to the optimizer. 'NA' transforms for optimization but skips the final back-transform.

...

Further arguments to be passed to fn and gr.

Value

optimControl object for nlmixr2

Author(s)

Matthew L. Fidler

Examples


# A logit regression example with emax model

dsn <- data.frame(i=1:1000)
dsn$time <- exp(rnorm(1000))
dsn$DV=rbinom(1000,1,exp(-1+dsn$time)/(1+exp(-1+dsn$time)))

mod <- function() {
 ini({
   E0 <- 0.5
   Em <- 0.5
   E50 <- 2
   g <- fix(2)
 })
 model({
   v <- E0+Em*time^g/(E50^g+time^g)
   ll(bin) ~ DV * v - log(1 + exp(v))
 })
}

fit2 <- nlmixr(mod, dsn, est="optim", optimControl(method="BFGS"))
fit2


List all post-final-object processing hooks

Description

List all post-final-object processing hooks

Usage

postFinalObjectHooks(name = NULL)

Arguments

name

when specified, the name of the hook, otherwise 'NULL' to list all hooks

Value

a charcter vector listing all pre-processing hooks or the function for the hook

Author(s)

Matthew L. Fidler

See Also

Other preProcessHooks: postFinalObjectHooksAdd(), postFinalObjectHooksRm(), preFinalParTableHooks(), preFinalParTableHooksAdd(), preFinalParTableHooksRm(), preProcessHooks(), preProcessHooksAdd(), preProcessHooksRm()


Register a post-final-object hook run after estimation completes

Description

'fun' must take one argument ('ret') and return the finalized return object (or 'NULL'/nothing to leave it unchanged).

Usage

postFinalObjectHooksAdd(name, fun)

Arguments

name

Character vector representing the name of the hook

fun

The function to run

Value

The function that was added (invisibly)

Author(s)

Matthew L. Fidler

See Also

Other preProcessHooks: postFinalObjectHooks(), postFinalObjectHooksRm(), preFinalParTableHooks(), preFinalParTableHooksAdd(), preFinalParTableHooksRm(), preProcessHooks(), preProcessHooksAdd(), preProcessHooksRm()


Remove a post-final-object hook from nlmixr2est

Description

Warns if the hook does not exist.

Usage

postFinalObjectHooksRm(name)

Arguments

name

Character vector representing the name of the hook

Value

logical indicating if the hook was removed (invisibly)

Author(s)

Matthew L. Fidler

See Also

Other preProcessHooks: postFinalObjectHooks(), postFinalObjectHooksAdd(), preFinalParTableHooks(), preFinalParTableHooksAdd(), preFinalParTableHooksRm(), preProcessHooks(), preProcessHooksAdd(), preProcessHooksRm()


Control options for the posthoc estimation method

Description

This option is for simply getting the maximum a-prior (MAP) also called the posthoc estimates

Usage

posthocControl(sigdig = 3, ..., interaction = FALSE, maxOuterIterations = NULL)

Arguments

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

...

Parameters used in the default 'foceiConrol()'

interaction

Interaction term for the model, in this case the default is 'FALSE', though you can set it to be 'TRUE' as well.

maxOuterIterations

ignored, posthoc always sets this to 0.

Value

posthocControl object

Author(s)

Matthew L. Fidler

Examples


posthocControl()

List all pre-final parameter table processing hooks

Description

List all pre-final parameter table processing hooks

Usage

preFinalParTableHooks(name = NULL)

Arguments

name

when specified, the name of the hook, otherwise 'NULL' to list all hooks

Value

a charcter vector listing all pre-processing hooks or the function for the hook

Author(s)

Matthew L. Fidler

See Also

Other preProcessHooks: postFinalObjectHooks(), postFinalObjectHooksAdd(), postFinalObjectHooksRm(), preFinalParTableHooksAdd(), preFinalParTableHooksRm(), preProcessHooks(), preProcessHooksAdd(), preProcessHooksRm()


Register a pre-final parameter table hook run before final table assembly

Description

'fun' must take one argument ('env') and update it in place (e.g. 'cov', 'theta', 'thetaNames', 'thetaDf') before the final tables are built.

Usage

preFinalParTableHooksAdd(name, fun)

Arguments

name

Character vector representing the name of the hook

fun

The function to run

Value

The function that was added (invisibly)

Author(s)

Matthew L. Fidler

See Also

Other preProcessHooks: postFinalObjectHooks(), postFinalObjectHooksAdd(), postFinalObjectHooksRm(), preFinalParTableHooks(), preFinalParTableHooksRm(), preProcessHooks(), preProcessHooksAdd(), preProcessHooksRm()


Remove a pre-final parameter table hook from nlmixr2est

Description

Warns if the hook does not exist.

Usage

preFinalParTableHooksRm(name)

Arguments

name

Character vector representing the name of the hook

Value

logical indicating if the hook was removed (invisibly)

Author(s)

Matthew L. Fidler

See Also

Other preProcessHooks: postFinalObjectHooks(), postFinalObjectHooksAdd(), postFinalObjectHooksRm(), preFinalParTableHooks(), preFinalParTableHooksAdd(), preProcessHooks(), preProcessHooksAdd(), preProcessHooksRm()


List all pre-processing hooks

Description

List all pre-processing hooks

Usage

preProcessHooks(name = NULL)

Arguments

name

when specified, the name of the hook, otherwise 'NULL' to list all hooks

Value

a charcter vector listing all pre-processing hooks or the function for the hook

Author(s)

Matthew L. Fidler

See Also

Other preProcessHooks: postFinalObjectHooks(), postFinalObjectHooksAdd(), postFinalObjectHooksRm(), preFinalParTableHooks(), preFinalParTableHooksAdd(), preFinalParTableHooksRm(), preProcessHooksAdd(), preProcessHooksRm()


Register a pre-processing hook run before estimation begins

Description

'fun' must take four arguments ('ui', 'est', 'data', 'control') and return a list with any of ''ui'‘, '’est'‘, '’data'‘, '’control'' to override; a non-returned element is left unchanged.

Usage

preProcessHooksAdd(name, fun)

Arguments

name

Character vector representing the name of the hook

fun

The function to run

Value

The function that was added (invisibly)

Author(s)

Matthew L. Fidler

See Also

Other preProcessHooks: postFinalObjectHooks(), postFinalObjectHooksAdd(), postFinalObjectHooksRm(), preFinalParTableHooks(), preFinalParTableHooksAdd(), preFinalParTableHooksRm(), preProcessHooks(), preProcessHooksRm()


Remove a pre-processing hook from nlmixr2est

Description

Warns if the hook does not exist.

Usage

preProcessHooksRm(name)

Arguments

name

Character vector representing the name of the hook

Value

logical indicating if the hook was removed (invisibly)

Author(s)

Matthew L. Fidler

See Also

Other preProcessHooks: postFinalObjectHooks(), postFinalObjectHooksAdd(), postFinalObjectHooksRm(), preFinalParTableHooks(), preFinalParTableHooksAdd(), preFinalParTableHooksRm(), preProcessHooks(), preProcessHooksAdd()


Predict method for nlmixr2 fit core objects

Description

Generates population- or individual-level predictions from an 'nlmixr2FitCore' object.

Usage

## S3 method for class 'nlmixr2FitCore'
predict(object, ..., level = c("population", "individual"))

Arguments

object

nlmixr2 fit core object to predict

...

additional arguments passed to rxode2::rxSolve or nlmixr2; matching other 'predict' methods, these can include 'newdata' and 'rxControl' settings

level

the prediction level; one of '"population"' (default) or '"individual"'; numeric values '0' and '1' are also accepted

Value

A data frame with predictions

Examples




one.compartment <- function() {
 ini({
  tka <- log(1)
  tcl <- log(10)
  tv <- log(35)
  eta.ka ~ 0.1
  eta.cl ~ 0.1
  eta.v ~ 0.1
  add.sd <- 0.1
 })
 model({
  ka <- exp(tka + eta.ka)
  cl <- exp(tcl + eta.cl)
  v <- exp(tv + eta.v)
  d/dt(depot) = -ka * depot
  d/dt(center) = ka * depot - cl / v * center
  cp = center / v
  cp ~ add(add.sd)
 })
}

# The fit is performed by the function nlmixr/nlmix2 specifying
# the model, data and estimate
fit <- nlmixr2(one.compartment, theo_sd, est = "focei",
               foceiControl(maxOuterIterations = 0L))

# Population predictions
ppred <- predict(fit, theo_sd, level="population")

# Individual predictions
ipred <- predict(fit, theo_sd, level="individual")




Print an SAEM model fit summary

Description

Print an SAEM model fit summary

Usage

## S3 method for class 'saemFit'
print(x, ...)

Arguments

x

a saemFit object

...

others

Value

a list


Control for the qrpem (quasi-random parametric EM) estimation method

Description

A convenience wrapper around [impmapControl()] defaulting 'qr=TRUE' (Sobol quasi-random importance samples) and 'sir=TRUE' (SIR-accelerated non-mu / residual-error M-step); explicitly supplied arguments win. See [impmapControl()] for the full parameter list.

Usage

qrpemControl(..., qr = TRUE, sir = TRUE)

Arguments

...

Parameters passed to [impmapControl()].

qr

When 'TRUE', draw quasi-random (Sobol low-discrepancy) importance samples instead of pseudo-random Gaussian samples (QRPEM, Leary & Dunlavey PAGE 2012); the E-step integrals converge at O(1/N) instead of O(1/sqrt(N)).

sir

When 'TRUE', accelerate the non-mu / residual-error M-step by SIR (sampling-importance-resampling): the theta-sensitivity Newton step uses 'sirSample' equal-weight resampled points per subject instead of all 'isample' weighted samples.

Details

Note this is not know to be the same as the QRPEM implementation in Phoenix NLME since the details of their method are not public. However, this matches the QRPEM method of using quasi-random parametric EM and SIR accelerated parameter convergence described in Leary & Dunlavey (2012) PAGE 2012, 19(1): 1-6.

Value

An 'impmapControl' object with the QRPEM defaults.

Author(s)

Matthew L. Fidler

Examples


qrpemControl()

Objects exported from other packages

Description

These objects are imported from other packages. Follow the links below to see their documentation.

nlme

ACF(), augPred(), fixed.effects(), fixef(), getData(), getVarCov(), groupedData(), nlme(), pdBlocked(), pdCompSymm(), pdConstruct(), pdDiag(), pdFactor(), pdIdent(), pdLogChol(), pdMat(), pdMatrix(), pdNatural(), pdSymm(), random.effects(), ranef(), reStruct(), varComb(), varConstPower(), VarCorr(), varExp(), varFixed(), varFunc(), varIdent(), varPower(), varWeights()

rxode2

add.dosing(), add.sampling(), as.rxUi(), et(), et(), eventTable(), expit(), geom_amt(), geom_cens(), ini(), logit(), lotri, model(), probit(), probitInv(), rxCat(), rxClean(), rxControl(), rxInit(), rxLhs(), rxModelVars(), rxModelVarsS3(), rxode(), RxODE(), rxode2(), rxParam(), rxParams(), rxParams(), rxSolve(), rxSolve(), rxState(), rxUiDeparse(), stat_amt(), stat_cens()


Extract residuals from the FOCEI fit

Description

Extract residuals from the FOCEI fit

Usage

## S3 method for class 'nlmixr2FitData'
residuals(
  object,
  ...,
  type = c("ires", "res", "iwres", "wres", "cwres", "cpred", "cres")
)

Arguments

object

focei.fit object

...

Additional arguments

type

Residuals type fitted.

Value

residuals

Author(s)

Matthew L. Fidler


Remove an eta from the model

Description

Remove an eta from the model

Usage

rmEta(ui, eta)

Arguments

ui

rxode2 user interface

eta

eta to remove

Value

ui model with eta removed

Author(s)

Matthew L. Fidler

Examples


mod <- function ()  {
 description <- "One compartment PK model with linear clearance"
 ini({
   lka <- 0.45
   lcl <- 1
   lvc <- 3.45
    propSd <- c(0, 0.5)
    etaKa ~ 0.1
  })
 model({
   ka <- exp(lka + etaKa)
   cl <- exp(lcl)
   vc <- exp(lvc)
   Cc <- linCmt()
   Cc ~ prop(propSd)
 })
}

mod |> rmEta("etaKa")

# This can also remove more than one eta

mod <- function ()  {
 description <- "One compartment PK model with linear clearance"
 ini({
   lka <- 0.45
   lcl <- 1
   lvc <- 3.45
   propSd <- c(0, 0.5)
   etaKa ~ 0.1
   etaCl ~ 0.2
   etaVc ~ 0.3
  })
 model({
   ka <- exp(lka + etaKa)
   cl <- exp(lcl + etaCl)
   vc <- exp(lvc + etaVc)
   Cc <- linCmt()
   Cc ~ prop(propSd)
 })
}

mod |> rmEta(c("etaKa", "etaCl"))


This is a S3 method for getting the distribution lines for a base rxode2 focei problem

Description

This is a S3 method for getting the distribution lines for a base rxode2 focei problem

Usage

rxGetDistributionFoceiLines(line)

Arguments

line

Parsed rxode2 model environment

Value

Lines for the focei. This is based on the idea that the focei parameters are defined

Author(s)

Matthew Fidler


This is a S3 method for getting the distribution lines for a base rxode2 nlme problem

Description

This is a S3 method for getting the distribution lines for a base rxode2 nlme problem

Usage

rxGetDistributionNlmeLines(line)

Arguments

line

Parsed rxode2 model environment

Value

Lines for the focei. This is based on the idea that the focei parameters are defined

Author(s)

Matthew Fidler


This is a S3 method for getting the distribution lines for a base rxode2 nls problem

Description

This is a S3 method for getting the distribution lines for a base rxode2 nls problem

Usage

rxGetDistributionNlsLines(line)

## S3 method for class 'norm'
rxGetDistributionNlsLines(line)

## Default S3 method:
rxGetDistributionNlsLines(line)

Arguments

line

Parsed rxode2 model environment

Value

Lines for the focei. This is based on the idea that the focei parameters are defined

Author(s)

Matthew Fidler


Second-order eta sensitivities of the prediction for the exact log-likelihood ('ll()'/generalized) inner Hessian under 'fast=TRUE'.

Description

For a generalized endpoint 'rx_pred_' is the per-observation log-density, so its second eta-derivatives 'd2(rx_pred_)/deta_i deta_j' let 'calcEtaHessian' assemble the exact inner Hessian 'H = Omega^-1 - sum_obs d2(logLik)/deta2' analytically – mirroring the Gaussian Gauss-Newton 'sum(cHff*a*a)+Omega^-1' assembly – instead of the Shi21 finite difference of the inner gradient. Reuses the augmented-model second-order chain ('.g2', see [.foceiAnalyticAugModelDirs]). Stores on the symengine env '..HdEta2' (the 'rx__d2pred_i_j__' lhs lines, upper triangle i<=j) and '..sens2' (the second-order state-sensitivity ODEs). Only built for a fast generalized fit; the ordinary inner model is unchanged.

Usage

## S3 method for class 'foceiHdEta2'
rxUiGet(x, ...)

Arguments

x

list of rxode2 UI

...

ignored

Value

symengine env with '..HdEta2' and '..sens2' added


Get the ODE states of a model (rxode2 v3/v4 compatible)

Description

Calls rxode2::rxState() (or rxode2::rxStateOde() with rxode2 version 4) on the input.

Usage

rxode2stateOde(inp)

Arguments

inp

rxode2 model (or symengine environment) to query

Value

character vector of ODE state names

Author(s)

Matthew L. Fidler


Control Options for SAEM

Description

Control Options for SAEM

Usage

saemControl(
  seed = 99,
  nBurn = 200,
  nEm = 300,
  nmc = 3,
  nu = c(2, 2, 2),
  print = 1L,
  trace = 0,
  covMethod = c("sa", "analytic", "linFim", "fim", "r,s", "r", "s", "imp", ""),
  covMethodDeferred = NA_character_,
  covFull = TRUE,
  nSaCov = 500L,
  calcTables = TRUE,
  logLik = FALSE,
  nnodesGq = 3,
  nsdGq = 1.6,
  optExpression = TRUE,
  literalFix = FALSE,
  adjObf = TRUE,
  sumProd = FALSE,
  addProp = c("combined2", "combined1"),
  tol = NULL,
  itmax = 30,
  type = c("newuoa", "nelder-mead"),
  powRange = 10,
  lambdaRange = 3,
  odeRecalcFactor = 10^(0.5),
  maxOdeRecalc = 5L,
  indTolRelax = TRUE,
  perSa = 0.75,
  perNoCor = 0.75,
  perFixOmega = 0.1,
  perFixResid = 0.1,
  compress = TRUE,
  rxControl = NULL,
  sigdig = NULL,
  sigdigTable = NULL,
  ci = 0.95,
  muRefCov = TRUE,
  muRefCovAlg = TRUE,
  handleUninformativeEtas = TRUE,
  iovXform = c("sd", "var", "logsd", "logvar"),
  boundedTransform = TRUE,
  eventSens = c("jump", "fd"),
  mixProbMethod = c("regress", "regularized", "annealed"),
  mixProbStepExp = 1,
  mixProbPriorN = 20,
  mixSampleMethod = c("parallel", "msaem"),
  nonMuTheta = c("regress", "eta"),
  residWarmStart = TRUE,
  censOption = c("gauss", "laplace"),
  lbfgsLmm = 5L,
  lbfgsFactr = NULL,
  lbfgsPgtol = NULL,
  lbfgsMaxIter = 20L,
  ...
)

Arguments

seed

Random Seed for SAEM step. (Needs to be set for reproducibility.) By default this is 99.

nBurn

Number of iterations in the first phase, ie the MCMC/Stochastic Approximation steps. This is equivalent to Monolix's K_0 or K_b.

nEm

Number of iterations in the Expectation-Maximization (EM) Step. This is equivalent to Monolix's K_1.

nmc

Number of Markov Chains. By default this is 3. When you increase the number of chains the numerical integration by MC method will be more accurate at the cost of more computation. In Monolix this is equivalent to L.

nu

This is a vector of 3 integers. They represent the numbers of transitions of the three different kernels used in the Hasting-Metropolis algorithm. The default value is c(2,2,2), representing 40 for each transition initially (each value is multiplied by 20).

The first value represents the initial number of multi-variate Gibbs samples are taken from a normal distribution.

The second value represents the number of uni-variate, or multi- dimensional random walk Gibbs samples are taken.

The third value represents the number of bootstrap/reshuffling or uni-dimensional random samples are taken.

print

Either a scalar print-frequency ('0' = suppress, '1' (default) = every evaluation, 'N' = every Nth), OR a pre-built [iterPrintControl()] object. Equivalent to 'iterPrintControl(every = print, ncol = printNcol, useColor = useColor)'.

trace

An integer indicating if you want to trace(1) the SAEM algorithm process. Useful for debugging, but not for typical fitting.

covMethod

Method for calculating covariance. In this discussion, R is the Hessian matrix of the objective function. The S matrix is the sum of each individual's gradient cross-product (evaluated at the individual empirical Bayes estimates).

"sa" (default) Use the stochastic-approximation Fisher Information Matrix. After estimation, a dedicated covariance phase (nSaCov iterations) holds the parameters at the converged estimate and keeps resimulating the individual parameters, Monte-Carlo averaging the Louis observed-information integrand into a converged FIM decoupled from the cooling schedule (the approach used by Monolix; Kuhn & Lavielle 2005). Always includes every estimated population parameter (theta, the Omega diagonal variances, and residual).

"analytic" Compute the FOCEI analytic observed-information covariance at the converged SAEM estimates. When the model is out of analytic-covariance scope (e.g. linCmt(), a non-normal likelihood, or a non-SD IOV parameterization) or the result is not positive definite, it falls back to the linearized Fisher information (linFim) with a message.

"linFim" Use the Linearized Fisher Information Matrix to calculate the covariance.

"fim" Use the Fisher Information Matrix accumulated during SAEM estimation to calculate the covariance. Like sa it inverts the observed information to a full theta + Omega diagonal + residual covariance, but uses the (noisier) estimation-phase matrix rather than a dedicated cov phase.

For both fim and sa the simulation-based Fisher information covers the structural theta, the Omega diagonal variances, and additive residual error. Off-diagonal Omega covariances and proportional/combined residual error are not estimated reliably by the simulation FIM (the complete-data correction is unstable when between-subject variability dominates the residual), so those variance-block standard errors are spliced in from the linearized FIM (linFim).

"r,s" Uses the sandwich matrix to calculate the covariance, that is: R^-1 \times S \times R^-1

"r" Uses the Hessian matrix to calculate the covariance as 2\times R^-1

"s" Uses the crossproduct matrix to calculate the covariance as 4\times S^-1

"" Does not calculate the covariance step.

covMethodDeferred

Internal. When a foreign covariance ("sa"/"imp") is requested, it is stashed here and computed post-fit at the converged estimates by the decoupled recompute engine (setCov() uses the same path); NA otherwise.

covFull

Boolean (default TRUE) indicating the covariance should include every estimated population parameter – the structural and residual thetas plus the Omega variance/covariance elements – named om.<eta> / cov.<eta>.<eta>. When FALSE the legacy structural-theta-only covariance is reported. Ignored by covMethod="sa", which is always full.

nSaCov

Number of iterations in the dedicated stochastic-approximation covariance phase used by covMethod="sa" (default 500). These iterations run at the converged estimate (parameters frozen) and only resimulate the individual parameters to build the observed Fisher information; a larger value gives a less noisy covariance. Ignored by other covariance methods.

calcTables

This boolean is to determine if the foceiFit will calculate tables. By default this is TRUE

logLik

boolean indicating that log-likelihood should be calculate by Gaussian quadrature.

nnodesGq

number of nodes to use for the Gaussian quadrature when computing the likelihood with this method (defaults to 1, equivalent to the Laplacian likelihood)

nsdGq

span (in SD) over which to integrate when computing the likelihood by Gaussian quadrature. Defaults to 3 (eg 3 times the SD)

optExpression

Optimize the rxode2 expression to speed up calculation. By default this is turned on.

literalFix

boolean, substitute fixed population values as literals and re-adjust ui and parameter estimates after optimization; Default is 'TRUE'.

adjObf

is a boolean to indicate if the objective function should be adjusted to be closer to NONMEM's default objective function. By default this is TRUE

sumProd

Is a boolean indicating if the model should change multiplication to high precision multiplication and sums to high precision sums using the PreciseSums package. By default this is FALSE.

addProp

Type of additive-plus-proportional error: '"combined1"', where standard deviations add:

y = f + (a + b\times f^c) \times \varepsilon

; or '"combined2"', where variances add:

y = f + \sqrt{a^2 + b^2\times f^{2\times c}} \times \varepsilon

. Here y = observed, f = predicted, a = additive sd, b = proportional/power sd, c = power exponent (1 in the proportional case).

tol

This is the tolerance for the regression models used for complex residual errors (ie add+prop etc)

itmax

This is the maximum number of iterations for the regression models used for complex residual errors. The number of iterations is itmax*number of parameters

type

indicates the type of optimization for the residuals; Can be one of c("nelder-mead", "newuoa")

powRange

This indicates the range that powers can take for residual errors; By default this is 10 indicating the range is c(-10, 10)

lambdaRange

This indicates the range that Box-Cox and Yeo-Johnson parameters are constrained to be; The default is 3 indicating the range c(-3,3)

odeRecalcFactor

The ODE recalculation factor when ODE solving goes bad, this is the factor the rtol/atol is reduced

maxOdeRecalc

Maximum number of times to reduce the ODE tolerances and try to resolve the system if there was a bad ODE solve.

indTolRelax

When 'TRUE' (default), only subjects whose ODE solve produced NaN/Inf have their tolerances relaxed, and the relaxed tolerance persists across optimizer calls (sticky). When 'FALSE', all subjects have their tolerances relaxed on each retry and tolerances are reset afterward.

perSa

This is the percent of the time the 'nBurn' iterations in phase runs runs a simulated annealing.

perNoCor

This is the percentage of the MCMC phase of the SAEM algorithm where the variance/covariance matrix has no correlations. By default this is 0.75 or 75 Monte-carlo iteration.

perFixOmega

This is the percentage of the 'nBurn' phase where the omega values are unfixed to allow better exploration of the likelihood surface. After this time, the omegas are fixed during optimization.

perFixResid

This is the percentage of the 'nBurn' phase where the residual components are unfixed to allow better exploration of the likelihood surface.

compress

Should the object have compressed items

rxControl

'rxode2' ODE solving options during fitting, created with 'rxControl()'

sigdig

Specifies the "significant digits" that the ODE solving requests. This is NULL by default, and while it is NULL it has no effect at all: rxSolve() uses the standard atol/rtol (and the standard sensitivity and steady-state tolerances). sigdig only changes a tolerance when you ask for it explicitly.

When it is supplied, the tolerances are derived with one solver-independent formula – the same for stiff, non-stiff and auto-switching solvers. The rtol exponent IS sigdig and atol sits three orders below it:

  • rtol = 10^(-sigdig), atol = 10^(-sigdig-3)

  • the sensitivity tolerances match the main solve, so rtolSens = rtol and atolSens = atol (gradients and covariances are built from them)

  • the steady-state tolerances run one order looser than the corresponding main tolerance, so ssRtol = ssRtolSens = 10*rtol and ssAtol = ssAtolSens = 10*atol

Each of these is set only when you did not pass that tolerance yourself; a tolerance you supply always wins. Because they are resolved independently, an explicit atol/rtol overrides the main solve but does not propagate to the sensitivity or steady-state tolerances – set those directly if you need them changed too.

This mapping matches how nlmixr2est derives solver tolerances from its optimization sigdig, so a sigdig used for estimation and the same sigdig used for a plain rxSolve() mean the same thing. Note it is keyed to sigdig as a request for that many significant digits, and is looser than the atol/rtol defaults for small sigdig – at sigdig = 4 it gives rtol = 1e-4 against a default rtol = 1e-6. Raise sigdig, or set atol/rtol directly, when you want a tighter solve.

sigdigTable

Significant digits in the final output table. If not specified, then it matches the significant digits in the 'sigdig' optimization algorithm. If 'sigdig' is NULL, use 3.

ci

Confidence level for some tables. By default this is 0.95 or 95% confidence.

muRefCov

This controls if mu-referenced covariates in 'saem' are handled differently than non mu-referenced covariates. When 'TRUE', mu-referenced covariates have special handling. When 'FALSE' mu-referenced covariates are treated the same as any other input parameter.

muRefCovAlg

This controls if algebraic expressions that can be mu-referenced are treated as mu-referenced covariates by:

1. Creating a internal data-variable 'nlmixrMuDerCov#' for each algebraic mu-referenced expression

2. Change the algebraic expression to 'nlmixrMuDerCov# * mu_cov_theta'

3. Use the internal mu-referenced covariate for saem

4. After optimization is completed, replace 'model()' with old 'model()' expression

5. Remove 'nlmixrMuDerCov#' from nlmix2 output

In general, these covariates should be more accurate since it changes the system to a linear compartment model. Therefore, by default this is 'TRUE'.

handleUninformativeEtas

boolean that tells nlmixr2's saem to calculate uninformative etas and handle them specially (default is 'TRUE').

iovXform

Transformation used on the diagonal of the IOV: one of "sd", "var", "logsd", or "logvar".

boundedTransform

When 'TRUE' (default), bounded parameters are transformed for unbounded optimization methods and back-transformed for final estimates. 'FALSE' optimizes on the original scale with bounds passed to the optimizer. 'NA' transforms for optimization but skips the final back-transform.

eventSens

Controls how dosing/event-parameter ('alag', 'F', 'rate', 'dur') sensitivities are computed for THETA/ETA gradients: ‘"jump"' (default) uses rxode2’s analytic event sensitivities; '"fd"' uses the legacy finite-difference behavior.

mixProbMethod

For mixture models ('mix()', more than one component), stabilizes the mixing-probability estimate against collapsing onto a single component (the responsibility used to update it is itself weighted by the current mixing probability, which can create a runaway feedback loop). Three options:

* '"regress"' (default): treat per-subject mixture membership as a fixed regressor. Each subject is hard-classified to a component up front, held fixed, and fed into the solve (via the existing mixture-index regressor), skipping the per-iteration soft-EM responsibility step entirely. Avoids the responsibility feedback loop / collapse by construction and is lower-bias; on heavily overlapping components it is higher-variance (an early misclassification is not revisited), so prefer '"regularized"' when membership is genuinely uncertain.

* '"regularized"': blend 'mixProbPriorN' pseudo-subjects, distributed per the initial mixing probability, into the responsibility average each iteration (Dirichlet/MAP-EM-style). Prevents collapse even in difficult cases, at the cost of some bias toward the initial guess; may need larger 'nBurn'/'nEm'.

* '"annealed"': give the mixing-probability update its own decaying step-size schedule ('mixProbStepExp') instead of the full-replacement step used during 'nBurn'. Lower bias, but does not by itself fix a systematic (non-noise-driven) collapse.

mixProbStepExp

Only used when 'mixProbMethod="annealed"'. Decay exponent for the mixing-probability step size ('1/iteration^mixProbStepExp'), applied from iteration 1. Default 1; smaller values decay more slowly.

mixProbPriorN

Only used when 'mixProbMethod="regularized"'. Number of pseudo-subjects blended into the responsibility average each iteration. Larger values are more robust to collapse but bias the estimate more and need more 'nBurn'/'nEm'. Default 20.

mixSampleMethod

For mixture models with per-component etas (split-ETA, e.g. 'cl <- mix(tcl1 + eta.cl1, p1, tcl2 + eta.cl2)'), controls the MCMC/sufficient-statistic architecture for the individual random effects, independent of 'mixProbMethod'. BSV ('$omega') for split components is unreliable under '"parallel"' regardless of 'mixProbMethod'.

* '"parallel"' (default): one full MCMC chain per component per subject per iteration, blended post hoc by responsibility. Mirrors NONMEM's '$MIX' and correctly estimates BSV shared across components, but cannot cleanly separate per-component BSV for split-ETA models (each "wrong-hypothesis" chain still explores its non-owned column(s) as unconstrained prior noise).

* '"msaem"' (experimental): the MSAEM algorithm (Lavielle & Mbogning 2014), as used by Monolix. Simulates one random-effects trajectory per subject per iteration (label marginalized out via a closed-form responsibility) instead of parallel per-component chains, so no post-hoc blending is needed. Not compute-matched to '"parallel"' at equal 'nmc' – set 'nmc' to roughly 'nMix' times its default for a fair comparison. Uses a model-aware stratified initialization for split-ETA components that reliably achieves full theta/fixed-effect separation. Split-ETA BSV recovery is improved (two numerical bugs fixed: an 'IGamma2_phi1' blowup that locked variance to exactly zero, and an inverted responsibility sign) but still not reliable – it often settles at a safety-floor value rather than the true variance. Prefer '"parallel"' unless specifically evaluating this method.

nonMuTheta

Controls how a population 'theta' that is not mu-referenced (does not appear linearly with an eta – the SAEM 'phi0' fixed effects) is estimated.

* '"regress"' (default): keep the parameter as a plain directly-estimated 'theta' regressor. Each iteration 'phi0' is estimated by a bounded direct optimization of the observation likelihood (robust coordinate descent within a local trust region, honoring the 'ini' bounds), held fixed rather than drawn stochastically with a shrinking variance. This recovers population parameters that have no associated random effect more accurately, at some extra runtime (the objective re-solves the ODE).

* '"eta"': the historic SAEM treatment (the parameter is carried through the stochastic 'phi0' block).

residWarmStart

Boolean (default 'TRUE'); warm-start the residual-error parameters from the observed per-endpoint moments at the initial predictions (additive SD from 'sqrt(mean(err^2))', proportional SD from 'sqrt(mean((err/f)^2))'), the same moment estimate 'est="npag"' uses. Gives the stochastic step a better starting residual scale. Set 'FALSE' to start from the 'ini'-block residual values instead.

censOption

Treatment of the second derivative for censored (M2/M3/M4/BLQ) observations in the FOCEI family. "gauss" (the default) keeps the historic uncensored Gauss-Newton curvature, matching common PMx tools; "laplace" uses the exact censored second derivative of the objective (a proper Laplace inner Hessian and analytic covariance). Accepted by saemControl/nlmControl for a uniform interface but inert there – SAEM (stochastic EM) has no Laplace inner Hessian, and NLM uses a finite-difference Hessian that already reflects censoring exactly.

lbfgsLmm

Integer number of BFGS corrections (the L-BFGS-B 'lmm' memory) used when refining the fixed-effect-only parameters of a general log-likelihood model ('ll(name) ~ <expr>') by direct L-BFGS-B optimization of the observation likelihood. Default 5.

lbfgsFactr

Convergence tolerance on the relative reduction in the objective for that L-BFGS-B refinement (the 'factr' control, in units of machine epsilon). When 'NULL' (default) it is derived from 'sigdig' the same way as 'foceiControl()' ('10^(-sigdig) / .Machine$double.eps').

lbfgsPgtol

Convergence tolerance on the projected gradient for that L-BFGS-B refinement (the 'pgtol' control). When 'NULL' (default) it is derived from 'sigdig' ('10^(-sigdig)').

lbfgsMaxIter

Integer maximum number of iterations for that L-BFGS-B refinement. Default 20.

...

Other arguments to control SAEM.

Value

List of options to be used in nlmixr2 fit for SAEM.

Author(s)

Wenping Wang & Matthew L. Fidler

References

Kuhn E, Lavielle M (2005). "Maximum likelihood estimation in nonlinear mixed effects models." Computational Statistics & Data Analysis, 49(4), 1020-1038. doi:10.1016/j.csda.2004.07.002

Jiang L, Roy A, Balasubramanian K, Davis D, Drusvyatskiy D, Na S (2025). "Online Covariance Estimation in Nonsmooth Stochastic Approximation." arXiv:2502.05305. doi:10.48550/arXiv.2502.05305

See Also

Other Estimation control: foceiControl(), nlmixr2NlmeControl()


Set the covariance type based on prior calculated covariances

Description

Switches a completed fit's covariance to method. A previously computed covariance is re-installed from the cache; otherwise it is recomputed at the converged estimates: "r,s"/"r"/"s" and "analytic" on a zero-iteration FOCEI model, and "sa" (SAEM Louis FIM) / "imp" (importance-sampling Monte-Carlo) via the decoupled recompute engine (the latter two require a mixed-effects fit). When "sa"/"imp"/"analytic" cannot be computed the covariance is left unchanged (it is never silently downgraded to "r,s").

Usage

setCov(fit, method)

Arguments

fit

nlmixr2 fit

method

covariance method (see the 'covMethod' argument for the control options for the choices)

Value

Fit object with covariance updated

Author(s)

Matt Fidler

See Also

foceiControl(), saemControl()


Set/get Objective function type for a nlmixr2 object

Description

Set/get Objective function type for a nlmixr2 object

Usage

setOfv(x, type)

getOfvType(x)

Arguments

x

nlmixr2 fit object

type

Type of objective function to use for AIC, BIC, and $objective

Value

Nothing

Author(s)

Matthew L. Fidler


Return the square root of general square matrix A

Description

Return the square root of general square matrix A

Usage

sqrtm(m)

Arguments

m

Matrix to take the square root of.

Value

A square root general square matrix of m


Print an SAEM model fit summary

Description

Print an SAEM model fit summary

Usage

## S3 method for class 'saemFit'
summary(object, ...)

Arguments

object

a saemFit object

...

others

Value

a list


Output table/data.frame options

Description

Output table/data.frame options

Usage

tableControl(
  npde = NULL,
  cwres = NULL,
  nsim = 300,
  ties = TRUE,
  censMethod = c("truncated-normal", "cdf", "ipred", "pred", "epred", "omit"),
  seed = 1009,
  cholSEtol = (.Machine$double.eps)^(1/3),
  state = TRUE,
  lhs = TRUE,
  eta = TRUE,
  covariates = TRUE,
  addDosing = FALSE,
  subsetNonmem = TRUE,
  cores = NULL,
  keep = NULL,
  drop = NULL
)

Arguments

npde

When TRUE, request npde regardless of the algorithm used.

cwres

When TRUE, request CWRES and FOCEi likelihood regardless of the algorithm used.

nsim

represents the number of simulations. For rxode2, if you supply single subject event tables (created with ⁠[eventTable()]⁠)

ties

When 'TRUE' jitter prediction-discrepancy points to discourage ties in cdf.

censMethod

Handle censoring method:

- '"truncated-normal"' Simulates from a truncated normal distribution under the assumption of the model and censoring.

- '"cdf"' Use the cdf-method for censoring with npde and use this for any other residuals ('cwres' etc)

- '"omit"' omit the residuals for censoring

seed

an object specifying if and how the random number generator should be initialized

cholSEtol

The tolerance for the 'rxode2::choleSE' function

state

is a Boolean indicating if 'state' values will be included (default 'TRUE')

lhs

is a Boolean indicating if remaining 'lhs' values will be included (default 'TRUE')

eta

is a Boolean indicating if 'eta' values will be included (default 'TRUE')

covariates

is a Boolean indicating if covariates will be included (default 'TRUE')

addDosing

Boolean indicating if the solve should add rxode2 EVID and related columns. This will also include dosing information and estimates at the doses. Be default, rxode2 only includes estimates at the observations. (default FALSE). When addDosing is NULL, only include EVID=0 on solve and exclude any model-times or EVID=2. If addDosing is NA the classic rxode2 EVID events are returned. When addDosing is TRUE add the event information in NONMEM-style format; If subsetNonmem=FALSE rxode2 will also include extra event types (EVID) for ending infusion and modeled times:

  • EVID=-1 when the modeled rate infusions are turned off (matches rate=-1)

  • EVID=-2 When the modeled duration infusions are turned off (matches rate=-2)

  • EVID=-10 When the specified rate infusions are turned off (matches rate>0)

  • EVID=-20 When the specified dur infusions are turned off (matches dur>0)

  • ⁠EVID=101,102,103,...⁠ Modeled time where 101 is the first model time, 102 is the second etc.

subsetNonmem

subset to NONMEM compatible EVIDs only. By default TRUE.

cores

Number of cores used in parallel ODE solving. This is equivalent to calling setRxThreads()

keep

is the keep sent to the table

drop

is the dropped variables sent to the table

Details

Use addCwres to add CWRES/FOCEi objective function, or addNpde to add NPDE/EPRED columns.

Value

A list of table options for nlmixr2

Author(s)

Matthew L. Fidler


Control for uobyqa estimation method in nlmixr2

Description

Control for uobyqa estimation method in nlmixr2

Usage

uobyqaControl(
  npt = NULL,
  rhobeg = NULL,
  rhoend = NULL,
  iprint = 0L,
  maxfun = 100000L,
  returnUobyqa = FALSE,
  stickyRecalcN = 4,
  maxOdeRecalc = 5,
  odeRecalcFactor = 10^(0.5),
  indTolRelax = TRUE,
  useColor = NULL,
  printNcol = NULL,
  print = 1L,
  normType = c("rescale2", "mean", "rescale", "std", "len", "constant"),
  scaleType = c("nlmixr2", "norm", "mult", "multAdd"),
  scaleCmax = 1e+05,
  scaleCmin = 1e-05,
  scaleC = NULL,
  scaleTo = 1,
  rxControl = NULL,
  optExpression = TRUE,
  sumProd = FALSE,
  literalFix = TRUE,
  literalFixRes = TRUE,
  addProp = c("combined2", "combined1"),
  calcTables = TRUE,
  compress = FALSE,
  covMethod = c("r", ""),
  adjObf = TRUE,
  ci = 0.95,
  sigdig = 3,
  sigdigTable = NULL,
  boundedTransform = TRUE,
  eventSens = c("jump", "fd"),
  ...
)

Arguments

npt

Number of points for bobyqa's quadratic approximation to the objective; must be in '[n+2, (n+1)(n+2)/2]'. Defaults to '2*n + 1'. (bobyqa)

rhobeg

Initial trust region radius for the bobyqa outer optimizer (with 'rhoend', must satisfy '0 < rhoend < rhobeg'). Default '0.2' (20 'abs(upper-lower)/2'. (bobyqa)

rhoend

Final trust region radius. If not defined, '10^(-sigdig)' is used. (bobyqa)

iprint

Controls amount of printing ('0'=none, '1'=start/end only, '2'=each new rho, '3'=every function evaluation, '>3'=every 'iprint' evaluations). Default '0'.

maxfun

The maximum allowed number of function evaluations. If this is exceeded, the method will terminate.

returnUobyqa

return the uobyqa output instead of the nlmixr2 fit

stickyRecalcN

The number of bad ODE solves before reducing the atol/rtol for the rest of the problem.

maxOdeRecalc

Maximum number of times to reduce the ODE tolerances and try to resolve the system if there was a bad ODE solve.

odeRecalcFactor

The ODE recalculation factor when ODE solving goes bad, this is the factor the rtol/atol is reduced

indTolRelax

When 'TRUE' (default), only subjects whose ODE solve produced NaN/Inf have their tolerances relaxed, and the relaxed tolerance persists across optimizer calls (sticky). When 'FALSE', all subjects have their tolerances relaxed on each retry and tolerances are reset afterward.

useColor

Logical (or 'NULL') emit ANSI bold/color escapes in the iteration print. 'NULL' (default) defers to [crayon::has_color()].

printNcol

Integer (or 'NULL') parameter columns per row before wrapping. 'NULL' (default) uses 'floor((getOption("width") - 23) / 12)'.

print

Either a scalar print-frequency ('0' = suppress, '1' (default) = every evaluation, 'N' = every Nth), OR a pre-built [iterPrintControl()] object. Equivalent to 'iterPrintControl(every = print, ncol = printNcol, useColor = useColor)'.

normType

Parameter normalization/scaling used to get scaled initial values for scaleType, of the form Vscaled = (Vunscaled-C1)/C2 (see Feature Scaling; rescale2 follows the OptdesX manual): "rescale2" scales all parameters to (-1, 1); "rescale" (min-max) scales to (0, 1); "mean" centers on the mean with range (0, 1); "std" standardizes by mean/sd; "len" scales to unit (Euclidean) length; "constant" performs no normalization (C1=0, C2=1).

scaleType

The scaling scheme for nlmixr2: "nlmixr2" (default) scales as (current-init)*scaleC[i] + scaleTo, with scaleTo from normType and scales from scaleC; "norm" uses the simple scaling from normType; "mult" scales multiplicatively as current/init*scaleTo; "multAdd" scales linearly ((current-init)+scaleTo) for parameters in an exponential block (e.g. exp(theta)) and multiplicatively otherwise.

scaleCmax

Maximum value of the scaleC to prevent overflow.

scaleCmin

Minimum value of the scaleC to prevent underflow.

scaleC

Scaling constant used with scaleType="nlmixr2"; when not specified, chosen by parameter type to keep gradient sizes similar on a log scale: '1' for exp()-transformed/power/boxCox/ yeoJohnson parameters, '0.5*abs(est)' for additive/proportional/ lognormal error parameters, 'abs(1/digamma(est+1))' for factorials, and 'log(abs(est))*abs(est)' for log-scale parameters. May be set explicitly per parameter if these defaults don't apply well.

scaleTo

Scale the initial parameter estimate to this value. By default this is 1. When zero or below, no scaling is performed.

rxControl

'rxode2' ODE solving options during fitting, created with 'rxControl()'

optExpression

Optimize the rxode2 expression to speed up calculation. By default this is turned on.

sumProd

Is a boolean indicating if the model should change multiplication to high precision multiplication and sums to high precision sums using the PreciseSums package. By default this is FALSE.

literalFix

boolean, substitute fixed population values as literals and re-adjust ui and parameter estimates after optimization; Default is 'TRUE'.

literalFixRes

boolean, substitute fixed population values as literals and re-adjust ui and parameter estimates after optimization; Default is 'TRUE'.

addProp

Type of additive-plus-proportional error: '"combined1"', where standard deviations add:

y = f + (a + b\times f^c) \times \varepsilon

; or '"combined2"', where variances add:

y = f + \sqrt{a^2 + b^2\times f^{2\times c}} \times \varepsilon

. Here y = observed, f = predicted, a = additive sd, b = proportional/power sd, c = power exponent (1 in the proportional case).

calcTables

This boolean is to determine if the foceiFit will calculate tables. By default this is TRUE

compress

Should the object have compressed items

covMethod

Method for calculating the covariance. "r" (the default) uses nlmixr2's nlmixr2Hess() Hessian; "" skips the covariance step.

adjObf

is a boolean to indicate if the objective function should be adjusted to be closer to NONMEM's default objective function. By default this is TRUE

ci

Confidence level for some tables. By default this is 0.95 or 95% confidence.

sigdig

Optimization significant digits. One value drives, with a single consistent formula, the inner/outer optimizer convergence tolerance (10^-sigdig), the boundary check tolerance (5*10^(-sigdig+1)), and the ODE solver tolerances: the rtol exponent IS sigdig and atol sits three orders below, so rtol = 10^-sigdig, atol = 10^(-sigdig-3) for every solver (stiff, non-stiff or auto-switching). The sensitivity (atolSens/rtolSens) tolerances match the main solve (the outer gradient and covariance are built from them); the steady-state (ssAtol/ssRtol) tolerances run one order looser. Keying the optimizer to the same 10^-sigdig means it converges to exactly the precision the solve supports. At the default sigdig = 3 this is atol = 1e-6, rtol = 1e-3.

sigdigTable

Significant digits in the final output table. If not specified, then it matches the significant digits in the 'sigdig' optimization algorithm. If 'sigdig' is NULL, use 3.

boundedTransform

When 'TRUE' (default), bounded parameters are transformed for unbounded optimization methods and back-transformed for final estimates. 'FALSE' optimizes on the original scale with bounds passed to the optimizer. 'NA' transforms for optimization but skips the final back-transform.

eventSens

Controls how dosing/event-parameter ('alag', 'F', 'rate', 'dur') sensitivities are computed for THETA/ETA gradients: ‘"jump"' (default) uses rxode2’s analytic event sensitivities; '"fd"' uses the legacy finite-difference behavior.

...

Ignored parameters

Value

uobyqa control structure

Author(s)

Matthew L. Fidler

Examples



# A logit regression example with emax model

dsn <- data.frame(i=1:1000)
dsn$time <- exp(rnorm(1000))
dsn$DV=rbinom(1000,1,exp(-1+dsn$time)/(1+exp(-1+dsn$time)))

mod <- function() {
 ini({
   E0 <- 0.5
   Em <- 0.5
   E50 <- 2
   g <- fix(2)
 })
 model({
   v <- E0+Em*time^g/(E50^g+time^g)
   ll(bin) ~ DV * v - log(1 + exp(v))
 })
}

fit2 <- nlmixr(mod, dsn, est="uobyqa")

print(fit2)

# you can also get the nlm output with fit2$nlm

fit2$uobyqa

# The nlm control has been modified slightly to include
# extra components and name the parameters


Control for vae (variational autoencoder) estimation method in nlmixr2

Description

Variational-autoencoder NLME estimation (Rohleff et al., CPT:PSP 2025): an LSTM encoder learns the individual posterior q(eta|y) and an rxode2 decoder reconstructs the observations, trained on an ELBO / BICc-ELBO objective for simultaneous population-parameter estimation and covariate selection.

Usage

vaeControl(
  seed = 42L,
  itersBurnIn = 100L,
  klWarmup = 50L,
  gammaIter = 250L,
  iters = 300L,
  nGradStep = 5L,
  hiddenDim = 25L,
  learningRate = 0.005,
  burnInLearningRate = 0.008,
  sigma0 = NULL,
  covariateSelection = TRUE,
  pinCovariates = TRUE,
  muRefCovAlg = TRUE,
  shapes = c("power", "lin", "log", "identity", "center", "hockey"),
  covCenterType = c("median", "mean"),
  covCenter = NULL,
  catCutoff = 0.05,
  covSelectAlpha = 2,
  covSelectSmooth = TRUE,
  gammaSeries = c("reference", "saem"),
  sigma0Interp = c("sd", "reference"),
  residOptimize = c("twoStage", "moment", "optimize"),
  residRhoend = NULL,
  omegaUpdate = c("suffStat", "blend"),
  perNoCor = 0.75,
  inputScale = c("reference", "observed"),
  covSelectMethod = c("auto", "bnb", "l0learn"),
  covSelectMaxExact = 17L,
  bnbStrategy = c("lifo", "fifo", "lc"),
  parEncoderBackward = !isTRUE(getOption("nlmixr2.identical", FALSE)),
  nonMuTheta = c("regress", "grad", "eta", "fix", "none"),
  nonMuEtaOmega = 0.01,
  mStepObjective = c("outer", "elbo"),
  likelihood = c("focei", "foce", "focep", "laplace"),
  objf = c("importanceSampling", "linear"),
  nIsSample = 3000L,
  returnVae = FALSE,
  print = 1L,
  useColor = NULL,
  printNcol = NULL,
  covMethod = c("r,s", "analytic", "r", "s", "sa", "imp", ""),
  optExpression = TRUE,
  sumProd = FALSE,
  literalFix = TRUE,
  literalFixRes = TRUE,
  addProp = c("combined2", "combined1"),
  calcTables = TRUE,
  compress = FALSE,
  adjObf = TRUE,
  ci = 0.95,
  sigdig = 3,
  sigdigTable = NULL,
  rhoend = NULL,
  stickyRecalcN = 4,
  maxOdeRecalc = 5,
  odeRecalcFactor = 10^(0.5),
  outerStickyRecalcN = 4,
  outerMaxOdeRecalc = 5,
  outerOdeRecalcFactor = 10^(0.5),
  indTolRelax = TRUE,
  eventSens = c("jump", "fd"),
  rxControl = NULL,
  ...
)

Arguments

seed

Random seed for the VAE training (encoder init, Adam, reparameterization sampling); default 42. Training is stochastic, so a fixed seed makes every fit reproducible.

itersBurnIn

Number of burn-in iterations (encoder-only, tiny KL weight) before the main EM phase.

klWarmup

Number of KL-annealing iterations over which the KL weight is ramped from a small value to 1 (prevents posterior collapse).

gammaIter

Number of main iterations before the EMA-smoothing phase of the population-parameter update begins.

iters

Total number of main-loop iterations (after burn-in).

nGradStep

Number of Adam gradient steps per EM outer iteration (the reference 'L_iter').

hiddenDim

LSTM hidden dimension (the reference 'h_dim').

learningRate

Adam learning rate used in the main training phase.

burnInLearningRate

Adam learning rate used during burn-in.

sigma0

Encoder prior standard deviation(s) at initialization (a small value giving a sharp initial posterior). 'NULL' uses a small default per individual parameter. This is distinct from the 'ini()' omega.

covariateSelection

When 'TRUE' (default) perform automated BICc-ELBO covariate selection during training; when 'FALSE' fit only the covariate structure written in the model. In the 'FALSE' case the model-declared covariate coefficients (both linear 'beta*WT' effects and transformed ones such as 'beta*log(WT/70)') are estimated in place by the regress M-step regardless of 'nonMuTheta'; a 'ini(... ~ fix())' coefficient stays fixed.

pinCovariates

When 'TRUE' (default) and the model already declares covariate effects, restrict the automatic covariate selection to only the covariate/parameter pairs written in the model – the branch-and-bound search may still drop a declared covariate, but can never add one the model did not specify. A declared covariate that is not a valid search candidate (time-varying, or a raw-linear form that does not match the 'log'/centered encoding) is estimated in place by the regress M-step instead, with a note in '$runInfo'. When the model declares no covariates there is nothing to pin and the full search runs. Has no effect when 'covariateSelection' is 'FALSE'.

muRefCovAlg

When 'TRUE' (default) an algebraic/centered covariate effect written in the model (e.g. 'wt.cl*(WT/70)' or 'wt.cl*log(WT/70)') is handled as a mu2/mu3 reference: the covariate expression – including its centering – is evaluated into an internal 'nlmixrMuDerCov#' data column and the model uses the linear 'wt.cl*nlmixrMuDerCov#' form during fitting, so the VAE covariate search never re-centers it. The original expression is restored in the reported model.

shapes

Which parameterizations ("shapes") of a continuous covariate the automatic search may consider, using the same vocabulary as 'nlmixr2scm::runSCM()': '"power"' ('beta*log(COV/ctr)'), '"lin"' ('beta*(COV - ctr)'), '"log"' ('beta*log(COV)'), '"identity"' ('beta*COV') and '"center"' ('beta*(COV/ctr)'). '"hockey"' is a two-armed piecewise linear relationship knotted at the centering value, written as 'beta.low*(COV < ctr)*(COV - ctr) + beta.hi*(COV >= ctr)*(COV - ctr)'; both arms enter or neither does, and it is skipped for a covariate with fewer than 'catCutoff' of the subjects on one side of the knot. At most one shape of a covariate may enter a given parameter. Because the selection objective is an ordinary least squares fit with a free intercept, '"power"'/'"log"' span the same model, as do '"lin"'/'"identity"'/'"center"'; the shape therefore decides how an accepted relationship is written back, and when several eligible shapes span the same model the one listed first wins. '"hockey"' spans a strictly larger model than the linear shapes and costs two coefficients rather than one.

May also be a **list**, whose elements are dispatched individually so the two forms mix freely: an element named by covariate ('WT = "power"') is shorthand for the covariate-wide rule 'list(covar = "WT", shapes = "power")', and a 'list(var=, covar=, shapes=)' element restricts one parameter/covariate pair. The most specific rule wins – 'var'+'covar' beats 'covar', which beats 'var', which beats a rule naming neither – and ties go to the rule listed last.

In the list form, **naming a covariate also puts it in the search**. 'fixCov = TRUE' (the default, given as an element of the list) fixes the searched set to exactly the covariates named, so 'shapes = list(WT = "power")' searches 'WT' and nothing else. Add 'fixCov = FALSE' to restrict parameterizations without restricting the search, which is what the list form meant previously. A shape value of 'TRUE' means "eligible, default shapes", and is how a categorical covariate is named ('list(WT = "power", SEX = TRUE)') since a categorical takes no parameterization. A 'var'-only rule makes every covariate eligible on that parameter alone; a rule naming neither 'var' nor 'covar' contradicts 'fixCov = TRUE' and is an error. A character vector names no covariate, so 'fixCov' does not apply and every covariate stays searchable.

'fixCov' is ignored when the model itself declares covariate effects: that already restricts the search (see 'pinCovariates') and the declaration is the more specific statement. The disagreement is reported in '$runInfo', as is every covariate 'fixCov' excludes. Categorical covariates always enter as indicators and take no shape, but 'fixCov' still governs whether they are searched at all.

covCenterType

Statistic used to center a continuous covariate, '"median"' (default) or '"mean"', computed over subjects rather than rows.

covCenter

Named numeric vector of centering values overriding 'covCenterType' for those covariates, e.g. 'c(WT = 70)'. Names are matched case-insensitively.

catCutoff

Minimum proportion of subjects a non-reference level must hold to get its own indicator. Rarer levels are lumped with the reference. Default '0.05'; '0' tests every level.

covSelectAlpha

Starting multiplier for the covariate-selection L0 penalty, ramped linearly from 'covSelectAlpha' down to '1' over the 'klWarmup' warmup iterations and held at '1' afterward (matching the reference implementation's 'linspace(alpha, 1, kl_iter)'). Values '> 1' penalize covariate entry more heavily early in training; '1' disables the ramp.

covSelectSmooth

When 'TRUE' (default) the covariate selection regresses the SAEM sufficient statistic – an exponential moving average of the posterior means, updated with the same gain as the M-step – rather than the current posterior means. This matches the reference implementation (Rohleff et al. 2025), which is the reason for the default. In practice it changes little: 'gamma' is exactly 1 until 'gammaIter', so the statistic equals the posterior mean for most of a run and is averaged only over the closing tail. 'FALSE' regresses the current posterior means.

gammaSeries

Decaying step-size series used once the smoothing phase starts (after 'gammaIter'); the gain is 1 throughout the EM phase either way.

* '"reference"' (default): '1/(iter - gammaIter)', the textbook Kuhn-Lavielle series the reference implementation uses. The first smoothing step is still a full replacement, and the decay follows. * '"saem"': '1/(1 + iter - gammaIter)', the CONTINUATION form saemControl() uses – nlmixr2est's SAEM builds its series so it continues rather than repeating a gain of 1, so the decay begins at '1/2'. Select this to match the step-size convention of the other nlmixr2 estimation methods rather than the reference.

sigma0Interp

How ‘sigma0' is turned into the encoder’s initial posterior spread. The encoder head emits 'logSigma' and forms 'diag(L) = exp(logSigma)', so 'diag(L)' is the posterior standard deviation.

* '"sd"' (default): the bias is 'log(sigma0)', so the initial posterior SD is 'sigma0' – what the argument says it is. * '"reference"': the bias is 'log(sigma0^2)', matching the reference implementation, whose initial posterior SD is therefore 'sigma0' SQUARED ('1e-6' rather than '1e-3' for the first neonatal dimension). The reference documents 'sigma0' as a standard deviation, so this appears to be unintended there; it is offered only to reproduce its published behavior.

residOptimize

How the residual-error parameters are estimated.

Residual forms the optimizer estimates: 'add', 'prop', 'add + prop', 'pow', 'lnorm', and a 'boxCox' or 'yeoJohnson' lambda (bounded to '(-2, 2)'). For a transform-both-sides model the objective transforms 'dv' only and carries the log-Jacobian, since 'f' leaves the solve already on the transformed scale.

'nonMuTheta = "grad"' bypasses this entirely: the analytic outer gradient already carries a residual sigma and a transform lambda as its own directions, so those parameters are stepped by the gradient through Adam and the two-stage path never runs. Which converges better is model-dependent.

* '"moment"': the closed-form moment estimator. For a model with a single additive error this is exactly the optimum ('sqrt(SSE/n)'); for any other error model it is either a different estimator or, for the forms with no closed form ('pow', Box-Cox, Yeo-Johnson), no estimator at all – the parameter stays at its 'ini()' value. There is no moment estimator for a log-likelihood ('ll()') parameter either, so those also stay at 'ini()'; use '"twoStage"' for such a model. * ‘"twoStage"' (default): block coordinate descent, as 'npag'’s 'residOptimize = "alternate"' does. Stage one optimizes the non-mu-referenced structural thetas with the residual parameters held, so it is driven by '(dv - f)'; stage two then holds those and optimizes the residual parameters alone against the extended least-squares objective 'sum[(y-f)^2/r + log r]' over the CACHED '(y, f)' pairs. Because 'f' is fixed by stage one, stage two needs no ODE re-solve – the same structure SAEM uses. On 'theo_sd' this beats the moment estimator on both a pure-additive model (objective 131.79 vs 131.81) and a combined one (121.03 vs 122.47).

Which parameters stage two owns is decided per parameter: an error parameter, or one that no 'd/dt()' right-hand side, initial condition or dosing modifier can reach. The second case is what a log-likelihood ('ll()') or generalized endpoint needs – its residual-like parameters are plain thetas with no error row, and on the error-only rule stage two was empty for such a model, silently making '"twoStage"' behave like '"optimize"'. When no regressed theta qualifies (every one feeds the solve) stage two has nothing to do and 'residOptimize' has no effect. * '"optimize"' (EXPERIMENTAL, diagnostic): a single JOINT solve over the structural and residual parameters together, against the full outer objective. Fine with one free residual parameter, but with 'add' and 'prop' both free it diverges – they are near-collinear, and routing the residual through the full outer objective lets the Laplace terms move with it at frozen etas (objective 320.7 against the moment estimator's 122.5). Retained for comparison; prefer '"twoStage"'.

residRhoend

Final trust-region radius ('rhoend') of the bounded 'bobyqa' that estimates the residual parameters – its convergence tolerance. 'NULL' (default) derives it from 'sigdig' ('10^(-sigdig)'), the same way every other optimizer tolerance in the package is derived, so 'sigdig' stays the single knob that moves them together. Set it explicitly when the residual step should converge tighter than the rest: it runs with the ODE frozen, so tightening it is far cheaper than tightening 'rhoend', which also tightens the structural regression that re-solves per candidate.

omegaUpdate

How the population variances are updated in the covariate M-step. '"suffStat"' (default) follows the reference: 'omega' is formed from the EMA sufficient statistics and ASSIGNED outright. '"blend"' is the historic behavior, blending the freshly computed 'omega' with the previous value at the M-step gain (so it is smoothed twice). Applies to 'omega' only.

Note this option reaches only ONE of the two omega M-steps. Which one runs is decided by 'covariateSelection': with 'TRUE' the covariate M-step runs and honors 'omegaUpdate'; with 'FALSE' the plain closed-form M-step runs, whose variances are always raw posterior moments blended at the gain. A declared correlated block's OFF-diagonals always follow whichever estimator that branch's diagonal used – estimating the two halves of one block by different estimators need not even give a positive-definite result.

The two settings are the SAME update while the gain is 1, which it is throughout burn-in and the EM phase (assigning a value and blending it in with weight 1 are the same operation); they differ only once 'gammaIter' decays the gain. A short run at default settings will show no difference.

'mStepObjective' does not enter the omega update at all – it scores the non-mu theta M-step. Omega has a closed-form EM update from the variational posterior either way.

The residual error estimate is still EMA-smoothed on the standard-deviation scale, where the reference smooths the residual sum of squares and takes the root afterwards – a known remaining difference. Matching it would need per-endpoint sufficient statistics plus an optimizer branch for the error models with no closed form ('add + prop', 'add + pow', Box-Cox / Yeo-Johnson), as saemControl() does.

perNoCor

Fraction of the EM phase ('gammaIter' iterations) over which a declared correlated 'omega' block is held at zero correlation, letting the variances settle before the correlations are estimated. This is saemControl()'s 'perNoCor' rule (0.75 there as well); it has no effect on a model with no declared off-diagonals.

Held at ZERO, following saem, not at the 'ini()' value: retaining an initial covariance while the variances shrink around it can leave the block non-positive-definite. A 'fixed()' covariance is exempt – it is not being estimated, so it keeps its value through the hold and out the other side.

The fraction is of the EM phase, 'min(gammaIter, iters)', not of the whole run. That matters: the gain is 1 for 'it <= gammaIter', so the release point falls while the gain is still 1 and the correlations are estimable the moment they are unfrozen. (This is why no gain restart is needed here, whereas emviControl() – whose run has no separate unit-gain phase – has to restart the off-diagonal gain at release.)

A value greater than 1 is an ABSOLUTE iteration count rather than a fraction, and must be a whole number. Prefer the absolute form whenever a run may be resumed or reproduced at a different length: a fraction of a shorter run is a different schedule, not the same one truncated.

inputScale

Which observations the encoder-input centering and scaling are computed over. '"reference"' (default) matches the reference implementation, which takes the mean and SD across the whole padded observation matrix, so the zero padding of subjects with fewer observations enters both statistics. On a ragged dataset that is a materially different scale from '"observed"', which uses only the observed values (on the neonatal case study the SD is 1582 against 506). Affects only the encoder's inputs, never the likelihood.

covSelectMethod

How the covariate M-step searches subsets. '"bnb"' is the exact branch-and-bound; it becomes impractical past a few dozen candidate covariates. '"l0learn"' has the 'L0Learn' package propose supports, which are then scored and polished with the same exact objective – so the search is approximate but the scoring is not. '"auto"' (default) uses '"l0learn"' for a latent dimension with at least 'covSelectMaxExact' candidate covariates and '"bnb"' otherwise. Set 'covSelectMaxExact = Inf' to force the exact search everywhere.

covSelectMaxExact

Search size at or above which 'covSelectMethod = "auto"' switches a latent dimension to 'L0Learn' (default '17', just above the measured wall-clock crossover of roughly 16 bits – see 'tools/benchVaeCovSelect.R', which finds the same crossover in bits whether a covariate carries one shape or two). Measured in bits of feasible-support space – 'sum over covariates of log2(1 + shapes tried)' – after 'pinCovariates' trimming, so it is the size of the search actually run. One shape per covariate costs exactly 1 bit, so with 'shapes' set to a single shape this is a plain candidate count; two shape families of one covariate cost ‘log2(3)', keeping the exact search’s worst-case node budget the same either way. 'Inf' forces the exact branch-and-bound everywhere.

bnbStrategy

Frontier discipline for the exact branch-and-bound covariate selection: '"lifo"' (default, last-in-first-out depth-first search), '"fifo"' (first-in-first-out) or '"lc"' (least cost / best-first). The solver is exact, so the selected covariates are identical for every strategy; only the search order (and thus efficiency) differs.

parEncoderBackward

Parallelize the encoder backward (gradient) pass over subjects. Defaults to 'TRUE' unless 'options(nlmixr2.identical = TRUE)' is set (which flips the default to 'FALSE'); an explicit value here always wins. The encoder forward pass and the covariate branch-and-bound already run multi-threaded and are bit-identical to the serial run. The backward gradient is a continuous cross-subject sum, so parallelizing it (per-thread partials reduced in thread order) makes the result deterministic for a fixed number of 'cores' but no longer bit-identical to the serial path: the per-step gradient differs at ~1e-12, which compounds through the iterative SGD/EM training to a small final difference (well below any estimation tolerance), and results may differ across different 'cores'. When it is active (and 'cores > 1') a note is added to the fit's '$runInfo'. Set this to 'FALSE' – or globally 'options(nlmixr2.identical = TRUE)' – for bit-identical, fully reproducible results.

nonMuTheta

How to treat a structural population 'theta' that has no random effect (is not mu-referenced) so it can still be estimated by the VAE (which only estimates parameters that occupy the latent space). For the eta-injection modes a small eta is injected so the parameter enters the latent space, and the reported fixed effect is 'theta + mean(eta)' with the temporary eta dropped from the output model.

* '"regress"' (default, matching 'saemControl(nonMuTheta=)'): no eta is injected; instead each such theta is estimated directly, re-optimized every M-step by a bounded 'bobyqa' regression against the full FOCEi outer objective (bounds from the 'ini()' lower/upper), blended with the M-step gain. 'mStepObjective' selects which objective that regression targets. This recovers a no-random-effect population parameter without adding a spurious random effect. 'nonMuEtaOmega' is unused in this mode. * '"grad"': same target as '"regress"' but stepped with the EXACT analytic outer gradient (Almquist sensitivity equations, the machinery behind 'foceiControl(fast=TRUE)') instead of a derivative-free search: one augmented sensitivity solve per M-step replaces the bobyqa sweep. Both modes optimize the same full outer objective (with every mu-referenced theta held at its current M-step value), so this changes the optimizer, not the target. It is also the more natural fit for the method: the gradient is handed to the SAME Adam machinery that moves the encoder weights, so the parameter is learned alongside the rest of the model on a shared schedule (same gain, same KL warmup gate), whereas '"regress"' pauses each M-step to run a separate derivative-free optimizer to convergence and adopts its answer. This is NOT a speed option – it is measurably SLOWER than '"regress"' (on 'theo_sd', 1.47x with one non-mu theta and 1.13x with three; the gap narrows as the number grows, since bobyqa's cost scales in it and a single solve does not, but it does not close). Choose it for accuracy: the exact gradient lands closer to the maximum-likelihood value than the derivative-free search ('theo_sd' non-mu 'tv': 3.4294 vs 3.4324, against a FOCEi MLE of 3.4293). Applies to a conditionally Gaussian model and to a single non-Gaussian ('ll()'/generalized) endpoint, which differentiates the log-density directly. Falls back to '"regress"' when the model is out of analytic scope ('linCmt()', IOV, 'fo', a multi-endpoint or censored 'll()' model, ...); 'nonMuEtaOmega' is unused. * '"eta"': inject the eta with an ESTIMATED omega (starting at 'nonMuEtaOmega'); the typical value is estimated and appears in the iteration table. * '"fix"': inject the eta with omega held FIXED at 'nonMuEtaOmega' AND hold the typical-value theta fixed at its 'ini()' value. Nothing about the parameter is estimated, so it is not shown in the iteration table (it is reported at its 'ini()' value, marked fixed, with the injected eta dropped). * '"none"': leave non-mu-referenced thetas frozen at their 'ini()' value (the historic behavior).

nonMuEtaOmega

Variance of the eta injected for a non-mu-referenced theta (starting value for 'nonMuTheta="eta"', fixed value for 'nonMuTheta="fix"'; unused for '"regress"').

mStepObjective

Objective the non-mu-referenced theta M-step ('nonMuTheta = "regress"' or '"grad"') is optimized against. It has no effect when there is no non-mu-referenced structural theta, and it never changes the encoder/ELBO training step or the covariate branch-and-bound criterion, both of which always follow the reference.

* '"outer"' (default): the full FOCEi outer objective – the frozen-eta joint likelihood PLUS the Laplace determinant, '0.5*log|Omega^-1|' and the DV-transform Jacobian. This is a deliberate deviation from Rohleff et al. (2025): it keeps the quantity being optimized equal to the objective the fit reports, and it is the functional the analytic outer gradient differentiates, so 'nonMuTheta = "grad"' optimizes one target rather than stepping one and scoring another. * '"elbo"': the reference behavior – the plain variational bound (frozen-eta joint likelihood, no Laplace term), matching the M-step in Rohleff et al. (2025). Use it to reproduce the reference implementation. The analytic outer gradient does not apply to this objective, so 'nonMuTheta = "grad"' is downgraded to '"regress"' with a note in '$runInfo'.

The two objectives differ by terms that depend on the non-mu thetas through the eta Hessian, so they can land on different estimates, and – because those estimates feed the latent means the covariate search regresses on – on different covariate sets.

likelihood

Inner likelihood used for the objective, EBEs, and gradients, all run through the same FOCEi inner interface: '"focei"' (default, with eta-epsilon interaction), '"foce"' (no interaction, NONMEM FOCE with R frozen at the population prediction), '"focep"' (FOCE+, no interaction but R evaluated at the live conditional eta), or '"laplace"'.

objf

Which objective-function value is active for AIC/BIC/BICc. Both the linearization and importance-sampling -2LL are always computed and stored; this selects the default active one.

nIsSample

Number of importance-sampling draws for the IS -2LL.

returnVae

When 'TRUE' return the raw VAE training object instead of the nlmixr2 fit.

print

Either a scalar print-frequency ('0' = suppress, '1' (default) = every evaluation, 'N' = every Nth), OR a pre-built [iterPrintControl()] object. Equivalent to 'iterPrintControl(every = print, ncol = printNcol, useColor = useColor)'.

useColor

Logical (or 'NULL') emit ANSI bold/color escapes in the iteration print. 'NULL' (default) defers to [crayon::has_color()].

printNcol

Integer (or 'NULL') parameter columns per row before wrapping. 'NULL' (default) uses 'floor((getOption("width") - 23) / 12)'.

covMethod

Method for calculating the covariance at the VAE estimates, run through the FOCEi covariance step; the same choices as foceiControl(): "analytic" (default), "r,s", "r", "s", or "" to skip.

optExpression

Optimize the rxode2 expression to speed up calculation. By default this is turned on.

sumProd

Is a boolean indicating if the model should change multiplication to high precision multiplication and sums to high precision sums using the PreciseSums package. By default this is FALSE.

literalFix

boolean, substitute fixed population values as literals and re-adjust ui and parameter estimates after optimization; Default is 'TRUE'.

literalFixRes

boolean, substitute fixed population values as literals and re-adjust ui and parameter estimates after optimization; Default is 'TRUE'.

addProp

Type of additive-plus-proportional error: '"combined1"', where standard deviations add:

y = f + (a + b\times f^c) \times \varepsilon

; or '"combined2"', where variances add:

y = f + \sqrt{a^2 + b^2\times f^{2\times c}} \times \varepsilon

. Here y = observed, f = predicted, a = additive sd, b = proportional/power sd, c = power exponent (1 in the proportional case).

calcTables

This boolean is to determine if the foceiFit will calculate tables. By default this is TRUE

compress

Should the object have compressed items

adjObf

is a boolean to indicate if the objective function should be adjusted to be closer to NONMEM's default objective function. By default this is TRUE

ci

Confidence level for some tables. By default this is 0.95 or 95% confidence.

sigdig

Specifies the "significant digits" that the ODE solving requests. This is NULL by default, and while it is NULL it has no effect at all: rxSolve() uses the standard atol/rtol (and the standard sensitivity and steady-state tolerances). sigdig only changes a tolerance when you ask for it explicitly.

When it is supplied, the tolerances are derived with one solver-independent formula – the same for stiff, non-stiff and auto-switching solvers. The rtol exponent IS sigdig and atol sits three orders below it:

  • rtol = 10^(-sigdig), atol = 10^(-sigdig-3)

  • the sensitivity tolerances match the main solve, so rtolSens = rtol and atolSens = atol (gradients and covariances are built from them)

  • the steady-state tolerances run one order looser than the corresponding main tolerance, so ssRtol = ssRtolSens = 10*rtol and ssAtol = ssAtolSens = 10*atol

Each of these is set only when you did not pass that tolerance yourself; a tolerance you supply always wins. Because they are resolved independently, an explicit atol/rtol overrides the main solve but does not propagate to the sensitivity or steady-state tolerances – set those directly if you need them changed too.

This mapping matches how nlmixr2est derives solver tolerances from its optimization sigdig, so a sigdig used for estimation and the same sigdig used for a plain rxSolve() mean the same thing. Note it is keyed to sigdig as a request for that many significant digits, and is looser than the atol/rtol defaults for small sigdig – at sigdig = 4 it gives rtol = 1e-4 against a default rtol = 1e-6. Raise sigdig, or set atol/rtol directly, when you want a tighter solve.

sigdigTable

Significant digits in the final output table. If not specified, then it matches the significant digits in the 'sigdig' optimization algorithm. If 'sigdig' is NULL, use 3.

rhoend

Final trust-region radius ('rhoend') of the inner bounded 'bobyqa' used by the non-mu / covariate regress M-step. 'NULL' (default) derives it from 'sigdig' ('10^(-sigdig)', matching the optimizer convergence tolerance), or '1e-4' when 'sigdig' is 'NULL'.

stickyRecalcN

The number of bad ODE solves before reducing the atol/rtol for the rest of the problem.

maxOdeRecalc

Maximum number of times to reduce the ODE tolerances and try to resolve the system if there was a bad ODE solve.

odeRecalcFactor

The ODE recalculation factor when ODE solving goes bad, this is the factor the rtol/atol is reduced

outerStickyRecalcN

The number of bad analytic outer solves for a subject before its loosened tolerance is kept for the rest of the problem; the outer counterpart of 'stickyRecalcN'.

outerMaxOdeRecalc

Maximum number of times to reduce the ODE tolerances for a single subject and retry when the analytic outer (augmented sensitivity) solve fails. Tracked separately from 'maxOdeRecalc', which governs the inner problem. A subject that solves after loosening still contributes an analytic gradient instead of dropping the whole gradient to finite differences.

outerOdeRecalcFactor

The factor the atol/rtol is loosened by on each analytic outer retry; the outer counterpart of 'odeRecalcFactor'.

indTolRelax

When 'TRUE' (default), only subjects whose ODE solve produced NaN/Inf have their tolerances relaxed, and the relaxed tolerance persists across optimizer calls (sticky). When 'FALSE', all subjects have their tolerances relaxed on each retry and tolerances are reset afterward.

eventSens

Controls how dosing/event-parameter ('alag', 'F', 'rate', 'dur') sensitivities are computed for THETA/ETA gradients: ‘"jump"' (default) uses rxode2’s analytic event sensitivities; '"fd"' uses the legacy finite-difference behavior.

rxControl

'rxode2' ODE solving options during fitting, created with 'rxControl()'

...

Other arguments to control SAEM.

Details

Covariate selection – MIQP vs. branch-and-bound. Per latent parameter the selection step minimizes the same L0/BIC objective 'RSS_S/omega + log(N)*|S|' over subsets 'S' of the candidate covariates ('RSS_S' is the residual sum of squares of the ordinary-least-squares fit on the intercept plus 'S'). The reference implementation (Rohleff et al.) writes this as a Mixed-Integer Quadratic Program (MIQP) – binary include/exclude indicators with big-M constraints – and solves it with the commercial Gurobi solver through 'cvxpy'. No MIQP-capable solver is freely available in R: Gurobi is commercial/licensed, and the open QP solvers on CRAN (e.g. 'osqp') are continuous-only and cannot represent the binary selection. A continuous convex relaxation (L1 / lasso) would be solvable but only approximates best subset.

This package instead solves the identical L0/BIC objective EXACTLY with a self-contained branch-and-bound: each candidate support's coefficients are the closed-form OLS fit and branches are pruned by a valid lower bound (the RSS of the OLS fit using all still-free covariates). It therefore returns the same optimum the MIQP would – no commercial dependency and no relaxation/accuracy loss – and scales to a few dozen covariates. The search is worst-case exponential in the number of covariates, but the pruning makes the practical (sparse) case fast (e.g. 32 candidate covariates in a fraction of a second).

Value

vae control structure (class 'vaeControl')

Author(s)

Matthew L. Fidler


Covariates explored by the VAE covariate search

Description

Returns the candidate columns that 'nlmixr2(..., est = "vae")' would explore during automated covariate selection, using the same discovery rules as the fit: every non-reserved data column that is constant within each subject is a candidate. A numeric candidate with more than two unique values is continuous and contributes one column per eligible shape; anything else is categorical and contributes an indicator per testable level. Columns sharing a 'group' are alternate shapes of one covariate, so at most one of them can enter a given parameter. Time-varying columns cannot be searched and are excluded with a warning.

Usage

vaeCovariates(
  data,
  warn = TRUE,
  shapes = c("power", "lin", "log", "identity", "center", "hockey"),
  covCenterType = c("median", "mean"),
  covCenter = NULL,
  catCutoff = 0.05
)

Arguments

data

estimation dataset containing at least an 'ID' column; column names are matched case-insensitively, as in the VAE fit

warn

when 'TRUE' (default) warn about time-varying columns excluded from the search; when 'FALSE' exclude them silently

shapes, covCenterType, covCenter, catCutoff

as in [vaeControl()]; control which shapes are explored and how covariates are centered

Value

a data frame with one row per candidate search column and columns 'covariate' (the column name), 'raw' (upper-cased data column it comes from), 'shape', 'level' (for categorical indicators), 'group' (mutual exclusion group), 'block' (columns selected all-or-none, i.e. the two arms of a '"hockey"' relationship), 'type' and 'center'; zero rows when nothing qualifies

Author(s)

Matthew L. Fidler

Examples

d <- data.frame(id = rep(1:3, each = 2), time = rep(0:1, 3), dv = rnorm(6),
                wt = rep(c(70, 80, 60), each = 2),
                sex = rep(c(0, 1, 0), each = 2))
vaeCovariates(d)

# restrict the explored shapes
vaeCovariates(d, shapes = "power")

Name the data and compartments

Description

Name the data and compartments

Usage

vpcNameDataCmts(object, data)

Arguments

object

nlmixr2 fit object

data

dataset to name 'dvid' and 'cmt' columns to correspond with the model

Value

Updated object/data

Author(s)

Matthew L. Fidler


VPC simulation

Description

VPC simulation

Usage

vpcSim(
  object,
  ...,
  keep = NULL,
  n = 300,
  pred = FALSE,
  seed = 1009,
  nretry = 50,
  minN = 10,
  normRelated = TRUE
)

Arguments

object

This is the nlmixr2 fit object

...

Other arguments sent to 'rxSolve()'

keep

Column names to keep in the output simulated dataset

n

Number of simulations

pred

Should predictions be added to the simulation

seed

Seed to set for the VPC simulation

nretry

Number of times to retry the simulation if there is NA values in the simulation

minN

With retries, the minimum number of studies to restimulate (by default 10)

normRelated

should the VPC style simulation be for normal related variables only

Value

data frame of the VPC simulation

Author(s)

Matthew L. Fidler

Examples




one.cmt <- function() {
 ini({
   ## You may label each parameter with a comment
   tka <- 0.45 # Log Ka
   tcl <- log(c(0, 2.7, 100)) # Log Cl
   ## This works with interactive models
   ## You may also label the preceding line with label("label text")
   tv <- 3.45; label("log V")
   ## the label("Label name") works with all models
   eta.ka ~ 0.6
   eta.cl ~ 0.3
   eta.v ~ 0.1
   add.sd <- 0.7
 })
 model({
   ka <- exp(tka + eta.ka)
   cl <- exp(tcl + eta.cl)
   v <- exp(tv + eta.v)
   linCmt() ~ add(add.sd)
 })
}

fit <- nlmixr(one.cmt, theo_sd, est="focei")

head(vpcSim(fit, pred=TRUE))



Expand a VPC simulation

Description

Expand a VPC simulation

Usage

vpcSimExpand(object, sim, extra, fullData = NULL)

Arguments

object

nlmixr fit object

sim

vpc simulation object

extra

extra data from original fit to add

fullData

is the full data (possibly modified); This is used for the vpc tad calculation

Value

Expanded data frame with extra pieces added

Author(s)

Matthew L. Fidler

These binaries (installable software) and packages are in development.
They may not be fully stable and should be used with caution. We make no claims about them.