---
title: Evolutionary Dynamics 
output:
  html_document:
    theme: null
    highlight: null
    fig_retina: null
    fig_caption: true
    mathjax: default 
    keep_md: false
bibliography: dsaide_references.bib
---

```{r, include = FALSE}
#load various variable definitions that are the same for each app
source('startup_script.R')
currentrmdfile = knitr::current_input() 
appsettings = get_settings(currentrmdfile,appdocdir,packagename)
```

## Overview {#shinytab1}
For this module, we will explore a stochastic SIR-type model with 2 different pathogen strains, wild-type and a drug resistant mutant in the presence of drug treatment. Read about the model in the "Model" tab. Then do the tasks described in the "What to do" tab.

### Learning Objectives


* Understand the central mechanisms and drivers of infectious disease evolution
* Be able to assess how different control strategies can affect infectious disease evolution


## The Model {#shinytab2}

### Model Overview

This model tracks susceptibles, wild-type infected untreated, wild-type infected treated, drug-resistant infected and recovered hosts. 
The following compartments are included:  

* __S__ - uninfected and susceptible individuals 
* __I~u~__ - individuals who are infected with the wild-type/drug sensitive strain and not on treatment.
* __I~t~__ - individuals who are infected with the wild-type/drug sensitive strain and on treatment.
* __I~r~__ - individuals who are infected with the drug-resistant strain. Treatment has no impact on those hosts, so is not modeled.
* __R__ - recovered/removed individuals. Those individuals have recovered and are immune. 


The included processes/mechanisms are the following:

* Susceptible individuals, _S_ can become infected by untreated or treated hosts infected with the wild-type strain at rates _b~u~_ and _b~t~_. 
* A fraction _f_ of those hosts infected with the wild-type strain are assumed to receive treatment (_I~t~_), while the remainder does not (_I~u~_). 
* Each time a wild-type infected host transmits to a susceptible host, there is a probability of a resistant mutant being transmitted; consequently, this generates a resistant infection. These probabilities are represented by _c~u~_ and _c~t~_ for wild-type untreated and treated hosts, respectively.
* Individuals infected with the resistant strain, _I~r~_, might receive treatment, but we assume treatment has no effect in those individuals so don't track them explicitly.
* Resistant infected individuals can infect susceptible individuals (S) with the resistant strain at rate _b~r~_. 
* All infected hosts recover at some rate _g~i~_, with _i=u,t,r_. 
* Recovered individuals are immune to reinfection. 



### Model Implementation
The flow diagram for the model implemented in this app is:

```{r modeldiagram,  fig.cap='Model Diagram',  echo=FALSE, out.width = "70%"}
knitr::include_graphics(here::here('inst/media',appsettings$modelfigname))
```

The deterministic/ODE equations for this model are:

$$\dot S = - S (b_u I_u + b_t I_t + b_r I_r)$$ 
$$\dot I_u = S (1-f) b_u (1-c_u) I_u + S (1-f)b_t (1-c_t) I_t  - g_u I_u$$
$$\dot I_t = S f b_u (1-c_u) I_u + S f b_t (1-c_t) I_t - g_t I_t$$
$$\dot I_r = S (b_u c_u I_u + b_t c_t I_t + b_r I_r) - g_r I_r$$
$$\dot R = g_u I_u + g_t I_t + g_r I_r$$

However, for this app we do __not__ implement a deterministic/ODE model. Instead, we implement its stochastic equivalent.
We can specify the model by writing down every possible transition/event/reaction that can occur and their propensities (the propensity multiplied with the
time step gives the probability that a given event/transition occurs). For our model these are the following:

Event type        |  Transitions               |   Propensity      |
----------        |  -----------               |   ----------      |
S turn into I~u~  |  S => S-1,  I~u~ => I~u~+1 |   (1-f) * (b~u~ * (1-c~u~) * I~u~ + b~t~ * (1-c~t~) * I~t~) * S  |
S turn into I~t~  |  S => S-1,  I~t~ => I~t~+1 |   f * (b~u~ * (1-c~u~) * I~u~ + b~t~ * (1-c~t~) * I~t~) * S  |
S turn into I~r~  |  S => S-1,  I~r~ => I~r~+1 |   (b~u~ * c~u~ * I~u~ + b~t~ * c~t~ * I~t~ + b~r~ * I~r~) * S  |
Recovery of I~u~  |  I~u~ => I~u~-1, R => R+1  |   g~u~ * I~u~       |
Recovery of I~t~  |  I~t~ => I~t~-1, R => R+1  |   g~t~ * I~t~       |
Recovery of I~r~  |  I~r~ => I~r~-1, R => R+1  |   g~r~ * I~r~       |




