---
title: "Calculating incidence"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{a05_Calculating_incidence}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 7,
  fig.height = 5,
  eval = Sys.getenv("$RUNNER_OS") != "macOS"
)
```


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

# Introduction
Incidence rates describe the rate at which new events occur in a population, with the denominator the person-time at risk of the event during this period. In the previous vignettes we have seen how we can identify a set of denominator and outcome cohorts. Incidence rates can then be calculated using time contributed from these denominator cohorts up to their entry into an outcome cohort.

There are a number of options to consider when calculating incidence rates. This package accommodates two main parameters, including:

1. **Outcome washout**: The number of days used for a 'washout' period between the end of one outcome ending and an individual starting to contribute time at risk again.
2. **Repeated events**: Whether individuals are able to contribute multiple events during the study period or if they will only contribute time up to their first event during the study period.

### No washout, no repetitive events
In this example there is no outcome washout specified and repetitive events are not allowed, so individuals contribute time up to their first event during the study period.
```{r,echo=FALSE, out.width="80%"}
knitr::include_graphics(here("vignettes/inc_no_rep_no_washout.png"))
```

### Washout all history, no repetitive events
In this example the outcome washout is all history and repetitive events are not allowed. As before individuals contribute time up to their first event during the study period, but having an outcome prior to the study period (such as person "3") means that no time at risk is contributed.

```{r,echo=FALSE, out.width="80%"}
knitr::include_graphics(here("vignettes/inc_no_rep_washout_all.png"))
```

### Some washout, no repetitive events
In this example there is some amount of outcome washout and repetitive events are not allowed. As before individuals contribute time up to their first event during the study period, but having an outcome prior to the study period (such as person "3") means that time at risk is only contributed once sufficient time has passed for the outcome washout criteria to have been satisfied.

```{r,echo=FALSE, out.width="80%"}
knitr::include_graphics(here("vignettes/inc_no_rep_some_washout.png"))
```

### Some washout, repetitive events
Now repetitive events are allowed with some amount of outcome washout specified. So individuals contribute time up to their first event during the study period, and then after passing the outcome washout requirement they begin to contribute time at risk again.

```{r,echo=FALSE, out.width="80%"}
knitr::include_graphics(here("vignettes/inc_rep_some_washout.png"))
```

# Outcome definition
Outcome cohorts are defined externally. When creating outcome cohorts for estimating incidence, the most important recommendations for defining an outcome cohort for calculating incidence are:

1. Do not restrict outcome cohorts to first events only. This will impact the ability to exclude participants (as they can be excluded based on the prior latest event) and to capture more than one event per person (which is an option allowed in the package).
2. Set an appropriate cohort exit strategy. If we want to consider multiple events per person, the duration of these events will be of importance, as we are not going to capture subsequent events if prior events have not yet been concluded. In addition, outcome washouts will be implemented relative to cohort exit from any previous event. 
3. Do not add further restrictions on sex, age and prior history requirements. These can be specified when identifying the denominator population with the `generateDenominatorCohortSet()` function.

# Using estimateIncidence()
`estimateIncidence()` is the function we use to estimate incidence rates. To demonstrate its use, let´s load the IncidencePrevalence package (along with a couple of packages to help for subsequent plots) and generate 50,000 example patients using the `mockIncidencePrevalenceRef()` function, from whom we´ll create a denominator population without adding any restrictions other than a study period. In this example we'll use permanent tables (rather than temporary tables which would be used by default).   

```{r setup}
library(IncidencePrevalence)
library(dplyr)
library(tidyr)

cdm <- mockIncidencePrevalenceRef(
  sampleSize = 20000,
  earliestObservationStartDate = as.Date("1960-01-01"), 
  minOutcomeDays = 365,
  outPre = 0.3
)

cdm <- generateDenominatorCohortSet(
  cdm = cdm, name = "denominator",
  cohortDateRange = c(as.Date("1990-01-01"), as.Date("2009-12-31")),
  ageGroup = list(c(0, 150)),
  sex = "Both",
  daysPriorObservation = 0
)

cdm$denominator %>%
  glimpse()
```


Let´s first calculate incidence rates on a yearly basis, without allowing repetitive events
```{r, message= FALSE, warning=FALSE}
inc <- estimateIncidence(
  cdm = cdm,
  denominatorTable = "denominator",
  outcomeTable = "outcome",
  interval = "years",
  outcomeWashout = 0,
  repeatedEvents = FALSE
)

inc %>%
  glimpse()

plotIncidence(inc)
```

Now with a washout of all prior history while still not allowing repetitive events. Here we use `Inf` to specify that we will use a washout of all prior history for an individual.
```{r, message= FALSE, warning=FALSE}
inc <- estimateIncidence(
  cdm = cdm,
  denominatorTable = "denominator",
  outcomeTable = "outcome",
  interval = "years",
  outcomeWashout = Inf,
  repeatedEvents = FALSE
)

inc %>%
  glimpse()

plotIncidence(inc)
```

Now we´ll set the washout to 180 days while still not allowing repetitive events
```{r, message= FALSE, warning=FALSE}
inc <- estimateIncidence(
  cdm = cdm,
  denominatorTable = "denominator",
  outcomeTable = "outcome",
  interval = "years",
  outcomeWashout = 180,
  repeatedEvents = FALSE
)

