---
title: "Fitting epicurves"
author: "Tim Taylor"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Fitting epicurves}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.align = "center",
  fig.width = 7,
  fig.height = 5
)
```

# Example
To illustrate the trend fitting functionality of *i2extras* we will use
the simulated Ebola Virus Disease (EVD) outbreak data from the
[outbreaks](https://CRAN.R-project.org/package=outbreaks) package.

## Loading relevant packages and data
```{r}
library(outbreaks)
library(i2extras)
library(ggplot2)

raw_dat <- ebola_sim_clean$linelist
```

For this example we will restrict ourselves to the first 20 weeks of data:

```{r}
dat <- incidence(
    raw_dat, 
    date_index = "date_of_onset",
    interval = "week",
    groups = "gender"
)[1:20, ]
dat
plot(dat, angle = 45, border_colour = "white")
```

## Modeling incidence
We can use `fit_curve()` to fit the data with either a poisson or 
negative binomial regression model.  The output from this will be a nested
object with class `incidence2_fit` which has methods available for both 
automatic plotting and the calculation of growth (decay) rates and doubling
(halving) times.

```{r}
out <- fit_curve(dat, model = "poisson", alpha = 0.05)
out
plot(out, angle = 45, border_colour = "white")
growth_rate(out)
```

To unnest the data we can use `unnest()` (a function that has been reexported
from the [tidyr](https://cran.r-project.org/package=tidyr) package.

```{r}
unnest(out, estimates)
```

`fit_curve()` also works nicely with grouped `incidence2` objects.  In this
situation, we return a nested tibble with some additional columns that 
indicate whether there has been a warning or error during the fitting
or prediction stages.

```{r}
grouped_dat <- incidence(
    raw_dat, 
    date_index = "date_of_onset",
    interval = "week",
    groups = "hospital"
)[1:120, ]
grouped_dat

out <- fit_curve(grouped_dat, model = "poisson", alpha = 0.05)
out

# plot with a prediction interval but not a confidence interval
plot(out, ci = FALSE, pi=TRUE, angle = 45, border_colour = "white")
growth_rate(out)
```

We provide helper functions, `is_ok()`, `is_warning()` and `is_error()` to
help filter the output as necessary.

```{r}
out <- fit_curve(grouped_dat, model = "negbin", alpha = 0.05)
is_warning(out)
unnest(is_warning(out), fitting_warning)
```


## Rolling average
We can add a rolling average, across current and previous intervals, to
an `incidence2` object with the `add_rolling_average()` function:

```{r rolling_average}
ra <- add_rolling_average(grouped_dat, n = 2L) # group observations with the 2 prior
plot(ra, border_colour = "white", angle = 45) +
    geom_line(aes(x = date_index, y = rolling_average))
```
