---
title: "Model fitting workflows"
author: "Kaique S. Alves"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Model fitting workflows}
  %\VignetteEncoding{UTF-8}
  %\VignetteEngine{knitr::rmarkdown}
---

```{r setup, message=FALSE, warning=FALSE}
library(epifitter)
library(dplyr)
library(ggplot2)
library(cowplot)
theme_set(cowplot::theme_half_open(font_size = 12))
```

## Overview

`epifitter` offers three complementary fitting workflows:

- `fit_lin()` for linearized model comparison;
- `fit_nlin()` for nonlinear fitting of two-parameter models;
- `fit_nlin2()` for nonlinear fitting when the asymptote `K` should be estimated.

## Compare models quickly with `fit_lin()`

```{r}
set.seed(1)
epi <- sim_logistic(N = 60, y0 = 0.01, dt = 5, r = 0.12, alpha = 0.2, n = 4)

fit_lin_out <- fit_lin(time = epi$time, y = epi$random_y)
knitr::kable(fit_lin_out$stats_all, digits = 4)
```

```{r fig.alt="Faceted plot comparing logistic and Gompertz fitted curves against observed disease intensity values."}
plot_fit(fit_lin_out, models = c("Logistic", "Gompertz"))
```

## Nonlinear fitting with starting values

```{r eval=FALSE}
fit_nlin_out <- fit_nlin(
  time = epi$time,
  y = epi$random_y,
  starting_par = list(y0 = 0.01, r = 0.03)
)

fit_nlin_out$stats_all
```

## Estimate `K` when the epidemic plateaus below 1

```{r eval=FALSE}
epi_partial <- epi %>%
  mutate(random_y = random_y * 0.8)

fit_k <- fit_nlin2(
  time = epi_partial$time,
  y = epi_partial$random_y,
  starting_par = list(y0 = 0.01, r = 0.03, K = 0.7)
)

fit_k$stats_all
```

## Grouped fitting with `fit_multi()`

```{r}
epi1 <- sim_gompertz(N = 50, y0 = 0.001, dt = 5, r = 0.08, alpha = 0.2, n = 3)
epi2 <- sim_gompertz(N = 50, y0 = 0.002, dt = 5, r = 0.11, alpha = 0.2, n = 3)

multi_epi <- bind_rows(epi1, epi2, .id = "curve")

multi_fit <- fit_multi(
  time_col = "time",
  intensity_col = "random_y",
  data = multi_epi,
  strata_cols = "curve"
)

knitr::kable(head(multi_fit$Parameters), digits = 4)
knitr::kable(head(multi_fit$Data), digits = 4)
```
