9  Plugins

9.1 autodec

Available as of mrgsolve version 1.0.0.

When this plugin is invoked, mrgsolve will search your model code for assignments and automatically declare them as double precision numbers. The following blocks are searched

  • $MAIN (or $PK)
  • $ODE (or $DES)
  • $TABLE (or $ERROR)
  • $PRED

For example, the following code requires that CL gets assigned a type

$PARAM WT = 70, TVCL = 1.2

double CL = TVCL * pow(WT/70, 0.75);

This is the default mrgsolve behavior and has been since the beginning.

The autodec plugin lets you write the following

$PLUGIN autodec 

$PARAM WT = 70, TVCL = 1.2

CL = TVCL * pow(WT/70, 0.75);

mrgsolve will find CL = ... and understand that this is a user initiated variable and will declare it as double for you. Don’t worry about WT = 70 in $PARAM; mrgsolve should already know about that won’t try to declare it.

When you are using the autodec plugin, you can still declare variables as double or int or bool. mrgsolve already finds those variables and will understand to leave those declarations alone. Note that it may still very convenient to declare using the capture type those variables that you want captured into the output

$PLUGIN autodec

capture Y = IPRED * exp(EPS(1));

The capture typedef makes Y a double; we didn’t need to declare it with autodec in play, but decided to declare with capture so that it is copied into the simulated output.

The autodec plugin is intended for more straightforward models where most / all variables are real valued. Because mrgsolve can handle any valid C++ code in these blocks, there is a possibility that the code could get much more complicated, including custom classes and methods. In this case, we recommend to bypass this feature and take control of declaring variables as you would in the default mode.

In case mrgsolve does try to declare (as double) a variable that shouldn’t be handled that way, you can note this name in an environment variable inside your model called MRGSOLVE_AUTODEC_SKIP

$ENV MRGSOLVE_AUTODEC_SKIP = c("my_variable_1")

This can be a vector of variable names to NOT declare when autodec is invoked.

9.2 nm-vars

Available as of mrgsolve version 1.0.0.

The nm-vars plugin provides a more NONMEM-like set of macros to use when coding your compartmental model. Only a small subset of the NONMEM model syntax is replicated here.


  • To set bioavailability for the nth compartment, use Fn
  • To set the infusion rate for the nth compartment, use Rn
  • To set the infusion duration for the nth compartment, use Dn
  • To set the lag time for the nth compartment, use ALAGn

For example


F1 = 0.87;    // equivalent to F_GUT  = 0.87;
R2 = 2.25;    // equivalent to R_CENT = 2.25;
ALAG3 = 0.25; // equivalent to ALAG_GUT2 = 0.25; 

A, A_0, DADT

  • To refer to the amount in the nth compartment, use A(n)
  • To refer to the initial amount in the nth compartment, use A_0(n)
  • To refer to the differential equation for the nth compartment, use DADT(n)

For example


A_0(2) = 50;
DADT(1) = -KA * A(1);
DADT(2) =  KA * A(1) - KE * A(2); 


Starting with version 1.0.1, macros are provided for several math functions

  • EXP(a) gets mapped to exp(a)
  • LOG(a) gets mapped to log(a)
  • SQRT(a) gets mapped to sqrt(a)

These are purely for convenience, so that upper-case versions from NMTRAN don’t require conversion to lower-case; this happens automatically via the C++ preprocessor.

Other syntax

  • Using THETA(n) in model code will resolve to THETAn; this feature is always available, even when nm-vars hasn’t been invoked; we mention it here since it is a fundamental piece of the NONMEM syntax that mrgsolve has internalized
  • Use T in $DES to refer to the current time in the odesolver rather than SOLVERTIME

Reserved words with nm-vars is invoked

There are some additional reserved words when the nm-vars plugin is invoked

  • A
  • A_0
  • DADT
  • T

It is an error to use one of these symbols as the name of a parameter or compartment or to try to declare them as variables.

mrgsolve syntax that is still required

There are a lot of differences remaining between mrgsolve and NONMEM syntax. We mention a few here to make the point

  • mrgsolve continues to require pow(base, exponent) rather than base**exponent
  • mrgsolve continues to require a semi-colon at the end of each statement (this is a C++ requirement)
  • mrgsolve continues to require that user-defined variables are declared with a type, except when the autodec plugin (Section 9.1) is invoked

An example

There is an example of this syntax (along with autodec features) in the internal model library

mod <- modlib("nm-like")
. Model file:  nm-like.cpp 
. $PROB Model written with some nonmem-like syntax features
. $PLUGIN nm-vars autodec
. THETA1 = 1, THETA2 = 21, THETA3 = 1.3, WT = 70, F1I = 0.5, D2I = 2
. KIN = 100, KOUT = 0.1, IC50 = 10, IMAX = 0.9
. $CMT @number 3
. $PK
. CL = THETA(1) * pow(WT/70, 0.75); 
. V  = THETA(2); 
. KA = THETA(3);
. F1 = F1I;
. D2 = D2I;
. A_0(3) = KIN / KOUT;
. $DES 
. CP = A(2)/V;
. INH = IMAX*CP/(IC50 + CP);
. DADT(1) = -KA*A(1);
. DADT(2) =  KA*A(1) - (CL/V)*A(2);
. DADT(3) =  KIN * (1-INH) - KOUT * A(3);
. CP = A(2)/V;