## What to do {#shinytab3}


**The tasks below are described in a way that assumes everything is in units of DAYS (rate parameters, therefore, have units of inverse days). If any quantity is not given in those units, you need to convert it first (e.g. if it says a week, you need to convert it to 7 days).**


```{r, echo=FALSE, eval=TRUE}
#this is the running counter for the records which starts at 1 
rc=1

#empty object, will hold all outcomes
alloutcomes = NULL

#########################
# Task 1
#########################
tid = 1
tasktext = "Set the model parameters to the following: susceptible _S_ = 500, and initially untreated infected host I~u~ = 1. No other infected hosts, no recovered. Set simulation duration to 300 days, start at day 0, time step doesn't matter. Assume that untreated individuals transmit at _b~u~_ = 0.001, treated at _b~t~_ = 0.0005, and resistant at _b~r~_ = 0.0008. Assume that the duration of the infectious period is 5 days for untreated, 4 days for treated and 5 days for resistant (for those individuals, treatment has no effect). Set the rates _g~i~_ accordingly. Assume nobody receives treatment and no resistance is generated (_f = c~u~ = c~t~ = 0_). Set the number of simulations to 20, random seed 123. With parameters set to correspond to the scenario just described, run the simulation. You should see 12 of the simulations with outbreaks and the others without. Only untreated infected will differ from zero. Make sure you understand why. For those simulations with outbreaks, you should have around 50-85 susceptible left at the end."
nrec = 1 # number of items to record
out_records = c("Average number of susceptible at end of simulation")
out_types = rep("Rounded_Integer",nrec)
out_notes = rep("Report the rounded integer",nrec)
outcomes = data.frame( TaskID = rep(tid,nrec),
                       TaskText = rep(tasktext,nrec),
                      RecordID = paste0('T',tid,'R',(1:nrec)),
                      Record = out_records, 
                      Type = out_types, 
                      Note = out_notes)
alloutcomes = rbind(alloutcomes,outcomes)
rc = rc + nrec #increment record counter by number of outcomes to record for this task 


#########################
# Task 2
#########################
tid = tid + 1
tasktext = "Now we'll explore treatment. Set initial untreated infected to 10 (to ensure we get outbreaks). Consecutively set the fraction receiving treatment, _f_, to 0, 0.25, 0.5, 0.75 and 1. For each treatment level, run 20 simulations (be patient) and record the average value of recovered at the end. Based on that, compute the reduction in total total number of infected as treatment level increases."
nrec = 3 # number of items to record
out_records = c("Number of averted infections going from f=0.25 to f=0.75",
                "Number of averted infections going from f=0 to f=0.5",
                "Number of averted infections going from f=0.5 to f=1")
out_types = rep("Rounded_Integer",nrec)
out_notes = rep("Report the rounded integer",nrec)
outcomes = data.frame( TaskID = rep(tid,nrec),
                       TaskText = rep(tasktext,nrec),
                      RecordID = paste0('T',tid,'R',(1:nrec)),
                      Record = out_records, 
                      Type = out_types, 
                      Note = out_notes)
alloutcomes = rbind(alloutcomes,outcomes)
rc = rc + nrec #increment record counter by number of outcomes to record for this task 




#########################
# Task 3
#########################
tid = tid + 1
tasktext = "Now allow resistance to be generated during treatment (_c~t~_ > 0). Set _c~t~ = 0.2_ for the fraction of resistant generation from treatment. Run the simulation for the treatment levels specified in the previous task, again determine total number infected for each treatment level. On a piece of paper, sketch out the relationship between treatment level and the total number infected in the absence and presence of resistance generation (_c~t~_ = 0, recorded in previous task, and _c~t~_ > 0, recorded here). What do you conclude from that?"
nrec = 3 # number of items to record
out_records = c("Number of averted infections going from f=0.25 to f=0.75",
                "Number of averted infections going from f=0 to f=0.5",
                "Number of averted infections going from f=0.5 to f=1")
out_types = rep("Rounded_Integer",nrec)
out_notes = rep("Report the rounded integer",nrec)
outcomes = data.frame( TaskID = rep(tid,nrec),
                       TaskText = rep(tasktext,nrec),
                      RecordID = paste0('T',tid,'R',(1:nrec)),
                      Record = out_records, 
                      Type = out_types, 
                      Note = out_notes)
alloutcomes = rbind(alloutcomes,outcomes)
rc = rc + nrec #increment record counter by number of outcomes to record for this task 


#########################
# Task 4
#########################
tid = tid + 1
tasktext = "Set the rate of transmission for resistant hosts to _b~r~ = 0.001_, also increase resistance generation during treatment to _c~t~ = 0.3_.  Keep everything else as previously. Contemplate what these changes mean biologically, and what you should expect from the simulations. Run the model for each of the 5 treatment levels specified above and record the total number infected at each treatment level. Draw them in the same figure you started above. What do you conclude from that?"
nrec = 3 # number of items to record
out_records = c("Number of averted infections going from f=0.25 to f=0.75",
                "Number of averted infections going from f=0 to f=0.5",
                "Number of averted infections going from f=0.5 to f=1")
out_types = rep("Rounded_Integer",nrec)
out_notes = rep("Report the rounded integer. Expect to get some negative values.",nrec)
outcomes = data.frame( TaskID = rep(tid,nrec),
                       TaskText = rep(tasktext,nrec),
                      RecordID = paste0('T',tid,'R',(1:nrec)),
                      Record = out_records, 
                      Type = out_types, 
                      Note = out_notes)
alloutcomes = rbind(alloutcomes,outcomes)
rc = rc + nrec #increment record counter by number of outcomes to record for this task 


#########################
# Task 5
#########################
tid = tid + 1
tasktext = "In the previous task, you should have found that as you increase treatment, the total number of infected initially goes down, but then goes up again. Let's try to find the optimal treatment level. Explore different values of _f_ in steps of 0.05 to find the value that gives the lowest total number of infected (of course you don't have to start at f=0, you can explore the space around the area where you know the optimal value is."
nrec = 1 # number of items to record
out_records = c("The treatment level f for which you get the lowest number of total infections")
out_types = rep("Numeric",nrec)
out_notes = rep("",nrec)
outcomes = data.frame( TaskID = rep(tid,nrec),
                       TaskText = rep(tasktext,nrec),
                      RecordID = paste0('T',tid,'R',(1:nrec)),
                      Record = out_records, 
                      Type = out_types, 
                      Note = out_notes)
alloutcomes = rbind(alloutcomes,outcomes)
rc = rc + nrec #increment record counter by number of outcomes to record for this task 



#########################
# Task 6
#########################
tid = tid + 1
tasktext = "The general idea explored here is that if you have a situation where resistance might emerge, it reduces the effectiveness of a treatment and might mean that sometimes more treatment is not better. The details depend on the fitness of the different infection compartments (in our model represented by the parameters _b~i~_ and _g~i~_) and the speed at which resistance can emerge either without or with treatment, which in our model is governed by the parameters _c~u~_ and _c~t~_. Explore how different values for those parameters impact the usefulness of treatment. As you change parameter values, try to connect them to biology, i.e. try to understand what it would mean in the real world if certain parameters had certain values."
nrec = 1 # number of items to record
out_records = c("Nothing")
out_types = rep("None",nrec)
out_notes = c("")
outcomes = data.frame( TaskID = rep(tid,nrec),
                       TaskText = rep(tasktext,nrec),
                      RecordID = paste0('T',tid,'R',(1:nrec)),
                      Record = out_records, 
                      Type = out_types, 
                      Note = out_notes)
alloutcomes = rbind(alloutcomes,outcomes)
rc = rc + nrec #increment record counter by number of outcomes to record for this task 
```


