---
title: "Performance benefit by using compiled model definitions in mkin"
author: "Johannes Ranke"
output:
  html_document:
    toc: true
    toc_float: true
    code_folding: show
    fig_retina: null
date: "`r Sys.Date()`"
vignette: >
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
library(knitr)
opts_chunk$set(tidy = FALSE, cache = FALSE)
```

## How to benefit from compiled models

When using an mkin version equal to or greater than 0.9-36 and a C compiler is
available, you will see a message that the model is being compiled from
autogenerated C code when defining a model using mkinmod. Starting from
version 0.9.49.9, the `mkinmod()` function checks for presence of a compiler
using

```{r check_gcc, eval = FALSE}
pkgbuild::has_compiler()
```

In previous versions, it used `Sys.which("gcc")` for this check.

On Linux, you need to have the essential build tools like make and gcc or clang
installed. On Debian based linux distributions, these will be pulled in by installing
the build-essential package.

On MacOS, which I do not use personally, I have had reports that a compiler is
available by default.

On Windows, you need to install Rtools and have the path to its bin directory
in your PATH variable. You do not need to modify the PATH variable when
installing Rtools. Instead, I would recommend to put the line

```{r Rprofile, eval = FALSE}
Sys.setenv(PATH = paste("C:/Rtools/bin", Sys.getenv("PATH"), sep=";"))
```
into your .Rprofile startup file. This is just a text file with some R
code that is executed when your R session starts. It has to be named .Rprofile
and has to be located in your home directory, which will generally be your
Documents folder. You can check the location of the home directory used by R by
issuing

```{r HOME, eval = FALSE}
Sys.getenv("HOME")
```

## Comparison with Eigenvalue based solutions

First, we build a simple degradation model for a parent compound with one metabolite.

```{r create_SFO_SFO}
library("mkin", quietly = TRUE)
SFO_SFO <- mkinmod(
  parent = mkinsub("SFO", "m1"),
  m1 = mkinsub("SFO"))
```

We can compare the performance of the Eigenvalue based solution against the
compiled version and the R implementation of the differential equations using
the benchmark package. In the output of below code, the warnings about zero
being removed from the FOCUS D dataset are suppressed.

```{r benchmark_SFO_SFO, fig.height = 3, message = FALSE, warning = FALSE}
if (require(rbenchmark)) {
  b.1 <- benchmark(
    "deSolve, not compiled" = mkinfit(SFO_SFO, FOCUS_2006_D,
                                      solution_type = "deSolve",
                                      use_compiled = FALSE, quiet = TRUE),
    "Eigenvalue based" = mkinfit(SFO_SFO, FOCUS_2006_D,
                                 solution_type = "eigen", quiet = TRUE),
    "deSolve, compiled" = mkinfit(SFO_SFO, FOCUS_2006_D,
                                  solution_type = "deSolve", quiet = TRUE),
    replications = 3)
  print(b.1)
  factor_SFO_SFO <- round(b.1["1", "relative"])
} else {
  factor_SFO_SFO <- NA
  print("R package rbenchmark is not available")
}
```

We see that using the compiled model is by a factor of around
`r factor_SFO_SFO`
faster than using the R version with the default ode solver, and it is even
faster than the Eigenvalue based solution implemented in R which does not need
iterative solution of the ODEs.


## Model that can not be solved with Eigenvalues

This evaluation is also taken from the example section of mkinfit.

```{r benchmark_FOMC_SFO, fig.height = 3, warning = FALSE}
if (require(rbenchmark)) {
  FOMC_SFO <- mkinmod(
    parent = mkinsub("FOMC", "m1"),
    m1 = mkinsub( "SFO"))

  b.2 <- benchmark(
    "deSolve, not compiled" = mkinfit(FOMC_SFO, FOCUS_2006_D,
                                      use_compiled = FALSE, quiet = TRUE),
    "deSolve, compiled" = mkinfit(FOMC_SFO, FOCUS_2006_D, quiet = TRUE),
    replications = 3)
  print(b.2)
  factor_FOMC_SFO <- round(b.2["1", "relative"])
} else {
  factor_FOMC_SFO <- NA
  print("R package benchmark is not available")
}
```

Here we get a performance benefit of a factor of
`r factor_FOMC_SFO`
using the version of the differential equation model compiled from C code!

This vignette was built with mkin `r utils::packageVersion("mkin")` on

```{r sessionInfo, echo = FALSE}
cat(utils::capture.output(utils::sessionInfo())[1:3], sep = "\n")
if(!inherits(try(cpuinfo <- readLines("/proc/cpuinfo")), "try-error")) {
  cat(gsub("model name\t: ", "CPU model: ", cpuinfo[grep("model name", cpuinfo)[1]]))
}
```
