Title: | Simulate from ODE-Based Models |
---|---|
Description: | Fast simulation from ordinary differential equation (ODE) based models typically employed in quantitative pharmacology and systems biology. |
Authors: | Kyle T Baron [aut, cre] , Bill Gillespie [ctb], Charles Margossian [ctb], Devin Pastoor [ctb], Bill Denney [ctb] , Dilawar Singh [ctb], Felicien Le Louedec [ctb] , Timothy Waterhouse [ctb] , Kyle Meyer [ctb], Metrum Research Group [cph] |
Maintainer: | Kyle T Baron <[email protected]> |
License: | GPL (>= 2) |
Version: | 1.5.2 |
Built: | 2024-11-18 06:27:50 UTC |
Source: | CRAN |
mrgsolve is an R package maintained under the auspices of Metrum Research Group that facilitates simulation from models based on systems of ordinary differential equations (ODE) that are typically employed for understanding pharmacokinetics, pharmacodynamics, and systems biology and pharmacology. mrgsolve consists of computer code written in the R and C++ languages, providing an interface to a C++ translation of the lsoda differential equation solver. See aboutsolver for more information.
Main mrgsolve resource page: https://mrgsolve.org
User guide: https://mrgsolve.org/user_guide/
Package documentation and vignettes: https://mrgsolve.org/docs/
mrgolve.project
: sets the default project director (mread()
)
mrgsolve.soloc
: sets the default package build directory (mread()
)
mrgsolve_mread_quiet
: don't print messages during mread()
mrgsolve.update.strict
: this option has been deprecated; use the strict
argument to update()
instead
Maintainer: Kyle T Baron [email protected] (ORCID)
Other contributors:
Bill Gillespie [contributor]
Charles Margossian [contributor]
Devin Pastoor [contributor]
Bill Denney (ORCID) [contributor]
Dilawar Singh [contributor]
Felicien Le Louedec (ORCID) [contributor]
Timothy Waterhouse (ORCID) [contributor]
Kyle Meyer [contributor]
Metrum Research Group [copyright holder]
Useful links:
Report bugs at https://github.com/metrumresearchgroup/mrgsolve/issues
## example("mrgsolve") mod <- mrgsolve::house(delta=0.1) %>% param(CL=0.5) events <- ev(amt=1000, cmt=1, addl=5, ii=24) events mod see(mod) ## Not run: stime(mod) ## End(Not run) param(mod) init(mod) out <- mod %>% ev(events) %>% mrgsim(end=168) head(out) tail(out) dim(out) plot(out, GUT+CP~.) sims <- as.data.frame(out) t72 <- dplyr::filter(sims, time==72) str(t72) idata <- data.frame(ID=c(1,2,3), CL=c(0.5,1,2),VC=12) out <- mod %>% ev(events) %>% mrgsim(end=168, idata=idata, req="") plot(out) out <- mod %>% ev(events) %>% mrgsim(carry_out="amt,evid,cmt,CL") head(out) ev1 <- ev(amt=500, cmt=2,rate=10) ev2 <- ev(amt=100, cmt=1, time=54, ii=8, addl=10) events <- c(ev1+ev2) events out <- mod %>% ev(events) %>% mrgsim(end=180, req="") plot(out) ## "Condensed" data set data(extran1) extran1 out <- mod %>% data_set(extran1) %>% mrgsim(end=200) plot(out,CP~time|factor(ID)) ## idata data(exidata) out <- mod %>% ev(amt=1000, cmt=1) %>% idata_set(exidata) %>% mrgsim(end=72) plot(out, CP~., as="log10") # Internal model library ## Not run: mod <- mread("irm1", modlib()) mod x <- mod %>% ev(amt=300, ii=12, addl=3) %>% mrgsim ## End(Not run)
## example("mrgsolve") mod <- mrgsolve::house(delta=0.1) %>% param(CL=0.5) events <- ev(amt=1000, cmt=1, addl=5, ii=24) events mod see(mod) ## Not run: stime(mod) ## End(Not run) param(mod) init(mod) out <- mod %>% ev(events) %>% mrgsim(end=168) head(out) tail(out) dim(out) plot(out, GUT+CP~.) sims <- as.data.frame(out) t72 <- dplyr::filter(sims, time==72) str(t72) idata <- data.frame(ID=c(1,2,3), CL=c(0.5,1,2),VC=12) out <- mod %>% ev(events) %>% mrgsim(end=168, idata=idata, req="") plot(out) out <- mod %>% ev(events) %>% mrgsim(carry_out="amt,evid,cmt,CL") head(out) ev1 <- ev(amt=500, cmt=2,rate=10) ev2 <- ev(amt=100, cmt=1, time=54, ii=8, addl=10) events <- c(ev1+ev2) events out <- mod %>% ev(events) %>% mrgsim(end=180, req="") plot(out) ## "Condensed" data set data(extran1) extran1 out <- mod %>% data_set(extran1) %>% mrgsim(end=200) plot(out,CP~time|factor(ID)) ## idata data(exidata) out <- mod %>% ev(amt=1000, cmt=1) %>% idata_set(exidata) %>% mrgsim(end=72) plot(out, CP~., as="log10") # Internal model library ## Not run: mod <- mread("irm1", modlib()) mod x <- mod %>% ev(amt=300, ii=12, addl=3) %>% mrgsim ## End(Not run)
Select columns from an ev object
## S4 method for signature 'ev' x$name ## S4 method for signature 'ev' x[[i, exact = TRUE]]
## S4 method for signature 'ev' x$name ## S4 method for signature 'ev' x[[i, exact = TRUE]]
x |
ev object |
name |
column to select |
i |
an element to select |
exact |
not used |
The $
and [[
operators get the value
of a single parameter in the model. The
[
gets several values, returning a
named list.
## S4 method for signature 'mrgmod' x$name ## S4 method for signature 'mrgmod' x[[i, exact = TRUE]] ## S4 method for signature 'mrgmod' x[i]
## S4 method for signature 'mrgmod' x$name ## S4 method for signature 'mrgmod' x[[i, exact = TRUE]] ## S4 method for signature 'mrgmod' x[i]
x |
mrgmod object |
name |
parameter to take |
i |
an element to select |
exact |
not used |
The differential equation solver is a C++ translation of DLSODA from ODEPACK. The C++ translation was created by Dilawar Singh and hosted here https://github.com/dilawar/libsoda-cxx/. As we understand the history of the code, Heng Li was also involved in early versions of the code written in C. There was a potentially-related project hosted here https://github.com/sdwfrost/liblsoda/.
The C++ translation by Dilawar Singh contains functions that appear to be based on BLAS and LAPACK routines. These functions have been renamed to be distinct from the respective BLAS and LAPACK function names. References are given in the section below.
The following history was recorded in the source code published by Dilawar Singh:
/* * HISTORY: * This is a CPP version of the LSODA library for integration into MOOSE somulator. * The original was aquired from * http://www.ccl.net/cca/software/SOURCES/C/kinetics2/index.shtml and modified by * Heng Li <[email protected]>. Heng merged several C files into one and added a * simpler interface. [Available here](http://lh3lh3.users.sourceforge.net/download/lsoda.c) * The original source code came with no license or copyright * information. Heng Li released his modification under the MIT/X11 license. I * maintain the same license. I have removed quite a lot of text/comments from * this library. Please refer to the standard documentation. * * Contact: Dilawar Singh <[email protected]> */
LAPACK: https://netlib.org/lapack/
BLAS: https://netlib.org/blas/
These are simple functions that may be helpful to create the matrix objects
that mrgsolve expects. Functions are named based on whether they create a
diagonal matrix (d
), a block matrix (b
), or a a correlation
matrix (c
).
as_bmat(x, ...) ## S4 method for signature 'list' as_bmat(x, ...) ## S4 method for signature 'numeric' as_bmat(x, pat = "*", ...) ## S4 method for signature 'data.frame' as_bmat(x, pat = "*", cols = NULL, ...) ## S4 method for signature 'ANY' as_bmat(x, ...) as_dmat(x, ...) ## S4 method for signature 'list' as_dmat(x, ...) ## S4 method for signature 'ANY' as_dmat(x, ...) ## S4 method for signature 'numeric' as_dmat(x, pat = "*", ...) ## S4 method for signature 'data.frame' as_dmat(x, pat = "*", cols = NULL, ...) as_cmat(x, ...)
as_bmat(x, ...) ## S4 method for signature 'list' as_bmat(x, ...) ## S4 method for signature 'numeric' as_bmat(x, pat = "*", ...) ## S4 method for signature 'data.frame' as_bmat(x, pat = "*", cols = NULL, ...) ## S4 method for signature 'ANY' as_bmat(x, ...) as_dmat(x, ...) ## S4 method for signature 'list' as_dmat(x, ...) ## S4 method for signature 'ANY' as_dmat(x, ...) ## S4 method for signature 'numeric' as_dmat(x, pat = "*", ...) ## S4 method for signature 'data.frame' as_dmat(x, pat = "*", cols = NULL, ...) as_cmat(x, ...)
x |
data frame or list. |
... |
|
pat |
regular expression, character. |
cols |
column names to use instead of |
Use as_dmat()
to create a diagonal matrix, as_bmat()
to create a block matrix, and as_cmat()
to create a block
matrix where off-diagonal elements are understood to be correlations
rather than covariances. as_cmat()
uses as_bmat()
to
form the matrix and then converts off-diagonal elements to
covariances before returning.
The methods for data.frame
will work down the rows
of the data frame and make the appropriate matrix from
the data in each row. The result is a list of matrices.
A numeric matrix for list and numeric methods. For data.frames, a list of matrices are returned.
df <- data.frame( OMEGA1.1 = c(1,2), OMEGA2.1 = c(11,22), OMEGA2.2 = c(3,4), SIGMA1.1 = 1, FOO=-1 ) as_bmat(df, "OMEGA") as_dmat(df,"SIGMA") as_dmat(df[1,],"OMEGA")
df <- data.frame( OMEGA1.1 = c(1,2), OMEGA2.1 = c(11,22), OMEGA2.2 = c(3,4), SIGMA1.1 = 1, FOO=-1 ) as_bmat(df, "OMEGA") as_dmat(df,"SIGMA") as_dmat(df[1,],"OMEGA")
The goal is to take a series of event objects or data frames and combine them
into a single data frame that can be passed to data_set()
.
as_data_set(x, ...) ## S4 method for signature 'ev' as_data_set(x, ...) ## S4 method for signature 'data.frame' as_data_set(x, ...)
as_data_set(x, ...) ## S4 method for signature 'ev' as_data_set(x, ...) ## S4 method for signature 'data.frame' as_data_set(x, ...)
x |
an ev object or data frame. |
... |
additional ev objects or data frames. |
Each event object or data frame is added to the data frame as an ID
or
set of ID
s that are distinct from the ID
s in the other event objects.
Note that including ID
argument to the ev()
call where length(ID)
is
greater than one will render that set of events for all of ID
s that are
requested.
When determining the case for output names, the case
attribute for
the first ev
object passed will be used to set the case for the output
data.frame. In the event x
is a data frame, the case of special column
names (like amt/AMT
or cmt/CMT
) in the first data frame will be assessed
and the case in the output data frame will be determined based on the
relative numbers of lower or upper names.
To get a data frame with one row (event) per ID
, look at expand.ev()
.
A data frame suitable for passing into data_set()
. The columns will appear
in a standardized order.
expand.ev()
, expand.evd()
, ev()
, evd()
, uctran()
,
lctran()
a <- ev(amt = c(100,200), cmt=1, ID = seq(3)) b <- ev(amt = 300, time = 24, ID = seq(2)) c <- ev(amt = 1000, ii = 8, addl = 10, ID = seq(3)) as_data_set(a, b, c) d <- evd(amt = 500) as_data_set(d, a) # Output will have upper case nmtran names as_data_set( data.frame(AMT = 100, ID = 1:2), data.frame(amt = 200, rate = 5, cmt = 2) ) # Instead of this, use expand.ev as_data_set(ev(amt = 100), ev(amt = 200), ev(amt = 300))
a <- ev(amt = c(100,200), cmt=1, ID = seq(3)) b <- ev(amt = 300, time = 24, ID = seq(2)) c <- ev(amt = 1000, ii = 8, addl = 10, ID = seq(3)) as_data_set(a, b, c) d <- evd(amt = 500) as_data_set(d, a) # Output will have upper case nmtran names as_data_set( data.frame(AMT = 100, ID = 1:2), data.frame(amt = 200, rate = 5, cmt = 2) ) # Instead of this, use expand.ev as_data_set(ev(amt = 100), ev(amt = 200), ev(amt = 300))
Create a list of designs from a data frame
as_deslist(data, descol = "ID")
as_deslist(data, descol = "ID")
data |
input data set; see Details. |
descol |
character column name to be used for design groups. |
The input data set must have a column with the same name as the value
of descol
. Other column names should be start
(the time
of the first observation), end
(the time of the last observation),
delta
(the time steps to take between start
and end
),
and add
(other, ad-hoc times). Note that add
might be
a list-column
to get a vector of times for each time grid object.
The function returns a list of tgrid
objects,
one for each unique value found in descol
.
idata <- tibble::tibble(ID=1:4, end=seq(24,96,24), delta=6, add=list(c(122,124,135),c(111), c(99),c(88))) idata <- dplyr::mutate(idata, GRP = ID %%2) idata l <- as_deslist(idata,"GRP") l lapply(l,stime) lapply(as_deslist(idata, "ID"),stime)
idata <- tibble::tibble(ID=1:4, end=seq(24,96,24), delta=6, add=list(c(122,124,135),c(111), c(99),c(88))) idata <- dplyr::mutate(idata, GRP = ID %%2) idata l <- as_deslist(idata,"GRP") l lapply(l,stime) lapply(as_deslist(idata, "ID"),stime)
Use this function to convert a data frame to an event object.
as.ev(x, ...) ## S4 method for signature 'data.frame' as.ev(x, keep_id = TRUE, clean = FALSE, ...) ## S4 method for signature 'ev' as.ev(x, ...)
as.ev(x, ...) ## S4 method for signature 'data.frame' as.ev(x, keep_id = TRUE, clean = FALSE, ...) ## S4 method for signature 'ev' as.ev(x, ...)
x |
an object to coerce. |
... |
not used. |
keep_id |
if |
clean |
if |
If CMT
(or cmt
) is missing from the input, it will be set to 1
in the event object.
If TIME
(or time
) is missing from the input, it will be set to
0 in the event object.
If EVID
(or evid
) is missing from the input, it will be set to
1 in the event object.
An object with class ev.
data <- data.frame(AMT = 100) as.ev(data) as.ev(data, clean = TRUE)
data <- data.frame(AMT = 100) as.ev(data) as.ev(data, clean = TRUE)
Coerce a model object to list
## S4 method for signature 'mrgmod' as.list(x, deep = FALSE, ...)
## S4 method for signature 'mrgmod' as.list(x, deep = FALSE, ...)
x |
a model object. |
deep |
if |
... |
not used. |
If deep
is TRUE
, then the values for trans
, advan
, and mindt
are
returned as well as a summary of internal model functions (with a call to
mrgsolve:::funset()
).
A named list containing formatted contents from x
.
npar
: number of parameters
neq
: number of compartments or differential equations
pars
: names of model parameters
covariates
: names of parameters identified as covariates
cmt
: names of model compartments
param
: the parameter list
init
: initial condition list
omega
: $OMEGA
matrices, as a matlist
object
sigma
: $SIGMA
matrices, as a matlist
object
fixed
: named list of $FIXED
values
model
: model name
project
: model project directory
soloc
: directory where the model is being built
sodll
: complete path to the model shared object
cfile
: path for the model source code file
shlib
: list of compilation information
start
: simulation start time
end
: simulation end time
delta
: simulation time step
add
: additional simulation times
capture
: names of captured data items
request
: compartments requested upon simulation
cmti
: named indices for current output compartments
capturei
: named indices for current output capture
random
: names and labels of $OMEGA
and $SIGMA
code
: model source code from cfile
details
: model details data frame
nm_import
: a character vector listing the names of nonmem output files
that were read to import estimates from a completed nonmem run
cpp_variables
: a data frame listing variables internal to the model
cpp file
atol
: see solversettings
rtol
: see solversettings
ss_atol
: absolute tolerance to use when advancing to PK steady state
ss_rtol
: relative tolerance to use when advancing to PK steady state
maxsteps
: see solversettings
hmin
: see solversettings
hmax
: see solversettings
envir
: the model environment
plugins
: plugins invoked in the model
digits
: number of digits to request in simulated data
tscale
: multiplicative scalar for time in results only
mindt
: simulation output time below which there model will assume to
have not advanced
preclean
: logical indicating to clean up compilation artifacts prior
to compiling
debug
: print debugging information during simulation run
verbose
: print extra information during setup for model run
mod <- mrgsolve::house() l <- as.list(mod)
mod <- mrgsolve::house() l <- as.list(mod)
Coerce an mrgsims object to list
## S4 method for signature 'mrgsims' as.list(x, ...)
## S4 method for signature 'mrgsims' as.list(x, ...)
x |
an mrgsims object. |
... |
not used. |
Most of the basic blocks are listed in this help topic.
But see also PKMODEL()
which has more-involved
options and is documented separately.
PARAM( x, env, pos = 1, annotated = FALSE, object = NULL, as_object = FALSE, covariates = FALSE, input = FALSE, tag = NULL, ... ) FIXED(x, env, pos = 1, annotated = FALSE, ...) THETA( x, env, pos = 1, annotated = FALSE, object = NULL, as_object = FALSE, name = "THETA", fill = NULL, ... ) INIT(x, env, pos = 1, annotated = FALSE, object = NULL, as_object = FALSE, ...) CMT( x, env, pos = 1, annotated = FALSE, object = NULL, as_object = FALSE, number = NULL, prefix = "A", ... ) CAPTURE(x, env, pos = 1, annotated = FALSE, etas = NULL, ...) HANDLEMATRIX( x, env, pos = 1, annotated = FALSE, object = NULL, as_object = FALSE, name = "...", type = NULL, oclass = "", prefix = "", labels = NULL, unlinked = FALSE, ... )
PARAM( x, env, pos = 1, annotated = FALSE, object = NULL, as_object = FALSE, covariates = FALSE, input = FALSE, tag = NULL, ... ) FIXED(x, env, pos = 1, annotated = FALSE, ...) THETA( x, env, pos = 1, annotated = FALSE, object = NULL, as_object = FALSE, name = "THETA", fill = NULL, ... ) INIT(x, env, pos = 1, annotated = FALSE, object = NULL, as_object = FALSE, ...) CMT( x, env, pos = 1, annotated = FALSE, object = NULL, as_object = FALSE, number = NULL, prefix = "A", ... ) CAPTURE(x, env, pos = 1, annotated = FALSE, etas = NULL, ...) HANDLEMATRIX( x, env, pos = 1, annotated = FALSE, object = NULL, as_object = FALSE, name = "...", type = NULL, oclass = "", prefix = "", labels = NULL, unlinked = FALSE, ... )
x |
data |
env |
parse environment |
pos |
block position |
annotated |
logical |
object |
the name of an object in |
as_object |
indicates that object code is being provided |
covariates |
logical; mark as covariates and potentially required data input |
input |
logical; mark as potentially required data input |
tag |
space or comma-separated user-defined tags for the parameter block |
... |
passed |
name |
block name |
fill |
deprecated; not used |
number |
number of compartments to create |
prefix |
a prefix to add to the label |
etas |
allows for block capture of ETAs in the simulated output; this should be R code that will get parsed and evaluated; the result should be an integer-like vector which identifies which ETAs will be captured. |
type |
internal use |
oclass |
internal use |
labels |
aliases to use for simulated ETA values |
unlinked |
internal use |
When using object
or as_object
populate the block contents, the following
types are required
PARAM
: a named list
INIT
: a named list
THETA
: a numeric vector; names are ignored
CMT
: a character vector
OMEGA
: matrix; set rownames on the matrix to create ETA labels; setting
rownames is the only way to specify labels
when working through the
object
or as_object
directives
SIGMA
: matrix; set rownames on the matrix to create EPS labels; setting
rownames is the only way to specify labels
when working through the
object
or as_object
directives
Return the code blocks from a model specification file
blocks(x, ...) ## S4 method for signature 'mrgmod' blocks(x, ...) ## S4 method for signature 'character' blocks(x, ...)
blocks(x, ...) ## S4 method for signature 'mrgmod' blocks(x, ...) ## S4 method for signature 'character' blocks(x, ...)
x |
model object or path to model specification file |
... |
passed along |
mod <- mrgsolve::house() mod %>% blocks mod %>% blocks(PARAM,TABLE)
mod <- mrgsolve::house() mod %>% blocks mod %>% blocks(PARAM,TABLE)
Operations with matlist objects
## S4 method for signature 'matlist' c(x, ..., recursive = FALSE)
## S4 method for signature 'matlist' c(x, ..., recursive = FALSE)
x |
a matlist object |
... |
other matlist objects |
recursive |
not used |
Operations with tgrid objects
## S4 method for signature 'tgrid' c(x, ..., recursive = FALSE) ## S4 method for signature 'tgrids' c(x, ..., recursive = FALSE) ## S4 method for signature 'tgrid,numeric' e1 + e2 ## S4 method for signature 'tgrid,numeric' e1 * e2 ## S4 method for signature 'tgrids,numeric' e1 + e2 ## S4 method for signature 'tgrids,numeric' e1 * e2
## S4 method for signature 'tgrid' c(x, ..., recursive = FALSE) ## S4 method for signature 'tgrids' c(x, ..., recursive = FALSE) ## S4 method for signature 'tgrid,numeric' e1 + e2 ## S4 method for signature 'tgrid,numeric' e1 * e2 ## S4 method for signature 'tgrids,numeric' e1 + e2 ## S4 method for signature 'tgrids,numeric' e1 * e2
x |
a tgrid object. |
... |
additional tgrid objects. |
recursive |
not used. |
e1 |
tgrid or tgrids object |
e2 |
numeric value |
When items named in this function are found in the input data set (either
data_set()
or idata_set()
), they are copied
into the simulated output. Special items like evid
or amt
or
the like are not copied from the data set per se, but they are copied from
datarecord
objects that are created during the simulation.
carry_out(x, ...) carry.out(x, ...)
carry_out(x, ...) carry.out(x, ...)
x |
model object. |
... |
unquoted names of data items to copy into the simulated output. |
There is also a carry_out
argument to mrgsim()
that can be set to
accomplish the same thing as a call to carry_out
in the pipeline.
carry.out
and carry_out
both do the same thing; using the underscore
version is now preferred.
mod <- mrgsolve::house() e <- ev(amt = 100, ii = 6, addl = 3, WT = 70, dose = amt) out <- mod %>% ev(e) %>% carry_out(amt, dose, WT) %>% mrgsim() head(out)
mod <- mrgsolve::house() e <- ev(amt = 100, ii = 6, addl = 3, WT = 70, dose = amt) out <- mod %>% ev(e) %>% carry_out(amt, dose, WT) %>% mrgsim() head(out)
Use this function to check names of input data sets against parameters that
have been assigned different tags. Assignment is made in the model
specification file. This is useful to alert the user to misspelled or
otherwise misspecified parameter names in input data sets. See param_tags()
for information on associating tags with parameters.
check_data_names( data, x, check_covariates = TRUE, check_inputs = TRUE, tags = NULL, mode = c("warn", "error", "inform"), silent = FALSE )
check_data_names( data, x, check_covariates = TRUE, check_inputs = TRUE, tags = NULL, mode = c("warn", "error", "inform"), silent = FALSE )
data |
a data frame or other object with names to check. |
x |
a model object. |
check_covariates |
logical; if |
check_inputs |
logical; if |
tags |
a character vector of user-defined parameter tags to require
in |
mode |
the default is to |
silent |
silences message on successful check. |
By default, data
will be checked for parameters with the covariates
or
input
tags; these checks can be bypassed with the check_covariates
and check_inputs
arguments. When a parameter name is missing from data
the user will be warned by default. Use mode = "error"
to generate an
error instead of a warning and use mode = "inform"
to simply be informed.
When the user has not tagged any parameters for checking, there will
either be a warning (default) or an error (when mode = "error"
).
It is an error to request a parameter tag via the tags
argument when that
tag is not found in the model.
It is an error to call check_data_names
when no parameters have been tagged
in the model specification file (see param_tags()
).
A logical value is returned; TRUE
if all expected parameters were found
and FALSE
otherwise.
mod <- mcode("ex-cdn", "$PARAM @input \n CL = 1, KA = 2", compile = FALSE) param(mod) # Coding mistake! data <- expand.evd(amt = 100, cl = 2, KA = 5) check_data_names(data, mod) try(check_data_names(data, mod, mode = "error")) check_data_names(data, mod, mode = "inform")
mod <- mcode("ex-cdn", "$PARAM @input \n CL = 1, KA = 2", compile = FALSE) param(mod) # Coding mistake! data <- expand.evd(amt = 100, cl = 2, KA = 5) check_data_names(data, mod) try(check_data_names(data, mod, mode = "error")) check_data_names(data, mod, mode = "inform")
Get the compartment number from a compartment name
cmtn(x, ...) ## S4 method for signature 'mrgmod' cmtn(x, tag, ...)
cmtn(x, ...) ## S4 method for signature 'mrgmod' cmtn(x, tag, ...)
x |
model object. |
... |
not used. |
tag |
compartment name. |
mod <- mrgsolve::house() cmtn(mod, "CENT")
mod <- mrgsolve::house() cmtn(mod, "CENT")
This function is currently not exported, so be sure to call it with
mrgsolve:::code(...)
.
code(x)
code(x)
x |
a model object. |
A character vector of model code.
mod <- mrgsolve::house() mrgsolve:::code(mod) # Alternative as.list(mod)$code
mod <- mrgsolve::house() mrgsolve:::code(mod) # Alternative as.list(mod)$code
This function is called by collapse_omega()
and collapse_sigma()
to
convert multiple matrix blocks into a single matrix block. This "collapsing"
of the matrix list is irreversible.
collapse_matrix(x, range = NULL, name = NULL)
collapse_matrix(x, range = NULL, name = NULL)
x |
an object that inherits from |
range |
numeric vector of length 2 specifying the range of matrices
to collapse in case there are more than 2. The second element may be |
name |
a new name for the collapsed matrix; note that this is the
matrix name, not the labels which alias |
An update matlist
object (either omegalist
or sigmalist
).
collapse_omega()
, collapse_sigma()
, omat()
, smat()
omega <- omat(list(dmat(1, 2), dmat(3, 4, 5))) omega collapse_matrix(omega)
omega <- omat(list(dmat(1, 2), dmat(3, 4, 5))) omega collapse_matrix(omega)
If multiple OMEGA
(or SIGMA
) blocks were written into the model,
these can be collapsed into a single matrix. This will not change the
functionality of the model, but will alter how OMEGA
(or SIGMA
) are
updated, usually making it easier. This "collapsing" of the matrix list
is irreversible.
collapse_omega(x, range = NULL, name = NULL) collapse_sigma(x, range = NULL, name = NULL)
collapse_omega(x, range = NULL, name = NULL) collapse_sigma(x, range = NULL, name = NULL)
x |
a model object. |
range |
numeric vector of length 2 specifying the range of matrices
to collapse in case there are more than 2. The second element may be |
name |
a new name for the collapsed matrix; note that this is the
matrix name, not the labels which alias |
A model object with updated OMEGA
or SIGMA
matrix lists.
code <- ' $OMEGA 1 2 3 $OMEGA 4 5 $OMEGA 6 7 8 9 ' mod <- mcode("collapse-example", code, compile = FALSE) revar(mod) collapse_omega(mod) %>% omat() collapse_omega(mod, range = c(2,3), name = "new_matrix") %>% omat() collapse_omega(mod, range = c(2,NA), name = "new_matrix") %>% omat()
code <- ' $OMEGA 1 2 3 $OMEGA 4 5 $OMEGA 6 7 8 9 ' mod <- mcode("collapse-example", code, compile = FALSE) revar(mod) collapse_omega(mod) %>% omat() collapse_omega(mod, range = c(2,3), name = "new_matrix") %>% omat() collapse_omega(mod, range = c(2,NA), name = "new_matrix") %>% omat()
The input data set (data_set
) is a data frame that specifies
observations, model events, and / or parameter values for a population
of individuals.
data_set(x, data, ...) ## S4 method for signature 'mrgmod,data.frame' data_set( x, data, .subset = TRUE, .select = TRUE, object = NULL, need = NULL, ... ) ## S4 method for signature 'mrgmod,ANY' data_set(x, data, ...) ## S4 method for signature 'mrgmod,ev' data_set(x, data, ...) ## S4 method for signature 'mrgmod,missing' data_set(x, object, ...)
data_set(x, data, ...) ## S4 method for signature 'mrgmod,data.frame' data_set( x, data, .subset = TRUE, .select = TRUE, object = NULL, need = NULL, ... ) ## S4 method for signature 'mrgmod,ANY' data_set(x, data, ...) ## S4 method for signature 'mrgmod,ev' data_set(x, data, ...) ## S4 method for signature 'mrgmod,missing' data_set(x, object, ...)
x |
a model object. |
data |
input data set as a data frame. |
... |
other arguments passed along when |
.subset |
an unquoted expression passed to
|
.select |
passed to |
object |
character name of an object existing in |
need |
passed to |
Input data sets are R
data frames that can include columns
with any valid name, however columns with selected names are
treated specially by mrgsolve and incorporated into the
simulation.
ID
specifies the subject ID and is required for every
input data set.
When columns have the same name as parameters ($PARAM
or $INPUT
in
the model specification file), the values in those columns will
be used to update the corresponding parameter as the simulation
progresses.
Input data set may include the following columns related to
PK dosing events: TIME
, CMT
, AMT
, RATE
, II
, ADDL
, SS
.
Both ID
and TIME
are required columns in the input data set unless
$PRED
is in use. Lower case PK dosing column names including
time
, cmt
, amt
, rate
, ii
, addl
, ss
are also recognized.
However, an error will be generated if a mix of both upper case and lower
case columns in this family are found. Use the functions lctran()
and
uctran()
to convert between upper and lower case naming for these
data items.
TIME
is the observation or event time, CMT
is the compartment number
(see init()
), AMT
is the dosing amount, RATE
is the infusion rate,
II
is the dosing interval, ADDL
specifies additional doses to
administer, and ss
is a flag indicating that the system should be advanced
to a pharmacokinetic steady state prior to administering the dose. These
column names operate similarly to other non-linear mixed effects modeling
software.
EVID
is an integer value specifying the ID of an event record. Values
include:
0: observation
1: dose event, either bolus or infusion
2: other-type event; in mrgsolve, this functions like an observation record, but a discontinuity is created in the simulation at the time of the event (i.e., the ODE solver will stop and restart at the time of the event)
3: reset the system
4: reset the system and dose
8: replace the amount in a compartment
For all EVID
greater than 0
, a discontinuity is created in the
simulation, as described for EVID 2
.
An error will be generated when mrgsolve detects that the data set
is not sorted by time
within an individual. mrgsolve does not allow time
to be reset to zero on records where EVID
is set to 4 (reset and dose).
Only numeric data can be brought in to the problem. Any non-numeric data
columns will be dropped with warning. See numerics_only()
, which is used
to prepare the data set.
An error will be generated if any parameter columns in the
input data set contain missing values (NA
). Likewise, and error will
be generated if missing values are found in the following
columns: ID
, time
/TIME
, rate
/RATE
.
See exdatasets for several example data sets that are provided by mrgsolve.
idata_set()
, ev()
, valid_data_set()
, valid_idata_set()
,
lctran()
, uctran()
.
mod <- mrgsolve::house() data <- expand.ev(ID = seq(3), amt = c(10, 20)) mod %>% data_set(data, ID > 1) %>% mrgsim() data(extran1) head(extran1) mod %>% data_set(extran1) %>% mrgsim() mod %>% mrgsim(data = extran1)
mod <- mrgsolve::house() data <- expand.ev(ID = seq(3), amt = c(10, 20)) mod %>% data_set(data, ID > 1) %>% mrgsim() data(extran1) head(extran1) mod %>% data_set(extran1) %>% mrgsim() mod %>% mrgsim(data = extran1)
This function also allows you to assign different designs to different groups or individuals in a population.
design(x, deslist = list(), descol = character(0), ...)
design(x, deslist = list(), descol = character(0), ...)
x |
model object |
deslist |
a list of |
descol |
the |
... |
not used |
This setup requires the use of an idata_set
, with individual-level
data passed in one ID
per row. For each ID
, specify a
grouping variable in idata
(descol
). For each unique value
of the grouping variable, make one tgrid
object and pass them
in order as ...
or form them into a list and pass as deslist
.
You must assign the idata_set
before assigning the designs in the
command chain (see the example below).
peak <- tgrid(0,6,0.1) sparse <- tgrid(0,24,6) des1 <- c(peak,sparse) des2 <- tgrid(0,72,4) data <- expand.ev(ID = 1:10, amt=c(100,300)) data$GRP <- data$amt/100 idata <- data[,c("ID", "amt")] mod <- mrgsolve::house() mod %>% omat(dmat(1,1,1,1)) %>% carry_out(GRP) %>% idata_set(idata) %>% design(list(des1, des2),"amt") %>% data_set(data) %>% mrgsim() %>% plot(RESP~time|GRP)
peak <- tgrid(0,6,0.1) sparse <- tgrid(0,24,6) des1 <- c(peak,sparse) des2 <- tgrid(0,72,4) data <- expand.ev(ID = 1:10, amt=c(100,300)) data$GRP <- data$amt/100 idata <- data[,c("ID", "amt")] mod <- mrgsolve::house() mod %>% omat(dmat(1,1,1,1)) %>% carry_out(GRP) %>% idata_set(idata) %>% design(list(des1, des2),"amt") %>% data_set(data) %>% mrgsim() %>% plot(RESP~time|GRP)
Extract model details
details(x, complete = FALSE, values = TRUE, ...)
details(x, complete = FALSE, values = TRUE, ...)
x |
a model object |
complete |
logical; if |
values |
logical; if |
... |
not used |
This function is not exported. You will have to call it
with mrgsolve:::details()
.
mod <- mrgsolve::house() mrgsolve:::details(mod)
mod <- mrgsolve::house() mrgsolve:::details(mod)
The $ENV
block is a block of R code that can realize any sort of R object
that might be used in running a model.
env_eval(x, seed = NULL)
env_eval(x, seed = NULL)
x |
a model object. |
seed |
passed to |
Return model environment
env_get(x, tolist = TRUE) env_get_env(x)
env_get(x, tolist = TRUE) env_get_env(x)
x |
a model object. |
tolist |
should the environment be coerced to |
Each model keeps an internal environment that allows the user
to carry any R
object along. Objects are coded in $ENV
.
env_ls(x, ...)
env_ls(x, ...)
x |
a model object. |
... |
passed to |
Update objects in model environment
env_update(.x, ..., .dots = list())
env_update(.x, ..., .dots = list())
.x |
a model object. |
... |
objects to update. |
.dots |
list of objects to updated. |
An event object specifies dosing or other interventions that get implemented during simulation. Event objects do similar things as data_set, but simpler and easier to create.
ev(x, ...) ## S4 method for signature 'mrgmod' ev(x, object = NULL, ...) ## S4 method for signature 'missing' ev( time = 0, amt = 0, evid = 1, cmt = 1, ID = numeric(0), replicate = TRUE, until = NULL, tinf = NULL, realize_addl = FALSE, ... ) ## S4 method for signature 'ev' ev(x, realize_addl = FALSE, ...)
ev(x, ...) ## S4 method for signature 'mrgmod' ev(x, object = NULL, ...) ## S4 method for signature 'missing' ev( time = 0, amt = 0, evid = 1, cmt = 1, ID = numeric(0), replicate = TRUE, until = NULL, tinf = NULL, realize_addl = FALSE, ... ) ## S4 method for signature 'ev' ev(x, realize_addl = FALSE, ...)
x |
a model object. |
... |
other items to be incorporated into the event object; see Details. |
object |
an event object to be added to a model object. |
time |
event time. |
amt |
dose amount. |
evid |
event ID. |
cmt |
compartment number or name. |
ID |
subject ID. |
replicate |
logical; if |
until |
the expected maximum observation time for this regimen;
doses will be scheduled up to, but not including, the |
tinf |
infusion time; if greater than zero, then the |
realize_addl |
if |
Required items in events objects include
time
, amt
, evid
and cmt
.
If not supplied, evid
is assumed to be 1.
If not supplied, cmt
is assumed to be 1.
If not supplied, time
is assumed to be 0.
If amt
is not supplied, an error will be generated.
If total
is supplied, then addl
will be set to total-1
.
Other items can include ii
, ss
, and addl
(see data_set for details on all of these items).
ID
may be specified as a vector.
If replicate is TRUE
(default), then the events
regimen is replicated for each ID
; otherwise, the number of
event rows must match the number of ID
s entered.
ev()
returns an event object.
evd()
, ev_rep()
, ev_days()
, ev_repeat()
, ev_assign()
,
ev_seq()
, mutate.ev()
, as.ev()
, as.evd()
, ev_methods.
mod <- mrgsolve::house() mod <- mod %>% ev(amt = 1000, time = 0, cmt = 1) loading <- ev(time = 0, cmt = 1, amt = 1000) maint <- ev(time = 12, cmt = 1, amt = 500, ii = 12, addl = 10) c(loading, maint) reduced_load <- dplyr::mutate(loading, amt = 750) # Three additional doses in this case e <- ev(amt = 100, ii = 4*7, until = 16*7) e # Last dose is given at 84 realize_addl(e) # Four additional doses with last at 112 in this case e <- ev(amt = 100, ii = 4*7, until = 16*7 + 0.001) realize_addl(e)
mod <- mrgsolve::house() mod <- mod %>% ev(amt = 1000, time = 0, cmt = 1) loading <- ev(time = 0, cmt = 1, amt = 1000) maint <- ev(time = 12, cmt = 1, amt = 500, ii = 12, addl = 10) c(loading, maint) reduced_load <- dplyr::mutate(loading, amt = 750) # Three additional doses in this case e <- ev(amt = 100, ii = 4*7, until = 16*7) e # Last dose is given at 84 realize_addl(e) # Four additional doses with last at 112 in this case e <- ev(amt = 100, ii = 4*7, until = 16*7 + 0.001) realize_addl(e)
Replicate a list of events into a data set
ev_assign(l, idata, evgroup, join = FALSE) assign_ev(...)
ev_assign(l, idata, evgroup, join = FALSE) assign_ev(...)
l |
list of event objects. |
idata |
an idata set (one ID per row). |
evgroup |
the character name of the column in |
join |
if |
... |
used to pass arguments from |
ev_assign()
connects events in a list passed in as the l
argument to
values in the data set identified in the evgroup
argument. For making
assignments, the unique values in the evgroup
column are first sorted so
that the first sorted unique value in evgroup
is assigned to the first
event in l
, the second sorted value in evgroup
column is assigned to the
second event in l
, and so on. This is a change from previous behavior,
which did not sort the unique values in evgroup
prior to making the
assignments.
ev1 <- ev(amt = 100) ev2 <- ev(amt = 300, rate = 100, ii = 12, addl = 10) idata <- data.frame(ID = seq(10)) idata$arm <- 1+(idata$ID %%2) ev_assign(list(ev1, ev2), idata, "arm", join = TRUE)
ev1 <- ev(amt = 100) ev2 <- ev(amt = 300, rate = 100, ii = 12, addl = 10) idata <- data.frame(ID = seq(10)) idata$arm <- 1+(idata$ID %%2) ev_assign(list(ev1, ev2), idata, "arm", join = TRUE)
This function lets you schedule doses on specific days of the week, allowing you to create dosing regimens on Monday/Wednesday/Friday, or Tuesday/Thursday, or every other day (however you want to define that) etc.
ev_days( ev = NULL, days = "", addl = 0, ii = 168, unit = c("hours", "days"), ... )
ev_days( ev = NULL, days = "", addl = 0, ii = 168, unit = c("hours", "days"), ... )
ev |
an event object. |
days |
comma- or space-separated character string of valid days of the the week (see details). |
addl |
additional doses to administer. |
ii |
inter-dose interval; intended use is to keep this at the default value. |
unit |
time unit; the function can only currently handle hours or days. |
... |
event objects named by one of the valid days of the week (see Details). |
Valid names of the week are:
m
for Monday
t
for Tuesday
w
for Wednesday
th
for Thursday
f
for Friday
sa
for Saturday
s
for Sunday
The whole purpose of this function is to schedule doses on specific
days of the week, in a repeating weekly schedule. Please do use caution
when changing ii
from its default value.
# Monday, Wednesday, Friday x 4 weeks e1 <- ev(amt = 100) ev_days(e1, days="m,w,f", addl = 3) # 50 mg Tuesdays, 100 mg Thursdays x 6 months e2 <- ev(amt = 50) ev_days(t = e2, th = e1, addl = 23)
# Monday, Wednesday, Friday x 4 weeks e1 <- ev(amt = 100) ev_days(e1, days="m,w,f", addl = 3) # 50 mg Tuesdays, 100 mg Thursdays x 6 months e2 <- ev(amt = 50) ev_days(t = e2, th = e1, addl = 23)
An event sequence can be replicated a certain number of times in a certain number of IDs.
ev_rep(x, ID = 1, n = NULL, wait = 0, as.ev = FALSE, id = NULL)
ev_rep(x, ID = 1, n = NULL, wait = 0, as.ev = FALSE, id = NULL)
x |
event object. |
ID |
numeric vector if IDs. |
n |
passed to |
wait |
passed to |
as.ev |
if |
id |
deprecated; use |
A single data.frame or event object as
determined by the value of as.ev()
.
e1 <- c(ev(amt=100), ev(amt=200, ii=24, addl=2, time=72)) ev_rep(e1, 1:5)
e1 <- c(ev(amt=100), ev(amt=200, ii=24, addl=2, time=72)) ev_rep(e1, 1:5)
Repeat a block of dosing events
ev_repeat(x, n, wait = 0, as.ev = FALSE)
ev_repeat(x, n, wait = 0, as.ev = FALSE)
x |
event object or dosing data frame. |
n |
number of times to repeat. |
wait |
time to wait between repeats. |
as.ev |
if |
See as.ev
argument.
e1 <- ev(amt = 100, ii = 24, addl = 20) e4 <- ev_repeat(e1, n = 4, wait = 168) mod <- mrgsolve::house() out <- mrgsim(mod, events = e4, end = 3200) plot(out, "CP")
e1 <- ev(amt = 100, ii = 24, addl = 20) e4 <- ev_repeat(e1, n = 4, wait = 168) mod <- mrgsolve::house() out <- mrgsim(mod, events = e4, end = 3200) plot(out, "CP")
See details below for Rx specification. Actual parsing is done
by parse_rx()
; this function can be used to debug Rx inputs.
ev_rx(x, y, ...) ## S4 method for signature 'mrgmod,character' ev_rx(x, y, ...) ## S4 method for signature 'character,missing' ev_rx(x, df = FALSE, ...) parse_rx(x)
ev_rx(x, y, ...) ## S4 method for signature 'mrgmod,character' ev_rx(x, y, ...) ## S4 method for signature 'character,missing' ev_rx(x, df = FALSE, ...) parse_rx(x)
x |
a model object or |
y |
|
... |
not used at this time. |
df |
if |
The method dispatched on model object (mrgmod
) returns another
model object. The character
method returns an event object. The
parse_rx
function return a list named with arguments for the event
object constructor ev()
.
The dose is found at the start of the string by sequential digits; this may be integer, decimal, or specified in scientific notation
Use in
to identify the dosing compartment number; must be integer
Use q
to identify the dosing interval; must be integer or
decimal number (but not scientific notation)
Use over
to indicate an infusion and its duration; integer or
decimal number
Use x
to indicate total number of doses; must be integer
Use then
or ,
to separate dosing periods
Use after
to insert a lag in the start of a period; integer or
decimal number (but not scientific notation)
Use &
to implement multiple doses at the same time
# example("ev_rx") ev_rx("100") ev_rx("100 in 2") ev_rx("100 q12 x 3") ev_rx("100 over 2") ev_rx("100 q 24 x 3 then 50 q12 x 2") ev_rx("100 then 50 q 24 after 12") ev_rx("100.2E-2 q4") ev_rx("100 over 2.23") ev_rx("100 q 12 x 3") ev_rx("100 in 1 & 200 in 2") parse_rx("100 mg q 24 then 200 mg q12")
# example("ev_rx") ev_rx("100") ev_rx("100 in 2") ev_rx("100 q12 x 3") ev_rx("100 over 2") ev_rx("100 q 24 x 3 then 50 q12 x 2") ev_rx("100 then 50 q 24 after 12") ev_rx("100.2E-2 q4") ev_rx("100 over 2.23") ev_rx("100 q 12 x 3") ev_rx("100 in 1 & 200 in 2") parse_rx("100 mg q 24 then 200 mg q12")
Use this function when you want to schedule two or more event objects in time
according the dosing interval (ii
) and additional doses (addl
).
ev_seq(..., ID = NULL, .dots = NULL, id = NULL) ## S3 method for class 'ev' seq(...)
ev_seq(..., ID = NULL, .dots = NULL, id = NULL) ## S3 method for class 'ev' seq(...)
... |
event objects or numeric arguments named |
ID |
numeric vector of subject IDs. |
.dots |
a list of event objects that replaces |
id |
deprecated; use |
Use the generic seq()
when the first argument is an event object. If a
waiting period (wait
or ii
) is the first event, you will need to use
ev_seq()
. When an event object has multiple rows, the end time for that
sequence is taken to be one dosing interval after the event that takes place
on the last row of the event object.
The doses for the next event line start after all of the doses from the previous event line plus one dosing interval from the previous event line (see Examples).
When numerics named wait
or ii
are mixed in with the event objects,
a period with no dosing activity is incorporated into the sequence,
between the adjacent dosing event objects. wait
and ii
accomplish a
similar result, but differ by the starting point for the inactive period.
Use wait
to schedule the next dose relative to the end of the dosing
interval for the previous dose.
Use ii
to schedule the next dose relative to the time of the the previous
dose.
So wait
acts like similar to an event object, by starting the waiting
period from one dosing interval after the last dose while ii
starts the
waiting period from the time of the last dose itself. Both wait
and ii
can accomplish identical behavior depending on whether the last dosing
interval is included (or not) in the value. Values for wait
or ii
can
be negative.
NOTE: .ii
had been available historically as an undocumented feature.
Starting with mrgsolve version 0.11.3
, the argument will be called ii
.
For now, both ii
and .ii
will be accepted but you will get a deprecation
warning if you use .ii
. Please use ii
instead.
Values for time
in any event object act like a prefix time spacer wherever
that event occurs in the event sequence (see Examples).
A single event object sorted by time
.
e1 <- ev(amt = 100, ii = 12, addl = 1) e2 <- ev(amt = 200) seq(e1, e2) seq(e1, ii = 8, e2) seq(e1, wait = 8, e2) seq(e1, ii = 8, e2, ID = seq(10)) ev_seq(ii = 12, e1, ii = 120, e2, ii = 120, e1) seq(ev(amt = 100, ii = 12), ev(time = 8, amt = 200))
e1 <- ev(amt = 100, ii = 12, addl = 1) e2 <- ev(amt = 200) seq(e1, e2) seq(e1, ii = 8, e2) seq(e1, wait = 8, e2) seq(e1, ii = 8, e2, ID = seq(10)) ev_seq(ii = 12, e1, ii = 120, e2, ii = 120, e1) seq(ev(amt = 100, ii = 12), ev(time = 8, amt = 200))
This function calls ev()
to create an event object and then sets the
case attribute so that it renders nmtran data names in upper case. An
object created with evd()
can be used in the same way as an object
created with ev()
.
evd(x, ...) ## S4 method for signature 'mrgmod' evd(x, ...) ## S4 method for signature 'missing' evd(x, ...) ## S4 method for signature 'ev' evd(x, ...) as.evd(x)
evd(x, ...) ## S4 method for signature 'mrgmod' evd(x, ...) ## S4 method for signature 'missing' evd(x, ...) ## S4 method for signature 'ev' evd(x, ...) as.evd(x)
x |
an event object. |
... |
arguments passed to |
Note that evd
isn't a separate class; it is just an ev
object with
a specific case
attribute. See examples which illustrate the difference.
a <- evd(amt = 100) b <- ev(amt = 300) a as.data.frame(a) as_data_set(a, b) as_data_set(b, a) as.data.frame(seq(a, b))
a <- evd(amt = 100) b <- ev(amt = 300) a as.data.frame(a) as_data_set(a, b) as_data_set(b, a) as.data.frame(seq(a, b))
Example input data sets
data(exidata) data(extran1) data(extran2) data(extran3) data(exTheoph) data(exBoot)
data(exidata) data(extran1) data(extran2) data(extran3) data(exTheoph) data(exBoot)
exidata
holds individual-level parameters and other data items, one per row
extran1
is a "condensed" data set
extran2
is a full dataset
extran3
is a full dataset with parameters
exTheoph
is the theophylline data set, ready for input into mrgsolve
exBoot
a set of bootstrap parameter estimates
mod <- mrgsolve::house() %>% update(end=240) %>% Req(CP) ## Full data set data(exTheoph) out <- mod %>% data_set(exTheoph) %>% mrgsim out plot(out) ## Condensed: mrgsolve fills in the observations data(extran1) out <- mod %>% data_set(extran1) %>% mrgsim out plot(out) ## Add a parameter to the data set stopifnot(require(dplyr)) data <- extran1 %>% distinct(ID) %>% select(ID) %>% mutate(CL=exp(log(1.5) + rnorm(nrow(.), 0,sqrt(0.1)))) %>% left_join(extran1,.) data out <- mod %>% data_set(data) %>% carry_out(CL) %>% mrgsim out plot(out) ## idata data(exidata) out <- mod %>% idata_set(exidata) %>% ev(amt=100,ii=24,addl=10) %>% mrgsim plot(out, CP~time|ID)
mod <- mrgsolve::house() %>% update(end=240) %>% Req(CP) ## Full data set data(exTheoph) out <- mod %>% data_set(exTheoph) %>% mrgsim out plot(out) ## Condensed: mrgsolve fills in the observations data(extran1) out <- mod %>% data_set(extran1) %>% mrgsim out plot(out) ## Add a parameter to the data set stopifnot(require(dplyr)) data <- extran1 %>% distinct(ID) %>% select(ID) %>% mutate(CL=exp(log(1.5) + rnorm(nrow(.), 0,sqrt(0.1)))) %>% left_join(extran1,.) data out <- mod %>% data_set(data) %>% carry_out(CL) %>% mrgsim out plot(out) ## idata data(exidata) out <- mod %>% idata_set(exidata) %>% ev(amt=100,ii=24,addl=10) %>% mrgsim plot(out, CP~time|ID)
Insert observations into a data set
expand_observations(data, times, unique = FALSE, obs_pos = -1L)
expand_observations(data, times, unique = FALSE, obs_pos = -1L)
data |
a data set or event object. |
times |
a vector of observation times. |
unique |
|
obs_pos |
determines sorting order for observations; use |
Non-numeric columns will be dropped with a warning.
A data frame with additional rows for added observation records.
data <- expand.ev(amt = c(100, 200, 300)) expand_observations(data, times = seq(0, 48, 2))
data <- expand.ev(amt = c(100, 200, 300)) expand_observations(data, times = seq(0, 48, 2))
These functions expand all combinations of arguments using
expand.grid()
. expand.idata()
generates an idata
set; the others
generate a full data set. The result always has only one row for one
individual. Use expand.evd()
or evd_expand()
to render NMTRAN names
(e.g. AMT
or CMT
) in upper case.
expand.idata(...) expand.ev(...) expand.evd(...) ev_expand(...) evd_expand(...)
expand.idata(...) expand.ev(...) expand.evd(...) ev_expand(...) evd_expand(...)
... |
passed to |
An ID column is added as if not supplied by the user. In the output data frame, ID is always re-written as the row number.
For expand.ev()
, defaults also added include cmt = 1
, time = 0
,
evid = 1
. If total
is included, then addl
is derived as total-1
.
If tinf
is included, then an infusion rate is derived for row where
tinf
is greater than zero.
ev_expand()
is a synonym for expand.ev()
and evd_expand()
is a
synonym for expand.evd()
.
A data frame containing one row for each combination of the items
passed in ...
. The result always has ID set to the row number.
idata <- expand.idata(CL = c(1,2,3), VC = c(10,20,30)) doses <- expand.ev(amt = c(300,100), ii = c(12,24), cmt = 1) infusion <- expand.ev(amt = 100, tinf = 2)
idata <- expand.idata(CL = c(1,2,3), VC = c(10,20,30)) doses <- expand.ev(amt = c(300,100), ii = c(12,24), cmt = 1) infusion <- expand.ev(amt = 100, tinf = 2)
The individual data set (idata_set
) is a data frame with one
row for each individual in a population, specifying parameters and
other individual-level data.
idata_set(x, data, ...) ## S4 method for signature 'mrgmod,data.frame' idata_set( x, data, .subset = TRUE, .select = TRUE, object = NULL, need = NULL, ... ) ## S4 method for signature 'mrgmod,ANY' idata_set(x, data, ...) ## S4 method for signature 'mrgmod,missing' idata_set(x, object, ...)
idata_set(x, data, ...) ## S4 method for signature 'mrgmod,data.frame' idata_set( x, data, .subset = TRUE, .select = TRUE, object = NULL, need = NULL, ... ) ## S4 method for signature 'mrgmod,ANY' idata_set(x, data, ...) ## S4 method for signature 'mrgmod,missing' idata_set(x, object, ...)
x |
model object. |
data |
a data set that can be coerced to data.frame. |
... |
other arguments passed along when |
.subset |
an unquoted expression passed to |
.select |
passed to |
object |
character name of an object existing in |
need |
passed to |
The idata_set
is a data frame that specifies individual-level
data for the problem. An ID
column is required and there
can be no more than one row in the data frame for each individual.
In most cases, the columns in the idata_set
have the same names
as parameters in the param()
list. When this is the case,
the parameter set is updated as the simulation proceeds once at the
start of each individual. The idata_set
can also be used to
set initial conditions for each individual: for a compartment called
CMT
, make a column in idata_set
called CMT_0
and
make the value the desired initial value for that compartment. Note that
this initial condition will be overridden if you also set the CMT_0
in $MAIN
($PK
).
The most common application of idata_set
is to specify a population
or batch of simulations to do. We commonly use idata_set
with an
event object (see ev()
). In that case, the event gets applied
to each individual in the idata_set
.
It is also possible to provide both a data_set
and a idata_set
.
In this case, the idata_set
is used as a parameter lookup for IDs
found in the data_set
. Remember in this case, it is the data_set
(not the idata_set
) that determines the number of individuals in the
simulation.
An error will be generated if any parameter columns in the
input idata set contain NA
.
mod <- mrgsolve::house() data(exidata) exidata mod %>% idata_set(exidata, ID <= 2) %>% ev(amt = 100) %>% mrgsim() %>% plot() mod %>% idata_set(exidata) %>% ev(amt = 100) %>% mrgsim() mod %>% ev(amt = 100) %>% mrgsim(idata=exidata)
mod <- mrgsolve::house() data(exidata) exidata mod %>% idata_set(exidata, ID <= 2) %>% ev(amt = 100) %>% mrgsim() %>% plot() mod %>% idata_set(exidata) %>% ev(amt = 100) %>% mrgsim() mod %>% ev(amt = 100) %>% mrgsim(idata=exidata)
Calling init()
with the model object as the first argument
will return the model initial conditions as a numericlist
object. See numericlist for methods to deal with
cmt_list
objects.
init(.x, ...) ## S4 method for signature 'mrgmod' init(.x, .y = list(), ..., .pat = "*") ## S4 method for signature 'mrgsims' init(.x, ...) ## S4 method for signature 'missing' init(.x, ...) ## S4 method for signature 'list' init(.x, ...) ## S4 method for signature 'ANY' init(.x, ...)
init(.x, ...) ## S4 method for signature 'mrgmod' init(.x, .y = list(), ..., .pat = "*") ## S4 method for signature 'mrgsims' init(.x, ...) ## S4 method for signature 'missing' init(.x, ...) ## S4 method for signature 'list' init(.x, ...) ## S4 method for signature 'ANY' init(.x, ...)
.x |
the model object. |
... |
|
.y |
list to be merged into parameter list. |
.pat |
a regular expression (character) to be applied as a filter when printing compartments to the screen. |
Can be used to either get a compartment list object from a
mrgmod
model object or to update the compartment initial
conditions in a model object. For both uses, the return value
is a cmt_list
object. For the former use, init()
is usually called to print the compartment initial conditions
to the screen, but the cmt_list
object can also be coerced
to a list or numeric R object.
An object of class cmt_list
(see numericlist).
## example("init") mod <- mrgsolve::house() init(mod) init(mod, .pat="^C") ## may be useful for large models class(init(mod)) init(mod)$CENT as.list(init(mod)) as.data.frame(init(mod))
## example("init") mod <- mrgsolve::house() init(mod) init(mod, .pat="^C") ## may be useful for large models class(init(mod)) init(mod)$CENT as.list(init(mod)) as.data.frame(init(mod))
This function has largely been superseded by check_data_names()
.
inventory(x, obj, ..., .strict = FALSE)
inventory(x, obj, ..., .strict = FALSE)
x |
model object. |
obj |
data.frame to pass to |
... |
capture dplyr-style parameter requirements. |
.strict |
whether to stop execution if all requirements are present
( |
If parameter requirements are not explicitly stated, the requirement defaults to
all parameter names in x
. Note that, by default,
the inventory is not .strict
unless the user explicitly
states the parameter requirement. That is, if parameter requirements are explicitly
stated, .strict
will be set to TRUE
if a value .strict
was not
passed in the call.
x
is returned invisibly.
## Not run: inventory(mod, idata, CL:V) # parameters defined, inclusively, CL through Volume inventory(mod, idata, everything()) # all parameters inventory(mod, idata, contains("OCC")) # all parameters containing OCC inventory(mod, idata, -F) # all parameters except F ## End(Not run)
## Not run: inventory(mod, idata, CL:V) # parameters defined, inclusively, CL through Volume inventory(mod, idata, everything()) # all parameters inventory(mod, idata, contains("OCC")) # all parameters containing OCC inventory(mod, idata, -F) # all parameters except F ## End(Not run)
The function checks to see if the object is either
mrgmod
or packmod
.
is.mrgmod(x)
is.mrgmod(x)
x |
any object |
TRUE
if the object inherits from either mrgmod
or packmod
class.
mod <- mrgsolve::house() is.mrgmod(mod)
mod <- mrgsolve::house() is.mrgmod(mod)
Check if an object is mrgsims output
is.mrgsims(x)
is.mrgsims(x)
x |
any object. |
TRUE
if x
inherits mrgsims
.
Previous data set requirements included lower case names for data items
like AMT
and EVID
. Lower case is no longer required. However, it is still
a requirement that nmtran like data column names are either all lower case
or all upper case.
lctran(data, ...) ## S3 method for class 'data.frame' lctran(data, warn = TRUE, ...) ## S3 method for class 'ev' lctran(data, ...) uctran(data, ...) ## S3 method for class 'data.frame' uctran(data, warn = TRUE, ...) ## S3 method for class 'ev' uctran(data, ...)
lctran(data, ...) ## S3 method for class 'data.frame' lctran(data, warn = TRUE, ...) ## S3 method for class 'ev' lctran(data, ...) uctran(data, ...) ## S3 method for class 'data.frame' uctran(data, warn = TRUE, ...) ## S3 method for class 'ev' uctran(data, ...)
data |
a data set with nmtran-like format or an event object. |
... |
for potential future use. |
warn |
if |
Columns that will be renamed with lower or upper case versions:
AMT / amt
II / ii
SS / ss
CMT / cmt
ADDL / addl
RATE / rate
EVID / evid
TIME / time
If both lower and upper case versions of the name are present in the data frame, no changes will be made.
A data frame or event object, with column names possibly converted to upper or lower case.
data <- data.frame(TIME = 0, AMT = 5, II = 24, addl = 2, WT = 80) lctran(data) data <- data.frame(TIME = 0, AMT = 5, II = 24, addl = 2, wt = 80) uctran(data) ev <- evd(amt = 100, evid = 3) uctran(ev) # warning data <- data.frame(TIME = 1, time = 2, CMT = 5) lctran(data)
data <- data.frame(TIME = 0, AMT = 5, II = 24, addl = 2, WT = 80) lctran(data) data <- data.frame(TIME = 0, AMT = 5, II = 24, addl = 2, wt = 80) uctran(data) ev <- evd(amt = 100, evid = 3) uctran(ev) # warning data <- data.frame(TIME = 1, time = 2, CMT = 5) lctran(data)
Once the model is compiled, the model object can be used to re-load the model shared object (the compiled code underlying the mode) when the simulation is to be done in a different R process.
loadso(x, ...) ## S3 method for class 'mrgmod' loadso(x, ...)
loadso(x, ...) ## S3 method for class 'mrgmod' loadso(x, ...)
x |
a model object. |
... |
not used. |
The loadso
function most frequently needs to be used when parallelizing
simulations across worker nodes. The model can be run after calling
loadso
, without requiring that it is re-compiled on worker nodes. It is
likely required that the model is built (and the shared object stored) in
a local directory off of the working R directory (see the second example).
The model object (invisibly).
## Not run: mod <- mread("pk1", modlib()) loadso(mod) mod2 <- mread("pk2", modlib(), soloc = "build") loadso(mod2) ## End(Not run)
## Not run: mod <- mread("pk1", modlib()) loadso(mod) mod2 <- mread("pk2", modlib(), soloc = "build") loadso(mod2) ## End(Not run)
These functions are simple utilities for creating diagonal, block or correlation matrices.
bmat(..., correlation = FALSE, digits = -1) cmat(..., digits = -1) dmat(...)
bmat(..., correlation = FALSE, digits = -1) cmat(..., digits = -1) dmat(...)
... |
matrix data. |
correlation |
logical; if |
digits |
if greater than zero, matrix is passed to |
bmat()
makes a block matrix. cmat()
makes a correlation matrix.
dmat()
makes a diagonal matrix.
A matrix.
dmat(1,2,3)/10 bmat(0.5,0.01,0.2) cmat(0.5, 0.87,0.2)
dmat(1,2,3)/10 bmat(0.5,0.01,0.2) cmat(0.5, 0.87,0.2)
This is a convenience function that ultimately calls mread()
.
Model code is written to a file and read back in using mread()
.
mcode(model, code, project = getOption("mrgsolve.project", tempdir()), ...) mcode_cache( model, code, project = getOption("mrgsolve.project", tempdir()), ... )
mcode(model, code, project = getOption("mrgsolve.project", tempdir()), ...) mcode_cache( model, code, project = getOption("mrgsolve.project", tempdir()), ... )
model |
model name. |
code |
character string specifying a |
project |
project directory for the model. |
... |
passed to |
Note that the arguments are in slightly different order than
mread()
. The default project
is tempdir()
.
See the mread()
help topic for discussion about caching
compilation results with mcode_cache()
.
## Not run: code <- ' $CMT DEPOT CENT $PKMODEL ncmt=1, depot=TRUE $MAIN double CL = 1; double V = 20; double KA = 1; ' mod <- mcode("example", code, compile = FALSE) ## End(Not run)
## Not run: code <- ' $CMT DEPOT CENT $PKMODEL ncmt=1, depot=TRUE $MAIN double CL = 1; double V = 20; double KA = 1; ' mod <- mcode("example", code, compile = FALSE) ## End(Not run)
Pre-coded models are included in the mrgsolve installation; these can be
compiled and loaded with modlib()
. These models are usually most useful
for exploratory simulation or learning mrgsolve. Production simulation work
is typically accomplished by a custom-coded model.
modlib(model = NULL, ..., list = FALSE)
modlib(model = NULL, ..., list = FALSE)
model |
|
... |
passed to |
list |
logical; if |
See modlib_details, modlib_pk, modlib_pkpd, modlib_tmdd, modlib_viral for details.
Call modlib("<modelname>")
to compile and load a mode from the
library.
Call modlib(list=TRUE)
to list available models. Once the model
is loaded (see examples below), call as.list(mod)$code
to extract
model code and equations.
## Not run: mod <- mread("pk1cmt", modlib()) mod <- mread("pk2cmt", modlib()) mod <- mread("pk3cmt", modlib()) mod <- mread("pk1", modlib()) mod <- mread("pk2", modlib()) mod <- mread("popex", modlib()) mod <- mread("irm1", modlib()) mod <- mread("irm2", modlib()) mod <- mread("irm3", modlib()) mod <- mread("irm4", modlib()) mod <- mread("emax", modlib()) mod <- mread("effect", modlib()) mod <- mread("tmdd", modlib()) mod <- mread("viral1", modlib()) mod <- mread("viral2", modlib()) mod <- mread("pred1", modlib()) mod <- mread("pbpk", modlib()) mod <- mread("1005", modlib()) # embedded NONMEM result mod <- mread("nm-like", modlib()) # model with nonmem-like syntax mod <- mread("evtools", modlib()) as.list(mod)$code ## End(Not run)
## Not run: mod <- mread("pk1cmt", modlib()) mod <- mread("pk2cmt", modlib()) mod <- mread("pk3cmt", modlib()) mod <- mread("pk1", modlib()) mod <- mread("pk2", modlib()) mod <- mread("popex", modlib()) mod <- mread("irm1", modlib()) mod <- mread("irm2", modlib()) mod <- mread("irm3", modlib()) mod <- mread("irm4", modlib()) mod <- mread("emax", modlib()) mod <- mread("effect", modlib()) mod <- mread("tmdd", modlib()) mod <- mread("viral1", modlib()) mod <- mread("viral2", modlib()) mod <- mread("pred1", modlib()) mod <- mread("pbpk", modlib()) mod <- mread("1005", modlib()) # embedded NONMEM result mod <- mread("nm-like", modlib()) # model with nonmem-like syntax mod <- mread("evtools", modlib()) as.list(mod)$code ## End(Not run)
modlib: PK/PD Model parameters, compartments, and output variables
EV1
, EV2
: extravascular dosing compartments
CENT
: central PK compartment
PERIPH
: peripheral PK compartment
PERIPH2
: peripheral PK compartment 2
RESP
: response PD compartment (irm models)
CP
: concentration in the central compartment (CENT/VC
)
RESP
: response (emax model)
KA1
, KA2
: first order absorption rate constants
from first and second extravascular compartment (1/time)
CL
: clearance (volume/time)
VC
: volume of distribution, central compartment (volume)
VP
: volume of distribution, peripheral compartment
(volume)
VP2
: volume of distribution, peripheral compartment 2
(volume)
Q
: intercompartmental clearance (volume/time)
Q2
: intercompartmental clearance 2 (volume/time)
VMAX
: maximum rate, nonlinear process (mass/time)
KM
: Michaelis constant (mass/volume)
K10
: elimination rate constant (1/time); CL/VC
K12
: rate constant for transfer to peripheral compartment
from central (1/time); Q/VC
K21
: rate constant for transfer to central compartment from
peripheral (1/time); Q/VP
E0
: baseline effect (emax model)
EMAX
, IMAX
: maximum effect (response)
EC50
, IC50
: concentration producing 50 percent of
effect (mass/volume)
KIN
: zero-order response production rate (irm models)
(response/time)
KOUT
: first-order response elimination rate (irm models)
(1/time)
n
: sigmoidicity factor
KEO
: rate constant for transfer to effect compartment
(1/time)
modlib: Pharmacokinetic models
... |
passed to update |
See modlib_details
for more detailed descriptions of
parameters and compartments.
The pk1cmt
model is parameterized in terms of CL
, VC
,
KA1
and KA2
and uses compartments EV1
,
EV2
, and CENT
. The pk2cmt
model adds a PERIPH
compartment and parameters Q
and VP
to that of the
one-compartment model. Likewise, the three-compartment model (pk3cmt
)
adds PERIPH2
and parameters Q2
and VP2
to
that of the two-compartment models. All pk models also have parameters
VMAX
(defaulting to zero, no non-linear clearance) and KM
.
an object of class packmod
All pk models have two extravascular dosing compartments and potential for linear and nonlinear clearance.
pk1cmt
: one compartment pk model using ODEs
pk2cmt
: two compartment pk model using ODEs
pk3cmt
: three compartment pk model using ODEs
pk1
: one compartment pk model in closed-form
pk2
: two compartment pk model in closed-form
popex
: a simple population pk model
modlib: Pharmacokinetic / pharmacodynamic models
See modlib_details
for more detailed descriptions of
parameters and compartments.
All PK/PD models include 2-compartment PK model with absorption from
2 extravascular compartments and linear + nonlinear clearance. The
PK models are parameterized with CL
, VC
, Q
,
VMAX
, KM
, KA1
and KA2
and implement
compartments EV1
, EV2
, CENT
, PERIPH
.
The indirect response models have compartment RESP
and the emax
model has output variable RESP
. PD parameters include KIN
,
KOUT
, IC50
, EC50
, IMAX
, EMAX
, E0
,
and n
.
Also, once the model is loaded, use see
method for
mrgmod
to view the model code.
irm1
inhibition of response production
irm2
inhibition of response loss
irm3
stimulation of response production
irm4
stimulation of response loss
pd_effect
effect compartment model
emax
sigmoid emax model
modlib: Target mediated disposition model
... |
passed to update |
KEL
: elimination rate constant
KTP
: tissue to plasma rate constant
KPT
: plasma to tissue rate constant
VC
: volume of distribution
KA1
, KA2
: absorption rate constants
KINT
: internalization rate constant
KON
: association rate constant
KOFF
: dissociation rate constant
KSYN
: target synthesis rate
KDEG
: target degredation rate constant
CENT
: unbound drug in central compartment
TISS
: unbound drug in tissue compartment
REC
: concentration of target
RC
: concentration of drug-target complex
EV1
, EV2
: extravascular dosing compartments
CP
: unbound drug in the central compartment
TOTAL
: total concentration of target (complexed and uncomplexed)
modlib: HCV viral dynamics models
viral1
: viral dynamics model with single HCV species
viral2
: viral dynamics model with wild-type and mutant
HCV species
s
: new hepatocyte synthesis rate (cells/ml/day)
d
: hepatocyte death rate constant (1/day)
p
: viral production rate constant (copies/cell/day)
beta
: new infection rate constant (ml/copy/day)
delta
: infected cell death rate constant (1/day)
c
: viral clearance rate constant (1/day)
fit
: mutant virus fitness
N
: non-target hepatocytes
mu
: forward mutation rate
Tmax
: maximum number of target hepatocytes (cells/ml)
rho
: maximum hepatocyte regeneration rate (1/day)
T
: uninfected target hepatocytes (cells/ml)
I
: productively infected hepatocytes (cells/ml)
V
: hepatitis C virus (copies/ml)
IM
: mutant infected hepatocytes (cells/ml)
VM
: mutant hepatitis C virus (copies/ml)
expos
: exposure metric to drive pharmacodynamic model
mread()
reads and parses the mrgsolve model specification file,
builds the model, and returns a model object for simulation.
mread_cache()
does the same, but caches the compilation result for
later use. mread_file()
can be used for convenience, taking the model
file name as the first argument.
mread( model, project = getOption("mrgsolve.project", getwd()), code = NULL, file = NULL, udll = TRUE, ignore.stdout = TRUE, raw = FALSE, compile = TRUE, audit = TRUE, quiet = getOption("mrgsolve_mread_quiet", FALSE), check.bounds = FALSE, warn = TRUE, soloc = getOption("mrgsolve.soloc", tempdir()), capture = NULL, preclean = FALSE, recover = FALSE, ... ) mread_cache( model = NULL, project = getOption("mrgsolve.project", getwd()), file = paste0(model, ".cpp"), code = NULL, soloc = getOption("mrgsolve.soloc", tempdir()), quiet = FALSE, preclean = FALSE, capture = NULL, ... ) mread_file(file, ...)
mread( model, project = getOption("mrgsolve.project", getwd()), code = NULL, file = NULL, udll = TRUE, ignore.stdout = TRUE, raw = FALSE, compile = TRUE, audit = TRUE, quiet = getOption("mrgsolve_mread_quiet", FALSE), check.bounds = FALSE, warn = TRUE, soloc = getOption("mrgsolve.soloc", tempdir()), capture = NULL, preclean = FALSE, recover = FALSE, ... ) mread_cache( model = NULL, project = getOption("mrgsolve.project", getwd()), file = paste0(model, ".cpp"), code = NULL, soloc = getOption("mrgsolve.soloc", tempdir()), quiet = FALSE, preclean = FALSE, capture = NULL, ... ) mread_file(file, ...)
model |
model name. |
project |
location of the model specification file an any
headers to be included; see also the discussion about model; this argument
can be set via |
code |
a character string with model specification code to be used instead of a model file. |
file |
the full file name (with extension, but without path) where the model is specified. |
udll |
use unique name for shared object. |
ignore.stdout |
passed to system call when compiling the model; set this
to |
raw |
if |
compile |
logical; if |
audit |
check the model specification file for errors. |
quiet |
don't print messages from mrgsolve when compiling. |
check.bounds |
check boundaries of parameter list. |
warn |
logical; if |
soloc |
the directory location where the model shared object is built
and stored; see details; this argument can be set via |
capture |
a character vector or comma-separated string of additional
model variables to capture; these variables will be added to the capture
list for the current call to |
preclean |
logical; if |
recover |
if |
... |
passed to |
The model
argument is required. For typical use,
the file
argument is omitted and the value
for file
is generated from the value for model
.
To determine the source file name, mrgsolve will look for
a file extension in model
. A file extension is
assumed when it finds a period followed by one to three alpha-numeric
characters at the end of the string (e.g. mymodel.txt
but not
my.model
). If no file extension is found, the extension .cpp
is assumed (e.g. file
is <model-name>.cpp
). If a file
extension is found, file
is <model-name>
.
Best practice is to avoid using .
in model
unless
you are using model
to point to the model specification
file name. Otherwise, use mread_file()
.
Use the soloc
argument to specify a directory location for building
the model. This is the location where the model shared object will be
stored on disk. The default is a temporary directory, so compilation
artifacts are lost when R restarts when the default is used. Changing
soloc
to a persistent directory location will preserve those
artifacts across R restarts. Also, if simulation from a single model is
being done in separate processes on separate compute nodes, it might be
necessary to store these compilation artifacts in a local directory
to make them accessible to the different nodes. If the soloc
directory does not exist, mread()
will attempt to create it.
Similarly, using mread_cache()
will cache results in the temporary
directory and the cache cannot be accessed after the R process is
restarted.
mrgsolve comes bundled with several pre-coded PK, PK/PD, and
other systems models that are accessible via the mread()
interface.
Models available in the library include:
PK models: pk1cmt
, pk2cmt
, pk3cmt
, pk1
, pk2
, popex
, tmdd
PKPD models: irm1
, irm2
, irm3
, irm4
, emax
, effect
Other models: viral1
, viral2
When the library model is accessed, mrgsolve will compile and load
the model as you would for any other model. It is only necessary to
reference the correct model name and point the project
argument
to the mrgsolve model library location via modlib()
.
For more details, see modlib_pk, modlib_pkpd, modlib_tmdd, modlib_viral, and modlib_details for more information about the state variables and parameters in each model.
## Not run: code <- ' $PARAM CL = 1, VC = 5 $CMT CENT $ODE dxdt_CENT = -(CL/VC)*CENT; ' mod <- mcode("ex_mread", code) mod mod %>% init(CENT=1000) %>% mrgsim() %>% plot() mod <- mread("irm3", modlib()) # if the model is in the file mymodel.cpp mod <- mread("mymodel") # if the model is in the file mymodel.txt mod <- mread(file = "mymodel.txt") or mod <- mread_file("mymodel.txt") ## End(Not run)
## Not run: code <- ' $PARAM CL = 1, VC = 5 $CMT CENT $ODE dxdt_CENT = -(CL/VC)*CENT; ' mod <- mcode("ex_mread", code) mod mod %>% init(CENT=1000) %>% mrgsim() %>% plot() mod <- mread("irm3", modlib()) # if the model is in the file mymodel.cpp mod <- mread("mymodel") # if the model is in the file mymodel.txt mod <- mread(file = "mymodel.txt") or mod <- mread_file("mymodel.txt") ## End(Not run)
Read back models written to file using mwrite_yaml()
. Function
yaml_to_cpp()
is also provided to convert the yaml file to mrgsolve cpp
file format.
mread_yaml( file, model = basename(file), project = tempdir(), update = FALSE, ... ) yaml_to_cpp(file, model = basename(file), project = getwd(), update = TRUE)
mread_yaml( file, model = basename(file), project = tempdir(), update = FALSE, ... ) yaml_to_cpp(file, model = basename(file), project = getwd(), update = TRUE)
file |
the yaml file name. |
model |
a new model name to use when calling |
project |
the directory where the model should be built. |
update |
|
... |
passed to |
Note that yaml_to_cpp()
by default writes model settings into the cpp
file. mread_yaml()
does not write model settings into the file but rather
update the model object directly with data read back from the yaml
file.
A model object.
mod <- house() temp <- tempfile(fileext = ".yaml") mwrite_yaml(mod, file = temp) # Note: this model is not compiled mod <- mread_yaml(temp, model = "new-house", compile = FALSE) mod cppfile <- yaml_to_cpp(temp, project = tempdir()) readLines(cppfile)
mod <- house() temp <- tempfile(fileext = ".yaml") mwrite_yaml(mod, file = temp) # Note: this model is not compiled mod <- mread_yaml(temp, model = "new-house", compile = FALSE) mod cppfile <- yaml_to_cpp(temp, project = tempdir()) readLines(cppfile)
This function sets up the simulation run from data stored in the model
object as well as arguments passed in. Use mrgsim_q()
instead
to benchmark mrgsolve or to do repeated quick simulation for tasks like
parameter optimization, sensitivity analyses, or optimal design. See
mrgsim_variants for other mrgsim-like functions that have more focused
inputs. mrgsim_df
coerces output to data.frame prior to returning.
mrgsim(x, data = NULL, idata = NULL, events = NULL, nid = NULL, ...) mrgsim_df(..., output = "df") do_mrgsim( x, data, idata = no_idata_set(), carry_out = carry.out, carry.out = character(0), recover = character(0), seed = as.integer(NA), Request = character(0), output = NULL, capture = NULL, obsonly = FALSE, obsaug = FALSE, tgrid = NULL, etasrc = "omega", recsort = 1, deslist = list(), descol = character(0), filbak = TRUE, tad = FALSE, nocb = TRUE, skip_init_calc = FALSE, ss_n = 500, ss_fixed = FALSE, interrupt = 256, ... )
mrgsim(x, data = NULL, idata = NULL, events = NULL, nid = NULL, ...) mrgsim_df(..., output = "df") do_mrgsim( x, data, idata = no_idata_set(), carry_out = carry.out, carry.out = character(0), recover = character(0), seed = as.integer(NA), Request = character(0), output = NULL, capture = NULL, obsonly = FALSE, obsaug = FALSE, tgrid = NULL, etasrc = "omega", recsort = 1, deslist = list(), descol = character(0), filbak = TRUE, tad = FALSE, nocb = TRUE, skip_init_calc = FALSE, ss_n = 500, ss_fixed = FALSE, interrupt = 256, ... )
x |
the model object. |
data |
NMTRAN-like data set (see |
idata |
a matrix or data frame of model parameters,
one parameter per row (see |
events |
an event object. |
nid |
integer number of individuals to simulate; only used if idata and data are missing. |
... |
passed to |
output |
if |
carry_out |
numeric data items to copy into the output. |
carry.out |
soon to be deprecated; use |
recover |
character column names in either |
seed |
deprecated. |
Request |
compartments or captured variables to retain
in the simulated output; this is different than the |
capture |
character file name used for debugging (not related
to |
obsonly |
if |
obsaug |
augment the data set with time grid observations; when
|
tgrid |
a tgrid object; or a numeric vector of simulation times
or another object with an |
etasrc |
source for |
recsort |
record sorting flag. Default value is 1. Possible values
are 1,2,3,4: 1 and 2 put doses in a data set after padded observations at
the same time; 3 and 4 put those doses before padded observations at the
same time. 2 and 4 will put doses scheduled through |
deslist |
a list of tgrid objects. |
descol |
the name of a column for assigning designs. |
filbak |
carry data items backward when the first data set row has time greater than zero. |
tad |
when |
nocb |
if |
skip_init_calc |
don't use |
ss_n |
maximum number of iterations for determining steady state for
the PK system; a warning will be issued if steady state is not achieved
within |
ss_fixed |
if |
interrupt |
integer check user interrupt interval; when |
Use mrgsim_df()
to return a data frame rather than
mrgsims
object.
Both data
and idata
will be coerced to numeric matrix
carry_out
can be used to insert data columns into the output
data set. This is partially dependent on the nature of the data brought
into the problem.
When using data
and idata
together, an error is
generated if an ID occurs in data
but not idata
.
Also, when looking up data in idata
, ID in idata
is
assumed to be uniquely keyed to ID in data
. No error is
generated if ID is duplicated in data
; parameters will be used
from the first occurrence found in idata
.
carry_out
: idata
is assumed to be individual-level and variables that
are carried from idata
are repeated throughout the individual's simulated
data. Variables carried from data
are carried via last-observation carry
forward. NA
is returned from observations that are inserted into
simulated output that occur prior to the first record in data
.
recover
: this is similar to carry_out
with respect to
end result, but it uses a different process. Columns to be recovered are
cached prior to running the simulation, and then joined back on to the
simulated data. So, whereas carry_out
will only accept numeric
data items, recover
can handle data frame columns of any type. There
is a small decrease in performance with recover
compared to
carry_out
, but it is likely that the performance difference is
difficult to perceive (when the simulation runs very fast) or only a small
fractional increase in run time when the simulation is very large. And any
performance hit is likely to be well worth it in light of the convenience
gain. Just think carefully about using this feature when every millisecond
counts.
etasrc
: this argument lets you control where ETA(n)
come from in the
model. When etasrc
is set to "omega"
(the default), ETAs
will be
simulated from a multivariate normal distribution defined by the $OMEGA
blocks in the model. Alternatively, input data
or idata
sets can be used
to pass in fixed ETA(n)
by setting etasrc
to "data"
, "idata"
,
"data.all"
or "idata.all"
. When etasrc
is set to "data"
or "data.all"
,
the input data set will be scanned for columns called ETA1
, ETA2
, ...,
ETAn
and those values will be copied into the appropriate slot in the
ETA()
vector. Only the first record for each individual will be copied into
ETA()
; all records after the first will be ignored. When there are more
than 9
ETAs
in a model, NONMEM will start naming the outputs ET10
,
ET11
etc rather than ETA10
and ETA11
. When mrgsolve is looking for
these columns, it will first search, for example, ET10
and use that value
if it is found. If ET10
isn't found and there are more than 9
ETAs
,
then it will also search for ETA10
. An error will be generated in case
mrgsolve finds both the ETA
and ET
name variant for the tenth and higher
ETA
(e.g. it is an error to have both ETA10
and ET10
in the data set).
When mrgsolve is searching for ETA
columns in the data set, it will
only look for ETAn
up to the number of rows (or columns) in all the
model $OMEGA
blocks. For example, if $OMEGA
is 5x5, only ETA1
through
ETA5
will be searched. An error will be generated in case mrgsolve finds
no columns with ETAn
names and something other than etasrc = "omega"
was passed. When etasrc = "data"
and an ETAn
column is missing from the
data set, the missing ETA()
will be set to 0
. Alternatively, the user
can pass etasrc = "data.all"
which causes an error to be generated if any
ETAn
is missing from the data set. Use this option when you intend to have
all ETAs
attached to the data set and want an error generated if mrgsolve
finds one or more of them is missing. Using etasrc ="idata"
or
"idata.all"
, the behavior is identical to "data"
(or "data.all"
),
except mrgsolve will look at the idata set rather than data set.
An object of class mrgsims.
## example("mrgsim") e <- ev(amt = 1000) mod <- mrgsolve::house() out <- mod %>% ev(e) %>% mrgsim() plot(out) out <- mod %>% ev(e) %>% mrgsim(end=22) out data(exTheoph) out <- mod %>% data_set(exTheoph) %>% mrgsim() out out <- mod %>% mrgsim(data=exTheoph) out <- mrgsim(mod, data=exTheoph, obsonly=TRUE) out out <- mod %>% mrgsim(data=exTheoph, obsaug=TRUE, carry_out="a.u.g") out out <- mod %>% ev(e) %>% mrgsim(outvars="CP,RESP") out a <- ev(amt = 1000, group = 'a') b <- ev(amt = 750, group = 'b') data <- as_data_set(a,b) out <- mrgsim_d(mod, data, recover="group") out
## example("mrgsim") e <- ev(amt = 1000) mod <- mrgsolve::house() out <- mod %>% ev(e) %>% mrgsim() plot(out) out <- mod %>% ev(e) %>% mrgsim(end=22) out data(exTheoph) out <- mod %>% data_set(exTheoph) %>% mrgsim() out out <- mod %>% mrgsim(data=exTheoph) out <- mrgsim(mod, data=exTheoph, obsonly=TRUE) out out <- mod %>% mrgsim(data=exTheoph, obsaug=TRUE, carry_out="a.u.g") out out <- mod %>% ev(e) %>% mrgsim(outvars="CP,RESP") out a <- ev(amt = 1000, group = 'a') b <- ev(amt = 750, group = 'b') data <- as_data_set(a,b) out <- mrgsim_d(mod, data, recover="group") out
Use the function when you would usually use mrgsim_d()
,
but you need a quicker turnaround time. The timing differences
might be difficult to detect for a single simulation run
but could become appreciable with repeated simulation. See
Details for important differences in how mrgsim_q()
is invoked compared to mrgsim()
and mrgsim_d()
.
This function should always be used for benchmarking simulation time with
mrgsolve.
mrgsim_q( x, data, recsort = 1, stime = numeric(0), output = "mrgsims", skip_init_calc = FALSE, simcall = 0, etasrc = "omega" )
mrgsim_q( x, data, recsort = 1, stime = numeric(0), output = "mrgsims", skip_init_calc = FALSE, simcall = 0, etasrc = "omega" )
x |
a model object. |
data |
a simulation data set. |
recsort |
record sorting flag. |
stime |
a numeric vector of observation times; these observation
times will only be added to the output if there are no observation
records in |
output |
output data type; if |
skip_init_calc |
don't use |
simcall |
not used; only the default value of 0 is allowed. |
etasrc |
source for ETA() values in the model; values can include:
"omega", |
mrgsim_q()
mainly cuts some of the overhead from the simulation. So, the
primary efficiency gain from using mrgsim_q()
comes when the simulation
executes very quickly. It is unlikely you will see a big performance
difference between mrgsim_q()
and mrgsim()
when the model is difficult to
solve or if there is a large input data set.
This function does not support the piped simulation workflow. All
arguments must be passed into the function except for x
.
A data set is required for this simulation workflow. The data set can have only dosing records or doses with observations. When the data set only includes doses, a single numeric vector of observation times should be passed in.
This simulation workflow does not support Req
(request)
functionality. All compartments and captured variables will
always be returned in the simulation output.
This simulation workflow does not support carry-out functionality.
This simulation workflow does not accept arguments to be passed
to update()
. This must be done by a separate
call to update()
.
This simulation workflow does not support use of event objects. If
an event object is needed, it should be converted to a data set
prior to the simulation run (see as_data_set()
or
as.data.frame()
).
This simulation workflow does not support idata sets or any
feature enabled by idata
set use. Individual level parameters
should be joined onto the data set prior to simulation. Otherwise
mrgsim_i()
or mrgsim_ei()
should be used.
By default, a mrgsims object is returned (as with mrgsim()
).
Use the output = "df"
argument to request a plain
data.frame of simulated data on return.
By default, an object of class mrgsims
. Use output = "df"
to return
a data frame.
mrgsim()
, mrgsim_variants, qsim()
mod <- mrgsolve::house() data <- expand.ev(amt = c(100, 300, 1000)) out <- mrgsim_q(mod, data) out
mod <- mrgsolve::house() data <- expand.ev(amt = c(100, 300, 1000)) out <- mrgsim_q(mod, data) out
These functions are called by mrgsim()
and have
explicit input requirements written into the function name. The motivation
behind these variants is to give the user a clear workflow with specific,
required inputs as indicated by the function name. Use
mrgsim_q()
instead to benchmark mrgsolve or to do repeated quick
simulation for tasks like parameter optimization, sensitivity analyses,
or optimal design.
mrgsim_e(x, events, idata = NULL, data = NULL, ...) mrgsim_d(x, data, idata = NULL, events = NULL, ...) mrgsim_ei(x, events, idata, data = NULL, ...) mrgsim_di(x, data, idata, events = NULL, ...) mrgsim_i(x, idata, data = NULL, events = NULL, ...) mrgsim_0(x, idata = NULL, data = NULL, events = NULL, ...)
mrgsim_e(x, events, idata = NULL, data = NULL, ...) mrgsim_d(x, data, idata = NULL, events = NULL, ...) mrgsim_ei(x, events, idata, data = NULL, ...) mrgsim_di(x, data, idata, events = NULL, ...) mrgsim_i(x, idata, data = NULL, events = NULL, ...) mrgsim_0(x, idata = NULL, data = NULL, events = NULL, ...)
x |
the model object. |
events |
an event object. |
idata |
a matrix or data frame of model parameters,
one parameter per row (see |
data |
NMTRAN-like data set (see |
... |
passed to |
Important: all of these functions require that
data
, idata
, and/or events
be pass directly to the functions. They
will not recognize these inputs from a pipeline.
mrgsim_e
simulate using an event object
mrgsim_ei
simulate using an event object and idata_set
mrgsim_d
simulate using a data_set
mrgsim_di
simulate using a data_set
and idata_set
mrgsim_i
simulate using a idata_set
mrgsim_0
simulate using just the model
mrgsim_q
simulate from a data set with quicker turnaround (see
mrgsim_q()
)
These methods modify the data in a mrgsims object and return a data frame. Contrast with the functions in mrgsims_modify.
## S3 method for class 'mrgsims' pull(.data, ...) ## S3 method for class 'mrgsims' filter(.data, ...) ## S3 method for class 'mrgsims' group_by(.data, ..., add = FALSE, .add = FALSE) ## S3 method for class 'mrgsims' distinct(.data, ..., .keep_all = FALSE) ## S3 method for class 'mrgsims' mutate(.data, ...) ## S3 method for class 'each' summarise(.data, funs, ...) ## S3 method for class 'mrgsims' summarise(.data, ...) ## S3 method for class 'mrgsims' do(.data, ..., .dots) ## S3 method for class 'mrgsims' select(.data, ...) ## S3 method for class 'mrgsims' slice(.data, ...) as_data_frame.mrgsims(x, ...) ## S3 method for class 'mrgsims' as_tibble(x, ...) as.tbl.mrgsims(x, ...)
## S3 method for class 'mrgsims' pull(.data, ...) ## S3 method for class 'mrgsims' filter(.data, ...) ## S3 method for class 'mrgsims' group_by(.data, ..., add = FALSE, .add = FALSE) ## S3 method for class 'mrgsims' distinct(.data, ..., .keep_all = FALSE) ## S3 method for class 'mrgsims' mutate(.data, ...) ## S3 method for class 'each' summarise(.data, funs, ...) ## S3 method for class 'mrgsims' summarise(.data, ...) ## S3 method for class 'mrgsims' do(.data, ..., .dots) ## S3 method for class 'mrgsims' select(.data, ...) ## S3 method for class 'mrgsims' slice(.data, ...) as_data_frame.mrgsims(x, ...) ## S3 method for class 'mrgsims' as_tibble(x, ...) as.tbl.mrgsims(x, ...)
.data |
an mrgsims object; passed to various |
... |
passed to other methods |
add |
passed to dplyr::group_by (for dplyr < |
.add |
passed to dplyr::group_by (for dplyr >= |
.keep_all |
passed to dplyr::distinct |
funs |
passed to dplyr::summarise_each |
.dots |
passed to various |
x |
mrgsims object. |
For the select_sims
function, the dots ...
must be either
compartment names or variables in $CAPTURE
. An error will be
generated if no valid names are selected or the names for selection are
not found in the simulated output.
out <- mrgsim(house(), events = ev(amt = 100), end = 5, delta=1) dplyr::filter(out, time==2) dplyr::mutate(out, label = "abc") dplyr::select(out, time, RESP, CP)
out <- mrgsim(house(), events = ev(amt = 100), end = 5, delta=1) dplyr::filter(out, time==2) dplyr::mutate(out, label = "abc") dplyr::select(out, time, RESP, CP)
These functions modify the simulated data in an mrgsims object and return the modified object. Contrast with the functions in mrgsims_dplyr.
mutate_sims(.data, ...) select_sims(.data, ...) filter_sims(.data, ...)
mutate_sims(.data, ...) select_sims(.data, ...) filter_sims(.data, ...)
.data |
a mrgsims object. |
... |
other arguments passed to the |
out <- mrgsim(house(), events = ev(amt = 100)) filter_sims(out, time > 2) mutate_sims(out, label = "abc") select_sims(out, RESP, CP)
out <- mrgsim(house(), events = ev(amt = 100)) filter_sims(out, time > 2) mutate_sims(out, label = "abc") select_sims(out, RESP, CP)
dplyr verbs for event objects
## S3 method for class 'ev' mutate(.data, ...) ## S3 method for class 'ev' select(.data, ...) ## S3 method for class 'ev' filter(.data, ...)
## S3 method for class 'ev' mutate(.data, ...) ## S3 method for class 'ev' select(.data, ...) ## S3 method for class 'ev' filter(.data, ...)
.data |
the event object. |
... |
passed to the |
Model code is written to a file in native mrgsolve format. This
can be useful for (1) breaking connection to NONMEM modeling outputs that
are imported by $NMXML
or $NMEXT
and (2) saving model updates (e.g.,
an updated parameter list). Models can be read back using mread()
.
mwrite_cpp(x, file, update = TRUE)
mwrite_cpp(x, file, update = TRUE)
x |
a model object. |
file |
output file name; if non-character (e.g., |
update |
|
See important details in mwrite_yaml()
.
A list containing data that was written out to the cpp file, with added
item file
, is returned invisibly.
temp <- tempfile(fileext = ".mod") mod <- modlib("pk1", compile = FALSE) x <- mwrite_cpp(mod, file = temp) mod <- mread(x$file, compile = FALSE) mod
temp <- tempfile(fileext = ".mod") mod <- modlib("pk1", compile = FALSE) x <- mwrite_cpp(mod, file = temp) mod <- mread(x$file, compile = FALSE) mod
Model code is written to a readable, transport format. This transport format
can be useful for (1) breaking connection to NONMEM modeling outputs that
are imported by $NMXML
or $NMEXT
and (2) saving model updates (e.g.,
an updated parameter list). Models can be read back using mread_yaml()
or
converted to mrgsolve cpp format with yaml_to_cpp()
.
mwrite_yaml(x, file, digits = 8)
mwrite_yaml(x, file, digits = 8)
x |
a model object. |
file |
output file name; if non-character (e.g., |
digits |
precision to use when writing outputs. |
Parameters and omega and sigma matrices that were imported via $NMXML
or $NMEXT
will be written into the yaml file and the NONMEM import blocks
will be dropped. This allows the user to load a model based on a NONMEM run
without having a connection to that output (e.g., root.xml
or root.ext
).
Given that the connection to the NONMEM modeling outputs is broken when
writing to yaml, any update to the NONMEM run will only be propagated to
the yaml file when mwrite_yaml()
is run again.
The yaml file does not currently have the ability to track
other external dependencies, such as user-defined header files or other
code that might be sourced in by the user when the model is loaded via
mread()
. NONMEM xml and ext files imported by $NMXML
or $NMEXT
are
the only external dependencies that are accounted for in the yaml
transport file.
A list containing data that was written out to the yaml file, with added
item file
, is returned invisibly.
mod <- house() temp1 <- tempfile(fileext = ".yaml") x <- mwrite_yaml(mod, temp1) readLines(temp1)
mod <- house() temp1 <- tempfile(fileext = ".yaml") x <- mwrite_yaml(mod, temp1) readLines(temp1)
Get all names from a model object
## S4 method for signature 'mrgmod' names(x)
## S4 method for signature 'mrgmod' names(x)
x |
the model object |
mod <- mrgsolve::house() names(mod)
mod <- mrgsolve::house() names(mod)
Import model estimates from a NONMEM ext file
nmext( run = NA_real_, project = getwd(), file = paste0(run, ".ext"), path = NULL, root = c("working", "cppfile"), index = "last", theta = TRUE, omega = TRUE, sigma = TRUE, olabels = NULL, slabels = NULL, oprefix = "", sprefix = "", tname = "THETA", oname = "...", sname = "...", read_fun = "data.table", env = NULL )
nmext( run = NA_real_, project = getwd(), file = paste0(run, ".ext"), path = NULL, root = c("working", "cppfile"), index = "last", theta = TRUE, omega = TRUE, sigma = TRUE, olabels = NULL, slabels = NULL, oprefix = "", sprefix = "", tname = "THETA", oname = "...", sname = "...", read_fun = "data.table", env = NULL )
run |
run number. |
project |
project directory. |
file |
deprecated; use |
path |
full path to NONMEM |
root |
the directory that |
index |
the estimation number to return; "last" will return the last estimation results; otherwise, pass an integer indicating which estimation results to return. |
theta |
logical; if TRUE, the |
omega |
logical; if TRUE, the |
sigma |
logical; if TRUE, the |
olabels |
labels for |
slabels |
labels for |
oprefix |
prefix for |
sprefix |
prefix for |
tname |
name for |
oname |
name for |
sname |
name for |
read_fun |
function to use when reading the |
env |
internal use only. |
Import model estimates from a NONMEM xml file
nmxml( run = numeric(0), project = character(0), file = character(0), path = character(0), root = c("working", "cppfile"), theta = TRUE, omega = TRUE, sigma = TRUE, olabels = NULL, slabels = NULL, oprefix = "", sprefix = "", tname = "THETA", oname = "...", sname = "...", index = "last", xpath = ".//nm:estimation", env = NULL )
nmxml( run = numeric(0), project = character(0), file = character(0), path = character(0), root = c("working", "cppfile"), theta = TRUE, omega = TRUE, sigma = TRUE, olabels = NULL, slabels = NULL, oprefix = "", sprefix = "", tname = "THETA", oname = "...", sname = "...", index = "last", xpath = ".//nm:estimation", env = NULL )
run |
run number. |
project |
project directory. |
file |
deprecated; use |
path |
the complete path to the |
root |
the directory that |
theta |
logical; if TRUE, the |
omega |
logical; if TRUE, the |
sigma |
logical; if TRUE, the |
olabels |
labels for |
slabels |
labels for |
oprefix |
prefix for |
sprefix |
prefix for |
tname |
name for |
oname |
name for |
sname |
name for |
index |
the estimation number to return; "last" will return the last estimation results; otherwise, pass an integer indicating which estimation results to return. |
xpath |
xml path containing run results; if the default doesn't work,
consider using |
env |
internal use only. |
If run
and project
are supplied, the .xml
file is
assumed to be located in run.xml
, in directory run
off the project
directory. If file
is supplied,
run
and project
arguments are ignored.
This function requires that the xml2 package
be installed and loadable. If requireNamespace("xml2")
fails, an error will be generated.
nmxml
usually expects to find run results in the xpath called
.//nm:estimation
. Occasionally, the run results are not stored in
this namespace but no namespaces are found in the xml file. In this case,
the user can specify the xpath containing run results. Consider trying
.//estimation
as an alternative if the default fails.
A list with theta, omega and sigma elements, depending on what was requested.
nmext
if(requireNamespace("xml2")) { proj <- system.file("nonmem", package = "mrgsolve") mrgsolve:::nmxml(run = 1005, project = proj) }
if(requireNamespace("xml2")) { proj <- system.file("nonmem", package = "mrgsolve") mrgsolve:::nmxml(run = 1005, project = proj) }
Prepare data.frame for input to mrgsim()
numerics_only(x, quiet = FALSE, convert_lgl = FALSE)
numerics_only(x, quiet = FALSE, convert_lgl = FALSE)
x |
a input data set. |
quiet |
logical indicating whether or not warnings should be printed. |
convert_lgl |
if |
Augment observations in the simulated output
obsaug(x, value = TRUE, ...)
obsaug(x, value = TRUE, ...)
x |
model object |
value |
the value for |
... |
passed along
There is also a |
Collect only observation records in the simulated output
obsonly(x, value = TRUE, ...)
obsonly(x, value = TRUE, ...)
x |
model object. |
value |
use 'TRUE' to collect and return observation records only. |
... |
not used. |
There is also an 'obsonly' argument to [mrgsim()] that can be set to accomplish the same thing as a call to 'obsonly()' in the pipeline.
The primary function is omat()
that can be used to both get the
$OMEGA
matrices out of a model object and to update $OMEGA
matrices in a model object.
omat(.x, ...) ## S4 method for signature 'missing' omat(.x, ...) ## S4 method for signature 'matrix' omat(.x, ..., labels = list()) ## S4 method for signature 'NULL' omat(.x, ...) ## S4 method for signature 'list' omat(.x, ...) ## S4 method for signature 'omegalist' omat(.x, ...) ## S4 method for signature 'mrgmod' omat(.x, ..., make = FALSE, open = FALSE) ## S4 method for signature 'mrgsims' omat(.x, make = FALSE, ...)
omat(.x, ...) ## S4 method for signature 'missing' omat(.x, ...) ## S4 method for signature 'matrix' omat(.x, ..., labels = list()) ## S4 method for signature 'NULL' omat(.x, ...) ## S4 method for signature 'list' omat(.x, ...) ## S4 method for signature 'omegalist' omat(.x, ...) ## S4 method for signature 'mrgmod' omat(.x, ..., make = FALSE, open = FALSE) ## S4 method for signature 'mrgsims' omat(.x, make = FALSE, ...)
.x |
a matrix, list of matrices or |
... |
passed to other functions, including |
labels |
character vector of names for |
make |
logical; if |
open |
passed to |
x |
|
smat()
, dmat()
, bmat()
, cmat()
# example("omega") mat1 <- matrix(1) mat2 <- diag(c(1,2,3)) mat3 <- matrix(c(0.1, 0.002, 0.002, 0.5), 2,2) mat4 <- dmat(0.1, 0.2, 0.3, 0.4) omat(mat1) omat(mat1, mat2, mat3) omat(A = mat1, B = mat2, C = mat3) mod <- mrgsolve::house() %>% omat(mat4) omat(mod) omat(mod, make = TRUE) as.matrix(omat(mod))
# example("omega") mat1 <- matrix(1) mat2 <- diag(c(1,2,3)) mat3 <- matrix(c(0.1, 0.002, 0.002, 0.5), 2,2) mat4 <- dmat(0.1, 0.2, 0.3, 0.4) omat(mat1) omat(mat1, mat2, mat3) omat(A = mat1, B = mat2, C = mat3) mod <- mrgsolve::house() %>% omat(mat4) omat(mod) omat(mod, make = TRUE) as.matrix(omat(mod))
Outputs can include model compartments or variables defined in the model
that have been marked to capture
in simulated output.
outvars(x, unlist = FALSE)
outvars(x, unlist = FALSE)
x |
model object. |
unlist |
if |
When unlist
is FALSE
(default) : a named list, with cmt
showing names
of output compartments and capture
giving names of output variables in
capture. When unlist
is TRUE
, then a single, unnamed character vector
of outvar names is returned.
mod <- mrgsolve::house() outvars(mod)
mod <- mrgsolve::house() outvars(mod)
See numericlist for methods to deal with parameter_list
objects.
param(.x, ...) ## S4 method for signature 'mrgmod' param(.x, .y = NULL, ..., .pat = "*", .strict = FALSE) ## S4 method for signature 'mrgsims' param(.x, ...) ## S4 method for signature 'missing' param(..., .strict = TRUE) ## S4 method for signature 'list' param(.x, ...) ## S4 method for signature 'ANY' param(.x, ...) allparam(.x)
param(.x, ...) ## S4 method for signature 'mrgmod' param(.x, .y = NULL, ..., .pat = "*", .strict = FALSE) ## S4 method for signature 'mrgsims' param(.x, ...) ## S4 method for signature 'missing' param(..., .strict = TRUE) ## S4 method for signature 'list' param(.x, ...) ## S4 method for signature 'ANY' param(.x, ...) allparam(.x)
.x |
the model object. |
... |
passed along or name/value pairs to update the parameters
in a model object; when passing new values this way, all values
must be numeric and all all names must exist in the parameter list
for |
.y |
an object to be merged into parameter list; non- |
.pat |
a regular expression (character) to be applied as a filter for which parameters to show when printing. |
.strict |
if |
Can be used to either get a parameter list object from a mrgmod
model object or to update the parameters in a model object.
For both uses, the return value is a parameter_list
object. For the
former use, param()
is usually called to print the parameters to the
screen, but the parameter_list
object can also be coerced to a list
or numeric R object.
Use allparam()
to get a parameter_list
object including
both model parameters and data items listed in $FIXED
.
The update to parameters can be permissive (candidates with names that don't
exist in the parameter list are silently ignored) or strict (all candidates
must already exist in the parameter list). When passing candidate values
via ...
, the update is strict and an error is generated if you pass a
name that isn't found in the parameter list. When candidate values
are passed as a named object via .y
, then the update is permissive. Any
permissive update can be made strict (error if foreign names are found in
the candidates) by passing .strict = TRUE
.
An alternative is to assess the incoming names using inventory()
.
An object of class parameter_list
(see numericlist).
## example("param") mod <- house() param(mod) param(mod, .pat="^(C|F)") ## may be useful when large number of parameters class(param(mod)) param(mod)$KA param(mod)[["KA"]] as.list(param(mod)) as.data.frame(param(mod)) mod <- param(mod, CL = 1.2) new_values <- list(CL = 1.3, VC = 20.5) mod <- param(mod, new_values)
## example("param") mod <- house() param(mod) param(mod, .pat="^(C|F)") ## may be useful when large number of parameters class(param(mod)) param(mod)$KA param(mod)[["KA"]] as.list(param(mod)) as.data.frame(param(mod)) mod <- param(mod, CL = 1.2) new_values <- list(CL = 1.3, VC = 20.5) mod <- param(mod, new_values)
Use this function if you added the @covariates
or @input
attributes or
specified a user-defined tag (via @tag
) in one or more parameter blocks
and need to extract that information. Also, using the $INPUT
block to
declare parameters will automatically add the input
tag (via @input
).
Once these attributes / tags are added, you can use check_data_names()
to
reconcile names of input data sets against tagged model parameters.
param_tags(x)
param_tags(x)
x |
mrgsolve model object. |
A data frame listing parameter names and their tags.
Note: it is good practice to tag parameters where appropriate with input
or covariates
as these will automatically be expected on input data when
you call check_data_names()
. User-defined tags are also possible, but you
will need to alert check_data_names()
to look for them.
Model Specification Examples
You can use the $INPUT
block to add the input
tag on these parameters
$INPUT STUDY = 101, WT = 70, DVID = 1
Tag some covariates in the model
$PARAM @covariates WT = 70, SEX = 1, EGFR = 110
A user-defined tag
$PARAM @tag flags FFLAG = 1, DFLAG = 0
mod <- mrgsolve::house() param_tags(mod)
mod <- mrgsolve::house() param_tags(mod)
Parse PKMODEL BLOCK data
PKMODEL( ncmt = 1, depot = FALSE, cmt = NULL, trans = pick_trans(ncmt, depot), env = list(), pos = 1, ... )
PKMODEL( ncmt = 1, depot = FALSE, cmt = NULL, trans = pick_trans(ncmt, depot), env = list(), pos = 1, ... )
ncmt |
number of compartments; must be 1 (one-compartment, not including a depot dosing compartment) or 2 (two-compartment model, not including a depot dosing compartment) |
depot |
logical indicating whether to add depot compartment |
cmt |
compartment names as comma-delimited character |
trans |
the parameterization for the PK model; must be 1, 2, 4, or 11 |
env |
parse environment |
pos |
block position number |
... |
not used |
When using $PKMODEL
, certain symbols must be defined in the
model specification depending on the value of ncmt
, depot
and trans
.
ncmt
1, depot FALSE
, trans 2: CL
, V
ncmt
1, depot TRUE
, trans 2: CL
, V
,
KA
ncmt
2, depot FALSE
, trans 4: CL
, V1
,
Q
, V2
ncmt
2, depot TRUE
, trans 4: CL
, V2
,
Q
, V3
, KA
If trans=11
is specified, use the symbols listed above for the
ncmt
/ depot
combination, but append i
at the end
(e.g. CLi
or Qi
or KAi
).
If trans=1
, the user must utilize the following symbols:
pred_CL
for clearance
pred_V
or pred_V2
for central compartment volume of
distribution
pred_Q
for intercompartmental clearance
pred_V3
for for peripheral compartment volume of distribution
pred_KA
for absorption rate constant
Generate a quick plot of simulated data
## S4 method for signature 'mrgsims,missing' plot(x, limit = 16, ...) ## S4 method for signature 'mrgsims,formula' plot( x, y, limit = 16, show.grid = TRUE, outer = TRUE, type = "l", lwd = 2, ylab = "value", groups = ID, scales = list(y = list(relation = "free")), logy = FALSE, logbr = 1, ... ) ## S4 method for signature 'mrgsims,character' plot(x, y, ...)
## S4 method for signature 'mrgsims,missing' plot(x, limit = 16, ...) ## S4 method for signature 'mrgsims,formula' plot( x, y, limit = 16, show.grid = TRUE, outer = TRUE, type = "l", lwd = 2, ylab = "value", groups = ID, scales = list(y = list(relation = "free")), logy = FALSE, logbr = 1, ... ) ## S4 method for signature 'mrgsims,character' plot(x, y, ...)
x |
mrgsims object |
limit |
limit the the number of panels to create |
... |
other arguments passed to xyplot |
y |
formula used for plotting |
show.grid |
logical indicating whether or not to draw panel.grid |
outer |
passed to xyplot |
type |
passed to xyplot |
lwd |
passed to xyplot |
ylab |
passed to xyplot |
groups |
passed to xyplot |
scales |
passed to xyplot |
logy |
plot the y variables on log scale |
logbr |
log scale breaks indicator; use |
mod <- mrgsolve::house(end=48, delta=0.2) %>% init(GUT=1000) out <- mrgsim(mod) plot(out) plot(out, subset=time <=24) plot(out, GUT+CP~.) plot(out, CP+RESP~time, col="black", scales="same", lty=2) ## Not run: plot(out, "CP RESP, GUT") ## End(Not run)
mod <- mrgsolve::house(end=48, delta=0.2) %>% init(GUT=1000) out <- mrgsim(mod) plot(out) plot(out, subset=time <=24) plot(out, GUT+CP~.) plot(out, CP+RESP~time, col="black", scales="same", lty=2) ## Not run: plot(out, "CP RESP, GUT") ## End(Not run)
Plot data as an mrgsims object
plot_sims(.data, ..., .f = NULL, .dots = list())
plot_sims(.data, ..., .f = NULL, .dots = list())
.data |
a data frame |
... |
unquoted column names to plot on y-axis |
.f |
a formula to plot |
.dots |
extra arguments passed to |
This function is only intended for use with data frames that
were created by modifying an mrgsims
object.
mod <- mrgsolve::house() %>% ev(amt = 100) out <- mrgsim(mod) out_df <- dplyr::mutate(out, time <= 72) plot(out) plot_sims(out, CP, RESP) ## Not run: plot_sims(out, .f = ~ CP + RESP) plot_sims(out, .f = CP + RESP ~ time) ## End(Not run)
mod <- mrgsolve::house() %>% ev(amt = 100) out <- mrgsim(mod) out_df <- dplyr::mutate(out, time <= 72) plot(out) plot_sims(out, CP, RESP) ## Not run: plot_sims(out, .f = ~ CP + RESP) plot_sims(out, .f = CP + RESP ~ time) ## End(Not run)
Plot method for mrgsims objects
## S4 method for signature 'batch_mrgsims,missing' plot(x, yval = variables(x), auto.key = list(), mincol = 3, ...) ## S4 method for signature 'batch_mrgsims,formula' plot( x, y, show.grid = TRUE, lwd = 2, type = "l", yval = variables(x), auto.key = list(columns = 1), scales = list(y = list(relation = "free")), ... )
## S4 method for signature 'batch_mrgsims,missing' plot(x, yval = variables(x), auto.key = list(), mincol = 3, ...) ## S4 method for signature 'batch_mrgsims,formula' plot( x, y, show.grid = TRUE, lwd = 2, type = "l", yval = variables(x), auto.key = list(columns = 1), scales = list(y = list(relation = "free")), ... )
x |
mrgsims object |
yval |
y variables to plot |
auto.key |
passed to xyplot |
mincol |
minimum number of columns in key |
... |
arguments passed to xyplot |
y |
a formula passed to xyplot |
show.grid |
print grid in the plot |
lwd |
passed to xyplot |
type |
passed to xyplot |
scales |
passed to xyplot |
This is just a lighter version of mrgsim()
, with fewer options but with
better efficiency in certain cases. See Details.
qsim( x, data, idata = no_idata_set(), obsonly = FALSE, tgrid = NULL, recsort = 1, tad = FALSE, Req = NULL, outvars = Req, skip_init_calc = FALSE, output = "mrgsims" )
qsim( x, data, idata = no_idata_set(), obsonly = FALSE, tgrid = NULL, recsort = 1, tad = FALSE, Req = NULL, outvars = Req, skip_init_calc = FALSE, output = "mrgsims" )
x |
the model object. |
data |
can be either event object or data set. |
idata |
a matrix or data frame of model parameters,
one parameter per row (see |
obsonly |
if |
tgrid |
a tgrid object; or a numeric vector of simulation times
or another object with an |
recsort |
record sorting flag. Default value is 1. Possible values
are 1,2,3,4: 1 and 2 put doses in a data set after padded observations at
the same time; 3 and 4 put those doses before padded observations at the
same time. 2 and 4 will put doses scheduled through |
tad |
when |
Req |
synonym for |
outvars |
output items to request; if missing, then only captured items will be returned in the output. |
skip_init_calc |
don't use |
output |
output data type; the default is |
qsim()
mainly cuts some of the overhead from the simulation. So, the
primary efficiency gain from using qsim()
comes when the simulation
executes very quickly. It is unlikely you will see a big performance
difference between qsim()
and mrgsim()
when the model is difficult to
solve or if there is a large input data set.
There is no pipeline interface for this function; all configuration options
(see Arguments) must be passed as formal arguments to the function.
You can't carry_out
, Request
specific columns, or pass items in for update.
Some other limitations, but only convenience-related. See Arguments for
available options. Specifically, there is no ...
argument for this function.
Use the update()
method to update the model object.
mrgsim_q()
, mrgsim()
, mrgsim_variants
mod <- mrgsolve::house() dose <- ev(amt = 100) out <- qsim(mod,dose)
mod <- mrgsolve::house() dose <- ev(amt = 100) out <- qsim(mod,dose)
This function retrieves NONMEM estimates for use in the mrgsolve model when
$NMEXT
is invoked. See nmext()
.
read_nmext( run = NA_real_, project = getwd(), file = paste0(run, ".ext"), path = NULL, read_fun = c("data.table", "read.table"), index = "last" )
read_nmext( run = NA_real_, project = getwd(), file = paste0(run, ".ext"), path = NULL, read_fun = c("data.table", "read.table"), index = "last" )
run |
a run number or run identifier. |
project |
the NONMEM project directory. |
file |
the |
path |
full path and file name for |
read_fun |
function to read the |
index |
selects the table number whose results will be returned;
use value "last" to select the last table in the |
A list with param, omega, and sigma in a format ready to be used to update a model object.
project <- system.file("nonmem", package = "mrgsolve") est <- read_nmext(1005, project = project) est$param est$omega est$sigma est <- read_nmext(2005, project = project, index = 3)
project <- system.file("nonmem", package = "mrgsolve") est <- read_nmext(1005, project = project) est$param est$omega est$sigma est <- read_nmext(2005, project = project, index = 3)
When doses are scheduled with ii
and addl
, the object is expanded to
include one record for every dose. In the result, no record with have
ii
or addl
set to non-zero value.
realize_addl(x, ...) ## S3 method for class 'data.frame' realize_addl( x, warn = FALSE, mark_new = FALSE, fill = c("inherit", "na", "locf"), ... ) ## S3 method for class 'ev' realize_addl(x, ...)
realize_addl(x, ...) ## S3 method for class 'data.frame' realize_addl( x, warn = FALSE, mark_new = FALSE, fill = c("inherit", "na", "locf"), ... ) ## S3 method for class 'ev' realize_addl(x, ...)
x |
a |
... |
not used. |
warn |
if |
mark_new |
if |
fill |
specifies how to handle non-dose related data columns in new data set records; this option is critical when handling data sets with time-varying, non-dose-related data items; see Details. |
If no addl
column is found the data frame is returned and
a warning is issued if warn
is true. If ii
,
time
, or evid
are missing, an error is generated.
If a grouped data.frame (via dplyr::group_by()
) is passed, it will be
ungrouped.
Use caution when passing in data that has non-dose-related data
columns that vary within a subject and pay special attention
to the fill
argument. By definition, realize_addl()
will add new rows to your data frame and it is not obvious
how the non-dose-related data should be handled in these new
rows. When inherit
is chosen, the new records have
non-dose-related data that is identical to the originating
dose record. This should be fine when these data items are not
varying with time, but will present a problem when the data
are varying with time. When locf
is chosen,
the missing data are filled in with NA
and an
last observation carry forward operation is applied to
every column in the data set. This may not be what
you want if you already had missing values in the input
data set and want to preserve that missingness. When na
is chosen, the missing data are filled in with NA
and
no locf
operation is applied. But note that these
missing values may be problematic for a mrgsolve simulation
run. If you have any time-varying columns or missing data
in your data set, be sure to check that the output from
this function is what you were expecting.
A data.frame or event object, consistent with the type of x
.
The ii
and addl
columns will all be set to zero. The result is always
ungrouped.
e <- ev(amt = 100, ii = 12, addl = 3) realize_addl(e) a <- ev(amt = 100, ii = 12, addl = 2, WT = 69) b <- ev(amt = 200, ii = 24, addl = 2, WT = 70) c <- ev(amt = 50, ii = 6, addl = 2, WT = 71) e <- ev_seq(a,b,c) realize_addl(e, mark_new = TRUE)
e <- ev(amt = 100, ii = 12, addl = 3) realize_addl(e) a <- ev(amt = 100, ii = 12, addl = 2, WT = 69) b <- ev(amt = 200, ii = 24, addl = 2, WT = 70) c <- ev(amt = 50, ii = 6, addl = 2, WT = 71) e <- ev_seq(a,b,c) realize_addl(e, mark_new = TRUE)
Render a model to a document
render(x, ...) ## S4 method for signature 'character' render(x, project = NULL, ...) ## S4 method for signature 'mrgmod' render(x, ...) dorender(model, project, template = NULL, compile = TRUE, ...)
render(x, ...) ## S4 method for signature 'character' render(x, project = NULL, ...) ## S4 method for signature 'mrgmod' render(x, ...) dorender(model, project, template = NULL, compile = TRUE, ...)
x |
model object or the model name |
... |
passed to |
project |
the directory containing the |
model |
model name |
template |
template document |
compile |
logical; if true, the model will be compiled to run |
## Not run: mod <- mrgsolve::house() mrgsolve:::render(mod) mrgsolve:::render("irm2", modlib()) ## End(Not run)
## Not run: mod <- mrgsolve::house() mrgsolve:::render(mod) mrgsolve:::render("irm2", modlib()) ## End(Not run)
Use this function to select, by name, either compartments or derived variables that have been captured (see CAPTURE) into the simulated output.
Req(x, ...) req(x, ...) ## S3 method for class 'mrgmod' req(x, ...)
Req(x, ...) req(x, ...) ## S3 method for class 'mrgmod' req(x, ...)
x |
model object. |
... |
unquoted names of compartments or tabled items. |
There is also a Req
argument to mrgsim()
that can
be set to accomplish the same thing as a call to Req
in
the pipeline.
Note the difference between req
and Req
: the former only
selects compartments to appear in output while the latter selects both
compartments and captured items. Also, when there are items explicitly
listed in Req
, all other compartments or captured items not listed
there are ignored. But when compartments are selected with req
all of the captured items are returned. Remember that req
is
strictly for compartments.
mod <- mrgsolve::house() mod %>% Req(CP,RESP) %>% ev(amt=1000) %>% mrgsim()
mod <- mrgsolve::house() mod %>% Req(CP,RESP) %>% ev(amt=1000) %>% mrgsim()
Reserved words
reserved()
reserved()
Note: this function is not exported; you must go into the
mrgsolve
namespace by using the mrgsolve:::
prefix.
mrgsolve:::reserved()
mrgsolve:::reserved()
Use this function to extract both OMEGA and SIGMA matrices from a model object. Typical use is for display on the R console.
revar(x, ...) ## S4 method for signature 'mrgmod' revar(x, ...)
revar(x, ...) ## S4 method for signature 'mrgmod' revar(x, ...)
x |
model object. |
... |
passed along. |
A named list containing omega
and sigma
matrices.
mod <- mrgsolve::house() revar(mod)
mod <- mrgsolve::house() revar(mod)
This is a simple way to display the model code on the R console using
the model object. The raw
argument will return the model code as a
character vector.
see(x, ...) ## S4 method for signature 'mrgmod' see(x, raw = FALSE, ...)
see(x, ...) ## S4 method for signature 'mrgmod' see(x, raw = FALSE, ...)
x |
model object. |
... |
not used. |
raw |
return the raw code. |
NULL
is returned invisibly when raw
is FALSE
; when raw
is
set to TRUE
, the model code is returned as a character vector.
The primary function is smat()
which can be used to both get the
$SIGMA
matrices out of a model object and to update $SIGMA
matrices in a model object.
smat(.x, ...) ## S4 method for signature 'missing' smat(.x, ...) ## S4 method for signature 'matrix' smat(.x, ..., labels = list()) ## S4 method for signature 'list' smat(.x, ...) ## S4 method for signature 'sigmalist' smat(.x, ...) ## S4 method for signature 'mrgmod' smat(.x, ..., make = FALSE, open = FALSE) ## S4 method for signature 'NULL' smat(.x, ...) ## S4 method for signature 'mrgsims' smat(.x, make = FALSE, ...)
smat(.x, ...) ## S4 method for signature 'missing' smat(.x, ...) ## S4 method for signature 'matrix' smat(.x, ..., labels = list()) ## S4 method for signature 'list' smat(.x, ...) ## S4 method for signature 'sigmalist' smat(.x, ...) ## S4 method for signature 'mrgmod' smat(.x, ..., make = FALSE, open = FALSE) ## S4 method for signature 'NULL' smat(.x, ...) ## S4 method for signature 'mrgsims' smat(.x, make = FALSE, ...)
.x |
a matrix, list of matrices or |
... |
passed to other functions, including |
labels |
character vector of names for |
make |
logical; if |
open |
passed to |
x |
|
## example("sigma") mat1 <- matrix(1) mat2 <- diag(c(1,2)) mat3 <- matrix(c(0.1, 0.002, 0.002, 0.5), 2,2) mat4 <- dmat(0.1, 0.2, 0.3, 0.4) smat(mat1) smat(mat1, mat2, mat3) smat(A=mat1, B=mat2, C=mat3) mod <- mrgsolve::house() %>% smat(mat1) smat(mod) smat(mod, make=TRUE)
## example("sigma") mat1 <- matrix(1) mat2 <- diag(c(1,2)) mat3 <- matrix(c(0.1, 0.002, 0.002, 0.5), 2,2) mat4 <- dmat(0.1, 0.2, 0.3, 0.4) smat(mat1) smat(mat1, mat2, mat3) smat(A=mat1, B=mat2, C=mat3) mod <- mrgsolve::house() %>% smat(mat1) smat(mod) smat(mod, make=TRUE)
As a model object navigates a pipeline prior to simulation, arguments are
collected to eventually be passed to mrgsim()
. simargs()
lets you
intercept and possibly clear those arguments.
simargs(x, which = NULL, clear = FALSE, ...)
simargs(x, which = NULL, clear = FALSE, ...)
x |
model object. |
which |
character with length 1 naming a single arg to get. |
clear |
logical indicating whether or not to clear |
... |
not used. |
If clear
is TRUE
, the argument list is
cleared and the model object is returned. Otherwise, the argument
list is returned.
mod <- mrgsolve::house() mod %>% Req(CP, RESP) %>% carry_out(evid, WT, FLAG) %>% simargs()
mod <- mrgsolve::house() mod %>% Req(CP, RESP) %>% carry_out(evid, WT, FLAG) %>% simargs()
This is also the directory where the model is built, which could be the
value of tempdir()
.
soloc(x, short = FALSE)
soloc(x, short = FALSE)
x |
model object. |
short |
logical; if |
A string containing the full path to the model shared object.
mod <- mrgsolve::house() soloc(mod)
mod <- mrgsolve::house() soloc(mod)
These are settings for the differential equation
solver (lsoda
) that can be accessed via
the R interface. The code listing below is taken directly
from the lsoda
source code.
The following items can be set
hmax
(HMAX
below); decrease hmax
when
you want to limit how big of a step the solver can take when
integrating from one time to the next time. However be aware
that smaller hmax
will result in longer run times.
hmin
(HMIN
below); don't fiddle with this
unless you know what you're doing.
ixpr
(IXPR
below)
maxsteps
(MXSTEP
below); increase this
number when the solver has a long interval between
two integration times (e.g. when observation records are
far apart).
mxhnil
(MXHNIL below
); don't usually
modify this one
atol
- the absolute solver tolerance; decrease
this number (e.g. to 1E-10 or 1E-20 or 1E-50) when the
value in a compartment can get extremely small; without this
extra (lower) tolerance, the value can get so low that the number
can randomly become negative. However be aware that more precision
here will result in longer run times.
rtol
- the relative solver tolerances; decrease this
number when you want a more precise solution. However be aware
that more precision here will result in longer run times.
Print summary of a mrgmod object
## S3 method for class 'mrgmod' summary(object, ...)
## S3 method for class 'mrgmod' summary(object, ...)
object |
a mrgmod object |
... |
not used |
Re-scale time in the simulated output
tscale(x, value = 1, ...)
tscale(x, value = 1, ...)
x |
model object. |
value |
value by which time will be scaled. |
... |
not used. |
There is also a tscale
argument to mrgsim()
that can
be set to accomplish the same thing as a call to tscale
in
the pipeline.
# The model is in hours: mod <- mrgsolve::house() # The output is in days: mod %>% tscale(1/24) %>% mrgsim()
# The model is in hours: mod <- mrgsolve::house() # The output is in days: mod %>% tscale(1/24) %>% mrgsim()
After the model object is created, update various attributes.
## S4 method for signature 'mrgmod' update(object, ..., merge = TRUE, open = FALSE, data = NULL, strict = TRUE) ## S4 method for signature 'omegalist' update(object, y, ...) ## S4 method for signature 'sigmalist' update(object, y, ...) ## S4 method for signature 'parameter_list' update(object, .y, ...)
## S4 method for signature 'mrgmod' update(object, ..., merge = TRUE, open = FALSE, data = NULL, strict = TRUE) ## S4 method for signature 'omegalist' update(object, y, ...) ## S4 method for signature 'sigmalist' update(object, y, ...) ## S4 method for signature 'parameter_list' update(object, .y, ...)
object |
a model object. |
... |
named items to update. |
merge |
logical indicating to merge (rather than replace) new and existing attributes. |
open |
logical; used only when merge is |
data |
a list of items to update; this list is combined
with any items passed in via |
strict |
if |
y |
another object involved in update |
.y |
data to update |
Slots that can be updated:
verbose
debug
preclean
mindt
digits
atol - absolute solver tolerance; see solversettings
rtol - relative solver tolerance; see solversettings
ss_rtol - relative tolerance when finding steady state
ss_atol - absolute tolerance when finding steady state
ixpr - see IXPR
in solversettings
mxhnil - see MXHNIL
in solversettings
hmin - see HMIN
in solversettings
hmax - see HMAX
in solversettings
maxsteps - see MXSTEP
in solversettings
start, end, delta, add
tscale
request
param
init
omega
sigma
outvars
The updated model object is returned.
## Not run: mod <- house() mod <- update(mod, end = 120, delta = 4, param = list(CL = 19.1)) ## End(Not run)
## Not run: mod <- house() mod <- update(mod, end = 120, delta = 4, param = list(CL = 19.1)) ## End(Not run)
This function is called by mrgsim()
and friends to check and prepare
input data sets for simulation. Users may also call this function to
pre-validate data when the same data set is used for repeated simulation.
valid_data_set(x, m = NULL, verbose = FALSE, quiet = FALSE) valid_data_set.matrix(x, verbose = FALSE)
valid_data_set(x, m = NULL, verbose = FALSE, quiet = FALSE) valid_data_set.matrix(x, verbose = FALSE)
x |
data.frame or matrix. |
m |
a model object. |
verbose |
logical. |
quiet |
if |
An error will be issued when
non-numeric data is found in columns sharing names with model parameters
non-numeric data is found in reserved data items related to dosing
(see mrgsolve:::GLOBALS$CARRY_TRAN
)
a column is found that is "internally classed", including columns that
inherit from integer64
(see is.object()
)
A matrix with non-numeric columns dropped; if x is a
data.frame with character cmt
column comprised of valid
compartment names and m
is a model object,
the cmt
column will be converted to the corresponding
compartment number.
valid_idata_set()
, idata_set()
, data_set()
mod <- mrgsolve::house() data(exTheoph) d <- valid_data_set(exTheoph, mod)
mod <- mrgsolve::house() data(exTheoph) d <- valid_data_set(exTheoph, mod)
This function is called by mrgsim()
and friends to check and prepare
input data sets for simulation. Users may also call this function to
pre-validate data when the same data set is used for repeated simulation.
valid_idata_set(x, m, verbose = FALSE, quiet = FALSE)
valid_idata_set(x, m, verbose = FALSE, quiet = FALSE)
x |
data.frame or matrix. |
m |
a model object. |
verbose |
logical. |
quiet |
if |
An error will be issued when
non-numeric data is found in columns sharing names with model parameters
a column is found that is internally classed, including columns that
inherit from integer64
(see is.object()
)
A numeric matrix with class valid_idata_set
.
valid_data_set()
, idata_set()
, data_set()
The main use case for using within rather than update or param or init is when you want to update to a new value that is calculated from the existing value. See the example in details
## S3 method for class 'mrgmod' within(data, expr, ...)
## S3 method for class 'mrgmod' within(data, expr, ...)
data |
an object with class mrgmod |
expr |
expressions evaluated in an environment containing various model object components, including parameters, initial conditions, and others (see details) |
... |
not used |
Other model object slots that can be updated: start
, end
, delta
,
add
, rtol
, atol
, hmax
, maxsteps
. These are include for convenience,
but we expect that most of the time these will get updated through the
update method.
mod <- mrgsolve::house() mod2 <- within(mod, {CL <- CL * 1.5}) mod$CL mod2$CL
mod <- mrgsolve::house() mod2 <- within(mod, {CL <- CL * 1.5}) mod$CL mod2$CL
Sets all elements of the OMEGA or SIGMA matrix to zero.
zero_re(.x, ...) ## S4 method for signature 'mrgmod' zero_re(.x, ...)
zero_re(.x, ...) ## S4 method for signature 'mrgmod' zero_re(.x, ...)
.x |
a model object. |
... |
which matrix to zero out; pass |
An updated object with elements of OMEGA and/or SIGMA set to zero.
mod <- house() revar(mod) mod <- zero_re(mod) revar(mod) ## Not run: mod <- modlib("popex", compile = FALSE) mod <- zero_re(mod, omega) revar(mod) ## End(Not run)
mod <- house() revar(mod) mod <- zero_re(mod) revar(mod) ## Not run: mod <- modlib("popex", compile = FALSE) mod <- zero_re(mod, omega) revar(mod) ## End(Not run)