```{r echo=FALSE}
#save the fully filled task table to a tsv file
alloutcomes$QuizID = paste0(packagename,"_",appsettings$appid)
alloutcomes$AppTitle = appsettings$apptitle
alloutcomes$AppID = appsettings$appid
#remove a few variables from the data frame
savedoutcomes <- dplyr::select(alloutcomes,QuizID,AppID,AppTitle,TaskID,TaskText,RecordID,Record,Type,Note)		
write.table(savedoutcomes, paste0(appsettings$appid,"_tasktable.tsv"), append = FALSE, sep = "\t", row.names = F, col.names = TRUE)
```


```{r, echo=FALSE, results='asis'}
# Take all the text stored in the table and print the tasks and items to record
write_tasktext(alloutcomes)
```





## Further Information {#shinytab4}

* This app (and all others) are structured such that the Shiny part (the graphical interface you see and the server-side function that goes with it) calls an underlying R script (or several) which runs the simulation for the model of interest and returns the results.
* For this app, the underlying function(s) running the simulation are called ``r appsettings$simfunction``. You can call them directly, without going through the shiny app. Use the `help()` command for more information on how to use the functions directly. If you go that route, you need to use the results returned from this function and produce useful output (such as a plot) yourself. 
* You can also download all simulator functions and modify them for your own purposes.  Of course to modify these functions, you'll need to do some coding.
* For examples on using the simulators directly and how to modify them, read the package vignette by typing `vignette('DSAIDE')` into the R console.
* The model is a simpler version of a previously published model in [@handel09a].


### References
