---
title: "Fit one EC50 model"
author: "Kaique S Alves"
date: "`r Sys.Date()`"
output:
  rmarkdown::html_vignette:
    toc: true
    toc_depth: 2
vignette: >
  %\VignetteIndexEntry{Fit one EC50 model}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

## When to Use This Workflow

Use `estimate_EC50()` when the dose-response model is already chosen and should
be fitted to every isolate or isolate-by-stratum group. This is common when a
protocol, previous experiment, or study design already identifies the model that
should be used for final EC50 estimation.

If you still need to compare candidate models, start with
`ec50_multimodel()` instead.

## Packages and Data

```{r message=FALSE, warning=FALSE}
library(ec50estimator)
library(drc)
library(ggplot2)
```

```{r}
data(multi_isolate)

example_data <- subset(
  multi_isolate,
  isolate %in% 1:6 & fungicida == "Fungicide A"
)

head(example_data)
```

## Check Fit Readiness

Before fitting, check whether each isolate and field has enough observations,
enough dose levels, and measurable response variation.

```{r}
check_ec50_data(
  example_data,
  response = "growth",
  dose = "dose",
  isolate = "isolate",
  strata = "field"
)
```

## Fit the Model

`estimate_EC50()` takes a `drc` model function through `fct`. The example below
fits a three-parameter log-logistic model within each isolate and field.

```{r}
fit <- estimate_EC50(
  growth ~ dose,
  data = example_data,
  isolate_col = "isolate",
  strata_col = "field",
  fct = drc::LL.3(),
  interval = "delta"
)

head(fit)
```

The object behaves like a data frame. The first columns identify the isolate
and strata. The remaining columns contain the EC50 estimate and uncertainty
columns returned by `drc::ED()`.

```{r}
ec50_estimates(fit)
```

## Review the Fit Object

Use metadata and quality helpers to understand what was fitted.

```{r}
ec50_metadata(fit)

fit_quality(fit)

fit_failures(fit)
```

For advanced users, `fitted_models()` returns the stored `drc` model objects.
Most users can stay with the higher-level helpers.

```{r}
models <- fitted_models(fit)

length(models)
names(models)[1:3]
```

## Plot the Fitted Curves

Pass the fitted object directly to `plot_EC50_curves()`. The function uses the
stored formula, data, grouping columns, and fitted models.

```{r fig.alt="Faceted dose-response plot with raw observations and one fitted EC50 curve for each isolate and field."}
plot_EC50_curves(fit)
```

If your experiment has more than one stratum, the first stratum is used as
columns and the second as rows by default. You can override the layout with
`facet_col` and `facet_row`.

## Predict and Report

Use `predict_ec50()` to predict the response at doses chosen by the user.

```{r}
predict_ec50(
  fit,
  dose = c(0.001, 0.01, 0.1)
)
```

Use `report_ec50()` when you want a plain table for export or manuscript work.

```{r}
report_ec50(fit)
```

## Build a Custom Figure

`curve_data()` returns the coordinates used to draw the fitted curves. This is
useful when you want full control over a `ggplot2` figure.

```{r}
curves <- curve_data(fit)

head(curves)
```

```{r fig.alt="Custom EC50 estimate plot showing EC50 estimates and confidence intervals by isolate and field."}
estimates <- ec50_estimates(fit)
estimates$ID <- factor(estimates$ID, levels = sort(unique(estimates$ID)))

ggplot(estimates, aes(ID, Estimate, color = field)) +
  geom_point(size = 2) +
  geom_errorbar(aes(ymin = Lower, ymax = Upper), width = 0.15) +
  scale_y_log10() +
  labs(x = "Isolate", y = "EC50", color = "Field") +
  theme_light()
```

## Check Residuals

Residual diagnostics are available as data and as a `ggplot2` figure.

```{r}
head(residual_data(fit))
```

```{r fig.alt="Residual diagnostic plot with residuals against fitted values for EC50 models."}
plot_residuals(fit)
```
