diff --git a/config.yaml b/config.yaml index c62ee29f..c9b07d54 100644 --- a/config.yaml +++ b/config.yaml @@ -11,7 +11,7 @@ carpentry: 'incubator' # Overall title for pages. -title: 'Outbreak analytics with R' +title: 'Real-time analysis and forecasting for outbreak analytics with R' # Date the lesson was created (YYYY-MM-DD, this is empty by default) created: @@ -59,14 +59,8 @@ contact: 'andree.valle-campos@lshtm.ac.uk' # Order of episodes in your lesson episodes: -- introduction.Rmd -- read-delays.Rmd - quantify-transmissibility.Rmd - create-forecast.Rmd -- simulating-transmission.Rmd -- model-choices.Rmd -- modelling-interventions.Rmd -- compare-interventions.Rmd # Information for Learners learners: @@ -84,4 +78,4 @@ profiles: varnish: epiverse-trace/varnish@epiversetheme # this is carpentries/sandpaper#533 in our fork so we can keep it up to date with main -sandpaper: epiverse-trace/sandpaper@patch-renv-github-bug +sandpaper: epiverse-trace/sandpaper@patch-renv-github-bug diff --git a/episodes/compare-interventions.Rmd b/episodes/compare-interventions.Rmd deleted file mode 100644 index 419379da..00000000 --- a/episodes/compare-interventions.Rmd +++ /dev/null @@ -1,275 +0,0 @@ ---- -title: 'Comparing public health outcomes of interventions' -teaching: 45 # teaching time in minutes -exercises: 30 # exercise time in minutes - ---- - -:::::::::::::::::::::::::::::::::::::: questions - -- How can I quantify the effect of an intervention? - - -:::::::::::::::::::::::::::::::::::::::::::::::: - -::::::::::::::::::::::::::::::::::::: objectives - -- Compare intervention scenarios - -:::::::::::::::::::::::::::::::::::::::::::::::: - -::::::::::::::::::::::::::::::::::::: prereq - -## Prerequisites -+ Complete tutorials [Simulating transmission](../episodes/simulating-transmission.md) and [Modelling interventions](../episodes/modelling-interventions.md) - -Learners should familiarise themselves with following concept dependencies before working through this tutorial: - -**Outbreak response** : [Intervention types](https://www.cdc.gov/nonpharmaceutical-interventions/). -::::::::::::::::::::::::::::::::: - - -## Introduction - -In this tutorial we will compare intervention scenarios against each other. To quantify the effect of the intervention we need to compare our intervention scenario to a counter factual scenario. The *counter factual* is the scenario in which nothing changes, often referred to as the 'do nothing' scenario. The counter factual scenario may include no interventions, or if we are investigating the potential impact of an additional intervention in the later stages of an outbreak there may be existing interventions in place. - -We must also decide what our *outcome of interest* is to make comparisons between intervention and counter factual scenarios. The outcome of interest can be: - -+ a model outcome, e.g. number of infections or hospitalisations, -+ a metric such as the epidemic peak time or size, -+ a measure that uses the model outcomes such as QALY/DALYs. - - -:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: instructor - -In this tutorial we introduce the concept of the counter factual and how to compare scenarios (counter factual versus intervention) against each other. - -:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: - -## Vacamole model - -The Vacamole model is a deterministic model based on a system of ODEs in [Ainslie et al. 2022]( https://doi.org/10.2807/1560-7917.ES.2022.27.44.2101090) to describe the effect of vaccination on COVID-19 dynamics. The model consists of 11 compartments, individuals are classed as one of the following: - -+ susceptible, $S$, -+ partial vaccination ($V_1$), fully vaccination ($V_2$), -+ exposed, $E$ and exposed while vaccinated, $E_V$, -+ infectious, $I$ and infectious while vaccinated, $I_V$, -+ hospitalised, $H$ and hospitalised while vaccinated, $H_V$, -+ dead, $D$, -+ recovered, $R$. - -The diagram below describes the flow of individuals through the different compartments. - -```{r, echo = FALSE, message = FALSE} -DiagrammeR::grViz("digraph{ - # graph statement - ################# - graph [layout = dot, - rankdir = LR, - overlap = true, - fontsize = 10] - - # nodes - ####### - node [shape = square, - fixedsize = true - width = 1.3] - - S - E - Ev [label = 'E@_{V}', style = filled, fillcolour = 'gray'] - I - Iv [label = 'I@_{V}', style = filled, fillcolour = 'gray'] - H - Hv [label = 'H@_{V}', style = filled, fillcolour = 'gray'] - D - R - V1 [label = 'V@_{1}', style = filled, fillcolour = 'gray'] - V2 [label = 'V@_{2}', style = filled, fillcolour = 'gray'] - - - # edges - ####### - S -> E [label = ' infection (β) '] - S -> V1 [label = ' vaccination (ν1)'] - V1 -> E [label = ' infection (β)'] - V1 -> V2 [label = ' vaccination\n(second dose) (ν2)'] - V2 -> Ev [label = ' infection (β)'] - Ev -> Iv [label = ' onset of \ninfectiousness (α) '] - E -> I [label = ' onset of \ninfectiousness (α) '] - I -> H [label = ' hospitalisation (η)'] - Iv -> Hv [label = ' hospitalisation (η@_{V})'] - I -> D [label = ' death (ω)'] - I -> R [label = ' recovery (γ)'] - Iv -> D [label = ' death (ω@_{V})'] - Iv -> R [label = ' recovery (γ)'] - Hv -> D [label = ' death (ω@_{V})'] - Hv -> R [label = ' recovery (γ)'] - H -> D [label = ' death (ω)'] - H -> R [label = ' recovery (γ)'] - - subgraph { - rank = same; S; V1;V2; - } -}") -``` - - -::::::::::::::::::::::::::::::::::::: challenge - -## Running a counterfactual scenario using the Vacamole model - -1. Run the model with the default parameter values for the UK population assuming that : - -+ 1 in a million individual are infectious (and not vaccinated) at the start of the simulation -+ The contact matrix for the United Kingdom has age bins: - + age between 0 and 20 years, - + age between 20 and 40, - + 40 years and over. -+ There is no vaccination scheme in place - -2. Using the output, plot the number of deaths through time - - -::::::::::::::::: hint - -### Vaccination code - -To run the model with no vaccination in place we can *either* create two vaccination objects (one for each dose) using `vaccination()` with the time start, time end and vaccination rate all set to 0, or we can use the `no_vaccination()` function to create a vaccination object for two doses with all values set to 0. - -```{r, eval = FALSE} -no_vaccination <- no_vaccination(population = uk_population, doses = 2) -``` -:::::::::::::::::::::: - -::::::::::::::::: hint - -### HINT : Running the model with default parameter values - -We can run the Vacamole model with [default parameter values](https://epiverse-trace.github.io/epidemics/articles/vacamole.html#model-epidemic-using-vacamole) by just specifying the population object and number of time steps to run the model for: - - -```{r, eval = FALSE} -output <- model_vacamole_cpp( - population = uk_population, - vaccination = no_vaccination, - time_end = 300 -) -``` - -:::::::::::::::::::::: - - - -::::::::::::::::: solution - -### SOLUTION - -1. Run the model - -```{r} -polymod <- socialmixr::polymod -contact_data <- socialmixr::contact_matrix( - survey = polymod, - countries = "United Kingdom", - age.limits = c(0, 20, 40), - symmetric = TRUE -) -# prepare contact matrix -contact_matrix <- t(contact_data$matrix) - -# extract demography vector -demography_vector <- contact_data$demography$population -names(demography_vector) <- rownames(contact_matrix) - -# prepare initial conditions -initial_i <- 1e-6 - -initial_conditions <- c( - S = 1 - initial_i, - V1 = 0, V2 = 0, - E = 0, EV = 0, - I = initial_i, IV = 0, - H = 0, HV = 0, D = 0, R = 0 -) - -initial_conditions <- rbind( - initial_conditions, - initial_conditions, - initial_conditions -) -rownames(initial_conditions) <- rownames(contact_matrix) - -# prepare population object -uk_population <- population( - name = "UK", - contact_matrix = contact_matrix, - demography_vector = demography_vector, - initial_conditions = initial_conditions -) - -no_vaccination <- no_vaccination(population = uk_population, doses = 2) - -# run model -output <- model_vacamole_cpp( - population = uk_population, - vaccination = no_vaccination, - time_end = 300 -) -``` - -2. Plot the number of deaths through time - -```{r} -ggplot(output[output$compartment == "dead", ]) + - geom_line( - aes(time, value, colour = demography_group), - linewidth = 1 - ) + - scale_colour_brewer( - palette = "Dark2", - labels = rownames(contact_matrix), - name = "Age group" - ) + - scale_y_continuous( - labels = scales::comma - ) + - labs( - x = "Simulation time (days)", - y = "Individuals" - ) + - theme( - legend.position = "top" - ) + - theme_bw( - base_size = 15 - ) -``` - - - -::::::::::::::::::::::::::: - - -:::::::::::::::::::::::::::::::::::::::::::::::: - - - -## Comparing scenarios - -*Coming soon* - - - -## Challenge : Ebola outbreak analysis - -*Coming soon* - - - - -::::::::::::::::::::::::::::::::::::: keypoints - -- The counter factual scenario must be defined to make comparisons - -:::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/episodes/introduction.Rmd b/episodes/introduction.Rmd deleted file mode 100644 index bf059f68..00000000 --- a/episodes/introduction.Rmd +++ /dev/null @@ -1,179 +0,0 @@ ---- -title: 'Outbreak analytics pipelines' -teaching: 10 -exercises: 2 -editor_options: - chunk_output_type: console ---- - -:::::::::::::::::::::::::::::::::::::: questions - -- Why use R packages for Outbreak analytics? -- What can we do to analyse our outbreak data? -- How can I start doing Outbreak Analytics with R? - -:::::::::::::::::::::::::::::::::::::::::::::::: - -::::::::::::::::::::::::::::::::::::: objectives - -- Explain our vision on the need for outbreak analytics R packages. -- Share our strategy to create R packages into an outbreak analytics pipeline. -- Define our plan to start your learning path in outbreak analytics with R. - -:::::::::::::::::::::::::::::::::::::::::::::::: - -::::::::::::::::::::::::::::::::::::: prereq - -## Prerequisites - -This episode requires you to be familiar with: - -**Data science** : Basic programming with R. - -**Epidemic theory** : Reproduction number. - -::::::::::::::::::::::::::::::::: - -## Why to use R packages for Outbreak analytics? - -Outbreaks appear with different diseases and in different contexts, but what all of them have in common are the key public health questions ([Cori et al. 2017](https://royalsocietypublishing.org/doi/10.1098/rstb.2016.0371#d1e605)). - -Is the epidemic going to take off? Is it under control? How much effort will be needed to control it? We can answer them by _quantifying the transmissibility_ of the disease. The most used parameter for this is the reproduction number ($R$), the average number of secondary infections caused by a typical primary case in the population -of interest ([Prism, 2016](http://prism.edu.au/publications/prism-modeling-guideline/)). We can intuitively interpret it as: - -- if $R>1$, the epidemic is likely to grow, -- if $R<1$, the epidemic is likely to decline. - -We can estimate the reproduction number by initially using two __data inputs__: the incidence of reported cases and the [generation time](../learners/reference.md#generationtime) distribution. But to calculate it, we must apply the appropriate mathematical models written in code with the required computational methods. That is not enough! Following _good practices_, the code we write should be peer-reviewed and contain internal tests to double-check that we are getting the estimates we expect. Imagine rewriting all of it during a health emergency! - -In R, the fundamental unit of shareable code is the _package_. A package bundles together code, data, documentation, and tests and is easy to share with others ([Wickham and Bryan, 2023](https://r-pkgs.org/introduction.html)). We, as epidemiologists, can contribute to their collaborative maintenance as a community to perform less error-prone data analysis pipelines. - -::::::::::::::::::::::::::::::::: discussion - -### Questions to think about - -Remember your last experience with outbreak data and reflect on these questions: - -- What data sources did you need to understand the outbreak? -- How did you get access to that data? -- Is that analysis pipeline you followed reusable for the next response? - -Reflect on your experiences. - -::::::::::::::::::::::::::::::::::::::::::: - - -## Example: Quantify transmission - -The `{EpiNow2}` package provides a three-step solution to _quantify the transmissibility_. Let's see how to do this with a minimal example. First, load the package: - -```{r,warning=FALSE} -library(EpiNow2) -``` - -### First, get your case data - -Case incidence data must be stored in a data frame with the observed number of cases per day. We can read an example from the package: - -```{r} -example_confirmed -``` - -### Then, set the generation time - -Not all primary cases have the same probability of generating a secondary case. The onset and cessation of [infectiousness](../learners/reference.md#infectiousness) may occur gradually. For `{EpiNow2}`, we can specify it as a probability `distribution` with `mean`, standard deviation `sd`, and maximum value `max`: - -```{r} -generation_time <- dist_spec( - mean = 3.6, - sd = 3.1, - max = 20, - distribution = "lognormal" -) -``` - -### Let's calculate the reproduction number! - -In the `epinow()` function we can add: - -- the `reported_cases` data frame, -- the `generation_time` delay distribution, and -- the computation `stan` parameters for this calculation: - -```{r,message=FALSE,warning=FALSE} -epinow_estimates <- epinow( - # cases - reported_cases = example_confirmed[1:60], - # delays - generation_time = generation_time_opts(generation_time), - # computation - stan = stan_opts( - cores = 4, samples = 1000, chains = 3, - control = list(adapt_delta = 0.99) - ) -) -``` - -As an output, we get the time-varying (or [effective](../learners/reference.md#effectiverepro)) reproduction number, as well as the cases by date of report and date of infection: - -```{r} -base::plot(epinow_estimates) -``` - -::::::::::::::::: callout - -### Is this $Rt$ estimation biased? - -Review [Gostic et al., 2020](https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1008409) about what additional adjustments this estimation requires to avoid false precision in $Rt$. - -::::::::::::::::::::::::: - -## The problem! - -However, _quantifying the transmissibility_ during a real-life outbreak response is more challenging than this example! - -Usually, we receive outbreak data in non-standard formats, requiring specific steps and taking the most time to prepare usable data inputs. Some of them are: - -- Read delay distributions from the literature -- Read and clean case data -- Validate your line list -- Describe case data - -And this is not the end. After _quantifying transmissibility_ we need to answer more key public health questions like: What is the attack rate we expect? What would be the impact of a given intervention? We can use the reproduction number and other outputs as new inputs for complementary tasks. For example: - -- Estimate severity -- Create short-term forecast -- Simulate transmission scenarios -- Compare interventions - -So, all these tasks can be interconnected in a pipeline: - -![The outbreak analytics pipeline.](https://epiverse-trace.github.io/task_pipeline-minimal.svg) - -## What can we do? - -Our strategy is gradually incorporating specialised R packages into our traditional analysis pipeline. These packages should fill the gaps in these epidemiology-specific tasks in response to outbreaks. - -Epiverse-TRACE's aim is to provide a software ecosystem for outbreak analytics. We support the development of software pieces, make the existing ones interoperable for the user experience, and stimulate a community of practice. - -![](fig/pkgs-hexlogos.png) - -## How can I start? - -Our plan for these tutorials is to introduce key solutions from packages in all the tasks before and after the _Quantify transmission_ task, plus the required theory concepts to interpret modelling outputs and make rigorous conclusions. - -- In the first set of episodes, you will learn how to optimise the reading of delay distributions and cleaning of case data to input them into the _Quantify transmission_ task. These preliminary tasks are the __Early tasks__. These include packages like `{readepi}`, `{cleanepi}`, `{linelist}`, `{epiparameter}`, and `{episoap}`. - -- Then, we will get deeper into the packages and required theory to _Quantify transmission_ and perform more real-time analysis tasks next to it. These are the __Middle tasks__. This includes `{EpiNow2}`, `{cfr}`, `{epichains}`, and `{superspreading}`. - -- Lastly, we will use _Quantify transmission_ data outputs to compare it to other indicators and simulate epidemic scenarios as part of the __Late tasks__. This includes `{finalsize}`, `{epidemics}`, and `{scenarios}`. - - -::::::::::::::::::::::::::::::::::::: keypoints - -- Our vision is to have pipelines of R packages for outbreak analytics. -- Our strategy is to create interconnected tasks to get relevant outputs for public health questions. -- We plan to introduce package solutions and theory bits for each of the tasks in the outbreak analytics pipeline. - -:::::::::::::::::::::::::::::::::::::::::::::::: - diff --git a/episodes/model-choices.Rmd b/episodes/model-choices.Rmd deleted file mode 100644 index 4a60e366..00000000 --- a/episodes/model-choices.Rmd +++ /dev/null @@ -1,418 +0,0 @@ ---- -title: 'Choosing an appropriate model' -teaching: 10 # teaching time in minutes -exercises: 20 # exercise time in minutes - ---- - -```{r setup, echo = FALSE, message = FALSE, warning = FALSE} -library(epidemics) -library(dplyr) -library(ggplot2) -``` - -:::::::::::::::::::::::::::::::::::::: questions - -- How do I choose a mathematical model that's appropriate to complete my analytical task? - - -:::::::::::::::::::::::::::::::::::::::::::::::: - -::::::::::::::::::::::::::::::::::::: objectives - -- Understand the model requirements for a specific research question - -:::::::::::::::::::::::::::::::::::::::::::::::: - -::::::::::::::::::::::::::::::::::::: prereq - -## Prerequisites -+ Complete tutorial [Simulating transmission](../episodes/simulating-transmission.md) -::::::::::::::::::::::::::::::::: - - -## Introduction - -There are existing mathematical models for different infections, interventions and transmission patterns which can be used to answer new questions. In this tutorial, we will learn how to choose an existing model to complete a given task. - -:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: instructor - -The focus of this tutorial is understanding existing models to decide if they are appropriate for a defined question. - -:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: - -::::::::::::::::::::::::::::::::::::::: discussion - -### Choosing a model - -When deciding which mathematical model to use, there are a number of questions we must consider : - -::::::::::::::::::::::::::::::::::::::::::::::::::: - -:::::::::::::::: solution - -### What is the infection/disease of interest? - -A model may already exist for your study disease, or there may be a model for an infection that has the same transmission pathways and epidemiological features that can be used. - -::::::::::::::::::::::::: - -:::::::::::::::: solution - -### Do we need a [deterministic](../learners/reference.md#deterministic) or [stochastic](../learners/reference.md#stochastic) model? - -Model structures differ for whether the disease has pandemic potential or not. When predicted numbers of infection are small, stochastic variation in output can have an effect on whether an outbreak takes off or not. Outbreaks are usually smaller in magnitude than epidemics, so its often appropriate to use a stochastic model to characterise the uncertainty in the early stages of the outbreak. Epidemics are larger in magnitude than outbreaks and so a deterministic model is suitable as we have less interest in the stochastic variation in output. - -::::::::::::::::::::::::: - -:::::::::::::::: solution - -## What is the outcome of interest? - -The outcome of interest can be a feature of a mathematical model. It may be that you are interested in the predicted numbers of infection through time, or in a specific outcome such as hospitalisations or cases of severe disease. - -::::::::::::::::::::::::: - -:::::::::::::::: solution - -## How is transmission modelled? - -For example, [direct](../learners/reference.md#direct) or [indirect](../learners/reference.md#indirect), [airborne](../learners/reference.md#airborne) or [vector-borne](../learners/reference.md#vectorborne). -::::::::::::::::::::::::: - - -:::::::::::::::: solution - -## How are the different processes (e.g. transmission) formulated in the equations? - -There can be subtle differences in model structures for the same infection or outbreak type which can be missed without studying the equations. For example, transmissibility parameters can be specified as rates or probabilities. If you want to use parameter values from other published models, you must check that transmission is formulated in the same way. -::::::::::::::::::::::::: - -:::::::::::::::: solution - -## Will any interventions be modelled? - -Finally, interventions such as vaccination may be of interest. A model may or may not have the capability to include the impact of different interventions on different time scales (continuous time or at discrete time points). We discuss interventions in detail in the tutorial [Modelling interventions](../episodes/modelling-interventions.md). - -::::::::::::::::::::::::: - - - - - - -## Available models in `epidemics` - -The R package `epidemics` contains functions to run existing models. -For details on the models that are available, see the package [vignettes](https://epiverse-trace.github.io/epidemics/articles). To learn how to run the models in R, read the documentation using `?epidemics::model_ebola_r`. - - -::::::::::::::::::::::::::::::::::::: challenge - -## What model? - -You have been asked to explore the variation in numbers of infectious individuals in the early stages of an Ebola outbreak. - -Which of the following models would be an appropriate choice for this task: - -+ `model_default_cpp()` - -+ `model_ebola_r()` - -::::::::::::::::: hint - -### HINT - -Consider the following questions: - -::::::::::::::::::::::::::::::::::::: checklist - -+ What is the infection/disease of interest? -+ Do we need a deterministic or stochastic model? -+ What is the outcome of interest? -+ Will any interventions be modelled? - -:::::::::::::::::::::::::::::::::::::::::::::::: - - -:::::::::::::::::::::: - - -::::::::::::::::: solution - -### SOLUTION - - -+ What is the infection/disease of interest? **Ebola** -+ Do we need a deterministic or stochastic model? **A stochastic model would allow us to explore variation in the early stages of the outbreak** -+ What is the outcome of interest? **Number of infections** -+ Will any interventions be modelled? **No** - -#### `model_default_cpp()` - -A deterministic SEIR model with age specific direct transmission. - -```{r diagram, echo = FALSE, message = FALSE} -DiagrammeR::grViz("digraph { - - # graph statement - ################# - graph [layout = dot, - rankdir = LR, - overlap = true, - fontsize = 10] - - # nodes - ####### - node [shape = square, - fixedsize = true - width = 1.3] - - S - E - I - R - - # edges - ####### - S -> E [label = ' infection \n(transmissibility β)'] - E -> I [label = ' onset of infectiousness \n(infectiousness rate α)'] - I -> R [label = ' recovery \n(recovery rate γ)'] - -}") -``` - - -The model is capable of predicting an Ebola type outbreak, but as the model is deterministic, we are not able to explore stochastic variation in the early stages of the outbreak. - - -#### `model_ebola_r()` - -A stochastic SEIHFR (Susceptible, Exposed, Infectious, Hospitalised, Funeral, Removed) model that was developed specifically for infection with Ebola. The model has stochasticity in the passage times between states, which are modelled as Erlang distributions. - -The key parameters affecting the transition between states are: - -+ $R_0$, the basic reproduction number, -+ $\rho^I$, the mean infectious period, -+ $\rho^E$, the mean preinfectious period, -+ $p_{hosp}$ the probability of being transferred to the hospitalised compartment. - -**Note: the functional relationship between the preinfectious period ($\rho^E$) and the transition rate between exposed and infectious ($\gamma^E$) is $\rho^E = k^E/\gamma^E$ where $k^E$ is the shape of the Erlang distribution. Similarly for the infectious period $\rho^I = k^I/\gamma^I$. See [here](https://epiverse-trace.github.io/epidemics/articles/ebola_model.html#details-discrete-time-ebola-virus-disease-model) for more detail on the stochastic model formulation. ** - -```{r, echo = FALSE, message = FALSE} -DiagrammeR::grViz("digraph { - - # graph statement - ################# - graph [layout = dot, - rankdir = LR, - overlap = true, - fontsize = 10] - - # nodes - ####### - node [shape = square, - fixedsize = true - width = 1.3] - - S - E - I - H - F - R - - # edges - ####### - S -> E [label = ' infection (β)'] - E -> I [label = ' onset of \ninfectiousness (γ E)'] - I -> F [label = ' death (funeral) \n(γ I)'] - F -> R [label = ' safe burial (one timestep) '] - I -> H [label = ' hospitalisation (p hosp)'] - H -> R [label = ' recovery or safe burial \n (γ I)'] - - subgraph { - rank = same; I; F; - } - subgraph { - rank = same; H; R; - } -}") -``` - -The model has additional parameters describing the transmission risk in hospital and funeral settings: - -+ $p_{ETU}$, the proportion of hospitalised cases contributing to the infection of susceptibles (ETU = Ebola virus treatment units), -+ $p_{funeral}$, the proportion of funerals at which the risk of transmission is the same as of infectious individuals in the community. - -As this model is stochastic, it is the most appropriate choice to explore how variation in numbers of infected individuals in the early stages of an Ebola outbreak. - - -::::::::::::::::::::::::::: - - -:::::::::::::::::::::::::::::::::::::::::::::::: - - -## Challenge : Ebola outbreak analysis - - - -::::::::::::::::::::::::::::::::::::: challenge - -## Running the model - -You have been tasked to generate initial trajectories of an Ebola outbreak in Guinea. Using `model_ebola_r()` and the the information detailed below, complete the following tasks: - -1. Run the model once and plot the number of infectious individuals through time -2. Run model 100 times and plot the mean, upper and lower 95% quantiles of the number of infectious individuals through time - -+ Population size : 14 million -+ Initial number of exposed individuals : 10 -+ Initial number of infectious individuals : 5 -+ Time of simulation : 120 days -+ Parameter values : - + $R_0$ (`r0`) = 1.1, - + $p^I$ (`infectious_period`) = 12, - + $p^E$ (`preinfectious_period`) = 5, - + $k^E=k^I = 2$, - + $1-p_{hosp}$ (`prop_community`) = 0.9, - + $p_{ETU}$ (`etu_risk`) = 0.7, - + $p_{funeral}$ (`funeral_risk`) = 0.5 - -::::::::::::::::: hint - -### Code for initial conditions - -```{r} -# set population size -population_size <- 14e6 - -E0 <- 10 -I0 <- 5 -# prepare initial conditions as proportions -initial_conditions <- c( - S = population_size - (E0 + I0), E = E0, I = I0, H = 0, F = 0, R = 0 -) / population_size - -guinea_population <- population( - name = "Guinea", - contact_matrix = matrix(1), # note dummy value - demography_vector = population_size, # 14 million, no age groups - initial_conditions = matrix( - initial_conditions, - nrow = 1 - ) -) -``` - - -:::::::::::::::::::::: - - -::::::::::::::::: hint - -### HINT : Multiple model simulations - -Adapt the code from the [accounting for uncertainty](../episodes/simulating-transmission.md#accounting-for-uncertainty) section - -:::::::::::::::::::::: - -::::::::::::::::: solution - -### SOLUTION - -1. Run the model once and plot the number of infectious individuals through time - - -```{r} -output <- model_ebola_r( - population = guinea_population, - transmissibility = 1.1 / 12, - infectiousness_rate = 2.0 / 5, - removal_rate = 2.0 / 12, - prop_community = 0.9, - etu_risk = 0.7, - funeral_risk = 0.5, - time_end = 100 -) - -ggplot(output[output$compartment == "infectious", ]) + - geom_line( - aes(time, value), - linewidth = 1.2 - ) + - scale_y_continuous( - labels = scales::comma - ) + - labs( - x = "Simulation time (days)", - y = "Individuals" - ) + - theme_bw( - base_size = 15 - ) -``` - -2. Run model 100 times and plot the mean, upper and lower 95% quantiles of the number of infectious individuals through time - -We run the model 100 times with the *same* parameter values. - -```{r} -output_samples <- Map( - x = seq(100), - f = function(x) { - output <- model_ebola_r( - population = guinea_population, - transmissibility = 1.1 / 12, - infectiousness_rate = 2.0 / 5, - removal_rate = 2.0 / 12, - prop_community = 0.9, - etu_risk = 0.7, - funeral_risk = 0.5, - time_end = 100 - ) - # add replicate number and return data - output$replicate <- x - output - } -) - -output_samples <- bind_rows(output_samples) # requires the dplyr package - -ggplot( - output_samples[output_samples$compartment == "infectious", ], - aes(time, value) -) + - stat_summary(geom = "line", fun = mean) + - stat_summary( - geom = "ribbon", - fun.min = function(z) { - quantile(z, 0.025) - }, - fun.max = function(z) { - quantile(z, 0.975) - }, - alpha = 0.3 - ) + - labs( - x = "Simulation time (days)", - y = "Individuals" - ) + - theme_bw( - base_size = 15 - ) -``` - -::::::::::::::::::::::::::: - - -:::::::::::::::::::::::::::::::::::::::::::::::: - - - -::::::::::::::::::::::::::::::::::::: keypoints - -- Existing mathematical models should be selected according to the research question -- It is important to check that a model has appropriate assumptions about transmission, outbreak potential, outcomes and interventions -:::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/episodes/modelling-interventions.Rmd b/episodes/modelling-interventions.Rmd deleted file mode 100644 index fd035843..00000000 --- a/episodes/modelling-interventions.Rmd +++ /dev/null @@ -1,442 +0,0 @@ ---- -title: 'Modelling interventions' -teaching: 45 # teaching time in minutes -exercises: 30 # exercise time in minutes - ---- - -```{r setup, echo= FALSE, message = FALSE, warning = FALSE} -library(ggplot2) -library(epidemics) -``` - -:::::::::::::::::::::::::::::::::::::: questions - -- How do I investigate the effect of interventions on disease trajectories? - - -:::::::::::::::::::::::::::::::::::::::::::::::: - -::::::::::::::::::::::::::::::::::::: objectives - -- Add pharmaceutical and non-pharmaceutical interventions to an {epidemics} model - -:::::::::::::::::::::::::::::::::::::::::::::::: - -::::::::::::::::::::::::::::::::::::: prereq - -## Prerequisites -+ Complete tutorial [Simulating transmission](../episodes/simulating-transmission.md) - -Learners should familiarise themselves with following concept dependencies before working through this tutorial: - -**Outbreak response** : [Intervention types](https://www.cdc.gov/nonpharmaceutical-interventions/). -::::::::::::::::::::::::::::::::: - - -## Introduction - -Mathematical models can be used to generate trajectories of disease spread under the implementation of interventions at different stages of an outbreak. These predictions can be used to make decisions on what interventions could be implemented to slow down the spread of diseases. - -We can assume interventions in mathematical models reduce the values of relevant parameters e.g. reduce transmissibility while in place. Or it may be appropriate to assume individuals are classified into a new disease state, e.g. once vaccinated we assume individuals are no longer susceptible to infection and therefore move to a vaccinated state. In this tutorial, we will introduce how to include three different interventions in model of COVID-19 transmission. - -:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: instructor - -In this tutorial different types of intervention and how they can be modelled are introduced. Learners should be able to understand the underlying mechanism of these interventions (e.g. reduce contact rate) as well as how to implement the code to include such interventions. - -:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: - -## Non-pharmaceutical interventions - -[Non-pharmaceutical interventions](../learners/reference.md#NPIs) (NPIs) are measures put in place to reduce transmission that do not include the administration of drugs or vaccinations. NPIs aim reduce contact between infectious and susceptible individuals. For example, washing hands, wearing masks and closures of school and workplaces. - -We will investigate the effect of interventions on a COVID-19 outbreak using an SEIR model (`model_default_cpp()` in the R package `{epidemics}`). We will set $R_0 = 2.7$, latent period or preinfectious period $= 4$ and the infectious_period $= 5.5$ (parameters adapted from [Davies et al. (2020)](https://doi.org/10.1016/S2468-2667(20)30133-X)). We load a contact matrix with age bins 0-18, 18-65, 65 years and older using `{socialmixr}` and assume that one in every 1 million in each age group is infectious at the start of the epidemic. - -```{r model_setup, echo = TRUE, message = FALSE} -polymod <- socialmixr::polymod -contact_data <- socialmixr::contact_matrix( - polymod, - countries = "United Kingdom", - age.limits = c(0, 15, 65), - symmetric = TRUE -) - -# prepare contact matrix -contact_matrix <- t(contact_data$matrix) - -# prepare the demography vector -demography_vector <- contact_data$demography$population -names(demography_vector) <- rownames(contact_matrix) - -# initial conditions: one in every 1 million is infected -initial_i <- 1e-6 -initial_conditions <- c( - S = 1 - initial_i, E = 0, I = initial_i, R = 0, V = 0 -) - -# build for all age groups -initial_conditions <- matrix( - rep(initial_conditions, dim(contact_matrix)[1]), - ncol = 5, byrow = TRUE -) -rownames(initial_conditions) <- rownames(contact_matrix) - -# prepare the population to model as affected by the epidemic -uk_population <- population( - name = "UK", - contact_matrix = contact_matrix, - demography_vector = demography_vector, - initial_conditions = initial_conditions -) -``` - -#### Effect of school closures on COVID-19 spread - -The first NPI we will consider is the effect of school closures on reducing the number of individuals infectious with COVID-19 through time. We assume that a school closure will reduce the frequency of contacts within and between different age groups. We assume that school closures will reduce the contacts between school aged children (aged 0-15) by 0.5, and will cause a small reduction (0.01) in the contacts between adults (aged 15 and over). - -To include an intervention in our model we must create an `intervention` object. The inputs are the name of the intervention (`name`), the type of intervention (`contacts` or `rate`), the start time (`time_begin`), the end time (`time_end`) and the reduction (`reduction`). The values of the reduction matrix are specified in the same order as the age groups in the contact matrix. - -```{r} -rownames(contact_matrix) -``` - -Therefore, we specify ` reduction = matrix(c(0.5, 0.01, 0.01))`. We assume that the school closures start on day 50 and are in place for a further 100 days. Therefore our intervention object is : - -```{r intervention} -close_schools <- intervention( - name = "School closure", - type = "contacts", - time_begin = 50, - time_end = 50 + 100, - reduction = matrix(c(0.5, 0.01, 0.01)) -) -``` - -::::::::::::::::::::::::::::::::::::: callout -### Effect of interventions on contacts - -In `epidemics`, the contact matrix is scaled down by proportions for the period in which the intervention is in place. To understand how the reduction is calculated within the model functions, consider a contact matrix for two age groups with equal number of contacts: - -```{r echo = FALSE} -reduction <- matrix(c(0.5, 0.1)) -contact_matrix_example <- matrix(c(1, 1, 1, 1), nrow = 2) -contact_matrix_example -``` - -If the reduction is 50% in group 1 and 10% in group 2, the contact matrix during the intervention will be: - -```{r echo = FALSE} -contact_matrix_example[1, ] <- contact_matrix_example[1, ] * (1 - reduction[1]) -contact_matrix_example[, 1] <- contact_matrix_example[, 1] * (1 - reduction[1]) -contact_matrix_example[2, ] <- contact_matrix_example[2, ] * (1 - reduction[2]) -contact_matrix_example[, 2] <- contact_matrix_example[, 2] * (1 - reduction[2]) -contact_matrix_example -``` - -The contacts within group 1 are reduced by 50% twice to accommodate for a 50% reduction in outgoing and incoming contacts ($1\times 0.5 \times 0.5 = 0.25$). Similarly, the contacts within group 2 are reduced by 10% twice. The contacts between group 1 and group 2 are reduced by 50% and then by 10% ($1 \times 0.5 \times 0.9= 0.45$). - -:::::::::::::::::::::::::::::::::::::::::::::::: - -Using transmissibility $= 2.7/5.5$ (remember that [transmissibility = $R_0$/ infectious period](../episodes/simulating-transmission.md#the-basic-reproduction-number-r_0)), infectiousness rate $1/= 4$ and the recovery rate $= 1/5.5$ we run the model with` intervention = list(contacts = close_schools)` as follows : - -```{r school} -output_school <- model_default_cpp( - population = uk_population, - transmissibility = 2.7 / 5.5, - infectiousness_rate = 1.0 / 4.0, - recovery_rate = 1.0 / 5.5, - intervention = list(contacts = close_schools), - time_end = 300, increment = 1.0 -) -``` - - -To be able to see the effect of our intervention, we also run the model where there is no intervention, combine the two outputs into one data frame and then plot the output. Here we plot the total number of infectious individuals in all age groups using `ggplot2::stat_summary()`: - -```{r baseline, echo = TRUE, fig.width = 10} -# run baseline simulation with no intervention -output_baseline <- model_default_cpp( - population = uk_population, - transmissibility = 2.7 / 5.5, - infectiousness_rate = 1.0 / 4.0, - recovery_rate = 1.0 / 5.5, - time_end = 300, increment = 1.0 -) - -# create intervention_type column for plotting -output_school$intervention_type <- "school closure" -output_baseline$intervention_type <- "baseline" -output <- rbind(output_school, output_baseline) - -ggplot(data = output[output$compartment == "infectious", ]) + - aes( - x = time, - y = value, - color = intervention_type, - linetype = intervention_type - ) + - stat_summary( - fun = "sum", - geom = "line", - linewidth = 1 - ) + - scale_y_continuous( - labels = scales::comma - ) + - labs( - x = "Simulation time (days)", - y = "Individuals" - ) + - theme_bw( - base_size = 15 - ) + - geom_vline( - xintercept = c(close_schools$time_begin, close_schools$time_end), - colour = "black", - linetype = "dashed", - linewidth = 0.2 - ) + - annotate( - geom = "text", - label = "Schools closed", - colour = "black", - x = (close_schools$time_end - close_schools$time_begin) / 2 + - close_schools$time_begin, - y = 10, - angle = 0, - vjust = "outward" - ) -``` -We see that with the intervention in place, the infection still spreads through the population, though the peak number of infectious individuals is smaller than the baseline with no intervention in place (solid line). - - - -#### Effect of mask wearing on COVID-19 spread - -We can model the effect of other NPIs as reducing the value of relevant parameters. For example, we want to investigate the effect of mask wearing on the number of individuals infectious with COVID-19 through time. - -We expect that mask wearing will reduce an individual's infectiousness. As we are using a population based model, we cannot make changes to individual behaviour and so assume that the transmissibility $\beta$ is reduced by a proportion due to mask wearing in the population. We specify this proportion, $\theta$ as product of the proportion wearing masks multiplied by the proportion reduction in transmissibility (adapted from [Li et al. 2020](https://doi.org/10.1371/journal.pone.0237691)) - -We create an intervention object with `type = rate` and `reduction = 0.161`. Using parameters adapted from [Li et al. 2020](https://doi.org/10.1371/journal.pone.0237691) we have proportion wearing masks = coverage $\times$ availability = $0.54 \times 0.525 = 0.2835$, proportion reduction in transmissibility = $0.575$. Therefore, $\theta = 0.2835 \times 0.575 = 0.163$. We assume that the mask wearing mandate starts at day 40 and is in place for 200 days. - -```{r masks} -mask_mandate <- intervention( - name = "mask mandate", - type = "rate", - time_begin = 40, - time_end = 40 + 200, - reduction = 0.163 -) -``` - -To implement this intervention on the parameter $\beta$, we specify `intervention = list(beta = mask_mandate)`. - -```{r output_masks} -output_masks <- model_default_cpp( - population = uk_population, - transmissibility = 2.7 / 5.5, - infectiousness_rate = 1.0 / 4.0, - recovery_rate = 1.0 / 5.5, - intervention = list(transmissibility = mask_mandate), - time_end = 300, increment = 1.0 -) -``` - - -```{r plot_masks, echo = TRUE, message = FALSE, fig.width = 10} -# create intervention_type column for plotting -output_masks$intervention_type <- "mask mandate" -output_baseline$intervention_type <- "baseline" -output <- rbind(output_masks, output_baseline) - -ggplot(data = output[output$compartment == "infectious", ]) + - aes( - x = time, - y = value, - color = intervention_type, - linetype = intervention_type - ) + - stat_summary( - fun = "sum", - geom = "line", - linewidth = 1 - ) + - scale_y_continuous( - labels = scales::comma - ) + - labs( - x = "Simulation time (days)", - y = "Individuals" - ) + - theme_bw( - base_size = 15 - ) + - geom_vline( - xintercept = c(mask_mandate$time_begin, mask_mandate$time_end), - colour = "black", - linetype = "dashed", - linewidth = 0.2 - ) + - annotate( - geom = "text", - label = "Mask mandate", - colour = "black", - x = (mask_mandate$time_end - mask_mandate$time_begin) / 2 + - mask_mandate$time_begin, - y = 10, - angle = 0, - vjust = "outward" - ) -``` - -::::::::::::::::::::::::::::::::::::: callout -### Intervention types - -There are two intervention types for `model_default_cpp()`. Rate interventions on model parameters (`transmissibillity` $\beta$, `infectiousness_rate` $\sigma$ and `recovery_rate` $\gamma$) and contact matrix reductions `contacts`. - -To implement both contact and rate interventions in the same simulation they must be passed as a list e.g. `intervention = list(transmissibility = mask_mandate, contacts = close_schools)`. But if there are multiple interventions that target contact rates, these must be passed as one `contacts` input. See the [vignette on modelling overlapping interventions](https://epiverse-trace.github.io/epidemics/articles/multiple_interventions.html) for more detail. - -:::::::::::::::::::::::::::::::::::::::::::::::: - - -## Pharmaceutical interventions - -Pharmaceutical interventions (PIs) are measures such as vaccination and mass treatment programs. In the previous section, we assumed that interventions reduced the value of parameter values while the intervention was in place. In the case of vaccination, we assume that after the intervention individuals are no longer susceptible and should be classified into a different disease state. Therefore, we specify the rate at which individuals are vaccinated and track the number of vaccinated individuals through time. - -The diagram below shows the SEIRV model implemented using `model_default_cpp()` where susceptible individuals are vaccinated and then move to the $V$ class. - -```{r diagram_SEIRV, echo = FALSE, message = FALSE} -DiagrammeR::grViz("digraph { - - # graph statement - ################# - graph [layout = dot, - rankdir = LR, - overlap = true, - fontsize = 10] - - # nodes - ####### - node [shape = square, - fixedsize = true - width = 1.3] - - S - E - I - R - V - - # edges - ####### - S -> E [label = ' infection (β)'] - S -> V [label = ' vaccination (ν)'] - E -> I [label = ' onset of \ninfectiousness (α)'] - I -> R [label = ' recovery (γ)'] - -}") -``` - - - -The equations describing this model are as follows: - -$$ -\begin{aligned} -\frac{dS_i}{dt} & = - \beta S_i \sum_j C_{i,j} I_j -\nu_{t} S_i \\ -\frac{dE_i}{dt} &= \beta S_i\sum_j C_{i,j} I_j - \alpha E_i \\ -\frac{dI_i}{dt} &= \alpha E_i - \gamma I_i \\ -\frac{dR_i}{dt} &=\gamma I_i \\ -\frac{dV_i}{dt} & =\nu_{i,t} S_i\\ -\end{aligned} -$$ -Individuals are vaccinated at an age group ($i$) specific time dependent ($t$) vaccination rate ($\nu_{i,t}$). The SEIR components of these equations are described in the tutorial [simulating transmission](../episodes/simulating-transmission.md#simulating-disease-spread). - -To explore the effect of vaccination we need to create a vaccination object to pass as an input into `model_default_cpp()` that includes an age groups specific vaccination rate `nu` and age group specific start and end times of the vaccination program (`time_begin` and `time_end`). - -Here we will assume all age groups are vaccinated at the same rate 0.01 and that the vaccination program starts on day 40 and is in place for 150 days. - -```{r vaccinate} -# prepare a vaccination object -vaccinate <- vaccination( - name = "vaccinate all", - time_begin = matrix(40, nrow(contact_matrix)), - time_end = matrix(40 + 150, nrow(contact_matrix)), - nu = matrix(c(0.01, 0.01, 0.01)) -) -``` - -We pass our vaccination object using `vaccination = vaccinate`: - -```{r output_vaccinate} -output_vaccinate <- model_default_cpp( - population = uk_population, - transmissibility = 2.7 / 5.5, - infectiousness_rate = 1.0 / 4.0, - recovery_rate = 1.0 / 5.5, - vaccination = vaccinate, - time_end = 300, increment = 1.0 -) -``` - - -::::::::::::::::::::::::::::::::::::: challenge - -## Compare interventions - -Plot the three interventions vaccination, school closure and mask mandate and the baseline simulation on one plot. Which intervention reduces the peak number of infectious individuals the most? - - -:::::::::::::::::::::::: solution - -## Output - -```{r plot_vaccinate, echo = TRUE, message = FALSE, fig.width = 10} -# create intervention_type column for plotting -output_vaccinate$intervention_type <- "vaccination" -output <- rbind(output_school, output_masks, output_vaccinate, output_baseline) - -ggplot(data = output[output$compartment == "infectious", ]) + - aes( - x = time, - y = value, - color = intervention_type, - linetype = intervention_type - ) + - stat_summary( - fun = "sum", - geom = "line", - linewidth = 1 - ) + - scale_y_continuous( - labels = scales::comma - ) + - labs( - x = "Simulation time (days)", - y = "Individuals" - ) + - theme_bw( - base_size = 15 - ) -``` - -From the plot we see that the peak number of total number of infectious individuals when vaccination is in place is much lower compared to school closures and mask wearing interventions. - -::::::::::::::::::::::::::::::::: -:::::::::::::::::::::::::::::::::::::::::::::::: - - - - -## Summary - -Different types of intervention can be implemented using mathematical modelling. Modelling interventions requires assumptions of which model parameters are affected (e.g. contact matrices, transmissibility), by what magnitude and and what times in the simulation of an outbreak. - -The next step is to quantify the effect of an interventions. If you are interested in learning how to compare interventions, please complete the tutorial [Comparing public health outcomes of interventions](../episodes/compare-interventions.md). - -::::::::::::::::::::::::::::::::::::: keypoints - -- The effect of NPIs can be modelled as reducing contact rates between age groups or reducing the transmissibility of infection -- Vaccination can be modelled by assuming individuals move to a different disease state $V$ - -:::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/episodes/read-delays.Rmd b/episodes/read-delays.Rmd deleted file mode 100644 index 90e6c8e3..00000000 --- a/episodes/read-delays.Rmd +++ /dev/null @@ -1,1380 +0,0 @@ ---- -title: 'Read delays' -teaching: 10 -exercises: 2 -editor_options: - chunk_output_type: console ---- - -:::::::::::::::::::::::::::::::::::::: questions - -- How to get delay distributions from a systematic review? -- How to connect reused delays with my existing analysis pipeline? -- When should delays be reused from a systematic review? - -:::::::::::::::::::::::::::::::::::::::::::::::: - -::::::::::::::::::::::::::::::::::::: objectives - -- Get delays from a systematic review with `{epiparameter}`. -- Get statistical summaries and distribution parameters of delay distributions. -- Use distribution functions from delay distributions. -- Convert a continuous to a discrete delay distribution. - -:::::::::::::::::::::::::::::::::::::::::::::::: - -::::::::::::::::::::::::::::::::::::: prereq - -## Prerequisites - -This episode requires you to be familiar with: - -**Data science** : Basic programming with R. - -**Epidemic theory** : Epidemiological parameters. Time periods. - -::::::::::::::::::::::::::::::::: - -## Introduction - -The [natural history](../learners/reference.md#naturalhistory) of an infectious disease shows that its development has a regularity from stage to stage. The time periods from an infectious disease inform about the timing of transmission and interventions. - -![Definition of key time periods. From [Xiang et al, 2021](https://www.sciencedirect.com/science/article/pii/S2468042721000038)](fig/time-periods.jpg) - - -::::::::::::::::: callout - -### Definitions - -Look at the [glossary](../learners/reference.md) for the definitions of all the time periods of the figure above! - -::::::::::::::::::::::::: - -However, early in an epidemic, modelling efforts can be delayed by the lack of a centralized resource that summarises input parameters for the disease of interest ([Nash et al., 2023](https://mrc-ide.github.io/epireview/)). Projects like `{epiparameter}` and `{epireview}` are building online catalogues following systematic review protocols that can help build models faster for coming outbreaks and epidemics from known pathogens and unknown ones related to known families of viruses. - - - -To exemplify how to use `{epiparameter}` in your analysis pipeline, our goal in this episode will be to replace the `generation_time` input that we can use for `EpiNow2::epinow()`. - -```r -epinow_estimates <- epinow( - # cases - reported_cases = example_confirmed[1:60], - # delays - generation_time = generation_time_opts(generation_time), - # computation - stan = stan_opts( - cores = 4, samples = 1000, chains = 3, - control = list(adapt_delta = 0.99) - ) -) -``` - -To do this replacement, instead of plug-in numeric values to `EpiNow2::dist_spec()` to manually specify the delay distribution parameters, we are going to collect them from the library of epidemiological parameters provided by `{epiparameter}`: - -```r -generation_time <- dist_spec( - mean = 3.6, - sd = 3.1, - max = 20, - distribution = "lognormal" -) -``` - -Let's explore how we can access this and other time delays using `{epiparameter}`. We'll use the pipe `%>%` to connect some of their functions, so let's also call to the `{tidyverse}` package: - -```{r,warning=FALSE,message=FALSE} -library(epiparameter) -library(EpiNow2) -library(tidyverse) -``` - -## Find a Generation time - -The generation time, jointly with the $R$, can inform about the speed of spread and its feasibility of control. Given a $R>1$, with a shorter generation time, cases can appear more quickly. - -![Video from the MRC Centre for Global Infectious Disease Analysis, Ep 76. Science In Context - Epi Parameter Review Group with Dr Anne Cori (27-07-2023) at ](fig/reproduction-generation-time.png) - -In calculating the effective reproduction number ($R_{t}$), the *generation time* distribution is often approximated by the [serial interval](../learners/reference.md#serialinterval) distribution. -This frequent approximation is because it is easier to observe and measure the onset of symptoms than the onset of infectiousness. - -![A schematic of the relationship of different time periods of transmission between an infector and an infectee in a transmission pair. Exposure window is defined as the time interval having viral exposure, and transmission window is defined as the time interval for onward transmission with respect to the infection time ([Chung Lau et al. 2021](https://academic.oup.com/jid/article/224/10/1664/6356465)).](fig/serial-interval-observed.jpeg) - -However, using the *serial interval* as an approximation of the *generation time* is primarily valid for diseases in which infectiousness starts after symptom onset ([Chung Lau et al. 2021](https://academic.oup.com/jid/article/224/10/1664/6356465)). In cases where infectiousness starts before symptom onset, the serial intervals can have negative values, which is the case of a pre-symptomatic transmission ([Nishiura et al. (2020)](https://www.ijidonline.com/article/S1201-9712(20)30119-3/fulltext#gr2)). - -Additionally, even if the *generation time* and *serial interval* have the same mean, their variance usually differs, propagating bias to the $R_{t}$ estimation. $R_{t}$ estimates are sensitive not only to the mean generation time but also to the variance and form of the generation interval distribution [(Gostic et al., 2020)](https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1008409). - -::::::::::::::::: callout - -### From time periods to probability distributions. - -When we calculate the *serial interval*, we see that not all case pairs have the same time length. We will observe this variability for any case pair and individual time period, including the [incubation period](../learners/reference.md#incubation) and [infectious period](../learners/reference.md#infectiousness). - -![Serial intervals of possible case pairs in (a) COVID-19 and (b) MERS-CoV. Pairs represent a presumed infector and their presumed infectee plotted by date of symptom onset ([Althobaity et al., 2022](https://www.sciencedirect.com/science/article/pii/S2468042722000537#fig6)).](fig/serial-interval-pairs.jpg) - -To summarize these data from individual and pair time periods, we can find the **statistical distributions** that best fit the data ([McFarland et al., 2023](https://www.eurosurveillance.org/content/10.2807/1560-7917.ES.2023.28.27.2200806)). - - - -![Fitted serial interval distribution for (a) COVID-19 and (b) MERS-CoV based on reported transmission pairs in Saudi Arabia. We fitted three commonly used distributions, Lognormal, Gamma, and Weibull distributions, respectively ([Althobaity et al., 2022](https://www.sciencedirect.com/science/article/pii/S2468042722000537#fig5)).](fig/seria-interval-fitted-distributions.jpg) - -Statistical distributions are summarized in terms of their **summary statistics** like the *location* (mean and percentiles) and *spread* (variance or standard deviation) of the distribution, or with their **distribution parameters** that inform about the *form* (shape and rate/scale) of the distribution. These estimated values can be reported with their **uncertainty** (95% confidence intervals). - -| Gamma | mean | shape | rate/scale | -|:--------------|:--------------|:--------------|:--------------| -| MERS-CoV | 14.13(13.9–14.7) | 6.31(4.88–8.52) | 0.43(0.33–0.60) | -| COVID-19 | 5.1(5.0–5.5) | 2.77(2.09–3.88) | 0.53(0.38–0.76) | - -| Weibull | mean | shape | rate/scale | -|:--------------|:--------------|:--------------|:--------------| -| MERS-CoV | 14.2(13.3–15.2) | 3.07(2.64–3.63) | 16.1(15.0–17.1) | -| COVID-19 | 5.2(4.6–5.9) | 1.74(1.46–2.11) | 5.83(5.08–6.67) | - -| Log normal | mean | mean-log | sd-log | -|:--------------|:--------------|:--------------|:--------------| -| MERS-CoV | 14.08(13.1–15.2) | 2.58(2.50–2.68) | 0.44(0.39–0.5) | -| COVID-19 | 5.2(4.2–6.5) | 1.45(1.31–1.61) | 0.63(0.54–0.74) | - -Table: Serial interval estimates using Gamma, Weibull, and Log normal distributions. 95% confidence intervals for the shape and scale (logmean and sd for Log normal) parameters are shown in brackets ([Althobaity et al., 2022](https://www.sciencedirect.com/science/article/pii/S2468042722000537#tbl3)). - -::::::::::::::::::::::::: - -::::::::::::::::::::::::::::::::: challenge - -### Serial interval - -Assume that COVID-19 and SARS have similar reproduction number values and that the serial interval approximates the generation time. - -Given the Serial interval of both infections in the figure below: - -- Which one would be harder to control? -- Why do you conclude that? - -![Serial interval of novel coronavirus (COVID-19) infections overlaid with a published distribution of SARS. ([Nishiura et al, 2020](https://www.ijidonline.com/article/S1201-9712(20)30119-3/fulltext))](fig/serial-interval-covid-sars.jpg) - -::::::::::::::::: hint - -The peak of each curve can inform you about the location of the mean of each distribution. The larger the mean, the larger the serial interval. - -:::::::::::::::::::::: - -::::::::::::::::: solution - -Which one would be harder to control? - -- COVID-19 - -Why do you conclude that? - -- COVID-19 has the lowest mean serial interval. The approximate mean value for the serial interval of COVID-19 is around four days, and SARS is about seven days. Thus, COVID-19 will likely have newer generations in less time than SARS, assuming similar reproduction numbers. - -:::::::::::::::::::::::::: - -::::::::::::::::::::::::::::::::::::::::::: - -:::::::::::::::::::::: instructor - -The objective of the assessment above is to assess the interpretation of a larger or shorter generation time. - -:::::::::::::::::::::: - -## Extract epidemiological parameters - -First, let's assume that the data set `example_confirmed` has COVID-19 observed cases. So, we need to find a reported generation time for COVID-19 or any other useful parameter for this aim. - -Let's start by looking at how many parameters we have in the epidemiological distributions database (`epidist_db`) for the `disease` named `covid`-19: - -```{r} -epiparameter::epidist_db( - disease = "covid" -) -``` - -From the `{epiparameter}` package, we can use the `epidist_db()` function to ask for any `disease` and also for a specific epidemiological distribution (`epi_dist`). - -Let's ask now how many parameters we have in the epidemiological distributions database (`epidist_db`) with the generation time using the string `generation`: - -```{r} -epiparameter::epidist_db( - epi_dist = "generation" -) -``` - -Currently, in the library of epidemiological parameters, we have one `generation` time entry for Influenza. Considering the abovementioned considerations, we can look at the `serial` intervals for `COVID`-19. - -```{r} -epiparameter::epidist_db( - disease = "COVID", - epi_dist = "serial" -) -``` - -::::::::::::::::: callout - -### CASE-INSENSITIVE - -`epidist_db` is [case-insensitive](https://dillionmegida.com/p/case-sensitivity-vs-case-insensitivity/#case-insensitivity). This means that you can use strings with letters in upper or lower case indistinctly. - -::::::::::::::::::::::::: - -We get more than one epidemiological delay. To summarize this view and get the column names from the underlying parameter dataset, we can add the `epiparameter::list_distributions()` function to the previous code using the pipe `%>%`: - -```{r} -epiparameter::epidist_db( - disease = "covid", - epi_dist = "serial" -) %>% - epiparameter::list_distributions() -``` - -::::::::::::::::::::::::::::::::: challenge - -### Ebola's incubation periods - -Take 5 minutes: - -- How many delay distributions are for the Ebola disease? - -- How many delay distributions are for the incubation period of Ebola? - -- Explore the library and find the disease with the delay distribution of your interest! Do you recognize the paper? - -::::::::::::::::: hint - -The `{epiparameter}` combo of `epidist_db()` plus `list_distributions()` list all the entries by: - -- disease, -- epidemiological distribution, -- the type of the probability distribution, -- author of the study, and -- year of study. - -:::::::::::::::::::::: - -::::::::::::::::: solution - -```{r,eval=FALSE} -# 16 delays distributions -epiparameter::epidist_db( - disease = "ebola" -) - -# 5 delay distributions are for the incubation period -epiparameter::epidist_db( - disease = "ebola", - epi_dist = "incubation" -) -``` - -Now, from the output of `epiparameter::epidist_db()`, What is an [offspring distribution](../learners/reference.md#offspringdist)? - -:::::::::::::::::::::::::: - -::::::::::::::::::::::::::::::::::::::::::: - - -## Select a single distribution - -The `epiparameter::epidist_db()` function works as a filtering or subset function. Let's use the `author` argument to filter `Hiroshi Nishiura` parameters: - -```{r} -epiparameter::epidist_db( - disease = "covid", - epi_dist = "serial", - author = "Hiroshi" -) %>% - epiparameter::list_distributions() -``` - -We still get more than one epidemiological parameter. We can set the `single_epidist` argument to `TRUE` to only one: - -```{r} -epiparameter::epidist_db( - disease = "covid", - epi_dist = "serial", - author = "Hiroshi", - single_epidist = TRUE -) -``` - -::::::::::::::::: callout - -### How does `single_epidist` works? - -Looking at the help documentation for `?epiparameter::epidist_db()`: - -- If multiple entries match the arguments supplied and `single_epidist = TRUE`, -- Then, the parameterised `⁠`⁠ with the largest sample size will be returned. -- If multiple entries are equal after this sorting, the first entry will be returned. - -What does a parametrised `` is? Look at `?is_parameterised`. - -::::::::::::::::::::::::: - -Now, we have an epidemiological parameter we can reuse! We can replace the numbers we plug into `EpiNow2::dist_spec()`. - -Let's assign this `` class object to the `covid_serialint` object. - -```{r} -covid_serialint <- - epiparameter::epidist_db( - disease = "covid", - epi_dist = "serial", - author = "Nishiura", - single_epidist = TRUE - ) - -covid_serialint -``` - -::::::::::::::::::::::::::::::::: challenge - -### Ebola's incubation period - -Take 2 minutes: - -- What type of distribution has the incubation period of Ebola with the highest sample size? -- How would you access to the sample size of the other studies in the `` class object? - -::::::::::::::::: hint - -The `{epiparameter}` combo of `epidist_db()` plus `list_distributions()` list all the entries by: - -- disease, -- epidemiological distribution, -- the type of the probability distribution, -- author of the study, and -- year of study. - -This is a `` class object: - -```{r,eval=FALSE} -epiparameter::epidist_db( - disease = "ebola", - epi_dist = "incubation" -) -``` - - -:::::::::::::::::::::: - -::::::::::::::::: solution - -```{r,eval=FALSE} -# the distribution with the highest sample size has a gamma distribution -epiparameter::epidist_db( - disease = "ebola", - epi_dist = "incubation", - single_epidist = TRUE -) -``` - -To access the `sample_size`, review an [issue reported in the GitHub repository](https://github.com/epiverse-trace/epiparameter/issues/227) of the `{epiparameter}` package. - -:::::::::::::::::::::::::: - -::::::::::::::::::::::::::::::::::::::::::: - -## Extract the summary statistics - -We can get the `mean` and standard deviation (`sd`) from this `` diving into the `summary_stats` object: - -```{r} -# get the mean -covid_serialint$summary_stats$mean -``` - -:::::::::::::::::::::::::::::: challenge - -### How to get the `sd` and other nested elements? - -Take 1 minute to: - -1. Get the `sd` of the epidemiological distribution. - -2. Find the `sample_size` used in the study. - -3. Explore all the other nested elements within the `` object. - -Share about: - -- What elements do you find useful for your analysis? -- What other elements would you like to see in this object? How? - -::::::::: hint - -Use the `$` operator plus the tab keyboard button to explore them as an expandable list: - -```r -covid_serialint$ -``` - -Use the `str()` to display the structure of the `` R object. - -:::::::::::::::::: - -:::::::::: solution - -```{r,eval=FALSE} -# get the sd -covid_serialint$summary_stats$sd - -# get the sample_size -covid_serialint$metadata$sample_size -``` - -:::::::::::::::::::: - -:::::::::::::::::::::::::::::::: - -:::::::::::::::::::: intructor - -An interesting element is the `method_assess` nested entry, which refers to the methods used by the study authors to assess for bias while estimating the serial interval distribution. - -```{r} -covid_serialint$method_assess -``` - -We will explore these concepts at the end! - -:::::::::::::::::::::::::::::: - - -::::::::::::::::::::::::::::::::: challenge - -### Ebola's severity parameter - -A severity parameter like the duration of hospitalization could add to the information needed about the bed capacity in response to an outbreak ([Cori et al., 2017](https://royalsocietypublishing.org/doi/10.1098/rstb.2016.0371)). - -For Ebola: - -- what is a reported point estimate and uncertainty of the mean duration of health-care and case isolation? - -::::::::::::::::: hint - -An informative delay measures the time from symptom onset to recovery or death. - -:::::::::::::::::::::: - -::::::::::::::::: solution - -```{r,eval=FALSE} -# one way to get the list of all the available parameters -epidist_db(disease = "all") %>% - list_distributions() %>% - as_tibble() %>% - distinct(epi_distribution) - -ebola_severity <- epidist_db( - disease = "ebola", - epi_dist = "onset to discharge" -) - -# point estimate -ebola_severity$summary_stats$mean -# 95% confidence intervals -ebola_severity$summary_stats$mean_ci -# limits of the confidence intervals -ebola_severity$summary_stats$mean_ci_limits -``` - -:::::::::::::::::::::::::: - -::::::::::::::::::::::::::::::::::::::::::: - - -## Continuous distributions - -The following output has four entries with different content in the **probability distribution** (`prob_distribution`) column: - -```{r} -distribution <- - epiparameter::epidist_db( - disease = "covid", - epi_dist = "serial" - ) - -distribution %>% - list_distributions() -``` - -Entries with a missing value (``) in the `prob_distribution` column are *non-parameterised* entries. They have summary statistics but no probability distribution. Compare these two outputs: - -```{r,eval=FALSE} -distribution[[1]]$summary_stats -distribution[[1]]$prob_dist -``` - -::::::::::::::::: spoiler - -### Parameterised entries have an Inference method - -As detailed in `?is_parameterised`, a parameterised distribution is the entry that has a probability distribution associated with it provided by an `inference_method` as shown in `metadata`: - -```{r,eval=FALSE} -distribution[[1]]$metadata$inference_method -distribution[[2]]$metadata$inference_method -distribution[[4]]$metadata$inference_method -``` - -::::::::::::::::::::::::: - -In the `epiparameter::list_distributions()` output, we can also find different types of probability distributions (e.g., Log-normal, Weibull, Normal). - -```{r} -distribution %>% - list_distributions() -``` - -In `{epiparameter}`, you will mostly find **continuous** distributions like these. You can visualize any of them with the `plot()` function and access to: - -- the *Probability Density Function (PDF)* and -- the *Cumulative Distribution Function (CDF)*. - -```{r} -plot(distribution[[2]]) -``` - -With the `day_range` argument, you can change the length or number of days in the `x` axis. Explore what it look like: - -```{r,eval=FALSE} -plot(distribution[[2]], day_range = 0:20) -``` - -::::::::::::::::: discussion - -### The distribution Zoo - -Explore this shinyapp called **The Distribution Zoo**! - -Follow these steps to reproduce the form of the `covid_serialint` distribution: - -1. Access to shinyapp website, -2. Go to the left panel, -3. Keep the *Category of distribution*: `Continuous Univariate`, -4. Select a new *Type of distribution*: `Log-Normal`, -5. Move the **sliders**, i.e. the graphical control element that allows you to adjust a value by moving a handle along a horizontal track or bar to the `covid_serialint` parameters. - -Replicate these with the `distribution` object and all its list elements: `2`, `3`, and `4`. Explore how the shape of a distribution changes when its parameters change. - -Share about: - -- What other features of the website do you find helpful? - -::::::::::::::::::::::::: - - - -## Distribution functions - -In R, all the statistical distributions have functions to access the: - -- Probability **Density** function (PDF), -- Cumulative Distribution function (**CDF**), -- **Quantile** function, and -- **Random** values from the given distribution. - -:::::::::::: spoiler - -### Functions for the Normal distribution - -If you need it, read in detail about the [R probability functions for the normal distribution](https://sakai.unc.edu/access/content/group/3d1eb92e-7848-4f55-90c3-7c72a54e7e43/public/docs/lectures/lecture13.htm#probfunc), each of its definitions and identify in which part of a distribution they are located! - -![The four probability functions for the normal distribution ([Jack Weiss, 2012](https://sakai.unc.edu/access/content/group/3d1eb92e-7848-4f55-90c3-7c72a54e7e43/public/docs/lectures/lecture13.htm#probfunc))](fig/fig5a-normaldistribution.png) - -:::::::::::::::::::: - -If you look at `?stats::Distributions`, each type of distribution has a unique set of functions. However, `{epiparameter}` gives you the same four functions to access each of the values above for any `` object you want! - -```{r,eval=FALSE} -# plot this to have a visual reference -plot(covid_serialint, day_range = 0:20) -``` - -```{r} -# the density value at quantile value of 10 (days) -density(covid_serialint, at = 10) - -# the cumulative probability at quantile value of 10 (days) -cdf(covid_serialint, q = 10) - -# the quantile value (day) at a cumulative probability of 60% -quantile(covid_serialint, p = 0.6) - -# generate 10 random values (days) given -# the distribution family and its parameters -generate(covid_serialint, times = 10) -``` - -::::::::: instructor - -Access to the reference documentation (Help files) for these functions is accessible with the three double-colon notation: `epiparameter:::` - -- `?epiparameter:::density.epidist()` -- `?epiparameter:::cdf.epidist()` -- `?epiparameter:::quantile.epidist()` -- `?epiparameter:::generate.epidist()` - -:::::::::::::::::: - -::::::::::::::::::::::::::::::::: challenge - -### Window for contact tracing and the Serial interval - -The **serial interval** is important in the optimization of contact tracing since it provides a time window for the containment of a disease spread ([Fine, 2003](https://academic.oup.com/aje/article/158/11/1039/162725)). Depending on the serial interval, we can evaluate the need to expand the number of days pre-onset to consider in the contact tracing to include more backwards contacts ([Davis et al., 2020](https://assets.publishing.service.gov.uk/media/61e9ab3f8fa8f50597fb3078/S0523_Oxford_-_Backwards_contact_tracing.pdf)). - -With the COVID-19 serial interval (`covid_serialint`) calculate: - -- How much more of the backward cases could be captured if the contact tracing method considered contacts up to 6 days pre-onset compared to 2 days pre-onset? - -::::::::::::::::: hint - -In Figure 5 from the [R probability functions for the normal distribution](https://sakai.unc.edu/access/content/group/3d1eb92e-7848-4f55-90c3-7c72a54e7e43/public/docs/lectures/lecture13.htm#probfunc), the shadowed section represents a cumulative probability of `0.997` for the quantile value at `x = 2`. - -:::::::::::::::::::::: - -::::::::::::::::: solution - -```{r,eval=FALSE} -plot(covid_serialint) -``` - -```{r,eval=FALSE} -cdf(covid_serialint, q = 2) -cdf(covid_serialint, q = 6) -``` - -Given the COVID-19 serial interval: - -- A contact tracing method considering contacts up to 2 days pre-onset will capture around 11.1% of backward cases. - -- If this period is extended to 6 days pre-onset, this could include 76.2% of backward contacts. - -:::::::::::::::::::::::::: - -::::::::::::::::: solution - -### What if - -If we exchange the question between days and cumulative probability to: - -- When considering secondary cases, how many days following the symptom onset of primary cases can we expect 55% of symptom onset to occur? - -```{r,eval=FALSE} -quantile(covid_serialint, p = 0.55) -``` - -An interpretation could be: - -- The 55% percent of the symptom onset of secondary cases will happen after 4.2 days after the symptom onset of primary cases. - -:::::::::::::::::::::::::: - - -::::::::::::::::::::::::::::::::::::::::::: - - -## Discretize a continuous distribution - -We are getting closer to the end! `EpiNow2::dist_spec()` still needs a maximum value (`max`). - -One way to do this is to get the quantile value for the distribution's 99.9th percentile or `0.999` cumulative probability. For this, we need access to the set of distribution functions for our `` object. - -We can use the set of distribution functions for a _continuous_ distribution (as above). However, these values will be _continuous_ numbers. We can **discretize** the continuous distribution stored in our `` object to get discrete values from a continuous distribution. - -When we `epiparameter::discretise()` the continuous distribution we get a **discrete**(-ized) distribution: - -```{r} -covid_serialint_discrete <- - epiparameter::discretise(covid_serialint) - -covid_serialint_discrete -``` - -We identify this change in the `Distribution:` output line of the `` object. Take a double check to this line: - -``` -Distribution: discrete lnorm -``` - -While for a **continuous** distribution, we plot the *Probability Density Function (PDF)*, for a **discrete** distribution, we plot the *Probability Mass Function (PMF)*: - -```{r,eval=FALSE} -# continuous -plot(covid_serialint) - -# discrete -plot(covid_serialint_discrete) -``` - -To finally get a `max` value, let's access the quantile value of the 99.9th percentile or `0.999` probability of the distribution with the `prob_dist$q` notation, similarly to how we access the `summary_stats` values. - -```{r} -covid_serialint_discrete_max <- - covid_serialint_discrete$prob_dist$q(p = 0.999) -``` - -::::::::::::::::::::::::::::::::: challenge - -### Lenght of quarantine and Incubation period - -The **incubation period** distribution is a useful delay to assess the length of active monitoring or quarantine ([Lauer et al., 2020](https://www.acpjournals.org/doi/10.7326/M20-0504)). Similarly, delays from symptom onset to recovery (or death) will determine the required duration of health-care and case isolation ([Cori et al., 2017](https://royalsocietypublishing.org/doi/10.1098/rstb.2016.0371)). - -Calculate: - -- Within what exact time frame do 99% of individuals who develop COVID-19 symptoms exhibit them after infection? - -::::::::::::::::: hint - -What delay distribution measures the time between infection and the onset of symptoms? - -The probability function for `` **discrete** distributions differ from the *continuous* ones! - -```{r,eval=FALSE} -# plot to have a visual reference -plot(covid_serialint_discrete, day_range = 0:20) - -# density value at quantile value 10 (day) -covid_serialint_discrete$prob_dist$d(10) - -# cumulative probability at quantile value 10 (day) -covid_serialint_discrete$prob_dist$cdf(10) - -# In what quantile value (days) do we have the 60% cumulative probability? -covid_serialint_discrete$prob_dist$q(0.6) - -# generate random values -covid_serialint_discrete$prob_dist$r(10) -``` - -:::::::::::::::::::::: - -::::::::::::::::: solution - -```{r,eval=FALSE} -covid_incubation <- - epiparameter::epidist_db( - disease = "covid", - epi_dist = "incubation", - single_epidist = TRUE - ) - -covid_incubation_discrete <- epiparameter::discretise(covid_incubation) - -covid_incubation_discrete$prob_dist$q(0.99) -``` - -99% of those who develop COVID-19 symptoms will do so within 16 days of infection. - -Now, _Is this result expected in epidemiological terms?_ - -:::::::::::::::::::::::::: - -::::::::::::::::: solution - -### how to create a distribution plot? - -From a maximum value with `$prob_dist$q()`, we can create a sequence of quantile values as a numeric vector and map density values for each: - -```{r,eval=FALSE} -# create a discrete distribution visualization -# from a maximum value from the distribution -covid_serialint_discrete$prob_dist$q(0.999) %>% - # generate quantile values - # as a sequence for each natural number - seq(1L, to = ., by = 1L) %>% - # coerce numeric vector to data frame - as_tibble_col(column_name = "quantile_values") %>% - mutate( - # map density values - # for each quantile in the density function - density_values = - covid_serialint_discrete$prob_dist$d(quantile_values) - ) %>% - # create plot - ggplot( - aes( - x = quantile_values, - y = density_values - ) - ) + - geom_col() -``` - -:::::::::::::::::::::::::: - -::::::::::::::::::::::::::::::::::::::::::: - - -## Plug-in `{epiparameter}` to `{EpiNow2}` - -Now we can plug everything into the `EpiNow2::dist_spec()` function! - -```{r} -serial_interval_covid <- - dist_spec( - mean = covid_serialint$summary_stats$mean, - sd = covid_serialint$summary_stats$sd, - max = covid_serialint_discrete_max, - distribution = "lognormal" - ) - -serial_interval_covid -``` - -:::::::::: callout - -### Warning - -Using the serial interval instead of the generation time is an alternative that can propagate bias in your estimates, even more so in diseases with reported pre-symptomatic transmission. - -:::::::::::::::::: - -Let's replace the `generation_time` input we used for `EpiNow2::epinow()`. - -```{r,eval=FALSE} -epinow_estimates <- epinow( - # cases - reported_cases = example_confirmed[1:60], - # delays - generation_time = generation_time_opts(serial_interval_covid), - # computation - stan = stan_opts( - cores = 4, samples = 1000, chains = 3, - control = list(adapt_delta = 0.99) - ) -) - -base::plot(epinow_estimates) -``` - -::::::::::::::::::::::::::::::::: challenge - -### Ebola's effective reproduction number - -Download and read the [Ebola dataset](data/ebola_cases.csv): - -- Reuse one epidemiological parameter to estimate the effective reproduction number for the Ebola dataset. -- Why did you choose that parameter? - -::::::::::::::::: hint - -To calculate the $R_t$, we need: - -- data set with confirmed cases per day and -- one key delay distribution - -Key functions we applied in this episode are: - -- `epidist_db()` -- `list_distributions()` -- `discretise()` -- probability functions for continuous and discrete distributions - -:::::::::::::::::::::: - -::::::::::::::::: solution - -```{r,eval=FALSE,echo=FALSE} -# read data from the tutorial repository R project -ebola_confirmed <- - read_csv(file.path("episodes", "data", "ebola_cases.csv")) -``` - -```{r,message=FALSE,warning=FALSE,eval=FALSE} -# read data -# e.g.: if path to file is data/raw-data/ebola_cases.csv then: -ebola_confirmed <- - read_csv(here::here("data", "raw-data", "ebola_cases.csv")) - -# list distributions -epidist_db(disease = "ebola") %>% - list_distributions() - -# subset one distribution -ebola_serial <- epidist_db( - disease = "ebola", - epi_dist = "serial", - single_epidist = TRUE -) - -ebola_serial_discrete <- discretise(ebola_serial) - -serial_interval_ebola <- - dist_spec( - mean = ebola_serial$summary_stats$mean, - sd = ebola_serial$summary_stats$sd, - max = ebola_serial_discrete$prob_dist$q(p = 0.999), - distribution = "gamma" - ) - -# name of the type of distribution -# only for the discretised distribution -ebola_serial_discrete$prob_dist$name - -epinow_estimates <- epinow( - # cases - reported_cases = ebola_confirmed, - # delays - generation_time = generation_time_opts(serial_interval_ebola), - # computation - stan = stan_opts( - cores = 4, samples = 1000, chains = 3, - control = list(adapt_delta = 0.99) - ) -) - -plot(epinow_estimates) - -``` - -:::::::::::::::::::::::::: - - -::::::::::::::::::::::::::::::::::::::::::: - -## Adjusting for reporting delays - -Estimating $R_t$ requires data on the daily number of new infections. Due to lags in the development of detectable viral loads, symptom onset, seeking care, and reporting, these numbers are not readily available. All observations reflect transmission events from some time in the past. In other words, if $d$ is the delay from infection to observation, then observations at time $t$ inform $R_{t−d}$, not $R_t$. [(Gostic et al., 2020)](https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1008409#sec007) - -![Timeline for chain of disease reporting, the Netherlands. Lab, laboratory; PHA, public health authority. From [Marinović et al., 2015](https://wwwnc.cdc.gov/eid/article/21/2/13-0504_article)](fig/disease-reporting.jpg) - -The **delay distribution** could be inferred jointly with the underlying times of infection or estimated as the sum of the **[incubation period](../learners/reference.md#incubation)** distribution and the distribution of delays from symptom onset to observation from line list data **([reporting delay](../learners/reference.md#reportingdelay))**. - -For `{EpiNow2}`, we can specify these two complementary delay distributions in the `delays` argument. - -![Rt is a measure of transmission at time t. Observations after time t must be adjusted. ICU, intensive care unit. From [Gostic et al., 2020](https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1008409#sec007)](fig/rt-adjusting-delays.png) - -::::::::::::::::::::::::::::::::: challenge - -### Reuse an Incubation period for COVID-19 - -Use `{epiparameter}` to: - -- Find an incubation period for COVID-19. -- Add our last `epinow()` code chunk using the `delays` argument and the `delay_opts()` helper function. - -::::::::::::::::: hint - -The `delays` argument and the `delay_opts()` helper function are analogous to the `generation_time` argument and the `generation_time_opts()` helper function. - -```r -epinow_estimates <- epinow( - # cases - reported_cases = example_confirmed[1:60], - # delays - generation_time = generation_time_opts(serial_interval_covid), - delays = delay_opts(incubation_time_covid), - # computation - stan = stan_opts( - cores = 4, samples = 1000, chains = 3, - control = list(adapt_delta = 0.99) - ) -) -``` - -:::::::::::::::::::::: - -::::::::::::::::: solution - -```{r,eval=FALSE} -covid_incubation <- epiparameter::epidist_db( - disease = "covid", - epi_dist = "incubation", - author = "Natalie", - single_epidist = TRUE -) - -covid_incubation - -covid_incubation_discrete <- epiparameter::discretise(covid_incubation) - -incubation_time_covid <- dist_spec( - mean = covid_incubation$summary_stats$mean, - sd = covid_incubation$summary_stats$sd, - max = covid_incubation_discrete$prob_dist$q(p = 0.999), - distribution = "lognormal" -) - -epinow_estimates <- epinow( - # cases - reported_cases = example_confirmed[1:60], - # delays - generation_time = generation_time_opts(serial_interval_covid), - delays = delay_opts(incubation_time_covid), - # computation - stan = stan_opts( - cores = 4, samples = 1000, chains = 3, - control = list(adapt_delta = 0.99) - ) -) - -base::plot(epinow_estimates) -``` - -:::::::::::::::::::::::::: - -:::::::::::::: solution - -### How much has it changed? - -After adding the incubation period, discuss: - -- Does the retrospective trend of forecast change? -- Has the uncertainty changed? -- How would you explain or interpret any of these changes? - -:::::::::::::::::::::::::::: - -::::::::::::::::::::::::::::::::::::::::::: - - -::::::::::::::::::::::::::::::::: challenge - -### Ebola's effective reproduction number was adjusted by reporting delays - -Using the same [Ebola dataset](data/ebola_cases.csv): - -- Reuse one additional epidemiological parameter for the `delays` argument in `EpiNow2::epinow()`. -- Estimate the effective reproduction number using `EpiNow2::epinow()`. -- Why did you choose that parameter? - -::::::::::::::::: hint - -We can use two complementary delay distributions to estimate the $R_t$ at time $t$. - -:::::::::::::::::::::: - -::::::::::::::::: solution - -```{r,eval=FALSE,echo=FALSE} -# read data from the tutorial repository R project -ebola_confirmed <- - read_csv(file.path("episodes", "data", "ebola_cases.csv")) -``` - -```{r,message=FALSE,warning=FALSE,eval=FALSE} -# read data -# e.g.: if path to file is data/raw-data/ebola_cases.csv then: -ebola_confirmed <- - read_csv(here::here("data", "raw-data", "ebola_cases.csv")) - -# list distributions -epidist_db(disease = "ebola") %>% - list_distributions() - -# subset one distribution for the generation time -ebola_serial <- epidist_db( - disease = "ebola", - epi_dist = "serial", - single_epidist = TRUE -) - -ebola_serial_discrete <- discretise(ebola_serial) - -serial_interval_ebola <- - dist_spec( - mean = ebola_serial$summary_stats$mean, - sd = ebola_serial$summary_stats$sd, - max = ebola_serial_discrete$prob_dist$q(p = 0.999), - distribution = "gamma" - ) - -# subset one distribution for delay of the incubation period -ebola_incubation <- epidist_db( - disease = "ebola", - epi_dist = "incubation", - single_epidist = TRUE -) - -ebola_incubation_discrete <- discretise(ebola_incubation) - -incubation_period_ebola <- - dist_spec( - mean = ebola_incubation$summary_stats$mean, - sd = ebola_incubation$summary_stats$sd, - max = ebola_incubation_discrete$prob_dist$q(p = 0.999), - distribution = "gamma" - ) - -epinow_estimates <- epinow( - # cases - reported_cases = ebola_confirmed, - # delays - generation_time = generation_time_opts(serial_interval_ebola), - delays = delay_opts(incubation_period_ebola), - # computation - stan = stan_opts( - cores = 4, samples = 1000, chains = 3, - control = list(adapt_delta = 0.99) - ) -) - -plot(epinow_estimates) - -``` - -:::::::::::::::::::::::::: - -::::::::::::::::::::::::::::::::::::::::::: - - -::::::::::::::::::::::::::::::::: challenge - -### Extract parameters - -Use the `influenza_england_1978_school` from the `{outbreaks}` package to calculate the effective reproduction number. - -::::::::::::::::: hint - -How to get the mean and standard deviation from a generation time with median and quantiles as summary statistics? - -- Look at how to extract parameters from `{epiparameter}` vignette on [parameter extraction and conversion](https://epiverse-trace.github.io/epiparameter/articles/extract_convert.html) - -:::::::::::::::::::::: - -::::::::::::::::: solution - - - -```{r,eval=FALSE} -# What parameters are available for Influenza? -epidist_db(disease = "influenza") %>% - list_distributions() %>% - as_tibble() %>% - count(epi_distribution) - -influenza_generation <- - epidist_db( - disease = "influenza", - epi_dist = "generation" - ) - -influenza_generation_discrete <- - discretise(influenza_generation) - -# problem -# the summary statistics do not have mean and sd -influenza_generation$summary_stats -influenza_generation$summary_stats$median -influenza_generation$summary_stats$quantiles - -# solution -# extract parameters from percentiles -influenza_extracted <- extract_param( - type = "percentiles", - values = c(influenza_generation$summary_stats$quantiles[1], - influenza_generation$summary_stats$quantiles[2]), - distribution = "lnorm", - percentiles = c(0.05, 0.95) -) - -influenza_extracted - -generation_time_influenza <- - dist_spec( - mean = influenza_extracted[1], - sd = influenza_extracted[2], - max = influenza_generation_discrete$prob_dist$q(p = 0.999), - distribution = "lognormal" - ) - -influenza_cleaned <- - outbreaks::influenza_england_1978_school %>% - select(date, confirm = in_bed) - -epinow_estimates <- epinow( - # cases - reported_cases = influenza_cleaned, - # delays - generation_time = generation_time_opts(generation_time_influenza), - # computation - stan = stan_opts( - cores = 4, samples = 1000, chains = 3, - control = list(adapt_delta = 0.99) - ) -) - -plot(epinow_estimates) -``` - - - - - - - - - - -:::::::::::::::::::::::::: - -::::::::::::::::::::::::::::::::::::::::::: - -## When to reuse? When to estimate? - -In the early stage of an outbreak, we can rely on reusing parameters for known pathogens to unknown ones, like for the [Disease X](https://en.wikipedia.org/wiki/Disease_X), a pathogen currently unknown to cause human disease and potentially cause a serious international epidemic ([WHO, 2018](https://www.who.int/activities/prioritizing-diseases-for-research-and-development-in-emergency-contexts)). - -But when data from **lines list paired with contact tracing** is available, we can estimate the key delay distributions that best fit our data. These will help us to inform, compare and update any previous estimate about questions like: - -- How long should contacts be followed? -- What is the required duration of contact tracing? -- How long should cases be isolated to reduce transmission? - -However, the methods to accurately estimate delays like the generation interval from contact tracing data involve adjusting for biases like **[censoring](../learners/reference.md#censoring)**, **[right truncation](../learners/reference.md#truncation)** and **[epidemic phase bias](../learners/reference.md#phasebias)**. [(Gostic et al., 2020)](https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1008409) - -We can identify what entries in the `{epiparameter}` library assessed for these biases in their methodology with the `method_assess` nested entry: - -```{r} -covid_serialint$method_assess -``` - -::::::::::::::::: testimonial - -### How to estimate delay distributions for Disease X? - -Refer to this excellent tutorial on estimating the serial interval and incubation period of Disease X accounting for *censoring* using Bayesian inference with packages like `{rstan}` and `{coarseDataTools}`. - -- Tutorial in English: -- Tutorial en Español: - -::::::::::::::::::::::::::::: - -:::::::::::::::::::::::::: spoiler - -### How to assess for pre-symptomatic infection? - -The lengths of the Serial interval and Incubation period determine the type of disease transmission. - -![The relationship between the incubation period and serial interval. From [Nishiura 2020](https://www.ijidonline.com/article/S1201-9712(20)30119-3/fulltext)](fig/incubation-period-serial-interval.jpg) - -Estimating the proportion of pre-symptomatic infections, or the extent to which infectiousness precedes symptom onset will determine the effectiveness of contact tracing and the feasibility of controlling an outbreak ([Fraser et al., 2004](https://www.pnas.org/doi/full/10.1073/pnas.0307506101) and [Hellewell et al., 2020](https://www.thelancet.com/article/S2214-109X(20)30074-7/fulltext)). - - - -![Parameter estimates. Plausible ranges for the key parameters R0 and θ (read the main text for sources) for four viral infections of public concern are shown as shaded regions. The size of the shaded area reflects the uncertainties in the parameter estimates. [Fraser et al., 2004](https://www.pnas.org/doi/10.1073/pnas.0307506101)](fig/reproduction-number-pre-symptomatic.png) - -Meta-analysis on the proportion of pre-symptomatic and asymptomatic transmission in SARS-CoV-2 found limitations of the evidence given high heterogeneity and high risk of selection and information bias between studies ([Buitrago-Garcia et al., 2022](https://journals.plos.org/plosmedicine/article/figure?id=10.1371/journal.pmed.1003987.g003)). This is a call to action to improve the Outbreak Analytic pipelines to use and reuse in the early phase of an outbreak. - -::::::::::::::::::::::::::::::::::: - -::::::::::::::::::::::::::::::::: challenge - -### What type of transmission? - -Compare the serial interval and incubation period of Influenza and MERS: - -- What type of transmission has Influenza? -- What type of transmission has MERS? -- Do these results correlate with the available evidence? - -::::::::::::::::: hint - -For types of transmission, we refer to infections with symptomatic or pre-symptomatic transmission. - -Key functions: - -- `epidist_db()` -- `epidist$summary_stats$` - -:::::::::::::::::::::: - -::::::::::::::::: solution - -In this solution we use `purrr::pluck()` to extract elements within the `summary_stats` object which is of class `list`. - -```{r,eval=FALSE} -# pre-symptomatic transmission -epidist_db( - disease = "influenza", - epi_dist = "incubation", - single_epidist = TRUE -) %>% - pluck("summary_stats") %>% - pluck("mean") - -epidist_db( - disease = "influenza", - epi_dist = "serial", - single_epidist = TRUE -) %>% - pluck("summary_stats") %>% - pluck("mean") - -# symptomatic transmission -epidist_db( - disease = "mers", - epi_dist = "incubation", - single_epidist = TRUE -) %>% - pluck("summary_stats") %>% - pluck("median") - -epidist_db( - disease = "mers", - epi_dist = "serial", - single_epidist = TRUE -) %>% - pluck("summary_stats") %>% - pluck("mean") -``` - -```{r,eval=FALSE} -# pre-symptomatic transmission -epidist_db( - disease = "covid", - epi_dist = "incubation", - author = "Stephen", - single_epidist = TRUE -) %>% - pluck("summary_stats") %>% - pluck("mean") - -epidist_db( - disease = "covid", - epi_dist = "serial", - author = "Nishiura", - single_epidist = TRUE -) %>% - pluck("summary_stats") %>% - pluck("mean") - -# symptomatic transmission -epidist_db( - disease = "ebola", - epi_dist = "incubation", - single_epidist = TRUE -) %>% - pluck("summary_stats") %>% - pluck("mean") - -epidist_db( - disease = "ebola", - epi_dist = "serial", - single_epidist = TRUE -) %>% - pluck("summary_stats") %>% - pluck("mean") -``` - -:::::::::::::::::::::::::: - -::::::::::::::::::::::::::::::::::::::::::: - - - - -::::::::::::::::::::::::::::::::::::: keypoints - -- Use `{epiparameter}` to access the systematic review catalogue of epidemiological delay distributions. -- Use `epidist_db()` to select single delay distributions. -- Use `list_distributions()` for an overview of multiple delay distributions. -- Use `discretise()` to convert continuous to discrete delay distributions. -- Use `{epiparameter}` probability functions for any delay distributions. - -:::::::::::::::::::::::::::::::::::::::::::::::: - diff --git a/episodes/simulating-transmission.Rmd b/episodes/simulating-transmission.Rmd deleted file mode 100644 index c0804502..00000000 --- a/episodes/simulating-transmission.Rmd +++ /dev/null @@ -1,555 +0,0 @@ ---- -title: 'Simulating transmission' -teaching: 45 # teaching time in minutes -exercises: 30 # exercise time in minutes ---- - -```{r setup, echo= FALSE, message = FALSE, warning = FALSE} -library(ggplot2) -library(dplyr) -library(tidyverse) -library(DiagrammeR) -library(webshot) -library(epidemics) -webshot::install_phantomjs(force = TRUE) -``` - - -:::::::::::::::::::::::::::::::::::::: questions - -- How do I simulate disease spread using a mathematical model? -- What inputs are needed for a model simulation? -- How do I account for uncertainty? - -:::::::::::::::::::::::::::::::::::::::::::::::: - -::::::::::::::::::::::::::::::::::::: objectives - -- Load an existing model structure from `{epidemics}` R package -- Load an existing social contact matrix with `{socialmixr}` -- Generate a disease spread model simulation with `{epidemics}` -- Generate multiple model simulations and visualise uncertainty - -:::::::::::::::::::::::::::::::::::::::::::::::: - -::::::::::::::::::::::::::::::::::::: prereq - -## Prerequisites - -Learners should familiarise themselves with following concept dependencies before working through this tutorial: - -**Mathematical Modelling** : [Introduction to infectious disease models](https://doi.org/10.1038/s41592-020-0856-2), [state variables](../learners/reference.md#state), [model parameters](../learners/reference.md#parsode), [initial conditions](../learners/reference.md#initial), [ordinary differential equations](../learners/reference.md#ordinary). - -**Epidemic theory** : [Transmission](https://doi.org/10.1155/2011/267049), [Reproduction number](https://doi.org/10.3201/eid2501.171901). -::::::::::::::::::::::::::::::::: - - - -## Introduction - -Mathematical models are useful tools for generating future trajectories of disease spread. In this tutorial, we will use the R package `{epidemics}` to generate disease trajectories of an influenza strain with pandemic potential. By the end of this tutorial, you will be able to generate the trajectory below showing the number of infectious individuals in different age categories over time. - -```{r traj, echo = FALSE, message = FALSE, fig.width = 10, eval = TRUE} -# load contact and population data from socialmixr::polymod -polymod <- socialmixr::polymod -contact_data <- socialmixr::contact_matrix( - polymod, - countries = "United Kingdom", - age.limits = c(0, 20, 40), - symmetric = TRUE -) - -# prepare contact matrix -contact_matrix <- t(contact_data$matrix) - -# prepare the demography vector -demography_vector <- contact_data$demography$population -names(demography_vector) <- rownames(contact_matrix) - -# initial conditions: one in every 1 million is infected -initial_i <- 1e-6 -initial_conditions_inf <- c( - S = 1 - initial_i, E = 0, I = initial_i, R = 0, V = 0 -) - -initial_conditions_free <- c( - S = 1, E = 0, I = 0, R = 0, V = 0 -) - -# build for all age groups -initial_conditions <- rbind( - initial_conditions_inf, - initial_conditions_free, - initial_conditions_free -) -rownames(initial_conditions) <- rownames(contact_matrix) - -# prepare the population to model as affected by the epidemic -uk_population <- population( - name = "UK", - contact_matrix = contact_matrix, - demography_vector = demography_vector, - initial_conditions = initial_conditions -) - -# run an epidemic model using `epidemic()` -output_plot <- model_default_cpp( - population = uk_population, - transmissibility = 1.46 / 7.0, - infectiousness_rate = 1.0 / 3.0, - recovery_rate = 1.0 / 7.0, - time_end = 600, increment = 1.0 -) - -filter(output_plot, compartment %in% c("exposed", "infectious")) %>% - ggplot( - aes( - x = time, - y = value, - col = demography_group, - linetype = compartment - ) - ) + - geom_line( - linewidth = 1.2 - ) + - scale_y_continuous( - labels = scales::comma - ) + - scale_colour_brewer( - palette = "Dark2", - name = "Age group" - ) + - expand_limits( - y = c(0, 500e3) - ) + - coord_cartesian( - expand = FALSE - ) + - theme_bw( - base_size = 15 - ) + - theme( - legend.position = "top" - ) + - labs( - x = "Simulation time (days)", - linetype = "Compartment", - y = "Individuals" - ) -``` - - -:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: instructor - -By the end of this tutorial, learners should be able to replicate the above image on their own computers. - -:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: - - -## Simulating disease spread - -To generate predictions of infectious disease trajectories, we must first select a mathematical model to use. -There is a library of models to choose from in `epidemics`. Models in `epidemics` are prefixed with `model` and suffixed by the name of infection (e.g. Ebola) or a different identifier (e.g. default), and whether the model has a R or [C++](../learners/reference.md#cplusplus) code base. - -In this tutorial, we will use the default model in `epidemics`, `model_default_cpp()` which is an age-structured SEIR model described by a system of [ordinary differential equations](../learners/reference.md#ordinary). For each age group $i$, individuals are classed as either susceptible $S$, infected but not yet infectious $E$, infectious $I$ or recovered $R$. The schematic below shows the processes which describe the flow of individuals between the disease states $S$, $E$, $I$ and $R$ and the key parameters for each process. - -```{r diagram, echo = FALSE, message = FALSE} -DiagrammeR::grViz("digraph { - - # graph statement - ################# - graph [layout = dot, - rankdir = LR, - overlap = true, - fontsize = 10] - - # nodes - ####### - node [shape = square, - fixedsize = true - width = 1.3] - - S - E - I - R - - # edges - ####### - S -> E [label = ' infection \n(transmissibility β)'] - E -> I [label = ' onset of infectiousness \n(infectiousness rate α)'] - I -> R [label = ' recovery \n(recovery rate γ)'] - -}") -``` - - -::::::::::::::::::::::::::::::::::::: callout -### Model parameters : rates - -In ODE models, model parameters are often (but not always) specified as rates. The rate at which an event occurs is the inverse of the average time until that event. For example, in the SEIR model, the recovery rate $\gamma$ is the inverse of the average infectious period. - -We can use knowledge of the natural history of the disease to inform our values of rates. If the average infectious period of an infection is 8 days, then the daily recovery rate is $\gamma = 1/8 = 0.125$. - - -:::::::::::::::::::::::::::::::::::::::::::::::: - - -For each disease state ($S$, $E$, $I$ and $R$) and age group ($i$), we have an ordinary differential equation describing the rate of change with respect to time. - -$$ -\begin{aligned} -\frac{dS_i}{dt} & = - \beta S_i \sum_j C_{i,j} I_j \\ -\frac{dE_i}{dt} &= \beta S_i\sum_j C_{i,j} I_j - \alpha E_i \\ -\frac{dI_i}{dt} &= \alpha E_i - \gamma I_i \\ -\frac{dR_i}{dt} &=\gamma I_i \\ -\end{aligned} -$$ -Individuals in age group ($i$) move from the susceptible state ($S_i$) to the exposed state ($E_i$) via age group specific contact with the infectious individuals in their own and other age groups $\beta S_i \sum_j C_{i,j} I_j$. The contact matrix $C$ allows for heterogeneity in contacts between age groups. They then move to the infectious state at a rate $\alpha$ and recover at a rate $\gamma$. There is no loss of immunity (there are no flows out of the recovered state). - -The model parameters definitions are : - -- transmission rate or transmissibility $\beta$, -- [contact matrix](../learners/reference.md#contact) $C$ containing the frequency of contacts between age groups (a square $i \times j$ matrix), -- infectiousness rate $\alpha$ (preinfectious period ([latent period](../learners/reference.md#latent)) =$1/\alpha$), -- recovery rate $\gamma$ (infectious period = $1/\gamma$). - - -::::::::::::::::::::::::::::::::::::: callout -### Exposed, infected, infectious - -Confusion sometimes arises when referring to the terms 'exposed', 'infected' and 'infectious' in mathematical modelling. Infection occurs after a person has been exposed, but in modelling terms individuals that are 'exposed' are treated as already infected. - -We will use the following definitions for our state variables: - -+ $E$ = Exposed : infected **but not yet** infectious, -+ $I$ = Infectious: infected **and** infectious. -:::::::::::::::::::::::::::::::::::::::::::::::: - - -To generate trajectories using our model, we must prepare the following inputs : - -1. Contact matrix -2. Initial conditions -3. Population structure -4. Model parameters - -### 1. Contact matrix - -Contact matrices can be estimated from surveys or contact data, or synthetic ones can be used. We will use the R package `{socialmixr}` to load in a contact matrix estimated from POLYMOD survey data [(Mossong et al. 2008)](https://doi.org/10.1371/journal.pmed.0050074). - - -::::::::::::::::::::::::::::::::::::: challenge - -## Load contact and population data - -Using the R package `socialmixr`, run the following lines of R code to obtain the contact matrix for the United Kingdom for the year age bins: - -+ age between 0 and 20 years, -+ age between 20 and 40, -+ 40 years and over. - -```r -polymod <- socialmixr::polymod -contact_data <- socialmixr::contact_matrix( - survey = polymod, - countries = "United Kingdom", - age.limits = c(0, 20, 40), - symmetric = TRUE -) -# prepare contact matrix -contact_matrix <- t(contact_data$matrix) -contact_matrix -``` - -:::::::::::::::::::::::: solution - -## Output - -```{r polymod_uk, echo = FALSE, message = FALSE} -polymod <- socialmixr::polymod -contact_data <- socialmixr::contact_matrix( - polymod, - countries = "United Kingdom", - age.limits = c(0, 20, 40), - symmetric = TRUE -) -# prepare contact matrix -contact_matrix <- t(contact_data$matrix) -contact_matrix -``` - - -::::::::::::::::::::::::::::::::: -:::::::::::::::::::::::::::::::::::::::::::::::: - -The result is a square matrix with rows and columns for each age group. Contact matrices can be loaded from other sources, but they must be formatted as a matrix to be used in `epidemics`. - -::::::::::::::::::::::::::::::::::::: callout -### Why would a contact matrix be non-symmetric? - -One of the arguments of the function `contact_matrix()` is `symmetric=TRUE`. This means that the total number of contacts of age group 1 with age group 2, should be the same as the total number of contacts of age group 2 and age group 1 (see the `socialmixr` [vignette](https://cran.r-project.org/web/packages/socialmixr/vignettes/socialmixr.html) for more detail). However, when contact matrices are estimated from surveys or other sources, the *reported* number of contacts may differ by age group resulting in a non-symmetric contact matrix [(Prem et al 2021)](https://doi.org/10.1371/journal.pcbi.1009098). -:::::::::::::::::::::::::::::::::::::::::::::::: - - -### 2. Initial conditions - -The initial conditions are the proportion of individuals in each disease state $S$, $E$, $I$ and $R$ for each age group at time 0. In this example, we have three age groups age between 0 and 20 years, age between 20 and 40 years and over. Let's assume that in the youngest age category, one in a million individuals are infectious, and the remaining age categories are infection free. - -The initial conditions in the first age category are $S(0)=1-\frac{1}{1,000,000}$, $E(0) =0$, $I(0)=\frac{1}{1,000,000}$, $R(0)=0$. This is specified as a vector as follows: - -```{r initial_inf} -initial_i <- 1e-6 -initial_conditions_inf <- c( - S = 1 - initial_i, E = 0, I = initial_i, R = 0, V = 0 -) -``` - -For the age categories that are free from infection, the initial conditions are $S(0)=1$, $E(0) =0$, $I(0)=0$, $R(0)=0$. We specify this as follows, - -```{r initial_free} -initial_conditions_free <- c( - S = 1, E = 0, I = 0, R = 0, V = 0 -) -``` - -We combine the three initial conditions vectors into one matrix, - -```{r initial condtions} -# combine the initial conditions -initial_conditions <- rbind( - initial_conditions_inf, # age group 1 - initial_conditions_free, # age group 2 - initial_conditions_free # age group 3 -) - -# use contact matrix to assign age group names -rownames(initial_conditions) <- rownames(contact_matrix) -initial_conditions -``` - - - - -### 3. Population structure -The population object requires a vector containing the demographic structure of the population. The demographic vector must be a named vector containing the number of individuals in each age group of our given population. In this example, we can extract the demographic information from the `contact_data` object that we obtained using the `socialmixr` package. - -```{r demography} -demography_vector <- contact_data$demography$population -names(demography_vector) <- rownames(contact_matrix) -demography_vector -``` - -To create our population object, we call the function `population()` specifying a name, the contact matrix, the demography vector and the initial conditions. - -```{r population} -uk_population <- population( - name = "UK", - contact_matrix = contact_matrix, - demography_vector = demography_vector, - initial_conditions = initial_conditions -) -``` - - -### 4. Model parameters - -To run our model we need to specify the model parameters: - -- transmissibility $\beta$, -- infectiousness rate $\alpha$ (preinfectious period=$1/\alpha$), -- recovery rate $\gamma$ (infectious period=$1/\gamma$). - -In `epidemics`, we specify the model inputs as : - -- `transmissibility` = $R_0 \gamma$, -- `infectiousness_rate` = $\alpha$, -- `recovery_rate` = $\gamma$, - -We will simulate a strain of influenza with pandemic potential with $R_0=1.46$, a preinfectious period of 3 days and infectious period of 7 days. Therefore our inputs will be: - -- `transmissibility = 1.46 / 7.0`, -- `infectiousness_rate = 1.0 / 3.0`, -- `recovery_rate = 1.0 / 7.0`. - -::::::::::::::::::::::::::::::::::::: callout -### The basic reproduction number $R_0$ -The basic reproduction number, $R_0$, for the SEIR model is: - -$$ R_0 = \frac{\beta}{\gamma}.$$ - -Therefore, we can rewrite transmissibility $\beta$, as: - -$$ \beta = R_0 \gamma.$$ - - -:::::::::::::::::::::::::::::::::::::::::::::::: - - - - - -## Running the model - -::::::::::::::::::::::::::::::::::::: callout -### Running (solving) the model - -For models that are described by ODEs, running the model actually means to solve the system of ODEs. ODEs describe the rate of change in the disease states with respect to time, to find the number of individuals in each of these states, we use numerical integration methods to solve the equations. - -In `epidemics`, the [ODE solver](https://www.boost.org/doc/libs/1_82_0/libs/numeric/odeint/doc/html/index.htm) uses the [Runge-Kutta method](https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods). -:::::::::::::::::::::::::::::::::::::::::::::::: - -Now we are ready to run our model. Let's load the `epidemics` package : - -```{r loading} -library(epidemics) -``` - -Then we specify `time_end=600` to run the model for 600 days. -```{r run_model} -output <- model_default_cpp( - population = uk_population, - transmissibility = 1.46 / 7.0, - infectiousness_rate = 1.0 / 3.0, - recovery_rate = 1.0 / 7.0, - time_end = 600, increment = 1.0 -) -head(output) -``` - -*Note : This model also has the functionality to include vaccination and tracks the number of vaccinated individuals through time. Even though we have not specified any vaccination, there is still a vaccinated compartment in the output (containing no individuals). We will cover the use of vaccination in future tutorials.* - -Our model output consists of the number of individuals in each compartment in each age group through time. We can visualise the infectious individuals only (those in the $I$ class) through time. - -```{r visualise, fig.width = 10} -filter(output_plot, compartment %in% c("exposed", "infectious")) %>% - ggplot( - aes( - x = time, - y = value, - col = demography_group, - linetype = compartment - ) - ) + - geom_line( - linewidth = 1.2 - ) + - scale_y_continuous( - labels = scales::comma - ) + - scale_colour_brewer( - palette = "Dark2", - name = "Age group" - ) + - expand_limits( - y = c(0, 500e3) - ) + - coord_cartesian( - expand = FALSE - ) + - theme_bw( - base_size = 15 - ) + - theme( - legend.position = "top" - ) + - labs( - x = "Simulation time (days)", - linetype = "Compartment", - y = "Individuals" - ) -``` - - -::::::::::::::::::::::::::::::::::::: callout -### Time increments - -Note that there is a default argument of `increment = 1`. This relates to the time step of the ODE solver. When the parameters are specified on a daily time-scale and maximum number of time steps (`time_end`) is days, the default time step of the ODE solver one day. - -The choice of increment will depend on the time scale of the parameters, and the rate at which events can occur. In general, the increment should smaller than the fastest event. For example, if parameters are on a monthly time scale, but some events will occur within a month, then the increment should be less than one month. - -:::::::::::::::::::::::::::::::::::::::::::::::: - -## Accounting for uncertainty - -As the epidemic model is [deterministic](../learners/reference.md#deterministic), we have one trajectory for our given parameter values. In practice, we have uncertainty in the value of our parameters. To account for this, we must run our model for different parameter combinations. - -We ran our model with $R_0= 1.5$. However, we believe that $R_0$ follows a normal distribution with mean 1.5 and standard deviation 0.05. To account for uncertainty we will run the model for different values of $R_0$. The steps we will follow to do this are: - -1. Obtain 100 samples from the from a normal distribution - -```{r normal, echo = TRUE} -R0_vec <- rnorm(100, 1.5, 0.05) -``` - -2. Run the model 100 times with $R_0$ equal to a different sample each time - -```{r samples} -output_samples <- Map( - R0_vec, - seq_along(R0_vec), - f = function(x, i) { - # run an epidemic model using `epidemic()` - output <- model_default_cpp( - population = uk_population, - transmissibility = x / 7.0, - infectiousness_rate = 1.0 / 3.0, - recovery_rate = 1.0 / 7.0, - time_end = 600, increment = 1.0 - ) - - # add replicate number and return data - output$replicate <- x - output - } -) - -# combine to prepare for plotting -output_samples <- bind_rows(output_samples) -``` - - -3. Calculate the mean and 95% quantiles of number of infectious individuals across each model simulation and visualise output - -```{r plot, fig.width = 10} -ggplot( - output_samples[output_samples$compartment == "infectious", ], - aes(time, value) -) + - stat_summary(geom = "line", fun = mean) + - stat_summary( - geom = "ribbon", - fun.min = function(z) { - quantile(z, 0.025) - }, - fun.max = function(z) { - quantile(z, 0.975) - }, - alpha = 0.3 - ) + - facet_grid( - cols = vars(demography_group) - ) + - labs( - x = "Simulation time (days)", - y = "Individuals" - ) + - theme_bw( - base_size = 15 - ) -``` - - -Deciding which parameters to include uncertainty in depends on a few factors: how well informed a parameter value is e.g. consistency of estimates from the literature; how sensitive model outputs are to parameter value changes; and the purpose of the modelling task. See [McCabe et al. 2021](https://doi.org/10.1016%2Fj.epidem.2021.100520) to learn about different types of uncertainty in infectious disease modelling. - -## Summary - -In this tutorial, we have learnt how to simulate disease spread using a mathematical model. Once a model has been chosen, the parameters and other inputs must be specified in the correct way to perform model simulations. In the next tutorial, we will consider how to choose the right model for different tasks. - -::::::::::::::::::::::::::::::::::::: keypoints - -- Disease trajectories can be generated using the R package `epidemics` -- Uncertainty should be included in model trajectories using a range of model parameter values - -:::::::::::::::::::::::::::::::::::::::::::::::: diff --git a/learners/setup.md b/learners/setup.md index 47742e35..7d6db2b6 100644 --- a/learners/setup.md +++ b/learners/setup.md @@ -54,8 +54,6 @@ if(!require("pak")) install.packages("pak") new_packages <- c( "EpiNow2", "epiverse-trace/epiparameter", - "socialmixr", - "epiverse-trace/epidemics", "tidyverse" ) @@ -69,8 +67,6 @@ When the installation has finished, you can try to load the packages by pasting ```r library(EpiNow2) library(epiparameter) -library(socialmixr) -library(epidemics) library(tidyverse) ``` diff --git a/renv/profiles/lesson-requirements/renv.lock b/renv/profiles/lesson-requirements/renv.lock index 028832b9..e1c15df3 100644 --- a/renv/profiles/lesson-requirements/renv.lock +++ b/renv/profiles/lesson-requirements/renv.lock @@ -39,34 +39,6 @@ ], "Hash": "9b4993e98e0e19da84c168460c032fef" }, - "DiagrammeR": { - "Package": "DiagrammeR", - "Version": "1.0.11", - "Source": "Repository", - "Repository": "CRAN", - "Requirements": [ - "R", - "RColorBrewer", - "cli", - "dplyr", - "glue", - "htmltools", - "htmlwidgets", - "igraph", - "magrittr", - "purrr", - "readr", - "rlang", - "rstudioapi", - "scales", - "stringr", - "tibble", - "tidyr", - "viridisLite", - "visNetwork" - ], - "Hash": "584c1e1cbb6f9b6c3b0f4ef0ad960966" - }, "EpiNow2": { "Package": "EpiNow2", "Version": "1.4.0", @@ -546,20 +518,6 @@ ], "Hash": "59351f28a81f0742720b85363c4fdd61" }, - "deSolve": { - "Package": "deSolve", - "Version": "1.40", - "Source": "Repository", - "Repository": "CRAN", - "Requirements": [ - "R", - "grDevices", - "graphics", - "methods", - "stats" - ], - "Hash": "0a861334beb4eb8ca0d24a27b28b6679" - }, "desc": { "Package": "desc", "Version": "1.4.3", @@ -674,30 +632,6 @@ ], "Hash": "bb0eec2fe32e88d9e2836c2f73ea2077" }, - "epidemics": { - "Package": "epidemics", - "Version": "0.0.0.9000", - "Source": "GitHub", - "RemoteType": "github", - "RemoteUsername": "epiverse-trace", - "RemoteRepo": "epidemics", - "RemoteRef": "main", - "RemoteSha": "f7e33b594768fb1fdac3fb97f9c075c7f9e9ce76", - "RemoteHost": "api.github.com", - "Requirements": [ - "BH", - "Rcpp", - "RcppEigen", - "checkmate", - "cli", - "data.table", - "deSolve", - "glue", - "stats", - "utils" - ], - "Hash": "3799aa7424ed199ea2f83a439655f1b1" - }, "epiparameter": { "Package": "epiparameter", "Version": "0.0.0.9000", @@ -1102,21 +1036,6 @@ ], "Hash": "2d7b3857980e0e0d0a1fd6f11928ab0f" }, - "htmlwidgets": { - "Package": "htmlwidgets", - "Version": "1.6.4", - "Source": "Repository", - "Repository": "CRAN", - "Requirements": [ - "grDevices", - "htmltools", - "jsonlite", - "knitr", - "rmarkdown", - "yaml" - ], - "Hash": "04291cc45198225444a397606810ac37" - }, "httr": { "Package": "httr", "Version": "1.4.7", @@ -1143,28 +1062,6 @@ ], "Hash": "99df65cfef20e525ed38c3d2577f7190" }, - "igraph": { - "Package": "igraph", - "Version": "2.0.1.1", - "Source": "Repository", - "Repository": "CRAN", - "Requirements": [ - "Matrix", - "R", - "cli", - "cpp11", - "grDevices", - "graphics", - "lifecycle", - "magrittr", - "methods", - "pkgconfig", - "rlang", - "stats", - "utils" - ], - "Hash": "fb2999614d40fe7fd61cf569b66a2dbc" - }, "incidence2": { "Package": "incidence2", "Version": "2.2.3", @@ -1633,7 +1530,7 @@ "Package": "ragg", "Version": "1.2.7", "Source": "Repository", - "Repository": "RSPM", + "Repository": "https://carpentries.r-universe.dev", "Requirements": [ "systemfonts", "textshaping" @@ -1925,7 +1822,7 @@ "Package": "stringi", "Version": "1.8.3", "Source": "Repository", - "Repository": "RSPM", + "Repository": "https://carpentries.r-universe.dev", "Requirements": [ "R", "stats", @@ -2165,24 +2062,6 @@ ], "Hash": "c826c7c4241b6fc89ff55aaea3fa7491" }, - "visNetwork": { - "Package": "visNetwork", - "Version": "2.1.2", - "Source": "Repository", - "Repository": "CRAN", - "Requirements": [ - "R", - "grDevices", - "htmltools", - "htmlwidgets", - "jsonlite", - "magrittr", - "methods", - "stats", - "utils" - ], - "Hash": "3e48b097e8d9a91ecced2ed4817a678d" - }, "vroom": { "Package": "vroom", "Version": "1.6.5", @@ -2209,19 +2088,6 @@ ], "Hash": "390f9315bc0025be03012054103d227c" }, - "webshot": { - "Package": "webshot", - "Version": "0.5.5", - "Source": "Repository", - "Repository": "CRAN", - "Requirements": [ - "R", - "callr", - "jsonlite", - "magrittr" - ], - "Hash": "16858ee1aba97f902d24049d4a44ef16" - }, "withr": { "Package": "withr", "Version": "3.0.0", diff --git a/tutorials.Rproj b/tutorials-middle.Rproj similarity index 100% rename from tutorials.Rproj rename to tutorials-middle.Rproj