---
title: Probability of freedom
author: Thomas Rosendal [![ORCID iD](https://orcid.org/sites/default/files/images/orcid_16x16.gif)](https://orcid.org/0000-0002-6576-9668)
output:
  html_document:
    toc: true
    toc_float:
      collapsed: false
      smooth_scroll: true
    toc_depth: 3
vignette: >
  %\VignetteIndexEntry{Probability of freedom}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

# Simple freedom calculation

## Scenario

You have a population of 10000 herds of which 500 are tested per year
using a test that has a herd sensitivity (HSe) of 20%; all of these
tests were negative. You need to calculate the annual surveillance
system sensitivity (SysSe) and the probability that the disease has a
lower than 1% prevalence (dp) in the population of herd over time
given a prior assumption that the probability of the disease being
absent from the population is 50% (prior_pr). You also assume that the
annual cumulative probability of introduction to the population is 1%
(prob_intro). This programme was ongoing from 2012 to 2020.

## Calculate system sensitivity

```{r, echo = TRUE, eval = TRUE, message = FALSE, results = 'hide'}
library(freedom)

Hse <- rep(0.2, 500)
dp <- rep(0.01, 500)
SysSe <- sysse(dp, Hse)

```

## Temporal discounting

The surveillance system has a sensitivity of detecting the disease at
a prevalence of greater than of equal to `r dp[1]` is `r SysSe` for 1
year. We can then use this to calculate the probability of freedom of
disease over time.

```{r, echo = TRUE, eval = TRUE, message = FALSE, results = 'hide'}
prior_pr <- 0.5
prob_intro <- 0.01

pr_free <- data.frame(year = 2012:2020,
                      prior_fr = NA,
                      post_fr = NA,
                      stringsAsFactors = FALSE)
## At the beginning of the first year the probability of freedom is just
## the prior.

pr_free$prior_fr[1] <- prior_pr
pr_free$post_fr[1] <- post_fr(pr_free$prior_fr[1], SysSe)

## Then we use the temporal discouting proceedure to calculate the subsequent
## years:

for (i in seq(2, nrow(pr_free))) {
    pr_free$prior_fr[i] <- prior_fr(pr_free$post_fr[i - 1], prob_intro)
    pr_free$post_fr[i] <- post_fr(pr_free$prior_fr[i], SysSe)
}

```

## Plot results

Now we have the prior and posterior probability of freedom in the
population for each of the 8 years of surveillance:

```{r, echo = TRUE, eval = TRUE, message = FALSE}
pr_free
plot(x = pr_free$year,
     y = pr_free$post_fr,
     type = "l",
     xlab = "year",
     ylab = "probability of freedom",
     main = "Probability of freedom at the end of each calendar year")
```
