---
title: "Introduction to RxODE"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Introduction to RxODE}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---


```{r, echo=FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
  )
options(knitr.table.format = "html")
```

# Introduction

`RxODE` is an R package that facilitates simulation with ODE models in
R. It is designed with pharmacometrics models in mind, but can be
applied more generally to any ODE model.

# Description of RxODE illustrated through an example

The model equations can be specified through a text string, a model
file or an R expression. Both differential and algebraic equations are
permitted. Differential equations are specified by `d/dt(var_name) = `. Each
equation can be separated by a semicolon.

To load `RxODE` package and compile the model: 

```{r}
library(RxODE)
library(units)

mod1 <-RxODE({
    C2 = centr/V2;
    C3 = peri/V3;
    d/dt(depot) =-KA*depot;
    d/dt(centr) = KA*depot - CL*C2 - Q*C2 + Q*C3;
    d/dt(peri)  =                    Q*C2 - Q*C3;
    d/dt(eff)  = Kin - Kout*(1-C2/(EC50+C2))*eff;
});
```

## Specify ODE parameters and initial conditions

Model parameters can be defined as named vectors. Names of parameters in
the vector must be a superset of parameters in the ODE model, and the
order of parameters within the vector is not important. 

```{r}
theta <- 
   c(KA=2.94E-01, CL=1.86E+01, V2=4.02E+01, # central 
     Q=1.05E+01,  V3=2.97E+02,              # peripheral
     Kin=1, Kout=1, EC50=200)               # effects
```

Initial conditions (ICs) are defined through a vector as well.  If the
elements are not specified, the initial condition for the compartment
is assumed to be zero.


```{r}
inits <- c(eff=1);
```

## Specify Dosing and sampling in RxODE

`RxODE` provides a simple and very flexible way to specify dosing and
sampling through functions that generate an event table. First, an
empty event table is generated through the "eventTable()" function:

```{r}
ev <- eventTable(amount.units='mg', time.units='hours')
```

Next, use the `add.dosing()` and `add.sampling()` functions of the
`EventTable` object to specify the dosing (amounts, frequency and/or
times, etc.) and observation times at which to sample the state of the
system.  These functions can be called multiple times to specify more
complex dosing or sampling regiments.  Here, these functions are used
to specify 10mg BID dosing for 5 days, followed by 20mg QD dosing for
5 days:

```{r}
ev$add.dosing(dose=10000, nbr.doses=10, dosing.interval=12)
ev$add.dosing(dose=20000, nbr.doses=5, start.time=120, dosing.interval=24)
ev$add.sampling(0:240)
```

If you wish you can also do this with the `mattigr` pipe operator `%>%`

```{r}
ev <- eventTable(amount.units="mg", time.units="hours") %>%
    add.dosing(dose=10000, nbr.doses=10, dosing.interval=12) %>%
    add.dosing(dose=20000, nbr.doses=5, start.time=120,dosing.interval=24) %>%
    add.sampling(0:240);
```

The functions `get.dosing()` and `get.sampling()` can be used to
retrieve information from the event table.

```{r}
head(ev$get.dosing())
```

```{r}
head(ev$get.sampling())
```

You may notice that these are similar to NONMEM event tables; If you
are more familiar with NONMEM data and events you could use them
directly with the event table function `et`

```{r}
ev  <- et(amountUnits="mg", timeUnits="hours") %>%
    et(amt=10000, addl=9,ii=12,cmt="depot") %>%
    et(time=120, amt=2000, addl=4, ii=14, cmt="depot") %>%
    et(0:240) # Assumes sampling when there is no dosing information
```

You can see from the above code, you can dose to the compartment named
in the RxODE model.  This slight deviation from NONMEM can reduce the
need for compartment renumbering.

These events can also be combined and expanded (to multi-subject
events and complex regimens) with `rbind`, `c`, `seq`, and `rep`. For
more information about creating complex dosing regimens using RxODE
see the [RxODE events vignette](https://nlmixrdevelopment.github.io/RxODE.doc/articles/RxODE-events.html).


# Solving ODEs

The ODE can now be solved by calling the model object's `run` or `solve`
function. Simulation results for all variables in the model are stored
in the output matrix x. 

```{r, results="asis"}
x <- mod1$solve(theta, ev, inits);
knitr::kable(head(x))
```

You can also solve this and create a RxODE data frame:


```{r}
x <- mod1 %>% solve(theta, ev, inits);
x
```

This returns a modified data frame.  You can see the compartment
values in the plot below:

```{r}
library(ggplot2)
plot(x,C2) + ylab("Central Concentration") + xlab("Time");
```

Or, 

```{r}
plot(x,eff)  + ylab("Effect") + xlab("Time");
```

Note that the labels are automatically labeled with the units from the
initial event table. This is because RxODE uses the `units` package to
handle units and `ggforce` to handle the plotting.