9.3 tad

Purpose Advanced calculation time after dose within your model. We call this “advanced” because it lets you track doses in multiple compartments. See the note below about a simpler way to calculate time after dose that should work fine if doses are only in a single compartment. This functionality is provided by mrgsolve.


First, tell mrgsolve that you want to use the tad plugin


The create tadose objects, one for each compartment where you want to track time after dose. One approach is to do this in [ global ]

[plugin] tad

[ global ] 
mrg::tadose tad_cmt_1(1); 
mrg::tadose tad_cmt_2(2);

Notice that we pass the compartment number that we want to track in each case and also that we refer to the mrg:: namespace for the tadose class.

The tadose objects contain the following (public) members

  • cmt the compartment to track
  • told the time of last dose; defaults to -1e9
  • had_dose indicates if a dose has already been given for the current individual
  • tad(self) the function to call to calculate time after dose
    • the self object (Section 2.3.12) must be passed as the only argument
    • when the member function is called prior to the first administered dose, a value of -1.0 is returned
  • reset() resets the state of the object; be sure to reset prior to simulating a new individual

As an example, you can call the reset() method on one of the tadose objects


You can find the source code for this object here.

A working example model that tracks doses in compartments 1 and 2 is provided here

[plugin] tad

[ global ] 
mrg::tadose tad_cmt_1(1); 
mrg::tadose tad_cmt_2(2);

[ pkmodel ] cmt = "GUT,CENT", depot = TRUE

[ param ] CL = 1, V = 20, KA = 1

[ main ] 
capture tad1 = tad_cmt_1.tad(self); 
capture tad2 = tad_cmt_2.tad(self);

Static approach

Another approach would be to make these static in [ main ] but this approach would only work if you only use these in [ main ]; the [ global ] approach is preferable since then you can access the object in any block (function).

9.3.1 Note

Note there is a simpler way to calculate time after dose when only dosing into a single compartment

[ main ]
double tad = self.tad();

The self object (Section 2.3.21) contains a tad() member which will track time after dose. Note that this needs to be called every record.

9.4 evtools


The evtools plugin is a set of functions and classes you can use to implement dosing regimens from inside your model. It first became available in mrgsolve 1.4.1. The most common use for this plugin is when you want to implement dynamic dosing simulations where the dose amount or the dosing interval is able to change based on how the system has advanced up to a certain point. For example, you might have a PKPD model for an oncology drug that includes a PK model for the drug as well as a dynamic model for platelets where a decline in platelets is driven by the drug concentration. In this case you might monitor platelets at different clinical visits and reduce the or hold dose or increase the dosing interval in response to Grade 3 or Grade 4 thrombocytopenia.


Like all other plugins, you must invoke evtools in the $PLUGIN block

$PLUGIN evtools

9.4.1 Namespace

All the functionality made available by the evtools plugin is located in a namespace called evt. So you will need to prefix all functions and classes with evt::. For example, you can read about a function called bolus below; when you call that function, you need to refer to evt::bolus, locating that function in the evt namespace.

9.4.2 Event object type

Chapter 10 introduces a C++ event object called mrg::evdata. The evt namespace provides an easier to remember typedef for that object called evt::ev. So if a function returns an event object, you can use evt::ev for that type. For example

evt::ev dose = evt::bolus(100, 1);

is equivalent to

mrg::evdata dose evt::bolus(100, 1);

9.4.3 Simple administration of single doses now

The evt namespace allows you to easily administer single bolus or infusion doses. The functions are

  • void evt::bolus(self, <amt>, <cmt>) where
    • self is the the self object, described in Section 2.3.12
    • <amt> is the dose amount (type double)
    • <cmt> is the dosing compartment (type double)
  • void evt::infuse(self, <amt>, <cmt>, <rate>) where
    • self is the the self object, described in Section 2.3.12
    • <amt> is the dose amount (type double)
    • <cmt> is the dosing compartment (type double)
    • <rate> is the infusion rate (type double)

Note that self is passed as the first argument, there is no return value, and there is no time specified for the dose. All doses invoked this way are given now, as-is; so you should only call these functions when the model code has decided it is time to administer a dose.

Important: Because doses are given now, these functions should almost be called in $TABLE (i.e., $ERROR).

9.4.4 Customized doses, potentially given later

The evt namespace also provides variants of these functions which return the event object to you so you can modify some of the attributes, including potentially scheduling the dose in the future, prior to sending the object back to mrgsolve. These functions are

  • evt::ev evt::bolus(<amt>, <cmt>) where
    • <amt> is the dose amount (type double)
    • <cmt> is the dosing compartment (type double)
  • evt::ev evt::infuse(<amt>, <cmt>, <rate>) where
    • <amt> is the dose amount (type double)
    • <cmt> is the dosing compartment (type double)
    • <rate> is the infusion rate (type double)

