---
title: "Benchmarks"
author: "Matthijs S. Berends"
date: '`r format(Sys.Date(), "%d %B %Y")`'
output: 
  rmarkdown::html_vignette:
    toc: true
    toc_depth: 3
vignette: >
  %\VignetteIndexEntry{Benchmarks}
  %\VignetteEncoding{UTF-8}
  %\VignetteEngine{knitr::rmarkdown}
editor_options: 
  chunk_output_type: console
---

```{r setup, include = FALSE, results = 'markup'}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#",
  fig.width = 7.5,
  fig.height = 4.5
)
```

One of the most important features of this package is the complete microbial taxonomic database, supplied by the [Catalogue of Life](http://catalogueoflife.org). We created a function `as.mo()` that transforms any user input value to a valid microbial ID by using intelligent rules combined with the taxonomic tree of Catalogue of Life.

Using the `microbenchmark` package, we can review the calculation performance of this function. Its function `microbenchmark()` runs different input expressions independently of each other and measures their time-to-result.

```{r, message = FALSE, echo = FALSE}
library(dplyr)
```

```{r, message = FALSE}
library(microbenchmark)
library(AMR)
```

In the next test, we try to 'coerce' different input values for *Staphylococcus aureus*. The actual result is the same every time: it returns its MO code `B_STPHY_AUR` (*B* stands for *Bacteria*, the taxonomic kingdom). 

But the calculation time differs a lot:

```{r}
S.aureus <- microbenchmark(as.mo("sau"),
                           as.mo("stau"),
                           as.mo("staaur"),
                           as.mo("STAAUR"),
                           as.mo("S. aureus"),
                           as.mo("S.  aureus"),
                           as.mo("Staphylococcus aureus"),
                           times = 10)
print(S.aureus, unit = "ms", signif = 2)
```

In the table above, all measurements are shown in milliseconds (thousands of seconds). A value of 5 milliseconds means it can determine 200 input values per second. It case of 100 milliseconds, this is only 10 input values per second. The second input is the only one that has to be looked up thoroughly. All the others are known codes (the first one is a WHONET code) or common laboratory codes, or common full organism names like the last one. Full organism names are always preferred.

To achieve this speed, the `as.mo` function also takes into account the prevalence of human pathogenic microorganisms. The downside is of course that less prevalent microorganisms will be determined less fast. See this example for the ID of *Thermus islandicus* (`B_THERMS_ISL`), a bug probably never found before in humans:

```{r}
T.islandicus <- microbenchmark(as.mo("theisl"),
                               as.mo("THEISL"),
                               as.mo("T. islandicus"),
                               as.mo("T.  islandicus"),
                               as.mo("Thermus islandicus"),
                               times = 10)
print(T.islandicus, unit = "ms", signif = 2)
```

That takes `r round(mean(T.islandicus$time, na.rm = TRUE) / mean(S.aureus$time, na.rm = TRUE), 1)` times as much time on average. A value of 100 milliseconds means it can only determine ~10 different input values per second. We can conclude that looking up arbitrary codes of less prevalent microorganisms is the worst way to go, in terms of calculation performance. Full names (like *Thermus islandicus*) are almost fast - these are the most probable input from most data sets.

In the figure below, we compare *Escherichia coli* (which is very common) with *Prevotella brevis* (which is moderately common) and with *Thermus islandicus* (which is very uncommon):

```{r}
par(mar = c(5, 16, 4, 2)) # set more space for left margin text (16)

boxplot(microbenchmark(as.mo("Thermus islandicus"),
                       as.mo("Prevotella brevis"),
                       as.mo("Escherichia coli"),
                       as.mo("T. islandicus"),
                       as.mo("P. brevis"),
                       as.mo("E. coli"),
                       times = 10),
        horizontal = TRUE, las = 1, unit = "s", log = FALSE,
        xlab = "", ylab = "Time in seconds",
        main = "Benchmarks per prevalence")
```


```{r, echo = FALSE, eval = FALSE}
# In reality, the `as.mo()` functions **learns from its own output to speed up determinations for next times**. In above figure, this effect was disabled to show the difference with the boxplot below - when you would use `as.mo()` yourself:

clean_mo_history()
par(mar = c(5, 16, 4, 2))
boxplot(microbenchmark(
  'as.mo("Thermus islandicus")' = as.mo("Thermus islandicus", force_mo_history = TRUE),
  'as.mo("Prevotella brevis")' = as.mo("Prevotella brevis", force_mo_history = TRUE),
  'as.mo("Escherichia coli")' = as.mo("Escherichia coli", force_mo_history = TRUE),
  'as.mo("T. islandicus")' = as.mo("T. islandicus", force_mo_history = TRUE),
  'as.mo("P. brevis")' = as.mo("P. brevis", force_mo_history = TRUE),
  'as.mo("E. coli")' = as.mo("E. coli", force_mo_history = TRUE),
  times = 10),
        horizontal = TRUE, las = 1, unit = "s", log = FALSE,
        xlab = "", ylab = "Time in seconds", ylim = c(0, 0.5),
        main = "Benchmarks per prevalence")

# The highest outliers are the first times. All next determinations were done in only thousands of seconds. For now, learning only works per session. If R is closed or terminated, the algorithms reset. This will probably be resolved in a next version.
```

Uncommon microorganisms take a lot more time than common microorganisms. To relieve this pitfall and further improve performance, two important calculations take almost no time at all: **repetitive results** and **already precalculated results**.

### Repetitive results

Repetitive results are unique values that are present more than once. Unique values will only be calculated once by `as.mo()`. We will use `mo_name()` for this test - a helper function that returns the full microbial name (genus, species and possibly subspecies) which uses `as.mo()` internally.

```{r, message = FALSE}
library(dplyr)
# take all MO codes from the septic_patients data set
x <- septic_patients$mo %>%
  # keep only the unique ones
  unique() %>%
  # pick 50 of them at random
  sample(50) %>%
  # paste that 10,000 times
  rep(10000) %>%
  # scramble it
  sample()
  
# got indeed 50 times 10,000 = half a million?
length(x)

# and how many unique values do we have?
n_distinct(x)

# now let's see:
run_it <- microbenchmark(mo_name(x),
                         times = 10)
print(run_it, unit = "ms", signif = 3)
```

So transforming 500,000 values (!!) of `r n_distinct(x)` unique values only takes `r round(median(run_it$time, na.rm = TRUE) / 1e9, 2)` seconds (`r as.integer(median(run_it$time, na.rm = TRUE) / 1e6)` ms). You only lose time on your unique input values.

### Precalculated results

What about precalculated results? If the input is an already precalculated result of a helper function like `mo_name()`, it almost doesn't take any time at all (see 'C' below):

```{r}
run_it <- microbenchmark(A = mo_name("B_STPHY_AUR"),
                         B = mo_name("S. aureus"),
                         C = mo_name("Staphylococcus aureus"),
                         times = 10)
print(run_it, unit = "ms", signif = 3)
```

So going from `mo_name("Staphylococcus aureus")` to `"Staphylococcus aureus"` takes `r format(round(run_it %>% filter(expr == "C") %>% pull(time) %>% median() / 1e9, 4), scientific = FALSE)` seconds - it doesn't even start calculating *if the result would be the same as the expected resulting value*. That goes for all helper functions:

```{r}
run_it <- microbenchmark(A = mo_species("aureus"),
                         B = mo_genus("Staphylococcus"),
                         C = mo_name("Staphylococcus aureus"),
                         D = mo_family("Staphylococcaceae"),
                         E = mo_order("Bacillales"),
                         F = mo_class("Bacilli"),
                         G = mo_phylum("Firmicutes"),
                         H = mo_kingdom("Bacteria"),
                         times = 10)
print(run_it, unit = "ms", signif = 3)
```

Of course, when running `mo_phylum("Firmicutes")` the function has zero knowledge about the actual microorganism, namely *S. aureus*. But since the result would be `"Firmicutes"` too, there is no point in calculating the result. And because this package 'knows' all phyla of all known bacteria (according to the Catalogue of Life), it can just return the initial value immediately.

### Results in other languages

When the system language is non-English and supported by this `AMR` package, some functions will have a translated result. This almost does't take extra time:

```{r}
mo_name("CoNS", language = "en") # or just mo_name("CoNS") on an English system

mo_name("CoNS", language = "es") # or just mo_name("CoNS") on a Spanish system

mo_name("CoNS", language = "nl") # or just mo_name("CoNS") on a Dutch system

run_it <- microbenchmark(en = mo_name("CoNS", language = "en"),
                         de = mo_name("CoNS", language = "de"),
                         nl = mo_name("CoNS", language = "nl"),
                         es = mo_name("CoNS", language = "es"),
                         it = mo_name("CoNS", language = "it"),
                         fr = mo_name("CoNS", language = "fr"),
                         pt = mo_name("CoNS", language = "pt"),
                         times = 10)
print(run_it, unit = "ms", signif = 4)
```

Currently supported are German, Dutch, Spanish, Italian, French and Portuguese.
