Version: | 4.0.1 |
Title: | Facilities for Simulating from ODE-Based Models |
Maintainer: | Matthew L. Fidler <matthew.fidler@gmail.com> |
Depends: | R (≥ 4.0.0) |
Suggests: | Matrix, DT, covr, crayon, curl, digest, dplyr (≥ 0.8.0), ggrepel, gridExtra, htmltools, knitr, learnr, microbenchmark, nlme, remotes, rlang, rmarkdown, scales, shiny, stringi, symengine, testthat, tidyr, usethis, vdiffr (≥ 1.0), withr, xgxr, pillar, tibble, units (≥ 0.6-0), rsconnect, devtools, patchwork, nlmixr2data, lifecycle, kableExtra, pmxTools |
Imports: | PreciseSums (≥ 0.7), Rcpp (≥ 0.12.3), backports, cli (≥ 2.0.0), checkmate, ggplot2 (≥ 3.4.0), inline, lotri (≥ 1.0.0), magrittr, memoise, methods, rex, sys, tools, utils, dparser (≥ 1.3.1-12), rxode2ll(≥ 2.0.9), data.table (≥ 1.12.4), qs (≥ 0.26.3) |
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. |
BugReports: | https://github.com/nlmixr2/rxode2/issues/ |
NeedsCompilation: | yes |
VignetteBuilder: | knitr |
License: | GPL (≥ 3) |
URL: | https://nlmixr2.github.io/rxode2/, https://github.com/nlmixr2/rxode2/ |
RoxygenNote: | 7.3.2 |
Biarch: | true |
LinkingTo: | sitmo, lotri (≥ 1.0.0), PreciseSums (≥ 0.7), Rcpp, RcppArmadillo (≥ 0.9.300.2.0), BH, RcppParallel, RcppEigen (≥ 0.3.3.9.2), StanHeaders (≥ 2.21.0.7), dparser (≥ 1.3.1-12) |
Encoding: | UTF-8 |
LazyData: | true |
Language: | en-US |
Config/testthat/edition: | 3 |
Packaged: | 2025-07-17 18:04:26 UTC; matt |
Author: | Matthew L. Fidler |
Repository: | CRAN |
Date/Publication: | 2025-07-18 00:10:02 UTC |
Update Solved object with '+'
Description
Update Solved object with '+'
Usage
## S3 method for class 'rxSolve'
solved + new
Arguments
solved |
Solved object |
new |
New information added to the table. |
Value
new solved object
Author(s)
Matthew L. Fidler
This function asserts the requested rename makes sense
Description
It returns the new expression, old expression, new variable and old variable
Usage
.assertRenameErrorModelLine(line, vars)
Arguments
line |
quoted call information line |
vars |
Variables contained within the mdel |
Value
list(new, old, newChar, oldChar)
Author(s)
Matthew L. Fidler
cbind Ome
Description
cbind Ome
Usage
.cbindOme(et, mat, n)
Arguments
et |
The theta data frame |
mat |
The full matrix simulation from omegas |
n |
number of subject simulated |
Value
data frame with et combined with simulated omega matrix values
Author(s)
Matthew Fidler
Clear/Set pipeline
Description
Clear/Set pipeline
Usage
.clearPipe(
rx = NULL,
inits = NULL,
events = NULL,
params = NULL,
iCov = NULL,
keep = NULL,
thetaMat = NULL,
omega = NULL,
sigma = NULL,
dfObs = NULL,
dfSub = NULL,
nSub = NULL,
nStud = NULL
)
Arguments
rx |
rxode2 object |
Value
None, clears rxode2 pipeline
Collect warnings and just warn once.
Description
Collect warnings and just warn once.
Usage
.collectWarnings(expr, lst = FALSE)
Arguments
expr |
R expression |
lst |
When |
Value
The value of the expression or a list with the value of the expression and a list of warning messages
Author(s)
Matthew L. Fidler
Convert a factor/char to an id
Description
Convert a factor/char to an id
Usage
.convertId(a)
Arguments
a |
value to convert to an id |
Value
id factor
Author(s)
Matthew L. Fidler
Examples
.convertId("a")
This copies the rxode2 UI object so it can be modified
Description
This copies the rxode2 UI object so it can be modified
Usage
.copyUi(ui)
Arguments
ui |
Original UI object |
Value
Copied UI object
Author(s)
Matthew L. Fidler
Expand parameters
Description
Expand parameters
Usage
.expandPars(object, params, events, control)
Arguments
object |
rxode2 model variables object |
params |
parameters to expand |
events |
event table to help with the expansion |
control |
control structure to help with the parameter generation |
Value
Expanded parameters for simulation
Author(s)
Matthew L. Fidler
Generate extraC information for rxode2 models
Description
Generate extraC information for rxode2 models
Usage
.extraC(extraC = NULL)
Arguments
extraC |
Additional extraC from rxode2 compile optioioins |
Value
Nothing, called for side effects
Author(s)
Matthew L. Fidler
Get the extraCnow for compiling
Description
Get the extraCnow for compiling
Usage
.extraCnow()
Value
string of extraC information
Author(s)
Matthew L. Fidler
Get the last idLvl
Description
Get the last idLvl
Usage
.getLastIdLvl()
Value
Last idLvl
Author(s)
Matthew L. Fidler
Examples
.getLastIdLvl()
Get the internal breakdown of an evid
Description
Get the internal breakdown of an evid
Usage
.getWh(i)
Arguments
i |
evid to breakdown |
Value
named evid integer vector
Author(s)
Matthew L. Fidler
Examples
.getWh(1001)
.getWh(10401)
Handle the single error for normal or t distributions
Description
Handle the single error for normal or t distributions
Usage
.handleSingleErrTypeNormOrTFoceiBase(
env,
pred1,
errNum = 1L,
rxPredLlik = TRUE
)
Arguments
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 |
Value
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
Author(s)
Matthew Fidler
This gets the append arg for the ini() piping
Description
This gets the append arg for the ini() piping
Usage
.iniGetAppendArg(f, s)
Arguments
f |
this is the |
s |
this is the |
Value
corrected ini piping argument
This is exported for creating new ini methods that have the same requirements for piping
Author(s)
Matthew L. Fidler
Reorder rows in iniDf
Description
Reorder rows in iniDf
Usage
.iniHandleAppend(expr, rxui, envir, append)
Arguments
expr |
Expression for parsing |
rxui |
User interface function |
envir |
Environment for parsing |
append |
Reorder theta parameters. |
Value
Nothing, called for side effects
Update the iniDf of a model
Description
Update the iniDf of a model
Usage
.iniHandleLine(expr, rxui, envir = parent.frame(), append = NULL)
.iniHandleFixOrUnfix(expr, rxui, envir = parent.frame(), append = NULL)
Arguments
expr |
Expression for parsing |
rxui |
User interface function |
envir |
Environment for parsing |
append |
Reorder theta parameters. |
Value
Nothing, called for side effects
Author(s)
Matthew L. Fidler
Check if a language object matches a template language object
Description
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.
Usage
.matchesLangTemplate(x, template)
Arguments
x |
The object to check |
template |
The template object it should match |
Value
TRUE if it matches, FALSE, otherwise
Examples
.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/."))
Internal messaging statements
Description
Internal messaging statements
Usage
.minfo(text, ..., .envir = parent.frame())
.malert(text, ..., .envir = parent.frame())
.mwarn(text, ..., .envir = parent.frame())
.msuccess(text, ..., .envir = parent.frame())
Arguments
text |
Text |
... |
Other arguments |
.envir |
Environment to evaluate in |
Value
Nothing, called for side effects
Author(s)
Matthew L. Fidler
Handle model lines
Description
Handle model lines
Usage
.modelHandleModelLines(
modelLines,
rxui,
modifyIni = FALSE,
append = NULL,
auto = getOption("rxode2.autoVarPiping", TRUE),
cov = NULL,
envir
)
Arguments
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 |
Value
New UI
Author(s)
Matthew L. Fidler
Assign in the rxode2 pipeline
Description
Assign in the rxode2 pipeline
Usage
.pipeRx(obj)
.pipeInits(obj)
.pipeEvents(obj)
.pipeParams(obj)
.pipeKeep(obj)
.pipeThetaMat(obj)
.pipeOmega(obj)
.pipeSigma(obj)
.pipeDfObs(obj)
.pipeDfSub(obj)
.pipeNSub(obj)
.pipeNStud(obj)
Arguments
obj |
Object to assign. If NA return the value. |
Value
The pipeline object (invisibly)
Author(s)
Matthew L. Fidler
Returns quoted call information
Description
Returns quoted call information
Usage
.quoteCallInfoLines(callInfo, envir = parent.frame(), iniDf = NULL)
Arguments
callInfo |
Call information |
envir |
Environment for evaluation (if needed) |
iniDf |
The parent model |
Value
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.
Author(s)
Matthew L. Fidler
Get a blank, theta1, or eta1 initialization block for iniDf
Description
Get a blank, theta1, or eta1 initialization block for iniDf
Usage
.rxBlankIni(type = c("empty", "theta", "eta"))
Arguments
type |
type of initialization block to return |
Value
A data.frame with the appropriate number/type of columns.
For type="empty", the data.frame will have 0 rows but all the correct types.
For type="theta", the data.frame will have 1 row with the correct types and default values. The "name" and "est" will likely need to be updated.
For type="eta", the data.frame will have 1 row with the correct types and default values for the a single eta being added. The "name" and "est" will likely need to be updated.
Author(s)
Matthew L. Fidler
Examples
.rxBlankIni("empty")
.rxBlankIni("theta")
.rxBlankIni("eta")
Return the C code of an internal function
Description
Return the C code of an internal function
Usage
.rxC(fun)
Arguments
fun |
is the string of a function that you wish to get the C code for |
Value
C code if found (as a string) or NULL if not found
Author(s)
Matthew Fider
Print out a table in the documentation
Description
Print out a table in the documentation
Usage
.rxDocTable(table, caption = "none")
Arguments
table |
data frame |
caption |
a character vector representing the caption for the latex table |
Value
based on the knitr
context:
output a
kableExtra::kbl
forlatex
outputoutput a
DT::datatable
for html outputotherwise output a
knitr::kable
Author(s)
Matthew L. Fidler
Examples
.rxDocTable(rxReservedKeywords)
Get the upper boundary condition when the transformation it
Description
Get the upper boundary condition when the transformation it
Usage
.rxGetHiBoundaryPred1AndIni(env, pred1)
Arguments
env |
Environment for the parsed model |
pred1 |
The |
Value
Upper Boundary
Author(s)
Matthew Fidler
Get the lambda value based on the pred information
Description
Get the lambda value based on the pred information
Usage
.rxGetLambdaFromPred1AndIni(env, pred1)
Arguments
env |
Environment that has the environment |
pred1 |
Single error data frame |
Value
Lambda expression
Author(s)
Matthew Fidler
Get the lower boundary condition when the transformation requires it
Description
Get the lower boundary condition when the transformation requires it
Usage
.rxGetLowBoundaryPred1AndIni(env, pred1)
Arguments
env |
Environment for the parsed model |
pred1 |
The |
Value
Lower Boundary
Author(s)
Matthew Fidler
Get the Observation transformation
Description
Get the Observation transformation
Usage
.rxGetPredictionDVTransform(env, pred1, yj)
Arguments
env |
Environment for the parsed model |
pred1 |
The |
yj |
The transformation number for the current error |
Value
The transformation expression
Author(s)
Matthew Fidler
Get the prediction name
Description
Get the prediction name
Usage
.rxGetPredictionF(env, pred1)
Arguments
env |
Environment for the parsed model |
pred1 |
The |
Value
The prediction symbol
Author(s)
Matthew Fidler
Get the prediction transformation
Description
Get the prediction transformation
Usage
.rxGetPredictionFTransform(env, pred1, yj)
Arguments
env |
Environment for the parsed model |
pred1 |
The |
yj |
The transformation number for the current error |
Value
The transformation expression
Author(s)
Matthew Fidler
Get Variance for error type
Description
Get Variance for error type
Usage
.rxGetVarianceForErrorType(env, pred1)
Arguments
env |
Environment |
pred1 |
Pred for one end-point |
Value
Variance error type
Author(s)
Matthew L. Fidler
Internal function to tell if the linCmt() is the model variables
Description
Internal function to tell if the linCmt() is the model variables
Usage
.rxIsLinCmt()
Value
0 or 1
Author(s)
Matthew L. Fidler
Internal function for calculating the Jacobian
Description
Internal function for calculating the Jacobian
Usage
.rxJacobian(model, vars = TRUE)
Arguments
model |
symengine environment |
vars |
Variables |
Value
Jacobian information
Author(s)
Matthew L. Fidler
Get the linear compartment model states
Description
Get the linear compartment model states
Usage
.rxLinCmt(obj)
Arguments
obj |
rxode2 type of object |
Value
compartment names
Author(s)
Matthew L. Fidler
Internal function to generate the model variables for a linCmt() model
Description
Internal function to generate the model variables for a linCmt() model
Usage
.rxLinCmtGen(lenState, vars)
Arguments
lenState |
Length of the state |
vars |
Variables in the model |
Value
Model variables of expanded linCmt model
Author(s)
Matthew L. Fidler
Get the number of linear compartments
Description
Get the number of linear compartments
Usage
.rxLinNcmt(obj)
Arguments
obj |
rxode2 object |
Value
A named integer vector with the number of linear compartments (numLin, numLinSens and depotLin)
Author(s)
Matthew L. Fidler
Internal Pruning function
Description
Internal Pruning function
Usage
.rxPrune(x, envir = parent.frame(), strAssign = list())
Arguments
x |
List of quoted lines |
envir |
Environment where information is stored |
strAssign |
string assignment list from model variables |
Value
Pruned model code
Author(s)
Matthew L. Fidler
Return the equivalents symengine user functions from C
Description
Return the equivalents symengine user functions from C
Usage
.rxSEeqUsr()
Value
equivalent symengine user functions
Author(s)
Matthew L. Fidler
Sensitivity for model
Description
Sensitivity for model
Usage
.rxSens(model, vars, vars2)
Arguments
model |
symengine model environment |
vars |
Variables for single sensitivity |
vars2 |
if present, 2 parameter sensitivity |
Value
Sensitivity
Author(s)
Matthew L. Fidler
Get the information about the rxode2 derived parameter transformation
Description
Get the information about the rxode2 derived parameter transformation
Usage
.rxTransInfo(...)
Arguments
... |
Parameters translated, should be unquoted and not assigned to anything. |
Value
Translation information; This list contains:
-
$str
A named string of the parameters as seen in the underlying C/C++ code. The parameters that are NA are not used in the linear compartment model calculations. -
$ncmt
the number of compartments in the model -
$trans
the rxode2 translation number of the parameterization
This contains the linCmt() translation number, the number of compartments and the parameters
Author(s)
Matthew L. Fidler
Examples
.rxTransInfo(cl, v , Vp, vp2, q, q2)
.rxTransInfo(k12, k21, k13, k31, kel, v)
.rxTransInfo(k12, k21, k13, k31, kel, v, ka)
.rxTransInfo(CL, V)
rxode2 general transformation function
Description
rxode2 general transformation function
Usage
.rxTransform(
x,
lambda = 1,
low = 0,
high = 1,
transform = c("boxCox", "yeoJohnson", "untransformed", "lnorm", "logit",
"logit + yeoJohnson", "probit", "probit + yeoJohnson", "logit + boxCox",
"probit + boxCox"),
inverse = FALSE
)
Arguments
x |
value that will be transformed |
lambda |
lambda value for the transformation |
low |
lower bound for the transformation |
high |
upper bound for the transformation |
transform |
transformation to use (can be integer or string matching supported transformations) |
inverse |
boolean if the inverse transformation should be performed |
Value
transformed value
Author(s)
Matthew L. Fidler
Examples
logit(0.25)
.rxTransform(0.25, transform="logit")
expit(-1.09)
.rxTransform(-1.09, transform="logit", inverse=TRUE)
Temporarily set options then restore them while running code
Description
Temporarily set options then restore them while running code
Usage
.rxWithOptions(ops, code)
Arguments
ops |
list of options that will be temporarily set for the
|
code |
The code to run during the sink |
Value
value of code
Examples
.rxWithOptions(list(digits = 21), {
print(pi)
})
print(pi)
With one sink, then release
Description
With one sink, then release
Usage
.rxWithSink(file, code)
.rxWithSinkBoth(file, code)
Arguments
file |
the path to the file sink while running the |
code |
The code to run during the sink |
Details
.rxWithSink
captures output from cat
.rxWithSinkBoth
captures output from cat
and message
Value
Will return the results of the code
section
Author(s)
Matthew Fidler
Examples
t <- tempfile()
.rxWithSink(t, cat("message\n"))
cat("cat2\n") # now you can see the cat2
lines <- readLines(t)
unlink(t)
Temporarily set options then restore them while running code
Description
Temporarily set options then restore them while running code
Usage
.rxWithWd(wd, code)
Arguments
wd |
working directory to temporarily set the system to while evaluating the code |
code |
The code to run during the sink |
Value
value of code
Examples
.rxWithWd(tempdir(), {
getwd()
})
getwd()
Get the rxode2 function pointers
Description
This function is used to get the function pointers for rxode2. This is used to allow rxode2 to have binary linkage to nlmixr2est.
Usage
.rxode2ptrs()
Value
a list of function pointers
Author(s)
Matthew L. Fidler
Examples
.rxode2ptrs()
Register a method for a suggested dependency
Description
Generally, the recommend way to register an S3 method is to use the
S3Method()
namespace directive (often generated automatically by the
@export
roxygen2 tag). However, this technique requires that the generic
be in an imported package, and sometimes you want to suggest a package,
and only provide a method when that package is loaded. s3_register()
can be called from your package's .onLoad()
to dynamically register
a method only if the generic's package is loaded. (To avoid taking a
dependency on vctrs for this one function, please feel free to copy
and paste the function source into your own package.)
Usage
.s3register(generic, class, method = NULL)
Arguments
generic |
Name of the generic in the form |
class |
Name of the class |
method |
Optionally, the implementation of the method. By default,
this will be found by looking for a function called Note that providing |
Details
For R 3.5.0 and later, s3_register()
is also useful when demonstrating
class creation in a vignette, since method lookup no longer always involves
the lexical scope. For R 3.6.0 and later, you can achieve a similar effect
by using "delayed method registration", i.e. placing the following in your
NAMESPACE
file:
if (getRversion() >= "3.6.0") { S3method(package::generic, class) }
Value
nothing; called for side effects
Examples
# A typical use case is to dynamically register tibble/pillar methods
# for your class. That way you avoid creating a hard dependency on packages
# that are not essential, while still providing finer control over
# printing when they are used.
.onLoad <- function(...) {
.s3Register("pillar::pillar_shaft", "vctrs_vctr")
.s3Register("tibble::type_sum", "vctrs_vctr")
}
Calculate the lambdas and coefficients of the two compartment model
Description
Calculate the lambdas and coefficients of the two compartment model
Usage
.solComp2(k10, k12, k21)
Arguments
k10 |
elimination rate |
k12 |
rate from central to peripheral compartment |
k21 |
rate from peripheral to central compartment |
Value
List with L
vector and matrices C1
and C2
Author(s)
Matthew L. Fidler based on wnl
package/paper, implemented
in C/C++
Examples
.solComp2(k10=0.1, k12=3, k21=1)
Calculate the lambdas and coefficients of the three compartment model
Description
Calculate the lambdas and coefficients of the three compartment model
Usage
.solComp3(k10, k12, k21, k13, k31)
Arguments
k10 |
elimination rate |
k12 |
rate from central to peripheral compartment |
k21 |
rate from peripheral to central compartment |
k13 |
rate from central to peripheral compartment #2 |
k31 |
rate from peripheral compartment #2 to central |
Value
List with L
vector and matrices C1
, C2
and C3
Author(s)
Matthew L. Fidler
Examples
.solComp3(k10=0.1, k12=3, k21=1, k13=2, k31=0.5)
Return symengineFs from user functions
Description
Return symengineFs from user functions
Usage
.symengineFs()
Value
symengineFs from user functions
Author(s)
Matthew L. Fidler
This converts NONMEM-style EVIDs to classic RxODE events
Description
This converts NONMEM-style EVIDs to classic RxODE events
Usage
.toClassicEvid(cmt = 1L, amt = 0, rate = 0, dur = 0, ii = 0, evid = 0L, ss = 0)
Arguments
cmt |
compartment flag |
amt |
dose amount |
rate |
dose rate |
dur |
dose duration |
ii |
inter-dose interval |
evid |
event id |
ss |
steady state |
Value
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.
Author(s)
Matthew L. Fidler
Examples
.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)
Get the function name with the current arguments as a string
Description
Get the function name with the current arguments as a string
Usage
.udfCallFunArg(fun, args)
Arguments
fun |
function name |
args |
arguments |
Value
string of the form 'fun(arg1, arg2)':
Author(s)
Matthew L. Fidler
Lock/Unlock environment for getting R user functions
Description
Lock/Unlock environment for getting R user functions
Usage
.udfEnvReset(lock = TRUE)
Arguments
lock |
logical to see if environment to look for user defined functions is locked. If it is locked then environments are not assigned. When NULL returns lock status |
Value
lock status
Author(s)
Matthew L. Fidler
Setup the UDF environment (for querying user defined funtions)
Description
Setup the UDF environment (for querying user defined funtions)
Usage
.udfEnvSet(env)
Arguments
env |
environment where user defined functions are queried. If NULL return current environment |
Value
environment
Author(s)
Matthew L. Fidler
Use the udf model variable information to get the environment where the functions exists
Description
Use the udf model variable information to get the environment where the functions exists
Usage
.udfEnvSetUdf(udf)
Arguments
udf |
modelVars$udf, integer vector with NA_integer_ for the address of the environment where the functions exist |
Value
nothing called for side effects
Author(s)
Matthew L. Fidler
See if the UI function exists in given environment.
Description
If other functions have been declared, make sure they exist too.
Usage
.udfExists(fun, nargs, envir, doList = TRUE)
Arguments
fun |
Function to check |
nargs |
Number of args to check |
envir |
Environment to check |
doList |
A boolean to see if the functions in .udfEnv$fun should be checked too. By default TRUE, but this is called recursively for each function (and set to FALSE) |
Value
logical declaring if the udf function exists in this environment
Author(s)
Matthew L. Fidler
Get the udf strings for creating model md5
Description
Get the udf strings for creating model md5
Usage
.udfMd5Info()
Value
string vector
Author(s)
Matthew L. Fidler
Handle arguments for ui functions
Description
Note this is an internal function but it is exported in case it is useful.
Usage
.uiArg(char, f, dp)
Arguments
char |
This is the character equivalent of the argument |
f |
This is the forced equivalent of the argument |
dp |
This is deparsed expression |
Value
character representing the underlying rxode2 code for the argument
Author(s)
Matthew L. Fidler
Examples
.uiArg("1.0", 1.0, "1.0")
Internal function to figure out if this session supports Unicode
Description
Internal function to figure out if this session supports Unicode
Usage
.useUtf()
Value
boolean indicating if this session supports Unicode
Convert numeric vector to repeated data.frame
Description
Convert numeric vector to repeated data.frame
Usage
.vecDf(vec, n)
Arguments
vec |
Named input vector |
n |
Number of columns |
Value
Data frame with repeated vec
Author(s)
Matthew Fidler
Exponential Linear Unit (ELU) Activation Function
Description
Exponential Linear Unit (ELU) Activation Function
Usage
ELU(x, alpha = 1)
Arguments
x |
A numeric vector. All elements must be finite and non-missing. |
alpha |
A numeric scalar. All elements must be finite and non-missing. |
Value
A numeric vector where the ReLU function has been applied
to each element of x
.
Author(s)
Matthew Fidler
See Also
Other Activation Functions:
GELU()
,
PReLU()
,
ReLU()
,
SELU()
,
Swish()
,
dELU()
,
dGELU()
,
dPReLU()
,
dReLU()
,
dSELU()
,
dSwish()
,
dlReLU()
,
dsoftplus()
,
lReLU()
,
softplus()
Examples
ELU(c(-1, 0, 1, 2), 2)
# Can also be used in rxode2:
x <- rxode2({
r=SELU(time)
})
e <- et(c(-1, 0, 1, 2))
rxSolve(x, e)
GELU activation function
Description
GELU activation function
Usage
GELU(x)
Arguments
x |
numeric vector |
Value
numeric vector
See Also
Other Activation Functions:
ELU()
,
PReLU()
,
ReLU()
,
SELU()
,
Swish()
,
dELU()
,
dGELU()
,
dPReLU()
,
dReLU()
,
dSELU()
,
dSwish()
,
dlReLU()
,
dsoftplus()
,
lReLU()
,
softplus()
Examples
GELU(c(-2, -1, 0, 1, 2))
# you can use rxode2 as well
r <- rxode2({
r = GELU(time)
})
et <- et(c(-2, -1, 0, 1, 2))
rxSolve(r, et)
Parametric ReLU Activation Function
Description
Parametric ReLU Activation Function
Usage
PReLU(x, alpha = 1)
Arguments
x |
A numeric vector. All elements must be finite and non-missing. |
alpha |
A numeric scalar. All elements must be finite and non-missing. |
Value
A numeric vector where the ReLU function has been applied
to each element of x
.
Author(s)
Matthew Fidler
See Also
Other Activation Functions:
ELU()
,
GELU()
,
ReLU()
,
SELU()
,
Swish()
,
dELU()
,
dGELU()
,
dPReLU()
,
dReLU()
,
dSELU()
,
dSwish()
,
dlReLU()
,
dsoftplus()
,
lReLU()
,
softplus()
Examples
PReLU(c(-1, 0, 1, 2), 2)
# Can also be used in rxode2:
x <- rxode2({
r=PReLU(time, 2)
})
e <- et(c(-1, 0, 1, 2))
rxSolve(x, e)
Rectified Linear Unit (ReLU) Activation Function
Description
This function applies the Rectified Linear Unit (ReLU) activation function to the input numeric vector.
The ReLU function is defined as the positive part of its argument: f(x) = max(0, x)
.
Usage
ReLU(x)
Arguments
x |
A numeric vector. All elements must be finite and non-missing. |
Value
A numeric vector where the ReLU function has been applied
to each element of x
.
Author(s)
Matthew Fidler
See Also
Other Activation Functions:
ELU()
,
GELU()
,
PReLU()
,
SELU()
,
Swish()
,
dELU()
,
dGELU()
,
dPReLU()
,
dReLU()
,
dSELU()
,
dSwish()
,
dlReLU()
,
dsoftplus()
,
lReLU()
,
softplus()
Examples
ReLU(c(-1, 0, 1, 2))
# Can also be used in rxode2:
x <- rxode2({
r=ReLU(time)
})
e <- et(c(-1, 0, 1, 2))
rxSolve(x, e)
Scaled Exponential Linear Unit (SELU) Activation Function
Description
Scaled Exponential Linear Unit (SELU) Activation Function
Usage
SELU(x)
Arguments
x |
A numeric vector. All elements must be finite and non-missing. |
Value
A numeric vector where the ReLU function has been applied
to each element of x
.
Author(s)
Matthew Fidler
See Also
Other Activation Functions:
ELU()
,
GELU()
,
PReLU()
,
ReLU()
,
Swish()
,
dELU()
,
dGELU()
,
dPReLU()
,
dReLU()
,
dSELU()
,
dSwish()
,
dlReLU()
,
dsoftplus()
,
lReLU()
,
softplus()
Examples
SELU(c(-1, 0, 1, 2))
# Can also be used in rxode2:
x <- rxode2({
r=SELU(time)
})
e <- et(c(-1, 0, 1, 2))
rxSolve(x, e)
Switch Activation Function
Description
The switch activation function is defined as:
Usage
Swish(x)
Arguments
x |
A numeric vector. All elements must be finite and non-missing. |
Details
f(x) = x \cdot \text{sigmoid}(x)
Value
A numeric vector where the ReLU function has been applied
to each element of x
.
Author(s)
Matthew Fidler
See Also
Other Activation Functions:
ELU()
,
GELU()
,
PReLU()
,
ReLU()
,
SELU()
,
dELU()
,
dGELU()
,
dPReLU()
,
dReLU()
,
dSELU()
,
dSwish()
,
dlReLU()
,
dsoftplus()
,
lReLU()
,
softplus()
Examples
Swish(c(-1, 0, 1, 2))
# Can also be used in rxode2:
x <- rxode2({
r<- Swish(time)
})
e <- et(c(-1, 0, 1, 2))
rxSolve(x, e)
Add dosing to eventTable
Description
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(...)
Usage
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_,
...
)
Arguments
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 |
Value
eventTable with updated dosing (note the event table will be updated anyway)
Author(s)
Matthew L. Fidler
Matthew L Fidler, Wenping Wang
References
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
See Also
eventTable
, add.sampling
,
add.dosing
, et
,
etRep
, etRbind
,
rxode2
Examples
## Not run:
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)
## End(Not run)
Add sampling to eventTable
Description
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()
Usage
add.sampling(eventTable, time, time.units = NA)
Arguments
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
|
Value
eventTable with updated sampling. (Note the event table will be updated even if you don't reassign the eventTable)
Author(s)
Matthew L Fidler, Wenping Wang
References
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
See Also
eventTable
, add.sampling
,
add.dosing
, et
,
etRep
, etRbind
,
rxode2
Examples
## Not run:
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)
## End(Not run)
Coerce object to data.frame
Description
Coerce object to data.frame
Usage
as.et(x, ...)
## Default S3 method:
as.et(x, ...)
Arguments
x |
Object to coerce to et. |
... |
Other parameters |
Value
An event table
Turn into an ini block for initialization
Description
Turn into an ini block for initialization
Usage
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)
Arguments
x |
Item to convert to a rxode2/nlmixr2 ui ini expression |
Value
rxode2 ini expression
Author(s)
Matthew L. Fidler
Examples
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
Description
Turn into a model expression
Usage
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)
Arguments
x |
item to convert to a |
Value
model expression
Author(s)
Matthew L. Fidler
Examples
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
Description
As rxode2 ui
Usage
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)
Arguments
x |
Object to convert to |
Value
rxUi object (or error if it cannot be converted)
Author(s)
Matthew L. Fidler
Examples
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
Description
Verify that the compartment exists in a model
Usage
assertCompartmentExists(ui, x)
testCompartmentExists(ui, x)
Arguments
ui |
is the model to test |
x |
The value to test (can be a vector of strings) |
Value
the value of the compartment that exists; if it is a vector returns the first item that matches
Functions
-
testCompartmentExists()
: Test if compartment exists
Author(s)
Matthew Fidler & Bill Denney
See Also
Other Assertions:
assertCompartmentName()
,
assertCompartmentNew()
,
assertRxUi()
,
assertVariableExists()
,
assertVariableNew()
,
testIniDf()
,
testRxUnbounded()
Verify that a value is a valid nlmixr2 compartment name
Description
Verify that a value is a valid nlmixr2 compartment name
Usage
assertCompartmentName(x)
assertVariableName(x)
assertParameterValue(x)
assertExists(ui, x)
testExists(ui, x)
Arguments
x |
The value to test |
ui |
when needed, this is the rxode2/nlmixr2 model |
Value
The value or an error
Functions
-
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
Author(s)
Bill Denney
See Also
Other Assertions:
assertCompartmentExists()
,
assertCompartmentNew()
,
assertRxUi()
,
assertVariableExists()
,
assertVariableNew()
,
testIniDf()
,
testRxUnbounded()
Verify that a compartment would be new to the model
Description
Verify that a compartment would be new to the model
Usage
assertCompartmentNew(ui, x)
Arguments
ui |
is the model to test that a model paramet exists |
x |
The value to test |
Value
The value or an error
Author(s)
Matthew Fidler & Bill Denney
See Also
Other Assertions:
assertCompartmentExists()
,
assertCompartmentName()
,
assertRxUi()
,
assertVariableExists()
,
assertVariableNew()
,
testIniDf()
,
testRxUnbounded()
Assert properties of the rxUi models
Description
Assert properties of the rxUi models
Usage
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))
Arguments
ui |
Model to check |
extra |
Extra text to append to the error message (like "for focei") |
.var.name |
[ |
Details
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
Value
the rxUi model
Author(s)
Matthew L. Fidler
See Also
Other Assertions:
assertCompartmentExists()
,
assertCompartmentName()
,
assertCompartmentNew()
,
assertVariableExists()
,
assertVariableNew()
,
testIniDf()
,
testRxUnbounded()
Examples
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
Description
Assert a variable exists in the model
Usage
assertVariableExists(ui, x)
testVariableExists(ui, x)
Arguments
ui |
rxode2 ui model |
x |
does the |
Value
variable that matches, in the case of multiple variables, the first that matches. If nothing matches return error
Functions
-
testVariableExists()
: Test if variable exists
Author(s)
Matthew L. Fidler
See Also
Other Assertions:
assertCompartmentExists()
,
assertCompartmentName()
,
assertCompartmentNew()
,
assertRxUi()
,
assertVariableNew()
,
testIniDf()
,
testRxUnbounded()
Assert a variable would be new to the model
Description
Assert a variable would be new to the model
Usage
assertVariableNew(ui, x)
Arguments
ui |
rxode2 ui model |
x |
would the variable |
Value
nothing, but will error if x
would not be new
Author(s)
Matthew L. Fidler
See Also
Other Assertions:
assertCompartmentExists()
,
assertCompartmentName()
,
assertCompartmentNew()
,
assertRxUi()
,
assertVariableExists()
,
testIniDf()
,
testRxUnbounded()
Calculate expected confidence bands with binomial sampling distribution
Description
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.
Usage
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"),
...
)
Arguments
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.
|
Details
It is used for confidence intervals with rxode2 solved objects using
confint(mean="binom")
Value
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.
Author(s)
Matthew L. Fidler
References
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.
Examples
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)
boxCox/yeoJohnson and inverse boxCox/yeoJohnson functions
Description
boxCox/yeoJohnson and inverse boxCox/yeoJohnson functions
Usage
boxCox(x, lambda = 1)
boxCoxInv(x, lambda = 1)
yeoJohnson(x, lambda = 1)
yeoJohnsonInv(x, lambda = 1)
Arguments
x |
input value(s) to transform |
lambda |
lambda value for the transformation |
Value
values from boxCox and boxCoxInv
Examples
boxCox(10, 0.5)
boxCoxInv(4.32, 0.5)
yeoJohnson(10, 0.5)
yeoJohnsonInv(4.32, 0.5)
Return the rxode2 coefficients
Description
This returns the parameters , state variables
Usage
## S3 method for class 'rxode2'
coef(object, ...)
Arguments
object |
is an rxode2 object |
... |
ignored arguments |
Value
a rxCoef object with the following
-
params
is a list of strings for parameters for the rxode2 object -
state
is a list of strings for the names of each state in the rxode2 object. -
ini
is the model specified default values for the parameters. -
rxode2
is the referring rxode2 object
Author(s)
Matthew L.Fidler
Sample a covariance Matrix from the Posterior Inverse Wishart distribution.
Description
Note this Inverse wishart rescaled to match the original scale of the covariance matrix.
Usage
cvPost(
nu,
omega,
n = 1L,
omegaIsChol = FALSE,
returnChol = FALSE,
type = c("invWishart", "lkj", "separation"),
diagXformType = c("log", "identity", "variance", "nlmixrSqrt", "nlmixrLog",
"nlmixrIdentity")
)
Arguments
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. |
Details
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.
Value
a matrix (n=1) or a list of matrices (n > 1)
Author(s)
Matthew L.Fidler & Wenping Wang
References
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
Examples
## 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
)
Derivatives of the Exponential Linear Unit (ELU) Activation Function
Description
Derivatives of the Exponential Linear Unit (ELU) Activation Function
Usage
dELU(x, alpha = 1)
d2ELU(x, alpha = 1)
d2aELU(x, alpha = 1)
dELUa(x, alpha = 1)
d2ELUa(x, alpha = 1)
Arguments
x |
A numeric vector. All elements must be finite and non-missing. |
alpha |
A numeric scalar. All elements must be finite and non-missing. |
Value
A numeric vector where the derivative(s) of the ELU function has been applied
to each element of x
.
Author(s)
Matthew L. Fidler
See Also
Other Activation Functions:
ELU()
,
GELU()
,
PReLU()
,
ReLU()
,
SELU()
,
Swish()
,
dGELU()
,
dPReLU()
,
dReLU()
,
dSELU()
,
dSwish()
,
dlReLU()
,
dsoftplus()
,
lReLU()
,
softplus()
Examples
dELU(c(-1, 0, 1, 2), 2)
d2ELU(c(-1, 0, 1, 2), 2)
d2aELU(c(-1, 0, 1, 2), 2)
dELUa(c(-1, 0, 1, 2), 2)
d2ELUa(c(-1, 0, 1, 2), 2)
# Can also be used in rxode2:
r <- rxode2({
r1=dELU(time, 2)
r2=d2ELU(time, 2)
r2a=d2aELU(time, 2)
ra=dELUa(time, 2)
r2a=d2ELUa(time, 2)
})
e <- et(c(-1, 0, 1, 2))
rxSolve(r, e)
Derivatives of GELU
Description
Derivatives of GELU
Usage
dGELU(x)
d2GELU(x)
d3GELU(x)
d4GELU(x)
Arguments
x |
numeric vector |
Value
numeric vector
See Also
Other Activation Functions:
ELU()
,
GELU()
,
PReLU()
,
ReLU()
,
SELU()
,
Swish()
,
dELU()
,
dPReLU()
,
dReLU()
,
dSELU()
,
dSwish()
,
dlReLU()
,
dsoftplus()
,
lReLU()
,
softplus()
Examples
dGELU(c(-2, -1, 0, 1, 2))
d2GELU(c(-2, -1, 0, 1, 2))
d3GELU(c(-2, -1, 0, 1, 2))
d4GELU(c(-2, -1, 0, 1, 2))
# you can use rxode2 as well
r <- rxode2({
r1 <- dGELU(time)
r2 <- d2GELU(time)
r3 <- d3GELU(time)
r4 <- d4GELU(time)
})
et <- et(c(-2, -1, 0, 1, 2))
rxSolve(r, et)
Derivatives Parametric ReLU Activation Function
Description
Derivatives Parametric ReLU Activation Function
Usage
dPReLU(x, alpha = 1)
dPReLUa(x, alpha = 1)
dPReLUa1(x, alpha = 1)
Arguments
x |
A numeric vector. All elements must be finite and non-missing. |
alpha |
A numeric scalar. All elements must be finite and non-missing. |
Value
A numeric vector where the derivative(s) of the ELU function has been applied
to each element of x
.
Author(s)
Matthew L. Fidler
See Also
Other Activation Functions:
ELU()
,
GELU()
,
PReLU()
,
ReLU()
,
SELU()
,
Swish()
,
dELU()
,
dGELU()
,
dReLU()
,
dSELU()
,
dSwish()
,
dlReLU()
,
dsoftplus()
,
lReLU()
,
softplus()
Examples
dPReLU(c(-1, 0, 1, 2), 2)
dPReLUa(c(-1, 0, 1, 2), 2)
dPReLUa1(c(-1, 0, 1, 2), 2)
# Can also be used in rxode2:
r <- rxode2({
r1=dPReLU(time, 2)
r2a=dPReLUa(time, 2)
ra=dPReLUa1(time, 2)
})
e <- et(c(-1, 0, 1, 2))
rxSolve(r, e)
Derivative of the Rectified Linear Unit (ReLU) Activation Function
Description
This function applies the derivative of the Rectified Linear Unit (ReLU) activation function to the input numeric vector.
Usage
dReLU(x)
Arguments
x |
A numeric vector. All elements must be finite and non-missing. |
Value
A numeric vector where the derivative of the ReLU function
See Also
Other Activation Functions:
ELU()
,
GELU()
,
PReLU()
,
ReLU()
,
SELU()
,
Swish()
,
dELU()
,
dGELU()
,
dPReLU()
,
dSELU()
,
dSwish()
,
dlReLU()
,
dsoftplus()
,
lReLU()
,
softplus()
Examples
dReLU(c(-1, 0, 1, 2))
# Can also be used in rxode2:
x <- rxode2({
r=dReLU(time)
})
e <- et(c(-1, 0, 1, 2))
rxSolve(x, e)
Derivative of the Scaled Exponential Linear Unit (SELU) Activation Function
Description
Derivative of the Scaled Exponential Linear Unit (SELU) Activation Function
Usage
dSELU(x)
Arguments
x |
A numeric vector. All elements must be finite and non-missing. |
Value
A numeric vector where the derivative of the SELU function
has been applied to each element of x
.
Author(s)
Matthew Fidler
See Also
Other Activation Functions:
ELU()
,
GELU()
,
PReLU()
,
ReLU()
,
SELU()
,
Swish()
,
dELU()
,
dGELU()
,
dPReLU()
,
dReLU()
,
dSwish()
,
dlReLU()
,
dsoftplus()
,
lReLU()
,
softplus()
Examples
dSELU(c(-1, 0, 1, 2))
# Can also be used in rxode2:
x <- rxode2({
r=dSELU(time)
})
e <- et(c(-1, 0, 1, 2))
rxSolve(x, e)
Derivative of the Swish Activation Function
Description
Derivative of the Swish Activation Function
Usage
dSwish(x)
Arguments
x |
A numeric vector. All elements must be finite and non-missing. |
Value
A numeric vector where the derivative of the SELU function
has been applied to each element of x
.
Author(s)
Matthew Fidler
See Also
Other Activation Functions:
ELU()
,
GELU()
,
PReLU()
,
ReLU()
,
SELU()
,
Swish()
,
dELU()
,
dGELU()
,
dPReLU()
,
dReLU()
,
dSELU()
,
dlReLU()
,
dsoftplus()
,
lReLU()
,
softplus()
Examples
dSwish(c(-1, 0, 1, 2))
# Can also be used in rxode2:
x <- rxode2({
r <- dSwish(time)
})
e <- et(c(-1, 0, 1, 2))
rxSolve(x, e)
This uses simulations to match the rse
Description
This uses simulations to match the rse
Usage
dfWishart(omega, n, rse, upper, totN = 1000, diag = TRUE, seed = 1234)
Arguments
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 |
Value
output from uniroot()
to find the right estimate
Author(s)
Matthew L. Fidler
Examples
dfWishart(lotri::lotri(a+b~c(1, 0.5, 1)), 100)
Derivative of Leaky ReLU activation function
Description
Derivative of Leaky ReLU activation function
Usage
dlReLU(x)
Arguments
x |
numeric vector |
Value
numeric vector
See Also
Other Activation Functions:
ELU()
,
GELU()
,
PReLU()
,
ReLU()
,
SELU()
,
Swish()
,
dELU()
,
dGELU()
,
dPReLU()
,
dReLU()
,
dSELU()
,
dSwish()
,
dsoftplus()
,
lReLU()
,
softplus()
Examples
dlReLU(c(-1, 0, 1))
# Can use in rxode2 as well
r <- rxode2({r <- dlReLU(time)})
e <- et(c(-1, 0, 1))
rxSolve(r, e)
Default Softplus Activation Function
Description
Default Softplus Activation Function
Usage
dsoftplus(x)
d2softplus(x)
d3softplus(x)
d4softplus(x)
Arguments
x |
numeric vector |
Value
numeric vector
Author(s)
Matthew L. Fidler
See Also
Other Activation Functions:
ELU()
,
GELU()
,
PReLU()
,
ReLU()
,
SELU()
,
Swish()
,
dELU()
,
dGELU()
,
dPReLU()
,
dReLU()
,
dSELU()
,
dSwish()
,
dlReLU()
,
lReLU()
,
softplus()
Examples
dsoftplus(c(-1, 0, 1, 2))
# You can use rxode2 too:
r <- rxode2({
s1 <- dsoftplus(time)
})
e <- et(c(-1, 0, 1, 2))
rxSolve(r, e)
Error function
Description
Error function
Usage
erf(x)
Arguments
x |
vector or real values |
Value
erf of x
Author(s)
Matthew L. Fidler
Examples
erf(1.0)
Event Table Function
Description
Event Table Function
Usage
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
)
Arguments
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 |
Value
A new event table
Author(s)
Matthew L Fidler, Wenping Wang
References
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
See Also
eventTable
, add.sampling
,
add.dosing
, et
,
etRep
, etRbind
,
rxode2
Examples
## Not run:
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)
## End(Not run)
Expand additional doses
Description
Expand additional doses
Usage
etExpand(et)
Arguments
et |
Event table to expand additional doses for. |
Value
New event table with addl
doses expanded
Author(s)
Matthew Fidler
Examples
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
Description
Combining event tables
Usage
etRbind(
...,
samples = c("use", "clear"),
waitII = c("smart", "+ii"),
id = c("merge", "unique")
)
## S3 method for class 'rxEt'
rbind(..., deparse.level = 1)
Arguments
... |
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 |
Value
An event table
Author(s)
Matthew L Fidler
Matthew L Fidler, Wenping Wang
References
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
See Also
eventTable
, add.sampling
,
add.dosing
, et
,
etRep
, etRbind
,
rxode2
Examples
## Not run:
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)
## End(Not run)
Repeat an rxode2 event table
Description
Repeat an rxode2 event table
Usage
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, ...)
Arguments
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. |
Value
An event table
Author(s)
Matthew L Fidler, Wenping Wang
References
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
See Also
eventTable
, add.sampling
,
add.dosing
, et
,
etRep
, etRbind
,
rxode2
Examples
## Not run:
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)
## End(Not run)
Sequence of event tables
Description
This combines a sequence of event tables.
Usage
etSeq(..., samples = c("clear", "use"), waitII = c("smart", "+ii"), ii = 24)
## S3 method for class 'rxEt'
seq(...)
Arguments
... |
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
|
Details
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.
Value
An event table
Author(s)
Matthew L Fidler, Wenping Wang
References
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
See Also
eventTable
, add.sampling
,
add.dosing
, et
,
etRep
, etRbind
,
rxode2
Examples
## Not run:
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)
## End(Not run)
Event translation for rxode2
Description
Event translation for rxode2
Usage
etTrans(
inData,
obj,
addCmt = FALSE,
dropUnits = FALSE,
allTimeVar = FALSE,
keepDosingOnly = FALSE,
combineDvid = NULL,
keep = character(0),
addlKeepsCov = FALSE,
addlDropSs = TRUE,
ssAtDoseTime = TRUE,
iCov = NULL
)
Arguments
inData |
Data frame to translate |
obj |
object where model variables can be extracted from |
addCmt |
Add compartment to data frame (default |
dropUnits |
Boolean to drop the units (default |
allTimeVar |
Treat all covariates as if they were time-varying |
keepDosingOnly |
keep the individuals who only have dosing records and any trailing dosing records after the last observation. |
combineDvid |
is a boolean indicating if rxode2 will use |
keep |
This is a named vector of items you want to keep in the final rxode2 dataset. For added rxode2 event records (if seen), last observation carried forward will be used. |
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 |
iCov |
A data frame of individual non-time varying covariates
to combine with the |
Value
Object for solving in rxode2
Create an event table object
Description
Initializes an object of class ‘EventTable’ with methods for adding and querying dosing and observation records
Usage
eventTable(amount.units = NA, time.units = NA)
Arguments
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. |
Value
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 useqd2 <- qd$copy()
-
expand()
Expands the event table for multi-subject solving. This is done byqd$expand(400)
for a 400 subject data expansion
Author(s)
Matthew Fidler, Melissa Hallow and Wenping Wang
See Also
Examples
# 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())
Find the assignments in R expression
Description
Find the assignments in R expression
Usage
findLhs(x)
Arguments
x |
R expression |
Value
list of assigned parameters
Author(s)
Hadley Wickham and Matthew L. Fidler
Force using base order for rxode2 radix sorting
Description
Force using base order for rxode2 radix sorting
Usage
forderForceBase(forceBase = FALSE)
Arguments
forceBase |
boolean indicating if rxode2 should use R's
|
Value
value of forceBase
(can change if data.table
is not
available)
Examples
forderForceBase(TRUE) # Use base `order` for rxode2 sorts
forderForceBase(FALSE) # Use `data.table` for rxode2 sorts
Gammap: normalized lower incomplete gamma function
Description
This is the gamma_p from the boost library
Usage
gammap(a, z)
Arguments
a |
The numeric 'a' parameter in the normalized lower incomplete gamma |
z |
The numeric 'z' parameter in the normalized lower incomplete gamma |
Details
The gamma p function is given by:
gammap = lowergamma(a, z)/gamma(a)
Value
gammap results
Author(s)
Matthew L. Fidler
Examples
gammap(1, 3)
gammap(1:3, 3)
gammap(1, 1:3)
gammapDer: derivative of gammap
Description
This is the gamma_p_derivative from the boost library
Usage
gammapDer(a, z)
Arguments
a |
The numeric 'a' parameter in the upper incomplete gamma |
z |
The numeric 'z' parameter in the upper incomplete gamma |
Value
lowergamma results
Author(s)
Matthew L. Fidler
Examples
gammapDer(1:3, 3)
gammapDer(1, 1:3)
gammapInv and gammapInva: Inverses of normalized gammap function
Description
gammapInv and gammapInva: Inverses of normalized gammap function
Usage
gammapInv(a, p)
gammapInva(x, p)
Arguments
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 |
Details
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
Value
inverse gammap results
Author(s)
Matthew L. Fidler
Examples
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)
Gammaq: normalized upper incomplete gamma function
Description
This is the gamma_q from the boost library
Usage
gammaq(a, z)
Arguments
a |
The numeric 'a' parameter in the normalized upper incomplete gamma |
z |
The numeric 'z' parameter in the normalized upper incomplete gamma |
Details
The gamma q function is given by:
gammaq = uppergamma(a, z)/gamma(a)
Value
gammaq results
Author(s)
Matthew L. Fidler
Examples
gammaq(1, 3)
gammaq(1:3, 3)
gammaq(1, 1:3)
gammaqInv and gammaqInva: Inverses of normalized gammaq function
Description
gammaqInv and gammaqInva: Inverses of normalized gammaq function
Usage
gammaqInv(a, q)
gammaqInva(x, q)
Arguments
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 |
Details
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
Value
inverse gammaq results
Author(s)
Matthew L. Fidler
Examples
gammaqInv(1:3, 0.5)
gammaqInv(1, 1:3 / 3)
gammaqInv(1:3, 1:3 / 3.1)
gammaqInva(1:3, 1:3 / 3.1)
Generate an example (template) of a dosing regimen shiny app
Description
Create a complete shiny application for exploring dosing regimens given a (hardcoded) PK/PD model.
Usage
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)
Arguments
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 |
Value
None, these functions are used for their side effects.
Note
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.
See Also
rxode2()
,eventTable()
, and the package shiny (https://shiny.posit.co).
Examples
# 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 the base simulation model for simulation with inis in the underlying rxode2 model
Description
Get the base simulation model for simulation with inis in the underlying rxode2 model
Usage
getBaseIniSimModel(obj)
Arguments
obj |
Fit Object |
Value
Simulation object
Author(s)
Matthew L. Fidler
Get the base simulation model for simulation
Description
Get the base simulation model for simulation
Usage
getBaseSimModel(obj)
## Default S3 method:
getBaseSimModel(obj)
## Default S3 method:
getBaseIniSimModel(obj)
Arguments
obj |
Fit Object |
Value
Simulation object
Author(s)
Matthew L. Fidler
Get the symengine for loading into symengine with rxS()
Description
Get the symengine for loading into symengine with rxS()
Usage
getBaseSymengineModel(obj)
Arguments
obj |
Object |
Value
Simulation model ready to load into symeng
Author(s)
Matthew L. Fidler
Get/Set the number of threads that rxode2 uses
Description
Get/Set the number of threads that rxode2 uses
Usage
getRxThreads(verbose = FALSE)
setRxThreads(threads = NULL, percent = NULL, throttle = NULL)
rxCores(verbose = FALSE)
Arguments
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. |
Value
number of threads that rxode2 uses
Empty Guide
Description
This empty guide draws nothing; It is included in rxode2 for compatibility with ggplot 3.2
Usage
guide_none(title = waiver(), position = waiver())
Arguments
title |
A character string or expression indicating a title of guide.
If |
position |
Where this guide should be drawn: one of top, bottom, left, or right. |
Value
nothing, simply included to be compatible with ggplot 3.2
Assign the ini block in the rxode2 related object
Description
Assign the ini block in the rxode2 related object
Usage
ini(x, envir = environment(x)) <- value
Arguments
x |
rxode2 related object |
envir |
Environment where assignment occurs |
value |
Value of the object |
Value
rxode2 related object
Author(s)
Matthew L. Fidler
Ini block for rxode2/nlmixr models
Description
The ini block controls initial conditions for 'theta' (fixed effects), 'omega' (random effects), and 'sigma' (residual error) elements of the model.
Usage
## 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)
Arguments
x |
expression |
... |
Other expressions for |
envir |
the |
append |
Reorder theta parameters. |
Details
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)
. As of rxode2 3.0 you can also use
iivKa ~ 2, iivCL ~ c(2.5, 3)
for covariance matrices as
well.
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)")
.
Off diagonal values of 'omega' can be set to zero using the
diag()
to remove all off-diagonals can be removed with
ini(diag())
. To remove covariances of 'omega' item with iivKa
,
you can use %>% ini(diag(iivKa))
. Or to remove covariances that
contain either iivKa
or iivCl
you can use %>% ini(diag(iivKa, iivCl))
. For finer control you can remove the covariance between
two items (like iivKa
and iivCl
) by '%>% ini(-cov(iivKa, iivCl))
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())
.
Value
ini block
Author(s)
Matthew Fidler
See Also
Other Initial conditions:
zeroRe()
Examples
# 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)")
One correlation sample from the Inverse Wishart distribution
Description
This correlation is constructed by transformation of the Inverse Wishart random covariate to a correlation.
Usage
invWR1d(d, nu, omegaIsChol = FALSE)
Arguments
d |
The dimension of the correlation matrix |
nu |
Degrees of freedom of the Wishart distribution |
omegaIsChol |
is an indicator of if the omega matrix is in
the Cholesky decomposition. This is only used when |
Value
One correlation sample from the inverse wishart
Author(s)
Matthew Fidler
Check to see if this is an rxEt object.
Description
Check to see if this is an rxEt object.
Usage
is.rxEt(x)
Arguments
x |
object to check to see if it is rxEt If this is an rxEt object that has expired strip all rxEt information. |
Value
Boolean indicating if this is a rxode2 event table
Author(s)
Matthew L.Fidler
Check to see if this is an rxSolve object.
Description
Check to see if this is an rxSolve object.
Usage
is.rxSolve(x)
Arguments
x |
object to check to see if it is rxSolve If this is an rxSolve object that has expired strip all rxSolve information. |
Value
boolean indicating if this is a rxSolve
object
Author(s)
Matthew L.Fidler
Return if the object can be stacked
Description
Return if the object can be stacked
Usage
is.rxStackData(object)
Arguments
object |
object to test if it can be stacked |
Value
boolean to tell if an object can be stacked using rxode2
Author(s)
Matthew L. Fidler
Examples
is.rxStackData(NULL)
Leaky ReLU activation function
Description
Leaky ReLU activation function
Usage
lReLU(x)
Arguments
x |
numeric vector |
Value
numeric vector
See Also
Other Activation Functions:
ELU()
,
GELU()
,
PReLU()
,
ReLU()
,
SELU()
,
Swish()
,
dELU()
,
dGELU()
,
dPReLU()
,
dReLU()
,
dSELU()
,
dSwish()
,
dlReLU()
,
dsoftplus()
,
softplus()
Examples
lReLU(c(-1, 0, 1))
# Can use in rxode2 as well
r <- rxode2({r <- lReLU(time)})
e <- et(c(-1, 0, 1))
rxSolve(r, e)
Linear model to replace in rxode2 ui model
Description
Linear model to replace in rxode2 ui model
Usage
linMod(
variable,
power,
dv = "dv",
intercept = TRUE,
type = c("replace", "before", "after"),
num = NULL,
iniDf = NULL,
data = FALSE,
mv = FALSE
)
linMod0(..., intercept = FALSE)
linModB(..., type = "before")
linModB0(..., intercept = FALSE, type = "before")
linModA(..., type = "after")
linModA0(..., intercept = FALSE, type = "after")
linModD(..., intercept = TRUE, data = TRUE)
linModD0(..., intercept = FALSE, data = TRUE)
linModM(..., intercept = TRUE, mv = TRUE)
linModM0(..., intercept = FALSE, mv = TRUE)
Arguments
variable |
The variable that the rxode2 will be made on. |
power |
The power of the polynomial that will be generated. |
dv |
the dependent variable to use to generate the initial
estimates from the data. If |
intercept |
Boolean that tells if the intercept be generated. |
type |
the type of linear model replacement to be used. |
num |
the number the particular model is being generated. If
unspecified, query using |
iniDf |
the initialization |
data |
logical that tells if the initial estimates of the linear model should be estimated from the data. |
mv |
logical that tell if the model variables need to be used to generate model variables. |
... |
arguments that are passed to |
Value
a list for use in when generating the rxode2
ui model see
rxUdfUi()
for details.
Functions
-
linMod0()
: linear model without intercept -
linModB()
: linear model before where it occurs -
linModB0()
: linear model before where the user function occurs -
linModA()
: linear model after where the user function occurs -
linModA0()
: liner model without an intercept placed after where the user function occurs -
linModD()
: linear model where initial estimates are generated from the data -
linModD0()
: linear model where initial estimates are generated from the data (no intercept) -
linModM()
: linear model where the model variables are used to generate the model variables -
linModM0()
: linear model where the model variables are used to generate the model variables (no intercept)
Author(s)
Matthew L. Fidler
See Also
Other User functions:
rxUdfUiControl()
,
rxUdfUiData()
,
rxUdfUiEst()
,
rxUdfUiIniLhs()
,
rxUdfUiMv()
,
rxUdfUiNum()
,
rxUdfUiParsing()
Examples
linMod(x, 3)
Calculate the log likelihood of the binomial function (and its derivatives)
Description
Calculate the log likelihood of the binomial function (and its derivatives)
Usage
llikBeta(x, shape1, shape2, full = FALSE)
Arguments
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 |
Details
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()
.
Value
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
Author(s)
Matthew L. Fidler
Examples
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)
Description
Calculate the log likelihood of the binomial function (and its derivatives)
Usage
llikBinom(x, size, prob, full = FALSE)
Arguments
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 |
Details
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()
Value
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
Author(s)
Matthew L. Fidler
Examples
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)
Description
log likelihood of Cauchy distribution and it's derivatives (from stan)
Usage
llikCauchy(x, location = 0, scale = 1, full = FALSE)
Arguments
x |
Observation |
location , scale |
location and scale parameters. |
full |
Add the data frame showing x, mean, sd as well as the fx and derivatives |
Details
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()
.
Value
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
Author(s)
Matthew L. Fidler
Examples
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
Description
log likelihood and derivatives for chi-squared distribution
Usage
llikChisq(x, df, full = FALSE)
Arguments
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 |
Details
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()
.
Value
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
Author(s)
Matthew L. Fidler
Examples
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
Description
log likelihood and derivatives for exponential distribution
Usage
llikExp(x, rate, full = FALSE)
Arguments
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 |
Details
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()
.
Value
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
Author(s)
Matthew L. Fidler
Examples
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
Description
log likelihood and derivatives for F distribution
Usage
llikF(x, df1, df2, full = FALSE)
Arguments
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 |
Details
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()
.
Value
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
Author(s)
Matthew L. Fidler
Examples
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
Description
log likelihood and derivatives for Gamma distribution
Usage
llikGamma(x, shape, rate, full = FALSE)
Arguments
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 |
Details
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()
.
Value
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
Author(s)
Matthew L. Fidler
Examples
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
Description
log likelihood and derivatives for Geom distribution
Usage
llikGeom(x, prob, full = FALSE)
Arguments
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 |
Details
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()
.
Value
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
Author(s)
Matthew L. Fidler
Examples
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)
Description
Calculate the log likelihood of the negative binomial function (and its derivatives)
Usage
llikNbinom(x, size, prob, full = FALSE)
Arguments
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 |
Details
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()
Value
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
Author(s)
Matthew L. Fidler
Examples
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)
Description
Calculate the log likelihood of the negative binomial function (and its derivatives)
Usage
llikNbinomMu(x, size, mu, full = FALSE)
Arguments
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 |
Details
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()
Value
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
Author(s)
Matthew L. Fidler
Examples
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
Description
Log likelihood for normal distribution
Usage
llikNorm(x, mean = 0, sd = 1, full = FALSE)
Arguments
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 |
Details
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()
Value
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
Author(s)
Matthew L. Fidler
Examples
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
Description
log-likelihood for the Poisson distribution
Usage
llikPois(x, lambda, full = FALSE)
Arguments
x |
non negative integers |
lambda |
non-negative means |
full |
Add the data frame showing x, mean, sd as well as the fx and derivatives |
Details
In an rxode2()
model, you can use llikPois()
but you have to
use all arguments. You can also get the derivatives with
llikPoisDlambda()
Value
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
Author(s)
Matthew L. Fidler
Examples
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)
Description
Log likelihood of T and it's derivatives (from stan)
Usage
llikT(x, df, mean = 0, sd = 1, full = FALSE)
Arguments
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 |
Details
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()
.
Value
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
Author(s)
Matthew L. Fidler
Examples
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
Description
log likelihood and derivatives for Unif distribution
Usage
llikUnif(x, alpha, beta, full = FALSE)
Arguments
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 |
Details
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()
.
Value
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
Author(s)
Matthew L. Fidler
Examples
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
Description
log likelihood and derivatives for Weibull distribution
Usage
llikWeibull(x, shape, scale, full = FALSE)
Arguments
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 |
Details
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()
.
Value
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
Author(s)
Matthew L. Fidler
Examples
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
Description
logit and inverse logit (expit) functions
Usage
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, ...)
Arguments
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 |
Details
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.
Value
values from logit and expit
Examples
logit(0.25)
expit(-1.09)
logitNormInfo(logit(0.25), sd = 0.1)
logitNormInfo(logit(1, 0, 10), sd = 1, low = 0, high = 10)
lowergamma: upper incomplete gamma function
Description
This is the tgamma_lower from the boost library
Usage
lowergamma(a, z)
Arguments
a |
The numeric 'a' parameter in the upper incomplete gamma |
z |
The numeric 'z' parameter in the upper incomplete gamma |
Details
The lowergamma function is given by:
lowergamma(a, z) = \int_{0}^{z}t^{a-1}\cdot e^{-t} dt
Value
lowergamma results
Author(s)
Matthew L. Fidler
Examples
lowergamma(1, 3)
lowergamma(1:3, 3)
lowergamma(1, 1:3)
Calculate expected confidence bands or prediction intreval with normal or t sampling distribution
Description
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.
Usage
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,
...
)
Arguments
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 |
Details
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.
Value
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.
Author(s)
Matthew L. Fidler
Examples
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)
Assign the model block in the rxode2 related object
Description
Assign the model block in the rxode2 related object
Usage
model(x, envir = environment(x)) <- value
Arguments
x |
rxode2 related object |
envir |
Environment where assignment occurs |
value |
Value of the object |
Value
rxode2 related object
Author(s)
Matthew L. Fidler
Model block for rxode2/nlmixr models
Description
Model block for rxode2/nlmixr models
Usage
## 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())
Arguments
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 |
Value
Model block with ini information included. ini
must be
called before model
block
Author(s)
Matthew Fidler
Extract model lines from a rxui model
Description
Extract model lines from a rxui model
Usage
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()
)
Arguments
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 |
Value
expressions or strings of extracted lines. Note if there is a duplicated lhs expression in the line, it will return both lines
Author(s)
Matthew L. Fidler
Examples
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)
Conversion between character and integer ODE integration methods for rxode2
Description
If NULL
is given as the method, all choices are returned as a named
vector.
Usage
odeMethodToInt(method = c("liblsoda", "lsoda", "dop853", "indLin"))
Arguments
method |
The method for solving ODEs. Currently this supports:
|
Value
An integer for the method (unless the input is NULL, in which case, see the details)
Cumulative distribution of standard normal
Description
Cumulative distribution of standard normal
Usage
phi(q)
Arguments
q |
vector of quantiles |
Value
cumulative distribution of standard normal distribution
Author(s)
Matthew Fidler
Examples
# phi is equivalent to pnorm(x)
phi(3)
# See
pnorm(3)
# This is provided for NONMEM-like compatibility in rxode2 models
Plot rxode2 objects
Description
Plot rxode2 objects
Usage
## 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 = "")
Arguments
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 |
Value
A ggplot2 object
See Also
Other rxode2 plotting:
rxTheme()
Print the rxCoef object
Description
This prints out the user supplied arguments for rxCoef object
Usage
## S3 method for class 'rxCoef'
print(x, ...)
Arguments
x |
rxCoef object |
Value
original object
Author(s)
Matthew L.Fidler
Print rxDll object
Description
This tells if the rxDll is loaded, ready and/or deleted.
Usage
## S3 method for class 'rxDll'
print(x, ...)
Value
original object
Author(s)
Matthew L.Fidler
Print Values
Description
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.
Usage
## S3 method for class 'rxModelVars'
print(x, ...)
Arguments
x |
an object used to select a method. |
... |
further arguments passed to or from other methods. |
Details
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.
Value
This returns invisibly the model variables object
References
Chambers, J. M. and Hastie, T. J. (1992) Statistical Models in S. Wadsworth & Brooks/Cole.
See Also
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.
Examples
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 >
Print information about the rxode2 object.
Description
This prints the model name and its status for being able to be solved
Usage
## S3 method for class 'rxode2'
print(x, ...)
Arguments
x |
An rxode2 object |
... |
Ignored parameters |
Value
original object
Author(s)
Matthew L.Fidler
probit and inverse probit functions
Description
probit and inverse probit functions
Usage
probit(x, low = 0, high = 1)
probitInv(x, low = 0, high = 1)
Arguments
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 |
Value
values from probit, probitInv and probitNormInfo
Examples
probit(0.25)
probitInv(-0.674)
probitNormInfo(probit(0.25), sd = 0.1)
probitNormInfo(probit(1, 0, 10), sd = 1, low = 0, high = 10)
One correlation sample from the LKJ distribution
Description
One correlation sample from the LKJ distribution
Usage
rLKJ1(d, eta = 1, cholesky = FALSE)
Arguments
d |
The dimension of the correlation matrix |
eta |
The scaling parameter of the LKJ distribution. Must be > 1. Also related to the degrees of freedom nu. eta = (nu-1)/2. |
cholesky |
boolean; If |
Value
A correlation sample from the LKJ distribution
Author(s)
Matthew Fidler (translated to RcppArmadillo) and Emma Schwager
Objects exported from other packages
Description
These objects are imported from other packages. Follow the links below to see their documentation.
- ggplot2
aes
,expand_limits
,facet_wrap
,geom_line
,ggplot
,label_both
,label_context
,label_context
,label_value
,label_wrap_gen
,scale_type
,scale_x_continuous
,scale_x_date
,scale_x_discrete
,scale_y_continuous
,scale_y_date
,scale_y_discrete
,waiver
,xlab
,ylab
- lotri
- magrittr
Value
Inherited from parent routine
Scaled Inverse Chi Squared distribution
Description
Scaled Inverse Chi Squared distribution
Usage
rinvchisq(n = 1L, nu = 1, scale = 1)
Arguments
n |
Number of random samples |
nu |
degrees of freedom of inverse chi square |
scale |
Scale of inverse chi squared distribution (default is 1). |
Value
a vector of inverse chi squared deviates.
Examples
rinvchisq(3, 4, 1) ## Scale = 1, degrees of freedom = 4
rinvchisq(2, 4, 2) ## Scale = 2, degrees of freedom = 4
Allow unloading of dlls
Description
Allow unloading of dlls
Usage
rxAllowUnload(allow)
Arguments
allow |
boolean indicating if garbage collection will unload of rxode2 dlls. |
Value
Boolean allow; called for side effects
Author(s)
Matthew Fidler
Examples
# 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
Description
Append two rxui models together
Usage
rxAppendModel(..., common = TRUE)
Arguments
... |
models to append together |
common |
boolean that determines if you need a common value to bind |
Value
New model with both models appended together
Author(s)
Matthew L. Fidler
Examples
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
Description
Assign Control Variable
Usage
rxAssignControlValue(ui, option, value)
Arguments
ui |
rxode2 ui function |
option |
Option name in the control to modify |
value |
Value of control to modify |
Value
Nothing; called for the side effects
Author(s)
Matthew L. Fidler
Assign pointer based on model variables
Description
Assign pointer based on model variables
Usage
rxAssignPtr(object = NULL)
Arguments
object |
rxode2 family of objects |
Value
nothing, called for side effects
Creates a logical matrix for block matrixes.
Description
Creates a logical matrix for block matrixes.
Usage
rxBlockZeros(mat, i)
Arguments
mat |
Matrix |
i |
Row/column where block matrix should be setup. |
Value
A logical matrix returning where the elements should be zero.
Return the C file associated with the rxode2 object
Description
This will return C code for generating the rxode2 DLL.
Usage
rxC(obj)
Arguments
obj |
A rxode2 family of objects or a character string of the model specification or location of a file with a model specification. |
Value
a path of the library
Author(s)
Matthew L.Fidler
Use cat when rxode2.verbose is TRUE
Description
Use cat when rxode2.verbose is TRUE
Usage
rxCat(a, ...)
Arguments
... |
Parameters sent to cat |
Value
nothing
Author(s)
Matthew L. Fidler
Bind the study parameters and individual parameters
Description
Bind the study parameters and individual parameters
Usage
rxCbindStudyIndividual(studyParameters, individualParameters)
Arguments
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 |
Value
Data frame that can be used in rxode2 simulations
Author(s)
Matthew Fidler
Examples
# 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)
rxChain Chain or add item to solved system of equations
Description
Add item to solved system of equations
Usage
rxChain(obj1, obj2)
## S3 method for class 'solveRxDll'
obj1 + obj2
Arguments
obj1 |
Solved object. |
obj2 |
New object to be added/piped/chained to solved object. |
Value
When newObject
is an event table, return a new
solved object with the new event table.
Author(s)
Matthew L. Fidler
Second command in chaining commands
Description
This is s3 method is called internally with +
and \%>\%
operators.
Usage
rxChain2(obj, solvedObject)
## Default S3 method:
rxChain2(obj, solvedObject)
## S3 method for class 'EventTable'
rxChain2(obj, solvedObject)
Arguments
obj |
the object being added/chained/piped to the solved object |
solvedObject |
the solved object |
Value
chained operation
Author(s)
Matthew L.Fidler
Cleanup anonymous DLLs by unloading them
Description
This cleans up any rxode2 loaded DLLs
Usage
rxClean(wd)
Arguments
wd |
What directory should be cleaned; (DEPRECIATED), this no longer does anything. This unloads all rxode2 anonymous dlls. |
Value
TRUE if successful
Author(s)
Matthew L. Fidler
Combine Error Lines and create rxode2 expression
Description
Combine Error Lines and create rxode2 expression
Usage
rxCombineErrorLines(
uiModel,
errLines = NULL,
prefixLines = NULL,
paramsLine = NULL,
modelVars = FALSE,
cmtLines = TRUE,
dvidLine = TRUE,
lstExpr = NULL,
useIf = TRUE,
interpLines = NULL,
levelLines = NULL
)
Arguments
uiModel |
UI model |
errLines |
Error lines; If missing, get the error lines from
|
prefixLines |
Prefix lines, after param statement |
paramsLine |
Params line, if not present. |
modelVars |
Return model vars instead of rxode2 statement |
cmtLines |
Include trailing |
dvidLine |
Include trailing |
lstExpr |
A list of expressions for model, or NULL. When NULL
defaults to the model expressions accessible by
|
useIf |
Use an |
interpLines |
Interpolation lines, if not present |
levelLines |
Levels lines for assigned strings. If not present, use the interpolation lines from the current model. |
Details
This is exported to allow other functions to mangle the error lines to make other types of estimation methods (if needed)
Value
quoted expression that can be evaluated to compiled rxode2 model
Author(s)
Matthew L. Fidler
Examples
one.cmt <- function() {
ini({
## You may label each parameter with a comment
tka <- 0.45 # Log Ka
tcl <- log(c(0, 2.7, 100)) # Log Cl
## This works with interactive models
## You may also label the preceding line with label("label text")
tv <- 3.45; label("log V")
## the label("Label name") works with all models
eta.ka ~ 0.6
eta.cl ~ 0.3
eta.v ~ 0.1
add.sd <- 0.7
})
model({
ka <- exp(tka + eta.ka)
cl <- exp(tcl + eta.cl)
v <- exp(tv + eta.v)
linCmt() ~ add(add.sd)
})
}
f <- rxode2(one.cmt)
# You can get the simulation model easily by
rxCombineErrorLines(f)
# You can then get the compiled model by simply evaluting the model:
r <- eval(rxCombineErrorLines(f))
# This also works with multile endpoint models:
pk.turnover.emax <- function() {
ini({
tktr <- log(1)
tka <- log(1)
tcl <- log(0.1)
tv <- log(10)
##
eta.ktr ~ 1
eta.ka ~ 1
eta.cl ~ 2
eta.v ~ 1
prop.err <- 0.1
pkadd.err <- 0.1
##
temax <- logit(0.8)
tec50 <- log(0.5)
tkout <- log(0.05)
te0 <- log(100)
##
eta.emax ~ .5
eta.ec50 ~ .5
eta.kout ~ .5
eta.e0 ~ .5
##
pdadd.err <- 10
})
model({
ktr <- exp(tktr + eta.ktr)
ka <- exp(tka + eta.ka)
cl <- exp(tcl + eta.cl)
v <- exp(tv + eta.v)
##
emax=expit(temax+eta.emax)
ec50 = exp(tec50 + eta.ec50)
kout = exp(tkout + eta.kout)
e0 = exp(te0 + eta.e0)
##
DCP = center/v
PD=1-emax*DCP/(ec50+DCP)
##
effect(0) = e0
kin = e0*kout
##
d/dt(depot) = -ktr * depot
d/dt(gut) = ktr * depot -ka * gut
d/dt(center) = ka * gut - cl / v * center
d/dt(effect) = kin*PD -kout*effect
##
cp = center / v
cp ~ prop(prop.err) + add(pkadd.err)
effect ~ add(pdadd.err)
})
}
f <- rxode2(pk.turnover.emax)
rxCombineErrorLines(f)
# Note that in the parsed form, you can also get the compiled rxode2
# model with $simulationModel
f$simulationModel
Compile a model if needed
Description
This is the compilation workhorse creating the rxode2 model DLL files.
Usage
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, ...)
Arguments
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 |
Value
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.
Author(s)
Matthew L.Fidler
See Also
Current Condition for rxode2 object
Description
Current Condition for rxode2 object
Usage
rxCondition(obj, condition = NULL)
Arguments
obj |
rxode2 object |
condition |
If specified and is one of the conditions in the
rxode2 object (as determined by |
Value
Current condition for rxode2 object
Author(s)
Matthew L. Fidler
This updates the tolerances based on the sensitivity equations
Description
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)
Usage
rxControlUpdateSens(rxControl, sensCmt = NULL, ncmt = NULL)
Arguments
rxControl |
Input list or rxControl type of list |
sensCmt |
Number of sensitivity compartments |
ncmt |
Number of compartments |
Value
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).
Author(s)
Matthew L. Fidler
Examples
tmp <- rxControl()
tmp2 <- rxControlUpdateSens(tmp, 3, 6)
tmp2$atol
tmp2$rtol
tmp2$ssAtol
tmp2$ssRtol
This will create the cache directory for rxode2 to save between sessions
Description
When run, if the R_user_dir
for rxode2's cache isn't present,
create the cache
Usage
rxCreateCache()
Value
nothing
Author(s)
Matthew Fidler
Add to rxode2's derivative tables
Description
Add to rxode2's derivative tables
Usage
rxD(name, derivatives)
Arguments
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. |
Value
nothing
Author(s)
Matthew Fidler
Examples
## 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)
}
))
Delete the DLL for the model
Description
This function deletes the DLL, but doesn't delete the model information in the object.
Usage
rxDelete(obj)
Arguments
obj |
rxode2 family of objects |
Value
A boolean stating if the operation was successful.
Author(s)
Matthew L.Fidler
Demote the error type
Description
Demote the error type
Usage
rxDemoteAddErr(errType)
Arguments
errType |
Error type factor |
Value
Demoted Error Type
Author(s)
Matthew Fidler
Examples
rxErrTypeCombine("add") %>%
rxErrTypeCombine("prop")
# This removes the internal additive error
rxErrTypeCombine("add") %>%
rxErrTypeCombine("prop") %>%
rxDemoteAddErr()
# This is used for logitNorm(NA), the additive portion is stripped
Calculate derived parameters for the 1-, 2-, and 3- compartment linear models.
Description
This calculates the derived parameters based on what is provided in a data frame or arguments
Usage
rxDerived(..., verbose = FALSE, digits = 0)
Arguments
... |
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. |
Value
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
:t_{1/2,\alpha}
; (1-, 2-, and 3-compartment models) -
t12beta
:t_{1/2,\beta}
; (2- and 3-compartment models) -
t12gamma
:t_{1/2,\gamma}
; (3-compartment model) -
alpha
:\alpha
; (1-, 2-, and 3-compartment models) -
beta
:\beta
; (2- and 3-compartment models) -
gamma
:\beta
; (3-compartment model) -
A
: trueA
; (1-, 2-, and 3-compartment models) -
B
: trueB
; (2- and 3-compartment models) -
C
: trueC
; (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)
Author(s)
Matthew Fidler and documentation from Justin Wilkins, justin.wilkins@occams.com
References
Shafer S. L. CONVERT.XLS
Rowland M, Tozer TN. Clinical Pharmacokinetics and Pharmacodynamics: Concepts and Applications (4th). Clipping Williams & Wilkins, Philadelphia, 2010.
Examples
## 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)
Jacobian and parameter derivatives
Description
Return Jacobain and parameter derivatives
Usage
rxDfdy(obj)
Arguments
obj |
rxode2 family of objects |
Value
A list of the jacobian parameters defined in this rxode2 object.
Author(s)
Matthew L. Fidler
See Also
Other Query model information:
rxInits()
,
rxLhs()
,
rxModelVars()
,
rxParams()
,
rxState()
Return the DLL associated with the rxode2 object
Description
This will return the dynamic load library or shared object used to run the C code for rxode2.
Usage
rxDll(obj)
Arguments
obj |
A rxode2 family of objects or a character string of the model specification or location of a file with a model specification. |
Value
a path of the library
Author(s)
Matthew L.Fidler
Load rxode2 object
Description
Load rxode2 object
Usage
rxDynLoad(obj)
rxLoad(obj)
Arguments
obj |
A rxode2 family of objects |
Value
Boolean returning if the rxode2 library is loaded.
Author(s)
Matthew L.Fidler
Unload rxode2 object
Description
Unload rxode2 object
Usage
rxDynUnload(obj)
rxUnload(obj)
Arguments
obj |
A rxode2 family of objects |
Value
Boolean returning if the rxode2 library is loaded.
Author(s)
Matthew L.Fidler
Combine transformations and error structures
Description
Combine error information to figure out what transformation is being applied for the current endpoint
Usage
rxErrTypeCombine(oldErrType, newErrType)
Arguments
oldErrType |
This is the old transformation, by default is
zero representing no prior transformation. This parameter is
first to allow piping. When the parameter |
newErrType |
This is the new distribution that is being
"added" to the current transformation. These assumes the inputs
are in the preferred distribution name, as determined by
|
Value
The new transformation as a factor
Author(s)
Matthew Fidler
Examples
rxErrTypeCombine("probitNorm")
rxErrTypeCombine("probitNorm") %>%
rxErrTypeCombine("boxCox")
Dispatch solve to 'rxode2' solve
Description
Dispatch solve to 'rxode2' solve
Usage
rxEtDispatchSolve(x, ...)
## Default S3 method:
rxEtDispatchSolve(x, ...)
Arguments
x |
rxode2 solve dispatch object |
... |
other arguments |
Value
if 'rxode2' is loaded, a solved object, otherwise an error
Author(s)
Matthew L. Fidler
EVID formatting for tibble and other places.
Description
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.
Usage
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 replacement method for class 'rxEvid'
units(x) <- value
## 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, ...)
Arguments
x |
Item to be converted to a rxode2 EVID specification. |
... |
Other parameters |
value |
It will be an error to set units for evid |
Value
rxEvid specification
Examples
rxEvid(1:7)
Expand d(f)/d(eta)
Description
Expand d(f)/d(eta)
Usage
rxExpandFEta_(state, neta, pred, isTheta = FALSE)
Arguments
state |
is the state to expand |
neta |
is the number of etas |
pred |
type of prediction |
isTheta |
logical, is the expansion actually for thetas instead of etas |
Value
String of symengine expressions to evaluate to calculate df/deta
Faster expand.grid
Description
Only support x and y as characters right now
Usage
rxExpandGrid(x, y, type = 0L)
Arguments
x |
first element (must be character) |
y |
second element (must be character) |
type |
Internal type=0L is traditional expand grid and type=1L is Jacobian expand grid (adds symbols) |
Value
Expand grid
Author(s)
Matthew Fidler
Examples
##
rxExpandGrid(letters, letters)
## Another fast method; See
## https://stackoverflow.com/questions/10405637/use-outer-instead-of-expand-grid
expand.grid.jc <- function(seq1, seq2) {
cbind(
Var1 = rep.int(seq1, length(seq2)),
Var2 = rep.int(seq2, rep.int(length(seq1), length(seq2)))
)
}
microbenchmark::microbenchmark(rxExpandGrid(letters, letters), expand.grid.jc(letters, letters))
Expand grid internal function
Description
Expand grid internal function
Usage
rxExpandGrid_(c1, c2, type)
Arguments
c1 |
character vector of items to be expanded |
c2 |
second character vector of items to be expanded |
type |
0 for a typical data frame, 1 for symengine sensitivity expansion |
Value
data frame (when type = 0) or symengine string (when type=1)
Expand if/else clauses into multiple different types of lines.
Description
Expand if/else clauses into multiple different types of lines.
Usage
rxExpandIfElse(model, removeInis = TRUE, removePrint = TRUE)
Arguments
model |
Model can be a character, or a rxode2 model. It needs
to have normalized syntax, that is |
removeInis |
A boolean indicating if parameter initializations should be removed from the model. |
removePrint |
A boolean indicating if printing statements should be removed from the model. |
Value
A named character vector. The names of the vector are the logical conditions, the values are the lines that satisfy the logical conditions.
Author(s)
Matthew L. Fidler
Expand second order sensitivity
Description
Expand second order sensitivity
Usage
rxExpandSens2_(state, s1, s2)
Arguments
state |
is the state to expand |
s1 |
is the variables to calculate sensitivity |
s2 |
is the variables to calculate second order sensitivity |
Value
string for symengine second order sensitivity
Expand sensitivity
Description
Expand sensitivity
Usage
rxExpandSens_(state, calcSens)
Arguments
state |
is the state to expand |
calcSens |
is the variables to calculate sensitivity |
Value
symengine string for expanded sensitivity
Apply the fixed population estimated parameters
Description
Apply the fixed population estimated parameters
Usage
rxFixPop(ui, returnNull = FALSE)
Arguments
ui |
rxode2 ui function |
returnNull |
boolean for if unchanged values should return the
original ui ( |
Value
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.
Author(s)
Matthew L. Fidler
Examples
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)
Literally fix residual parameters
Description
Literally fix residual parameters
Usage
rxFixRes(ui, returnNull = FALSE)
Arguments
ui |
rxode2 ui function |
returnNull |
boolean for if unchanged values should return the
original ui ( |
Value
model with residual parameters literally fixed in the model
Author(s)
Matthew L. Fidler
Examples
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 <- 0.75 #allometric exponent cl
ALLV <- 1.00 #allometric exponent v
prop.err <- fix(0.15) #proportional error (SD/mean)
add.err <- fix(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 <- rxFixRes(One.comp.transit.allo)
Clear memoise cache for rxode2
Description
Clear memoise cache for rxode2
Usage
rxForget()
Value
nothing; called for side effects
Author(s)
Matthew L. Fidler
Add/Create C functions for use in rxode2
Description
Add/Create C functions for use in rxode2
Usage
rxFun(name, args, cCode)
rxRmFun(name)
Arguments
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 |
Examples
# 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")
Add user function to rxode2
Description
This adds a user function to rxode2 that can be called. If needed,
these functions can be differentiated by numerical differences or
by adding the derivatives to rxode2's internal derivative table
with rxode2's rxD
function
Usage
rxFunParse(name, args, cCode)
rxRmFunParse(name)
Arguments
name |
This gives the name of the user function |
args |
This gives the arguments of the user function |
cCode |
This is the C-code for the new function |
Value
nothing
Author(s)
Matthew L. Fidler
rxGetControl option from ui
Description
rxGetControl option from ui
Usage
rxGetControl(ui, option, default)
Arguments
ui |
rxode2 ui object |
option |
Option to get |
default |
Default value |
Value
Option (if present) or default value
Author(s)
Matthew L. Fidler
This is a S3 method for getting the distribution lines for a rxode2 simulation
Description
This is a S3 method for getting the distribution lines for a rxode2 simulation
Usage
rxGetDistributionSimulationLines(line)
## S3 method for class 'norm'
rxGetDistributionSimulationLines(line)
## S3 method for class 'dnorm'
rxGetDistributionSimulationLines(line)
## S3 method for class 't'
rxGetDistributionSimulationLines(line)
## S3 method for class 'cauchy'
rxGetDistributionSimulationLines(line)
## S3 method for class 'ordinal'
rxGetDistributionSimulationLines(line)
## Default S3 method:
rxGetDistributionSimulationLines(line)
## S3 method for class 'rxUi'
rxGetDistributionSimulationLines(line)
Arguments
line |
Parsed rxode2 model environment |
Value
Lines for the simulation of ipred
and dv
. This is based
on the idea that the focei parameters are defined
Author(s)
Matthew Fidler
Get the linear compartment model true function
Description
Get the linear compartment model true function
Usage
rxGetLin(model, linCmtSens = c("linCmtA", "linCmtB"), verbose = FALSE)
Arguments
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 |
Value
model with linCmt() replaced with linCmtA()
Author(s)
Matthew Fidler
Get model properties without compiling it.
Description
Get model properties without compiling it.
Usage
rxGetModel(
model,
calcSens = NULL,
calcJac = NULL,
collapseModel = NULL,
indLin = FALSE
)
Arguments
model |
rxode2 specification |
calcSens |
boolean indicating if rxode2 will calculate the sensitivities according to the specified ODEs. |
calcJac |
boolean indicating if rxode2 will calculate the Jacobain according to the specified ODEs. |
collapseModel |
boolean indicating if rxode2 will remove all LHS variables when calculating sensitivities. |
indLin |
Calculate inductive linearization matrices and compile with inductive linearization support. |
Value
rxode2 trans list
Author(s)
Matthew L. Fidler
Get the rxode2 seed
Description
Get the rxode2 seed
Usage
rxGetSeed()
Value
rxode2 seed state or -1 when the seed isn't set
See Also
rxSetSeed, rxWithSeed, rxWithPreserveSeed
Examples
# 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()
Get rxode2 model from object
Description
Get rxode2 model from object
Usage
rxGetrxode2(obj)
Arguments
obj |
rxode2 family of objects |
Value
rxode2 model
Format rxSolve and related objects as html.
Description
Format rxSolve and related objects as html.
Usage
rxHtml(x, ...)
## S3 method for class 'rxSolve'
rxHtml(x, ...)
Arguments
x |
rxode2 object |
... |
Extra arguments sent to kable |
Value
html code for rxSolve object
Author(s)
Matthew L. Fidler
Set the preferred factoring by state
Description
Set the preferred factoring by state
Usage
rxIndLinState(preferred = NULL)
Arguments
preferred |
A list of each state's preferred factorization |
Value
Nothing
Author(s)
Matthew Fidler
This sets the inductive linearization strategy for matrix building
Description
When there is more than one state in a ODE that cannot be separated this specifies how it is incorporated into the matrix exponential.
Usage
rxIndLinStrategy(strategy = c("curState", "split"))
Arguments
strategy |
The strategy for inductive linearization matrix building
|
Value
Nothing
Author(s)
Matthew L. Fidler
Initial Values and State values for a rxode2 object
Description
Returns the initial values of the rxDll object
Usage
rxInits(
obj,
vec = NULL,
req = NULL,
defaultValue = 0,
noerror = FALSE,
noini = FALSE,
rxLines = FALSE
)
rxInit(
obj,
vec = NULL,
req = NULL,
defaultValue = 0,
noerror = FALSE,
noini = FALSE,
rxLines = FALSE
)
Arguments
obj |
rxDll, rxode2, or named vector representing default initial arguments |
vec |
If supplied, named vector for the model. |
req |
Required names, and the required order for the ODE solver |
defaultValue |
a number or NA representing the default value for
parameters missing in |
noerror |
is a boolean specifying if an error should be thrown
for missing parameter values when |
Value
Initial values of the rxDll object
Author(s)
Matthew L.Fidler
See Also
Other Query model information:
rxDfdy()
,
rxLhs()
,
rxModelVars()
,
rxParams()
,
rxState()
Convert a positive base
Description
Convert a positive base
Usage
rxIntToBase(x, base = 36L)
Arguments
x |
integer to convert |
base |
can be 2 to 36 |
Value
a sequence of letters and representing the number(s) input
Author(s)
Matthew L. Fidler
Examples
rxIntToBase(1:100)
Convert a positive integer to a letter series
Description
Convert a positive integer to a letter series
Usage
rxIntToLetter(x, base = 26L)
Arguments
x |
integer to convert |
base |
can be 2 to 26 |
Value
a sequence of letters representing the number(s) input
Author(s)
Matthew L. Fidler
Examples
rxIntToLetter(1:100)
Invert matrix using RcppArmadillo.
Description
Invert matrix using RcppArmadillo.
Usage
rxInv(matrix)
Arguments
matrix |
matrix to be inverted. |
Value
inverse or pseudo inverse of matrix.
Check the type of an object using Rcpp
Description
Check the type of an object using Rcpp
Usage
rxIs(obj, cls)
Arguments
obj |
Object to check |
cls |
Type of class. Only s3 classes for lists/environments
and primitive classes are checked. For matrix types they are
distinguished as |
Value
A boolean indicating if the object is a member of the class.
Author(s)
Matthew L. Fidler
Checks if the rxode2 object was built with the current build
Description
Checks if the rxode2 object was built with the current build
Usage
rxIsCurrent(obj)
Arguments
obj |
rxode2 family of objects |
Value
boolean indicating if this was built with current rxode2
Determine if the DLL associated with the rxode2 object is loaded
Description
Determine if the DLL associated with the rxode2 object is loaded
Usage
rxIsLoaded(obj)
rxDllLoaded(obj)
Arguments
obj |
A rxode2 family of objects |
Value
Boolean returning if the rxode2 library is loaded.
Author(s)
Matthew L.Fidler
Left handed Variables
Description
This returns the model calculated variables
Usage
rxLhs(obj)
Arguments
obj |
rxode2 family of objects |
Value
a character vector listing the calculated parameters
Author(s)
Matthew L.Fidler
See Also
Other Query model information:
rxDfdy()
,
rxInits()
,
rxModelVars()
,
rxParams()
,
rxState()
Lock/unlocking of rxode2 dll file
Description
Lock/unlocking of rxode2 dll file
Usage
rxLock(obj)
rxUnlock(obj)
Arguments
obj |
A rxode2 family of objects |
Value
nothing; called for side effects
Return the md5 of an rxode2 object or file
Description
This md5 is based on the model and possibly the extra c code supplied for the model. In addition the md5 is based on syntax options, compiled rxode2 library md5, and the rxode2 version/repository.
Usage
rxMd5(model, ...)
Arguments
model |
This is the ODE model specification. It can be:
An ODE expression enclosed in (see also the |
... |
ignored arguments |
Value
If this is a rxode2 object, return a named list:
-
file_md5
is the model's file's md5 -
parsed_md5
is the parsed model's file's md5.
Otherwise return the md5 based on the arguments provided
Author(s)
Matthew L.Fidler
All model variables for a rxode2 object
Description
Return all the known model variables for a specified rxode2 object
Usage
rxModelVars(obj)
rxModelVarsS3(obj)
## S3 method for class 'rxUi'
rxModelVarsS3(obj)
## Default S3 method:
rxModelVarsS3(obj)
Arguments
obj |
rxode2 family of objects |
Details
These items are only calculated after compilation; they are built-into the rxode2 compiled DLL.
To allow extension, an s3 hook is added in the function rxModelVarsS3
.
Value
A list of rxode2 model properties including:
-
params
a character vector of names of the model parameters -
lhs
a character vector of the names of the model calculated parameters -
state
a character vector of the compartments in rxode2 object -
trans
a named vector of translated model properties including what type of jacobian is specified, theC
function prefixes, as well as theC
functions names to be called through the compiled model. -
md5
a named vector that gives the digest of the model (file_md5
) and the parsed model (parsed_md5
) -
model
a named vector giving the input model (model
), normalized model (no comments and standard syntax for parsing,normModel
), and interim code that is used to generate the final C fileparseModel
Author(s)
Matthew L. Fidler
See Also
Other Query model information:
rxDfdy()
,
rxInits()
,
rxLhs()
,
rxParams()
,
rxState()
Get the rxModels information
Description
Get the rxModels information
Usage
rxModels_(env = TRUE)
Arguments
env |
boolean that returns the environment where models are stored (TRUE), or the currently assigned rxode2 model variables (FALSE). |
Value
internal rxModels information environment
Get the normalized model
Description
This get the syntax preferred model for processing
Usage
rxNorm(obj, condition = NULL, removeInis, removeJac, removeSens)
Arguments
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. |
Value
Normalized Normal syntax (no comments)
Author(s)
Matthew L. Fidler
Optimize rxode2 for computer evaluation
Description
This optimizes rxode2 code for computer evaluation by only calculating redundant expressions once.
Usage
rxOptExpr(x, msg = "model")
Arguments
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... |
Value
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.
Author(s)
Matthew L. Fidler
Parameters specified by the model
Description
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
Usage
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, ...)
Arguments
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. |
Value
When extracting the parameters from an rxode2 model, a character vector listing the parameters in the model.
Author(s)
Matthew L.Fidler
See Also
Other Query model information:
rxDfdy()
,
rxInits()
,
rxLhs()
,
rxModelVars()
,
rxState()
Prepare Error function for inclusion in rxode2
Description
Prepare Error function for inclusion in rxode2
Usage
rxParseErr(
x,
baseTheta,
ret = "rx_r_",
init = NULL,
addProp = c("combined2", "combined1")
)
Arguments
x |
error function |
baseTheta |
Base theta to start numbering add(.) and prop(.) from. |
ret |
Internal return type. Should not be changed by the user... |
init |
Initialization vector |
Value
rxode2 transformed text
Author(s)
Matthew L. Fidler
Parse PK function for inclusion in rxode2
Description
Parse PK function for inclusion in rxode2
Usage
rxParsePk(x, init = NULL)
Arguments
x |
PK function |
init |
Initialization vector |
Value
rxode2 transformed text.
Author(s)
Matthew L. Fidler
Prepare Pred function for inclusion in rxode2
Description
Prepare Pred function for inclusion in rxode2
Usage
rxParsePred(x, init = NULL, err = NULL, addProp = c("combined2", "combined1"))
Arguments
x |
pred function |
init |
Initialization vector |
Value
rxode2 transformed text.
Author(s)
Matthew L. Fidler
Silence some of rxode2's C/C++ messages
Description
Silence some of rxode2's C/C++ messages
Usage
rxParseSetSilentErr(silent)
Arguments
silent |
can be 0L "noisy" or 1L "silent" |
Value
TRUE; called for side effects
Respect suppress messages
Description
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()
Usage
rxParseSuppressMsg()
Value
Nothing
Author(s)
Matthew Fidler
Examples
# 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
Description
Creates a package from compiled rxode2 models
Usage
rxPkg(
...,
package,
wd = getwd(),
action = c("install", "build", "binary", "create"),
license = c("gpl3", "lgpl", "mit", "agpl3"),
name = "Firstname Lastname",
fields = list()
)
Arguments
... |
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 |
Value
this function returns nothing and is used for its side effects
Author(s)
Matthew Fidler
Simulate a from a Poisson process
Description
Simulate a from a Poisson process
Usage
rxPp(
n,
lambda,
gamma = 1,
prob = NULL,
t0 = 0,
tmax = Inf,
randomOrder = FALSE
)
Arguments
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 |
Value
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.
Author(s)
Matthew Fidler
Examples
## 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))
})
Change distribution name to the preferred distribution name term
Description
This is determined by the internal preferred condition name list
.errIdenticalDists
Usage
rxPreferredDistributionName(dist)
Arguments
dist |
This is the input distribution |
Value
Preferred distribution term
Author(s)
Matthew Fidler
Examples
rxPreferredDistributionName("dt")
rxPreferredDistributionName("add")
# can be vectorized
rxPreferredDistributionName(c("add","dt"))
rxode2 progress bar functions
Description
rxProgress
sets up the progress bar
Usage
rxProgress(num, core = 0L)
rxTick()
rxProgressStop(clear = TRUE)
rxProgressAbort(error = "Aborted calculation")
Arguments
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 |
Details
rxTick
is a progress bar tick
rxProgressStop
stop progress bar
rxProgressAbort
shows an abort if rxProgressStop
wasn't called.
Value
All return NULL invisibly.
Author(s)
Matthew L. Fidler
Examples
f <- function() {
on.exit({
rxProgressAbort()
})
rxProgress(100)
for (i in 1:100) {
rxTick()
Sys.sleep(1 / 100)
}
rxProgressStop()
}
f()
Prune branches (ie if/else) from rxode2
Description
This prunes branches (ie if/else) from rxode2.
Usage
rxPrune(x)
Arguments
x |
rxode2 model that can be accessed by rxNorm |
Value
Pruned rxode2 model text.
Author(s)
Matthew L. Fidler
Creates a rxRateDur object
Description
This is primarily to display information about rate
Usage
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[[...]]
Arguments
x |
rxRateDur data |
... |
Other parameters |
Value
rxRateDur object
Reload rxode2 DLL
Description
Can be useful for debugging
Usage
rxReload()
Value
boolean of if the object is reloaded
Author(s)
Matthew L. Fidler
rxRemoveControl options for UI object
Description
rxRemoveControl options for UI object
Usage
rxRemoveControl(ui)
Arguments
ui |
rxode2 ui object |
Value
Nothing, called for side effects
Author(s)
Matthew L. Fidler
Rename items inside of a rxode2
ui model
Description
rxRename()
changes the names of individual variables, lhs, and ode states using
new_name = old_name
syntax
Usage
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, ...)
Arguments
.data |
rxode2 ui function, named data to be consistent with |
... |
rename items |
envir |
Environment for evaluation |
Details
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
Value
New model with items renamed
Author(s)
Matthew L. Fidler
Examples
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)
Rep R0 for foce
Description
Rep R0 for foce
Usage
rxRepR0_(neta)
Arguments
neta |
ETA to substitute |
Value
Returns a string of R code to substitute the rx_r expression in the symengine environment .s
Require namespace, otherwise throw error.
Description
Require namespace, otherwise throw error.
Usage
rxReq(pkg)
Arguments
pkg |
Package required for function to work. |
Value
Nothing
Author(s)
Matthew L. Fidler
A list and description of rxode2 supported reserved keywords
Description
A list and description of rxode2 supported reserved keywords
Usage
rxReservedKeywords
Format
A data frame with 3 columns and 31 rows
- Reserved Name
Reserved Keyword Name
- Meaning
Reserved Keyword Meaning
- Alias
Keyword Alias
A description of Rode2 supported residual errors
Description
A description of Rode2 supported residual errors
Usage
rxResidualError
Format
A data frame with 6 columns and 181 rows
- Error model
A description of the type of residual error
- Functional Form
For additive and proportional what functional form is used
- Transformation
The type of transformation that is done on the DV and the prediction
- code
Example code for the residual error type
- addProp
The type of add+prop residual error default that would be equivalent
- lhs
what the left handed side of the specification represents, either a response variable, or a compartment specification
Simulate from a (truncated) multivariate normal
Description
This is simulated with the fast, thread-safe threefry simulator and can use multiple cores to generate the random deviates.
Usage
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
)
Arguments
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 |
Value
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.
Author(s)
Matthew Fidler, Zdravko Botev and some from Matteo Fasiolo
References
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;
Examples
## 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
Description
Load a model into a symengine environment
Usage
rxS(x, doConst = TRUE, promoteLinSens = FALSE, envir = parent.frame())
Arguments
x |
rxode2 object |
doConst |
Load constants into the environment as well. |
promoteLinSens |
Promote solved linear compartment systems to sensitivity-based solutions. |
envir |
default is |
Value
rxode2/symengine environment
Author(s)
Matthew Fidler
This seeds the engine based on the number of cores used in random number generation
Description
This seeds the engine based on the number of cores used in random number generation
Usage
rxSeedEng(ncores = 1L)
Arguments
ncores |
is the number of cores to use. |
Value
Nothing, called for side effects
Examples
rxSeedEng()
rxSetControl options for UI object
Description
rxSetControl options for UI object
Usage
rxSetControl(ui, control)
Arguments
ui |
rxode2 ui object |
control |
Default value |
Value
Nothing, called for side effects
Author(s)
Matthew L. Fidler
Assign covariates for piping
Description
Assign covariates for piping
Usage
rxSetCovariateNamesForPiping(covariates = NULL)
Arguments
covariates |
NULL (for no covariates), or the list of covariates. nlmixr uses this function to set covariates if you pipe from a nlmixr fit. |
Value
Nothing, called for side effects
Author(s)
Matthew L. Fidler
Examples
# 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
Description
Set Initial conditions to time zero instead of the first observed/dosed time
Usage
rxSetIni0(ini0 = TRUE)
Arguments
ini0 |
When |
Value
the boolean ini0, though this is called for its side effects
Set the variables for the model piping automatic covarite selection
Description
Set the variables for the model piping automatic covarite selection
Usage
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")
)
Arguments
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 |
Details
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
Value
Nothing, called for side effects
Author(s)
Matthew L. Fidler
Defunct setting of product
Description
Defunct setting of product
Usage
rxSetProd(type = c("long double", "double", "logify"))
Arguments
type |
used to be type of product |
Value
nothing
Set timing for progress bar
Description
Set timing for progress bar
Usage
rxSetProgressBar(seconds = 1)
Arguments
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. |
Value
nothing, used for side effects
Author(s)
Matthew Fidler
Set the parallel seed for rxode2 random number generation
Description
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.
Usage
rxSetSeed(seed)
Arguments
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. |
Details
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.
Value
Nothing, called for its side effects
Author(s)
Matthew Fidler
References
JD Cook. (2016). Random number generator seed mistakes. https://www.johndcook.com/blog/2016/01/29/random-number-generator-seed-mistakes/
See Also
rxGetSeed, rxWithSeed, rxWithPreserveSeed
Examples
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)
Silence some of rxode2's C/C++ messages
Description
Silence some of rxode2's C/C++ messages
Usage
rxSetSilentErr(silent)
Arguments
silent |
can be 0L "noisy" or 1L "silent" |
Value
TRUE; called for side effects
Defunct setting of sum
Description
Defunct setting of sum
Usage
rxSetSum(type = c("pairwise", "fsum", "kahan", "neumaier", "c"))
Arguments
type |
used to be type of product |
Value
nothing
Setup the initial conditions.
Description
Setup the initial conditions.
Usage
rxSetupIni(obj, inits = NULL)
Arguments
obj |
rxode2 object |
inits |
A numeric vector of initial conditions. |
Value
initial conditions that were setup
Author(s)
Matthew L. Fidler
Setup the initial conditions.
Description
Setup the initial conditions.
Usage
rxSetupScale(obj, scale = NULL, extraArgs = NULL)
Arguments
obj |
rxode2 object |
scale |
A numeric vector scales |
extraArgs |
A list of extra args to parse for initial conditions. |
Value
setup scale for changing compartment values
Author(s)
Matthew L. Fidler
Use Shiny to help develop an rxode2 model
Description
Use Shiny to help develop an rxode2 model
Usage
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()
)
Arguments
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 |
Value
Nothing; Starts a shiny server
Author(s)
Zufar Mulyukov and Matthew L. Fidler
Simulate Parameters from a Theta/Omega specification
Description
Simulate Parameters from a Theta/Omega specification
Usage
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))
)
Arguments
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 |
Value
a data frame with the simulated subjects
Author(s)
Matthew L.Fidler
Options, Solving & Simulation of an ODE/solved system
Description
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
.
Usage
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("na", "locf", "nocb"),
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 = 10000L,
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"),
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,
ssSolved = TRUE,
linCmtSensType = c("auto", "endpoint5", "endpoint5G", "forward3", "forward3G", "AD",
"central", "forward", "forwardG", "forwardH", "centralH", "forward3H", "endpointH5",
"forwardG"),
linCmtSensH = 1e-04,
linCmtGillFtol = 0,
linCmtGillK = 20L,
linCmtGillStep = 4,
linCmtGillRtol = sqrt(.Machine$double.eps),
linCmtShiErr = sqrt(.Machine$double.eps),
linCmtShiMax = 20L,
linCmtScale = FALSE,
linCmtHcmt = NULL,
linCmtHmeanI = c("geometric", "arithmetic", "harmonic"),
linCmtHmeanO = c("geometric", "arithmetic", "harmonic"),
linCmtSuspect = 1e-06,
linCmtForwardMax = 2L,
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()
)
Arguments
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
|
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 |
ssSolved |
When |
linCmtSensType |
The type of linear compartment sensitivity/gradients to use. The current options are:
|
linCmtSensH |
The step size for the forward and central
differences when using the option |
linCmtGillFtol |
The gillFtol is the gradient error tolerance that is acceptable before issuing a warning/error about the gradient estimates. |
linCmtGillK |
The total number of possible steps to determine the optimal forward/central difference step size per parameter (by the Gill 1983 method). If 0, no optimal step size is determined. Otherwise this is the optimal step size determined. |
linCmtGillStep |
When looking for the optimal forward difference step size, this is This is the step size to increase the initial estimate by. So each iteration the new step size = (prior step size)*gillStep |
linCmtGillRtol |
The relative tolerance used for Gill 1983 optimal step size determination. |
linCmtShiErr |
Shi difference error |
linCmtShiMax |
The maximum number of steps for the optimization of the forward-difference step size in linear compartment numeric difference. |
linCmtScale |
The scale of the linear compartment model. This
is applied to sensitivity approximation using numeric
differences. When |
linCmtHcmt |
This represents the compartments considered when optimizing the forward difference step size. When a character vector it can be any of the following (multiple allowed):
|
linCmtHmeanI |
This represents the type of sum done for each
time-point of the linear solved systems (as defined by
|
linCmtHmeanO |
This represents the type of sum done for the
overall problem of the linear solved systems (first each time
point mean is calculated with
|
linCmtSuspect |
The tolerance for gradients in linear compartment solutions to re-compute when gradients seem to be zero. |
linCmtForwardMax |
The maximum number of points in a forward difference to take while calculating the gradients. This is an integer from 1 to 3. There is at least 1 extra point taken for gradient calculation, if the gradient is suspect another is taken (if this value is 2), and finally a third is calculated if the gradient is still suspect. |
envir |
is the environment to look for R user functions (defaults to parent environment) |
a |
when using |
b |
when using |
Details
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.
Value
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.
Author(s)
Matthew Fidler, Melissa Hallow and Wenping Wang
References
"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).
See Also
Free the C solving/parsing information.
Description
Take the ODE C system and free it.
Usage
rxSolveFree()
Value
logical indicating if the memory was successfully freed
See if the memory is installed for a solve
Description
See if the memory is installed for a solve
Usage
rxSolveSetup()
Value
boolean saying if the memnory is currently free for rxode2
Author(s)
Matthew L. Fidler
This function splits a function based on + or - terms
Description
It uses the parser and does not disturb terms within other functions. For example:
Usage
rxSplitPlusQ(x, level = 0, mult = FALSE)
Arguments
x |
Quoted R expression for splitting |
level |
Internal level of parsing |
mult |
boolean to split based on * and / expressions instead. By default this is turned off. |
Details
aexp(b+c)+dlog(e-f)-g*f
would return
c("a * exp(b + c)", "d * log(e - f)", "- g * f")
Value
character vector of the split expressions
Author(s)
Matthew L. Fidler
Stack a solved object for things like default ggplot2 plot
Description
Stack a solved object for things like default ggplot2 plot
Usage
rxStack(data, vars = NULL, doSim = TRUE)
Arguments
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
|
Value
Stacked data with value
and trt
, where value is the values
and trt
is the state and lhs
variables.
Author(s)
Matthew Fidler
State variables
Description
This returns the model's compartments or states.
Usage
rxState(obj = NULL, state = NULL)
Arguments
obj |
rxode2 family of objects |
state |
is a string indicating the state or compartment that you would like to lookup. |
Value
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.
Author(s)
Matthew L.Fidler
See Also
Other Query model information:
rxDfdy()
,
rxInits()
,
rxLhs()
,
rxModelVars()
,
rxParams()
Get the ODE states only
Description
Get the ODE states only
Usage
rxStateOde(obj)
Arguments
obj |
rxode2 object |
Value
ODE states only
Author(s)
Matthew L. Fidler
Examples
mod <- rxode2({
Cp <- linCmt(Cl, V, Q2, V2, Q3, V3)
ke0 <- log(2)/(50)
d/dt(Ce) <- (Cp-Ce)*ke0
})
rxStateOde(mod)
rxState(mod)
mod <- rxode2({
Cp <- linCmt(Cl, V, Q2, V2, Q3, V3, ka)
ke0 <- log(2)/(50)
d/dt(Ce) <- (Cp-Ce)*ke0
}, linCmtSens="linCmtB")
rxStateOde(mod)
rxState(mod)
Recast model in terms of sum/prod
Description
Recast model in terms of sum/prod
Usage
rxSumProdModel(model, expand = FALSE, sum = TRUE, prod = TRUE)
Arguments
model |
rxode2 model |
expand |
Boolean indicating if the expression is expanded. |
sum |
Use sum(...) |
prod |
Use prod(...) |
Value
model string with prod(.) and sum(.) for all these operations.
Author(s)
Matthew L. Fidler
Get list of supported functions
Description
Get list of supported functions
Usage
rxSupportedFuns()
Value
list of supported functions in rxode2
Examples
rxSupportedFuns()
Respect suppress messages
Description
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()
Usage
rxSuppressMsg()
Value
Nothing
Author(s)
Matthew Fidler
Examples
# 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
Description
Get Omega^-1 and derivatives
Usage
rxSymInvChol(
invObjOrMatrix,
theta = NULL,
type = "cholOmegaInv",
thetaNumber = 0L
)
Arguments
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 |
Value
Matrix based on parameters or environment with all the
matrixes calculated in variables omega
, omegaInv
, dOmega
,
dOmegaInv
.
Author(s)
Matthew L. Fidler
Creates an object for calculating Omega/Omega^-1 and derivatives
Description
Creates an object for calculating Omega/Omega^-1 and derivatives
Usage
rxSymInvCholCreate(
mat,
diag.xform = c("sqrt", "log", "identity"),
create.env = TRUE,
envir = parent.frame()
)
Arguments
mat |
Initial Omega matrix |
diag.xform |
transformation to diagonal elements of OMEGA. or |
create.env |
– Create an environment to calculate the inverses. (By default TRUE) |
envir |
– Environment to evaluate function, bu default it is the parent frame. |
Value
A rxSymInv object OR a rxSymInv environment
Author(s)
Matthew L. Fidler
Return the dimension of the built-in derivatives/inverses
Description
Return the dimension of the built-in derivatives/inverses
Usage
rxSymInvCholN()
Value
dimension of built-in derivatives/inverses
Sync options with rxode2 variables
Description
Accessing rxode2 options via getOption slows down solving. This allows the options to be synced with variables.
Usage
rxSyncOptions(setDefaults = c("none", "permissive", "strict"))
Arguments
setDefaults |
This will setup rxode2's default solving options with the following options:
|
Value
nothing; called for side effects
Author(s)
Matthew L. Fidler
A list and description of Rode supported syntax functions
Description
A list and description of Rode supported syntax functions
Usage
rxSyntaxFunctions
Format
A data frame with 3 columns and 102 rows
- Function
Reserved function Name
- Description
Description of function
- Aliases
Function Aliases
Get the rxode2 temporary directory
Description
Get the rxode2 temporary directory
Usage
rxTempDir()
Value
rxode2 temporary directory.
rxTheme is the ggplot2 theme for rxode2 plots
Description
rxTheme is the ggplot2 theme for rxode2 plots
Usage
rxTheme(
base_size = 11,
base_family = "",
base_line_size = base_size/22,
base_rect_size = base_size/22,
grid = TRUE
)
Arguments
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 ( |
Value
ggplot2 theme used in rxode2
See Also
Other rxode2 plotting:
plot.rxSolve()
rxode2 to symengine environment
Description
rxode2 to symengine environment
Usage
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)
Arguments
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 |
Value
An rxode2 symengine environment
Author(s)
Matthew L. Fidler
Translate the model to C code if needed
Description
This function translates the model to C code, if needed
Usage
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,
...
)
Arguments
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. |
Value
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.
Author(s)
Matthew L.Fidler
See Also
This function is called when processing rxode2 user functions from the models
Description
This function is called when processing rxode2 user functions from the models
Usage
rxUdfUi(fun)
## S3 method for class 'rinbinom'
rxUdfUi(fun)
Arguments
fun |
this is the function that needs to be parsed and changed. This is a R language expression |
Value
This needs to return a list with the following elements:
-
iniDf
– the modified initial estimate data.frame -
before
– any model code that needs to be added before the current line -
after
– any model code that needs to be added after the current line -
replace
– replacement code for this user function
Author(s)
Matthew L. Fidler
Return the control that is being processed or setup control for processing
Description
Return the control that is being processed or setup control for processing
Usage
rxUdfUiControl(value)
Arguments
value |
when specified, this assigns the control to be
processed, or resets it by assigning it to be |
Value
value of the data.frame
being processed or NULL
.
Author(s)
Matthew L. Fidler
See Also
Other User functions:
linMod()
,
rxUdfUiData()
,
rxUdfUiEst()
,
rxUdfUiIniLhs()
,
rxUdfUiMv()
,
rxUdfUiNum()
,
rxUdfUiParsing()
Examples
rxUdfUiControl()
Return the data.frame that is being processed or setup data.frame for processing
Description
Return the data.frame that is being processed or setup data.frame for processing
Usage
rxUdfUiData(value)
Arguments
value |
when specified, this assigns the data.frame to be processed, or resets it by assigning it to be |
Value
value of the data.frame
being processed or NULL
.
Author(s)
Matthew L. Fidler
See Also
Other User functions:
linMod()
,
rxUdfUiControl()
,
rxUdfUiEst()
,
rxUdfUiIniLhs()
,
rxUdfUiMv()
,
rxUdfUiNum()
,
rxUdfUiParsing()
Examples
rxUdfUiData()
Return the current estimation method for the UI processing
Description
Return the current estimation method for the UI processing
Usage
rxUdfUiEst(value)
Arguments
value |
when specified, this assigns the character value of the estimation method or NULL if there is nothing being estimated |
Value
value of the estimation method being processed or NULL
Author(s)
Matthew L. Fidler
See Also
Other User functions:
linMod()
,
rxUdfUiControl()
,
rxUdfUiData()
,
rxUdfUiIniLhs()
,
rxUdfUiMv()
,
rxUdfUiNum()
,
rxUdfUiParsing()
Examples
rxUdfUiEst()
Get the rxode2 iniDf of the current UI being processed (or return NULL)
Description
Get the rxode2 iniDf of the current UI being processed (or return NULL)
Usage
rxUdfUiIniDf()
Value
Initial data.frame
being processed or NULL
for nothing.
Author(s)
Matthew L. Fidler
Examples
rxUdfUiIniDf()
Return the lhs parsed language expression
Description
Return the lhs parsed language expression
Usage
rxUdfUiIniLhs()
Value
lhs language expression or NULL
Author(s)
Matthew L. Fidler
See Also
Other User functions:
linMod()
,
rxUdfUiControl()
,
rxUdfUiData()
,
rxUdfUiEst()
,
rxUdfUiMv()
,
rxUdfUiNum()
,
rxUdfUiParsing()
Examples
rxUdfUiIniLhs()
Return the model variables that is being processed or setup model variables for processing
Description
Return the model variables that is being processed or setup model variables for processing
Usage
rxUdfUiMv(value)
Arguments
value |
when specified, this assigns the model variables to be
processed, or resets it by assigning it to be |
Value
value of the modelVariables
being processed or NULL
.
Author(s)
Matthew L. Fidler
See Also
Other User functions:
linMod()
,
rxUdfUiControl()
,
rxUdfUiData()
,
rxUdfUiEst()
,
rxUdfUiIniLhs()
,
rxUdfUiNum()
,
rxUdfUiParsing()
Examples
rxUdfUiMv()
This gives the current number in the ui of the particular function being called.
Description
If this is called outside of function parsing or the input is unexpected this returns 1L. This is useful when writing replacement UI functions
Usage
rxUdfUiNum()
Value
integer greater than 1L
Author(s)
Matthew L. Fidler
See Also
Other User functions:
linMod()
,
rxUdfUiControl()
,
rxUdfUiData()
,
rxUdfUiEst()
,
rxUdfUiIniLhs()
,
rxUdfUiMv()
,
rxUdfUiParsing()
Examples
rxUdfUiNum()
Returns if the current ui function is being parsed
Description
Returns if the current ui function is being parsed
Usage
rxUdfUiParsing()
Value
logical if the current ui function is being parsed
Author(s)
Matthew L. Fidler
See Also
Other User functions:
linMod()
,
rxUdfUiControl()
,
rxUdfUiData()
,
rxUdfUiEst()
,
rxUdfUiIniLhs()
,
rxUdfUiMv()
,
rxUdfUiNum()
Examples
rxUdfUiParsing()
Reset the rxode2 ui environment variables
Description
Reset the rxode2 ui environment variables
Usage
rxUdfUiReset()
Value
NULL silently
Author(s)
Matthew L. Fidler
Examples
rxUdfUiReset()
Compress/Decompress rxode2
ui
Description
Compress/Decompress rxode2
ui
Usage
rxUiDecompress(ui)
rxUiCompress(ui)
Arguments
ui |
rxode2 ui object |
Value
A compressed or decompressed rxui object
Author(s)
Matthew L. Fidler
Examples
one.cmt <- function() {
ini({
## You may label each parameter with a comment
tka <- 0.45 # Log Ka
tcl <- log(c(0, 2.7, 100)) # Log Cl
## This works with interactive models
## You may also label the preceding line with label("label text")
tv <- 3.45; label("log V")
## the label("Label name") works with all models
eta.ka ~ 0.6
eta.cl ~ 0.3
eta.v ~ 0.1
add.sd <- 0.7
})
model({
ka <- exp(tka + eta.ka)
cl <- exp(tcl + eta.cl)
v <- exp(tv + eta.v)
linCmt() ~ add(add.sd) | 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))
This is a generic function for deparsing certain objects when printing out a rxode2 object. Currently it is used for any meta-information
Description
This is a generic function for deparsing certain objects when printing out a rxode2 object. Currently it is used for any meta-information
rxUiDeparse.rxControl(rxControl(covsInterpolation="linear", method="dop853", naInterpolation="nocb", keepInterpolation="nocb", sigmaXform="variance", omegaXform="variance", returnType="data.frame", sumType="fsum", prodType="logify"), "ctl")
Usage
rxUiDeparse(object, var)
## S3 method for class 'lotriFix'
rxUiDeparse(object, var)
## Default S3 method:
rxUiDeparse(object, var)
## S3 method for class 'rxControl'
rxUiDeparse(object, var)
Arguments
object |
object to be deparsed |
var |
variable name to be assigned |
Value
parsed R expression that can be used for printing and
as.function()
calls.
Author(s)
Matthew L. Fidler
Examples
mat <- matrix(c(1, 0.1, 0.1, 1), 2, 2, dimnames=list(c("a", "b"), c("a", "b")))
rxUiDeparse(matrix(c(1, 0.1, 0.1, 1), 2, 2, dimnames=list(c("a", "b"), c("a", "b"))), "x")
S3 for getting information from UI model
Description
S3 for getting information from UI model
Usage
## 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 'funPartsDigest'
rxUiGet(x, ...)
## S3 method for class 'md5'
rxUiGet(x, ...)
## S3 method for class 'sha1'
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, ...)
Arguments
x |
list of (UIenvironment, exact). UI environment is the
parsed function for rxode2. |
... |
Other arguments |
Value
value that was requested from the UI object
Author(s)
Matthew Fidler
Unloads all rxode2 compiled DLLs
Description
Unloads all rxode2 compiled DLLs
Usage
rxUnloadAll()
Value
List of rxode2 dlls still loaded
boolean of if all rxode2 dlls have been unloaded
Examples
print(rxUnloadAll())
Use model object in your package
Description
Use model object in your package
Usage
rxUse(obj, overwrite = TRUE, compress = "bzip2", internal = FALSE)
Arguments
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 |
Value
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.
Description
Validate rxode2 This allows easy validation/qualification of nlmixr by running the testing suite on your system.
Usage
rxValidate(type = NULL, skipOnCran = TRUE)
rxTest(type = NULL, skipOnCran = TRUE)
Arguments
type |
Type of test or filter of test type, When this is an
expression, evaluate the contents, respecting |
skipOnCran |
when |
Value
nothing
Author(s)
Matthew L. Fidler
Version and repository for this dparser package.
Description
Version and repository for this dparser package.
Usage
rxVersion(
extra = "",
echo = FALSE,
version = sessionInfo()$otherPkgs$rxode2$Version
)
Arguments
extra |
extra text to display in the logo |
echo |
Boolean to echo the text logo, by default FALSE |
version |
Version to display/return |
Value
A character vector with the version and repository.
Author(s)
Matthew L. Fidler
Preserved seed and possibly set the seed
Description
Preserved seed and possibly set the seed
Usage
rxWithSeed(
seed,
code,
rxseed = rxGetSeed(),
kind = "default",
normal.kind = "default",
sample.kind = "default"
)
rxWithPreserveSeed(code)
Arguments
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 |
Value
returns whatever the code is returning
See Also
rxGetSeed, rxSetSeed
Examples
rxGetSeed()
rxWithSeed(1, {
print(rxGetSeed())
rxnorm()
print(rxGetSeed())
rxnorm()
}, rxseed=3)
Simulate beta variable from threefry generator
Description
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.
Usage
rxbeta(shape1, shape2, n = 1L, ncores = 1L)
Arguments
shape1 , shape2 |
non-negative parameters of the Beta distribution. |
n |
number of observations. If |
ncores |
Number of cores for the simulation
|
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.
Value
beta random deviates
Examples
## 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)
Simulate Binomial variable from threefry generator
Description
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.
Usage
rxbinom(size, prob, n = 1L, ncores = 1L)
Arguments
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
|
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.
Value
binomial random deviates
Examples
## 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)
Simulate Cauchy variable from threefry generator
Description
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.
Usage
rxcauchy(location = 0, scale = 1, n = 1L, ncores = 1L)
Arguments
location , scale |
location and scale parameters. |
n |
number of observations. If |
ncores |
Number of cores for the simulation
|
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.
Value
Cauchy random deviates
Examples
## 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)
Simulate chi-squared variable from threefry generator
Description
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.
Usage
rxchisq(df, n = 1L, ncores = 1L)
Arguments
df |
degrees of freedom (non-negative, but can be non-integer). |
n |
number of observations. If |
ncores |
Number of cores for the simulation
|
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.
Value
chi squared random deviates
Examples
## 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)
Simulate exponential variable from threefry generator
Description
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.
Usage
rxexp(rate, n = 1L, ncores = 1L)
Arguments
rate |
vector of rates. |
n |
number of observations. If |
ncores |
Number of cores for the simulation
|
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.
Value
exponential random deviates
Examples
## 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)
Simulate F variable from threefry generator
Description
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.
Usage
rxf(df1, df2, n = 1L, ncores = 1L)
Arguments
df1 , df2 |
degrees of freedom. |
n |
number of observations. If |
ncores |
Number of cores for the simulation
|
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.
Value
f random deviates
Examples
## 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)
Simulate gamma variable from threefry generator
Description
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.
Usage
rxgamma(shape, rate = 1, n = 1L, ncores = 1L)
Arguments
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
|
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.
Value
gamma random deviates
Examples
## 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)
Simulate geometric variable from threefry generator
Description
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.
Usage
rxgeom(prob, n = 1L, ncores = 1L)
Arguments
prob |
probability of success in each trial. |
n |
number of observations. If |
ncores |
Number of cores for the simulation
|
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.
Value
geometric random deviates
Examples
## 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)
Simulate Binomial variable from threefry generator
Description
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.
Usage
rxnbinom(size, prob, mu, n = 1L, ncores = 1L)
rxnbinomMu(size, mu, n = 1L, ncores = 1L)
Arguments
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. |
mu |
alternative parametrization via mean: see ‘Details’. |
n |
number of observations. If |
ncores |
Number of cores for the simulation
|
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.
Value
negative binomial random deviates. Note that rxbinom2
uses the mu
parameterization an the rxbinom
uses the prob
parameterization (mu=size/(prob+size)
)
Examples
## 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)
Simulate random normal variable from threefry generator
Description
Simulate random normal variable from threefry generator
Usage
rxnormV(mean = 0, sd = 1, n = 1L, ncores = 1L)
rxnorm(mean = 0, sd = 1, n = 1L, ncores = 1L)
Arguments
mean |
vector of means. |
sd |
vector of standard deviations. |
n |
number of observations |
ncores |
Number of cores for the simulation
|
Value
normal random number deviates
Examples
## 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 an ODE-based model specification
Description
Create a dynamic ODE-based model object suitably for translation into fast C code
Usage
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"),
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"),
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"),
indLin = FALSE,
verbose = FALSE,
fullPrint = getOption("rxode2.fullPrint", FALSE),
envir = parent.frame()
)
Arguments
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) |
Details
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.
The ODE-based model specification may be coded inside four places:
Inside a
rxode2({})
block statements:
library(rxode2) mod <- rxode2({ # simple assignment C2 <- centr/V2 # time-derivative assignment d/dt(centr) <- F*KA*depot - CL*C2 - Q*C2 + Q*C3; })
Inside a
rxode2("")
string statement:
mod <- rxode2(" # simple assignment C2 <- centr/V2 # time-derivative assignment d/dt(centr) <- F*KA*depot - CL*C2 - Q*C2 + Q*C3; ")
In a file name to be loaded by rxode2:
writeLines(" # simple assignment C2 <- centr/V2 # time-derivative assignment d/dt(centr) <- F*KA*depot - CL*C2 - Q*C2 + Q*C3; ", "modelFile.rxode2") mod <- rxode2(filename='modelFile.rxode2') unlink("modelFile.rxode2")
In a model function which can be parsed by
rxode2
:
mod <- function() { model({ # simple assignment C2 <- centr/V2 # time-derivative assignment d/dt(centr) <- F*KA*depot - CL*C2 - Q*C2 + Q*C3; }) } mod <- rxode2(mod) # or simply mod() if the model is at the end of the function # These model functions often have residual components and initial # (`ini({})`) conditions attached as well. For example the # theophylline model can be written as: 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) }) } # after parsing the model mod <- one.compartment()
For the block statement, character string or text file an internal
rxode2
compilation manager translates the ODE system into C, compiles
it and loads it into the R session. The call to rxode2
produces an
object of class rxode2
which consists of a list-like structure
(environment) with various member functions.
For the last type of model (a model function), a call to rxode2
creates a parsed rxode2
ui that can be translated to the rxode2
compilation model.
mod$simulationModel # or mod$simulationIniModel
This is the same type of function required for nlmixr2
estimation and
can be extended and modified by model piping. For this reason will be
focused on in the documentation.
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 asdf(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 therxode2
model. As such, they are declared in much the same way asR
, 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 andmidpoint(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.
Identifiers
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), andpodo
(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
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.
Supported functions
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)
Reserved keywords
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.
Residual functions when using rxode2 functions
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.
Transformations
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.
Normal and t-related distributions
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
.
Notes on additive + proportional models
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
.
Distributions of known likelihoods
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
Ordinal likelihoods
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 |
General table of supported residual distributions
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 | ||
Value
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.
Creating rxode2 models
NA
Note on strings in rxode2
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.
Author(s)
Melissa Hallow, Wenping Wang and Matthew Fidler
References
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.
See Also
eventTable()
, et()
, add.sampling()
, add.dosing()
Examples
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)
Description
Set the function body of an rxUi object while retaining other object information (like data)
Usage
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
Arguments
x |
The rxUi object |
envir |
environment where the assignment ocurs |
value |
the value that will be assigned |
Value
The rxode2 ui/function
Examples
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
Description
Internal translation to get model variables list
Usage
rxode2parse(
model,
linear = FALSE,
linCmtSens = c("linCmtA", "linCmtB"),
verbose = FALSE,
code = NULL,
envir = parent.frame()
)
Arguments
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) |
Value
A rxModelVars object that has the model variables of a rxode2 syntax expression
Examples
rxode2parse("a=3")
This sets function gets the currently assigned function pointer assignments
Description
This sets function gets the currently assigned function pointer assignments
Usage
rxode2parseAssignPointerTranslation(var)
Arguments
var |
List of packages where pointer assignment will be called. |
Value
Nothing, called for side effects
Author(s)
Matthew L. Fidler
Examples
rxode2parseAssignPointerTranslation("rxode2")
This assigns the c level linkages for a roxde2 model
Description
This assigns the c level linkages for a roxde2 model
Usage
rxode2parseAssignTranslation(df)
Arguments
df |
data frame containing the character column names rxFun, fun, type, package, packageFun and the integer column names argMin and argMax |
Value
Nothing called for side effects
Author(s)
Matthew L. Fidler
Examples
rxode2parseAssignTranslation(rxode2parseGetTranslation())
This gives the derivative table for rxode2
Description
This will help allow registration of functions in rxode2
Usage
rxode2parseD()
Details
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.
Value
Derivative table environment for rxode2
Author(s)
Matthew L. Fidler
Control the packages that are loaded when a rxode2
model dll is loaded
Description
Control the packages that are loaded when a rxode2
model dll is loaded
Usage
rxode2parseGetPackagesToLoad()
rxode2parseAssignPackagesToLoad(pkgs = rxode2parseGetPackagesToLoad())
Arguments
pkgs |
The packages to make sure are loaded every time you load an rxode2 model. |
Value
List of packages to load
Author(s)
Matthew Fidler
Examples
rxode2parseGetPackagesToLoad()
rxode2parseAssignPackagesToLoad(rxode2parseGetPackagesToLoad())
This function gets the currently assigned function pointer assignments
Description
This function gets the currently assigned function pointer assignments
Usage
rxode2parseGetPointerAssignment()
Value
The currently assigned pointer assignments
Author(s)
Matthew L. Fidler
Examples
rxode2parseGetTranslation()
This function gets the currently assigned translations
Description
This function gets the currently assigned translations
Usage
rxode2parseGetTranslation()
Value
The currently assigned translations
Author(s)
Matthew L. Fidler
Examples
rxode2parseGetTranslation()
Simulate ordinal value
Description
Simulate ordinal value
Usage
rxord(...)
Arguments
... |
the probabilities to be simulated. These should sum up to a number below one. |
Details
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)
Value
A number from 1 to the (number of probabilities specified + 1)
Author(s)
Matthew L. Fidler
Examples
# 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)
Simulate random Poisson variable from threefry generator
Description
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.
Usage
rxpois(lambda, n = 1L, ncores = 1L)
Arguments
lambda |
vector of (non-negative) means. |
n |
number of random values to return. |
ncores |
Number of cores for the simulation
|
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.
Value
poission random number deviates
Examples
## 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 student t variable from threefry generator
Description
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.
Usage
rxt(df, n = 1L, ncores = 1L)
Arguments
df |
degrees of freedom ( |
n |
number of observations. If |
ncores |
Number of cores for the simulation
|
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.
Value
t-distribution random numbers
Examples
## 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)
Simulate uniform variable from threefry generator
Description
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.
Usage
rxunif(min = 0, max = 1, n = 1L, ncores = 1L)
Arguments
min , max |
lower and upper limits of the distribution. Must be finite. |
n |
number of observations. If |
ncores |
Number of cores for the simulation
|
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.
Value
uniform random numbers
Examples
## 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)
Simulate Weibull variable from threefry generator
Description
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.
Usage
rxweibull(shape, scale = 1, n = 1L, ncores = 1L)
Arguments
shape , scale |
shape and scale parameters, the latter defaulting to 1. |
n |
number of observations. If |
ncores |
Number of cores for the simulation
|
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.
Value
Weibull random deviates
Examples
## 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)
Softplus Activation Function
Description
Softplus Activation Function
Usage
softplus(x)
Arguments
x |
numeric vector |
Value
numeric vector
Author(s)
Matthew L. Fidler
See Also
Other Activation Functions:
ELU()
,
GELU()
,
PReLU()
,
ReLU()
,
SELU()
,
Swish()
,
dELU()
,
dGELU()
,
dPReLU()
,
dReLU()
,
dSELU()
,
dSwish()
,
dlReLU()
,
dsoftplus()
,
lReLU()
Examples
softplus(c(-1, 0, 1, 2))
# You can use rxode2 too:
r <- rxode2({
s <- softplus(time)
})
e <- et(c(-1, 0, 1, 2))
rxSolve(r, e)
Dosing/Amt geom/stat
Description
This is a dosing geom that shows the vertical lines where a dose occurs
Usage
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,
...
)
Arguments
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
|
Details
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
Value
This returns a stat_amt in context of a ggplot2 plot
Examples
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)
Censoring geom/stat
Description
This is a censoring geom that shows the left or right censoring specified in the nlmixr input data-set or fit
Usage
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,
...
)
Arguments
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
|
Details
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 or1
left censoring) -
LIMIT
which represents the corresponding limit ()
Will add boxes representing the areas of the fit that were censored.
Value
This returns a ggplot2 stat
Summary of rxDll object
Description
This gives expanded information about the rxDll object
Usage
## S3 method for class 'rxDll'
summary(object, ...)
Arguments
object |
RxDll object |
... |
Other arguments. Includes |
Value
object is returned
Author(s)
Matthew L.Fidler
Print expanded information about the rxode2 object.
Description
This prints the expanded information about the rxode2 object.
Usage
## S3 method for class 'rxode2'
summary(object, ...)
Arguments
object |
rxode2 object |
... |
Ignored parameters |
Value
object is returned
Author(s)
Matthew L.Fidler
Swaps the matrix list with a cube
Description
Swaps the matrix list with a cube
Usage
swapMatListWithCube(matrixListOrCube)
Arguments
matrixListOrCube |
Either a list of 2-dimensional matrices or a cube of matrices |
Value
A list or a cube (opposite format as input)
Author(s)
Matthew L. Fidler
Examples
# 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)
This function tests if this object is a iniDf as needed by the UI
Description
This function tests if this object is a iniDf as needed by the UI
Usage
testIniDf(iniDf)
assertIniDf(iniDf, extra = "", .var.name = .vname(iniDf), null.ok = FALSE)
Arguments
iniDf |
the object to test if it is a rxode2 ui |
extra |
information to append to the error message |
.var.name |
[ |
null.ok |
[ |
Value
boolean, indicating if the object is a valid initialization data frame
Functions
-
assertIniDf()
: Assert that the object is a valid rxode2 ui initialization data frame
Author(s)
Matthew L. Fidler
See Also
Other Assertions:
assertCompartmentExists()
,
assertCompartmentName()
,
assertCompartmentNew()
,
assertRxUi()
,
assertVariableExists()
,
assertVariableNew()
,
testRxUnbounded()
Examples
testIniDf(TRUE)
Test if rxode2 uses linear solved systems
Description
Test if rxode2 uses linear solved systems
Usage
testRxLinCmt(ui, extra = "", .var.name = .vname(ui))
assertRxLinCmt(ui, extra = "", .var.name = .vname(ui))
Arguments
ui |
rxode2 model |
extra |
Extra text to append to the error message (like "for focei") |
.var.name |
[ |
Value
TRUE if the model uses linear solved systems, FALSE otherwise
Functions
-
assertRxLinCmt()
: Assert that the rxode2 uses linear solved systems
Author(s)
Matthew L. Fidler
Examples
one.cmt <- function() {
ini({
## You may label each parameter with a comment
tka <- 0.45 # Log Ka
tcl <- log(c(0, 2.7, 100)) # Log Cl
## This works with interactive models
## You may also label the preceding line with label("label text")
tv <- 3.45; label("log V")
## the label("Label name") works with all models
eta.ka ~ 0.6
eta.cl ~ 0.3
eta.v ~ 0.1
add.sd <- 0.7
})
model({
ka <- exp(tka + eta.ka)
cl <- exp(tcl + eta.cl)
v <- exp(tv + eta.v)
linCmt() ~ add(add.sd)
})
}
testRxLinCmt(one.cmt)
Test if the rxode2 model has any parameters with user defined boundaries
Description
Test if the rxode2 model has any parameters with user defined boundaries
Usage
testRxUnbounded(ui)
assertRxUnbounded(ui, extra = "", .var.name = .vname(ui))
warnRxBounded(ui, extra = "", .var.name = .vname(ui))
Arguments
ui |
rxode2 ui |
extra |
extra information to append to the error message |
.var.name |
variable name |
Value
boolean indicating if any parameters have user defined boundaries
Functions
-
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
Author(s)
Matthew L. Fidler
See Also
Other Assertions:
assertCompartmentExists()
,
assertCompartmentName()
,
assertCompartmentNew()
,
assertRxUi()
,
assertVariableExists()
,
assertVariableNew()
,
testIniDf()
Examples
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.
Description
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.
Usage
toTrialDuration(ev, trialEnd, interval, writeDir = NULL)
Arguments
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 |
Author(s)
Omar Elashkar
Examples
# 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
Description
Update for rxUi
Usage
## S3 method for class 'rxUi'
update(object, ..., envir = parent.frame())
Arguments
object |
rxode2 UI object |
... |
Lines to update |
envir |
Environment for evaluating ini() style calls |
Value
a new rxode2 updated UI object
uppergamma: upper incomplete gamma function
Description
This is the tgamma from the boost library
Usage
uppergamma(a, z)
Arguments
a |
The numeric 'a' parameter in the upper incomplete gamma |
z |
The numeric 'z' parameter in the upper incomplete gamma |
Details
The uppergamma function is given by:
uppergamma(a, z) = \int_{z}^{\infty}t^{a-1}\cdot e^{-t} dt
Value
uppergamma results
Author(s)
Matthew L. Fidler
Examples
uppergamma(1, 3)
uppergamma(1:3, 3)
uppergamma(1, 1:3)
Set random effects and residual error to zero
Description
Set random effects and residual error to zero
Usage
zeroRe(object, which = c("omega", "sigma"), fix = TRUE)
Arguments
object |
The model to modify |
which |
The types of parameters to set to zero |
fix |
Should the parameters be fixed to the zero value? |
Value
The object
with some parameters set to zero
Author(s)
Bill Denney
See Also
Other Initial conditions:
ini.rxUi()
Examples
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)