Note that we don’t pass in the self object here; just the dose amount, compartment, and rate for infusions. These functions also return and event object (type evt::ev) that you can work with. See Section 10.3 for documentation of those attributes.

9.4.5 API for customizing doses

While Section 10.3 shows you some low-level ways to customize the event object, the evt namespace provides some API for making these changes.


The evt::retime function can be used to set the time attribute.

evt::ev dose = evt::bolus(100, 1);
evt::retime(dose, 24);


  • an event object (evt::ev)
  • the new dose time (<double>)

Return: void (or nothing)

When doses are retimed this way, the now attribute is forced to be false.


Use evt::now to set the now attribute to true



  • an event object (evt::ev)

Return: void (nothing)


The evt namespace includes a push function to send an event object back to mrgsolve. For example

evt::ev dose = evt::bolus(100, 1);
evt::retime(dose, 24);
evt::push(self, dose);

This function will continue to be available in the evt namespace. But note that self has a push() method as of mrgsolve 1.4.1 to do the same thing


Use this function to test for equality between floating put numbers. For example, to test if TIME is (about) equal to 24.5, you can call

if(evt::near(TIME, 24.5)) { 
  // do something  

This function is similar to the dplyr::near() function.


  • a number to test (double)
  • another number to test (double)
  • optional argument <eps>, which is the tolerance for establishing equality between the two test numbers; <eps> defaults to 1e-8

Return: bool

9.4.6 Class to implement a dosing regimen

The evtools namespace also includes a class for implementing “automatic” dosing in a regimen. The documentation presented here will be limited to a brief discussion of the constructor and member functions for this class. More is written in Chapter 10 about how you can use this class effectively.

  • The constructor evt::regimen::regimen() does not take any arguments, but it dose call the reset() method.
  • void init(self) initializes the object; the argument is the self object (see Section 2.3.12)
  • void reset() resets the object to sensible defaults
    • dose compartment is set to 1
    • dose amount is set to 0
    • infusion rate is set to 0
    • dosing interval is set to 1e9
    • dosing duration is set to 1e9
    • other internal configuration

A series of setter functions let you set different attributes for the dosing regimen. All of the following functions return void. In the examples below, object refers to an object with class evt::regimen.

  • object.amt(<double>) sets the dose amount
  • object.cmt(<int>) sets the dosing compartment number
  • object.rate(<double>) sets the infusion rate
  • object.ii(<double>) sets the dosing interval
  • object.until(<double>) sets the time of the last dose

Similarly, there are a set of getter functions to return these data members

  • double object.amt() returns the dose amount
  • int object.cmt() returns the dosing compartment number
  • double object.rate() returns the infusion rate
  • double object.ii() returns the dosing interval
  • double object.until() return the time of the last dose

To start the dose regimen, call


This should almost always be called in $TABLE (i.e., $ERROR).

To force the simulation to stop at the time of the next dose with EVID set to 3333, use the flagnext() member function


This is usually set once at the start of the problem, either in $PREAMBLE or in $MAIN when NEWIND <= 1.

9.5 CXX11


Compile your model file with C++11 standard.



9.6 Rcpp


Link to Rcpp headers into your model.



Note that once your model is linked to Rcpp, you can start using that functionality immediately (without including Rcpp.h).

A very useful feature provided by Rcpp is that it exposes all of the dpqr functions that you normally use in R (e.g. rnorm() or runif()). So, if you want to simulate a number from Uniform (0,1) you can write


double uni = R::runif(0,1);

Note that the arguments are the same as the R version (?runif) except there is no n argument; you always only get one draw.

Information about Rcpp can be found here: https://github.com/RcppCore/Rcpp

9.7 mrgx

Compile in extra C++ / Rcpp functions that can be helpful to you for more advanced model coding. The mrgx plugin is dependent on the Rcpp plugin.

The functions provided by mrgx are in a namespace of the same name, so to invoke these functions, you always prepend mrgx::.

9.7.1 Get the model environment

Note that your model object (mod) contains an R environment. For example

. <environment: 0x10a5ed468>

The objects in this environment are created by a block called $ENV in your model code (see Section 2.2.27);

To access this environment in your model, call

Rcpp::Environment env = mrgx::get_envir(self);

9.8 Extract an object from the model environment

When you have an object created in $ENV

[ env ] 
rand <- rnorm(100)

You can extract this object with

[ preamble ]
Rcpp::NumericVector draw = mrgx::get("rand", self);

9.9 RcppArmadillo


Link to RcppArmadillo headers into your model.


$PLUGIN RcppArmadillo

Information about armadillo can be found here: http://arma.sourceforge.net/ Information about RcppArmadillo can be found here: https://github.com/RcppCore/RcppArmadillo

9.10 BH


Link to boost headers into your model.



Note that once your model is linked to BH (boost), you will be able to include the boost header file that you need. You have to include the header file that contains the boost function you want to use.

Information about boost can be found here: https://boost.org. Information about BH can be found here: https://github.com/eddelbuettel/bh