Title: | Facilities for Simulating from ODE-Based Models |
---|---|
Description: | Facilities for running simulations from ordinary differential equation ('ODE') models, such as pharmacometrics and other compartmental models. A compilation manager translates the ODE model into C, compiles it, and dynamically loads the object code into R for improved computational efficiency. An event table object facilitates the specification of complex dosing regimens (optional) and sampling schedules. NB: The use of this package requires both C and Fortran compilers, for details on their use with R please see Section 6.3, Appendix A, and Appendix D in the "R Administration and Installation" manual. Also the code is mostly released under GPL. The 'VODE' and 'LSODA' are in the public domain. The information is available in the inst/COPYRIGHTS. |
Authors: | Matthew L. Fidler [aut, cre] |
Maintainer: | Matthew L. Fidler <[email protected]> |
License: | GPL (>= 3) |
Version: | 3.0.0 |
Built: | 2024-09-03 03:22:04 UTC |
Source: | https://github.com/nlmixr2/rxode2 |
cbind Ome
.cbindOme(et, mat, n)
.cbindOme(et, mat, n)
et |
The theta data frame |
mat |
The full matrix simulation from omegas |
n |
number of subject simulated |
data frame with et combined with simulated omega matrix values
Matthew Fidler
Collect warnings and just warn once.
.collectWarnings(expr, lst = FALSE)
.collectWarnings(expr, lst = FALSE)
expr |
R expression |
lst |
When |
The value of the expression or a list with the value of the expression and a list of warning messages
Matthew L. Fidler
This copies the rxode2 UI object so it can be modified
.copyUi(ui)
.copyUi(ui)
ui |
Original UI object |
Copied UI object
Matthew L. Fidler
Handle the single error for normal or t distributions
.handleSingleErrTypeNormOrTFoceiBase( env, pred1, errNum = 1L, rxPredLlik = TRUE )
.handleSingleErrTypeNormOrTFoceiBase( env, pred1, errNum = 1L, rxPredLlik = TRUE )
env |
Environment for the parsed model |
pred1 |
The |
errNum |
The number of the error specification in the nlmixr2 model |
rxPredLlik |
A boolean indicating if the log likelihood should
be calculated for non-normal distributions. By default |
A list of the lines added. The lines will contain
rx_yj_
which is an integer that corresponds to the
transformation type.
rx_lambda_
is the transformation lambda
rx_low_
The lower boundary of the transformation
rx_hi_
The upper boundary of the transformation
rx_pred_f_
The prediction function
rx_pred_
The transformed prediction function
rx_r_
The transformed variance
Matthew Fidler
If template == str2lang(".")
, it will match anything.
If template == str2lang(".name")
, it will match any name.
If template == str2lang(".call()")
, it will match any call.
.matchesLangTemplate(x, template)
.matchesLangTemplate(x, template)
x |
The object to check |
template |
The template object it should match |
TRUE if it matches, FALSE, otherwise
.matchesLangTemplate(str2lang("d/dt(foo)"), str2lang("d/dt(.name)")) .matchesLangTemplate(str2lang("d/dt(foo)"), str2lang("d/foo(.name)")) .matchesLangTemplate(str2lang("d/dt(foo)"), str2lang("d/."))
.matchesLangTemplate(str2lang("d/dt(foo)"), str2lang("d/dt(.name)")) .matchesLangTemplate(str2lang("d/dt(foo)"), str2lang("d/foo(.name)")) .matchesLangTemplate(str2lang("d/dt(foo)"), str2lang("d/."))
Handle model lines
.modelHandleModelLines( modelLines, rxui, modifyIni = FALSE, append = NULL, auto = getOption("rxode2.autoVarPiping", TRUE), cov = NULL, envir )
.modelHandleModelLines( modelLines, rxui, modifyIni = FALSE, append = NULL, auto = getOption("rxode2.autoVarPiping", TRUE), cov = NULL, envir )
modelLines |
The model lines that are being considered |
rxui |
The rxode2 UI object |
modifyIni |
Should the ini() be considered |
append |
This is a boolean to determine if the lines are appended in piping. The possible values for this is:
|
auto |
This boolean tells if piping automatically selects the
parameters should be characterized as a population parameter,
between subject variability, or a covariate. When |
cov |
is a character vector of variables that should be assumed to be covariates. This will override automatic promotion to a population parameter estimate (or an eta) |
envir |
Environment for evaluation |
New UI
Matthew L. Fidler
Returns quoted call information
.quoteCallInfoLines(callInfo, envir = parent.frame(), iniDf = NULL)
.quoteCallInfoLines(callInfo, envir = parent.frame(), iniDf = NULL)
callInfo |
Call information |
envir |
Environment for evaluation (if needed) |
iniDf |
The parent model |
Quote call information. for name=expression
, change to
name<-expression
in quoted call list. For expressions that are
within brackets ie {}
, unlist the brackets as if they were
called in one single sequence.
Matthew L. Fidler
Internal function to generate the model variables for a linCmt() model
.rxLinCmtGen(lenState, vars)
.rxLinCmtGen(lenState, vars)
lenState |
Length of the state |
vars |
Variables in the model |
Model variables of expanded linCmt model
Matthew L. Fidler
This function is used to get the function pointers for rxode2. This is used to allow rxode2 to have binary linkage to nlmixr2est.
.rxode2ptrs()
.rxode2ptrs()
a list of function pointers
Matthew L. Fidler
.rxode2ptrs()
.rxode2ptrs()
Temporarily set options then restore them while running code
.rxWithOptions(ops, code)
.rxWithOptions(ops, code)
ops |
list of options that will be temporarily set for the
|
code |
The code to run during the sink |
value of code
.rxWithOptions(list(digits = 21), { print(pi) }) print(pi)
.rxWithOptions(list(digits = 21), { print(pi) }) print(pi)
Temporarily set options then restore them while running code
.rxWithWd(wd, code)
.rxWithWd(wd, code)
wd |
working directory to temporarily set the system to while evaluating the code |
code |
The code to run during the sink |
value of code
.rxWithWd(tempdir(), { getwd() }) getwd()
.rxWithWd(tempdir(), { getwd() }) getwd()
This converts NONMEM-style EVIDs to classic RxODE events
.toClassicEvid(cmt = 1L, amt = 0, rate = 0, dur = 0, ii = 0, evid = 0L, ss = 0)
.toClassicEvid(cmt = 1L, amt = 0, rate = 0, dur = 0, ii = 0, evid = 0L, ss = 0)
cmt |
compartment flag |
amt |
dose amount |
rate |
dose rate |
dur |
dose duration |
ii |
inter-dose interval |
evid |
event id |
ss |
steady state |
classic evids, excluding evids that are added (you need to add them manually) or simply use etTran. This is mostly for testing and really shouldn't be used directly.
Matthew L. Fidler
.toClassicEvid(cmt=10, amt=3, evid=1) .toClassicEvid(cmt=10, amt=3, rate=2, evid=1) .toClassicEvid(cmt=10, amt=3, rate=-1, evid=1) .toClassicEvid(cmt=10, amt=3, rate=-2, evid=1) .toClassicEvid(cmt=10, amt=3, dur=2, evid=1) .toClassicEvid(cmt=304, amt=3, dur=2, evid=1) .toClassicEvid(cmt=7, amt=0, rate=2, evid=1, ss=1) .toClassicEvid(cmt=-10, amt=3, evid=1) .toClassicEvid(cmt=10, amt=3, evid=5) .toClassicEvid(cmt=6, amt=3, evid=6) .toClassicEvid(cmt=6, amt=3, evid=7) .toClassicEvid(evid=2) .toClassicEvid(evid=4)
.toClassicEvid(cmt=10, amt=3, evid=1) .toClassicEvid(cmt=10, amt=3, rate=2, evid=1) .toClassicEvid(cmt=10, amt=3, rate=-1, evid=1) .toClassicEvid(cmt=10, amt=3, rate=-2, evid=1) .toClassicEvid(cmt=10, amt=3, dur=2, evid=1) .toClassicEvid(cmt=304, amt=3, dur=2, evid=1) .toClassicEvid(cmt=7, amt=0, rate=2, evid=1, ss=1) .toClassicEvid(cmt=-10, amt=3, evid=1) .toClassicEvid(cmt=10, amt=3, evid=5) .toClassicEvid(cmt=6, amt=3, evid=6) .toClassicEvid(cmt=6, amt=3, evid=7) .toClassicEvid(evid=2) .toClassicEvid(evid=4)
Convert numeric vector to repeated data.frame
.vecDf(vec, n)
.vecDf(vec, n)
vec |
Named input vector |
n |
Number of columns |
Data frame with repeated vec
Matthew Fidler
This adds a dosing event to the event table. This is provided for
piping syntax through magrittr. It can also be accessed by eventTable$add.dosing(...)
add.dosing( eventTable, dose, nbr.doses = 1L, dosing.interval = 24, dosing.to = 1L, rate = NULL, amount.units = NA_character_, start.time = 0, do.sampling = FALSE, time.units = NA_character_, ... )
add.dosing( eventTable, dose, nbr.doses = 1L, dosing.interval = 24, dosing.to = 1L, rate = NULL, amount.units = NA_character_, start.time = 0, do.sampling = FALSE, time.units = NA_character_, ... )
eventTable |
eventTable object; When accessed from object it would be |
dose |
numeric scalar, dose amount in |
nbr.doses |
integer, number of doses; |
dosing.interval |
required numeric scalar, time between doses
in |
dosing.to |
integer, compartment the dose goes into (first compartment by default); |
rate |
for infusions, the rate of infusion (default is
|
amount.units |
optional string indicating the dosing units.
Defaults to |
start.time |
required dosing start time; |
do.sampling |
logical, should observation sampling records be
added at the dosing times? Defaults to |
time.units |
optional string indicating the time units.
Defaults to |
... |
Other parameters passed to |
eventTable with updated dosing (note the event table will be updated anyway)
Matthew L. Fidler
Matthew L Fidler, Wenping Wang
Wang W, Hallow K, James D (2015). "A Tutorial on rxode2: Simulating Differential Equation Pharmacometric Models in R." CPT: Pharmacometrics and Systems Pharmacology, 5(1), 3-10. ISSN 2163-8306, <URL: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4728294/>.
eventTable
, add.sampling
,
add.dosing
, et
,
etRep
, etRbind
,
rxode2
library(rxode2) library(units) # Model from rxode2 tutorial # Using a nlmixr2 style function mod1 <-function(){ ini({ KA <- 2.94E-01 CL <- 1.86E+01 V2 <- 4.02E+01 Q <- 1.05E+01 V3 <- 2.97E+02 Kin <- 1 Kout <- 1 EC50 <- 200 }) model({ C2 <- centr/V2 C3 <- peri/V3 d/dt(depot) <- -KA*depot d/dt(centr) <- KA*depot - CL*C2 - Q*C2 + Q*C3 d/dt(peri) <- Q*C2 - Q*C3 d/dt(eff) <- Kin - Kout*(1-C2/(EC50+C2))*eff }) } ## These are making the more complex regimens of the rxode2 tutorial ## bid for 5 days bid <- et(timeUnits="hr") %>% et(amt=10000,ii=12,until=set_units(5, "days")) ## qd for 5 days qd <- et(timeUnits="hr") %>% et(amt=20000,ii=24,until=set_units(5, "days")) ## bid for 5 days followed by qd for 5 days et <- seq(bid,qd) %>% et(seq(0,11*24,length.out=100)) bidQd <- rxSolve(mod1, et) plot(bidQd, C2) ## Now Infusion for 5 days followed by oral for 5 days ## note you can dose to a named compartment instead of using the compartment number infusion <- et(timeUnits = "hr") %>% et(amt=10000, rate=5000, ii=24, until=set_units(5, "days"), cmt="centr") qd <- et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(5, "days"), cmt="depot") et <- seq(infusion,qd) infusionQd <- rxSolve(mod1, et) plot(infusionQd, C2) ## 2wk-on, 1wk-off qd <- et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(2, "weeks"), cmt="depot") et <- seq(qd, set_units(1,"weeks"), qd) %>% add.sampling(set_units(seq(0, 5.5,by=0.005),weeks)) wkOnOff <- rxSolve(mod1, et) plot(wkOnOff, C2) ## You can also repeat the cycle easily with the rep function qd <-et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(2, "weeks"), cmt="depot") et <- etRep(qd, times=4, wait=set_units(1,"weeks")) %>% add.sampling(set_units(seq(0, 12.5,by=0.005),weeks)) repCycle4 <- rxSolve(mod1, et) plot(repCycle4, C2)
library(rxode2) library(units) # Model from rxode2 tutorial # Using a nlmixr2 style function mod1 <-function(){ ini({ KA <- 2.94E-01 CL <- 1.86E+01 V2 <- 4.02E+01 Q <- 1.05E+01 V3 <- 2.97E+02 Kin <- 1 Kout <- 1 EC50 <- 200 }) model({ C2 <- centr/V2 C3 <- peri/V3 d/dt(depot) <- -KA*depot d/dt(centr) <- KA*depot - CL*C2 - Q*C2 + Q*C3 d/dt(peri) <- Q*C2 - Q*C3 d/dt(eff) <- Kin - Kout*(1-C2/(EC50+C2))*eff }) } ## These are making the more complex regimens of the rxode2 tutorial ## bid for 5 days bid <- et(timeUnits="hr") %>% et(amt=10000,ii=12,until=set_units(5, "days")) ## qd for 5 days qd <- et(timeUnits="hr") %>% et(amt=20000,ii=24,until=set_units(5, "days")) ## bid for 5 days followed by qd for 5 days et <- seq(bid,qd) %>% et(seq(0,11*24,length.out=100)) bidQd <- rxSolve(mod1, et) plot(bidQd, C2) ## Now Infusion for 5 days followed by oral for 5 days ## note you can dose to a named compartment instead of using the compartment number infusion <- et(timeUnits = "hr") %>% et(amt=10000, rate=5000, ii=24, until=set_units(5, "days"), cmt="centr") qd <- et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(5, "days"), cmt="depot") et <- seq(infusion,qd) infusionQd <- rxSolve(mod1, et) plot(infusionQd, C2) ## 2wk-on, 1wk-off qd <- et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(2, "weeks"), cmt="depot") et <- seq(qd, set_units(1,"weeks"), qd) %>% add.sampling(set_units(seq(0, 5.5,by=0.005),weeks)) wkOnOff <- rxSolve(mod1, et) plot(wkOnOff, C2) ## You can also repeat the cycle easily with the rep function qd <-et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(2, "weeks"), cmt="depot") et <- etRep(qd, times=4, wait=set_units(1,"weeks")) %>% add.sampling(set_units(seq(0, 12.5,by=0.005),weeks)) repCycle4 <- rxSolve(mod1, et) plot(repCycle4, C2)
This adds a dosing event to the event table. This is provided for
piping syntax through magrittr. It can also be accessed by
eventTable$add.sampling()
add.sampling(eventTable, time, time.units = NA)
add.sampling(eventTable, time, time.units = NA)
eventTable |
An eventTable object. When accessed from object it would be |
time |
a vector of time values (in |
time.units |
an optional string specifying the time
units. Defaults to the units specified when the
|
eventTable with updated sampling. (Note the event table will be updated even if you don't reassign the eventTable)
Matthew L Fidler, Wenping Wang
Wang W, Hallow K, James D (2015). "A Tutorial on rxode2: Simulating Differential Equation Pharmacometric Models in R." CPT: Pharmacometrics and Systems Pharmacology, 5(1), 3-10. ISSN 2163-8306, <URL: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4728294/>.
eventTable
, add.sampling
,
add.dosing
, et
,
etRep
, etRbind
,
rxode2
library(rxode2) library(units) # Model from rxode2 tutorial # Using a nlmixr2 style function mod1 <-function(){ ini({ KA <- 2.94E-01 CL <- 1.86E+01 V2 <- 4.02E+01 Q <- 1.05E+01 V3 <- 2.97E+02 Kin <- 1 Kout <- 1 EC50 <- 200 }) model({ C2 <- centr/V2 C3 <- peri/V3 d/dt(depot) <- -KA*depot d/dt(centr) <- KA*depot - CL*C2 - Q*C2 + Q*C3 d/dt(peri) <- Q*C2 - Q*C3 d/dt(eff) <- Kin - Kout*(1-C2/(EC50+C2))*eff }) } ## These are making the more complex regimens of the rxode2 tutorial ## bid for 5 days bid <- et(timeUnits="hr") %>% et(amt=10000,ii=12,until=set_units(5, "days")) ## qd for 5 days qd <- et(timeUnits="hr") %>% et(amt=20000,ii=24,until=set_units(5, "days")) ## bid for 5 days followed by qd for 5 days et <- seq(bid,qd) %>% et(seq(0,11*24,length.out=100)) bidQd <- rxSolve(mod1, et) plot(bidQd, C2) ## Now Infusion for 5 days followed by oral for 5 days ## note you can dose to a named compartment instead of using the compartment number infusion <- et(timeUnits = "hr") %>% et(amt=10000, rate=5000, ii=24, until=set_units(5, "days"), cmt="centr") qd <- et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(5, "days"), cmt="depot") et <- seq(infusion,qd) infusionQd <- rxSolve(mod1, et) plot(infusionQd, C2) ## 2wk-on, 1wk-off qd <- et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(2, "weeks"), cmt="depot") et <- seq(qd, set_units(1,"weeks"), qd) %>% add.sampling(set_units(seq(0, 5.5,by=0.005),weeks)) wkOnOff <- rxSolve(mod1, et) plot(wkOnOff, C2) ## You can also repeat the cycle easily with the rep function qd <-et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(2, "weeks"), cmt="depot") et <- etRep(qd, times=4, wait=set_units(1,"weeks")) %>% add.sampling(set_units(seq(0, 12.5,by=0.005),weeks)) repCycle4 <- rxSolve(mod1, et) plot(repCycle4, C2)
library(rxode2) library(units) # Model from rxode2 tutorial # Using a nlmixr2 style function mod1 <-function(){ ini({ KA <- 2.94E-01 CL <- 1.86E+01 V2 <- 4.02E+01 Q <- 1.05E+01 V3 <- 2.97E+02 Kin <- 1 Kout <- 1 EC50 <- 200 }) model({ C2 <- centr/V2 C3 <- peri/V3 d/dt(depot) <- -KA*depot d/dt(centr) <- KA*depot - CL*C2 - Q*C2 + Q*C3 d/dt(peri) <- Q*C2 - Q*C3 d/dt(eff) <- Kin - Kout*(1-C2/(EC50+C2))*eff }) } ## These are making the more complex regimens of the rxode2 tutorial ## bid for 5 days bid <- et(timeUnits="hr") %>% et(amt=10000,ii=12,until=set_units(5, "days")) ## qd for 5 days qd <- et(timeUnits="hr") %>% et(amt=20000,ii=24,until=set_units(5, "days")) ## bid for 5 days followed by qd for 5 days et <- seq(bid,qd) %>% et(seq(0,11*24,length.out=100)) bidQd <- rxSolve(mod1, et) plot(bidQd, C2) ## Now Infusion for 5 days followed by oral for 5 days ## note you can dose to a named compartment instead of using the compartment number infusion <- et(timeUnits = "hr") %>% et(amt=10000, rate=5000, ii=24, until=set_units(5, "days"), cmt="centr") qd <- et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(5, "days"), cmt="depot") et <- seq(infusion,qd) infusionQd <- rxSolve(mod1, et) plot(infusionQd, C2) ## 2wk-on, 1wk-off qd <- et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(2, "weeks"), cmt="depot") et <- seq(qd, set_units(1,"weeks"), qd) %>% add.sampling(set_units(seq(0, 5.5,by=0.005),weeks)) wkOnOff <- rxSolve(mod1, et) plot(wkOnOff, C2) ## You can also repeat the cycle easily with the rep function qd <-et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(2, "weeks"), cmt="depot") et <- etRep(qd, times=4, wait=set_units(1,"weeks")) %>% add.sampling(set_units(seq(0, 12.5,by=0.005),weeks)) repCycle4 <- rxSolve(mod1, et) plot(repCycle4, C2)
Coerce object to data.frame
as.et(x, ...) ## Default S3 method: as.et(x, ...)
as.et(x, ...) ## Default S3 method: as.et(x, ...)
x |
Object to coerce to et. |
... |
Other parameters |
An event table
Turn into an ini block for initialization
as.ini(x) ## S3 method for class 'character' as.ini(x) ## S3 method for class 'data.frame' as.ini(x) ## S3 method for class 'call' as.ini(x) ## S3 method for class 'lotriFix' as.ini(x) ## S3 method for class 'matrix' as.ini(x) ## Default S3 method: as.ini(x)
as.ini(x) ## S3 method for class 'character' as.ini(x) ## S3 method for class 'data.frame' as.ini(x) ## S3 method for class 'call' as.ini(x) ## S3 method for class 'lotriFix' as.ini(x) ## S3 method for class 'matrix' as.ini(x) ## Default S3 method: as.ini(x)
x |
Item to convert to a rxode2/nlmixr2 ui ini expression |
rxode2 ini expression
Matthew L. Fidler
ini <- quote(ini({ tka <- log(1.57) tcl <- log(2.72) tv <- log(31.5) eta.ka ~ 0.6 eta.cl ~ 0.3 eta.v ~ 0.1 add.sd <- 0.7 })) as.ini(ini) l <- quote(lotri({ tka <- log(1.57) tcl <- log(2.72) tv <- log(31.5) eta.ka ~ 0.6 eta.cl ~ 0.3 eta.v ~ 0.1 add.sd <- 0.7 })) as.ini(l) m <- lotri({ eta.ka ~ 0.6 eta.cl ~ 0.3 eta.v ~ 0.1 }) as.ini(m) one.compartment <- function() { ini({ tka <- log(1.57) tcl <- log(2.72) tv <- log(31.5) 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) d/dt(depot) = -ka * depot d/dt(center) = ka * depot - cl / v * center cp = center / v cp ~ add(add.sd) }) } as.ini(one.compartment) ui <- one.compartment() as.ini(ui) ui$iniDf as.ini(ui$iniDf) ini <- c("ini({", "tka <- log(1.57)", "tcl <- log(2.72)", "tv <- log(31.5)", "eta.ka ~ 0.6", "eta.cl ~ 0.3", "eta.v ~ 0.1", "add.sd <- 0.7", "})") as.ini(ini) ini <- paste(ini, collapse="\n") as.ini(ini)
ini <- quote(ini({ tka <- log(1.57) tcl <- log(2.72) tv <- log(31.5) eta.ka ~ 0.6 eta.cl ~ 0.3 eta.v ~ 0.1 add.sd <- 0.7 })) as.ini(ini) l <- quote(lotri({ tka <- log(1.57) tcl <- log(2.72) tv <- log(31.5) eta.ka ~ 0.6 eta.cl ~ 0.3 eta.v ~ 0.1 add.sd <- 0.7 })) as.ini(l) m <- lotri({ eta.ka ~ 0.6 eta.cl ~ 0.3 eta.v ~ 0.1 }) as.ini(m) one.compartment <- function() { ini({ tka <- log(1.57) tcl <- log(2.72) tv <- log(31.5) 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) d/dt(depot) = -ka * depot d/dt(center) = ka * depot - cl / v * center cp = center / v cp ~ add(add.sd) }) } as.ini(one.compartment) ui <- one.compartment() as.ini(ui) ui$iniDf as.ini(ui$iniDf) ini <- c("ini({", "tka <- log(1.57)", "tcl <- log(2.72)", "tv <- log(31.5)", "eta.ka ~ 0.6", "eta.cl ~ 0.3", "eta.v ~ 0.1", "add.sd <- 0.7", "})") as.ini(ini) ini <- paste(ini, collapse="\n") as.ini(ini)
Turn into a model expression
as.model(x) ## S3 method for class 'character' as.model(x) ## S3 method for class 'call' as.model(x) ## S3 method for class 'list' as.model(x) ## Default S3 method: as.model(x)
as.model(x) ## S3 method for class 'character' as.model(x) ## S3 method for class 'call' as.model(x) ## S3 method for class 'list' as.model(x) ## Default S3 method: as.model(x)
x |
item to convert to a |
model expression
Matthew L. Fidler
model <- quote(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) })) as.model(model) one.compartment <- function() { ini({ tka <- log(1.57) tcl <- log(2.72) tv <- log(31.5) 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) d/dt(depot) = -ka * depot d/dt(center) = ka * depot - cl / v * center cp = center / v cp ~ add(add.sd) }) } as.model(one.compartment) ui <- one.compartment() as.model(ui) model <- c("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)", "})") as.model(model) model <- paste(model, collapse="\n") as.model(model)
model <- quote(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) })) as.model(model) one.compartment <- function() { ini({ tka <- log(1.57) tcl <- log(2.72) tv <- log(31.5) 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) d/dt(depot) = -ka * depot d/dt(center) = ka * depot - cl / v * center cp = center / v cp ~ add(add.sd) }) } as.model(one.compartment) ui <- one.compartment() as.model(ui) model <- c("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)", "})") as.model(model) model <- paste(model, collapse="\n") as.model(model)
As rxode2 ui
as.rxUi(x) ## S3 method for class 'rxode2' as.rxUi(x) ## S3 method for class 'rxode2tos' as.rxUi(x) ## S3 method for class 'rxModelVars' as.rxUi(x) ## S3 method for class ''function'' as.rxUi(x) ## S3 method for class 'rxUi' as.rxUi(x) ## Default S3 method: as.rxUi(x)
as.rxUi(x) ## S3 method for class 'rxode2' as.rxUi(x) ## S3 method for class 'rxode2tos' as.rxUi(x) ## S3 method for class 'rxModelVars' as.rxUi(x) ## S3 method for class ''function'' as.rxUi(x) ## S3 method for class 'rxUi' as.rxUi(x) ## Default S3 method: as.rxUi(x)
x |
Object to convert to |
rxUi object (or error if it cannot be converted)
Matthew L. Fidler
mod1 <- function() { ini({ # central KA=2.94E-01 CL=1.86E+01 V2=4.02E+01 # peripheral Q=1.05E+01 V3=2.97E+02 # effects Kin=1 Kout=1 EC50=200 }) model({ C2 <- centr/V2 C3 <- peri/V3 d/dt(depot) <- -KA*depot d/dt(centr) <- KA*depot - CL*C2 - Q*C2 + Q*C3 d/dt(peri) <- Q*C2 - Q*C3 eff(0) <- 1 d/dt(eff) <- Kin - Kout*(1-C2/(EC50+C2))*eff }) } as.rxUi(mod1)
mod1 <- function() { ini({ # central KA=2.94E-01 CL=1.86E+01 V2=4.02E+01 # peripheral Q=1.05E+01 V3=2.97E+02 # effects Kin=1 Kout=1 EC50=200 }) model({ C2 <- centr/V2 C3 <- peri/V3 d/dt(depot) <- -KA*depot d/dt(centr) <- KA*depot - CL*C2 - Q*C2 + Q*C3 d/dt(peri) <- Q*C2 - Q*C3 eff(0) <- 1 d/dt(eff) <- Kin - Kout*(1-C2/(EC50+C2))*eff }) } as.rxUi(mod1)
Verify that the compartment exists in a model
assertCompartmentExists(ui, x) testCompartmentExists(ui, x)
assertCompartmentExists(ui, x) testCompartmentExists(ui, x)
ui |
is the model to test |
x |
The value to test (can be a vector of strings) |
the value of the compartment that exists; if it is a vector returns the first item that matches
testCompartmentExists()
: Test if compartment exists
Matthew Fidler & Bill Denney
Other Assertions:
assertCompartmentName()
,
assertCompartmentNew()
,
assertRxUi()
,
assertVariableExists()
,
assertVariableNew()
,
testRxUnbounded()
Verify that a value is a valid nlmixr2 compartment name
assertCompartmentName(x) assertVariableName(x) assertParameterValue(x) assertExists(ui, x) testExists(ui, x)
assertCompartmentName(x) assertVariableName(x) assertParameterValue(x) assertExists(ui, x) testExists(ui, x)
x |
The value to test |
ui |
when needed, this is the rxode2/nlmixr2 model |
The value or an error
assertVariableName()
: Verify that a value is a valid
nlmixr2 variable name
assertParameterValue()
: Verify that a value is a valid
nlmixr2 parameter value
assertExists()
: Assert compartment/variable exists
testExists()
: Test compartment/variable exists
Bill Denney
Other Assertions:
assertCompartmentExists()
,
assertCompartmentNew()
,
assertRxUi()
,
assertVariableExists()
,
assertVariableNew()
,
testRxUnbounded()
Verify that a compartment would be new to the model
assertCompartmentNew(ui, x)
assertCompartmentNew(ui, x)
ui |
is the model to test that a model paramet exists |
x |
The value to test |
The value or an error
Matthew Fidler & Bill Denney
Other Assertions:
assertCompartmentExists()
,
assertCompartmentName()
,
assertRxUi()
,
assertVariableExists()
,
assertVariableNew()
,
testRxUnbounded()
Assert properties of the rxUi models
assertRxUi(ui, extra = "", .var.name = .vname(ui)) assertRxUiPrediction(ui, extra = "", .var.name = .vname(ui)) assertRxUiSingleEndpoint(ui, extra = "", .var.name = .vname(ui)) assertRxUiTransformNormal(ui, extra = "", .var.name = .vname(ui)) assertRxUiNormal(ui, extra = "", .var.name = .vname(ui)) assertRxUiMuRefOnly(ui, extra = "", .var.name = .vname(ui)) assertRxUiEstimatedResiduals(ui, extra = "", .var.name = .vname(ui)) assertRxUiPopulationOnly(ui, extra = "", .var.name = .vname(ui)) assertRxUiMixedOnly(ui, extra = "", .var.name = .vname(ui)) assertRxUiRandomOnIdOnly(ui, extra = "", .var.name = .vname(ui))
assertRxUi(ui, extra = "", .var.name = .vname(ui)) assertRxUiPrediction(ui, extra = "", .var.name = .vname(ui)) assertRxUiSingleEndpoint(ui, extra = "", .var.name = .vname(ui)) assertRxUiTransformNormal(ui, extra = "", .var.name = .vname(ui)) assertRxUiNormal(ui, extra = "", .var.name = .vname(ui)) assertRxUiMuRefOnly(ui, extra = "", .var.name = .vname(ui)) assertRxUiEstimatedResiduals(ui, extra = "", .var.name = .vname(ui)) assertRxUiPopulationOnly(ui, extra = "", .var.name = .vname(ui)) assertRxUiMixedOnly(ui, extra = "", .var.name = .vname(ui)) assertRxUiRandomOnIdOnly(ui, extra = "", .var.name = .vname(ui))
ui |
Model to check |
extra |
Extra text to append to the error message (like "for focei") |
.var.name |
[ |
These functions have different types of assertions
assertRxUi
– Make sure this is a proper rxode2 model (if not throw error)
assertRxUiSingleEndpoint
– Make sure the rxode2 model is only
a single endpoint model (if not throw error)
assertRxUiTransformNormal
– Make sure that the model residual
distribution is normal or transformably normal
assertRxUiNormal
– Make sure that the model residual distribution is normal
assertRxUiEstimatedResiduals
– Make sure that the residual error
parameters are estimated (not modeled).
assertRxUiPopulationOnly
– Make sure the model is the population only
model (no mixed effects)
assertRxUiMixedOnly
– Make sure the model is a mixed effect model (not a
population effect, only)
assertRxUiPrediction
– Make sure the model has predictions
assertRxUiMuRefOnly
– Make sure that all the parameters are mu-referenced
assertRxUiRandomOnIdOnly
– Make sure there are only random effects at the ID level
the rxUi model
Matthew L. Fidler
Other Assertions:
assertCompartmentExists()
,
assertCompartmentName()
,
assertCompartmentNew()
,
assertVariableExists()
,
assertVariableNew()
,
testRxUnbounded()
one.cmt <- function() { ini({ tka <- 0.45; label("Ka") tcl <- log(c(0, 2.7, 100)); label("Cl") tv <- 3.45; label("V") 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) }) } assertRxUi(one.cmt) # assertRxUi(rnorm) # will fail assertRxUiSingleEndpoint(one.cmt)
one.cmt <- function() { ini({ tka <- 0.45; label("Ka") tcl <- log(c(0, 2.7, 100)); label("Cl") tv <- 3.45; label("V") 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) }) } assertRxUi(one.cmt) # assertRxUi(rnorm) # will fail assertRxUiSingleEndpoint(one.cmt)
Assert a variable exists in the model
assertVariableExists(ui, x) testVariableExists(ui, x)
assertVariableExists(ui, x) testVariableExists(ui, x)
ui |
rxode2 ui model |
x |
does the |
variable that matches, in the case of multiple variables, the first that matches. If nothing matches return error
testVariableExists()
: Test if variable exists
Matthew L. Fidler
Other Assertions:
assertCompartmentExists()
,
assertCompartmentName()
,
assertCompartmentNew()
,
assertRxUi()
,
assertVariableNew()
,
testRxUnbounded()
Assert a variable would be new to the model
assertVariableNew(ui, x)
assertVariableNew(ui, x)
ui |
rxode2 ui model |
x |
would the variable |
nothing, but will error if x
would not be new
Matthew L. Fidler
Other Assertions:
assertCompartmentExists()
,
assertCompartmentName()
,
assertCompartmentNew()
,
assertRxUi()
,
assertVariableExists()
,
testRxUnbounded()
This is meant to perform in the same way as quantile()
so it can
be a drop in replacement for code using quantile()
but using
distributional assumptions.
binomProbs(x, ...) ## Default S3 method: binomProbs( x, probs = c(0.025, 0.05, 0.5, 0.95, 0.975), na.rm = FALSE, names = TRUE, onlyProbs = TRUE, n = 0L, m = 0L, pred = FALSE, piMethod = c("lim"), M = 5e+05, tol = .Machine$double.eps^0.25, ciMethod = c("wilson", "wilsonCorrect", "agrestiCoull", "wald", "wc", "ac"), ... )
binomProbs(x, ...) ## Default S3 method: binomProbs( x, probs = c(0.025, 0.05, 0.5, 0.95, 0.975), na.rm = FALSE, names = TRUE, onlyProbs = TRUE, n = 0L, m = 0L, pred = FALSE, piMethod = c("lim"), M = 5e+05, tol = .Machine$double.eps^0.25, ciMethod = c("wilson", "wilsonCorrect", "agrestiCoull", "wald", "wc", "ac"), ... )
x |
numeric vector whose mean and probability based confidence
values are wanted, NA and NaN values are not allowed in numeric
vectors unless |
... |
Arguments passed to default method, allows many different methods to be applied. |
probs |
numeric vector of probabilities with values in the interval 0 to 1, inclusive. When 0, it represents the maximum observed, when 1, it represents the maximum observed. When 0.5 it represents the expected probability (mean). |
na.rm |
logical; if true, any NA and NaN's are removed from
|
names |
logical; if true, the result has a names attribute. |
onlyProbs |
logical; if true, only return the probability based confidence interval/prediction interval estimates, otherwise return extra statistics. |
n |
integer/integerish; this is the n used to calculate the
prediction or confidence interval. When |
m |
integer. When using the prediction interval this represents the number of samples that will be observed in the future for the prediction interval. |
pred |
Use a prediction interval instead of a confidence
interval. By default this is |
piMethod |
gives the prediction interval method (currently only lim) from Lu 2020 |
M |
number of simulations to run for the LIM PI. |
tol |
tolerance of root finding in the LIM prediction interval |
ciMethod |
gives the method for calculating the confidence interval. Can be:
https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Agresti-Coull_Interval.
|
It is used for confidence intervals with rxode2 solved objects using
confint(mean="binom")
By default the return has the probabilities as names (if
named) with the points where the expected distribution are
located given the sampling mean and standard deviation. If
onlyProbs=FALSE
then it would prepend mean, variance, standard
deviation, minimum, maximum and number of non-NA observations.
Matthew L. Fidler
Newcombe, R. G. (1998). "Two-sided confidence intervals for the single proportion: comparison of seven methods". Statistics in Medicine. 17 (8): 857–872. doi:10.1002/(SICI)1097-0258(19980430)17:8<857::AID-SIM777>3.0.CO;2-E. PMID 9595616.
Hezhi Lu, Hua Jin, A new prediction interval for binomial random variable based on inferential models, Journal of Statistical Planning and Inference, Volume 205, 2020, Pages 156-174, ISSN 0378-3758, https://doi.org/10.1016/j.jspi.2019.07.001.
x<- rbinom(7001, p=0.375, size=1) binomProbs(x) # you can also use the prediction interval binomProbs(x, pred=TRUE) # Can get some extra statistics if you request onlyProbs=FALSE binomProbs(x, onlyProbs=FALSE) x[2] <- NA_real_ binomProbs(x, onlyProbs=FALSE) binomProbs(x, na.rm=TRUE)
x<- rbinom(7001, p=0.375, size=1) binomProbs(x) # you can also use the prediction interval binomProbs(x, pred=TRUE) # Can get some extra statistics if you request onlyProbs=FALSE binomProbs(x, onlyProbs=FALSE) x[2] <- NA_real_ binomProbs(x, onlyProbs=FALSE) binomProbs(x, na.rm=TRUE)
Note this Inverse wishart rescaled to match the original scale of the covariance matrix.
cvPost( nu, omega, n = 1L, omegaIsChol = FALSE, returnChol = FALSE, type = c("invWishart", "lkj", "separation"), diagXformType = c("log", "identity", "variance", "nlmixrSqrt", "nlmixrLog", "nlmixrIdentity") )
cvPost( nu, omega, n = 1L, omegaIsChol = FALSE, returnChol = FALSE, type = c("invWishart", "lkj", "separation"), diagXformType = c("log", "identity", "variance", "nlmixrSqrt", "nlmixrLog", "nlmixrIdentity") )
nu |
Degrees of Freedom (Number of Observations) for covariance matrix simulation. |
omega |
Either the estimate of covariance matrix or the estimated standard deviations in matrix form each row forming the standard deviation simulated values |
n |
Number of Matrices to sample. By default this is 1.
This is only useful when |
omegaIsChol |
is an indicator of if the omega matrix is in
the Cholesky decomposition. This is only used when |
returnChol |
Return the Cholesky decomposition of the
covariance matrix sample. This is only used when |
type |
The type of covariance posterior that is being simulated. This can be:
|
diagXformType |
Diagonal transformation type. These could be:
The nlmixr transformations only make sense when there is no off-diagonal correlations modeled. |
If your covariance matrix is a 1x1 matrix, this uses an scaled inverse chi-squared which is equivalent to the Inverse Wishart distribution in the uni-directional case.
In general, the separation strategy is preferred for diagonal
matrices. If the dimension of the matrix is below 10, lkj
is numerically faster than separation
method. However, the
lkj
method has densities too close to zero (XXXX) when the
dimension is above 10. In that case, though computationally more
expensive separation
method performs better.
For matrices with modeled covariances, the easiest method to use is the inverse Wishart which allows the simulation of correlation matrices (XXXX). This method is more well suited for well behaved matrices, that is the variance components are not too low or too high. When modeling nonlinear mixed effects modeling matrices with too high or low variances are considered sub-optimal in describing a system. With these rules in mind, it is reasonable to use the inverse Wishart.
a matrix (n=1) or a list of matrices (n > 1)
Matthew L.Fidler & Wenping Wang
Alvarez I, Niemi J and Simpson M. (2014) Bayesian Inference for a Covariance Matrix. Conference on Applied Statistics in Agriculture.
Wang1 Z, Wu Y, and Chu H. (2018) On Equivalence of the LKJ distribution and the restricted Wishart distribution. <doi:10.48550/arXiv.1809.047463
## Sample a single covariance. draw1 <- cvPost(3, matrix(c(1, .3, .3, 1), 2, 2)) ## Sample 3 covariances set.seed(42) draw3 <- cvPost(3, matrix(c(1, .3, .3, 1), 2, 2), n = 3) ## Sample 3 covariances, but return the cholesky decomposition set.seed(42) draw3c <- cvPost(3, matrix(c(1, .3, .3, 1), 2, 2), n = 3, returnChol = TRUE) ## Sample 3 covariances with lognormal standard deviations via LKJ ## correlation sample cvPost(3, sapply(1:3, function(...) { rnorm(10) }), type = "lkj") ## or return cholesky decomposition cvPost(3, sapply(1:3, function(...) { rnorm(10) }), type = "lkj", returnChol = TRUE ) ## Sample 3 covariances with lognormal standard deviations via separation ## strategy using inverse Wishart correlation sample cvPost(3, sapply(1:3, function(...) { rnorm(10) }), type = "separation") ## or returning the cholesky decomposition cvPost(3, sapply(1:3, function(...) { rnorm(10) }), type = "separation", returnChol = TRUE )
## Sample a single covariance. draw1 <- cvPost(3, matrix(c(1, .3, .3, 1), 2, 2)) ## Sample 3 covariances set.seed(42) draw3 <- cvPost(3, matrix(c(1, .3, .3, 1), 2, 2), n = 3) ## Sample 3 covariances, but return the cholesky decomposition set.seed(42) draw3c <- cvPost(3, matrix(c(1, .3, .3, 1), 2, 2), n = 3, returnChol = TRUE) ## Sample 3 covariances with lognormal standard deviations via LKJ ## correlation sample cvPost(3, sapply(1:3, function(...) { rnorm(10) }), type = "lkj") ## or return cholesky decomposition cvPost(3, sapply(1:3, function(...) { rnorm(10) }), type = "lkj", returnChol = TRUE ) ## Sample 3 covariances with lognormal standard deviations via separation ## strategy using inverse Wishart correlation sample cvPost(3, sapply(1:3, function(...) { rnorm(10) }), type = "separation") ## or returning the cholesky decomposition cvPost(3, sapply(1:3, function(...) { rnorm(10) }), type = "separation", returnChol = TRUE )
This uses simulations to match the rse
dfWishart(omega, n, rse, upper, totN = 1000, diag = TRUE, seed = 1234)
dfWishart(omega, n, rse, upper, totN = 1000, diag = TRUE, seed = 1234)
omega |
represents the matrix for simulation |
n |
This represents the number of subjects/samples this comes from (used to calculate rse). When present it assumes the rse= sqrt(2)/sqrt(n) |
rse |
This is the rse that we try to match, if not specified,
it is derived from |
upper |
The upper boundary for root finding in terms of degrees of freedom. If not specified, it is n*200 |
totN |
This represents the total number of simulated inverse wishart deviates |
diag |
When |
seed |
to make the simulation reproducible, this represents the seed that is used for simulating the inverse Wishart distribution |
output from uniroot()
to find the right estimate
Matthew L. Fidler
dfWishart(lotri::lotri(a+b~c(1, 0.5, 1)), 100)
dfWishart(lotri::lotri(a+b~c(1, 0.5, 1)), 100)
Error function
erf(x)
erf(x)
x |
vector or real values |
erf of x
Matthew L. Fidler
erf(1.0)
erf(1.0)
Event Table Function
et(x, ..., envir = parent.frame()) ## S3 method for class 'rxode2' et(x, ..., envir = parent.frame()) ## S3 method for class ''function'' et(x, ..., envir = parent.frame()) ## S3 method for class 'rxUi' et(x, ..., envir = parent.frame()) ## S3 method for class 'rxSolve' et(x, ..., envir = parent.frame()) ## S3 method for class 'rxParams' et(x, ..., envir = parent.frame()) ## Default S3 method: et( x, ..., time, amt, evid, cmt, ii, addl, ss, rate, dur, until, id, amountUnits, timeUnits, addSampling, envir = parent.frame(), by = NULL, length.out = NULL )
et(x, ..., envir = parent.frame()) ## S3 method for class 'rxode2' et(x, ..., envir = parent.frame()) ## S3 method for class ''function'' et(x, ..., envir = parent.frame()) ## S3 method for class 'rxUi' et(x, ..., envir = parent.frame()) ## S3 method for class 'rxSolve' et(x, ..., envir = parent.frame()) ## S3 method for class 'rxParams' et(x, ..., envir = parent.frame()) ## Default S3 method: et( x, ..., time, amt, evid, cmt, ii, addl, ss, rate, dur, until, id, amountUnits, timeUnits, addSampling, envir = parent.frame(), by = NULL, length.out = NULL )
x |
This is the first argument supplied to the event table.
This is named to allow |
|||||||||||||
... |
Times or event tables. They can also be one of the named arguments below. |
|||||||||||||
envir |
the |
|||||||||||||
time |
Time is the time of the dose or the sampling times. This can also be unspecified and is determined by the object type (list or numeric/integer). |
|||||||||||||
amt |
Amount of the dose. If specified, this assumes a dosing record, instead of a sampling record. |
|||||||||||||
evid |
Event ID; This can be:
Note a reset event resets all the compartment values to zero and turns off all infusions. |
|||||||||||||
cmt |
Compartment name or number. If a number, this is an integer starting at 1. Negative compartments turn off a compartment. If the compartment is a name, the compartment name is changed to the correct state/compartment number before running the simulation. For a compartment named "-cmt" the compartment is turned off. Can also specify `cmt` as `dosing.to`, `dose.to`, `doseTo`, `dosingTo`, and `state`. |
|||||||||||||
ii |
When specifying a dose, this is the inter-dose interval
for |
|||||||||||||
addl |
The number of additional doses at a inter-dose interval after one dose. |
|||||||||||||
ss |
Steady state flag; It can be one of:
When All other values of |
|||||||||||||
rate |
When positive, this is the rate of infusion. Otherwise:
When a modeled bioavailability is applied to positive rates
( If instead you want the modeled bioavailability to increase the
rate of infusion instead of the duration of infusion, specify the
|
|||||||||||||
dur |
Duration of infusion. When |
|||||||||||||
until |
This is the time until the dosing should end. It can be an easier way to figure out how many additional doses are needed over your sampling period. |
|||||||||||||
id |
A integer vector of IDs to add or remove from the event table. If the event table is identical for each ID, then you may expand it to include all the IDs in this vector. All the negative IDs in this vector will be removed. |
|||||||||||||
amountUnits |
The units for the dosing records ( |
|||||||||||||
timeUnits |
The units for the time records ( |
|||||||||||||
addSampling |
This is a boolean indicating if a sampling time
should be added at the same time as a dosing time. By default
this is |
|||||||||||||
by |
number: increment of the sequence. |
|||||||||||||
length.out |
desired length of the sequence. A
non-negative number, which for |
A new event table
Matthew L Fidler, Wenping Wang
Wang W, Hallow K, James D (2015). "A Tutorial on rxode2: Simulating Differential Equation Pharmacometric Models in R." CPT: Pharmacometrics and Systems Pharmacology, 5(1), 3-10. ISSN 2163-8306, <URL: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4728294/>.
eventTable
, add.sampling
,
add.dosing
, et
,
etRep
, etRbind
,
rxode2
library(rxode2) library(units) # Model from rxode2 tutorial # Using a nlmixr2 style function mod1 <-function(){ ini({ KA <- 2.94E-01 CL <- 1.86E+01 V2 <- 4.02E+01 Q <- 1.05E+01 V3 <- 2.97E+02 Kin <- 1 Kout <- 1 EC50 <- 200 }) model({ C2 <- centr/V2 C3 <- peri/V3 d/dt(depot) <- -KA*depot d/dt(centr) <- KA*depot - CL*C2 - Q*C2 + Q*C3 d/dt(peri) <- Q*C2 - Q*C3 d/dt(eff) <- Kin - Kout*(1-C2/(EC50+C2))*eff }) } ## These are making the more complex regimens of the rxode2 tutorial ## bid for 5 days bid <- et(timeUnits="hr") %>% et(amt=10000,ii=12,until=set_units(5, "days")) ## qd for 5 days qd <- et(timeUnits="hr") %>% et(amt=20000,ii=24,until=set_units(5, "days")) ## bid for 5 days followed by qd for 5 days et <- seq(bid,qd) %>% et(seq(0,11*24,length.out=100)) bidQd <- rxSolve(mod1, et) plot(bidQd, C2) ## Now Infusion for 5 days followed by oral for 5 days ## note you can dose to a named compartment instead of using the compartment number infusion <- et(timeUnits = "hr") %>% et(amt=10000, rate=5000, ii=24, until=set_units(5, "days"), cmt="centr") qd <- et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(5, "days"), cmt="depot") et <- seq(infusion,qd) infusionQd <- rxSolve(mod1, et) plot(infusionQd, C2) ## 2wk-on, 1wk-off qd <- et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(2, "weeks"), cmt="depot") et <- seq(qd, set_units(1,"weeks"), qd) %>% add.sampling(set_units(seq(0, 5.5,by=0.005),weeks)) wkOnOff <- rxSolve(mod1, et) plot(wkOnOff, C2) ## You can also repeat the cycle easily with the rep function qd <-et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(2, "weeks"), cmt="depot") et <- etRep(qd, times=4, wait=set_units(1,"weeks")) %>% add.sampling(set_units(seq(0, 12.5,by=0.005),weeks)) repCycle4 <- rxSolve(mod1, et) plot(repCycle4, C2)
library(rxode2) library(units) # Model from rxode2 tutorial # Using a nlmixr2 style function mod1 <-function(){ ini({ KA <- 2.94E-01 CL <- 1.86E+01 V2 <- 4.02E+01 Q <- 1.05E+01 V3 <- 2.97E+02 Kin <- 1 Kout <- 1 EC50 <- 200 }) model({ C2 <- centr/V2 C3 <- peri/V3 d/dt(depot) <- -KA*depot d/dt(centr) <- KA*depot - CL*C2 - Q*C2 + Q*C3 d/dt(peri) <- Q*C2 - Q*C3 d/dt(eff) <- Kin - Kout*(1-C2/(EC50+C2))*eff }) } ## These are making the more complex regimens of the rxode2 tutorial ## bid for 5 days bid <- et(timeUnits="hr") %>% et(amt=10000,ii=12,until=set_units(5, "days")) ## qd for 5 days qd <- et(timeUnits="hr") %>% et(amt=20000,ii=24,until=set_units(5, "days")) ## bid for 5 days followed by qd for 5 days et <- seq(bid,qd) %>% et(seq(0,11*24,length.out=100)) bidQd <- rxSolve(mod1, et) plot(bidQd, C2) ## Now Infusion for 5 days followed by oral for 5 days ## note you can dose to a named compartment instead of using the compartment number infusion <- et(timeUnits = "hr") %>% et(amt=10000, rate=5000, ii=24, until=set_units(5, "days"), cmt="centr") qd <- et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(5, "days"), cmt="depot") et <- seq(infusion,qd) infusionQd <- rxSolve(mod1, et) plot(infusionQd, C2) ## 2wk-on, 1wk-off qd <- et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(2, "weeks"), cmt="depot") et <- seq(qd, set_units(1,"weeks"), qd) %>% add.sampling(set_units(seq(0, 5.5,by=0.005),weeks)) wkOnOff <- rxSolve(mod1, et) plot(wkOnOff, C2) ## You can also repeat the cycle easily with the rep function qd <-et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(2, "weeks"), cmt="depot") et <- etRep(qd, times=4, wait=set_units(1,"weeks")) %>% add.sampling(set_units(seq(0, 12.5,by=0.005),weeks)) repCycle4 <- rxSolve(mod1, et) plot(repCycle4, C2)
Expand additional doses
etExpand(et)
etExpand(et)
et |
Event table to expand additional doses for. |
New event table with addl
doses expanded
Matthew Fidler
ev <- et(amt = 3, ii = 24, until = 240) print(ev) etExpand(ev) # expands event table, but doesn't modify it print(ev) ev$expand() ## Expands the current event table and saves it in ev
ev <- et(amt = 3, ii = 24, until = 240) print(ev) etExpand(ev) # expands event table, but doesn't modify it print(ev) ev$expand() ## Expands the current event table and saves it in ev
Combining event tables
etRbind( ..., samples = c("use", "clear"), waitII = c("smart", "+ii"), id = c("merge", "unique") ) ## S3 method for class 'rxEt' rbind(..., deparse.level = 1)
etRbind( ..., samples = c("use", "clear"), waitII = c("smart", "+ii"), id = c("merge", "unique") ) ## S3 method for class 'rxEt' rbind(..., deparse.level = 1)
... |
The event tables and optionally time between event tables, called waiting times in this help document. |
samples |
How to handle samples when repeating an event table. The options are:
|
waitII |
This determines how waiting times between events are handled. The options are:
|
id |
This is how rbind will handle IDs. There are two different types of options:
|
deparse.level |
The |
An event table
Matthew L Fidler
Matthew L Fidler, Wenping Wang
Wang W, Hallow K, James D (2015). "A Tutorial on rxode2: Simulating Differential Equation Pharmacometric Models in R." CPT: Pharmacometrics and Systems Pharmacology, 5(1), 3-10. ISSN 2163-8306, <URL: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4728294/>.
eventTable
, add.sampling
,
add.dosing
, et
,
etRep
, etRbind
,
rxode2
library(rxode2) library(units) # Model from rxode2 tutorial # Using a nlmixr2 style function mod1 <-function(){ ini({ KA <- 2.94E-01 CL <- 1.86E+01 V2 <- 4.02E+01 Q <- 1.05E+01 V3 <- 2.97E+02 Kin <- 1 Kout <- 1 EC50 <- 200 }) model({ C2 <- centr/V2 C3 <- peri/V3 d/dt(depot) <- -KA*depot d/dt(centr) <- KA*depot - CL*C2 - Q*C2 + Q*C3 d/dt(peri) <- Q*C2 - Q*C3 d/dt(eff) <- Kin - Kout*(1-C2/(EC50+C2))*eff }) } ## These are making the more complex regimens of the rxode2 tutorial ## bid for 5 days bid <- et(timeUnits="hr") %>% et(amt=10000,ii=12,until=set_units(5, "days")) ## qd for 5 days qd <- et(timeUnits="hr") %>% et(amt=20000,ii=24,until=set_units(5, "days")) ## bid for 5 days followed by qd for 5 days et <- seq(bid,qd) %>% et(seq(0,11*24,length.out=100)) bidQd <- rxSolve(mod1, et) plot(bidQd, C2) ## Now Infusion for 5 days followed by oral for 5 days ## note you can dose to a named compartment instead of using the compartment number infusion <- et(timeUnits = "hr") %>% et(amt=10000, rate=5000, ii=24, until=set_units(5, "days"), cmt="centr") qd <- et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(5, "days"), cmt="depot") et <- seq(infusion,qd) infusionQd <- rxSolve(mod1, et) plot(infusionQd, C2) ## 2wk-on, 1wk-off qd <- et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(2, "weeks"), cmt="depot") et <- seq(qd, set_units(1,"weeks"), qd) %>% add.sampling(set_units(seq(0, 5.5,by=0.005),weeks)) wkOnOff <- rxSolve(mod1, et) plot(wkOnOff, C2) ## You can also repeat the cycle easily with the rep function qd <-et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(2, "weeks"), cmt="depot") et <- etRep(qd, times=4, wait=set_units(1,"weeks")) %>% add.sampling(set_units(seq(0, 12.5,by=0.005),weeks)) repCycle4 <- rxSolve(mod1, et) plot(repCycle4, C2)
library(rxode2) library(units) # Model from rxode2 tutorial # Using a nlmixr2 style function mod1 <-function(){ ini({ KA <- 2.94E-01 CL <- 1.86E+01 V2 <- 4.02E+01 Q <- 1.05E+01 V3 <- 2.97E+02 Kin <- 1 Kout <- 1 EC50 <- 200 }) model({ C2 <- centr/V2 C3 <- peri/V3 d/dt(depot) <- -KA*depot d/dt(centr) <- KA*depot - CL*C2 - Q*C2 + Q*C3 d/dt(peri) <- Q*C2 - Q*C3 d/dt(eff) <- Kin - Kout*(1-C2/(EC50+C2))*eff }) } ## These are making the more complex regimens of the rxode2 tutorial ## bid for 5 days bid <- et(timeUnits="hr") %>% et(amt=10000,ii=12,until=set_units(5, "days")) ## qd for 5 days qd <- et(timeUnits="hr") %>% et(amt=20000,ii=24,until=set_units(5, "days")) ## bid for 5 days followed by qd for 5 days et <- seq(bid,qd) %>% et(seq(0,11*24,length.out=100)) bidQd <- rxSolve(mod1, et) plot(bidQd, C2) ## Now Infusion for 5 days followed by oral for 5 days ## note you can dose to a named compartment instead of using the compartment number infusion <- et(timeUnits = "hr") %>% et(amt=10000, rate=5000, ii=24, until=set_units(5, "days"), cmt="centr") qd <- et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(5, "days"), cmt="depot") et <- seq(infusion,qd) infusionQd <- rxSolve(mod1, et) plot(infusionQd, C2) ## 2wk-on, 1wk-off qd <- et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(2, "weeks"), cmt="depot") et <- seq(qd, set_units(1,"weeks"), qd) %>% add.sampling(set_units(seq(0, 5.5,by=0.005),weeks)) wkOnOff <- rxSolve(mod1, et) plot(wkOnOff, C2) ## You can also repeat the cycle easily with the rep function qd <-et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(2, "weeks"), cmt="depot") et <- etRep(qd, times=4, wait=set_units(1,"weeks")) %>% add.sampling(set_units(seq(0, 12.5,by=0.005),weeks)) repCycle4 <- rxSolve(mod1, et) plot(repCycle4, C2)
Repeat an rxode2 event table
etRep( x, times = 1, length.out = NA, each = NA, n = NULL, wait = 0, id = integer(0), samples = c("clear", "use"), waitII = c("smart", "+ii"), ii = 24 ) ## S3 method for class 'rxEt' rep(x, ...)
etRep( x, times = 1, length.out = NA, each = NA, n = NULL, wait = 0, id = integer(0), samples = c("clear", "use"), waitII = c("smart", "+ii"), ii = 24 ) ## S3 method for class 'rxEt' rep(x, ...)
x |
An rxode2 event table |
times |
Number of times to repeat the event table |
length.out |
Invalid with rxode2 event tables, will throw an error if used. |
each |
Invalid with rxode2 event tables, will throw an error if used. |
n |
The number of times to repeat the event table. Overrides
|
wait |
Waiting time between each repeated event table. By default there is no waiting, or wait=0 |
id |
A integer vector of IDs to add or remove from the event table. If the event table is identical for each ID, then you may expand it to include all the IDs in this vector. All the negative IDs in this vector will be removed. |
samples |
How to handle samples when repeating an event table. The options are:
|
waitII |
This determines how waiting times between events are handled. The options are:
|
ii |
When specifying a dose, this is the inter-dose interval
for |
... |
Times or event tables. They can also be one of the named arguments below. |
An event table
Matthew L Fidler, Wenping Wang
Wang W, Hallow K, James D (2015). "A Tutorial on rxode2: Simulating Differential Equation Pharmacometric Models in R." CPT: Pharmacometrics and Systems Pharmacology, 5(1), 3-10. ISSN 2163-8306, <URL: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4728294/>.
eventTable
, add.sampling
,
add.dosing
, et
,
etRep
, etRbind
,
rxode2
library(rxode2) library(units) # Model from rxode2 tutorial # Using a nlmixr2 style function mod1 <-function(){ ini({ KA <- 2.94E-01 CL <- 1.86E+01 V2 <- 4.02E+01 Q <- 1.05E+01 V3 <- 2.97E+02 Kin <- 1 Kout <- 1 EC50 <- 200 }) model({ C2 <- centr/V2 C3 <- peri/V3 d/dt(depot) <- -KA*depot d/dt(centr) <- KA*depot - CL*C2 - Q*C2 + Q*C3 d/dt(peri) <- Q*C2 - Q*C3 d/dt(eff) <- Kin - Kout*(1-C2/(EC50+C2))*eff }) } ## These are making the more complex regimens of the rxode2 tutorial ## bid for 5 days bid <- et(timeUnits="hr") %>% et(amt=10000,ii=12,until=set_units(5, "days")) ## qd for 5 days qd <- et(timeUnits="hr") %>% et(amt=20000,ii=24,until=set_units(5, "days")) ## bid for 5 days followed by qd for 5 days et <- seq(bid,qd) %>% et(seq(0,11*24,length.out=100)) bidQd <- rxSolve(mod1, et) plot(bidQd, C2) ## Now Infusion for 5 days followed by oral for 5 days ## note you can dose to a named compartment instead of using the compartment number infusion <- et(timeUnits = "hr") %>% et(amt=10000, rate=5000, ii=24, until=set_units(5, "days"), cmt="centr") qd <- et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(5, "days"), cmt="depot") et <- seq(infusion,qd) infusionQd <- rxSolve(mod1, et) plot(infusionQd, C2) ## 2wk-on, 1wk-off qd <- et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(2, "weeks"), cmt="depot") et <- seq(qd, set_units(1,"weeks"), qd) %>% add.sampling(set_units(seq(0, 5.5,by=0.005),weeks)) wkOnOff <- rxSolve(mod1, et) plot(wkOnOff, C2) ## You can also repeat the cycle easily with the rep function qd <-et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(2, "weeks"), cmt="depot") et <- etRep(qd, times=4, wait=set_units(1,"weeks")) %>% add.sampling(set_units(seq(0, 12.5,by=0.005),weeks)) repCycle4 <- rxSolve(mod1, et) plot(repCycle4, C2)
library(rxode2) library(units) # Model from rxode2 tutorial # Using a nlmixr2 style function mod1 <-function(){ ini({ KA <- 2.94E-01 CL <- 1.86E+01 V2 <- 4.02E+01 Q <- 1.05E+01 V3 <- 2.97E+02 Kin <- 1 Kout <- 1 EC50 <- 200 }) model({ C2 <- centr/V2 C3 <- peri/V3 d/dt(depot) <- -KA*depot d/dt(centr) <- KA*depot - CL*C2 - Q*C2 + Q*C3 d/dt(peri) <- Q*C2 - Q*C3 d/dt(eff) <- Kin - Kout*(1-C2/(EC50+C2))*eff }) } ## These are making the more complex regimens of the rxode2 tutorial ## bid for 5 days bid <- et(timeUnits="hr") %>% et(amt=10000,ii=12,until=set_units(5, "days")) ## qd for 5 days qd <- et(timeUnits="hr") %>% et(amt=20000,ii=24,until=set_units(5, "days")) ## bid for 5 days followed by qd for 5 days et <- seq(bid,qd) %>% et(seq(0,11*24,length.out=100)) bidQd <- rxSolve(mod1, et) plot(bidQd, C2) ## Now Infusion for 5 days followed by oral for 5 days ## note you can dose to a named compartment instead of using the compartment number infusion <- et(timeUnits = "hr") %>% et(amt=10000, rate=5000, ii=24, until=set_units(5, "days"), cmt="centr") qd <- et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(5, "days"), cmt="depot") et <- seq(infusion,qd) infusionQd <- rxSolve(mod1, et) plot(infusionQd, C2) ## 2wk-on, 1wk-off qd <- et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(2, "weeks"), cmt="depot") et <- seq(qd, set_units(1,"weeks"), qd) %>% add.sampling(set_units(seq(0, 5.5,by=0.005),weeks)) wkOnOff <- rxSolve(mod1, et) plot(wkOnOff, C2) ## You can also repeat the cycle easily with the rep function qd <-et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(2, "weeks"), cmt="depot") et <- etRep(qd, times=4, wait=set_units(1,"weeks")) %>% add.sampling(set_units(seq(0, 12.5,by=0.005),weeks)) repCycle4 <- rxSolve(mod1, et) plot(repCycle4, C2)
This combines a sequence of event tables.
etSeq(..., samples = c("clear", "use"), waitII = c("smart", "+ii"), ii = 24) ## S3 method for class 'rxEt' seq(...)
etSeq(..., samples = c("clear", "use"), waitII = c("smart", "+ii"), ii = 24) ## S3 method for class 'rxEt' seq(...)
... |
The event tables and optionally time between event tables, called waiting times in this help document. |
samples |
How to handle samples when repeating an event table. The options are:
|
waitII |
This determines how waiting times between events are handled. The options are:
|
ii |
If there was no inter-dose intervals found in the event
table, assume that the interdose interval is given by this
|
This seq
uences all the event tables in added in the
argument list ...
. By default when combining the event
tables the offset is at least by the last inter-dose interval in
the prior event table (or ii
). If you separate any of the
event tables by a number, the event tables will be separated at
least the wait time defined by that number or the last inter-dose
interval.
An event table
Matthew L Fidler, Wenping Wang
Wang W, Hallow K, James D (2015). "A Tutorial on rxode2: Simulating Differential Equation Pharmacometric Models in R." CPT: Pharmacometrics and Systems Pharmacology, 5(1), 3-10. ISSN 2163-8306, <URL: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4728294/>.
eventTable
, add.sampling
,
add.dosing
, et
,
etRep
, etRbind
,
rxode2
library(rxode2) library(units) # Model from rxode2 tutorial # Using a nlmixr2 style function mod1 <-function(){ ini({ KA <- 2.94E-01 CL <- 1.86E+01 V2 <- 4.02E+01 Q <- 1.05E+01 V3 <- 2.97E+02 Kin <- 1 Kout <- 1 EC50 <- 200 }) model({ C2 <- centr/V2 C3 <- peri/V3 d/dt(depot) <- -KA*depot d/dt(centr) <- KA*depot - CL*C2 - Q*C2 + Q*C3 d/dt(peri) <- Q*C2 - Q*C3 d/dt(eff) <- Kin - Kout*(1-C2/(EC50+C2))*eff }) } ## These are making the more complex regimens of the rxode2 tutorial ## bid for 5 days bid <- et(timeUnits="hr") %>% et(amt=10000,ii=12,until=set_units(5, "days")) ## qd for 5 days qd <- et(timeUnits="hr") %>% et(amt=20000,ii=24,until=set_units(5, "days")) ## bid for 5 days followed by qd for 5 days et <- seq(bid,qd) %>% et(seq(0,11*24,length.out=100)) bidQd <- rxSolve(mod1, et) plot(bidQd, C2) ## Now Infusion for 5 days followed by oral for 5 days ## note you can dose to a named compartment instead of using the compartment number infusion <- et(timeUnits = "hr") %>% et(amt=10000, rate=5000, ii=24, until=set_units(5, "days"), cmt="centr") qd <- et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(5, "days"), cmt="depot") et <- seq(infusion,qd) infusionQd <- rxSolve(mod1, et) plot(infusionQd, C2) ## 2wk-on, 1wk-off qd <- et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(2, "weeks"), cmt="depot") et <- seq(qd, set_units(1,"weeks"), qd) %>% add.sampling(set_units(seq(0, 5.5,by=0.005),weeks)) wkOnOff <- rxSolve(mod1, et) plot(wkOnOff, C2) ## You can also repeat the cycle easily with the rep function qd <-et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(2, "weeks"), cmt="depot") et <- etRep(qd, times=4, wait=set_units(1,"weeks")) %>% add.sampling(set_units(seq(0, 12.5,by=0.005),weeks)) repCycle4 <- rxSolve(mod1, et) plot(repCycle4, C2)
library(rxode2) library(units) # Model from rxode2 tutorial # Using a nlmixr2 style function mod1 <-function(){ ini({ KA <- 2.94E-01 CL <- 1.86E+01 V2 <- 4.02E+01 Q <- 1.05E+01 V3 <- 2.97E+02 Kin <- 1 Kout <- 1 EC50 <- 200 }) model({ C2 <- centr/V2 C3 <- peri/V3 d/dt(depot) <- -KA*depot d/dt(centr) <- KA*depot - CL*C2 - Q*C2 + Q*C3 d/dt(peri) <- Q*C2 - Q*C3 d/dt(eff) <- Kin - Kout*(1-C2/(EC50+C2))*eff }) } ## These are making the more complex regimens of the rxode2 tutorial ## bid for 5 days bid <- et(timeUnits="hr") %>% et(amt=10000,ii=12,until=set_units(5, "days")) ## qd for 5 days qd <- et(timeUnits="hr") %>% et(amt=20000,ii=24,until=set_units(5, "days")) ## bid for 5 days followed by qd for 5 days et <- seq(bid,qd) %>% et(seq(0,11*24,length.out=100)) bidQd <- rxSolve(mod1, et) plot(bidQd, C2) ## Now Infusion for 5 days followed by oral for 5 days ## note you can dose to a named compartment instead of using the compartment number infusion <- et(timeUnits = "hr") %>% et(amt=10000, rate=5000, ii=24, until=set_units(5, "days"), cmt="centr") qd <- et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(5, "days"), cmt="depot") et <- seq(infusion,qd) infusionQd <- rxSolve(mod1, et) plot(infusionQd, C2) ## 2wk-on, 1wk-off qd <- et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(2, "weeks"), cmt="depot") et <- seq(qd, set_units(1,"weeks"), qd) %>% add.sampling(set_units(seq(0, 5.5,by=0.005),weeks)) wkOnOff <- rxSolve(mod1, et) plot(wkOnOff, C2) ## You can also repeat the cycle easily with the rep function qd <-et(timeUnits = "hr") %>% et(amt=10000, ii=24, until=set_units(2, "weeks"), cmt="depot") et <- etRep(qd, times=4, wait=set_units(1,"weeks")) %>% add.sampling(set_units(seq(0, 12.5,by=0.005),weeks)) repCycle4 <- rxSolve(mod1, et) plot(repCycle4, C2)
Initializes an object of class ‘EventTable’ with methods for adding and querying dosing and observation records
eventTable(amount.units = NA, time.units = NA)
eventTable(amount.units = NA, time.units = NA)
amount.units |
string denoting the amount dosing units, e.g.,
“mg”, “ug”. Default to |
time.units |
string denoting the time units, e.g.,
“hours”, “days”. Default to An Currently, events can be of two types: dosing events that represent inputs to the system and sampling time events that represent observations of the system with ‘amount.units’ and ‘time.units’, respectively. |
A modified data.frame with the following accessible functions:
get.EventTable()
returns the current event table
add.dosing()
adds dosing records to the event table.
get.dosing()
returns a data.frame of dosing records.
clear.dosing()
clears or deletes all dosing from event table
'add.sampling()
adds sampling time observation records to the
event table.
get.sampling()
returns a data.frame of sampled observation records.
clear.sampling()
removes all sampling from event table.
get.obs.rec()
returns a logical vector indicating whether each
event record represents an observation or not.
get.nobs()
returns the number of observation (not dosing) records.
get.units()
returns a two-element character vector with the
dosing and time units, respectively
copy()
makes a copy of the current event table. To create
a copy of an event table object use qd2 <- qd$copy()
expand()
Expands the event table for multi-subject solving.
This is done by qd$expand(400)
for a 400 subject data expansion
Matthew Fidler, Melissa Hallow and Wenping Wang
# create dosing and observation (sampling) events # QD 50mg dosing, 5 days followed by 25mg 5 days # qd <- eventTable(amount.units = "mg", time.units = "days") # qd$add.dosing(dose = 50, nbr.doses = 5, dosing.interval = 1, do.sampling = FALSE) # # sample the system's drug amounts hourly the first day, then every 12 hours # for the next 4 days qd$add.sampling(seq(from = 0, to = 1, by = 1 / 24)) qd$add.sampling(seq(from = 1, to = 5, by = 12 / 24)) # # print(qd$get.dosing()) # table of dosing records print(qd$get.nobs()) # number of observation (not dosing) records # # BID dosing, 5 days bid <- eventTable("mg", "days") # only dosing bid$add.dosing( dose = 10000, nbr.doses = 2 * 5, dosing.interval = 12, do.sampling = FALSE ) # # Use the copy() method to create a copy (clone) of an existing # event table (simple assignments just create a new reference to # the same event table object (closure)). # bid.ext <- bid$copy() # three-day extension for a 2nd cohort bid.ext$add.dosing( dose = 5000, nbr.doses = 2 * 3, start.time = 120, dosing.interval = 12, do.sampling = FALSE ) # You can also use the Piping operator to create a table qd2 <- eventTable(amount.units = "mg", time.units = "days") %>% add.dosing(dose = 50, nbr.doses = 5, dosing.interval = 1, do.sampling = FALSE) %>% add.sampling(seq(from = 0, to = 1, by = 1 / 24)) %>% add.sampling(seq(from = 1, to = 5, by = 12 / 24)) # print(qd2$get.dosing()) # table of dosing records print(qd2$get.nobs()) # number of observation (not dosing) records # Note that piping with %>% will update the original table. qd3 <- qd2 %>% add.sampling(seq(from = 5, to = 10, by = 6 / 24)) print(qd2$get.nobs()) print(qd3$get.nobs())
# create dosing and observation (sampling) events # QD 50mg dosing, 5 days followed by 25mg 5 days # qd <- eventTable(amount.units = "mg", time.units = "days") # qd$add.dosing(dose = 50, nbr.doses = 5, dosing.interval = 1, do.sampling = FALSE) # # sample the system's drug amounts hourly the first day, then every 12 hours # for the next 4 days qd$add.sampling(seq(from = 0, to = 1, by = 1 / 24)) qd$add.sampling(seq(from = 1, to = 5, by = 12 / 24)) # # print(qd$get.dosing()) # table of dosing records print(qd$get.nobs()) # number of observation (not dosing) records # # BID dosing, 5 days bid <- eventTable("mg", "days") # only dosing bid$add.dosing( dose = 10000, nbr.doses = 2 * 5, dosing.interval = 12, do.sampling = FALSE ) # # Use the copy() method to create a copy (clone) of an existing # event table (simple assignments just create a new reference to # the same event table object (closure)). # bid.ext <- bid$copy() # three-day extension for a 2nd cohort bid.ext$add.dosing( dose = 5000, nbr.doses = 2 * 3, start.time = 120, dosing.interval = 12, do.sampling = FALSE ) # You can also use the Piping operator to create a table qd2 <- eventTable(amount.units = "mg", time.units = "days") %>% add.dosing(dose = 50, nbr.doses = 5, dosing.interval = 1, do.sampling = FALSE) %>% add.sampling(seq(from = 0, to = 1, by = 1 / 24)) %>% add.sampling(seq(from = 1, to = 5, by = 12 / 24)) # print(qd2$get.dosing()) # table of dosing records print(qd2$get.nobs()) # number of observation (not dosing) records # Note that piping with %>% will update the original table. qd3 <- qd2 %>% add.sampling(seq(from = 5, to = 10, by = 6 / 24)) print(qd2$get.nobs()) print(qd3$get.nobs())
This is the gamma_p from the boost library
gammap(a, z)
gammap(a, z)
a |
The numeric 'a' parameter in the normalized lower incomplete gamma |
z |
The numeric 'z' parameter in the normalized lower incomplete gamma |
The gamma p function is given by:
gammap = lowergamma(a, z)/gamma(a)
gammap results
Matthew L. Fidler
gammap(1, 3) gammap(1:3, 3) gammap(1, 1:3)
gammap(1, 3) gammap(1:3, 3) gammap(1, 1:3)
This is the gamma_p_derivative from the boost library
gammapDer(a, z)
gammapDer(a, z)
a |
The numeric 'a' parameter in the upper incomplete gamma |
z |
The numeric 'z' parameter in the upper incomplete gamma |
lowergamma results
Matthew L. Fidler
gammapDer(1:3, 3) gammapDer(1, 1:3)
gammapDer(1:3, 3) gammapDer(1, 1:3)
gammapInv and gammapInva: Inverses of normalized gammap function
gammapInv(a, p) gammapInva(x, p)
gammapInv(a, p) gammapInva(x, p)
a |
The numeric 'a' parameter in the upper incomplete gamma |
p |
The numeric 'p' parameter in the upper incomplete gamma |
x |
The numeric 'x' parameter in the upper incomplete gamma |
With the equation:
p = gammap(a, x)
The 'gammapInv' function returns a value 'x' that satisfies the equation above
The 'gammapInva' function returns a value 'q' that satisfies the equation above
NOTE: gammapInva is slow
inverse gammap results
Matthew L. Fidler
gammapInv(1:3, 0.5) gammapInv(1, 1:3 / 3.1) gammapInv(1:3, 1:3 / 3.1) gammapInva(1:3, 1:3 / 3.1)
gammapInv(1:3, 0.5) gammapInv(1, 1:3 / 3.1) gammapInv(1:3, 1:3 / 3.1) gammapInva(1:3, 1:3 / 3.1)
This is the gamma_q from the boost library
gammaq(a, z)
gammaq(a, z)
a |
The numeric 'a' parameter in the normalized upper incomplete gamma |
z |
The numeric 'z' parameter in the normalized upper incomplete gamma |
The gamma q function is given by:
gammaq = uppergamma(a, z)/gamma(a)
gammaq results
Matthew L. Fidler
gammaq(1, 3) gammaq(1:3, 3) gammaq(1, 1:3)
gammaq(1, 3) gammaq(1:3, 3) gammaq(1, 1:3)
gammaqInv and gammaqInva: Inverses of normalized gammaq function
gammaqInv(a, q) gammaqInva(x, q)
gammaqInv(a, q) gammaqInva(x, q)
a |
The numeric 'a' parameter in the upper incomplete gamma |
q |
The numeric 'q' parameter in the upper incomplete gamma |
x |
The numeric 'x' parameter in the upper incomplete gamma |
With the equation:
q = gammaq(a, x)
The 'gammaqInv' function returns a value 'x' that satisfies the equation above
The 'gammaqInva' function returns a value 'a' that satisfies the equation above
NOTE: gammaqInva is slow
inverse gammaq results
Matthew L. Fidler
gammaqInv(1:3, 0.5) gammaqInv(1, 1:3 / 3) gammaqInv(1:3, 1:3 / 3.1) gammaqInva(1:3, 1:3 / 3.1)
gammaqInv(1:3, 0.5) gammaqInv(1, 1:3 / 3) gammaqInv(1:3, 1:3 / 3.1) gammaqInva(1:3, 1:3 / 3.1)
Create a complete shiny application for exploring dosing regimens given a (hardcoded) PK/PD model.
genShinyApp.template( appDir = "shinyExample", verbose = TRUE, ODE.config = list(ode = "model", params = c(KA = 0.294), inits = c(eff = 1), method = "lsoda", atol = 1e-08, rtol = 1e-06) ) write.template.server(appDir) write.template.ui(appDir, statevars)
genShinyApp.template( appDir = "shinyExample", verbose = TRUE, ODE.config = list(ode = "model", params = c(KA = 0.294), inits = c(eff = 1), method = "lsoda", atol = 1e-08, rtol = 1e-06) ) write.template.server(appDir) write.template.ui(appDir, statevars)
appDir |
a string with a directory where to store the shiny
app, by default is |
verbose |
logical specifying whether to write messages as the
shiny app is generated. Defaults to |
ODE.config |
model name compiled and list of parameters sent to |
statevars |
List of statevars passed to to the A PK/PD model is defined using The function evaluates the following PK/PD model by default: C2 = centr/V2; C3 = peri/V3; d/dt(depot) =-KA*depot; d/dt(centr) = KA*depot - CL*C2 - Q*C2 + Q*C3; d/dt(peri) = Q*C2 - Q*C3; d/dt(eff) = Kin - Kout*(1-C2/(EC50+C2))*eff; This can be changed by the To launch the shiny app, simply issue the |
None, these functions are used for their side effects.
These functions create a simple, but working example of a
dosing regimen simulation web application. Users may want to
modify the code to experiment creating shiny applications for
their specific rxode2
models.
rxode2()
,eventTable()
, and the package shiny (https://shiny.posit.co).
# remove myapp when the example is complete on.exit(unlink("myapp", recursive = TRUE, force = TRUE)) # create the shiny app example (template) genShinyApp.template(appDir = "myapp") # run the shiny app if (requireNamespace("shiny", quietly=TRUE)) { library(shiny) # runApp("myapp") # Won't launch in environments without browsers }
# remove myapp when the example is complete on.exit(unlink("myapp", recursive = TRUE, force = TRUE)) # create the shiny app example (template) genShinyApp.template(appDir = "myapp") # run the shiny app if (requireNamespace("shiny", quietly=TRUE)) { library(shiny) # runApp("myapp") # Won't launch in environments without browsers }
Get/Set the number of threads that rxode2 uses
getRxThreads(verbose = FALSE) setRxThreads(threads = NULL, percent = NULL, throttle = NULL) rxCores(verbose = FALSE)
getRxThreads(verbose = FALSE) setRxThreads(threads = NULL, percent = NULL, throttle = NULL) rxCores(verbose = FALSE)
verbose |
Display the value of relevant OpenMP settings |
threads |
NULL (default) rereads environment variables. 0 means to use all logical CPUs available. Otherwise a number >= 1 |
percent |
If provided it should be a number between 2 and 100; the percentage of logical CPUs to use. By default on startup, 50 percent. |
throttle |
2 (default) means that, roughly speaking, a single thread will be used when number subjects solved for is <=2, 2 threads when the number of all points is <=4, etc. The throttle is to speed up small data tasks (especially when repeated many times) by not incurring the overhead of managing multiple threads. The throttle will also suppress sorting which ID will be solved first
when there are (nsubject solved)*throttle <= nthreads. In
In rxode2 the IDs are sorted by the individual number of solving points (largest first). It also has a C interface that allows these IDs to be resorted by total time spent solving the equation. This allows packages like nlmixr to sort by solving time if needed. Overall the the number of threads is throttled (restricted) for small tasks and sorting for IDs are suppressed. |
number of threads that rxode2 uses
The ini block controls initial conditions for 'theta' (fixed effects), 'omega' (random effects), and 'sigma' (residual error) elements of the model.
## S3 method for class 'rxUi' ini(x, ..., envir = parent.frame(), append = NULL) ## Default S3 method: ini(x, ..., envir = parent.frame(), append = NULL) ini(x, ..., envir = parent.frame(), append = NULL)
## S3 method for class 'rxUi' ini(x, ..., envir = parent.frame(), append = NULL) ## Default S3 method: ini(x, ..., envir = parent.frame(), append = NULL) ini(x, ..., envir = parent.frame(), append = NULL)
x |
expression |
... |
Other expressions for |
envir |
the |
append |
Reorder theta parameters. |
The ini()
function is used in two different ways. The main way that
it is used is to set the initial conditions and associated attributes
(described below) in a model. The other way that it is used is for updating
the initial conditions in a model, often using the pipe operator.
'theta' and 'sigma' can be set using either <-
or =
such as
tvCL <- 1
or equivalently tvCL = 1
. 'omega' can be set with a
~
such as etaCL ~ 0.1
.
Parameters can be named or unnamed (though named parameters are preferred).
A named parameter is set using the name on the left of the assignment while
unnamed parameters are set without an assignment operator. tvCL <- 1
would set a named parameter of tvCL
to 1
. Unnamed parameters
are set using just the value, such as 1
.
For some estimation methods, lower and upper bounds can be set for 'theta'
and 'sigma' values. To set a lower and/or upper bound, use a vector of
values. The vector is c(lower, estimate, upper)
. The vector may be
given with just the estimate (estimate
), the lower bound and
estimate (c(lower, estimate)
), or all three (c(lower, estimate,
upper)
). To set an estimate and upper bound without a lower bound, set the
lower bound to -Inf
, c(-Inf, estimate, upper)
. When an
estimation method does not support bounds, the bounds will be ignored with a
warning.
'omega' values can be set as a single value or as the values of a
lower-triangular matrix. The values may be set as either a
variance-covariance matrix (the default) or as a correlation matrix for the
off-diagonals with the standard deviations on the diagonals. Names may be
set on the left side of the ~
. To set a variance-covariance matrix
with variance values of 2 and 3 and a covariance of -2.5 use ~c(2, 2.5,
3)
. To set the same matrix with names of iivKa
and iivCL
, use
iivKa + iivCL~c(2, 2.5, 3)
. To set a correlation matrix with standard
deviations on the diagonal, use cor()
like iivKa + iivCL~cor(2,
-0.5, 3)
.
Values may be fixed (and therefore not estimated) using either the name
fixed
at the end of the assignment or by calling fixed()
as a
function for the value to fix. For 'theta' and 'sigma', either the estimate
or the full definition (including lower and upper bounds) may be included in
the fixed setting. For example, the following are all effectively equivalent
to set a 'theta' or 'sigma' to a fixed value (because the lower and upper
bounds are ignored for a fixed value): tvCL <- fixed(1)
, tvCL <-
fixed(0, 1)
, tvCL <- fixed(0, 1, 2)
, tvCL <- c(0, fixed(1),
2)
, or tvCL <- c(0, 1, fixed)
. For 'omega' assignment, the full
block or none of the block must be set as fixed
. Examples of setting
an 'omega' value as fixed are: iivKa~fixed(1)
, iivKa +
iivCL~fixed(1, 2, 3)
, or iivKa + iivCL~c(1, 2, 3, fixed)
. Anywhere
that fixed
is used, FIX
, FIXED
, or fix
may be
used equivalently.
For any value, standard mathematical operators or functions may be used to
define the value. For example, log(2)
and 24*30
may be used to
define a value anywhere that a number can be used (e.g. lower bound,
estimate, upper bound, variance, etc.).
Values may be labeled using the label()
function after the assignment.
Labels are are used to make reporting easier by giving a human-readable
description of the parameter, but the labels do not have any effect on
estimation. The typical way to set a label so that the parameter tvCL
has a label of "Typical Value of Clearance (L/hr)" is tvCL <- 1;
label("Typical Value of Clearance (L/hr)")
.
rxode2
/nlmixr2
will attempt to determine some
back-transformations for the user. For example, CL <- exp(tvCL)
will
detect that tvCL
must be back-transformed by exp()
for easier
interpretation. When you want to control the back-transformation, you can
specify the back-transformation using backTransform()
after the
assignment. For example, to set the
back-transformation to exp()
, you can use tvCL <- 1;
backTransform(exp())
.
ini block
Matthew Fidler
Other Initial conditions:
zeroRe()
# Set the ini() block in a model one.compartment <- function() { ini({ tka <- log(1.57); label("Ka") tcl <- log(2.72); label("Cl") tv <- log(31.5); label("V") 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) d/dt(depot) = -ka * depot d/dt(center) = ka * depot - cl / v * center cp = center / v cp ~ add(add.sd) }) } # Use piping to update initial conditions one.compartment %>% ini(tka <- log(2)) one.compartment %>% ini(tka <- label("Absorption rate, Ka (1/hr)")) # Move the tka parameter to be just below the tv parameter (affects parameter # summary table, only) one.compartment %>% ini(tka <- label("Absorption rate, Ka (1/hr)"), append = "tv") # When programming with rxode2/nlmixr2, it may be easier to pass strings in # to modify the ini one.compartment %>% ini("tka <- log(2)")
# Set the ini() block in a model one.compartment <- function() { ini({ tka <- log(1.57); label("Ka") tcl <- log(2.72); label("Cl") tv <- log(31.5); label("V") 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) d/dt(depot) = -ka * depot d/dt(center) = ka * depot - cl / v * center cp = center / v cp ~ add(add.sd) }) } # Use piping to update initial conditions one.compartment %>% ini(tka <- log(2)) one.compartment %>% ini(tka <- label("Absorption rate, Ka (1/hr)")) # Move the tka parameter to be just below the tv parameter (affects parameter # summary table, only) one.compartment %>% ini(tka <- label("Absorption rate, Ka (1/hr)"), append = "tv") # When programming with rxode2/nlmixr2, it may be easier to pass strings in # to modify the ini one.compartment %>% ini("tka <- log(2)")
Assign the ini block in the rxode2 related object
ini(x, envir = environment(x)) <- value
ini(x, envir = environment(x)) <- value
x |
rxode2 related object |
envir |
Environment where assignment occurs |
value |
Value of the object |
rxode2 related object
Matthew L. Fidler
Return if the object can be stacked
is.rxStackData(object)
is.rxStackData(object)
object |
object to test if it can be stacked |
boolean to tell if an object can be stacked using rxode2
Matthew L. Fidler
is.rxStackData(NULL)
is.rxStackData(NULL)
Calculate the log likelihood of the binomial function (and its derivatives)
llikBeta(x, shape1, shape2, full = FALSE)
llikBeta(x, shape1, shape2, full = FALSE)
x |
Observation |
shape1 , shape2
|
non-negative parameters of the Beta distribution. |
full |
Add the data frame showing x, mean, sd as well as the fx and derivatives |
In an rxode2()
model, you can use llikBeta()
but you have to
use all arguments. You can also get the derivative of shape1
and shape2
with
llikBetaDshape1()
and llikBetaDshape2()
.
data frame with fx
for the log pdf value of with
dShape1
and dShape2
that has the derivatives with respect to the parameters at
the observation time-point
Matthew L. Fidler
x <- seq(1e-4, 1 - 1e-4, length.out = 21) llikBeta(x, 0.5, 0.5) llikBeta(x, 1, 3, TRUE) et <- et(seq(1e-4, 1-1e-4, length.out=21)) et$shape1 <- 0.5 et$shape2 <- 1.5 model <- function() { model({ fx <- llikBeta(time, shape1, shape2) dShape1 <- llikBetaDshape1(time, shape1, shape2) dShape2 <- llikBetaDshape2(time, shape1, shape2) }) } rxSolve(model, et)
x <- seq(1e-4, 1 - 1e-4, length.out = 21) llikBeta(x, 0.5, 0.5) llikBeta(x, 1, 3, TRUE) et <- et(seq(1e-4, 1-1e-4, length.out=21)) et$shape1 <- 0.5 et$shape2 <- 1.5 model <- function() { model({ fx <- llikBeta(time, shape1, shape2) dShape1 <- llikBetaDshape1(time, shape1, shape2) dShape2 <- llikBetaDshape2(time, shape1, shape2) }) } rxSolve(model, et)
Calculate the log likelihood of the binomial function (and its derivatives)
llikBinom(x, size, prob, full = FALSE)
llikBinom(x, size, prob, full = FALSE)
x |
Number of successes |
size |
Size of trial |
prob |
probability of success |
full |
Add the data frame showing x, mean, sd as well as the fx and derivatives |
In an rxode2()
model, you can use llikBinom()
but you have to
use all arguments. You can also get the derivative of prob
with
llikBinomDprob()
data frame with fx
for the pdf value of with
dProb
that has the derivatives with respect to the parameters at
the observation time-point
Matthew L. Fidler
llikBinom(46:54, 100, 0.5) llikBinom(46:54, 100, 0.5, TRUE) # In rxode2 you can use: et <- et(46:54) et$size <- 100 et$prob <-0.5 model <- function() { model({ fx <- llikBinom(time, size, prob) dProb <- llikBinomDprob(time, size, prob) }) } rxSolve(model, et)
llikBinom(46:54, 100, 0.5) llikBinom(46:54, 100, 0.5, TRUE) # In rxode2 you can use: et <- et(46:54) et$size <- 100 et$prob <-0.5 model <- function() { model({ fx <- llikBinom(time, size, prob) dProb <- llikBinomDprob(time, size, prob) }) } rxSolve(model, et)
log likelihood of Cauchy distribution and it's derivatives (from stan)
llikCauchy(x, location = 0, scale = 1, full = FALSE)
llikCauchy(x, location = 0, scale = 1, full = FALSE)
x |
Observation |
location , scale
|
location and scale parameters. |
full |
Add the data frame showing x, mean, sd as well as the fx and derivatives |
In an rxode2()
model, you can use llikCauchy()
but you have to
use all arguments. You can also get the derivative of location
and scale
with
llikCauchyDlocation()
and llikCauchyDscale()
.
data frame with fx
for the log pdf value of with
dLocation
and dScale
that has the derivatives with respect to the parameters at
the observation time-point
Matthew L. Fidler
x <- seq(-3, 3, length.out = 21) llikCauchy(x, 0, 1) llikCauchy(x, 3, 1, full=TRUE) et <- et(-3, 3, length.out=10) et$location <- 0 et$scale <- 1 model <- function() { model({ fx <- llikCauchy(time, location, scale) dLocation <- llikCauchyDlocation(time, location, scale) dScale <- llikCauchyDscale(time, location, scale) }) } rxSolve(model, et)
x <- seq(-3, 3, length.out = 21) llikCauchy(x, 0, 1) llikCauchy(x, 3, 1, full=TRUE) et <- et(-3, 3, length.out=10) et$location <- 0 et$scale <- 1 model <- function() { model({ fx <- llikCauchy(time, location, scale) dLocation <- llikCauchyDlocation(time, location, scale) dScale <- llikCauchyDscale(time, location, scale) }) } rxSolve(model, et)
log likelihood and derivatives for chi-squared distribution
llikChisq(x, df, full = FALSE)
llikChisq(x, df, full = FALSE)
x |
variable that is distributed by chi-squared distribution |
df |
degrees of freedom (non-negative, but can be non-integer). |
full |
Add the data frame showing x, mean, sd as well as the fx and derivatives |
In an rxode2()
model, you can use llikChisq()
but you have to
use the x and df arguments. You can also get the derivative of df
with
llikChisqDdf()
.
data frame with fx
for the log pdf value of with dDf
that has the derivatives with respect to the df
parameter
the observation time-point
Matthew L. Fidler
llikChisq(1, df = 1:3, full=TRUE) llikChisq(1, df = 6:9) et <- et(1:3) et$x <- 1 model <- function() { model({ fx <- llikChisq(x, time) dDf <- llikChisqDdf(x, time) }) } rxSolve(model, et)
llikChisq(1, df = 1:3, full=TRUE) llikChisq(1, df = 6:9) et <- et(1:3) et$x <- 1 model <- function() { model({ fx <- llikChisq(x, time) dDf <- llikChisqDdf(x, time) }) } rxSolve(model, et)
log likelihood and derivatives for exponential distribution
llikExp(x, rate, full = FALSE)
llikExp(x, rate, full = FALSE)
x |
variable that is distributed by exponential distribution |
rate |
vector of rates. |
full |
Add the data frame showing x, mean, sd as well as the fx and derivatives |
In an rxode2()
model, you can use llikExp()
but you have to
use the x and rate arguments. You can also get the derivative of rate
with
llikExpDrate()
.
data frame with fx
for the log pdf value of with dRate
that has the derivatives with respect to the rate
parameter
the observation time-point
Matthew L. Fidler
llikExp(1, 1:3) llikExp(1, 1:3, full=TRUE) # You can use rxode2 for these too: et <- et(1:3) et$x <- 1 model <- function() { model({ fx <- llikExp(x, time) dRate <- llikExpDrate(x, time) }) } rxSolve(model, et)
llikExp(1, 1:3) llikExp(1, 1:3, full=TRUE) # You can use rxode2 for these too: et <- et(1:3) et$x <- 1 model <- function() { model({ fx <- llikExp(x, time) dRate <- llikExpDrate(x, time) }) } rxSolve(model, et)
log likelihood and derivatives for F distribution
llikF(x, df1, df2, full = FALSE)
llikF(x, df1, df2, full = FALSE)
x |
variable that is distributed by f distribution |
df1 , df2
|
degrees of freedom. |
full |
Add the data frame showing x, mean, sd as well as the fx and derivatives |
In an rxode2()
model, you can use llikF()
but you have to
use the x and rate arguments. You can also get the derivative of df1
and df2
with
llikFDdf1()
and llikFDdf2()
.
data frame with fx
for the log pdf value of with dDf1
and dDf2
that has the derivatives with respect to the df1
/df2
parameters at
the observation time-point
Matthew L. Fidler
x <- seq(0.001, 5, length.out = 100) llikF(x^2, 1, 5) model <- function(){ model({ fx <- llikF(time, df1, df2) dMean <- llikFDdf1(time, df1, df2) dSd <- llikFDdf2(time, df1, df2) }) } et <- et(x) et$df1 <- 1 et$df2 <- 5 rxSolve(model, et)
x <- seq(0.001, 5, length.out = 100) llikF(x^2, 1, 5) model <- function(){ model({ fx <- llikF(time, df1, df2) dMean <- llikFDdf1(time, df1, df2) dSd <- llikFDdf2(time, df1, df2) }) } et <- et(x) et$df1 <- 1 et$df2 <- 5 rxSolve(model, et)
log likelihood and derivatives for Gamma distribution
llikGamma(x, shape, rate, full = FALSE)
llikGamma(x, shape, rate, full = FALSE)
x |
variable that is distributed by gamma distribution |
shape |
this is the distribution's shape parameter. Must be positive. |
rate |
this is the distribution's rate parameters. Must be positive. |
full |
Add the data frame showing x, mean, sd as well as the fx and derivatives |
In an rxode2()
model, you can use llikGamma()
but you have to
use the x and rate arguments. You can also get the derivative of shape
or rate
with
llikGammaDshape()
and llikGammaDrate()
.
data frame with fx
for the log pdf value of with dProb
that has the derivatives with respect to the prob
parameters at
the observation time-point
Matthew L. Fidler
llikGamma(1, 1, 10) # You can use this in `rxode2` too: et <- et(seq(0.001, 1, length.out=10)) et$shape <- 1 et$rate <- 10 model <- function() { model({ fx <- llikGamma(time, shape, rate) dShape<- llikGammaDshape(time, shape, rate) dRate <- llikGammaDrate(time, shape, rate) }) } rxSolve(model, et)
llikGamma(1, 1, 10) # You can use this in `rxode2` too: et <- et(seq(0.001, 1, length.out=10)) et$shape <- 1 et$rate <- 10 model <- function() { model({ fx <- llikGamma(time, shape, rate) dShape<- llikGammaDshape(time, shape, rate) dRate <- llikGammaDrate(time, shape, rate) }) } rxSolve(model, et)
log likelihood and derivatives for Geom distribution
llikGeom(x, prob, full = FALSE)
llikGeom(x, prob, full = FALSE)
x |
variable distributed by a geom distribution |
prob |
probability of success in each trial. |
full |
Add the data frame showing x, mean, sd as well as the fx and derivatives |
In an rxode2()
model, you can use llikGeom()
but you have to
use the x and rate arguments. You can also get the derivative of prob
with
llikGeomDprob()
.
data frame with fx
for the log pdf value of with dProb
that has the derivatives with respect to the prob
parameters at
the observation time-point
Matthew L. Fidler
llikGeom(1:10, 0.2) et <- et(1:10) et$prob <- 0.2 model <- function() { model({ fx <- llikGeom(time, prob) dProb <- llikGeomDprob(time, prob) }) } rxSolve(model, et)
llikGeom(1:10, 0.2) et <- et(1:10) et$prob <- 0.2 model <- function() { model({ fx <- llikGeom(time, prob) dProb <- llikGeomDprob(time, prob) }) } rxSolve(model, et)
Calculate the log likelihood of the negative binomial function (and its derivatives)
llikNbinom(x, size, prob, full = FALSE)
llikNbinom(x, size, prob, full = FALSE)
x |
Number of successes |
size |
Size of trial |
prob |
probability of success |
full |
Add the data frame showing x, mean, sd as well as the fx and derivatives |
In an rxode2()
model, you can use llikNbinom()
but you have to
use all arguments. You can also get the derivative of prob
with
llikNbinomDprob()
data frame with fx
for the pdf value of with
dProb
that has the derivatives with respect to the parameters at
the observation time-point
Matthew L. Fidler
llikNbinom(46:54, 100, 0.5) llikNbinom(46:54, 100, 0.5, TRUE) # In rxode2 you can use: et <- et(46:54) et$size <- 100 et$prob <-0.5 model <- function() { model({ fx <- llikNbinom(time, size, prob) dProb <- llikNbinomDprob(time, size, prob) }) } rxSolve(model, et)
llikNbinom(46:54, 100, 0.5) llikNbinom(46:54, 100, 0.5, TRUE) # In rxode2 you can use: et <- et(46:54) et$size <- 100 et$prob <-0.5 model <- function() { model({ fx <- llikNbinom(time, size, prob) dProb <- llikNbinomDprob(time, size, prob) }) } rxSolve(model, et)
Calculate the log likelihood of the negative binomial function (and its derivatives)
llikNbinomMu(x, size, mu, full = FALSE)
llikNbinomMu(x, size, mu, full = FALSE)
x |
Number of successes |
size |
Size of trial |
mu |
mu parameter for negative binomial |
full |
Add the data frame showing x, mean, sd as well as the fx and derivatives |
In an rxode2()
model, you can use llikNbinomMu()
but you have to
use all arguments. You can also get the derivative of mu
with
llikNbinomMuDmu()
data frame with fx
for the pdf value of with
dProb
that has the derivatives with respect to the parameters at
the observation time-point
Matthew L. Fidler
llikNbinomMu(46:54, 100, 40) llikNbinomMu(46:54, 100, 40, TRUE) et <- et(46:54) et$size <- 100 et$mu <- 40 model <- function() { model({ fx <- llikNbinomMu(time, size, mu) dProb <- llikNbinomMuDmu(time, size, mu) }) } rxSolve(model, et)
llikNbinomMu(46:54, 100, 40) llikNbinomMu(46:54, 100, 40, TRUE) et <- et(46:54) et$size <- 100 et$mu <- 40 model <- function() { model({ fx <- llikNbinomMu(time, size, mu) dProb <- llikNbinomMuDmu(time, size, mu) }) } rxSolve(model, et)
Log likelihood for normal distribution
llikNorm(x, mean = 0, sd = 1, full = FALSE)
llikNorm(x, mean = 0, sd = 1, full = FALSE)
x |
Observation |
mean |
Mean for the likelihood |
sd |
Standard deviation for the likelihood |
full |
Add the data frame showing x, mean, sd as well as the fx and derivatives |
In an rxode2()
model, you can use llikNorm()
but you have to
use all arguments. You can also get the derivatives with
llikNormDmean()
and llikNormDsd()
data frame with fx
for the pdf value of with dMean
and
dSd
that has the derivatives with respect to the parameters at
the observation time-point
Matthew L. Fidler
llikNorm(0) llikNorm(seq(-2,2,length.out=10), full=TRUE) # With rxode2 you can use: et <- et(-3, 3, length.out=10) et$mu <- 0 et$sigma <- 1 model <- function(){ model({ fx <- llikNorm(time, mu, sigma) dMean <- llikNormDmean(time, mu, sigma) dSd <- llikNormDsd(time, mu, sigma) }) } ret <- rxSolve(model, et) ret
llikNorm(0) llikNorm(seq(-2,2,length.out=10), full=TRUE) # With rxode2 you can use: et <- et(-3, 3, length.out=10) et$mu <- 0 et$sigma <- 1 model <- function(){ model({ fx <- llikNorm(time, mu, sigma) dMean <- llikNormDmean(time, mu, sigma) dSd <- llikNormDsd(time, mu, sigma) }) } ret <- rxSolve(model, et) ret
log-likelihood for the Poisson distribution
llikPois(x, lambda, full = FALSE)
llikPois(x, lambda, full = FALSE)
x |
non negative integers |
lambda |
non-negative means |
full |
Add the data frame showing x, mean, sd as well as the fx and derivatives |
In an rxode2()
model, you can use llikPois()
but you have to
use all arguments. You can also get the derivatives with
llikPoisDlambda()
data frame with fx
for the pdf value of with
dLambda
that has the derivatives with respect to the parameters at
the observation time-point
Matthew L. Fidler
llikPois(0:7, lambda = 1) llikPois(0:7, lambda = 4, full=TRUE) # In rxode2 you can use: et <- et(0:10) et$lambda <- 0.5 model <- function() { model({ fx <- llikPois(time, lambda) dLambda <- llikPoisDlambda(time, lambda) }) } rxSolve(model, et)
llikPois(0:7, lambda = 1) llikPois(0:7, lambda = 4, full=TRUE) # In rxode2 you can use: et <- et(0:10) et$lambda <- 0.5 model <- function() { model({ fx <- llikPois(time, lambda) dLambda <- llikPoisDlambda(time, lambda) }) } rxSolve(model, et)
Log likelihood of T and it's derivatives (from stan)
llikT(x, df, mean = 0, sd = 1, full = FALSE)
llikT(x, df, mean = 0, sd = 1, full = FALSE)
x |
Observation |
df |
degrees of freedom ( |
mean |
Mean for the likelihood |
sd |
Standard deviation for the likelihood |
full |
Add the data frame showing x, mean, sd as well as the fx and derivatives |
In an rxode2()
model, you can use llikT()
but you have to
use all arguments. You can also get the derivative of df
, mean
and sd
with
llikTDdf()
, llikTDmean()
and llikTDsd()
.
data frame with fx
for the log pdf value of with dDf
dMean
and dSd
that has the derivatives with respect to the parameters at
the observation time-point
Matthew L. Fidler
x <- seq(-3, 3, length.out = 21) llikT(x, 7, 0, 1) llikT(x, 15, 0, 1, full=TRUE) et <- et(-3, 3, length.out=10) et$nu <- 7 et$mean <- 0 et$sd <- 1 model <- function() { model({ fx <- llikT(time, nu, mean, sd) dDf <- llikTDdf(time, nu, mean, sd) dMean <- llikTDmean(time, nu, mean, sd) dSd <- llikTDsd(time, nu, mean, sd) }) } rxSolve(model, et)
x <- seq(-3, 3, length.out = 21) llikT(x, 7, 0, 1) llikT(x, 15, 0, 1, full=TRUE) et <- et(-3, 3, length.out=10) et$nu <- 7 et$mean <- 0 et$sd <- 1 model <- function() { model({ fx <- llikT(time, nu, mean, sd) dDf <- llikTDdf(time, nu, mean, sd) dMean <- llikTDmean(time, nu, mean, sd) dSd <- llikTDsd(time, nu, mean, sd) }) } rxSolve(model, et)
log likelihood and derivatives for Unif distribution
llikUnif(x, alpha, beta, full = FALSE)
llikUnif(x, alpha, beta, full = FALSE)
x |
variable distributed by a uniform distribution |
alpha |
is the lower limit of the uniform distribution |
beta |
is the upper limit of the distribution |
full |
Add the data frame showing x, mean, sd as well as the fx and derivatives |
In an rxode2()
model, you can use llikUnif()
but you have to
use the x and rate arguments. You can also get the derivative of alpha
or beta
with
llikUnifDalpha()
and llikUnifDbeta()
.
data frame with fx
for the log pdf value of with dProb
that has the derivatives with respect to the prob
parameters at
the observation time-point
Matthew L. Fidler
llikUnif(1, -2, 2) et <- et(seq(1,1, length.out=4)) et$alpha <- -2 et$beta <- 2 model <- function() { model({ fx <- llikUnif(time, alpha, beta) dAlpha<- llikUnifDalpha(time, alpha, beta) dBeta <- llikUnifDbeta(time, alpha, beta) }) } rxSolve(model, et)
llikUnif(1, -2, 2) et <- et(seq(1,1, length.out=4)) et$alpha <- -2 et$beta <- 2 model <- function() { model({ fx <- llikUnif(time, alpha, beta) dAlpha<- llikUnifDalpha(time, alpha, beta) dBeta <- llikUnifDbeta(time, alpha, beta) }) } rxSolve(model, et)
log likelihood and derivatives for Weibull distribution
llikWeibull(x, shape, scale, full = FALSE)
llikWeibull(x, shape, scale, full = FALSE)
x |
variable distributed by a Weibull distribution |
shape , scale
|
shape and scale parameters, the latter defaulting to 1. |
full |
Add the data frame showing x, mean, sd as well as the fx and derivatives |
In an rxode2()
model, you can use llikWeibull()
but you have to
use the x and rate arguments. You can also get the derivative of shape
or scale
with
llikWeibullDshape()
and llikWeibullDscale()
.
data frame with fx
for the log pdf value of with dProb
that has the derivatives with respect to the prob
parameters at
the observation time-point
Matthew L. Fidler
llikWeibull(1, 1, 10) # rxode2 can use this too: et <- et(seq(0.001, 1, length.out=10)) et$shape <- 1 et$scale <- 10 model <- function() { model({ fx <- llikWeibull(time, shape, scale) dShape<- llikWeibullDshape(time, shape, scale) dScale <- llikWeibullDscale(time, shape, scale) }) } rxSolve(model, et)
llikWeibull(1, 1, 10) # rxode2 can use this too: et <- et(seq(0.001, 1, length.out=10)) et$shape <- 1 et$scale <- 10 model <- function() { model({ fx <- llikWeibull(time, shape, scale) dShape<- llikWeibullDshape(time, shape, scale) dScale <- llikWeibullDscale(time, shape, scale) }) } rxSolve(model, et)
logit and inverse logit (expit) functions
logit(x, low = 0, high = 1) expit(alpha, low = 0, high = 1) logitNormInfo(mean = 0, sd = 1, low = 0, high = 1, abs.tol = 1e-06, ...) probitNormInfo(mean = 0, sd = 1, low = 0, high = 1, abs.tol = 1e-06, ...)
logit(x, low = 0, high = 1) expit(alpha, low = 0, high = 1) logitNormInfo(mean = 0, sd = 1, low = 0, high = 1, abs.tol = 1e-06, ...) probitNormInfo(mean = 0, sd = 1, low = 0, high = 1, abs.tol = 1e-06, ...)
x |
Input value(s) in range [low,high] to translate -Inf to Inf |
low |
Lowest value in the range |
high |
Highest value in the range |
alpha |
Infinite value(s) to translate to range of [low, high] |
mean |
logit-scale mean |
sd |
logit-scale standard deviation |
abs.tol |
absolute accuracy requested. |
... |
other parameters passed to |
logit is given by:
logit(p) = -log(1/p-1)
where:
p = x-low/high-low
expit is given by:
expit(p, low, high) = (high-low)/(1+exp(-alpha)) + low
The logitNormInfo()
gives the mean, variance and coefficient of
variability on the untransformed scale.
values from logit and expit
logit(0.25) expit(-1.09) logitNormInfo(logit(0.25), sd = 0.1) logitNormInfo(logit(1, 0, 10), sd = 1, low = 0, high = 10)
logit(0.25) expit(-1.09) logitNormInfo(logit(0.25), sd = 0.1) logitNormInfo(logit(1, 0, 10), sd = 1, low = 0, high = 10)
This is the tgamma_lower from the boost library
lowergamma(a, z)
lowergamma(a, z)
a |
The numeric 'a' parameter in the upper incomplete gamma |
z |
The numeric 'z' parameter in the upper incomplete gamma |
The lowergamma function is given by:
lowergamma results
Matthew L. Fidler
lowergamma(1, 3) lowergamma(1:3, 3) lowergamma(1, 1:3)
lowergamma(1, 3) lowergamma(1:3, 3) lowergamma(1, 1:3)
The generic function meanProbs
produces expected confidence bands
under either the t distribution or the normal sampling
distribution. This uses qnorm()
or qt()
with the mean and
standard deviation.
meanProbs(x, ...) ## Default S3 method: meanProbs( x, probs = seq(0, 1, 0.25), na.rm = FALSE, names = TRUE, useT = TRUE, onlyProbs = TRUE, pred = FALSE, n = 0L, ... )
meanProbs(x, ...) ## Default S3 method: meanProbs( x, probs = seq(0, 1, 0.25), na.rm = FALSE, names = TRUE, useT = TRUE, onlyProbs = TRUE, pred = FALSE, n = 0L, ... )
x |
numeric vector whose mean and probability based confidence values are wanted, NA and NaN values are not allowed in numeric vectors unless ‘na.rm’ is ‘TRUE’. |
... |
Arguments passed to default method, allows many different methods to be applied. |
probs |
numeric vector of probabilities with values in the interval from 0 to 1 . |
na.rm |
logical; if true, any NA and NaN's are removed from
|
names |
logical; if true, the result has a names attribute. |
useT |
logical; if true, use the t-distribution to calculate the confidence-based estimates. If false use the normal distribution to calculate the confidence based estimates. |
onlyProbs |
logical; if true, only return the probability based confidence interval estimates, otherwise return |
pred |
logical; if true use the prediction interval instead of the confidence interval |
n |
integer/integerish; this is the n used to calculate the
prediction or confidence interval. When |
For a single probability, p, it uses either:
mean + qt(p, df=n)*sd/sqrt(n)
or
mean + qnorm(p)*sd/sqrt(n)
The smallest observation corresponds to a probability of 0 and the largest to a probability of 1 and the mean corresponds to 0.5.
The mean and standard deviation of the sample is calculated based on Welford's method for a single pass.
This is meant to perform in the same way as quantile()
so it can
be a drop in replacement for code using quantile()
but using
distributional assumptions.
By default the return has the probabilities as names (if
named) with the points where the expected distribution are
located given the sampling mean and standard deviation. If
onlyProbs=FALSE
then it would prepend mean, variance, standard
deviation, minimum, maximum and number of non-NA observations.
Matthew L. Fidler
quantile(x<- rnorm(1001)) meanProbs(x) # Can get some extra statistics if you request onlyProbs=FALSE meanProbs(x, onlyProbs=FALSE) x[2] <- NA_real_ meanProbs(x, onlyProbs=FALSE) quantile(x<- rnorm(42)) meanProbs(x) meanProbs(x, useT=FALSE)
quantile(x<- rnorm(1001)) meanProbs(x) # Can get some extra statistics if you request onlyProbs=FALSE meanProbs(x, onlyProbs=FALSE) x[2] <- NA_real_ meanProbs(x, onlyProbs=FALSE) quantile(x<- rnorm(42)) meanProbs(x) meanProbs(x, useT=FALSE)
Model block for rxode2/nlmixr models
## S3 method for class ''function'' model( x, ..., append = NULL, auto = getOption("rxode2.autoVarPiping", TRUE), cov = NULL, envir = parent.frame() ) ## S3 method for class 'rxUi' model( x, ..., append = NULL, auto = getOption("rxode2.autoVarPiping", TRUE), cov = NULL, envir = parent.frame() ) ## S3 method for class 'rxode2' model( x, ..., append = NULL, auto = getOption("rxode2.autoVarPiping", TRUE), cov = NULL, envir = parent.frame() ) ## S3 method for class 'rxModelVars' model( x, ..., append = NULL, auto = getOption("rxode2.autoVarPiping", TRUE), cov = NULL, envir = parent.frame() ) model( x, ..., append = FALSE, auto = getOption("rxode2.autoVarPiping", TRUE), cov = NULL, envir = parent.frame() ) ## Default S3 method: model(x, ..., append = FALSE, cov = NULL, envir = parent.frame())
## S3 method for class ''function'' model( x, ..., append = NULL, auto = getOption("rxode2.autoVarPiping", TRUE), cov = NULL, envir = parent.frame() ) ## S3 method for class 'rxUi' model( x, ..., append = NULL, auto = getOption("rxode2.autoVarPiping", TRUE), cov = NULL, envir = parent.frame() ) ## S3 method for class 'rxode2' model( x, ..., append = NULL, auto = getOption("rxode2.autoVarPiping", TRUE), cov = NULL, envir = parent.frame() ) ## S3 method for class 'rxModelVars' model( x, ..., append = NULL, auto = getOption("rxode2.autoVarPiping", TRUE), cov = NULL, envir = parent.frame() ) model( x, ..., append = FALSE, auto = getOption("rxode2.autoVarPiping", TRUE), cov = NULL, envir = parent.frame() ) ## Default S3 method: model(x, ..., append = FALSE, cov = NULL, envir = parent.frame())
x |
model expression |
... |
Other arguments |
append |
This is a boolean to determine if the lines are appended in piping. The possible values for this is:
|
auto |
This boolean tells if piping automatically selects the
parameters should be characterized as a population parameter,
between subject variability, or a covariate. When |
cov |
is a character vector of variables that should be assumed to be covariates. This will override automatic promotion to a population parameter estimate (or an eta) |
envir |
the |
Model block with ini information included. ini
must be
called before model
block
Matthew Fidler
Assign the model block in the rxode2 related object
model(x, envir = environment(x)) <- value
model(x, envir = environment(x)) <- value
x |
rxode2 related object |
envir |
Environment where assignment occurs |
value |
Value of the object |
rxode2 related object
Matthew L. Fidler
Extract model lines from a rxui model
modelExtract( x, ..., expression = FALSE, endpoint = FALSE, lines = FALSE, envir = parent.frame() ) ## S3 method for class ''function'' modelExtract( x, ..., expression = FALSE, endpoint = FALSE, lines = FALSE, envir = parent.frame() ) ## S3 method for class 'rxUi' modelExtract( x, ..., expression = FALSE, endpoint = FALSE, lines = FALSE, envir = parent.frame() ) ## S3 method for class 'rxode2' modelExtract( x, ..., expression = FALSE, endpoint = FALSE, lines = FALSE, envir = parent.frame() ) ## S3 method for class 'rxModelVars' modelExtract( x, ..., expression = FALSE, endpoint = FALSE, lines = FALSE, envir = parent.frame() ) ## Default S3 method: modelExtract( x, ..., expression = FALSE, endpoint = FALSE, lines = FALSE, envir = parent.frame() )
modelExtract( x, ..., expression = FALSE, endpoint = FALSE, lines = FALSE, envir = parent.frame() ) ## S3 method for class ''function'' modelExtract( x, ..., expression = FALSE, endpoint = FALSE, lines = FALSE, envir = parent.frame() ) ## S3 method for class 'rxUi' modelExtract( x, ..., expression = FALSE, endpoint = FALSE, lines = FALSE, envir = parent.frame() ) ## S3 method for class 'rxode2' modelExtract( x, ..., expression = FALSE, endpoint = FALSE, lines = FALSE, envir = parent.frame() ) ## S3 method for class 'rxModelVars' modelExtract( x, ..., expression = FALSE, endpoint = FALSE, lines = FALSE, envir = parent.frame() ) ## Default S3 method: modelExtract( x, ..., expression = FALSE, endpoint = FALSE, lines = FALSE, envir = parent.frame() )
x |
model to extract lines from |
... |
variables to extract. When it is missing, it will extract the entire model (conditioned on the endpoint option below) |
expression |
return expressions (if |
endpoint |
include endpoint. This can be:
|
lines |
is a boolean. When |
envir |
Environment for evaluating variables |
expressions or strings of extracted lines. Note if there is a duplicated lhs expression in the line, it will return both lines
Matthew L. Fidler
one.compartment <- function() { ini({ tka <- 0.45 # Log Ka tcl <- 1 # Log Cl tv <- 3.45 # Log V 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) d/dt(depot) <- -ka * depot d/dt(center) <- ka * depot - cl / v * center cp <- center / v cp ~ add(add.sd) }) } f <- one.compartment() modelExtract(f, cp) modelExtract(one.compartment, d/dt(depot)) # from variable var <- "d/dt(depot)" modelExtract(one.compartment, var) modelExtract(f, endpoint=NA, lines=TRUE, expression=TRUE)
one.compartment <- function() { ini({ tka <- 0.45 # Log Ka tcl <- 1 # Log Cl tv <- 3.45 # Log V 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) d/dt(depot) <- -ka * depot d/dt(center) <- ka * depot - cl / v * center cp <- center / v cp ~ add(add.sd) }) } f <- one.compartment() modelExtract(f, cp) modelExtract(one.compartment, d/dt(depot)) # from variable var <- "d/dt(depot)" modelExtract(one.compartment, var) modelExtract(f, endpoint=NA, lines=TRUE, expression=TRUE)
If NULL
is given as the method, all choices are returned as a named
vector.
odeMethodToInt(method = c("liblsoda", "lsoda", "dop853", "indLin"))
odeMethodToInt(method = c("liblsoda", "lsoda", "dop853", "indLin"))
method |
The method for solving ODEs. Currently this supports:
|
An integer for the method (unless the input is NULL, in which case, see the details)
Cumulative distribution of standard normal
phi(q)
phi(q)
q |
vector of quantiles |
cumulative distribution of standard normal distribution
Matthew Fidler
# phi is equivalent to pnorm(x) phi(3) # See pnorm(3) # This is provided for NONMEM-like compatibility in rxode2 models
# phi is equivalent to pnorm(x) phi(3) # See pnorm(3) # This is provided for NONMEM-like compatibility in rxode2 models
Plot rxode2 objects
## S3 method for class 'rxSolve' plot(x, y, ..., log = "", xlab = "Time", ylab = "") ## S3 method for class 'rxSolveConfint1' plot(x, y, ..., xlab = "Time", ylab = "", log = "") ## S3 method for class 'rxSolveConfint2' plot(x, y, ..., xlab = "Time", ylab = "", log = "")
## S3 method for class 'rxSolve' plot(x, y, ..., log = "", xlab = "Time", ylab = "") ## S3 method for class 'rxSolveConfint1' plot(x, y, ..., xlab = "Time", ylab = "", log = "") ## S3 method for class 'rxSolveConfint2' plot(x, y, ..., xlab = "Time", ylab = "", log = "")
x |
rxode2 object to plot |
y |
Compartments or left-hand-side values to plot either as a bare name or as a character vector |
... |
Ignored |
log |
Should "" (neither x nor y), "x", "y", or "xy" (or "yx") be log-scale? |
xlab , ylab
|
The x and y axis labels |
A ggplot2 object
Other rxode2 plotting:
rxTheme()
print
prints its argument and returns it invisibly (via
invisible(x)
). It is a generic function which means that
new printing methods can be easily added for new class
es.
## S3 method for class 'rxModelVars' print(x, ...)
## S3 method for class 'rxModelVars' print(x, ...)
x |
an object used to select a method. |
... |
further arguments passed to or from other methods. |
The default method, print.default
has its own help page.
Use methods("print")
to get all the methods for the
print
generic.
print.factor
allows some customization and is used for printing
ordered
factors as well.
print.table
for printing table
s allows other
customization. As of R 3.0.0, it only prints a description in case of a table
with 0-extents (this can happen if a classifier has no valid data).
See noquote
as an example of a class whose main
purpose is a specific print
method.
This returns invisibly the model variables object
Chambers, J. M. and Hastie, T. J. (1992) Statistical Models in S. Wadsworth & Brooks/Cole.
The default method print.default
, and help for the
methods above; further options
, noquote
.
For more customizable (but cumbersome) printing, see
cat
, format
or also write
.
For a simple prototypical print method, see
.print.via.format
in package tools.
require(stats) ts(1:20) #-- print is the "Default function" --> print.ts(.) is called for(i in 1:3) print(1:i) ## Printing of factors attenu$station ## 117 levels -> 'max.levels' depending on width ## ordered factors: levels "l1 < l2 < .." esoph$agegp[1:12] esoph$alcgp[1:12] ## Printing of sparse (contingency) tables set.seed(521) t1 <- round(abs(rt(200, df = 1.8))) t2 <- round(abs(rt(200, df = 1.4))) table(t1, t2) # simple print(table(t1, t2), zero.print = ".") # nicer to read ## same for non-integer "table": T <- table(t2,t1) T <- T * (1+round(rlnorm(length(T)))/4) print(T, zero.print = ".") # quite nicer, print.table(T[,2:8] * 1e9, digits=3, zero.print = ".") ## still slightly inferior to Matrix::Matrix(T) for larger T ## Corner cases with empty extents: table(1, NA) # < table of extent 1 x 0 >
require(stats) ts(1:20) #-- print is the "Default function" --> print.ts(.) is called for(i in 1:3) print(1:i) ## Printing of factors attenu$station ## 117 levels -> 'max.levels' depending on width ## ordered factors: levels "l1 < l2 < .." esoph$agegp[1:12] esoph$alcgp[1:12] ## Printing of sparse (contingency) tables set.seed(521) t1 <- round(abs(rt(200, df = 1.8))) t2 <- round(abs(rt(200, df = 1.4))) table(t1, t2) # simple print(table(t1, t2), zero.print = ".") # nicer to read ## same for non-integer "table": T <- table(t2,t1) T <- T * (1+round(rlnorm(length(T)))/4) print(T, zero.print = ".") # quite nicer, print.table(T[,2:8] * 1e9, digits=3, zero.print = ".") ## still slightly inferior to Matrix::Matrix(T) for larger T ## Corner cases with empty extents: table(1, NA) # < table of extent 1 x 0 >
probit and inverse probit functions
probit(x, low = 0, high = 1) probitInv(x, low = 0, high = 1)
probit(x, low = 0, high = 1) probitInv(x, low = 0, high = 1)
x |
Input value(s) in range [low,high] to translate -Inf to Inf |
low |
Lowest value in the range |
high |
Highest value in the range |
values from probit, probitInv and probitNormInfo
probit(0.25) probitInv(-0.674) probitNormInfo(probit(0.25), sd = 0.1) probitNormInfo(probit(1, 0, 10), sd = 1, low = 0, high = 10)
probit(0.25) probitInv(-0.674) probitNormInfo(probit(0.25), sd = 0.1) probitNormInfo(probit(1, 0, 10), sd = 1, low = 0, high = 10)
Scaled Inverse Chi Squared distribution
rinvchisq(n = 1L, nu = 1, scale = 1)
rinvchisq(n = 1L, nu = 1, scale = 1)
n |
Number of random samples |
nu |
degrees of freedom of inverse chi square |
scale |
Scale of inverse chi squared distribution (default is 1). |
a vector of inverse chi squared deviates.
rinvchisq(3, 4, 1) ## Scale = 1, degrees of freedom = 4 rinvchisq(2, 4, 2) ## Scale = 2, degrees of freedom = 4
rinvchisq(3, 4, 1) ## Scale = 1, degrees of freedom = 4 rinvchisq(2, 4, 2) ## Scale = 2, degrees of freedom = 4
Allow unloading of dlls
rxAllowUnload(allow)
rxAllowUnload(allow)
allow |
boolean indicating if garbage collection will unload of rxode2 dlls. |
Boolean allow; called for side effects
Matthew Fidler
# Garbage collection will not unload un-used rxode2 dlls rxAllowUnload(FALSE); # Garbage collection will unload unused rxode2 dlls rxAllowUnload(TRUE);
# Garbage collection will not unload un-used rxode2 dlls rxAllowUnload(FALSE); # Garbage collection will unload unused rxode2 dlls rxAllowUnload(TRUE);
Append two rxui models together
rxAppendModel(..., common = TRUE)
rxAppendModel(..., common = TRUE)
... |
models to append together |
common |
boolean that determines if you need a common value to bind |
New model with both models appended together
Matthew L. Fidler
ocmt <- function() { ini({ tka <- exp(0.45) # Ka tcl <- exp(1) # Cl tv <- exp(3.45); # log V ## the label("Label name") works with all models add.sd <- 0.7 }) model({ ka <- tka cl <- tcl v <- tv d/dt(depot) <- -ka * depot d/dt(center) <- ka * depot - cl / v * center cp <- center / v cp ~ add(add.sd) }) } idr <- function() { ini({ tkin <- log(1) tkout <- log(1) tic50 <- log(10) gamma <- fix(1) idr.sd <- 1 }) model({ kin <- exp(tkin) kout <- exp(tkout) ic50 <- exp(tic50) d/dt(eff) <- kin - kout*(1-ceff^gamma/(ic50^gamma+ceff^gamma)) eff ~ add(idr.sd) }) } rxAppendModel(ocmt %>% model(ceff=cp,append=TRUE), idr)
ocmt <- function() { ini({ tka <- exp(0.45) # Ka tcl <- exp(1) # Cl tv <- exp(3.45); # log V ## the label("Label name") works with all models add.sd <- 0.7 }) model({ ka <- tka cl <- tcl v <- tv d/dt(depot) <- -ka * depot d/dt(center) <- ka * depot - cl / v * center cp <- center / v cp ~ add(add.sd) }) } idr <- function() { ini({ tkin <- log(1) tkout <- log(1) tic50 <- log(10) gamma <- fix(1) idr.sd <- 1 }) model({ kin <- exp(tkin) kout <- exp(tkout) ic50 <- exp(tic50) d/dt(eff) <- kin - kout*(1-ceff^gamma/(ic50^gamma+ceff^gamma)) eff ~ add(idr.sd) }) } rxAppendModel(ocmt %>% model(ceff=cp,append=TRUE), idr)
Assign Control Variable
rxAssignControlValue(ui, option, value)
rxAssignControlValue(ui, option, value)
ui |
rxode2 ui function |
option |
Option name in the control to modify |
value |
Value of control to modify |
Nothing; called for the side effects
Matthew L. Fidler
Assign pointer based on model variables
rxAssignPtr(object = NULL)
rxAssignPtr(object = NULL)
object |
rxode2 family of objects |
nothing, called for side effects
Care should be taken with this method not to encounter the
birthday problem, described
https://www.johndcook.com/blog/2016/01/29/random-number-generator-seed-mistakes/.
Since the sitmo
threefry
, this currently generates
one random deviate from the uniform distribution to seed the
engine threefry
and then run the code.
rxbeta(shape1, shape2, n = 1L, ncores = 1L)
rxbeta(shape1, shape2, n = 1L, ncores = 1L)
shape1 , shape2
|
non-negative parameters of the Beta distribution. |
n |
number of observations. If |
ncores |
Number of cores for the simulation
|
Therefore, a simple call to the random number generated followed by a second call to random number generated may have identical seeds. As the number of random number generator calls are increased the probability that the birthday problem will increase.
The key to avoid this problem is to either run all simulations in the
rxode2
environment once (therefore one seed or series of seeds
for the whole simulation), pre-generate all random variables
used for the simulation, or seed the rxode2 engine with rxSetSeed()
Internally each ID is seeded with a unique number so that the results do not depend on the number of cores used.
beta random deviates
## Use threefry engine rxbeta(0.5, 0.5, n = 10) # with rxbeta you have to explicitly state n rxbeta(5, 1, n = 10, ncores = 2) # You can parallelize the simulation using openMP rxbeta(1, 3) ## This example uses `rxbeta` directly in the model rx <- function() { model({ a <- rxbeta(2, 2) }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
## Use threefry engine rxbeta(0.5, 0.5, n = 10) # with rxbeta you have to explicitly state n rxbeta(5, 1, n = 10, ncores = 2) # You can parallelize the simulation using openMP rxbeta(1, 3) ## This example uses `rxbeta` directly in the model rx <- function() { model({ a <- rxbeta(2, 2) }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
Care should be taken with this method not to encounter the
birthday problem, described
https://www.johndcook.com/blog/2016/01/29/random-number-generator-seed-mistakes/.
Since the sitmo
threefry
, this currently generates
one random deviate from the uniform distribution to seed the
engine threefry
and then run the code.
rxbinom(size, prob, n = 1L, ncores = 1L)
rxbinom(size, prob, n = 1L, ncores = 1L)
size |
number of trials (zero or more). |
prob |
probability of success on each trial. |
n |
number of observations. If |
ncores |
Number of cores for the simulation
|
Therefore, a simple call to the random number generated followed by a second call to random number generated may have identical seeds. As the number of random number generator calls are increased the probability that the birthday problem will increase.
The key to avoid this problem is to either run all simulations in the
rxode2
environment once (therefore one seed or series of seeds
for the whole simulation), pre-generate all random variables
used for the simulation, or seed the rxode2 engine with rxSetSeed()
Internally each ID is seeded with a unique number so that the results do not depend on the number of cores used.
binomial random deviates
## Use threefry engine rxbinom(10, 0.9, n = 10) # with rxbinom you have to explicitly state n rxbinom(3, 0.5, n = 10, ncores = 2) # You can parallelize the simulation using openMP rxbinom(4, 0.7) ## This example uses `rxbinom` directly in the model rx <- function() { model({ a <- rxbinom(1, 0.5) }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
## Use threefry engine rxbinom(10, 0.9, n = 10) # with rxbinom you have to explicitly state n rxbinom(3, 0.5, n = 10, ncores = 2) # You can parallelize the simulation using openMP rxbinom(4, 0.7) ## This example uses `rxbinom` directly in the model rx <- function() { model({ a <- rxbinom(1, 0.5) }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
Care should be taken with this method not to encounter the
birthday problem, described
https://www.johndcook.com/blog/2016/01/29/random-number-generator-seed-mistakes/.
Since the sitmo
threefry
, this currently generates
one random deviate from the uniform distribution to seed the
engine threefry
and then run the code.
rxcauchy(location = 0, scale = 1, n = 1L, ncores = 1L)
rxcauchy(location = 0, scale = 1, n = 1L, ncores = 1L)
location , scale
|
location and scale parameters. |
n |
number of observations. If |
ncores |
Number of cores for the simulation
|
Therefore, a simple call to the random number generated followed by a second call to random number generated may have identical seeds. As the number of random number generator calls are increased the probability that the birthday problem will increase.
The key to avoid this problem is to either run all simulations in the
rxode2
environment once (therefore one seed or series of seeds
for the whole simulation), pre-generate all random variables
used for the simulation, or seed the rxode2 engine with rxSetSeed()
Internally each ID is seeded with a unique number so that the results do not depend on the number of cores used.
Cauchy random deviates
## Use threefry engine rxcauchy(0, 1, n = 10) # with rxcauchy you have to explicitly state n rxcauchy(0.5, n = 10, ncores = 2) # You can parallelize the simulation using openMP rxcauchy(3) ## This example uses `rxcauchy` directly in the model rx <- function() { model({ a <- rxcauchy(2) }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
## Use threefry engine rxcauchy(0, 1, n = 10) # with rxcauchy you have to explicitly state n rxcauchy(0.5, n = 10, ncores = 2) # You can parallelize the simulation using openMP rxcauchy(3) ## This example uses `rxcauchy` directly in the model rx <- function() { model({ a <- rxcauchy(2) }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
Bind the study parameters and individual parameters
rxCbindStudyIndividual(studyParameters, individualParameters)
rxCbindStudyIndividual(studyParameters, individualParameters)
studyParameters |
These are the study parameters, often can be generated by sampling from a population. This can be either a matrix or a data frame |
individualParameters |
A data frame of individual parameters |
Data frame that can be used in rxode2 simulations
Matthew Fidler
# Function for coverting coefficient of covariance into a variance lognCv <- function(x){log((x/100)^2+1)} set.seed(32) nSub <- 100 nStud <- 10 #define theta theta <- c(lka=log(0.5), # log ka lCl=log(5), # log Cl lV=log(300) # log V ) #define theta Matrix thetaMat <- lotri(lCl ~ lognCv(5), lV ~ lognCv(5), lka ~ lognCv(5)) nev <- nSub*nStud ev1 <- data.frame(COV1=rnorm(nev,50,30),COV2=rnorm(nev,75,10), COV3=sample(c(1.0,2.0),nev,replace=TRUE)) tmat <-rxRmvn(nStud, theta[dimnames(thetaMat)[[1]]], thetaMat) rxCbindStudyIndividual(tmat, ev1)
# Function for coverting coefficient of covariance into a variance lognCv <- function(x){log((x/100)^2+1)} set.seed(32) nSub <- 100 nStud <- 10 #define theta theta <- c(lka=log(0.5), # log ka lCl=log(5), # log Cl lV=log(300) # log V ) #define theta Matrix thetaMat <- lotri(lCl ~ lognCv(5), lV ~ lognCv(5), lka ~ lognCv(5)) nev <- nSub*nStud ev1 <- data.frame(COV1=rnorm(nev,50,30),COV2=rnorm(nev,75,10), COV3=sample(c(1.0,2.0),nev,replace=TRUE)) tmat <-rxRmvn(nStud, theta[dimnames(thetaMat)[[1]]], thetaMat) rxCbindStudyIndividual(tmat, ev1)
Care should be taken with this method not to encounter the
birthday problem, described
https://www.johndcook.com/blog/2016/01/29/random-number-generator-seed-mistakes/.
Since the sitmo
threefry
, this currently generates
one random deviate from the uniform distribution to seed the
engine threefry
and then run the code.
rxchisq(df, n = 1L, ncores = 1L)
rxchisq(df, n = 1L, ncores = 1L)
df |
degrees of freedom (non-negative, but can be non-integer). |
n |
number of observations. If |
ncores |
Number of cores for the simulation
|
Therefore, a simple call to the random number generated followed by a second call to random number generated may have identical seeds. As the number of random number generator calls are increased the probability that the birthday problem will increase.
The key to avoid this problem is to either run all simulations in the
rxode2
environment once (therefore one seed or series of seeds
for the whole simulation), pre-generate all random variables
used for the simulation, or seed the rxode2 engine with rxSetSeed()
Internally each ID is seeded with a unique number so that the results do not depend on the number of cores used.
chi squared random deviates
## Use threefry engine rxchisq(0.5, n = 10) # with rxchisq you have to explicitly state n rxchisq(5, n = 10, ncores = 2) # You can parallelize the simulation using openMP rxchisq(1) ## This example uses `rxchisq` directly in the model rx <- function() { model({ a <- rxchisq(2) }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
## Use threefry engine rxchisq(0.5, n = 10) # with rxchisq you have to explicitly state n rxchisq(5, n = 10, ncores = 2) # You can parallelize the simulation using openMP rxchisq(1) ## This example uses `rxchisq` directly in the model rx <- function() { model({ a <- rxchisq(2) }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
This cleans up any rxode2 loaded DLLs
rxClean(wd)
rxClean(wd)
wd |
What directory should be cleaned; (DEPRECIATED), this no longer does anything. This unloads all rxode2 anonymous dlls. |
TRUE if successful
Matthew L. Fidler
This is the compilation workhorse creating the rxode2 model DLL files.
rxCompile( model, dir, prefix, force = FALSE, modName = NULL, package = NULL, ... ) ## S3 method for class 'rxModelVars' rxCompile( model, dir = NULL, prefix = NULL, force = FALSE, modName = NULL, package = NULL, ... ) ## S3 method for class 'character' rxCompile( model, dir = NULL, prefix = NULL, force = FALSE, modName = NULL, package = NULL, ... ) ## S3 method for class 'rxDll' rxCompile(model, ...) ## S3 method for class 'rxode2' rxCompile(model, ...)
rxCompile( model, dir, prefix, force = FALSE, modName = NULL, package = NULL, ... ) ## S3 method for class 'rxModelVars' rxCompile( model, dir = NULL, prefix = NULL, force = FALSE, modName = NULL, package = NULL, ... ) ## S3 method for class 'character' rxCompile( model, dir = NULL, prefix = NULL, force = FALSE, modName = NULL, package = NULL, ... ) ## S3 method for class 'rxDll' rxCompile(model, ...) ## S3 method for class 'rxode2' rxCompile(model, ...)
model |
This is the ODE model specification. It can be:
An ODE expression enclosed in (see also the |
dir |
This is the model directory where the C file will be stored for compiling. If unspecified, the C code is stored in a temporary directory, then the model is compiled and moved to the current directory. Afterwards the C code is removed. If specified, the C code is stored in the specified directory and then compiled in that directory. The C code is not removed after the DLL is created in the same directory. This can be useful to debug the c-code outputs. |
prefix |
is a string indicating the prefix to use in the C based functions. If missing, it is calculated based on file name, or md5 of parsed model. |
force |
is a boolean stating if the (re)compile should be forced if rxode2 detects that the models are the same as already generated. |
modName |
a string to be used as the model name. This string
is used for naming various aspects of the computations,
including generating C symbol names, dynamic libraries,
etc. Therefore, it is necessary that |
package |
Package name for pre-compiled binaries. |
... |
Other arguments sent to the |
An rxDll object that has the following components
dll
DLL path
model
model specification
.c
A function to call C code in the correct context from the DLL
using the .C()
function.
.call
A function to call C code in the correct context from the DLL
using the .Call()
function.
args
A list of the arguments used to create the rxDll object.
Matthew L.Fidler
This assumes the normal ODE equations are the first equations and the ODE is expanded by the forward sensitivities or other type of sensitivity (like adjoint)
rxControlUpdateSens(rxControl, sensCmt = NULL, ncmt = NULL)
rxControlUpdateSens(rxControl, sensCmt = NULL, ncmt = NULL)
rxControl |
Input list or rxControl type of list |
sensCmt |
Number of sensitivity compartments |
ncmt |
Number of compartments |
Updated rxControl where $atol
, $rtol
, $ssAtol
$ssRtol
are updated with different sensitivities for the normal
ODEs (first) and a different sensitivity for the larger
compartments (sensitivities).
Matthew L. Fidler
tmp <- rxControl() tmp2 <- rxControlUpdateSens(tmp, 3, 6) tmp2$atol tmp2$rtol tmp2$ssAtol tmp2$ssRtol
tmp <- rxControl() tmp2 <- rxControlUpdateSens(tmp, 3, 6) tmp2$atol tmp2$rtol tmp2$ssAtol tmp2$ssRtol
When run, if the R_user_dir
for rxode2's cache isn't present,
create the cache
rxCreateCache()
rxCreateCache()
nothing
Matthew Fidler
Add to rxode2's derivative tables
rxD(name, derivatives)
rxD(name, derivatives)
name |
Function Name |
derivatives |
A list of functions. Each function takes the same number of arguments as the original function. The first function will construct the derivative with respect to the first argument; The second function will construct the derivitive with respect to the second argument, and so on. |
nothing
Matthew Fidler
## Add an arbitrary list of derivative functions ## In this case the fun(x,y) is assumed to be 0.5*x^2+0.5*y^2 rxD("fun", list( function(x, y) { return(x) }, function(x, y) { return(y) } ))
## Add an arbitrary list of derivative functions ## In this case the fun(x,y) is assumed to be 0.5*x^2+0.5*y^2 rxD("fun", list( function(x, y) { return(x) }, function(x, y) { return(y) } ))
This function deletes the DLL, but doesn't delete the model information in the object.
rxDelete(obj)
rxDelete(obj)
obj |
rxode2 family of objects |
A boolean stating if the operation was successful.
Matthew L.Fidler
This calculates the derived parameters based on what is provided in a data frame or arguments
rxDerived(..., verbose = FALSE, digits = 0)
rxDerived(..., verbose = FALSE, digits = 0)
... |
The input can be:
|
verbose |
boolean that when TRUE provides a message about the detected pk parameters
and the detected compartmental model. By default this is |
digits |
represents the number of significant digits for the output; If the number is zero or below (default), do not round. |
Return a data.frame of derived PK parameters for a 1-, 2-, or 3-compartment linear model given provided clearances and volumes based on the inferred model type.
The model parameters that will be provided in the data frame are:
vc
: Central Volume (for 1-, 2- and 3-
compartment models)
kel
: First-order elimination rate (for 1-, 2-, and
3-compartment models)
k12
: First-order rate of transfer from central to
first peripheral compartment; (for 2- and 3-compartment models)
k21
: First-order rate of transfer from first
peripheral to central compartment, (for 2- and 3-compartment
models)
k13
: First-order rate of transfer from central to
second peripheral compartment; (3-compartment model)
k31
: First-order rate of transfer from second
peripheral to central compartment (3-compartment model)
vp
: Peripheral Volume (for 2- and 3- compartment models)
vp2
: Peripheral Volume for 3rd compartment (3- compartment model)
vss
: Volume of distribution at steady state; (1-, 2-, and 3-compartment models)
t12alpha
: ; (1-, 2-, and 3-compartment models)
t12beta
: ; (2- and 3-compartment models)
t12gamma
: ; (3-compartment model)
alpha
: ; (1-, 2-, and 3-compartment models)
beta
: ; (2- and 3-compartment models)
gamma
: ; (3-compartment model)
A
: true A
; (1-, 2-, and 3-compartment models)
B
: true B
; (2- and 3-compartment models)
C
: true C
; (3-compartment model)
fracA
: fractional A; (1-, 2-, and 3-compartment models)
fracB
: fractional B; (2- and 3-compartment models)
fracC
: fractional C; (3-compartment model)
Matthew Fidler and documentation from Justin Wilkins, [email protected]
Shafer S. L. CONVERT.XLS
Rowland M, Tozer TN. Clinical Pharmacokinetics and Pharmacodynamics: Concepts and Applications (4th). Clipping Williams & Wilkins, Philadelphia, 2010.
## Note that rxode2 parses the names to figure out the best PK parameter params <- rxDerived(cl = 29.4, v = 23.4, Vp = 114, vp2 = 4614, q = 270, q2 = 73) ## That is why this gives the same results as the value before params <- rxDerived(CL = 29.4, V1 = 23.4, V2 = 114, V3 = 4614, Q2 = 270, Q3 = 73) ## You may also use micro-constants alpha/beta etc. params <- rxDerived(k12 = 0.1, k21 = 0.2, k13 = 0.3, k31 = 0.4, kel = 10, v = 10) ## or you can mix vectors and scalars params <- rxDerived(CL = 29.4, V = 1:3) ## If you want, you can round to a number of significant digits ## with the `digits` argument: params <- rxDerived(CL = 29.4, V = 1:3, digits = 2)
## Note that rxode2 parses the names to figure out the best PK parameter params <- rxDerived(cl = 29.4, v = 23.4, Vp = 114, vp2 = 4614, q = 270, q2 = 73) ## That is why this gives the same results as the value before params <- rxDerived(CL = 29.4, V1 = 23.4, V2 = 114, V3 = 4614, Q2 = 270, Q3 = 73) ## You may also use micro-constants alpha/beta etc. params <- rxDerived(k12 = 0.1, k21 = 0.2, k13 = 0.3, k31 = 0.4, kel = 10, v = 10) ## or you can mix vectors and scalars params <- rxDerived(CL = 29.4, V = 1:3) ## If you want, you can round to a number of significant digits ## with the `digits` argument: params <- rxDerived(CL = 29.4, V = 1:3, digits = 2)
Return Jacobain and parameter derivatives
rxDfdy(obj)
rxDfdy(obj)
obj |
rxode2 family of objects |
A list of the jacobian parameters defined in this rxode2 object.
Matthew L. Fidler
Other Query model information:
rxInits()
,
rxLhs()
,
rxModelVars()
,
rxParams()
,
rxState()
Dispatch solve to 'rxode2' solve
rxEtDispatchSolve(x, ...) ## Default S3 method: rxEtDispatchSolve(x, ...)
rxEtDispatchSolve(x, ...) ## Default S3 method: rxEtDispatchSolve(x, ...)
x |
rxode2 solve dispatch object |
... |
other arguments |
if 'rxode2' is loaded, a solved object, otherwise an error
Matthew L. Fidler
This is to make an EVID more readable by non pharmacometricians. It displays what each means and allows it to be displayed in a tibble.
rxEvid(x) as.rxEvid(x) ## S3 method for class 'rxEvid' c(x, ...) ## S3 method for class 'rxEvid' x[...] ## S3 method for class 'rxEvid' as.character(x, ...) ## S3 method for class 'rxEvid' x[[...]] ## S3 method for class 'rxRateDur' c(x, ...) ## S3 method for class 'rxEvid' format(x, ...) ## S3 method for class 'rxRateDur' format(x, ...) ## S3 method for class 'rxEvid' print(x, ...)
rxEvid(x) as.rxEvid(x) ## S3 method for class 'rxEvid' c(x, ...) ## S3 method for class 'rxEvid' x[...] ## S3 method for class 'rxEvid' as.character(x, ...) ## S3 method for class 'rxEvid' x[[...]] ## S3 method for class 'rxRateDur' c(x, ...) ## S3 method for class 'rxEvid' format(x, ...) ## S3 method for class 'rxRateDur' format(x, ...) ## S3 method for class 'rxEvid' print(x, ...)
x |
Item to be converted to a rxode2 EVID specification. |
... |
Other parameters |
rxEvid specification
rxEvid(1:7)
rxEvid(1:7)
Care should be taken with this method not to encounter the
birthday problem, described
https://www.johndcook.com/blog/2016/01/29/random-number-generator-seed-mistakes/.
Since the sitmo
threefry
, this currently generates
one random deviate from the uniform distribution to seed the
engine threefry
and then run the code.
rxexp(rate, n = 1L, ncores = 1L)
rxexp(rate, n = 1L, ncores = 1L)
rate |
vector of rates. |
n |
number of observations. If |
ncores |
Number of cores for the simulation
|
Therefore, a simple call to the random number generated followed by a second call to random number generated may have identical seeds. As the number of random number generator calls are increased the probability that the birthday problem will increase.
The key to avoid this problem is to either run all simulations in the
rxode2
environment once (therefore one seed or series of seeds
for the whole simulation), pre-generate all random variables
used for the simulation, or seed the rxode2 engine with rxSetSeed()
Internally each ID is seeded with a unique number so that the results do not depend on the number of cores used.
exponential random deviates
## Use threefry engine rxexp(0.5, n = 10) # with rxexp you have to explicitly state n rxexp(5, n = 10, ncores = 2) # You can parallelize the simulation using openMP rxexp(1) ## This example uses `rxexp` directly in the model rx <- function() { model({ a <- rxexp(2) }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
## Use threefry engine rxexp(0.5, n = 10) # with rxexp you have to explicitly state n rxexp(5, n = 10, ncores = 2) # You can parallelize the simulation using openMP rxexp(1) ## This example uses `rxexp` directly in the model rx <- function() { model({ a <- rxexp(2) }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
Care should be taken with this method not to encounter the
birthday problem, described
https://www.johndcook.com/blog/2016/01/29/random-number-generator-seed-mistakes/.
Since the sitmo
threefry
, this currently generates
one random deviate from the uniform distribution to seed the
engine threefry
and then run the code.
rxf(df1, df2, n = 1L, ncores = 1L)
rxf(df1, df2, n = 1L, ncores = 1L)
df1 , df2
|
degrees of freedom. |
n |
number of observations. If |
ncores |
Number of cores for the simulation
|
Therefore, a simple call to the random number generated followed by a second call to random number generated may have identical seeds. As the number of random number generator calls are increased the probability that the birthday problem will increase.
The key to avoid this problem is to either run all simulations in the
rxode2
environment once (therefore one seed or series of seeds
for the whole simulation), pre-generate all random variables
used for the simulation, or seed the rxode2 engine with rxSetSeed()
Internally each ID is seeded with a unique number so that the results do not depend on the number of cores used.
f random deviates
## Use threefry engine rxf(0.5, 0.5, n = 10) # with rxf you have to explicitly state n rxf(5, 1, n = 10, ncores = 2) # You can parallelize the simulation using openMP rxf(1, 3) ## This example uses `rxf` directly in the model rx <- function() { model({ a <- rxf(2, 2) }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
## Use threefry engine rxf(0.5, 0.5, n = 10) # with rxf you have to explicitly state n rxf(5, 1, n = 10, ncores = 2) # You can parallelize the simulation using openMP rxf(1, 3) ## This example uses `rxf` directly in the model rx <- function() { model({ a <- rxf(2, 2) }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
Apply the fixed population estimated parameters
rxFixPop(ui, returnNull = FALSE)
rxFixPop(ui, returnNull = FALSE)
ui |
rxode2 ui function |
returnNull |
boolean for if unchanged values should return the
original ui ( |
when returnNull
is TRUE, NULL if nothing was changed, or
the changed model ui. When returnNull
is FALSE, return a ui no
matter if it is changed or not.
Matthew L. Fidler
One.comp.transit.allo <- function() { ini({ # Where initial conditions/variables are specified lktr <- log(1.15) #log k transit (/h) lcl <- log(0.15) #log Cl (L/hr) lv <- log(7) #log V (L) ALLC <- fix(0.75) #allometric exponent cl ALLV <- fix(1.00) #allometric exponent v prop.err <- 0.15 #proportional error (SD/mean) add.err <- 0.6 #additive error (mg/L) eta.ktr ~ 0.5 eta.cl ~ 0.1 eta.v ~ 0.1 }) model({ #Allometric scaling on weight cl <- exp(lcl + eta.cl + ALLC * logWT70) v <- exp(lv + eta.v + ALLV * logWT70) ktr <- exp(lktr + eta.ktr) # RxODE-style differential equations are supported d/dt(depot) = -ktr * depot d/dt(central) = ktr * trans - (cl/v) * central d/dt(trans) = ktr * depot - ktr * trans ## Concentration is calculated cp = central/v # And is assumed to follow proportional and additive error cp ~ prop(prop.err) + add(add.err) }) } m <- rxFixPop(One.comp.transit.allo) m # now everything is already fixed, so calling again will do nothing rxFixPop(m) # if you call it with returnNull=TRUE when no changes have been # performed, the function will return NULL rxFixPop(m, returnNull=TRUE)
One.comp.transit.allo <- function() { ini({ # Where initial conditions/variables are specified lktr <- log(1.15) #log k transit (/h) lcl <- log(0.15) #log Cl (L/hr) lv <- log(7) #log V (L) ALLC <- fix(0.75) #allometric exponent cl ALLV <- fix(1.00) #allometric exponent v prop.err <- 0.15 #proportional error (SD/mean) add.err <- 0.6 #additive error (mg/L) eta.ktr ~ 0.5 eta.cl ~ 0.1 eta.v ~ 0.1 }) model({ #Allometric scaling on weight cl <- exp(lcl + eta.cl + ALLC * logWT70) v <- exp(lv + eta.v + ALLV * logWT70) ktr <- exp(lktr + eta.ktr) # RxODE-style differential equations are supported d/dt(depot) = -ktr * depot d/dt(central) = ktr * trans - (cl/v) * central d/dt(trans) = ktr * depot - ktr * trans ## Concentration is calculated cp = central/v # And is assumed to follow proportional and additive error cp ~ prop(prop.err) + add(add.err) }) } m <- rxFixPop(One.comp.transit.allo) m # now everything is already fixed, so calling again will do nothing rxFixPop(m) # if you call it with returnNull=TRUE when no changes have been # performed, the function will return NULL rxFixPop(m, returnNull=TRUE)
Add/Create C functions for use in rxode2
rxFun(name, args, cCode) rxRmFun(name)
rxFun(name, args, cCode) rxRmFun(name)
name |
This can either give the name of the user function or be a simple R function that you wish to convert to C. If you have rxode2 convert the R function to C, the name of the function will match the function name provided and the number of arguments will match the R function provided. Hence, if you are providing an R function for conversion to C, the rest of the arguments are implied. |
args |
This gives the arguments of the user function |
cCode |
This is the C-code for the new function |
# Right now rxode2 is not aware of the function fun # Therefore it cannot translate it to symengine or # Compile a model with it. try(rxode2("a=fun(a,b,c)")) # Note for this approach to work, it cannot interfere with C # function names or reserved rxode2 special terms. Therefore # f(x) would not work since f is an alias for bioavailability. fun <- " double fun(double a, double b, double c) { return a*a+b*a+c; } " # C-code for function rxFun("fun", c("a", "b", "c"), fun) ## Added function # Now rxode2 knows how to translate this function to symengine rxToSE("fun(a,b,c)") # And will take a central difference when calculating derivatives rxFromSE("Derivative(fun(a,b,c),a)") ## Of course, you could specify the derivative table manually rxD("fun", list( function(a, b, c) { paste0("2*", a, "+", b) }, function(a, b, c) { return(a) }, function(a, b, c) { return("0.0") } )) rxFromSE("Derivative(fun(a,b,c),a)") # You can also remove the functions by `rxRmFun` rxRmFun("fun") # you can also use R functions directly in rxode2 gg <- function(x, y) { x + y } f <- rxode2({ z = gg(x, y) }) e <- et(1:10) |> as.data.frame() e$x <- 1:10 e$y <- 21:30 rxSolve(f, e) # Note that since it touches R, it can only run single-threaded. # There are also requirements for the function: # # 1. It accepts one value per argument (numeric) # # 2. It returns one numeric value # If it is a simple function (like gg) you can also convert it to C # using rxFun and load it into rxode2 rxFun(gg) rxSolve(f, e) # to stop the recompile simply reassign the function f <- rxode2(f) rxSolve(f, e) rxRmFun("gg") rm(gg) rm(f) # You can also automatically convert a R function to R code (and # calculate first derivatives) fun <- function(a, b, c) { a^2+b*a+c } rxFun(fun) # You can see the R code if you want with rxC message(rxC("fun")) # you can also remove both the function and the # derivatives with rxRmFun("fun") rxRmFun("fun")
# Right now rxode2 is not aware of the function fun # Therefore it cannot translate it to symengine or # Compile a model with it. try(rxode2("a=fun(a,b,c)")) # Note for this approach to work, it cannot interfere with C # function names or reserved rxode2 special terms. Therefore # f(x) would not work since f is an alias for bioavailability. fun <- " double fun(double a, double b, double c) { return a*a+b*a+c; } " # C-code for function rxFun("fun", c("a", "b", "c"), fun) ## Added function # Now rxode2 knows how to translate this function to symengine rxToSE("fun(a,b,c)") # And will take a central difference when calculating derivatives rxFromSE("Derivative(fun(a,b,c),a)") ## Of course, you could specify the derivative table manually rxD("fun", list( function(a, b, c) { paste0("2*", a, "+", b) }, function(a, b, c) { return(a) }, function(a, b, c) { return("0.0") } )) rxFromSE("Derivative(fun(a,b,c),a)") # You can also remove the functions by `rxRmFun` rxRmFun("fun") # you can also use R functions directly in rxode2 gg <- function(x, y) { x + y } f <- rxode2({ z = gg(x, y) }) e <- et(1:10) |> as.data.frame() e$x <- 1:10 e$y <- 21:30 rxSolve(f, e) # Note that since it touches R, it can only run single-threaded. # There are also requirements for the function: # # 1. It accepts one value per argument (numeric) # # 2. It returns one numeric value # If it is a simple function (like gg) you can also convert it to C # using rxFun and load it into rxode2 rxFun(gg) rxSolve(f, e) # to stop the recompile simply reassign the function f <- rxode2(f) rxSolve(f, e) rxRmFun("gg") rm(gg) rm(f) # You can also automatically convert a R function to R code (and # calculate first derivatives) fun <- function(a, b, c) { a^2+b*a+c } rxFun(fun) # You can see the R code if you want with rxC message(rxC("fun")) # you can also remove both the function and the # derivatives with rxRmFun("fun") rxRmFun("fun")
Care should be taken with this method not to encounter the
birthday problem, described
https://www.johndcook.com/blog/2016/01/29/random-number-generator-seed-mistakes/.
Since the sitmo
threefry
, this currently generates
one random deviate from the uniform distribution to seed the
engine threefry
and then run the code.
rxgamma(shape, rate = 1, n = 1L, ncores = 1L)
rxgamma(shape, rate = 1, n = 1L, ncores = 1L)
shape |
The shape of the gamma random variable |
rate |
an alternative way to specify the scale. |
n |
number of observations. If |
ncores |
Number of cores for the simulation
|
Therefore, a simple call to the random number generated followed by a second call to random number generated may have identical seeds. As the number of random number generator calls are increased the probability that the birthday problem will increase.
The key to avoid this problem is to either run all simulations in the
rxode2
environment once (therefore one seed or series of seeds
for the whole simulation), pre-generate all random variables
used for the simulation, or seed the rxode2 engine with rxSetSeed()
Internally each ID is seeded with a unique number so that the results do not depend on the number of cores used.
gamma random deviates
## Use threefry engine rxgamma(0.5, n = 10) # with rxgamma you have to explicitly state n rxgamma(5, n = 10, ncores = 2) # You can parallelize the simulation using openMP rxgamma(1) ## This example uses `rxbeta` directly in the model rx <- function() { model({ a <- rxgamma(2) }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
## Use threefry engine rxgamma(0.5, n = 10) # with rxgamma you have to explicitly state n rxgamma(5, n = 10, ncores = 2) # You can parallelize the simulation using openMP rxgamma(1) ## This example uses `rxbeta` directly in the model rx <- function() { model({ a <- rxgamma(2) }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
Care should be taken with this method not to encounter the
birthday problem, described
https://www.johndcook.com/blog/2016/01/29/random-number-generator-seed-mistakes/.
Since the sitmo
threefry
, this currently generates
one random deviate from the uniform distribution to seed the
engine threefry
and then run the code.
rxgeom(prob, n = 1L, ncores = 1L)
rxgeom(prob, n = 1L, ncores = 1L)
prob |
probability of success in each trial. |
n |
number of observations. If |
ncores |
Number of cores for the simulation
|
Therefore, a simple call to the random number generated followed by a second call to random number generated may have identical seeds. As the number of random number generator calls are increased the probability that the birthday problem will increase.
The key to avoid this problem is to either run all simulations in the
rxode2
environment once (therefore one seed or series of seeds
for the whole simulation), pre-generate all random variables
used for the simulation, or seed the rxode2 engine with rxSetSeed()
Internally each ID is seeded with a unique number so that the results do not depend on the number of cores used.
geometric random deviates
## Use threefry engine rxgeom(0.5, n = 10) # with rxgeom you have to explicitly state n rxgeom(0.25, n = 10, ncores = 2) # You can parallelize the simulation using openMP rxgeom(0.75) ## This example uses `rxgeom` directly in the model rx <- function() { model({ a <- rxgeom(0.24) }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
## Use threefry engine rxgeom(0.5, n = 10) # with rxgeom you have to explicitly state n rxgeom(0.25, n = 10, ncores = 2) # You can parallelize the simulation using openMP rxgeom(0.75) ## This example uses `rxgeom` directly in the model rx <- function() { model({ a <- rxgeom(0.24) }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
rxGetControl option from ui
rxGetControl(ui, option, default)
rxGetControl(ui, option, default)
ui |
rxode2 ui object |
option |
Option to get |
default |
Default value |
Option (if present) or default value
Matthew L. Fidler
Get the linear compartment model true function
rxGetLin( model, linCmtSens = c("linCmtA", "linCmtB", "linCmtC"), verbose = FALSE )
rxGetLin( model, linCmtSens = c("linCmtA", "linCmtB", "linCmtC"), verbose = FALSE )
model |
This is the ODE model specification. It can be:
An ODE expression enclosed in (see also the |
linCmtSens |
The method to calculate the linCmt() solutions |
verbose |
When |
model with linCmt() replaced with linCmtA()
Matthew Fidler
Get rxode2 model from object
rxGetrxode2(obj)
rxGetrxode2(obj)
obj |
rxode2 family of objects |
rxode2 model
Get the rxode2 seed
rxGetSeed()
rxGetSeed()
rxode2 seed state or -1 when the seed isn't set
rxSetSeed, rxWithSeed, rxWithPreserveSeed
# without setting seed rxGetSeed() # Now set the seed rxSetSeed(42) rxGetSeed() rxnorm() rxGetSeed() # don't use the rxode2 seed again rxSetSeed(-1) rxGetSeed() rxnorm() rxGetSeed()
# without setting seed rxGetSeed() # Now set the seed rxSetSeed(42) rxGetSeed() rxnorm() rxGetSeed() # don't use the rxode2 seed again rxSetSeed(-1) rxGetSeed() rxnorm() rxGetSeed()
Format rxSolve and related objects as html.
rxHtml(x, ...) ## S3 method for class 'rxSolve' rxHtml(x, ...)
rxHtml(x, ...) ## S3 method for class 'rxSolve' rxHtml(x, ...)
x |
rxode2 object |
... |
Extra arguments sent to kable |
html code for rxSolve object
Matthew L. Fidler
Set the preferred factoring by state
rxIndLinState(preferred = NULL)
rxIndLinState(preferred = NULL)
preferred |
A list of each state's preferred factorization |
Nothing
Matthew Fidler
When there is more than one state in a ODE that cannot be separated this specifies how it is incorporated into the matrix exponential.
rxIndLinStrategy(strategy = c("curState", "split"))
rxIndLinStrategy(strategy = c("curState", "split"))
strategy |
The strategy for inductive linearization matrix building
|
Nothing
Matthew L. Fidler
Invert matrix using RcppArmadillo.
rxInv(matrix)
rxInv(matrix)
matrix |
matrix to be inverted. |
inverse or pseudo inverse of matrix.
Checks if the rxode2 object was built with the current build
rxIsCurrent(obj)
rxIsCurrent(obj)
obj |
rxode2 family of objects |
boolean indicating if this was built with current rxode2
This returns the model calculated variables
rxLhs(obj)
rxLhs(obj)
obj |
rxode2 family of objects |
a character vector listing the calculated parameters
Matthew L.Fidler
Other Query model information:
rxDfdy()
,
rxInits()
,
rxModelVars()
,
rxParams()
,
rxState()
Lock/unlocking of rxode2 dll file
rxLock(obj) rxUnlock(obj)
rxLock(obj) rxUnlock(obj)
obj |
A rxode2 family of objects |
nothing; called for side effects
Care should be taken with this method not to encounter the
birthday problem, described
https://www.johndcook.com/blog/2016/01/29/random-number-generator-seed-mistakes/.
Since the sitmo
threefry
, this currently generates
one random deviate from the uniform distribution to seed the
engine threefry
and then run the code.
rxnbinom(size, prob, n = 1L, ncores = 1L) rxnbinomMu(size, mu, n = 1L, ncores = 1L)
rxnbinom(size, prob, n = 1L, ncores = 1L) rxnbinomMu(size, mu, n = 1L, ncores = 1L)
size |
target for number of successful trials, or dispersion parameter (the shape parameter of the gamma mixing distribution). Must be strictly positive, need not be integer. |
prob |
probability of success in each trial. |
n |
number of observations. If |
ncores |
Number of cores for the simulation
|
mu |
alternative parametrization via mean: see ‘Details’. |
Therefore, a simple call to the random number generated followed by a second call to random number generated may have identical seeds. As the number of random number generator calls are increased the probability that the birthday problem will increase.
The key to avoid this problem is to either run all simulations in the
rxode2
environment once (therefore one seed or series of seeds
for the whole simulation), pre-generate all random variables
used for the simulation, or seed the rxode2 engine with rxSetSeed()
Internally each ID is seeded with a unique number so that the results do not depend on the number of cores used.
negative binomial random deviates. Note that rxbinom2
uses the mu
parameterization an the rxbinom
uses the prob
parameterization (mu=size/(prob+size)
)
## Use threefry engine rxnbinom(10, 0.9, n = 10) # with rxbinom you have to explicitly state n rxnbinom(3, 0.5, n = 10, ncores = 2) # You can parallelize the simulation using openMP rxnbinom(4, 0.7) # use mu parameter rxnbinomMu(40, 40, n=10) ## This example uses `rxbinom` directly in the model rx <- function() { model({ a <- rxnbinom(10, 0.5) }) } et <- et(1, id = 1:100) s <- rxSolve(rx, et) rx <- function() { model({ a <- rxnbinomMu(10, 40) }) } s <- rxSolve(rx, et)
## Use threefry engine rxnbinom(10, 0.9, n = 10) # with rxbinom you have to explicitly state n rxnbinom(3, 0.5, n = 10, ncores = 2) # You can parallelize the simulation using openMP rxnbinom(4, 0.7) # use mu parameter rxnbinomMu(40, 40, n=10) ## This example uses `rxbinom` directly in the model rx <- function() { model({ a <- rxnbinom(10, 0.5) }) } et <- et(1, id = 1:100) s <- rxSolve(rx, et) rx <- function() { model({ a <- rxnbinomMu(10, 40) }) } s <- rxSolve(rx, et)
This get the syntax preferred model for processing
rxNorm(obj, condition = NULL, removeInis, removeJac, removeSens)
rxNorm(obj, condition = NULL, removeInis, removeJac, removeSens)
obj |
rxode2 family of objects |
condition |
Character string of a logical condition to use
for subsetting the normalized model. When missing, and a
condition is not set via |
removeInis |
A boolean indicating if parameter initialization will be removed from the model |
removeJac |
A boolean indicating if the Jacobians will be removed. |
removeSens |
A boolean indicating if the sensitivities will be removed. |
Normalized Normal syntax (no comments)
Matthew L. Fidler
Simulate random normal variable from threefry generator
rxnormV(mean = 0, sd = 1, n = 1L, ncores = 1L) rxnorm(mean = 0, sd = 1, n = 1L, ncores = 1L)
rxnormV(mean = 0, sd = 1, n = 1L, ncores = 1L) rxnorm(mean = 0, sd = 1, n = 1L, ncores = 1L)
mean |
vector of means. |
sd |
vector of standard deviations. |
n |
number of observations |
ncores |
Number of cores for the simulation
|
normal random number deviates
## Use threefry engine rxnorm(n = 10) # with rxnorm you have to explicitly state n rxnorm(n = 10, ncores = 2) # You can parallelize the simulation using openMP rxnorm(2, 3) ## The first 2 arguments are the mean and standard deviation ## This example uses `rxnorm` directly in the model rx <- function() { model({ a <- rxnorm() }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
## Use threefry engine rxnorm(n = 10) # with rxnorm you have to explicitly state n rxnorm(n = 10, ncores = 2) # You can parallelize the simulation using openMP rxnorm(2, 3) ## The first 2 arguments are the mean and standard deviation ## This example uses `rxnorm` directly in the model rx <- function() { model({ a <- rxnorm() }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
Create a dynamic ODE-based model object suitably for translation into fast C code
rxode2( model, modName = basename(wd), wd = getwd(), filename = NULL, extraC = NULL, debug = FALSE, calcJac = NULL, calcSens = NULL, collapseModel = FALSE, package = NULL, ..., linCmtSens = c("linCmtA", "linCmtB", "linCmtC"), indLin = FALSE, verbose = FALSE, fullPrint = getOption("rxode2.fullPrint", FALSE), envir = parent.frame() ) RxODE( model, modName = basename(wd), wd = getwd(), filename = NULL, extraC = NULL, debug = FALSE, calcJac = NULL, calcSens = NULL, collapseModel = FALSE, package = NULL, ..., linCmtSens = c("linCmtA", "linCmtB", "linCmtC"), indLin = FALSE, verbose = FALSE, fullPrint = getOption("rxode2.fullPrint", FALSE), envir = parent.frame() ) rxode( model, modName = basename(wd), wd = getwd(), filename = NULL, extraC = NULL, debug = FALSE, calcJac = NULL, calcSens = NULL, collapseModel = FALSE, package = NULL, ..., linCmtSens = c("linCmtA", "linCmtB", "linCmtC"), indLin = FALSE, verbose = FALSE, fullPrint = getOption("rxode2.fullPrint", FALSE), envir = parent.frame() )
rxode2( model, modName = basename(wd), wd = getwd(), filename = NULL, extraC = NULL, debug = FALSE, calcJac = NULL, calcSens = NULL, collapseModel = FALSE, package = NULL, ..., linCmtSens = c("linCmtA", "linCmtB", "linCmtC"), indLin = FALSE, verbose = FALSE, fullPrint = getOption("rxode2.fullPrint", FALSE), envir = parent.frame() ) RxODE( model, modName = basename(wd), wd = getwd(), filename = NULL, extraC = NULL, debug = FALSE, calcJac = NULL, calcSens = NULL, collapseModel = FALSE, package = NULL, ..., linCmtSens = c("linCmtA", "linCmtB", "linCmtC"), indLin = FALSE, verbose = FALSE, fullPrint = getOption("rxode2.fullPrint", FALSE), envir = parent.frame() ) rxode( model, modName = basename(wd), wd = getwd(), filename = NULL, extraC = NULL, debug = FALSE, calcJac = NULL, calcSens = NULL, collapseModel = FALSE, package = NULL, ..., linCmtSens = c("linCmtA", "linCmtB", "linCmtC"), indLin = FALSE, verbose = FALSE, fullPrint = getOption("rxode2.fullPrint", FALSE), envir = parent.frame() )
model |
This is the ODE model specification. It can be:
An ODE expression enclosed in (see also the |
modName |
a string to be used as the model name. This string
is used for naming various aspects of the computations,
including generating C symbol names, dynamic libraries,
etc. Therefore, it is necessary that |
wd |
character string with a working directory where to
create a subdirectory according to |
filename |
A file name or connection object where the
ODE-based model specification resides. Only one of |
extraC |
Extra c code to include in the model. This can be
useful to specify functions in the model. These C functions
should usually take |
debug |
is a boolean indicating if the executable should be compiled with verbose debugging information turned on. |
calcJac |
boolean indicating if rxode2 will calculate the Jacobain according to the specified ODEs. |
calcSens |
boolean indicating if rxode2 will calculate the sensitivities according to the specified ODEs. |
collapseModel |
boolean indicating if rxode2 will remove all LHS variables when calculating sensitivities. |
package |
Package name for pre-compiled binaries. |
... |
ignored arguments. |
linCmtSens |
The method to calculate the linCmt() solutions |
indLin |
Calculate inductive linearization matrices and compile with inductive linearization support. |
verbose |
When |
fullPrint |
When using |
envir |
is the environment to look for R user functions (defaults to parent environment) |
The Rx
in the name rxode2
is meant to suggest the
abbreviation Rx for a medical prescription, and thus to
suggest the package emphasis on pharmacometrics modeling, including
pharmacokinetics (PK), pharmacodynamics (PD), disease progression,
drug-disease modeling, etc.
This basic model specification consists of one or more statements
optionally terminated by semi-colons ;
and optional comments (comments
are delimited by #
and an end-of-line).
A block of statements is a set of statements delimited by curly braces,
{ ... }
.
Statements can be either assignments, conditional if
/else if
/else
,
while
loops (can be exited by break
), special statements, or
printing statements (for debugging/testing).
Assignment statements can be:
simple assignments, where the left hand is an identifier (i.e., variable). This includes string assignments
special time-derivative assignments, where the left hand
specifies the change of the amount in the corresponding state
variable (compartment) with respect to time e.g., d/dt(depot)
:
special initial-condition assignments where the left hand
specifies the compartment of the initial condition being specified,
e.g. depot(0) = 0
special model event changes including bioavailability
(f(depot)=1
), lag time (alag(depot)=0
), modeled rate
(rate(depot)=2
) and modeled duration (dur(depot)=2
). An
example of these model features and the event specification for the
modeled infusions the rxode2 data specification is found in rxode2 events vignette.
special change point syntax, or model times. These model times
are specified by mtime(var)=time
special Jacobian-derivative assignments, where the left hand
specifies the change in the compartment ode with respect to a
variable. For example, if d/dt(y) = dy
, then a Jacobian for this
compartment can be specified as df(y)/dy(dy) = 1
. There may be
some advantage to obtaining the solution or specifying the Jacobian
for very stiff ODE systems. However, for the few stiff systems we
tried with LSODA, this actually slightly slowed down the solving.
Special string value declarations which tell what values a
string variable will take within a rxode2
solving structure. These
values will then cause a factor to be created for this variable on
solving the rxode2
model. As such, they are declared in much the
same way as R
, that is: labels(a) <- c("a1", "a2")
.
Note that assignment can be done by =
, <-
or ~
.
When assigning with the ~
operator, the simple assignments and
time-derivative assignments will not be output. Note that with the
rxode2
model functions assignment with ~
can also be overloaded with
a residual distribution specification.
Special statements can be:
Compartment declaration statements, which can change the default
dosing compartment and the assumed compartment number(s) as well as
add extra compartment names at the end (useful for multiple-endpoint
nlmixr models); These are specified by cmt(compartmentName)
Parameter declaration statements, which can make sure the input
parameters are in a certain order instead of ordering the parameters
by the order they are parsed. This is useful for keeping the
parameter order the same when using 2 different ODE models. These
are specified by param(par1, par2,...)
Variable interpolation statements, which tells the interpolation
for specific covariates. These include locf(cov1, cov2, ...)
for
last observation carried forward, nocb(cov1, cov2, ...)
for next
observation carried backward, linear(cov1, cov2, ...)
for linear
interpolation and midpoint(cov1, cov2, ...)
for midpoint
interpolation.
An example model is shown below:
# simple assignment C2 <- centr/V2 # time-derivative assignment d/dt(centr) <- F*KA*depot - CL*C2 - Q*C2 + Q*C3;
Expressions in assignment and if
statements can be numeric or logical.
Numeric expressions can include the following numeric operators +, -, *, /, ^
and those mathematical functions defined in the C or the R math
libraries (e.g., fabs
, exp
, log
, sin
, abs
).
You may also access the R’s functions in the R math libraries,
like lgammafn
for the log gamma function.
The rxode2
syntax is case-sensitive, i.e., ABC
is different than
abc
, Abc
, ABc
, etc.
Like R, Identifiers (variable names) may consist of one or more
alphanumeric, underscore _
or period .
characters, but the first
character cannot be a digit or underscore _
.
Identifiers in a model specification can refer to:
State variables in the dynamic system (e.g., compartments in a pharmacokinetics model).
Implied input variable, t
(time), tlast
(last time point), and
podo
(oral dose, in the undocumented case of absorption transit
models).
Special constants like pi
or R’s predefined constants.
Model parameters (e.g., ka
rate of absorption, CL
clearance,
etc.)
Others, as created by assignments as part of the model specification; these are referred as LHS (left-hand side) variable.
Currently, the rxode2
modeling language only recognizes system state
variables and “parameters”, thus, any values that need to be passed from
R to the ODE model (e.g., age
) should be either passed in the params
argument of the integrator function rxSolve()
or be in the supplied
event data-set.
There are certain variable names that are in the rxode2
event tables.
To avoid confusion, the following event table-related items cannot be
assigned, or used as a state but can be accessed in the rxode2 code:
cmt
dvid
addl
ss
amt
dur
rate
Rprintf
print
printf
id
However the following variables are cannot be used in a model specification:
evid
ii
Sometimes rxode2 generates variables that are fed back to rxode2.
Similarly, nlmixr2 generates some variables that are used in nlmixr
estimation and simulation. These variables start with the either the
rx
or nlmixr
prefixes. To avoid any problems, it is suggested to not
use these variables starting with either the rx
or nlmixr
prefixes.
Logical operators support the standard R operators ==
, !=
>=
<=
>
and <
. Like R these can be in if()
or while()
statements,
ifelse()
expressions. Additionally they can be in a standard
assignment. For instance, the following is valid:
cov1 = covm*(sexf == "female") + covm*(sexf != "female")
Notice that you can also use character expressions in comparisons. This
convenience comes at a cost since character comparisons are slower than
numeric expressions. Unlike R, as.numeric
or as.integer
for these
logical statements is not only not needed, but will cause an syntax
error if you try to use the function.
All the supported functions in rxode2 can be seen with the
rxSupportedFuns()
.
A brief description of the built-in functions are in the following table:
Function | Description | Aliases |
gamma(x) | The Gamma function | gammafn |
lgamma(x) | Natural logarithm of absolute value of gamma function | digamma |
digamma(x) | First derivative of lgamma | |
trigamma(x) | Second derivative of lgamma | |
tetragamma(x) | Third derivative of lgamma | |
pentagamma(x) | Fourth derivative of lgamma | |
psigamma(x, deriv) | n-th derivative of Psi, the digamma function, which is the derivative of lgammafn. In other words, digamma(x) is the same as psigamma(x,0), trigamma(x) == psigamma(x,1), etc. | |
cospi(x) | cos(pi*x) | |
sinpi(x) | sin(pi*x) | |
tanpi(x) | tan(pi*x) | |
beta(a, b) | Beta function | |
lbeta(a, b) | log Beta function | |
bessel_i(x, nu, expo) | Bessel function type I with index nu | expo==1 is unscaled expo==2 is scaled by exp(-x) |
bessel_j(x, nu) | Bessel function type J with index nu | |
bessel_k(x, ku, expo) | Bessel function type K with index nu | expo==1 is unscaled expo==2 is scaled by exp(x) |
bessel_y(x, nu) | Bessel function type Y with index nu | |
R_pow(x, y) | x^y | |
R_pow_di(x, I) | x^y | y is an integer |
log1pmx | log(1+x) - x | |
log1pexp | log(1+exp(x)) | |
expm1(x) | exp(x)-1 | |
lgamma1p(x) | log(gamma(x+1)) | |
sign(x) | Compute the signum function where sign(x) is 1, 0 -1 | |
fsign(x, y) | abs(x)*sign(y) | |
fprec(x, digits) | x rounded to digits (after the decimal point, used by signif() | |
fround(x, digits) | Round, used by R’s round() | |
ftrunc(x) | Truncated towards zero | |
abs(x) | absolute value of x | fabs |
sin(x) | sine of x | |
cos(x) | cos of x | |
tan(x) | tan of x | |
factorial(x) | factorial of x | |
lfactorial(x) | log(factorial(x)) | |
log10(x) | log base 10 | |
log2(x) | log base 2 | |
pnorm(x) | Normal CDF of x | normcdf, phi |
qnorm(x) | Normal pdf of x | norminv |
probit(x, low=0, hi=1) | Probit (normal pdf) of x transforming into a range | |
probitInv(q, low=0, hi=1) | Inverse probit of x transforming into a range | |
acos(x) | Inverse cosine | |
asin(x) | Inverse sine | |
atan(x) | Inverse tangent | |
atan2(a, b) | Four quadrant inverse tangent | |
sinh(x) | Hyperbolic sine | |
cosh(x) | Hyperbolic cosine | |
tanh(x) | Hyperbolic tangent | |
floor(x) | Downward rounding | |
ceil(x) | Upward rounding | |
logit(x, low=0, hi=1) | Logit transformation of x transforming into a range | |
expit(x, low=0, hi=1) | expit transofmration in range | invLogit, logitInv |
gammaq(a, z) | Normalized incomplete gamma from boost | |
gammaqInv(a, q) | Normalized incomplete gamma inverse from boost | |
ifelse(cond, trueValue, falseValue) | if else function | |
gammap(a, z) | Normalized lower incomplete gamma from boost | |
gammapInv(a, p) | Inverse of Normalized lower incomplete gamma from boost | |
gammapInva(x, p) | Inverse of Normalized lower incomplete gamma from boost | |
rxnorm(x) | Generate one deviate of from a normal distribution for each observation scale | |
rxnormV(x) | Generate one deviate from low discrepancy normal for each observation | |
rxcauchy | Generate one deviate from the cauchy distribution for each observation | |
rxchisq | Generate one deviate from the chisq distribution for each observation | |
rxexp | Generate one deviate from the exponential distribution for each observation | |
rxf | Generate one deviate from low discrepancy normal for each observation | |
rxgamma | Generate one deviate from the gamma distribution for each observation | |
rxbeta | Generate one deviate from the beta distribution for each observation | |
rxgeom | Generate one deviate from the geometric distribution for each observation | |
rxpois | Generate one deviate from the poission distribution for each observation | |
rxt | Generate one deviate from the t distribtuion for each observation | |
tad() or tad(x) | Time after dose (tad()) or time after dose for a compartment tad(cmt); no dose=NA | |
tad0() or tad0(x) | Time after dose (tad0()) or time after dose for a compartment tad0(cmt); no dose=0 | |
tafd() or tafd(x) | Time after first dose (tafd()) or time after first dose for a compartment tafd(cmt); no dose=NA | |
tafd0() or tafd0(x) | Time after first dose (tafd()) or time after first dose for a compartment tafd(cmt); no dose=NA | |
dosenum() | Dose Number | |
tlast() or tlast(cmt) | Time of Last dose; This takes into consideration any lag time, so if there is a dose at time 3 and a lag of 1, the time of last dose would be 4. tlast(cmt) calculates the time since last dose of a compartment; no dose=NA | |
tlast0() or tlast0(cmt) | Time of Last dose; This takes into consideration any lag time, so if there is a dose at time 3 and a lag of 1, the time of last dose would be 4. tlast(cmt) calculates the time since last dose of a compartment; no dose=0 | |
tfirst() or tfirst(cmt) | Time since first dose or time since first dose of a compartment; no dose=NA | |
tfirst0() or tfirst0(cmt) | Time since first dose or time since first dose of a compartment; no dose=0 | |
prod(…) | product of terms; This uses PreciseSums so the product will not have as much floating point errors (though it will take longer) | |
sum(…) | sum of terms; This uses PreciseSums so the product will not have as much floating point errors (though it will take longer) | |
max(…) | maximum of a group of numbers | |
min(…) | Min of a group of numbers | |
lag(parameter, number=1) | Get the lag of an input parameter; You can specify a number of lagged observations | |
lead(parameter, number=2) | Get the lead of an input parameter; You can specify a number of lead observation | |
diff(par, number=1) | Get the difference between the current parameter and the last parameter; Can change the parameter number | |
first(par) | Get the first value of an input parameter | |
last(par) | Get the last value of an input parameter | |
transit() | The transit compartment psuedo function | |
is.na() | Determine if a value is NA | |
is.nan() | Determine if a value is NaN | |
is.infinite() | Check to see if the value is infinite | |
rinorm(x) | Generate one deviate of from a normal distribution for each individual | |
rinormV(x) | Generate one deviate from low discrepancy normal for each individual | |
ricauchy | Generate one deviate from the cauchy distribution for each individual | |
richisq | Generate one deviate from the chisq distribution for each individual | |
riexp | Generate one deviate from the exponential distribution for each individual | |
rif | Generate one deviate from low discrepancy normal for each individual | |
rigamma | Generate one deviate from the gamma distribution for each individual | |
ribeta | Generate one deviate from the beta distribution for each individual | |
rigeom | Generate one deviate from the geometric distribution for each individual | |
ropois | Generate one deviate from the poission distribution for each individual | |
rit | Generate one deviate from the t distribtuion for each individual | |
simeps | Simulate EPS from possibly truncated sigma matrix. Will take sigma matrix from the current study. Simulated at the very last moment. | |
simeta | Simulate ETA from possibly truncated omega matrix. Will take the omega matrix from the current study. Simulated at the initilization of the ODE system or the intialization of lhs | |
Note that lag(cmt) =
is equivalent to alag(cmt) =
and not the same
as = lag(wt)
There are a few reserved keywords in a rxode2 model. They are in the following table:
Reserved Name | Meaning | Alias |
time | solver time | t |
podo | In Transit compartment models, last dose amount | |
tlast | Time of Last dose | |
M_E | Exp(1) | |
M_LOG2E | log2(e) | |
M_LOG10E | log10(e) | |
M_LN2 | log(2) | |
M_LN10 | log(10) | |
M_PI | pi | |
M_PI_2 | pi/2 | |
M_PI_4 | pi/4 | |
M_1_PI | 1/pi | |
M_2_PI | 2/pi | |
M_2_SQRTPI | 2/sqrt(pi) | |
M_SQRT2 | sqrt(2) | |
M_SQRT1_2 | 1/sqrt(2) | |
M_SQRT_3 | sqrt(3) | |
M_SQRT_32 | sqrt(32) | |
M_LOG10_2 | Log10(2) | |
M_2PI | 2*pi | |
M_SQRT_PI | sqrt(pi) | |
M_1_SQRT_2PI | 1/(sqrt(2*pi)) | |
M_LN_SQRT_PI | log(sqrt(pi)) | |
M_LN_SQRT_2PI | log(sqrt(2*pi)) | |
M_LN_SQRT_PId2 | log(sqrt(pi/2)) | |
pi | pi | |
NA | R’s NA value | |
NaN | Not a Number Value | |
Inf | Infinite Value | |
newind | 1: First record of individual; 2: Subsequent record of individual | NEWIND |
rxFlag | Flag for what part of the rxode2 model is being run; 1: ddt; 2: jac; 3: ini; 4: F; 5: lag; 6: rate; 7: dur; 8: mtime; 9: matrix exponential; 10: inductive linearization; 11: lhs | |
Note that rxFlag
will always output 11
or calc_lhs
since that is
where the final variables are calculated, though you can tweak or test
certain parts of rxode2
by using this flag.
In addition to ~
hiding output for certain types of output, it also is
used to specify a residual output or endpoint when the input is an
rxode2
model function (that includes the residual in the model({})
block).
These specifications are of the form:
var ~ add(add.sd)
Indicating the variable var
is the variable that represents the
individual central tendencies of the model and it also represents the
compartment specification in the data-set.
You can also change the compartment name using the |
syntax, that is:
var ~ add(add.sd) | cmt
In the above case var
represents the central tendency and cmt
represents the compartment or dvid
specification.
For normal and related distributions, you can apply the transformation on both sides by using some keywords/functions to apply these transformations.
Transformation | rxode2/nlmixr2 code |
Box-Cox | +boxCox(lambda) |
Yeo-Johnson | +yeoJohnson(lambda) |
logit-normal | +logitNorm(logit.sd, low, hi) |
probit-normal | +probitNorm(probid.sd, low, hi) |
log-normal | +lnorm(lnorm.sd) |
By default for the likelihood for all of these transformations is calculated on the untransformed scale.
For bounded variables like logit-normal or probit-normal the low and high values are defaulted to 0 and 1 if missing.
For models where you wish to have a proportional model on one of these
transformation you can replace the standard deviation with NA
To allow for more transformations, lnorm()
, probitNorm()
and
logitNorm()
can be combined the variance stabilizing yeoJohnson()
transformation.
For the normal and t-related distributions, we wanted to keep the
ability to use skewed distributions additive and proportional in the
t/cauchy-space, so these distributions are specified differently in
comparison to the other supported distributions within nlmixr2
:
Distribution | How to Add | Example |
Normal (log-likelihood) | +dnorm() | cc ~ add(add.sd) + dnorm() |
T-distribution | +dt(df) | cc ~a dd(add.sd) + dt(df) |
Cauchy (t with df=1) | +dcauchy() | cc ~ add(add.sd) + dcauchy() |
Note that with the normal and t-related distributions nlmixr2
will
calculate cwres
and npde
under the normal assumption to help assess
the goodness of the fit of the model.
Also note that the +dnorm()
is mostly for testing purposes and will
slow down the estimation procedure in nlmixr2
. We suggest not adding
it (except for explicit testing). When there are multiple endpoint
models that mix non-normal and normal distributions, the whole problem
is shifted to a log-likelihood method for estimation in nlmixr2
.
There are two different ways to specify additive and proportional models, which we will call combined1 and combined2, the same way that Monolix calls the two distributions (to avoid between software differences in naming).
The first, combined1, assumes that the additive and proportional differences are on the standard deviation scale, or:
y=f+(a+b* f^c)*err
The second, combined2, assumes that the additive and proportional differences are combined on a variance scale:
y=f+[sqrt(a^2+b^2 *f^(2c))]*err
The default in nlmixr2
/rxode2
if not otherwise specified is
combined2 since it mirrors how adding 2 normal distributions in
statistics will add their variances (not the standard deviations).
However, the combined1 can describe the data possibly even better
than combined2 so both are possible options in rxode2
/nlmixr2
.
For residuals that are not related to normal, t-distribution or cauchy, often the residual specification is of the form:
cmt ~ dbeta(alpha, beta)
Where the compartment specification is on the left handed side of the specification.
For generalized likelihood you can specify:
ll(cmt) ~ llik specification
Finally, ordinal likelihoods/simulations can be specified in 2 ways. The first is:
err ~ c(p0, p1, p2)
Here err
represents the compartment and p0
is the probability of
being in a specific category:
Category | Probability |
1 | p0 |
2 | p1 |
3 | p2 |
4 | 1-p0-p1-p2 |
It is up to the model to ensure that the sum of the p
values are less
than 1
. Additionally you can write an arbitrary number of categories
in the ordinal model described above.
It seems a little off that p0
is the probability for category 1
and
sometimes scores are in non-whole numbers. This can be modeled as
follows:
err ~ c(p0=0, p1=1, p2=2, 3)
Here the numeric categories are specified explicitly, and the probabilities remain the same:
Category | Probability |
0 | p0 |
1 | p1 |
2 | p2 |
3 | 1-p0-p1-p2 |
In general all the that are supported are in the following table
(available in rxode2::rxResidualError
)
Error model | Functional Form | Transformation | code | addProp | lhs |
constant | None | var ~ add(add.sd) | response variable | ||
proportional | None | var ~ prop(prop.sd) | response variable | ||
power | None | var ~ pow(pow.sd, exponent) | response variable | ||
additive+proportional | combined1 | None | var ~ add(add.sd) + prop(prop.sd) + combined1() | addProp=1 | response variable |
additive+proportional | combined2 | None | var ~ add(add.sd) + prop(prop.sd) + combined2() | addProp=2 | response variable |
additive+power | combined1 | None | var ~ add(add.sd) + pow(pow.sd, exponent) + combined1() | addProp=1 | response variable |
additive+power | combined2 | None | var ~ add(add.sd) + pow(pow.sd, exponent) + combined2() | addProp=2 | response variable |
constant | log | var ~ lnorm(add.sd) | response variable | ||
proportional | log | var ~ lnorm(NA) + prop(prop.sd) | response variable | ||
power | log | var ~ lnorm(NA) + pow(pow.sd, exponent) | response variable | ||
additive+proportional | combined1 | log | var ~ lnorm(add.sd) + prop(prop.sd) + combined1() | addProp=1 | response variable |
additive+proportional | combined2 | log | var ~ lnorm(add.sd) + prop(prop.sd) + combined2() | addProp=2 | response variable |
additive+power | combined1 | log | var ~ lnorm(add.sd) + pow(pow.sd, exponent) + combined1() | addProp=1 | response variable |
additive+power | combined2 | log | var ~ lnorm(add.sd) + pow(pow.sd, exponent) + combined2() | addProp=2 | response variable |
constant | boxCox | var ~ boxCox(lambda) + add(add.sd) | response variable | ||
proportional | boxCox | var ~ boxCox(lambda) + prop(prop.sd) | response variable | ||
power | boxCox | var ~ boxCox(lambda) + pow(pow.sd, exponent) | response variable | ||
additive+proportional | combined1 | boxCox | var ~ boxCox(lambda) + add(add.sd) + prop(prop.sd) + combined1() | addProp=1 | response variable |
additive+proportional | combined2 | boxCox | var ~ boxCox(lambda) + add(add.sd) + prop(prop.sd) + combined2() | addProp=2 | response variable |
additive+power | combined1 | boxCox | var ~ boxCox(lambda) + add(add.sd) + pow(pop.sd, exponent) + combined1() | addProp=1 | response variable |
additive+power | combined2 | boxCox | var ~ boxCox(lambda) + add(add.sd) + pow(pop.sd, exponent) + combined2() | addProp=2 | response variable |
constant | yeoJohnson | var ~ yeoJohnson(lambda) + add(add.sd) | response variable | ||
proportional | yeoJohnson | var ~ yeoJohnson(lambda) + prop(prop.sd) | response variable | ||
power | yeoJohnson | var ~ yeoJohnson(lambda) + pow(pow.sd, exponent) | response variable | ||
additive+proportional | combined1 | yeoJohnson | var ~ yeoJohnson(lambda) + add(add.sd) + prop(prop.sd) + combined1() | addProp=1 | response variable |
additive+proportional | combined2 | yeoJohnson | var ~ yeoJohnson(lambda) + add(add.sd) + prop(prop.sd) + combined2() | addProp=2 | response variable |
additive+power | combined1 | yeoJohnson | var ~ yeoJohnson(lambda) + add(add.sd) + pow(pop.sd, exponent) + combined1() | addProp=1 | response variable |
additive+power | combined2 | yeoJohnson | var ~ yeoJohnson(lambda) + add(add.sd) + pow(pop.sd, exponent) + combined2() | addProp=2 | response variable |
constant | logit | var ~ logitNorm(logit.sd) | response variable | ||
proportional | logit | var ~ logitNorm(NA) + prop(prop.sd) | response variable | ||
power | logit | var ~ logitNorm(NA) + pow(pow.sd, exponent) | response variable | ||
additive+proportional | combined1 | logit | var ~ logitNorm(logit.sd) + prop(prop.sd) | addProp=1 | response variable |
additive+proportional | combined2 | logit | var ~ logitNorm(logit.sd) + prop(prop.sd) | addProp=2 | response variable |
additive+power | combined1 | logit | var ~ logitNorm(logit.sd) + pow(pow.sd, exponent) | addProp=1 | response variable |
additive+power | combined2 | logit | var ~ logitNorm(logit.sd) + pow(pow.sd, exponent) | addProp=2 | response variable |
additive | yeoJohnson(logit()) | var ~ yeoJohnson(lambda) + logitNorm(logit.sd) | response variable | ||
proportional | yeoJohnson(logit()) | var ~ yeoJohnson(lambda) + logitNorm(NA) + prop(prop.sd) | response variable | ||
power | yeoJohnson(logit()) | var ~ yeoJohnson(lambda) + logitNorm(NA) + pow(pow.sd, exponent) | response variable | ||
additive+proportional | combined1 | yeoJohnson(logit()) | var ~ yeoJohnson(lambda) + logitNorm(logit.sd) + prop(prop.sd) | addProp=1 | response variable |
additive+proportional | combined2 | yeoJohnson(logit()) | var ~ yeoJohnson(lambda) + logitNorm(logit.sd) + prop(prop.sd) | addProp=2 | response variable |
additive+power | combined1 | yeoJohnson(logit()) | var ~ yeoJohnson(lambda) + logitNorm(logit.sd) + pow(pow.sd, exponent) | addProp=1 | response variable |
additive+power | combined2 | yeoJohnson(logit()) | var ~ yeoJohnson(lambda) + logitNorm(logit.sd) + pow(pow.sd, exponent) | addProp=2 | response variable |
constant | logit | var ~ probitNorm(probit.sd) | response variable | ||
proportional | probit | var ~ probitNorm(NA) + prop(prop.sd) | response variable | ||
power | probit | var ~ probitNorm(NA) + pow(pow.sd, exponent) | response variable | ||
additive+proportional | combined1 | probit | var ~ probitNorm(probit.sd) + prop(prop.sd) + combined1() | addProp=1 | response variable |
additive+proportional | combined2 | probit | var ~ probitNorm(probit.sd) + prop(prop.sd) + combined2() | addProp=2 | response variable |
additive+power | combined1 | probit | var ~ probitNorm(probit.sd) + pow(pow.sd, exponent) + combined1() | addProp=1 | response variable |
additive+power | combined2 | probit | var ~ probitNorm(probit.sd) + pow(pow.sd, exponent) + combined2() | addProp=2 | response variable |
additive | yeoJohnson(probit()) | var ~ yeoJohnson(lambda) + probitNorm(probit.sd) | response variable | ||
proportional | yeoJohnson(probit()) | var ~ yeoJohnson(lambda) + probitNorm(NA) + prop(prop.sd) | response variable | ||
power | yeoJohnson(probit()) | var ~ yeoJohnson(lambda) + probitNorm(NA) + pow(pow.sd, exponent) | response variable | ||
additive+proportional | combined1 | yeoJohnson(probit()) | var ~ yeoJohnson(lambda) + probitNorm(probit.sd) + prop(prop.sd) + combined1() | addProp=1 | response variable |
additive+proportional | combined2 | yeoJohnson(probit()) | var ~ yeoJohnson(lambda) + probitNorm(probit.sd) + prop(prop.sd) + combined2() | addProp=2 | response variable |
additive+power | combined1 | yeoJohnson(probit()) | var ~ yeoJohnson(lambda) + probitNorm(probit.sd) + pow(pow.sd, exponent) + combined1() | addProp=1 | response variable |
additive+power | combined2 | yeoJohnson(probit()) | var ~ yeoJohnson(lambda) + probitNorm(probit.sd) + pow(pow.sd, exponent) + combined2() | addProp=2 | response variable |
constant+t | None | var ~ add(add.sd) + dt(df) | response variable | ||
proportional+t | None | var ~ prop(prop.sd) + dt(df) | response variable | ||
power+t | None | var ~ pow(pow.sd, exponent) + dt(df) | response variable | ||
additive+proportional+t | combined1 | None | var ~ add(add.sd) + prop(prop.sd) + dt(df) + combined1() | addProp=1 | response variable |
additive+proportional+t | combined2 | None | var ~ add(add.sd) + prop(prop.sd) + dt(df) + combined2() | addProp=2 | response variable |
additive+power+t | combined1 | None | var ~ add(add.sd) + pow(pow.sd, exponent) + dt(df) +combined1() | addProp=1 | response variable |
additive+power+t | combined2 | None | var ~ add(add.sd) + pow(pow.sd, exponent) + dt(df) +combined2() | addProp=2 | response variable |
constant+t | log | var ~ lnorm(add.sd) + dt(df) | response variable | ||
proportional+t | log | var ~ lnorm(NA) + prop(prop.sd) + dt(df) | response variable | ||
power+t | log | var ~ lnorm(NA) + pow(pow.sd, exponent) + dt(df) | response variable | ||
additive+proportional+t | combined1 | log | var ~ lnorm(add.sd) + prop(prop.sd) + dt(df) +combined1() | addProp=1 | response variable |
additive+proportional+t | combined2 | log | var ~ lnorm(add.sd) + prop(prop.sd) + dt(df) + combined2() | addProp=2 | response variable |
additive+power+t | combined1 | log | var ~ lnorm(add.sd) + pow(pow.sd, exponent) + dt(df) + combined1() | addProp=1 | response variable |
additive+power+t | combined2 | log | var ~ lnorm(add.sd) + pow(pow.sd, exponent) + dt(df) + combined2() | addProp=2 | response variable |
constant+t | boxCox | var ~ boxCox(lambda) + add(add.sd)+dt(df) | response variable | ||
proportional+t | boxCox | var ~ boxCox(lambda) + prop(prop.sd)+dt(df) | response variable | ||
power+t | boxCox | var ~ boxCox(lambda) + pow(pow.sd, exponent)+dt(df) | response variable | ||
additive+proportional+t | combined1 | boxCox | var ~ boxCox(lambda) + add(add.sd) + prop(prop.sd) + dt(df) + combined1() | addProp=1 | response variable |
additive+proportional+t | combined2 | boxCox | var ~ boxCox(lambda) + add(add.sd) + prop(prop.sd) + dt(df) + combined2() | addProp=2 | response variable |
additive+power+t | combined1 | boxCox | var ~ boxCox(lambda) + add(add.sd) + pow(pop.sd, exponent) + dt(df) + combined1() | addProp=1 | response variable |
additive+power+t | combined2 | boxCox | var ~ boxCox(lambda) + add(add.sd) + pow(pop.sd, exponent) + dt(df) + combined2() | addProp=2 | response variable |
constant+t | yeoJohnson | var ~ yeoJohnson(lambda) + add(add.sd) + dt(df) | response variable | ||
proportional+t | yeoJohnson | var ~ yeoJohnson(lambda) + prop(prop.sd) + dt(df) | response variable | ||
power+t | yeoJohnson | var ~ yeoJohnson(lambda) + pow(pow.sd, exponent) + dt(df) | response variable | ||
additive+proportional+t | combined1 | yeoJohnson | var ~ yeoJohnson(lambda) + add(add.sd) + prop(prop.sd) + dt(df) + combined1() | addProp=1 | response variable |
additive+proportional+t | combined2 | yeoJohnson | var ~ yeoJohnson(lambda) + add(add.sd) + prop(prop.sd) + dt(df) + combined2() | addProp=2 | response variable |
additive+power+t | combined1 | yeoJohnson | var ~ yeoJohnson(lambda) + add(add.sd) + pow(pop.sd, exponent) + dt(df) + combined1() | addProp=1 | response variable |
additive+power+t | combined2 | yeoJohnson | var ~ yeoJohnson(lambda) + add(add.sd) + pow(pop.sd, exponent) + dt(df) + combined2() | addProp=2 | response variable |
constant+t | logit | var ~ logitNorm(logit.sd)+dt(df) | response variable | ||
proportional+t | logit | var ~ logitNorm(NA) + prop(prop.sd)+dt(df) | response variable | ||
power+t | logit | var ~ logitNorm(NA) + pow(pow.sd, exponent) + dt(df) | response variable | ||
additive+proportional+t | combined1 | logit | var ~ logitNorm(logit.sd) + prop(prop.sd) + dt(df) + combined1() | addProp=1 | response variable |
additive+proportional+t | combined2 | logit | var ~ logitNorm(logit.sd) + prop(prop.sd) + dt(df) + combined2() | addProp=2 | response variable |
additive+power+t | combined1 | logit | var ~ logitNorm(logit.sd) + pow(pow.sd, exponent) + dt(df) + combined1() | addProp=1 | response variable |
additive+power+t | combined2 | logit | var ~ logitNorm(logit.sd) + pow(pow.sd, exponent) + dt(df) + combined2() | addProp=2 | response variable |
additive+t | yeoJohnson(logit()) | var ~ yeoJohnson(lambda) + logitNorm(logit.sd) + dt(df) | response variable | ||
proportional+t | yeoJohnson(logit()) | var ~ yeoJohnson(lambda) + logitNorm(NA) + prop(prop.sd) + dt(df) | response variable | ||
power+t | yeoJohnson(logit()) | var ~ yeoJohnson(lambda) + logitNorm(NA) + pow(pow.sd, exponent) + dt(df) | response variable | ||
additive+proportional+t | combined1 | yeoJohnson(logit()) | var ~ yeoJohnson(lambda) + logitNorm(logit.sd) + prop(prop.sd) + dt(df) + combined1() | addProp=1 | response variable |
additive+proportional+t | combined2 | yeoJohnson(logit()) | var ~ yeoJohnson(lambda) + logitNorm(logit.sd) + prop(prop.sd) + dt(df) + combined2() | addProp=2 | response variable |
additive+power+t | combined1 | yeoJohnson(logit()) | var ~ yeoJohnson(lambda) + logitNorm(logit.sd) + pow(pow.sd, exponent) + dt(df) + combined1() | addProp=1 | response variable |
additive+power+t | combined2 | yeoJohnson(logit()) | var ~ yeoJohnson(lambda) + logitNorm(logit.sd) + pow(pow.sd, exponent) + dt(df) + combined2() | addProp=2 | response variable |
constant+t | logit | var ~ probitNorm(probit.sd) + dt(df) | response variable | ||
proportional+t | probit | var ~ probitNorm(NA) + prop(prop.sd) + dt(df) | response variable | ||
power+t | probit | var ~ probitNorm(NA) + pow(pow.sd, exponent) + dt(df) | response variable | ||
additive+proportional+t | combined1 | probit | var ~ probitNorm(probit.sd) + prop(prop.sd) + dt(df) + combined1() | addProp=1 | response variable |
additive+proportional+t | combined2 | probit | var ~ probitNorm(probit.sd) + prop(prop.sd) + dt(df) + combined2() | addProp=2 | response variable |
additive+power+t | combined1 | probit | var ~ probitNorm(probit.sd) + pow(pow.sd, exponent) + dt(df) + combined1() | addProp=1 | response variable |
additive+power+t | combined2 | probit | var ~ probitNorm(probit.sd) + pow(pow.sd, exponent) + dt(df) + combined2() | addProp=2 | response variable |
additive+t | yeoJohnson(probit()) | var ~ yeoJohnson(lambda) + probitNorm(probit.sd) + dt(df) | response variable | ||
proportional+t | yeoJohnson(probit()) | var ~ yeoJohnson(lambda) + probitNorm(NA) + prop(prop.sd) + dt(df) | response variable | ||
power+t | yeoJohnson(probit()) | var ~ yeoJohnson(lambda) + probitNorm(NA) + pow(pow.sd, exponent) + dt(df) | response variable | ||
additive+proportional+t | combined1 | yeoJohnson(probit()) | var ~ yeoJohnson(lambda) + probitNorm(probit.sd) + prop(prop.sd) + dt(df) + combined1() | addProp=1 | response variable |
additive+proportional+t | combined2 | yeoJohnson(probit()) | var ~ yeoJohnson(lambda) + probitNorm(probit.sd) + prop(prop.sd) + dt(df) + combined2() | addProp=2 | response variable |
additive+power+t | combined1 | yeoJohnson(probit()) | var ~ yeoJohnson(lambda) + probitNorm(probit.sd) + pow(pow.sd, exponent) + dt(df) + combined1() | addProp=1 | response variable |
additive+power+t | combined2 | yeoJohnson(probit()) | var ~ yeoJohnson(lambda) + probitNorm(probit.sd) + pow(pow.sd, exponent) + dt(df) +combined2() | addProp=2 | response variable |
constant+cauchy | None | var ~ add(add.sd) + dcauchy() | response variable | ||
proportional+cauchy | None | var ~ prop(prop.sd) + dcauchy() | response variable | ||
power+cauchy | None | var ~ pow(pow.sd, exponent) + dcauchy() | response variable | ||
additive+proportional+cauchy | combined1 | None | var ~ add(add.sd) + prop(prop.sd) + dcauchy() + combined1() | addProp=1 | response variable |
additive+proportional+cauchy | combined2 | None | var ~ add(add.sd) + prop(prop.sd) + dcauchy() + combined2() | addProp=2 | response variable |
additive+power+cauchy | combined1 | None | var ~ add(add.sd) + pow(pow.sd, exponent) + dcauchy() +combined1() | addProp=1 | response variable |
additive+power+cauchy | combined2 | None | var ~ add(add.sd) + pow(pow.sd, exponent) + dcauchy() +combined2() | addProp=2 | response variable |
constant+cauchy | log | var ~ lnorm(add.sd) + dcauchy() | response variable | ||
proportional+cauchy | log | var ~ lnorm(NA) + prop(prop.sd) + dcauchy() | response variable | ||
power+cauchy | log | var ~ lnorm(NA) + pow(pow.sd, exponent) + dcauchy() | response variable | ||
additive+proportional+cauchy | combined1 | log | var ~ lnorm(add.sd) + prop(prop.sd) + dcauchy() +combined1() | addProp=1 | response variable |
additive+proportional+cauchy | combined2 | log | var ~ lnorm(add.sd) + prop(prop.sd) + dcauchy() + combined2() | addProp=2 | response variable |
additive+power+cauchy | combined1 | log | var ~ lnorm(add.sd) + pow(pow.sd, exponent) + dcauchy() + combined1() | addProp=1 | response variable |
additive+power+cauchy | combined2 | log | var ~ lnorm(add.sd) + pow(pow.sd, exponent) + dcauchy() + combined2() | addProp=2 | response variable |
constant+cauchy | boxCox | var ~ boxCox(lambda) + add(add.sd)+dcauchy() | response variable | ||
proportional+cauchy | boxCox | var ~ boxCox(lambda) + prop(prop.sd)+dcauchy() | response variable | ||
power+cauchy | boxCox | var ~ boxCox(lambda) + pow(pow.sd, exponent)+dcauchy() | response variable | ||
additive+proportional+cauchy | combined1 | boxCox | var ~ boxCox(lambda) + add(add.sd) + prop(prop.sd) + dcauchy() + combined1() | addProp=1 | response variable |
additive+proportional+cauchy | combined2 | boxCox | var ~ boxCox(lambda) + add(add.sd) + prop(prop.sd) + dcauchy() + combined2() | addProp=2 | response variable |
additive+power+cauchy | combined1 | boxCox | var ~ boxCox(lambda) + add(add.sd) + pow(pop.sd, exponent) + dcauchy() + combined1() | addProp=1 | response variable |
additive+power+cauchy | combined2 | boxCox | var ~ boxCox(lambda) + add(add.sd) + pow(pop.sd, exponent) + dcauchy() + combined2() | addProp=2 | response variable |
constant+cauchy | yeoJohnson | var ~ yeoJohnson(lambda) + add(add.sd) + dcauchy() | response variable | ||
proportional+cauchy | yeoJohnson | var ~ yeoJohnson(lambda) + prop(prop.sd) + dcauchy() | response variable | ||
power+cauchy | yeoJohnson | var ~ yeoJohnson(lambda) + pow(pow.sd, exponent) + dcauchy() | response variable | ||
additive+proportional+cauchy | combined1 | yeoJohnson | var ~ yeoJohnson(lambda) + add(add.sd) + prop(prop.sd) + dcauchy() + combined1() | addProp=1 | response variable |
additive+proportional+cauchy | combined2 | yeoJohnson | var ~ yeoJohnson(lambda) + add(add.sd) + prop(prop.sd) + dcauchy() + combined2() | addProp=2 | response variable |
additive+power+cauchy | combined1 | yeoJohnson | var ~ yeoJohnson(lambda) + add(add.sd) + pow(pop.sd, exponent) + dcauchy() + combined1() | addProp=1 | response variable |
additive+power+cauchy | combined2 | yeoJohnson | var ~ yeoJohnson(lambda) + add(add.sd) + pow(pop.sd, exponent) + dcauchy() + combined2() | addProp=2 | response variable |
constant+cauchy | logit | var ~ logitNorm(logit.sd)+dcauchy() | response variable | ||
proportional+cauchy | logit | var ~ logitNorm(NA) + prop(prop.sd)+dcauchy() | response variable | ||
power+cauchy | logit | var ~ logitNorm(NA) + pow(pow.sd, exponent) + dcauchy() | response variable | ||
additive+proportional+cauchy | combined1 | logit | var ~ logitNorm(logit.sd) + prop(prop.sd) + dcauchy() + combined1() | addProp=1 | response variable |
additive+proportional+cauchy | combined2 | logit | var ~ logitNorm(logit.sd) + prop(prop.sd) + dcauchy() + combined2() | addProp=2 | response variable |
additive+power+cauchy | combined1 | logit | var ~ logitNorm(logit.sd) + pow(pow.sd, exponent) + dcauchy() + combined1() | addProp=1 | response variable |
additive+power+cauchy | combined2 | logit | var ~ logitNorm(logit.sd) + pow(pow.sd, exponent) + dcauchy() + combined2() | addProp=2 | response variable |
additive+cauchy | yeoJohnson(logit()) | var ~ yeoJohnson(lambda) + logitNorm(logit.sd) + dcauchy() | response variable | ||
proportional+cauchy | yeoJohnson(logit()) | var ~ yeoJohnson(lambda) + logitNorm(NA) + prop(prop.sd) + dcauchy() | response variable | ||
power+cauchy | yeoJohnson(logit()) | var ~ yeoJohnson(lambda) + logitNorm(NA) + pow(pow.sd, exponent) + dcauchy() | response variable | ||
additive+proportional+cauchy | combined1 | yeoJohnson(logit()) | var ~ yeoJohnson(lambda) + logitNorm(logit.sd) + prop(prop.sd) + dcauchy() + combined1() | addProp=1 | response variable |
additive+proportional+cauchy | combined2 | yeoJohnson(logit()) | var ~ yeoJohnson(lambda) + logitNorm(logit.sd) + prop(prop.sd) + dcauchy() + combined2() | addProp=2 | response variable |
additive+power+cauchy | combined1 | yeoJohnson(logit()) | var ~ yeoJohnson(lambda) + logitNorm(logit.sd) + pow(pow.sd, exponent) + dcauchy() + combined1() | addProp=1 | response variable |
additive+power+cauchy | combined2 | yeoJohnson(logit()) | var ~ yeoJohnson(lambda) + logitNorm(logit.sd) + pow(pow.sd, exponent) + dcauchy() + combined2() | addProp=2 | response variable |
constant+cauchy | logit | var ~ probitNorm(probit.sd) + dcauchy() | response variable | ||
proportional+cauchy | probit | var ~ probitNorm(NA) + prop(prop.sd) + dcauchy() | response variable | ||
power+cauchy | probit | var ~ probitNorm(NA) + pow(pow.sd, exponent) + dcauchy() | response variable | ||
additive+proportional+cauchy | combined1 | probit | var ~ probitNorm(probit.sd) + prop(prop.sd) + dcauchy() + combined1() | addProp=1 | response variable |
additive+proportional+cauchy | combined2 | probit | var ~ probitNorm(probit.sd) + prop(prop.sd) + dcauchy() + combined2() | addProp=2 | response variable |
additive+power+cauchy | combined1 | probit | var ~ probitNorm(probit.sd) + pow(pow.sd, exponent) + dcauchy() + combined1() | addProp=1 | response variable |
additive+power+cauchy | combined2 | probit | var ~ probitNorm(probit.sd) + pow(pow.sd, exponent) + dcauchy() + combined2() | addProp=2 | response variable |
additive+cauchy | yeoJohnson(probit()) | var ~ yeoJohnson(lambda) + probitNorm(probit.sd) + dcauchy() | response variable | ||
proportional+cauchy | yeoJohnson(probit()) | var ~ yeoJohnson(lambda) + probitNorm(NA) + prop(prop.sd) + dcauchy() | response variable | ||
power+cauchy | yeoJohnson(probit()) | var ~ yeoJohnson(lambda) + probitNorm(NA) + pow(pow.sd, exponent) + dcauchy() | response variable | ||
additive+proportional+cauchy | combined1 | yeoJohnson(probit()) | var ~ yeoJohnson(lambda) + probitNorm(probit.sd) + prop(prop.sd) + dcauchy() + combined1() | addProp=1 | response variable |
additive+proportional+cauchy | combined2 | yeoJohnson(probit()) | var ~ yeoJohnson(lambda) + probitNorm(probit.sd) + prop(prop.sd) + dcauchy() + combined2() | addProp=2 | response variable |
additive+power+cauchy | combined1 | yeoJohnson(probit()) | var ~ yeoJohnson(lambda) + probitNorm(probit.sd) + pow(pow.sd, exponent) + dcauchy() + combined1() | addProp=1 | response variable |
additive+power+cauchy | combined2 | yeoJohnson(probit()) | var ~ yeoJohnson(lambda) + probitNorm(probit.sd) + pow(pow.sd, exponent) + dcauchy() +combined2() | addProp=2 | response variable |
poission | none | cmt ~ dpois(lamba) | compartment specification | ||
binomial | none | cmt ~ dbinom(n, p) | compartment specification | ||
beta | none | cmt ~ dbeta(alpha, beta) | compartment specification | ||
chisq | none | cmt ~ dchisq(nu) | compartment specification | ||
exponential | none | cmt ~ dexp(r) | compartment specification | ||
uniform | none | cmt ~ dunif(a, b) | compartment specification | ||
weibull | none | cmt ~ dweibull(a, b) | compartment specification | ||
gamma | none | cmt ~ dgamma(a, b) | compartment specification | ||
geometric | none | cmt ~ dgeom(a) | compartment specification | ||
negative binomial form #1 | none | cmt ~ dnbinom(n, p) | compartment specification | ||
negative binomial form #2 | none | cmt ~ dnbinomMu(size, mu) | compartment specification | ||
ordinal probability | none | cmt ~ c(p0=0, p1=1, p2=2, 3) | compartment specification | ||
log-likelihood | none | ll(cmt) ~ log likelihood expression | likelihood + compartment expression | ||
An object (environment) of class rxode2
(see Chambers and Temple Lang (2001))
consisting of the following list of strings and functions:
* `model` a character string holding the source model specification. * `get.modelVars`a function that returns a list with 3 character vectors, `params`, `state`, and `lhs` of variable names used in the model specification. These will be output when the model is computed (i.e., the ODE solved by integration). * `solve`{this function solves (integrates) the ODE. This is done by passing the code to [rxSolve()]. This is as if you called `rxSolve(rxode2object, ...)`, but returns a matrix instead of a rxSolve object. `params`: a numeric named vector with values for every parameter in the ODE system; the names must correspond to the parameter identifiers used in the ODE specification; `events`: an `eventTable` object describing the input (e.g., doses) to the dynamic system and observation sampling time points (see [eventTable()]); `inits`: a vector of initial values of the state variables (e.g., amounts in each compartment), and the order in this vector must be the same as the state variables (e.g., PK/PD compartments); `stiff`: a logical (`TRUE` by default) indicating whether the ODE system is stiff or not. For stiff ODE systems (`stiff = TRUE`), `rxode2` uses the LSODA (Livermore Solver for Ordinary Differential Equations) Fortran package, which implements an automatic method switching for stiff and non-stiff problems along the integration interval, authored by Hindmarsh and Petzold (2003). For non-stiff systems (`stiff = FALSE`), `rxode2` uses `DOP853`, an explicit Runge-Kutta method of order 8(5, 3) of Dormand and Prince as implemented in C by Hairer and Wanner (1993). `trans_abs`: a logical (`FALSE` by default) indicating whether to fit a transit absorption term (TODO: need further documentation and example); `atol`: a numeric absolute tolerance (1e-08 by default); `rtol`: a numeric relative tolerance (1e-06 by default). The output of \dQuote{solve} is a matrix with as many rows as there are sampled time points and as many columns as system variables (as defined by the ODEs and additional assignments in the rxode2 model code).} * `isValid` a function that (naively) checks for model validity, namely that the C object code reflects the latest model specification. * `version` a string with the version of the `rxode2` object (not the package). * `dynLoad` a function with one `force = FALSE` argument that dynamically loads the object code if needed. * `dynUnload` a function with no argument that unloads the model object code. * `delete` removes all created model files, including C and DLL files. The model object is no longer valid and should be removed, e.g., `rm(m1)`. * `run` deprecated, use `solve`. * `get.index` deprecated. * `getObj` internal (not user callable) function.
NA
Strings are converted to double values inside of rxode2
, hence you can
refer to them as an integer corresponding to the string value or the
string value itself. For covariates these are calculated on the fly
based on your data and you should likely not try this, though you should
be aware. For strings defined in the model, this is fixed and both could
be used.
For example:
if (APGAR == 10 || APGAR == 8 || APGAR == 9) { tAPGAR <- "High" } else if (APGAR == 1 || APGAR == 2 || APGAR == 3) { tAPGAR <- "Low" } else if (APGAR == 4 || APGAR == 5 || APGAR == 6 || APGAR == 7) { tAPGAR <- "Med" } else { tAPGAR<- "Med" }
Could also be replaced by:
if (APGAR == 10 || APGAR == 8 || APGAR == 9) { tAPGAR <- "High" } else if (APGAR == 1 || APGAR == 2 || APGAR == 3) { tAPGAR <- "Low" } else if (APGAR == 4 || APGAR == 5 || APGAR == 6 || APGAR == 7) { tAPGAR <- "Med" } else { tAPGAR<- 3 }
Since "Med"
is already defined
If you wanted you can pre-declare what levels it has (and the order) to give you better control of this:
levels(tAPGAR) <- c("Med", "Low", "High") if (APGAR == 10 || APGAR == 8 || APGAR == 9) { tAPGAR <- 3 } else if (APGAR == 1 || APGAR == 2 || APGAR == 3) { tAPGAR <- 2 } else if (APGAR == 4 || APGAR == 5 || APGAR == 6 || APGAR == 7) { tAPGAR <- 1 } else { tAPGAR<- 1 }
You can see that the number changed since the declaration change the
numbers in each variable for tAPGAR
. These levels()
statements need
to be declared before the variable occurs to ensure the numbering is
consistent with what is declared.
Melissa Hallow, Wenping Wang and Matthew Fidler
Chamber, J. M. and Temple Lang, D. (2001) Object Oriented Programming in R. R News, Vol. 1, No. 3, September 2001. https://cran.r-project.org/doc/Rnews/Rnews_2001-3.pdf.
Hindmarsh, A. C. ODEPACK, A Systematized Collection of ODE Solvers. Scientific Computing, R. S. Stepleman et al. (Eds.), North-Holland, Amsterdam, 1983, pp. 55-64.
Petzold, L. R. Automatic Selection of Methods for Solving Stiff and Nonstiff Systems of Ordinary Differential Equations. Siam J. Sci. Stat. Comput. 4 (1983), pp. 136-148.
Hairer, E., Norsett, S. P., and Wanner, G. Solving ordinary differential equations I, nonstiff problems. 2nd edition, Springer Series in Computational Mathematics, Springer-Verlag (1993).
Plevyak, J.
dparser
, https://dparser.sourceforge.net/. Web. 12 Oct. 2015.
eventTable()
, et()
, add.sampling()
, add.dosing()
mod <- function() { ini({ KA <- .291 CL <- 18.6 V2 <- 40.2 Q <- 10.5 V3 <- 297.0 Kin <- 1.0 Kout <- 1.0 EC50 <- 200.0 }) model({ # A 4-compartment model, 3 PK and a PD (effect) compartment # (notice state variable names 'depot', 'centr', 'peri', 'eff') C2 <- centr/V2 C3 <- peri/V3 d/dt(depot) <- -KA*depot; d/dt(centr) <- KA*depot - CL*C2 - Q*C2 + Q*C3; d/dt(peri) <- Q*C2 - Q*C3; d/dt(eff) <- Kin - Kout*(1-C2/(EC50+C2))*eff; eff(0) <- 1 }) } m1 <- rxode2(mod) print(m1) # Step 2 - Create the model input as an EventTable, # including dosing and observation (sampling) events # QD (once daily) dosing for 5 days. qd <- et(amountUnits = "ug", timeUnits = "hours") %>% et(amt = 10000, addl = 4, ii = 24) # Sample the system hourly during the first day, every 8 hours # then after qd <- qd %>% et(0:24) %>% et(from = 24 + 8, to = 5 * 24, by = 8) # Step 3 - solve the system qd.cp <- rxSolve(m1, qd) head(qd.cp)
mod <- function() { ini({ KA <- .291 CL <- 18.6 V2 <- 40.2 Q <- 10.5 V3 <- 297.0 Kin <- 1.0 Kout <- 1.0 EC50 <- 200.0 }) model({ # A 4-compartment model, 3 PK and a PD (effect) compartment # (notice state variable names 'depot', 'centr', 'peri', 'eff') C2 <- centr/V2 C3 <- peri/V3 d/dt(depot) <- -KA*depot; d/dt(centr) <- KA*depot - CL*C2 - Q*C2 + Q*C3; d/dt(peri) <- Q*C2 - Q*C3; d/dt(eff) <- Kin - Kout*(1-C2/(EC50+C2))*eff; eff(0) <- 1 }) } m1 <- rxode2(mod) print(m1) # Step 2 - Create the model input as an EventTable, # including dosing and observation (sampling) events # QD (once daily) dosing for 5 days. qd <- et(amountUnits = "ug", timeUnits = "hours") %>% et(amt = 10000, addl = 4, ii = 24) # Sample the system hourly during the first day, every 8 hours # then after qd <- qd %>% et(0:24) %>% et(from = 24 + 8, to = 5 * 24, by = 8) # Step 3 - solve the system qd.cp <- rxSolve(m1, qd) head(qd.cp)
Set the function body of an rxUi object while retaining other object information (like data)
rxode2(x, envir = environment(x)) <- value ## S3 replacement method for class ''function'' rxode2(x, envir = environment(x)) <- value ## Default S3 replacement method: rxode2(x, envir = environment(x)) <- value rxode(x, envir = environment(x)) <- value RxODE(x, envir = environment(x)) <- value
rxode2(x, envir = environment(x)) <- value ## S3 replacement method for class ''function'' rxode2(x, envir = environment(x)) <- value ## Default S3 replacement method: rxode2(x, envir = environment(x)) <- value rxode(x, envir = environment(x)) <- value RxODE(x, envir = environment(x)) <- value
x |
The rxUi object |
envir |
environment where the assignment ocurs |
value |
the value that will be assigned |
The rxode2 ui/function
one.compartment <- function() { ini({ tka <- log(1.57); label("Ka") tcl <- log(2.72); label("Cl") tv <- log(31.5); label("V") 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) d/dt(depot) = -ka * depot d/dt(center) = ka * depot - cl / v * center cp = center / v cp ~ add(add.sd) }) } two.compartment <- function() { ini({ lka <- 0.45 ; label("Absorption rate (Ka)") lcl <- 1 ; label("Clearance (CL)") lvc <- 3 ; label("Central volume of distribution (V)") lvp <- 5 ; label("Peripheral volume of distribution (Vp)") lq <- 0.1 ; label("Intercompartmental clearance (Q)") propSd <- 0.5 ; label("Proportional residual error (fraction)") }) model({ ka <- exp(lka) cl <- exp(lcl) vc <- exp(lvc) vp <- exp(lvp) q <- exp(lq) kel <- cl/vc k12 <- q/vc k21 <- q/vp d/dt(depot) <- -ka*depot d/dt(central) <- ka*depot - kel*central - k12*central + k21*peripheral1 d/dt(peripheral1) <- k12*central - k21*peripheral1 cp <- central / vc cp ~ prop(propSd) }) } ui <- rxode2(one.compartment) rxode2(ui) <- two.compartment
one.compartment <- function() { ini({ tka <- log(1.57); label("Ka") tcl <- log(2.72); label("Cl") tv <- log(31.5); label("V") 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) d/dt(depot) = -ka * depot d/dt(center) = ka * depot - cl / v * center cp = center / v cp ~ add(add.sd) }) } two.compartment <- function() { ini({ lka <- 0.45 ; label("Absorption rate (Ka)") lcl <- 1 ; label("Clearance (CL)") lvc <- 3 ; label("Central volume of distribution (V)") lvp <- 5 ; label("Peripheral volume of distribution (Vp)") lq <- 0.1 ; label("Intercompartmental clearance (Q)") propSd <- 0.5 ; label("Proportional residual error (fraction)") }) model({ ka <- exp(lka) cl <- exp(lcl) vc <- exp(lvc) vp <- exp(lvp) q <- exp(lq) kel <- cl/vc k12 <- q/vc k21 <- q/vp d/dt(depot) <- -ka*depot d/dt(central) <- ka*depot - kel*central - k12*central + k21*peripheral1 d/dt(peripheral1) <- k12*central - k21*peripheral1 cp <- central / vc cp ~ prop(propSd) }) } ui <- rxode2(one.compartment) rxode2(ui) <- two.compartment
Internal translation to get model variables list
rxode2parse( model, linear = FALSE, linCmtSens = c("linCmtA", "linCmtB", "linCmtC"), verbose = FALSE, code = NULL, envir = parent.frame() )
rxode2parse( model, linear = FALSE, linCmtSens = c("linCmtA", "linCmtB", "linCmtC"), verbose = FALSE, code = NULL, envir = parent.frame() )
model |
Model (either file name or string) |
linear |
boolean indicating if linear compartment model should
be generated from |
linCmtSens |
Linear compartment model sensitivity type |
verbose |
is a boolean indicating the type of model detected
with |
code |
is a file name where the c code is written to (for
testing purposes mostly, it needs |
envir |
is the environment to look for R user functions (defaults to parent environment) |
A rxModelVars object that has the model variables of a rxode2 syntax expression
rxode2parse("a=3")
rxode2parse("a=3")
This assigns the c level linkages for a roxde2 model
rxode2parseAssignTranslation(df)
rxode2parseAssignTranslation(df)
df |
data frame containing the character column names rxFun, fun, type, package, packageFun and the integer column names argMin and argMax |
Nothing called for side effects
Matthew L. Fidler
rxode2parseAssignTranslation(rxode2parseGetTranslation())
rxode2parseAssignTranslation(rxode2parseGetTranslation())
This will help allow registration of functions in rxode2
rxode2parseD()
rxode2parseD()
This environment is a derivative table;
For example:
Derivative(f(a,b,c), a) = fa() Derivative(f(a,b,c), b) = fb() Derivative(f(a,b,c), c) = fc()
Then the derivative table for f
would be:
assign("f", list(fa(a,b,c), fb(a,b,c), fc(a,b,c)), rxode2parseD())
fa translates the arguments to the derivative with respect to a fb translates the arguments to the derivative with respect to b
If any of the list is NULL then rxode2 won't know how to take a derivative with respect to the argument.
If the list is shorter than the length of the arguments then the argument then the derivative of arguments that are not specified cannot be taken.
Derivative table environment for rxode2
Matthew L. Fidler
rxode2
model dll is loadedControl the packages that are loaded when a rxode2
model dll is loaded
rxode2parseGetPackagesToLoad() rxode2parseAssignPackagesToLoad(pkgs = rxode2parseGetPackagesToLoad())
rxode2parseGetPackagesToLoad() rxode2parseAssignPackagesToLoad(pkgs = rxode2parseGetPackagesToLoad())
pkgs |
The packages to make sure are loaded every time you load an rxode2 model. |
List of packages to load
Matthew Fidler
rxode2parseGetPackagesToLoad() rxode2parseAssignPackagesToLoad(rxode2parseGetPackagesToLoad())
rxode2parseGetPackagesToLoad() rxode2parseAssignPackagesToLoad(rxode2parseGetPackagesToLoad())
This function gets the currently assigned function pointer assignments
rxode2parseGetPointerAssignment()
rxode2parseGetPointerAssignment()
The currently assigned pointer assignments
Matthew L. Fidler
rxode2parseGetTranslation()
rxode2parseGetTranslation()
This function gets the currently assigned translations
rxode2parseGetTranslation()
rxode2parseGetTranslation()
The currently assigned translations
Matthew L. Fidler
rxode2parseGetTranslation()
rxode2parseGetTranslation()
This optimizes rxode2 code for computer evaluation by only calculating redundant expressions once.
rxOptExpr(x, msg = "model")
rxOptExpr(x, msg = "model")
x |
rxode2 model that can be accessed by rxNorm |
msg |
This is the name of type of object that rxode2 is optimizing that will in the message when optimizing. For example "model" will produce the following message while optimizing the model: finding duplicate expressions in model... |
Optimized rxode2 model text. The order and type lhs and state variables is maintained while the evaluation is sped up. While parameters names are maintained, their order may be modified.
Matthew L. Fidler
Simulate ordinal value
rxord(...)
rxord(...)
... |
the probabilities to be simulated. These should sum up to a number below one. |
The values entered into the 'rxord' simulation will simulate the probability of falling each group. If it falls outside of the specified probabilities, it will simulate the group (number of probabilities specified + 1)
A number from 1 to the (number of probabilities specified + 1)
Matthew L. Fidler
# This will give values 1, and 2 rxord(0.5) rxord(0.5) rxord(0.5) rxord(0.5) # This will give values 1, 2 and 3 rxord(0.3, 0.3) rxord(0.3, 0.3) rxord(0.3, 0.3)
# This will give values 1, and 2 rxord(0.5) rxord(0.5) rxord(0.5) rxord(0.5) # This will give values 1, 2 and 3 rxord(0.3, 0.3) rxord(0.3, 0.3) rxord(0.3, 0.3)
This returns the model's parameters that are required to solve the ODE system, and can be used to pipe parameters into an rxode2 solve
rxParams(obj, ...) ## S3 method for class 'rxode2' rxParams( obj, constants = TRUE, ..., params = NULL, inits = NULL, iCov = NULL, keep = NULL, thetaMat = NULL, omega = NULL, dfSub = NULL, sigma = NULL, dfObs = NULL, nSub = NULL, nStud = NULL ) ## S3 method for class 'rxSolve' rxParams( obj, constants = TRUE, ..., params = NULL, inits = NULL, iCov = NULL, keep = NULL, thetaMat = NULL, omega = NULL, dfSub = NULL, sigma = NULL, dfObs = NULL, nSub = NULL, nStud = NULL ) ## S3 method for class 'rxEt' rxParams( obj, ..., params = NULL, inits = NULL, iCov = NULL, keep = NULL, thetaMat = NULL, omega = NULL, dfSub = NULL, sigma = NULL, dfObs = NULL, nSub = NULL, nStud = NULL ) rxParam(obj, ...)
rxParams(obj, ...) ## S3 method for class 'rxode2' rxParams( obj, constants = TRUE, ..., params = NULL, inits = NULL, iCov = NULL, keep = NULL, thetaMat = NULL, omega = NULL, dfSub = NULL, sigma = NULL, dfObs = NULL, nSub = NULL, nStud = NULL ) ## S3 method for class 'rxSolve' rxParams( obj, constants = TRUE, ..., params = NULL, inits = NULL, iCov = NULL, keep = NULL, thetaMat = NULL, omega = NULL, dfSub = NULL, sigma = NULL, dfObs = NULL, nSub = NULL, nStud = NULL ) ## S3 method for class 'rxEt' rxParams( obj, ..., params = NULL, inits = NULL, iCov = NULL, keep = NULL, thetaMat = NULL, omega = NULL, dfSub = NULL, sigma = NULL, dfObs = NULL, nSub = NULL, nStud = NULL ) rxParam(obj, ...)
obj |
rxode2 family of objects |
... |
Other arguments including scaling factors for each compartment. This includes S# = numeric will scale a compartment # by a dividing the compartment amount by the scale factor, like NONMEM. |
constants |
is a boolean indicting if constants should be included in the list of parameters. Currently rxode2 parses constants into variables in case you wish to change them without recompiling the rxode2 model. |
params |
a numeric named vector with values for every parameter in the ODE system; the names must correspond to the parameter identifiers used in the ODE specification; |
inits |
a vector of initial values of the state variables (e.g., amounts in each compartment), and the order in this vector must be the same as the state variables (e.g., PK/PD compartments); |
iCov |
A data frame of individual non-time varying covariates
to combine with the |
keep |
Columns to keep from either the input dataset or the
|
thetaMat |
Named theta matrix. |
omega |
Estimate of Covariance matrix. When omega is a list,
assume it is a block matrix and convert it to a full matrix for
simulations. When |
dfSub |
Degrees of freedom to sample the between subject variability matrix from the inverse Wishart distribution (scaled) or scaled inverse chi squared distribution. |
sigma |
Named sigma covariance or Cholesky decomposition of a
covariance matrix. The names of the columns indicate
parameters that are simulated. These are simulated for every
observation in the solved system. When |
dfObs |
Degrees of freedom to sample the unexplained variability matrix from the inverse Wishart distribution (scaled) or scaled inverse chi squared distribution. |
nSub |
Number between subject variabilities ( |
nStud |
Number virtual studies to characterize uncertainty in estimated parameters. |
When extracting the parameters from an rxode2 model, a character vector listing the parameters in the model.
Matthew L.Fidler
Other Query model information:
rxDfdy()
,
rxInits()
,
rxLhs()
,
rxModelVars()
,
rxState()
This turns on the silent REprintf in C when suppressMessages()
is
turned on. This makes the REprintf
act like messages
in R,
they can be suppressed with suppressMessages()
rxParseSuppressMsg()
rxParseSuppressMsg()
Nothing
Matthew Fidler
# rxParseSuppressMsg() is called with rxode2() # Note the errors are output to the console try(rxode2parse("d/dt(matt)=/3"), silent = TRUE) # When using suppressMessages, the output is suppressed suppressMessages(try(rxode2parse("d/dt(matt)=/3"), silent = TRUE)) # In rxode2, we use REprintf so that interrupted threads do not crash R # if there is a user interrupt. This isn't captured by R's messages, but # This interface allows the `suppressMessages()` to suppress the C printing # as well # If you want to suppress messages from rxode2 in other packages, you can use # this function
# rxParseSuppressMsg() is called with rxode2() # Note the errors are output to the console try(rxode2parse("d/dt(matt)=/3"), silent = TRUE) # When using suppressMessages, the output is suppressed suppressMessages(try(rxode2parse("d/dt(matt)=/3"), silent = TRUE)) # In rxode2, we use REprintf so that interrupted threads do not crash R # if there is a user interrupt. This isn't captured by R's messages, but # This interface allows the `suppressMessages()` to suppress the C printing # as well # If you want to suppress messages from rxode2 in other packages, you can use # this function
Creates a package from compiled rxode2 models
rxPkg( ..., package, wd = getwd(), action = c("install", "build", "binary", "create"), license = c("gpl3", "lgpl", "mit", "agpl3"), name = "Firstname Lastname", fields = list() )
rxPkg( ..., package, wd = getwd(), action = c("install", "build", "binary", "create"), license = c("gpl3", "lgpl", "mit", "agpl3"), name = "Firstname Lastname", fields = list() )
... |
Models to build a package from |
package |
String of the package name to create |
wd |
character string with a working directory where to
create a subdirectory according to |
action |
Type of action to take after package is created |
license |
is the type of license for the package. |
name |
Full name of author |
fields |
A named list of fields to add to |
this function returns nothing and is used for its side effects
Matthew Fidler
Care should be taken with this method not to encounter the
birthday problem, described
https://www.johndcook.com/blog/2016/01/29/random-number-generator-seed-mistakes/.
Since the sitmo
threefry
, this currently generates
one random deviate from the uniform distribution to seed the
engine threefry
and then run the code.
rxpois(lambda, n = 1L, ncores = 1L)
rxpois(lambda, n = 1L, ncores = 1L)
lambda |
vector of (non-negative) means. |
n |
number of random values to return. |
ncores |
Number of cores for the simulation
|
Therefore, a simple call to the random number generated followed by a second call to random number generated may have identical seeds. As the number of random number generator calls are increased the probability that the birthday problem will increase.
The key to avoid this problem is to either run all simulations in the
rxode2
environment once (therefore one seed or series of seeds
for the whole simulation), pre-generate all random variables
used for the simulation, or seed the rxode2 engine with rxSetSeed()
Internally each ID is seeded with a unique number so that the results do not depend on the number of cores used.
poission random number deviates
## Use threefry engine rxpois(lambda = 3, n = 10) # with rxpois you have to explicitly state n rxpois(lambda = 3, n = 10, ncores = 2) # You can parallelize the simulation using openMP rxpois(4) ## The first arguments are the lambda parameter ## This example uses `rxpois` directly in the model rx <- function() { model({ a <- rxpois(3) }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
## Use threefry engine rxpois(lambda = 3, n = 10) # with rxpois you have to explicitly state n rxpois(lambda = 3, n = 10, ncores = 2) # You can parallelize the simulation using openMP rxpois(4) ## The first arguments are the lambda parameter ## This example uses `rxpois` directly in the model rx <- function() { model({ a <- rxpois(3) }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
Simulate a from a Poisson process
rxPp( n, lambda, gamma = 1, prob = NULL, t0 = 0, tmax = Inf, randomOrder = FALSE )
rxPp( n, lambda, gamma = 1, prob = NULL, t0 = 0, tmax = Inf, randomOrder = FALSE )
n |
Number of time points to simulate in the Poisson process |
lambda |
Rate of Poisson process |
gamma |
Asymmetry rate of Poisson process. When gamma=1.0, this simulates a homogenous Poisson process. When gamma<1.0, the Poisson process has more events early, when gamma > 1.0, the Poisson process has more events late in the process. When gamma is non-zero, the tmax should not be infinite but indicate the end of the Poisson process to be simulated. In most pharamcometric cases, this will be the end of the study. Internally this uses a rate of: l(t) = lambdagamma(t/tmax)^(gamma-1) |
prob |
When specified, this is a probability function with one argument, time, that gives the probability that a Poisson time t is accepted as a rejection time. |
t0 |
the starting time of the Poisson process |
tmax |
the maximum time of the Poisson process |
randomOrder |
when |
This returns a vector of the Poisson process times; If the dropout is >= tmax, then all the rest of the times are = tmax to indicate the dropout is equal to or after tmax.
Matthew Fidler
## Sample homogenous Poisson process of rate 1/10 rxPp(10, 1 / 10) ## Sample inhomogenous Poisson rate of 1/10 rxPp(10, 1 / 10, gamma = 2, tmax = 100) ## Typically the Poisson process times are in a sequential order, ## using randomOrder gives the Poisson process in random order rxPp(10, 1 / 10, gamma = 2, tmax = 10, randomOrder = TRUE) ## This uses an arbitrary function to sample a non-homogenous Poisson process rxPp(10, 1 / 10, prob = function(x) { 1/(1+abs(x)) })
## Sample homogenous Poisson process of rate 1/10 rxPp(10, 1 / 10) ## Sample inhomogenous Poisson rate of 1/10 rxPp(10, 1 / 10, gamma = 2, tmax = 100) ## Typically the Poisson process times are in a sequential order, ## using randomOrder gives the Poisson process in random order rxPp(10, 1 / 10, gamma = 2, tmax = 10, randomOrder = TRUE) ## This uses an arbitrary function to sample a non-homogenous Poisson process rxPp(10, 1 / 10, prob = function(x) { 1/(1+abs(x)) })
This is determined by the internal preferred condition name list
.errIdenticalDists
rxPreferredDistributionName(dist)
rxPreferredDistributionName(dist)
dist |
This is the input distribution |
Preferred distribution term
Matthew Fidler
rxPreferredDistributionName("dt") rxPreferredDistributionName("add") # can be vectorized rxPreferredDistributionName(c("add","dt"))
rxPreferredDistributionName("dt") rxPreferredDistributionName("add") # can be vectorized rxPreferredDistributionName(c("add","dt"))
rxProgress
sets up the progress bar
rxProgress(num, core = 0L) rxTick() rxProgressStop(clear = TRUE) rxProgressAbort(error = "Aborted calculation")
rxProgress(num, core = 0L) rxTick() rxProgressStop(clear = TRUE) rxProgressAbort(error = "Aborted calculation")
num |
Tot number of operations to track |
core |
Number of cores to show. If below 1, don't show number of cores |
clear |
Boolean telling if you should clear the progress bar after completion (as if it wasn't displayed). By default this is TRUE |
error |
With rxProgressAbort this is the error that is displayed |
rxTick
is a progress bar tick
rxProgressStop
stop progress bar
rxProgressAbort
shows an abort if rxProgressStop
wasn't called.
All return NULL invisibly.
Matthew L. Fidler
f <- function() { on.exit({ rxProgressAbort() }) rxProgress(100) for (i in 1:100) { rxTick() Sys.sleep(1 / 100) } rxProgressStop() } f()
f <- function() { on.exit({ rxProgressAbort() }) rxProgress(100) for (i in 1:100) { rxTick() Sys.sleep(1 / 100) } rxProgressStop() } f()
This is primarily to display information about rate
rxRateDur(x) ## S3 method for class 'rxRateDur' x[...] as.rxRateDur(x) ## S3 method for class 'rxRateDur' as.character(x, ...) ## S3 method for class 'rxRateDur' x[[...]]
rxRateDur(x) ## S3 method for class 'rxRateDur' x[...] as.rxRateDur(x) ## S3 method for class 'rxRateDur' as.character(x, ...) ## S3 method for class 'rxRateDur' x[[...]]
x |
rxRateDur data |
... |
Other parameters |
rxRateDur object
rxRemoveControl options for UI object
rxRemoveControl(ui)
rxRemoveControl(ui)
ui |
rxode2 ui object |
Nothing, called for side effects
Matthew L. Fidler
rxode2
ui modelrxRename()
changes the names of individual variables, lhs, and ode states using
new_name = old_name
syntax
rxRename(.data, ..., envir = parent.frame()) .rxRename(.data, ..., envir = parent.frame()) rename.rxUi(.data, ...) rename.function(.data, ...) ## S3 method for class 'rxUi' rxRename(.data, ...) ## S3 method for class ''function'' rxRename(.data, ...) ## Default S3 method: rxRename(.data, ...)
rxRename(.data, ..., envir = parent.frame()) .rxRename(.data, ..., envir = parent.frame()) rename.rxUi(.data, ...) rename.function(.data, ...) ## S3 method for class 'rxUi' rxRename(.data, ...) ## S3 method for class ''function'' rxRename(.data, ...) ## Default S3 method: rxRename(.data, ...)
.data |
rxode2 ui function, named data to be consistent with |
... |
rename items |
envir |
Environment for evaluation |
This is similar to dplyr
's rename()
function. When dplyr
is
loaded, the s3
methods work for the ui objects.
Note that the .rxRename()
is the internal function that is called
when renaming and is likely not what you need to call unless you
are writing your own extension of the function
New model with items renamed
Matthew L. Fidler
ocmt <- function() { ini({ tka <- exp(0.45) # Ka tcl <- exp(1) # Cl ## This works with interactive models ## You may also label the preceding line with label("label text") tv <- exp(3.45) # log V ## the label("Label name") works with all models add.sd <- 0.7 }) model({ ka <- tka cl <- tcl v <- tv d/dt(depot) = -ka * depot d/dt(center) = ka * depot - cl / v * center cp = center / v cp ~ add(add.sd) }) } ocmt %>% rxRename(cpParent=cp)
ocmt <- function() { ini({ tka <- exp(0.45) # Ka tcl <- exp(1) # Cl ## This works with interactive models ## You may also label the preceding line with label("label text") tv <- exp(3.45) # log V ## the label("Label name") works with all models add.sd <- 0.7 }) model({ ka <- tka cl <- tcl v <- tv d/dt(depot) = -ka * depot d/dt(center) = ka * depot - cl / v * center cp = center / v cp ~ add(add.sd) }) } ocmt %>% rxRename(cpParent=cp)
A list and description of rxode2 supported reserved keywords
rxReservedKeywords
rxReservedKeywords
A data frame with 3 columns and 31 rows
Reserved Keyword Name
Reserved Keyword Meaning
Keyword Alias
A description of Rode2 supported residual errors
rxResidualError
rxResidualError
A data frame with 6 columns and 181 rows
A description of the type of residual error
For additive and proportional what functional form is used
The type of transformation that is done on the DV and the prediction
Example code for the residual error type
The type of add+prop residual error default that would be equivalent
what the left handed side of the specification represents, either a response variable, or a compartment specification
This is simulated with the fast, thread-safe threefry simulator and can use multiple cores to generate the random deviates.
rxRmvn( n, mu = NULL, sigma, lower = -Inf, upper = Inf, ncores = 1, isChol = FALSE, keepNames = TRUE, a = 0.4, tol = 2.05, nlTol = 1e-10, nlMaxiter = 100L )
rxRmvn( n, mu = NULL, sigma, lower = -Inf, upper = Inf, ncores = 1, isChol = FALSE, keepNames = TRUE, a = 0.4, tol = 2.05, nlTol = 1e-10, nlMaxiter = 100L )
n |
Number of random row vectors to be simulated OR the matrix to use for simulation (faster). |
mu |
mean vector |
sigma |
Covariance matrix for multivariate normal or a list
of covariance matrices. If a list of covariance matrix, each
matrix will simulate |
lower |
is a vector of the lower bound for the truncated multivariate norm |
upper |
is a vector of the upper bound for the truncated multivariate norm |
ncores |
Number of cores used in the simulation |
isChol |
A boolean indicating if |
keepNames |
Keep the names from either the mean or covariance matrix. |
a |
threshold for switching between methods; They can be tuned for maximum speed; There are three cases that are considered: case 1: a < l < u case 2: l < u < -a case 3: otherwise where l=lower and u = upper |
tol |
When case 3 is used from the above possibilities, the tol value controls the acceptance rejection and inverse-transformation; When abs(u-l)>tol, uses accept-reject from randn |
nlTol |
Tolerance for newton line-search |
nlMaxiter |
Maximum iterations for newton line-search |
If n==integer
(default) the output is an (n x d) matrix
where the i-th row is the i-th simulated vector.
If is.matrix(n)
then the random vector are store in n
,
which is provided by the user, and the function returns
NULL
invisibly.
Matthew Fidler, Zdravko Botev and some from Matteo Fasiolo
John K. Salmon, Mark A. Moraes, Ron O. Dror, and David E. Shaw (2011). Parallel Random Numbers: As Easy as 1, 2, 3. D. E. Shaw Research, New York, NY 10036, USA.
The thread safe multivariate normal was inspired from the mvnfast
package by Matteo Fasiolo https://CRAN.R-project.org/package=mvnfast
The concept of the truncated multivariate normal was taken from Zdravko Botev Botev (2017) doi:10.1111/rssb.12162 and Botev and L'Ecuyer (2015) doi:10.1109/WSC.2015.7408180 and converted to thread safe simulation;
## From mvnfast ## Unlike mvnfast, uses threefry simulation d <- 5 mu <- 1:d # Creating covariance matrix tmp <- matrix(rnorm(d^2), d, d) mcov <- tcrossprod(tmp, tmp) set.seed(414) rxRmvn(4, 1:d, mcov) set.seed(414) rxRmvn(4, 1:d, mcov) set.seed(414) rxRmvn(4, 1:d, mcov, ncores = 2) # r.v. generated on the second core are different ###### Here we create the matrix that will hold the simulated # random variables upfront. A <- matrix(NA, 4, d) class(A) <- "numeric" # This is important. We need the elements of A to be of class "numeric". set.seed(414) rxRmvn(A, 1:d, mcov, ncores = 2) # This returns NULL ... A # ... but the result is here ## You can also simulate from a truncated normal: rxRmvn(10, 1:d, mcov, lower = 1:d - 1, upper = 1:d + 1) # You can also simulate from different matrices (if they match # dimensions) by using a list of matrices. matL <- lapply(1:4, function(...) { tmp <- matrix(rnorm(d^2), d, d) tcrossprod(tmp, tmp) }) rxRmvn(4, setNames(1:d, paste0("a", 1:d)), matL)
## From mvnfast ## Unlike mvnfast, uses threefry simulation d <- 5 mu <- 1:d # Creating covariance matrix tmp <- matrix(rnorm(d^2), d, d) mcov <- tcrossprod(tmp, tmp) set.seed(414) rxRmvn(4, 1:d, mcov) set.seed(414) rxRmvn(4, 1:d, mcov) set.seed(414) rxRmvn(4, 1:d, mcov, ncores = 2) # r.v. generated on the second core are different ###### Here we create the matrix that will hold the simulated # random variables upfront. A <- matrix(NA, 4, d) class(A) <- "numeric" # This is important. We need the elements of A to be of class "numeric". set.seed(414) rxRmvn(A, 1:d, mcov, ncores = 2) # This returns NULL ... A # ... but the result is here ## You can also simulate from a truncated normal: rxRmvn(10, 1:d, mcov, lower = 1:d - 1, upper = 1:d + 1) # You can also simulate from different matrices (if they match # dimensions) by using a list of matrices. matL <- lapply(1:4, function(...) { tmp <- matrix(rnorm(d^2), d, d) tcrossprod(tmp, tmp) }) rxRmvn(4, setNames(1:d, paste0("a", 1:d)), matL)
Load a model into a symengine environment
rxS(x, doConst = TRUE, promoteLinSens = FALSE, envir = parent.frame())
rxS(x, doConst = TRUE, promoteLinSens = FALSE, envir = parent.frame())
x |
rxode2 object |
doConst |
Load constants into the environment as well. |
promoteLinSens |
Promote solved linear compartment systems to sensitivity-based solutions. |
envir |
default is |
rxode2/symengine environment
Matthew Fidler
rxSetControl options for UI object
rxSetControl(ui, control)
rxSetControl(ui, control)
ui |
rxode2 ui object |
control |
Default value |
Nothing, called for side effects
Matthew L. Fidler
Assign covariates for piping
rxSetCovariateNamesForPiping(covariates = NULL)
rxSetCovariateNamesForPiping(covariates = NULL)
covariates |
NULL (for no covariates), or the list of covariates. nlmixr uses this function to set covariates if you pipe from a nlmixr fit. |
Nothing, called for side effects
Matthew L. Fidler
# First set the name of known covariates # Note this is case sensitive rxSetCovariateNamesForPiping(c("WT","HT", "TC")) one.compartment <- function() { ini({ tka <- 0.45 ; label("Log Ka") tcl <- 1 ; label("Log Cl") tv <- 3.45 ; label("Log V") eta.ka ~ 0.6 eta.cl ~ 0.3 eta.v ~ 0.1 add.err <- 0.7 }) model({ ka <- exp(tka + eta.ka) cl <- exp(tcl + eta.cl) v <- exp(tv + eta.v) d / dt(depot) <- -ka * depot d/dt(depot) <- -ka * depot d / dt(center) <- ka * depot - cl / v * center cp <- center / v cp ~ add(add.err) }) } # now TC is detected as a covariate instead of a population parameter one.compartment %>% model({ka <- exp(tka + eta.ka + TC * cov_C)}) # You can turn it off by simply adding it back rxSetCovariateNamesForPiping() one.compartment %>% model({ka <- exp(tka + eta.ka + TC * cov_C)}) # The covariates you set with `rxSetCovariateNamesForPiping()` # are turned off every time you solve (or fit in nlmixr)
# First set the name of known covariates # Note this is case sensitive rxSetCovariateNamesForPiping(c("WT","HT", "TC")) one.compartment <- function() { ini({ tka <- 0.45 ; label("Log Ka") tcl <- 1 ; label("Log Cl") tv <- 3.45 ; label("Log V") eta.ka ~ 0.6 eta.cl ~ 0.3 eta.v ~ 0.1 add.err <- 0.7 }) model({ ka <- exp(tka + eta.ka) cl <- exp(tcl + eta.cl) v <- exp(tv + eta.v) d / dt(depot) <- -ka * depot d/dt(depot) <- -ka * depot d / dt(center) <- ka * depot - cl / v * center cp <- center / v cp ~ add(add.err) }) } # now TC is detected as a covariate instead of a population parameter one.compartment %>% model({ka <- exp(tka + eta.ka + TC * cov_C)}) # You can turn it off by simply adding it back rxSetCovariateNamesForPiping() one.compartment %>% model({ka <- exp(tka + eta.ka + TC * cov_C)}) # The covariates you set with `rxSetCovariateNamesForPiping()` # are turned off every time you solve (or fit in nlmixr)
Set Initial conditions to time zero instead of the first observed/dosed time
rxSetIni0(ini0 = TRUE)
rxSetIni0(ini0 = TRUE)
ini0 |
When |
the boolean ini0, though this is called for its side effects
Set the variables for the model piping automatic covarite selection
rxSetPipingAuto( thetamodelVars = rex::rex(or("tv", "t", "pop", "POP", "Pop", "TV", "T", "cov", "err", "eff")), covariateExceptions = rex::rex(start, or("wt", "sex", "crcl", "kout"), end), etaParts = c("eta", "ETA", "Eta", "ppv", "PPV", "Ppv", "iiv", "Iiv", "bsv", "Bsv", "BSV", "bpv", "Bpv", "BPV", "psv", "PSV", "Psv") )
rxSetPipingAuto( thetamodelVars = rex::rex(or("tv", "t", "pop", "POP", "Pop", "TV", "T", "cov", "err", "eff")), covariateExceptions = rex::rex(start, or("wt", "sex", "crcl", "kout"), end), etaParts = c("eta", "ETA", "Eta", "ppv", "PPV", "Ppv", "iiv", "Iiv", "bsv", "Bsv", "BSV", "bpv", "Bpv", "BPV", "psv", "PSV", "Psv") )
thetamodelVars |
This is the prefixes for the theta model variables in a regular expression |
covariateExceptions |
This is a regular expression of covariates that should always be covariates |
etaParts |
This is the list of eta prefixes/post-fixes that identify a variable as a between subject variability |
This is called once at startup to set the defaults, though you can change this if you wish so that piping can work differently for your individual setup
Nothing, called for side effects
Matthew L. Fidler
Defunct setting of product
rxSetProd(type = c("long double", "double", "logify"))
rxSetProd(type = c("long double", "double", "logify"))
type |
used to be type of product |
nothing
Set timing for progress bar
rxSetProgressBar(seconds = 1)
rxSetProgressBar(seconds = 1)
seconds |
This sets the number of seconds that need to elapse before drawing the next segment of the progress bar. When this is zero or below this turns off the progress bar. |
nothing, used for side effects
Matthew Fidler
This sets the seed for the rxode2 parallel random number generation. If set, then whenever a seed is set for the threefry or vandercorput simulation engine, it will use this seed, increment for the number of seeds and continue with the sequence the next time the random number generator is called.
rxSetSeed(seed)
rxSetSeed(seed)
seed |
An integer that represents the rxode2 parallel and internal random number generator seed. When positive, use this seed for random number generation and increment and reseed any parallel or new engines that are being called. When negative, turn off the rxode2 seed and generate a seed from the R's uniform random number generator. Best practice is to set this seed. |
In contrast, when this is not called, the time that the vandercorput or threefry simulation engines are seeded it comes from a uniform random number generated from the standard R random seed. This may cause a duplicate seed based on the R seed state. This means that there could be correlations between simulations that do not exist This will avoid the birthday problem picking exactly the same seed using the seed state of the R random number generator. The more times the seed is called, the more likely this becomes.
Nothing, called for its side effects
Matthew Fidler
JD Cook. (2016). Random number generator seed mistakes. https://www.johndcook.com/blog/2016/01/29/random-number-generator-seed-mistakes/
rxGetSeed, rxWithSeed, rxWithPreserveSeed
rxSetSeed(42) # seed with generator 42 rxnorm() # Use R's random number generator rnorm(1) rxSetSeed(42) # reproduces the same number rxnorm() # But R's random number is not the same rnorm(1) # If we reset this to use the R's seed # (internally rxode2 uses a uniform random number to span seeds) # This can lead to duplicate sequences and seeds rxSetSeed(-1) # Now set seed works for both. # This is not recommended, but illustrates the different types of # seeds that can be generated. set.seed(42) rxnorm() rnorm(1) set.seed(42) rxnorm() rnorm(1)
rxSetSeed(42) # seed with generator 42 rxnorm() # Use R's random number generator rnorm(1) rxSetSeed(42) # reproduces the same number rxnorm() # But R's random number is not the same rnorm(1) # If we reset this to use the R's seed # (internally rxode2 uses a uniform random number to span seeds) # This can lead to duplicate sequences and seeds rxSetSeed(-1) # Now set seed works for both. # This is not recommended, but illustrates the different types of # seeds that can be generated. set.seed(42) rxnorm() rnorm(1) set.seed(42) rxnorm() rnorm(1)
Defunct setting of sum
rxSetSum(type = c("pairwise", "fsum", "kahan", "neumaier", "c"))
rxSetSum(type = c("pairwise", "fsum", "kahan", "neumaier", "c"))
type |
used to be type of product |
nothing
Use Shiny to help develop an rxode2 model
rxShiny( object, params = NULL, events = NULL, inits = NULL, ..., data = data.frame() ) ## S3 method for class 'rxSolve' rxShiny( object, params = NULL, events = NULL, inits = NULL, ..., data = data.frame() ) ## Default S3 method: rxShiny( object = NULL, params = NULL, events = NULL, inits = NULL, ..., data = data.frame() )
rxShiny( object, params = NULL, events = NULL, inits = NULL, ..., data = data.frame() ) ## S3 method for class 'rxSolve' rxShiny( object, params = NULL, events = NULL, inits = NULL, ..., data = data.frame() ) ## Default S3 method: rxShiny( object = NULL, params = NULL, events = NULL, inits = NULL, ..., data = data.frame() )
object |
A rxode2 family of objects. If not supplied a 2-compartment indirect effect model is used. If it is supplied, use the model associated with the rxode2 object for the model exploration. |
params |
Initial parameters for model |
events |
Event information (currently ignored) |
inits |
Initial estimates for model |
... |
Other arguments passed to rxShiny. Currently doesn't do anything. |
data |
Any data that you would like to plot. If the data has
a |
Nothing; Starts a shiny server
Zufar Mulyukov and Matthew L. Fidler
Simulate Parameters from a Theta/Omega specification
rxSimThetaOmega( params = NULL, omega = NULL, omegaDf = NULL, omegaLower = as.numeric(c(R_NegInf)), omegaUpper = as.numeric(c(R_PosInf)), omegaIsChol = FALSE, omegaSeparation = "auto", omegaXform = 1L, nSub = 1L, thetaMat = NULL, thetaLower = as.numeric(c(R_NegInf)), thetaUpper = as.numeric(c(R_PosInf)), thetaDf = NULL, thetaIsChol = FALSE, nStud = 1L, sigma = NULL, sigmaLower = as.numeric(c(R_NegInf)), sigmaUpper = as.numeric(c(R_PosInf)), sigmaDf = NULL, sigmaIsChol = FALSE, sigmaSeparation = "auto", sigmaXform = 1L, nCoresRV = 1L, nObs = 1L, dfSub = 0, dfObs = 0, simSubjects = TRUE, simVariability = as.logical(c(NA_LOGICAL)) )
rxSimThetaOmega( params = NULL, omega = NULL, omegaDf = NULL, omegaLower = as.numeric(c(R_NegInf)), omegaUpper = as.numeric(c(R_PosInf)), omegaIsChol = FALSE, omegaSeparation = "auto", omegaXform = 1L, nSub = 1L, thetaMat = NULL, thetaLower = as.numeric(c(R_NegInf)), thetaUpper = as.numeric(c(R_PosInf)), thetaDf = NULL, thetaIsChol = FALSE, nStud = 1L, sigma = NULL, sigmaLower = as.numeric(c(R_NegInf)), sigmaUpper = as.numeric(c(R_PosInf)), sigmaDf = NULL, sigmaIsChol = FALSE, sigmaSeparation = "auto", sigmaXform = 1L, nCoresRV = 1L, nObs = 1L, dfSub = 0, dfObs = 0, simSubjects = TRUE, simVariability = as.logical(c(NA_LOGICAL)) )
params |
Named Vector of rxode2 model parameters |
omega |
Estimate of Covariance matrix. When omega is a list,
assume it is a block matrix and convert it to a full matrix for
simulations. When |
omegaDf |
The degrees of freedom of a t-distribution for
simulation. By default this is |
omegaLower |
Lower bounds for simulated ETAs (by default -Inf) |
omegaUpper |
Upper bounds for simulated ETAs (by default Inf) |
omegaIsChol |
Indicates if the |
omegaSeparation |
Omega separation strategy Tells the type of separation strategy when
simulating covariance with parameter uncertainty with standard
deviations modeled in the
|
omegaXform |
When taking
|
nSub |
Number between subject variabilities ( |
thetaMat |
Named theta matrix. |
thetaLower |
Lower bounds for simulated population parameter
variability (by default |
thetaUpper |
Upper bounds for simulated population unexplained
variability (by default |
thetaDf |
The degrees of freedom of a t-distribution for
simulation. By default this is |
thetaIsChol |
Indicates if the |
nStud |
Number virtual studies to characterize uncertainty in estimated parameters. |
sigma |
Named sigma covariance or Cholesky decomposition of a
covariance matrix. The names of the columns indicate
parameters that are simulated. These are simulated for every
observation in the solved system. When |
sigmaLower |
Lower bounds for simulated unexplained variability (by default -Inf) |
sigmaUpper |
Upper bounds for simulated unexplained variability (by default Inf) |
sigmaDf |
Degrees of freedom of the sigma t-distribution. By
default it is equivalent to |
sigmaIsChol |
Boolean indicating if the sigma is in the Cholesky decomposition instead of a symmetric covariance |
sigmaSeparation |
separation strategy for sigma; Tells the type of separation strategy when
simulating covariance with parameter uncertainty with standard
deviations modeled in the
|
sigmaXform |
When taking
|
nCoresRV |
Number of cores used for the simulation of the sigma variables. By default this is 1. To reproduce the results you need to run on the same platform with the same number of cores. This is the reason this is set to be one, regardless of what the number of cores are used in threaded ODE solving. |
nObs |
Number of observations to simulate (with |
dfSub |
Degrees of freedom to sample the between subject variability matrix from the inverse Wishart distribution (scaled) or scaled inverse chi squared distribution. |
dfObs |
Degrees of freedom to sample the unexplained variability matrix from the inverse Wishart distribution (scaled) or scaled inverse chi squared distribution. |
simSubjects |
boolean indicated rxode2 should simulate subjects in studies ( |
simVariability |
determines if the variability is simulated.
When |
a data frame with the simulated subjects
Matthew L.Fidler
This uses rxode2 family of objects, file, or model specification to
solve a ODE system. There are many options for a solved rxode2
model, the first are the required object
, and events
with the
some-times optional params
and inits
.
rxSolve( object, params = NULL, events = NULL, inits = NULL, scale = NULL, method = c("liblsoda", "lsoda", "dop853", "indLin"), sigdig = NULL, atol = 1e-08, rtol = 1e-06, maxsteps = 70000L, hmin = 0, hmax = NA_real_, hmaxSd = 0, hini = 0, maxordn = 12L, maxords = 5L, ..., cores, covsInterpolation = c("locf", "linear", "nocb", "midpoint"), naInterpolation = c("locf", "nocb"), keepInterpolation = c("locf", "nocb", "na"), addCov = TRUE, sigma = NULL, sigmaDf = NULL, sigmaLower = -Inf, sigmaUpper = Inf, nCoresRV = 1L, sigmaIsChol = FALSE, sigmaSeparation = c("auto", "lkj", "separation"), sigmaXform = c("identity", "variance", "log", "nlmixrSqrt", "nlmixrLog", "nlmixrIdentity"), nDisplayProgress = 10000L, amountUnits = NA_character_, timeUnits = "hours", theta = NULL, thetaLower = -Inf, thetaUpper = Inf, eta = NULL, addDosing = FALSE, stateTrim = Inf, updateObject = FALSE, omega = NULL, omegaDf = NULL, omegaIsChol = FALSE, omegaSeparation = c("auto", "lkj", "separation"), omegaXform = c("variance", "identity", "log", "nlmixrSqrt", "nlmixrLog", "nlmixrIdentity"), omegaLower = -Inf, omegaUpper = Inf, nSub = 1L, thetaMat = NULL, thetaDf = NULL, thetaIsChol = FALSE, nStud = 1L, dfSub = 0, dfObs = 0, returnType = c("rxSolve", "matrix", "data.frame", "data.frame.TBS", "data.table", "tbl", "tibble"), seed = NULL, nsim = NULL, minSS = 10L, maxSS = 1000L, infSSstep = 12, strictSS = TRUE, istateReset = TRUE, subsetNonmem = TRUE, maxAtolRtolFactor = 0.1, from = NULL, to = NULL, by = NULL, length.out = NULL, iCov = NULL, keep = NULL, indLinPhiTol = 1e-07, indLinPhiM = 0L, indLinMatExpType = c("expokit", "Al-Mohy", "arma"), indLinMatExpOrder = 6L, drop = NULL, idFactor = TRUE, mxhnil = 0, hmxi = 0, warnIdSort = TRUE, warnDrop = TRUE, ssAtol = 1e-08, ssRtol = 1e-06, safeZero = TRUE, safeLog = TRUE, safePow = TRUE, sumType = c("pairwise", "fsum", "kahan", "neumaier", "c"), prodType = c("long double", "double", "logify"), sensType = c("advan", "autodiff", "forward", "central"), linDiff = c(tlag = 1.5e-05, f = 1.5e-05, rate = 1.5e-05, dur = 1.5e-05, tlag2 = 1.5e-05, f2 = 1.5e-05, rate2 = 1.5e-05, dur2 = 1.5e-05), linDiffCentral = c(tlag = TRUE, f = TRUE, rate = TRUE, dur = TRUE, tlag2 = TRUE, f2 = TRUE, rate2 = TRUE, dur2 = TRUE), resample = NULL, resampleID = TRUE, maxwhile = 1e+05, atolSens = 1e-08, rtolSens = 1e-06, ssAtolSens = 1e-08, ssRtolSens = 1e-06, simVariability = NA, nLlikAlloc = NULL, useStdPow = FALSE, naTimeHandle = c("ignore", "warn", "error"), addlKeepsCov = FALSE, addlDropSs = TRUE, ssAtDoseTime = TRUE, ss2cancelAllPending = FALSE, envir = parent.frame() ) ## S3 method for class ''function'' rxSolve( object, params = NULL, events = NULL, inits = NULL, ..., theta = NULL, eta = NULL, envir = parent.frame() ) ## S3 method for class 'rxUi' rxSolve( object, params = NULL, events = NULL, inits = NULL, ..., theta = NULL, eta = NULL, envir = parent.frame() ) ## S3 method for class 'rxode2tos' rxSolve( object, params = NULL, events = NULL, inits = NULL, ..., theta = NULL, eta = NULL, envir = parent.frame() ) ## S3 method for class 'nlmixr2FitData' rxSolve( object, params = NULL, events = NULL, inits = NULL, ..., theta = NULL, eta = NULL, envir = parent.frame() ) ## S3 method for class 'nlmixr2FitCore' rxSolve( object, params = NULL, events = NULL, inits = NULL, ..., theta = NULL, eta = NULL, envir = parent.frame() ) ## Default S3 method: rxSolve( object, params = NULL, events = NULL, inits = NULL, ..., theta = NULL, eta = NULL, envir = parent.frame() ) ## S3 method for class 'rxSolve' update(object, ...) ## S3 method for class 'rxode2' predict(object, ...) ## S3 method for class ''function'' predict(object, ...) ## S3 method for class 'rxUi' predict(object, ...) ## S3 method for class 'rxSolve' predict(object, ...) ## S3 method for class 'rxEt' predict(object, ...) ## S3 method for class 'rxParams' predict(object, ...) ## S3 method for class 'rxode2' simulate(object, nsim = 1L, seed = NULL, ...) ## S3 method for class 'rxSolve' simulate(object, nsim = 1L, seed = NULL, ...) ## S3 method for class 'rxParams' simulate(object, nsim = 1L, seed = NULL, ...) ## S3 method for class 'rxSolve' solve(a, b, ...) ## S3 method for class 'rxUi' solve(a, b, ...) ## S3 method for class ''function'' solve(a, b, ...) ## S3 method for class 'rxode2' solve(a, b, ...) ## S3 method for class 'rxParams' solve(a, b, ...) ## S3 method for class 'rxEt' solve(a, b, ...) rxControl( ..., params = NULL, events = NULL, inits = NULL, envir = parent.frame() )
rxSolve( object, params = NULL, events = NULL, inits = NULL, scale = NULL, method = c("liblsoda", "lsoda", "dop853", "indLin"), sigdig = NULL, atol = 1e-08, rtol = 1e-06, maxsteps = 70000L, hmin = 0, hmax = NA_real_, hmaxSd = 0, hini = 0, maxordn = 12L, maxords = 5L, ..., cores, covsInterpolation = c("locf", "linear", "nocb", "midpoint"), naInterpolation = c("locf", "nocb"), keepInterpolation = c("locf", "nocb", "na"), addCov = TRUE, sigma = NULL, sigmaDf = NULL, sigmaLower = -Inf, sigmaUpper = Inf, nCoresRV = 1L, sigmaIsChol = FALSE, sigmaSeparation = c("auto", "lkj", "separation"), sigmaXform = c("identity", "variance", "log", "nlmixrSqrt", "nlmixrLog", "nlmixrIdentity"), nDisplayProgress = 10000L, amountUnits = NA_character_, timeUnits = "hours", theta = NULL, thetaLower = -Inf, thetaUpper = Inf, eta = NULL, addDosing = FALSE, stateTrim = Inf, updateObject = FALSE, omega = NULL, omegaDf = NULL, omegaIsChol = FALSE, omegaSeparation = c("auto", "lkj", "separation"), omegaXform = c("variance", "identity", "log", "nlmixrSqrt", "nlmixrLog", "nlmixrIdentity"), omegaLower = -Inf, omegaUpper = Inf, nSub = 1L, thetaMat = NULL, thetaDf = NULL, thetaIsChol = FALSE, nStud = 1L, dfSub = 0, dfObs = 0, returnType = c("rxSolve", "matrix", "data.frame", "data.frame.TBS", "data.table", "tbl", "tibble"), seed = NULL, nsim = NULL, minSS = 10L, maxSS = 1000L, infSSstep = 12, strictSS = TRUE, istateReset = TRUE, subsetNonmem = TRUE, maxAtolRtolFactor = 0.1, from = NULL, to = NULL, by = NULL, length.out = NULL, iCov = NULL, keep = NULL, indLinPhiTol = 1e-07, indLinPhiM = 0L, indLinMatExpType = c("expokit", "Al-Mohy", "arma"), indLinMatExpOrder = 6L, drop = NULL, idFactor = TRUE, mxhnil = 0, hmxi = 0, warnIdSort = TRUE, warnDrop = TRUE, ssAtol = 1e-08, ssRtol = 1e-06, safeZero = TRUE, safeLog = TRUE, safePow = TRUE, sumType = c("pairwise", "fsum", "kahan", "neumaier", "c"), prodType = c("long double", "double", "logify"), sensType = c("advan", "autodiff", "forward", "central"), linDiff = c(tlag = 1.5e-05, f = 1.5e-05, rate = 1.5e-05, dur = 1.5e-05, tlag2 = 1.5e-05, f2 = 1.5e-05, rate2 = 1.5e-05, dur2 = 1.5e-05), linDiffCentral = c(tlag = TRUE, f = TRUE, rate = TRUE, dur = TRUE, tlag2 = TRUE, f2 = TRUE, rate2 = TRUE, dur2 = TRUE), resample = NULL, resampleID = TRUE, maxwhile = 1e+05, atolSens = 1e-08, rtolSens = 1e-06, ssAtolSens = 1e-08, ssRtolSens = 1e-06, simVariability = NA, nLlikAlloc = NULL, useStdPow = FALSE, naTimeHandle = c("ignore", "warn", "error"), addlKeepsCov = FALSE, addlDropSs = TRUE, ssAtDoseTime = TRUE, ss2cancelAllPending = FALSE, envir = parent.frame() ) ## S3 method for class ''function'' rxSolve( object, params = NULL, events = NULL, inits = NULL, ..., theta = NULL, eta = NULL, envir = parent.frame() ) ## S3 method for class 'rxUi' rxSolve( object, params = NULL, events = NULL, inits = NULL, ..., theta = NULL, eta = NULL, envir = parent.frame() ) ## S3 method for class 'rxode2tos' rxSolve( object, params = NULL, events = NULL, inits = NULL, ..., theta = NULL, eta = NULL, envir = parent.frame() ) ## S3 method for class 'nlmixr2FitData' rxSolve( object, params = NULL, events = NULL, inits = NULL, ..., theta = NULL, eta = NULL, envir = parent.frame() ) ## S3 method for class 'nlmixr2FitCore' rxSolve( object, params = NULL, events = NULL, inits = NULL, ..., theta = NULL, eta = NULL, envir = parent.frame() ) ## Default S3 method: rxSolve( object, params = NULL, events = NULL, inits = NULL, ..., theta = NULL, eta = NULL, envir = parent.frame() ) ## S3 method for class 'rxSolve' update(object, ...) ## S3 method for class 'rxode2' predict(object, ...) ## S3 method for class ''function'' predict(object, ...) ## S3 method for class 'rxUi' predict(object, ...) ## S3 method for class 'rxSolve' predict(object, ...) ## S3 method for class 'rxEt' predict(object, ...) ## S3 method for class 'rxParams' predict(object, ...) ## S3 method for class 'rxode2' simulate(object, nsim = 1L, seed = NULL, ...) ## S3 method for class 'rxSolve' simulate(object, nsim = 1L, seed = NULL, ...) ## S3 method for class 'rxParams' simulate(object, nsim = 1L, seed = NULL, ...) ## S3 method for class 'rxSolve' solve(a, b, ...) ## S3 method for class 'rxUi' solve(a, b, ...) ## S3 method for class ''function'' solve(a, b, ...) ## S3 method for class 'rxode2' solve(a, b, ...) ## S3 method for class 'rxParams' solve(a, b, ...) ## S3 method for class 'rxEt' solve(a, b, ...) rxControl( ..., params = NULL, events = NULL, inits = NULL, envir = parent.frame() )
object |
is a either a rxode2 family of objects, or a file-name with a rxode2 model specification, or a string with a rxode2 model specification. |
params |
a numeric named vector with values for every parameter in the ODE system; the names must correspond to the parameter identifiers used in the ODE specification; |
events |
an |
inits |
a vector of initial values of the state variables (e.g., amounts in each compartment), and the order in this vector must be the same as the state variables (e.g., PK/PD compartments); |
scale |
a numeric named vector with scaling for ode
parameters of the system. The names must correspond to the
parameter identifiers in the ODE specification. Each of the
ODE variables will be divided by the scaling factor. For
example |
method |
The method for solving ODEs. Currently this supports:
|
sigdig |
Specifies the "significant digits" that the ode
solving requests. When specified this controls the relative and
absolute tolerances of the ODE solvers. By default the tolerance
is |
atol |
a numeric absolute tolerance (1e-8 by default) used by the ODE solver to determine if a good solution has been achieved; This is also used in the solved linear model to check if prior doses do not add anything to the solution. |
rtol |
a numeric relative tolerance ( |
maxsteps |
maximum number of (internally defined) steps allowed during one call to the solver. (5000 by default) |
hmin |
The minimum absolute step size allowed. The default value is 0. |
hmax |
The maximum absolute step size allowed. When
|
hmaxSd |
The number of standard deviations of the time difference to add to hmax. The default is 0 |
hini |
The step size to be attempted on the first step. The
default value is determined by the solver (when |
maxordn |
The maximum order to be allowed for the nonstiff (Adams) method. The default is 12. It can be between 1 and 12. |
maxords |
The maximum order to be allowed for the stiff (BDF) method. The default value is 5. This can be between 1 and 5. |
... |
Other arguments including scaling factors for each compartment. This includes S# = numeric will scale a compartment # by a dividing the compartment amount by the scale factor, like NONMEM. |
cores |
Number of cores used in parallel ODE solving. This
is equivalent to calling |
covsInterpolation |
specifies the interpolation method for
time-varying covariates. When solving ODEs it often samples
times outside the sampling time specified in
|
naInterpolation |
specifies the interpolation method for
time-varying covariates when the instantaneous value is
This will look for the prior value (backwards/locf) when instantaneously missing, or the next value when instantaneously missing. If all the covariates are missing and you find the end/beginning of the individual record, switch direction. If all are really missing, then return missing. |
keepInterpolation |
specifies the interpolation method for
variables in the
|
addCov |
A boolean indicating if covariates should be added to the output matrix or data frame. By default this is disabled. |
sigma |
Named sigma covariance or Cholesky decomposition of a
covariance matrix. The names of the columns indicate
parameters that are simulated. These are simulated for every
observation in the solved system. When |
sigmaDf |
Degrees of freedom of the sigma t-distribution. By
default it is equivalent to |
sigmaLower |
Lower bounds for simulated unexplained variability (by default -Inf) |
sigmaUpper |
Upper bounds for simulated unexplained variability (by default Inf) |
nCoresRV |
Number of cores used for the simulation of the sigma variables. By default this is 1. To reproduce the results you need to run on the same platform with the same number of cores. This is the reason this is set to be one, regardless of what the number of cores are used in threaded ODE solving. |
sigmaIsChol |
Boolean indicating if the sigma is in the Cholesky decomposition instead of a symmetric covariance |
sigmaSeparation |
separation strategy for sigma; Tells the type of separation strategy when
simulating covariance with parameter uncertainty with standard
deviations modeled in the
|
sigmaXform |
When taking
|
nDisplayProgress |
An integer indicating the minimum number of c-based solves before a progress bar is shown. By default this is 10,000. |
amountUnits |
This supplies the dose units of a data frame supplied instead of an event table. This is for importing the data as an rxode2 event table. |
timeUnits |
This supplies the time units of a data frame supplied instead of an event table. This is for importing the data as an rxode2 event table. |
theta |
A vector of parameters that will be named |
thetaLower |
Lower bounds for simulated population parameter
variability (by default |
thetaUpper |
Upper bounds for simulated population unexplained
variability (by default |
eta |
A vector of parameters that will be named |
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
|
stateTrim |
When amounts/concentrations in one of the states
are above this value, trim them to be this value. By default
Inf. Also trims to -stateTrim for large negative
amounts/concentrations. If you want to trim between a range
say |
updateObject |
This is an internally used flag to update the
rxode2 solved object (when supplying an rxode2 solved object) as
well as returning a new object. You probably should not
modify it's |
omega |
Estimate of Covariance matrix. When omega is a list,
assume it is a block matrix and convert it to a full matrix for
simulations. When |
omegaDf |
The degrees of freedom of a t-distribution for
simulation. By default this is |
omegaIsChol |
Indicates if the |
omegaSeparation |
Omega separation strategy Tells the type of separation strategy when
simulating covariance with parameter uncertainty with standard
deviations modeled in the
|
omegaXform |
When taking
|
omegaLower |
Lower bounds for simulated ETAs (by default -Inf) |
omegaUpper |
Upper bounds for simulated ETAs (by default Inf) |
nSub |
Number between subject variabilities ( |
thetaMat |
Named theta matrix. |
thetaDf |
The degrees of freedom of a t-distribution for
simulation. By default this is |
thetaIsChol |
Indicates if the |
nStud |
Number virtual studies to characterize uncertainty in estimated parameters. |
dfSub |
Degrees of freedom to sample the between subject variability matrix from the inverse Wishart distribution (scaled) or scaled inverse chi squared distribution. |
dfObs |
Degrees of freedom to sample the unexplained variability matrix from the inverse Wishart distribution (scaled) or scaled inverse chi squared distribution. |
returnType |
This tells what type of object is returned. The currently supported types are:
|
seed |
an object specifying if and how the random number generator should be initialized |
nsim |
represents the number of simulations. For rxode2, if
you supply single subject event tables (created with
|
minSS |
Minimum number of iterations for a steady-state dose |
maxSS |
Maximum number of iterations for a steady-state dose |
infSSstep |
Step size for determining if a constant infusion has reached steady state. By default this is large value, 12. |
strictSS |
Boolean indicating if a strict steady-state is
required. If a strict steady-state is ( |
istateReset |
When |
subsetNonmem |
subset to NONMEM compatible EVIDs only. By
default |
maxAtolRtolFactor |
The maximum |
from |
When there is no observations in the event table, start observations at this value. By default this is zero. |
to |
When there is no observations in the event table, end observations at this value. By default this is 24 + maximum dose time. |
by |
When there are no observations in the event table, this
is the amount to increment for the observations between |
length.out |
The number of observations to create if there isn't any observations in the event table. By default this is 200. |
iCov |
A data frame of individual non-time varying covariates
to combine with the |
keep |
Columns to keep from either the input dataset or the
|
indLinPhiTol |
the requested accuracy tolerance on exponential matrix. |
indLinPhiM |
the maximum size for the Krylov basis |
indLinMatExpType |
This is them matrix exponential type that is use for rxode2. Currently the following are supported:
|
indLinMatExpOrder |
an integer, the order of approximation to
be used, for the |
drop |
Columns to drop from the output |
idFactor |
This boolean indicates if original ID values should be maintained. This changes the default sequentially ordered ID to a factor with the original ID values in the original dataset. By default this is enabled. |
mxhnil |
maximum number of messages printed (per problem)
warning that |
hmxi |
inverse of the maximum absolute value of |
warnIdSort |
Warn if the ID is not present and rxode2 assumes the order of the parameters/iCov are the same as the order of the parameters in the input dataset. |
warnDrop |
Warn if column(s) were supposed to be dropped, but were not present. |
ssAtol |
Steady state atol convergence factor. Can be a vector based on each state. |
ssRtol |
Steady state rtol convergence factor. Can be a vector based on each state. |
safeZero |
Use safe zero divide. By default this is turned on but you may turn it off if you wish. |
safeLog |
Use safe log. When enabled if your value that you are taking log() of is negative or zero, this will return |
safePow |
Use safe powers. When enabled if your power is
negative and your base is zero, this will return the |
sumType |
Sum type to use for
|
prodType |
Product to use for
|
sensType |
Sensitivity type for
|
linDiff |
This gives the linear difference amount for all the types of linear compartment model parameters where sensitivities are not calculated. The named components of this numeric vector are:
|
linDiffCentral |
This gives the which parameters use central
differences for the linear compartment model parameters. The
are the same components as |
resample |
A character vector of model variables to resample
from the input dataset; This sampling is done with replacement.
When |
resampleID |
boolean representing if the resampling should be
done on an individual basis |
maxwhile |
represents the maximum times a while loop is evaluated before exiting. By default this is 100000 |
atolSens |
Sensitivity atol, can be different than atol with liblsoda. This allows a less accurate solve for gradients (if desired) |
rtolSens |
Sensitivity rtol, can be different than rtol with liblsoda. This allows a less accurate solve for gradients (if desired) |
ssAtolSens |
Sensitivity absolute tolerance (atol) for calculating if steady state has been achieved for sensitivity compartments. |
ssRtolSens |
Sensitivity relative tolerance (rtol) for calculating if steady state has been achieved for sensitivity compartments. |
simVariability |
determines if the variability is simulated.
When |
nLlikAlloc |
The number of log likelihood endpoints that are used in the model. This allows independent log likelihood per endpoint in focei for nlmixr2. It likely shouldn't be set, though it won't hurt anything if you do (just may take up more memory for larger allocations). |
useStdPow |
This uses C's |
naTimeHandle |
Determines what time of handling happens when
the time becomes
|
addlKeepsCov |
This determines if the additional dosing items
repeats the dose only ( |
addlDropSs |
When there are steady state doses with an |
ssAtDoseTime |
Boolean that when |
ss2cancelAllPending |
When |
envir |
is the environment to look for R user functions (defaults to parent environment) |
a |
when using |
b |
when using |
The rest of the document focus on the different ODE solving methods, followed by the core solving method's options, rxode2 event handling options, rxode2's numerical stability options, rxode2's output options, and finally internal rxode2 options or compatibility options.
An “rxSolve” solve object that stores the solved
value in a special data.frame or other type as determined by
returnType
. By default this has as many rows as there are
sampled time points and as many columns as system variables (as
defined by the ODEs and additional assignments in the rxode2 model
code). It also stores information about the call to allow
dynamic updating of the solved object.
The operations for the object are similar to a data-frame, but
expand the $
and [[""]]
access operators and assignment
operators to resolve based on different parameter values, initial
conditions, solver parameters, or events (by updating the time
variable).
You can call the eventTable()
methods on the solved object to
update the event table and resolve the system of equations.
Matthew Fidler, Melissa Hallow and Wenping Wang
"New Scaling and Squaring Algorithm for the Matrix Exponential", by Awad H. Al-Mohy and Nicholas J. Higham, August 2009
Roger B. Sidje (1998). EXPOKIT: Software package for computing matrix exponentials. ACM - Transactions on Mathematical Software 24(1), 130-156.
Hindmarsh, A. C. ODEPACK, A Systematized Collection of ODE Solvers. Scientific Computing, R. S. Stepleman et al. (Eds.), North-Holland, Amsterdam, 1983, pp. 55-64.
Petzold, L. R. Automatic Selection of Methods for Solving Stiff and Nonstiff Systems of Ordinary Differential Equations. Siam J. Sci. Stat. Comput. 4 (1983), pp. 136-148.
Hairer, E., Norsett, S. P., and Wanner, G. Solving ordinary differential equations I, nonstiff problems. 2nd edition, Springer Series in Computational Mathematics, Springer-Verlag (1993).
Stack a solved object for things like default ggplot2 plot
rxStack(data, vars = NULL, doSim = TRUE)
rxStack(data, vars = NULL, doSim = TRUE)
data |
is a rxode2 object to be stacked. |
vars |
Variables to include in stacked data; By default this is all the variables when vars is NULL. When vars is When the vars is When you specify the |
doSim |
boolean that determines if the "sim" variable in a
|
Stacked data with value
and trt
, where value is the values
and trt
is the state and lhs
variables.
Matthew Fidler
This returns the model's compartments or states.
rxState(obj = NULL, state = NULL)
rxState(obj = NULL, state = NULL)
obj |
rxode2 family of objects |
state |
is a string indicating the state or compartment that you would like to lookup. |
If state is missing, return a character vector of all the states.
If state is a string, return the compartment number of the named state.
Matthew L.Fidler
Other Query model information:
rxDfdy()
,
rxInits()
,
rxLhs()
,
rxModelVars()
,
rxParams()
Recast model in terms of sum/prod
rxSumProdModel(model, expand = FALSE, sum = TRUE, prod = TRUE)
rxSumProdModel(model, expand = FALSE, sum = TRUE, prod = TRUE)
model |
rxode2 model |
expand |
Boolean indicating if the expression is expanded. |
sum |
Use sum(...) |
prod |
Use prod(...) |
model string with prod(.) and sum(.) for all these operations.
Matthew L. Fidler
Get list of supported functions
rxSupportedFuns()
rxSupportedFuns()
list of supported functions in rxode2
rxSupportedFuns()
rxSupportedFuns()
This turns on the silent REprintf in C when suppressMessages()
is
turned on. This makes the REprintf
act like messages
in R,
they can be suppressed with suppressMessages()
rxSuppressMsg()
rxSuppressMsg()
Nothing
Matthew Fidler
# rxSupressMsg() is called with rxode2() # Note the errors are output to the console try(rxode2("d/dt(matt)=/3"), silent = TRUE) # When using suppressMessages, the output is suppressed suppressMessages(try(rxode2("d/dt(matt)=/3"), silent = TRUE)) # In rxode2, we use REprintf so that interrupted threads do not crash R # if there is a user interrupt. This isn't captured by R's messages, but # This interface allows the `suppressMessages()` to suppress the C printing # as well # If you want to suppress messages from rxode2 in other packages, you can use # this function
# rxSupressMsg() is called with rxode2() # Note the errors are output to the console try(rxode2("d/dt(matt)=/3"), silent = TRUE) # When using suppressMessages, the output is suppressed suppressMessages(try(rxode2("d/dt(matt)=/3"), silent = TRUE)) # In rxode2, we use REprintf so that interrupted threads do not crash R # if there is a user interrupt. This isn't captured by R's messages, but # This interface allows the `suppressMessages()` to suppress the C printing # as well # If you want to suppress messages from rxode2 in other packages, you can use # this function
Get Omega^-1 and derivatives
rxSymInvChol( invObjOrMatrix, theta = NULL, type = "cholOmegaInv", thetaNumber = 0L )
rxSymInvChol( invObjOrMatrix, theta = NULL, type = "cholOmegaInv", thetaNumber = 0L )
invObjOrMatrix |
Object for inverse-type calculations. If
this is a matrix, setup the object for inversion
|
theta |
Thetas to be used for calculation. If missing ( |
type |
The type of object. Currently the following types are supported:
|
thetaNumber |
For types |
Matrix based on parameters or environment with all the
matrixes calculated in variables omega
, omegaInv
, dOmega
,
dOmegaInv
.
Matthew L. Fidler
Accessing rxode2 options via getOption slows down solving. This allows the options to be synced with variables.
rxSyncOptions(setDefaults = c("none", "permissive", "strict"))
rxSyncOptions(setDefaults = c("none", "permissive", "strict"))
setDefaults |
This will setup rxode2's default solving options with the following options:
|
nothing; called for side effects
Matthew L. Fidler
A list and description of Rode supported syntax functions
rxSyntaxFunctions
rxSyntaxFunctions
A data frame with 3 columns and 102 rows
Reserved function Name
Description of function
Function Aliases
Care should be taken with this method not to encounter the
birthday problem, described
https://www.johndcook.com/blog/2016/01/29/random-number-generator-seed-mistakes/.
Since the sitmo
threefry
, this currently generates
one random deviate from the uniform distribution to seed the
engine threefry
and then run the code.
rxt(df, n = 1L, ncores = 1L)
rxt(df, n = 1L, ncores = 1L)
df |
degrees of freedom ( |
n |
number of observations. If |
ncores |
Number of cores for the simulation
|
Therefore, a simple call to the random number generated followed by a second call to random number generated may have identical seeds. As the number of random number generator calls are increased the probability that the birthday problem will increase.
The key to avoid this problem is to either run all simulations in the
rxode2
environment once (therefore one seed or series of seeds
for the whole simulation), pre-generate all random variables
used for the simulation, or seed the rxode2 engine with rxSetSeed()
Internally each ID is seeded with a unique number so that the results do not depend on the number of cores used.
t-distribution random numbers
## Use threefry engine rxt(df = 3, n = 10) # with rxt you have to explicitly state n rxt(df = 3, n = 10, ncores = 2) # You can parallelize the simulation using openMP rxt(4) ## The first argument is the df parameter ## This example uses `rxt` directly in the model rx <- function() { model({ a <- rxt(3) }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
## Use threefry engine rxt(df = 3, n = 10) # with rxt you have to explicitly state n rxt(df = 3, n = 10, ncores = 2) # You can parallelize the simulation using openMP rxt(4) ## The first argument is the df parameter ## This example uses `rxt` directly in the model rx <- function() { model({ a <- rxt(3) }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
Get the rxode2 temporary directory
rxTempDir()
rxTempDir()
rxode2 temporary directory.
rxTheme is the ggplot2 theme for rxode2 plots
rxTheme( base_size = 11, base_family = "", base_line_size = base_size/22, base_rect_size = base_size/22, grid = TRUE )
rxTheme( base_size = 11, base_family = "", base_line_size = base_size/22, base_rect_size = base_size/22, grid = TRUE )
base_size |
base font size, given in pts. |
base_family |
base font family |
base_line_size |
base size for line elements |
base_rect_size |
base size for rect elements |
grid |
a Boolean indicating if the grid is on ( |
ggplot2 theme used in rxode2
Other rxode2 plotting:
plot.rxSolve()
rxode2 to symengine environment
rxToSE( x, envir = NULL, progress = FALSE, promoteLinSens = TRUE, parent = parent.frame() ) .rxToSE(x, envir = NULL, progress = FALSE) rxFromSE( x, unknownDerivatives = c("forward", "central", "error"), parent = parent.frame() ) .rxFromSE(x)
rxToSE( x, envir = NULL, progress = FALSE, promoteLinSens = TRUE, parent = parent.frame() ) .rxToSE(x, envir = NULL, progress = FALSE) rxFromSE( x, unknownDerivatives = c("forward", "central", "error"), parent = parent.frame() ) .rxFromSE(x)
x |
expression |
envir |
default is |
progress |
shows progress bar if true. |
promoteLinSens |
Promote solved linear compartment systems to sensitivity-based solutions. |
parent |
is the parent environment to look for R-based user functions |
unknownDerivatives |
When handling derivatives from unknown functions, the translator will translate into different types of numeric derivatives. The currently supported methods are: - `forward` for forward differences - `central` for central differences - `error` for throwing an error for unknown derivatives |
An rxode2 symengine environment
Matthew L. Fidler
This function translates the model to C code, if needed
rxTrans( model, modelPrefix = "", md5 = "", modName = NULL, modVars = FALSE, ... ) ## Default S3 method: rxTrans( model, modelPrefix = "", md5 = "", modName = NULL, modVars = FALSE, ... ) ## S3 method for class 'character' rxTrans( model, modelPrefix = "", md5 = "", modName = NULL, modVars = FALSE, ... )
rxTrans( model, modelPrefix = "", md5 = "", modName = NULL, modVars = FALSE, ... ) ## Default S3 method: rxTrans( model, modelPrefix = "", md5 = "", modName = NULL, modVars = FALSE, ... ) ## S3 method for class 'character' rxTrans( model, modelPrefix = "", md5 = "", modName = NULL, modVars = FALSE, ... )
model |
This is the ODE model specification. It can be:
An ODE expression enclosed in (see also the |
modelPrefix |
Prefix of the model functions that will be compiled to make sure that multiple rxode2 objects can coexist in the same R session. |
md5 |
Is the md5 of the model before parsing, and is used to
embed the md5 into DLL, and then provide for functions like
|
modName |
a string to be used as the model name. This string
is used for naming various aspects of the computations,
including generating C symbol names, dynamic libraries,
etc. Therefore, it is necessary that |
modVars |
returns the model variables instead of the named vector of translated properties. |
... |
Ignored parameters. |
a named vector of translated model properties
including what type of jacobian is specified, the C
function prefixes,
as well as the C
functions names to be called through the compiled model.
Matthew L.Fidler
rxode2
uiCompress/Decompress rxode2
ui
rxUiDecompress(ui) rxUiCompress(ui)
rxUiDecompress(ui) rxUiCompress(ui)
ui |
rxode2 ui object |
A compressed or decompressed rxui object
Matthew L. Fidler
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) | tmp }) } f <- rxode2(one.cmt) print(class(f)) print(is.environment(f)) f <- rxUiDecompress(f) print(class(f)) print(is.environment(f)) f <- rxUiCompress(f) print(class(f)) print(is.environment(f))
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) | tmp }) } f <- rxode2(one.cmt) print(class(f)) print(is.environment(f)) f <- rxUiDecompress(f) print(class(f)) print(is.environment(f)) f <- rxUiCompress(f) print(class(f)) print(is.environment(f))
S3 for getting information from UI model
## S3 method for class 'cmtLines' rxUiGet(x, ...) ## S3 method for class 'dvidLine' rxUiGet(x, ...) ## S3 method for class 'paramsLine' rxUiGet(x, ...) ## S3 method for class 'interpLines' rxUiGet(x, ...) ## S3 method for class 'simulationSigma' rxUiGet(x, ...) ## S3 method for class 'simulationModel' rxUiGet(x, ...) ## S3 method for class 'symengineModelNoPrune' rxUiGet(x, ...) ## S3 method for class 'symengineModelPrune' rxUiGet(x, ...) ## S3 method for class 'simulationIniModel' rxUiGet(x, ...) rxUiGet(x, ...) ## S3 method for class 'levels' rxUiGet(x, ...) ## S3 method for class 'state' rxUiGet(x, ...) ## S3 method for class 'stateDf' rxUiGet(x, ...) ## S3 method for class 'statePropDf' rxUiGet(x, ...) ## S3 method for class 'props' rxUiGet(x, ...) ## S3 method for class 'theta' rxUiGet(x, ...) ## S3 method for class 'lstChr' rxUiGet(x, ...) ## S3 method for class 'omega' rxUiGet(x, ...) ## S3 method for class 'funTxt' rxUiGet(x, ...) ## S3 method for class 'allCovs' rxUiGet(x, ...) ## S3 method for class 'muRefTable' rxUiGet(x, ...) ## S3 method for class 'multipleEndpoint' rxUiGet(x, ...) ## S3 method for class 'funPrint' rxUiGet(x, ...) ## S3 method for class 'fun' rxUiGet(x, ...) ## S3 method for class 'md5' rxUiGet(x, ...) ## S3 method for class 'ini' rxUiGet(x, ...) ## S3 method for class 'iniFun' rxUiGet(x, ...) ## S3 method for class 'modelFun' rxUiGet(x, ...) ## S3 method for class 'model' rxUiGet(x, ...) ## S3 method for class 'modelDesc' rxUiGet(x, ...) ## S3 method for class 'thetaLower' rxUiGet(x, ...) ## S3 method for class 'thetaUpper' rxUiGet(x, ...) ## S3 method for class 'lhsVar' rxUiGet(x, ...) ## S3 method for class 'varLhs' rxUiGet(x, ...) ## S3 method for class 'lhsEta' rxUiGet(x, ...) ## S3 method for class 'lhsTheta' rxUiGet(x, ...) ## S3 method for class 'lhsCov' rxUiGet(x, ...) ## S3 method for class 'etaLhs' rxUiGet(x, ...) ## S3 method for class 'thetaLhs' rxUiGet(x, ...) ## S3 method for class 'covLhs' rxUiGet(x, ...) ## Default S3 method: rxUiGet(x, ...)
## S3 method for class 'cmtLines' rxUiGet(x, ...) ## S3 method for class 'dvidLine' rxUiGet(x, ...) ## S3 method for class 'paramsLine' rxUiGet(x, ...) ## S3 method for class 'interpLines' rxUiGet(x, ...) ## S3 method for class 'simulationSigma' rxUiGet(x, ...) ## S3 method for class 'simulationModel' rxUiGet(x, ...) ## S3 method for class 'symengineModelNoPrune' rxUiGet(x, ...) ## S3 method for class 'symengineModelPrune' rxUiGet(x, ...) ## S3 method for class 'simulationIniModel' rxUiGet(x, ...) rxUiGet(x, ...) ## S3 method for class 'levels' rxUiGet(x, ...) ## S3 method for class 'state' rxUiGet(x, ...) ## S3 method for class 'stateDf' rxUiGet(x, ...) ## S3 method for class 'statePropDf' rxUiGet(x, ...) ## S3 method for class 'props' rxUiGet(x, ...) ## S3 method for class 'theta' rxUiGet(x, ...) ## S3 method for class 'lstChr' rxUiGet(x, ...) ## S3 method for class 'omega' rxUiGet(x, ...) ## S3 method for class 'funTxt' rxUiGet(x, ...) ## S3 method for class 'allCovs' rxUiGet(x, ...) ## S3 method for class 'muRefTable' rxUiGet(x, ...) ## S3 method for class 'multipleEndpoint' rxUiGet(x, ...) ## S3 method for class 'funPrint' rxUiGet(x, ...) ## S3 method for class 'fun' rxUiGet(x, ...) ## S3 method for class 'md5' rxUiGet(x, ...) ## S3 method for class 'ini' rxUiGet(x, ...) ## S3 method for class 'iniFun' rxUiGet(x, ...) ## S3 method for class 'modelFun' rxUiGet(x, ...) ## S3 method for class 'model' rxUiGet(x, ...) ## S3 method for class 'modelDesc' rxUiGet(x, ...) ## S3 method for class 'thetaLower' rxUiGet(x, ...) ## S3 method for class 'thetaUpper' rxUiGet(x, ...) ## S3 method for class 'lhsVar' rxUiGet(x, ...) ## S3 method for class 'varLhs' rxUiGet(x, ...) ## S3 method for class 'lhsEta' rxUiGet(x, ...) ## S3 method for class 'lhsTheta' rxUiGet(x, ...) ## S3 method for class 'lhsCov' rxUiGet(x, ...) ## S3 method for class 'etaLhs' rxUiGet(x, ...) ## S3 method for class 'thetaLhs' rxUiGet(x, ...) ## S3 method for class 'covLhs' rxUiGet(x, ...) ## Default S3 method: rxUiGet(x, ...)
x |
list of (UIenvironment, exact). UI environment is the
parsed function for rxode2. |
... |
Other arguments |
value that was requested from the UI object
Matthew Fidler
Care should be taken with this method not to encounter the
birthday problem, described
https://www.johndcook.com/blog/2016/01/29/random-number-generator-seed-mistakes/.
Since the sitmo
threefry
, this currently generates
one random deviate from the uniform distribution to seed the
engine threefry
and then run the code.
rxunif(min = 0, max = 1, n = 1L, ncores = 1L)
rxunif(min = 0, max = 1, n = 1L, ncores = 1L)
min , max
|
lower and upper limits of the distribution. Must be finite. |
n |
number of observations. If |
ncores |
Number of cores for the simulation
|
Therefore, a simple call to the random number generated followed by a second call to random number generated may have identical seeds. As the number of random number generator calls are increased the probability that the birthday problem will increase.
The key to avoid this problem is to either run all simulations in the
rxode2
environment once (therefore one seed or series of seeds
for the whole simulation), pre-generate all random variables
used for the simulation, or seed the rxode2 engine with rxSetSeed()
Internally each ID is seeded with a unique number so that the results do not depend on the number of cores used.
uniform random numbers
## Use threefry engine rxunif(min = 0, max = 4, n = 10) # with rxunif you have to explicitly state n rxunif(min = 0, max = 4, n = 10, ncores = 2) # You can parallelize the simulation using openMP rxunif() ## This example uses `rxunif` directly in the model rx <- function() { model({ a <- rxunif(0, 3) }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
## Use threefry engine rxunif(min = 0, max = 4, n = 10) # with rxunif you have to explicitly state n rxunif(min = 0, max = 4, n = 10, ncores = 2) # You can parallelize the simulation using openMP rxunif() ## This example uses `rxunif` directly in the model rx <- function() { model({ a <- rxunif(0, 3) }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
Unloads all rxode2 compiled DLLs
rxUnloadAll()
rxUnloadAll()
List of rxode2 dlls still loaded
boolean of if all rxode2 dlls have been unloaded
print(rxUnloadAll())
print(rxUnloadAll())
Use model object in your package
rxUse(obj, overwrite = TRUE, compress = "bzip2", internal = FALSE)
rxUse(obj, overwrite = TRUE, compress = "bzip2", internal = FALSE)
obj |
model to save. |
overwrite |
By default, |
compress |
Choose the type of compression used by |
internal |
If this is run internally. By default this is FALSE |
Nothing; This is used for its side effects and shouldn't be called by a user
Validate rxode2 This allows easy validation/qualification of nlmixr by running the testing suite on your system.
rxValidate(type = NULL, skipOnCran = TRUE) rxTest(type = NULL, skipOnCran = TRUE)
rxValidate(type = NULL, skipOnCran = TRUE) rxTest(type = NULL, skipOnCran = TRUE)
type |
Type of test or filter of test type, When this is an
expression, evaluate the contents, respecting |
skipOnCran |
when |
nothing
Matthew L. Fidler
Care should be taken with this method not to encounter the
birthday problem, described
https://www.johndcook.com/blog/2016/01/29/random-number-generator-seed-mistakes/.
Since the sitmo
threefry
, this currently generates
one random deviate from the uniform distribution to seed the
engine threefry
and then run the code.
rxweibull(shape, scale = 1, n = 1L, ncores = 1L)
rxweibull(shape, scale = 1, n = 1L, ncores = 1L)
shape , scale
|
shape and scale parameters, the latter defaulting to 1. |
n |
number of observations. If |
ncores |
Number of cores for the simulation
|
Therefore, a simple call to the random number generated followed by a second call to random number generated may have identical seeds. As the number of random number generator calls are increased the probability that the birthday problem will increase.
The key to avoid this problem is to either run all simulations in the
rxode2
environment once (therefore one seed or series of seeds
for the whole simulation), pre-generate all random variables
used for the simulation, or seed the rxode2 engine with rxSetSeed()
Internally each ID is seeded with a unique number so that the results do not depend on the number of cores used.
Weibull random deviates
## Use threefry engine # with rxweibull you have to explicitly state n rxweibull(shape = 1, scale = 4, n = 10) # You can parallelize the simulation using openMP rxweibull(shape = 1, scale = 4, n = 10, ncores = 2) rxweibull(3) ## This example uses `rxweibull` directly in the model rx <- function() { model({ a <- rxweibull(1, 3) }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
## Use threefry engine # with rxweibull you have to explicitly state n rxweibull(shape = 1, scale = 4, n = 10) # You can parallelize the simulation using openMP rxweibull(shape = 1, scale = 4, n = 10, ncores = 2) rxweibull(3) ## This example uses `rxweibull` directly in the model rx <- function() { model({ a <- rxweibull(1, 3) }) } et <- et(1, id = 1:2) s <- rxSolve(rx, et)
Preserved seed and possibly set the seed
rxWithSeed( seed, code, rxseed = rxGetSeed(), kind = "default", normal.kind = "default", sample.kind = "default" ) rxWithPreserveSeed(code)
rxWithSeed( seed, code, rxseed = rxGetSeed(), kind = "default", normal.kind = "default", sample.kind = "default" ) rxWithPreserveSeed(code)
seed |
R seed to use for the session |
code |
Is the code to evaluate |
rxseed |
is the rxode2 seed that is being preserved |
kind |
character or |
normal.kind |
character string or |
sample.kind |
character string or |
returns whatever the code is returning
rxGetSeed, rxSetSeed
rxGetSeed() rxWithSeed(1, { print(rxGetSeed()) rxnorm() print(rxGetSeed()) rxnorm() }, rxseed=3)
rxGetSeed() rxWithSeed(1, { print(rxGetSeed()) rxnorm() print(rxGetSeed()) rxnorm() }, rxseed=3)
This is a dosing geom that shows the vertical lines where a dose occurs
stat_amt( mapping = NULL, data = NULL, position = "identity", show.legend = NA, inherit.aes = TRUE, ... ) geom_amt( mapping = NULL, data = NULL, position = "identity", show.legend = NA, inherit.aes = TRUE, ... )
stat_amt( mapping = NULL, data = NULL, position = "identity", show.legend = NA, inherit.aes = TRUE, ... ) geom_amt( mapping = NULL, data = NULL, position = "identity", show.legend = NA, inherit.aes = TRUE, ... )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
... |
Other arguments passed on to
|
Requires the following aesthetics:
x representing the x values, usually time
amt representing the dosing values; They are missing or zero when no dose is given
This returns a stat_amt in context of a ggplot2 plot
library(rxode2) library(units) ## Model from RxODE tutorial mod1 <- function() { ini({ KA <- 2.94E-01 CL <- 1.86E+01 V2 <- 4.02E+01 Q <- 1.05E+01 V3 <- 2.97E+02 Kin <- 1 Kout <- 1 EC50 <- 200 }) model({ C2 <- centr/V2 C3 <- peri/V3 d/dt(depot) <- -KA*depot d/dt(centr) <- KA*depot - CL*C2 - Q*C2 + Q*C3 d/dt(peri) <- Q*C2 - Q*C3 d/dt(eff) <- Kin - Kout*(1-C2/(EC50+C2))*eff }) } ## These are making the more complex regimens of the rxode2 tutorial ## bid for 5 days bid <- et(timeUnits="hr") %>% et(amt=10000,ii=12,until=set_units(5, "days")) ## qd for 5 days qd <- et(timeUnits="hr") %>% et(amt=20000,ii=24,until=set_units(5, "days")) ## bid for 5 days followed by qd for 5 days et <- seq(bid,qd) %>% et(seq(0,11*24,length.out=100)) bidQd <- rxSolve(mod1, et, addDosing=TRUE) # by default dotted and under-stated plot(bidQd, C2) + geom_amt(aes(amt=amt)) # of course you can make it a bit more visible plot(bidQd, C2) + geom_amt(aes(amt=amt), col="red", lty=1, linewidth=1.2)
library(rxode2) library(units) ## Model from RxODE tutorial mod1 <- function() { ini({ KA <- 2.94E-01 CL <- 1.86E+01 V2 <- 4.02E+01 Q <- 1.05E+01 V3 <- 2.97E+02 Kin <- 1 Kout <- 1 EC50 <- 200 }) model({ C2 <- centr/V2 C3 <- peri/V3 d/dt(depot) <- -KA*depot d/dt(centr) <- KA*depot - CL*C2 - Q*C2 + Q*C3 d/dt(peri) <- Q*C2 - Q*C3 d/dt(eff) <- Kin - Kout*(1-C2/(EC50+C2))*eff }) } ## These are making the more complex regimens of the rxode2 tutorial ## bid for 5 days bid <- et(timeUnits="hr") %>% et(amt=10000,ii=12,until=set_units(5, "days")) ## qd for 5 days qd <- et(timeUnits="hr") %>% et(amt=20000,ii=24,until=set_units(5, "days")) ## bid for 5 days followed by qd for 5 days et <- seq(bid,qd) %>% et(seq(0,11*24,length.out=100)) bidQd <- rxSolve(mod1, et, addDosing=TRUE) # by default dotted and under-stated plot(bidQd, C2) + geom_amt(aes(amt=amt)) # of course you can make it a bit more visible plot(bidQd, C2) + geom_amt(aes(amt=amt), col="red", lty=1, linewidth=1.2)
This is a censoring geom that shows the left or right censoring specified in the nlmixr input data-set or fit
stat_cens( mapping = NULL, data = NULL, position = "identity", show.legend = NA, inherit.aes = TRUE, width = 0.01, ... ) geom_cens( mapping = NULL, data = NULL, position = "identity", show.legend = NA, inherit.aes = TRUE, width = 0.01, ... )
stat_cens( mapping = NULL, data = NULL, position = "identity", show.legend = NA, inherit.aes = TRUE, width = 0.01, ... ) geom_cens( mapping = NULL, data = NULL, position = "identity", show.legend = NA, inherit.aes = TRUE, width = 0.01, ... )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
width |
represents the width (in \ censoring box |
... |
Other arguments passed on to
|
Requires the following aesthetics:
x
Represents the independent variable, often the time scale
y
represents the dependent variable
CENS
for the censoring information; (-1
right censored, 0
no censoring or 1
left censoring)
LIMIT
which represents the corresponding limit ()
Will add boxes representing the areas of the fit that were censored.
This returns a ggplot2 stat
This prints the expanded information about the rxode2 object.
## S3 method for class 'rxode2' summary(object, ...)
## S3 method for class 'rxode2' summary(object, ...)
object |
rxode2 object |
... |
Ignored parameters |
object is returned
Matthew L.Fidler
Swaps the matrix list with a cube
swapMatListWithCube(matrixListOrCube)
swapMatListWithCube(matrixListOrCube)
matrixListOrCube |
Either a list of 2-dimensional matrices or a cube of matrices |
A list or a cube (opposite format as input)
Matthew L. Fidler
# Create matrix list matLst <- cvPost(10, lotri::lotri(a+b~c(1, 0.25, 1)), 3) print(matLst) # Convert to cube matCube <- swapMatListWithCube(matLst) print(matCube) # Convert back to list matLst2 <- swapMatListWithCube(matCube) print(matLst2)
# Create matrix list matLst <- cvPost(10, lotri::lotri(a+b~c(1, 0.25, 1)), 3) print(matLst) # Convert to cube matCube <- swapMatListWithCube(matLst) print(matCube) # Convert back to list matLst2 <- swapMatListWithCube(matCube) print(matLst2)
Test if rxode2 uses linear solved systems
testRxLinCmt(ui, extra = "", .var.name = .vname(ui)) assertRxLinCmt(ui, extra = "", .var.name = .vname(ui))
testRxLinCmt(ui, extra = "", .var.name = .vname(ui)) assertRxLinCmt(ui, extra = "", .var.name = .vname(ui))
ui |
rxode2 model |
extra |
Extra text to append to the error message (like "for focei") |
.var.name |
[ |
TRUE if the model uses linear solved systems, FALSE otherwise
assertRxLinCmt()
: Assert that the rxode2 uses linear solved systems
Matthew L. Fidler
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) }) } testRxLinCmt(one.cmt)
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) }) } testRxLinCmt(one.cmt)
Test if the rxode2 model has any parameters with user defined boundaries
testRxUnbounded(ui) assertRxUnbounded(ui, extra = "", .var.name = .vname(ui)) warnRxBounded(ui, extra = "", .var.name = .vname(ui))
testRxUnbounded(ui) assertRxUnbounded(ui, extra = "", .var.name = .vname(ui)) warnRxBounded(ui, extra = "", .var.name = .vname(ui))
ui |
rxode2 ui |
extra |
extra information to append to the error message |
.var.name |
variable name |
boolean indicating if any parameters have user defined boundaries
assertRxUnbounded()
: Assert that the rxode2 model has any parameters with user defined boundaries
warnRxBounded()
: Warn that the rxode2 model has any parameters with user defined boundaries
Matthew L. Fidler
Other Assertions:
assertCompartmentExists()
,
assertCompartmentName()
,
assertCompartmentNew()
,
assertRxUi()
,
assertVariableExists()
,
assertVariableNew()
one.cmt <- function() { ini({ tka <- 0.45; label("Ka") tcl <- log(c(0, 2.7, 100)); label("Cl") tv <- 3.45; label("V") 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) }) } testRxUnbounded(one.cmt) try(assertRxUnbounded(one.cmt)) warnRxBounded(one.cmt)
one.cmt <- function() { ini({ tka <- 0.45; label("Ka") tcl <- log(c(0, 2.7, 100)); label("Cl") tv <- 3.45; label("V") 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) }) } testRxUnbounded(one.cmt) try(assertRxUnbounded(one.cmt)) warnRxBounded(one.cmt)
Convert event data to trial duration data A helper function to create a custom event table. The observation time will start from the first event time (baseline) and end at trial duration. The interval is the spacing between each observation.
toTrialDuration(ev, trialEnd, interval, writeDir = NULL)
toTrialDuration(ev, trialEnd, interval, writeDir = NULL)
ev |
event data |
trialEnd |
extend trial duration. Must be same time unit as event data |
interval |
observation interval. Must be same time unit as event data |
writeDir |
if not NULL, write the output to a csv file |
Omar Elashkar
# Create event table with unique time for each ID ev = et(data.frame(id = rep(1:10, 3), time = runif(min = 10, max = 20, n = 30))) # select the duration and spacing interval (assuming time is in years) toTrialDuration(ev, trialEnd = 1.5, interval = 0.2)
# Create event table with unique time for each ID ev = et(data.frame(id = rep(1:10, 3), time = runif(min = 10, max = 20, n = 30))) # select the duration and spacing interval (assuming time is in years) toTrialDuration(ev, trialEnd = 1.5, interval = 0.2)
Update for rxUi
## S3 method for class 'rxUi' update(object, ..., envir = parent.frame())
## S3 method for class 'rxUi' update(object, ..., envir = parent.frame())
object |
rxode2 UI object |
... |
Lines to update |
envir |
Environment for evaluating ini() style calls |
a new rxode2 updated UI object
This is the tgamma from the boost library
uppergamma(a, z)
uppergamma(a, z)
a |
The numeric 'a' parameter in the upper incomplete gamma |
z |
The numeric 'z' parameter in the upper incomplete gamma |
The uppergamma function is given by:
uppergamma results
Matthew L. Fidler
uppergamma(1, 3) uppergamma(1:3, 3) uppergamma(1, 1:3)
uppergamma(1, 3) uppergamma(1:3, 3) uppergamma(1, 1:3)
Set random effects and residual error to zero
zeroRe(object, which = c("omega", "sigma"), fix = TRUE)
zeroRe(object, which = c("omega", "sigma"), fix = TRUE)
object |
The model to modify |
which |
The types of parameters to set to zero |
fix |
Should the parameters be fixed to the zero value? |
The object
with some parameters set to zero
Bill Denney
Other Initial conditions:
ini.rxUi()
one.compartment <- function() { ini({ tka <- log(1.57); label("Ka") tcl <- log(2.72); label("Cl") tv <- log(31.5); label("V") 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) d/dt(depot) = -ka * depot d/dt(center) = ka * depot - cl / v * center cp = center / v cp ~ add(add.sd) }) } zeroRe(one.compartment)
one.compartment <- function() { ini({ tka <- log(1.57); label("Ka") tcl <- log(2.72); label("Cl") tv <- log(31.5); label("V") 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) d/dt(depot) = -ka * depot d/dt(center) = ka * depot - cl / v * center cp = center / v cp ~ add(add.sd) }) } zeroRe(one.compartment)