---
title: ID Control 1 - Practice
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}
#*************************************
#general setup to define package and get path locations
#all paths are inside the package and retrieved with system.file
packagename = "DSAIDE"
helperdir = "helperfunctions"
mbmodeldir = "mbmodels"
figuredir = "media"
appdocdir = "appinformation" 
#*************************************
#Note: for this to process/knit, several helper functions need to be available (sourced) first
#those are in the inst/helperfunctions folder
#Note: in general, the "processing-script.R" in the docsfordevelopers should be used to produce the html docs
#manual knitting of each doc only during development/testing
#*************************************
files_to_source = list.files(system.file(helperdir,package = packagename),full.names=TRUE)
sapply(files_to_source, source) #sourcing needs to happen inside each Rmd file since knitr starts a new environment
#load the settings file for the current app 
#so we can automatically include figure, list the functions in the further information section
#and use other information specific to the current app for the task table generation
currentrmdfile = knitr::current_input() 
#currentrmdfile = "idcontrolvaccine_documentation.Rmd" # For debugging
appsettings = get_settings(currentrmdfile,appdocdir,packagename)
```




## Overview {#shinytab1}
This app links the reproductive number and ID control. Read about the model in the "Model" tab. Then do the tasks described in the "What to do" tab. Before going through this app, you should go through the 'Reproductive Number' apps first.

This app assumes that you have worked through the reproductive number apps.

### Learning Objectives
* Know how to the reproductive number informs control. 
* Know how different control measures impact the reproductive number.


## The Model {#shinytab2}

### Model Overview
For this app, we'll use the same basic compartmental SIR model as for the 'Reproductive Number 2' app. We allow for 3 different stages/compartments: 

* **S** - uninfected and susceptible individuals 
* **I** - infected and infectious individuals (note that these terms are often used interchangeably, but technically we are talking about someone who is infected **and** is infectious, i.e. can infect others)
* **R** - recovered/removed individuals. Those are individuals that do not further participate, either because they are now immune or because they died.


In addition to specifying the *compartments* of a model, we need to specify the dynamics determining the changes for each compartment. Broadly speaking, some processes increase the number of individuals in a given compartment/stage and other processes that lead to a reduction. Those processes are sometimes called inflows and outflows. 

For our system, we specify the following processes/flows: 

* Susceptible individuals (S) can become infected by infectious individuals (I) at some rate, _b_. This leads to the susceptible individual leaving the S compartment and entering the I compartment.   
* Infected individuals recover and enter the recovered (R) compartment at some rate, _g_.
* Recovered individuals can lose immunity at rate _w_ and return to the susceptible compartment. 
* Natural births (into the S compartment at rate _n_) and deaths (from all compartments at rate _m_) are possible.
* The model allows a fraction of individuals to be vaccinated before the outbreak. Those individuals are moved into the R compartment before the start of the outbreak.



### Model Implementation
The flow diagram and the set of equations which are used to implement this model are as follows:


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



$$\dot S =n - b SI - mS + wR$$ 
$$\dot I = b S I - g I - mI$$
$$\dot R = g I - mR - wR$$
$$S_{v} = (1-ef)S(0)$$
$$R(0) = efS(0)$$


### Vaccination Implementation
The model includes the process of vaccinating individuals. It is modeled in a fairly simple way. Before the simulation starts, it is assumed that a fraction _f_ of susceptibles are vaccinated. The vaccine protects those vaccinated with efficacy _e_. Those protected individuals move into the _R_ compartment, the remainder stay in _S_. Thus, the simulation is started with values for susceptibles and recovered following vaccination given by $S_{v} = (1 - fe) S$ and $R = feS$. As an example, for a perfect vaccine ($e=1$) given to half the population ($f=0.5$) the initial number of susceptibles is reduced by half.

Note the unfortunate fact that the recovered compartment uses the same letter as the reproductive number, and the starting value for the _R_ compartment, _R(0)_ looks similar to the basic reproductive number. This is common notation and I therefore use it here too. Just be careful to make sure you know which quantity is discussed.



## What to do {#shinytab3}


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

```{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 = "Knowing the reproductive number, _R_, is important for control strategies, e.g. for vaccine campaigns. You learned in the reproductive number apps that for _R=1_ an outbreak switches from growth to decline (often called the threshold value). Let's say you have an ID that enters a new population where everyone is susceptible. That ID has R~0~=4. Would you expect to see an outbreak? Why? Now let's assume that we protected half the population through a (100% effective) vaccine. What is the new value for R, i.e. how many people are being infected on average by an infected person after we vaccinated? Is that new value of R low enough to prevent the outbreak? What is the minimum percentage of the population you would need to be able to protect/vaccinate to achieve an R such that no outbreak can occur?"
nrec = 2 # number of items to record
out_records = c("The new value for R",
            "The percentage needed to vaccinate/protect to prevent an outbreak")
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 = 2
tasktext = "Let's test the vaccination idea with the computer simulation. Set the simulation with 1000 susceptibles and 1 infected, simulation time 24 months, _g_=5, no births, deaths or waning immunity. Choose the value for _b_ such that _R~0~=4_. Run the simulation for 0% vaccination coverage to confirm things happen as you expect. Use the final size equation for R~0~ to make sure it gives you a value of approximately 4." 
nrec = 2 # number of items to record
out_records = c("value for parameter b to get R=4",
            "Number of susceptible at end of simulation")
out_types = c("Numeric","Rounded_Integer")
out_notes = c("", "Report the rounded integer")
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 = 3
tasktext = "Now set 50% vaccination coverage at 100% vaccine efficacy (_f=0.5_ and _e=1_). This changes the effective number of susceptible, as described in the _Model_ section. What is the value of the effective _R_ after vaccination? Run a simulation, use final size equation to confirm the expected R value."
nrec = 2 # number of items to record
out_records = c("The new value for R",
            "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 4
#########################
tid = 4
tasktext = "Now run the simulation at the vaccination level you determined above to be enough to prevent an outbreak. Make sure the simulation results and your theoretical reasoning agree."
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 


#########################
# Task 5
#########################
tid = 5
tasktext = "Most vaccines are not perfect. For the model settings above (R=4), what percentage of the population would you need to vaccinate to prevent an outbreak if the vaccine efficacy/effectiveness was 75% (_e=0.75_)? Confirm with the simulation.  What happens to your ability to prevent an outbreak if the vaccine efficacy was was 65% or less?"
nrec = 1 # number of items to record
out_records = c("The percentage vaccinated needed to prevent an outbreak for _e=0.75_")
out_types = rep("Rounded_Integer",nrec)
out_notes = rep("Report 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 6
#########################
tid = 6
tasktext = "Other useful interventions are quarantine or isolation, types of social distancing. Isolation is usually the term applied to reduction of contacts of an infected/infectious individual, quarantine to possibly exposed but likely still susceptible individuals (though that terminololgy can vary). In our model, we can't distinguish between interventions that target susceptibles or infected, both could reduce the transmission rate. Targeting susceptibles before they become infected is of course preferable, but there are usually many more of those, so targeting infected is often easier. Interventions that reduce contact and transmission/infection risk for both groups are of course best.
Consider the scenario as in task 2, but now with _b=0.015_. If we were able to reduce contacts and thus transmission by half, what would _R~0~_ be (and would that prevent an outbreak)? Test with the simulation."
nrec = 1 # number of items to record
out_records = c("Value of R0 if transmission is reduced by half")
out_types = rep("Numeric",nrec)
out_notes = rep("Report one decimal place",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 7
#########################
tid = 7
tasktext = "If we want to completely prevent an outbreak, what value do we need to reduce _R~0~_ to? To achieve this, by what percentage do we need to reduce transmission? Express this reduction as a percent of the original value (e.g. reducing transmission from 0.1 to 0.06 is a (0.1-0.06)/0.1*100 = 40% reduction). Confirm with the model." 
nrec = 1 # number of items to record
out_records = c("Percentage by which transmission needs to be reduced")
out_types = rep("Rounded_Integer",nrec)
out_notes = rep("Report 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 8
#########################
tid = 8
tasktext = "Keep exploring. The model allows for births and deaths and waning immunity. We haven't explored that here, but you might want to. One limitation of the model is that it only allows vaccination at the start of the simulation, so any births will always be un-vaccinated. If one wanted a more realistic model, e.g. one that can mimick vaccination of children, one would want to modify the model to allow ongoing vaccination of a fraction of those entering the susceptible compartment." 
nrec = 1 # number of items to record
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('dsaide_',appsettings$appid)
alloutcomes$AppTitle = appsettings$apptitle
alloutcomes$AppID = appsettings$appid
alloutcomes$Answer = "" #add empty answer column, just for consistency. Should probably be removed here.
write.table(alloutcomes, 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_new(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.
* For the equations mentioned in the tasks, see e.g. [@heffernan05a; @keeling08; @vynnycky10].
* For some information on the reproductive number, see e.g. [@fine11; @heffernan05a; @roberts07; @wallinga07].

### References