inc %>%
  glimpse()

plotIncidence(inc)
```

And finally we´ll set the washout to 180 days and allow repetitive events
```{r, message= FALSE, warning=FALSE}
inc <- estimateIncidence(
  cdm = cdm,
  denominatorTable = "denominator",
  outcomeTable = "outcome",
  interval = "years",
  outcomeWashout = 180,
  repeatedEvents = TRUE
)

inc %>%
  glimpse()

plotIncidence(inc)
```

## Stratified analyses
As with prevalence. if we specified multiple denominator populations results will be returned for each. Here for example we define three age groups for denominator populations and get three sets of estimates back when estimating incidence

```{r}
cdm <- generateDenominatorCohortSet(
  cdm = cdm, name = "denominator_age_sex",
  cohortDateRange = c(as.Date("1990-01-01"), as.Date("2009-12-31")),
  ageGroup = list(c(0, 39),
                  c(41, 65),
                  c(66, 150)),
  sex = "Both",
  daysPriorObservation = 0
)
inc <- estimateIncidence(
  cdm = cdm,
  denominatorTable = "denominator_age_sex",
  outcomeTable = "outcome",
  interval = "years",
  outcomeWashout = 180,
  repeatedEvents = TRUE
)

plotIncidence(inc, facet = "denominator_age_group")
```

And again, as with prevalence while we specify time-varying stratifications when defining our denominator populations, if we have time-invariant stratifications we can include these at the the estimation stage. 

```{r}
cdm$denominator <- cdm$denominator %>% 
  mutate(group = if_else(as.numeric(subject_id)  < 3000, "first", "second")) 

inc <- estimateIncidence(
  cdm = cdm,
  denominatorTable = "denominator",
  outcomeTable = "outcome",
  strata = list("group"),
  outcomeWashout = 180,
  repeatedEvents = TRUE
)

plotIncidence(inc, 
               facet = "strata_level")

cdm$denominator <- cdm$denominator %>% 
  mutate(group_1 = if_else(as.numeric(subject_id)  < 3000, "first", "second"),
         group_2 = if_else(as.numeric(subject_id)  < 2000, "one", "two"))

inc <- estimateIncidence(
  cdm = cdm,
  denominatorTable = "denominator",
  outcomeTable = "outcome",
  strata = list(c("group_1"), # for just group_1
                c("group_2"), # for just group_2
                c("group_1", "group_2")),  # for group_1 and group_2  outcomeWashout = 180,
  repeatedEvents = TRUE
)

plotIncidence(inc, 
               facet = "strata_level")
```


### Other parameters
In the examples above, we have used calculated incidence rates by months and years, but it can be also calculated by weeks, months, quarters, or for the entire study time period. In addition, we can decide whether to include time intervals that are not fully captured in the database (e.g., having data up to June for the last study year when computing yearly incidence rates). By default, incidence will only be estimated for those intervals where the denominator cohort captures all the interval (completeDatabaseIntervals=TRUE).

Given that we can set `estimateIncidence()` to exclude individuals based on other parameters (e.g., outcomeWashout), it is important to note that the denominator population used to compute incidence rates might differ from the one calculated with `generateDenominatorCohortSet()`.

The user can also set the minimum number of events to be reported, below which results will be obscured. By default, results with <5 occurrences are blinded, but if minCellCount=0, all results will be reported. 95 % confidence intervals are calculated using the exact method. We can set verbose=TRUE to report progress as code is running. By default, no progress is reported (verbose=FALSE). 

```{r, message=TRUE, warning=FALSE}
inc <- estimateIncidence(
  cdm = cdm,
  denominatorTable = "denominator",
  outcomeTable = "outcome",
  interval = c("weeks"),
  completeDatabaseIntervals = FALSE,
  outcomeWashout = 180,
  repeatedEvents = TRUE,
  minCellCount = 0
)
```

### Output
`estimateIncidence()` will generate a table with incidence rates for each of the time intervals studied and for each combination of the parameters set. Similar to the output obtained by `generateDenominatorCohortSet()`, the table generated will also be associated with attributes such as settings and attrition.

```{r, message= FALSE, warning=FALSE}
inc <- estimateIncidence(
  cdm = cdm,
  denominatorTable = "denominator",
  outcomeTable = "outcome",
  interval = c("Years"),
  outcomeWashout = c(0, 180),
  repeatedEvents = TRUE,
  returnParticipants = TRUE
)
attrition(inc)
```

As with incidence, if we set returnParticipants as TRUE, we can identify the individuals who contributed to the analysis by using `participants(). For example, we can identify those people contributing to analysis 1 by running
```{r, message= FALSE, warning=FALSE}
participants(inc, analysisId = 1) %>%
  glimpse()
```

As we;ve used permanent tables for this example, we can drop these after running our analysis.

```{r, message= FALSE, warning=FALSE}
CDMConnector::listTables(attr(attr(cdm, "cdm_source"), "dbcon"))
CDMConnector::dropTable(cdm = cdm, name = starts_with("denominator"))
CDMConnector::dropTable(cdm = cdm, name = starts_with("inc_participants_"))
CDMConnector::listTables(attr(attr(cdm, "cdm_source"), "dbcon"))
```
