---
title: "infectionIndex: Disease Infection Intensity and Progress Analysis Tools"
author:
  - "Carlos Augusto Dórea Bragança, Universidade Federal do Recôncavo da Bahia (UFRB)"
  - "Malena Andrade Nogueira, Universidade Federal do Recôncavo da Bahia (UFRB)"
date: "`r Sys.Date()`"
output:
  rmarkdown::html_vignette:
    toc: true
vignette: >
  %\VignetteIndexEntry{infectionIndex: Disease Infection Intensity and Progress Analysis Tools}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

# Overview

`infectionIndex` provides tools for the analysis of disease infection
intensity and temporal disease progress in plant pathology experiments.
The package combines disease intensity indices, longitudinal analysis
using generalized estimating equations (GEE), disease progress metrics,
outlier assessment, sensitivity analysis, estimated marginal means,
temporal trends, and graphical visualization.

The main workflow is implemented in `run_di_pipeline()`. The package
also provides individual functions for disease intensity indices, GEE
models, and graphical visualization.

# Experimental data structure

The package is designed primarily around longitudinal disease assessment
data. The example dataset is supplied as an Excel workbook in
`inst/extdata` and can be accessed after installation using
`system.file()`.

A typical long-format dataset contains:

- `block`: experimental block or replicate;
- `trat`: treatment;
- `time`: assessment time;
- `class`: disease intensity class;
- `freq`: frequency of observations in each class.

The long format allows several disease classes to be represented for each
experimental unit and assessment time.

# Disease infection intensity indices

## Czermainski index

The package implements the Czermainski disease infection intensity index
as the principal index used by the main analytical workflow.

For disease classes represented by frequencies $F_0, F_1, \ldots, F_J$,
the implementation calculates the class-dependent weights from the
relative position of each class in the available scale and combines them
with the cumulative class probabilities.

The resulting angular quantity is transformed according to

$$
I = \sin^2(\omega).
$$

An important implementation feature is that the number of classes is
determined from the frequency vector supplied to the function. Thus, the
implementation is not hard-coded to a single disease assessment scale.
This is a computational generalization of the calculation to the number
of classes supplied by the user; it should not be interpreted as a claim
that the original method proposed a different theoretical scale.

The function `amaral_czermainski_I()` can also return the intermediate
angular quantity when requested.

## McKinney index

`mckinney_I()` is included as an alternative or comparative disease
intensity measure.

The index is calculated from the frequencies and the corresponding
disease scores:

$$
I_M = \frac{\sum_i F_i s_i}{n s_{\max}},
$$

where $F_i$ is the frequency in class $i$, $s_i$ is its disease score,
$n$ is the total number of observations, and $s_{\max}$ is the maximum
score.

The default scores are sequential class scores. Users can also provide
an explicit vector of scores when the disease scale is not equally spaced.

# Longitudinal GEE analysis

The temporal analysis uses generalized estimating equations (GEE).
The response supplied to the GEE is the angular transformation of the
disease intensity index, `DI_ang`.

The experimental unit is treated as the longitudinal cluster. Repeated
observations from the same experimental unit are therefore represented
within the same GEE cluster.

The package supports the following working correlation structures:

- AR(1);
- exchangeable;
- independence;
- unstructured.

## Unifactorial experiments

For a single treatment factor, the model without temporal interaction
has the general form

$$
DI_{ang} \sim treatment + time.
$$

The model including temporal interaction is

$$
DI_{ang} \sim treatment * time.
$$

The latter expands to the treatment main effect, time, and the
treatment-by-time interaction.

## Factorial experiments

For multiple treatment factors, the package constructs the factorial
model using the `*` operator. For example, with factors `cultivar` and
`produto`, the interaction model is represented by

$$
DI_{ang} \sim cultivar * produto * time.
$$

This includes the main effects, factorial interactions, temporal effects,
and their corresponding interactions with time.

## Testing temporal interaction

The package first attempts the standard model comparison. When this
comparison is unavailable or fails, a multivariate Wald test is used
to jointly evaluate the coefficients associated with interactions between
the treatment factors and time.

For a vector of interaction coefficients $\boldsymbol{\beta}$ and its
estimated covariance matrix $V$, the Wald statistic is

$$
W = \boldsymbol{\beta}^{T} V^{-1} \boldsymbol{\beta}.
$$

The statistic is evaluated against a chi-squared distribution with degrees
of freedom corresponding to the number of tested coefficients.

The implementation includes numerical safeguards. When coefficients or
their covariance matrix are non-finite, when model dispersion is nearly
zero, when the covariance matrix is singular, or when the calculated
statistic is invalid, the procedure returns an undefined inference
rather than forcing a potentially misleading result.

# Disease progress metrics

## AUDPC

The area under the disease progress curve (AUDPC) is calculated using
the trapezoidal rule:

$$
AUDPC = \sum_{i=1}^{n-1}
\frac{y_i+y_{i+1}}{2}(t_{i+1}-t_i).
$$

This formulation incorporates the actual interval between consecutive
assessments and therefore does not require equally spaced observations.

## AUDPS

The package also implements the area under the disease progress stairs
(AUDPS) following the approach of Simko and Piepho (2012). The
implementation first calculates the trapezoidal area and then adds an
endpoint correction based on the mean assessment interval:

$$
AUDPS = AUDPC +
\frac{y_1+y_n}{2}\frac{D}{n-1},
$$

where $D$ is the elapsed time between the first and last assessments.

# Outlier assessment and sensitivity analysis

The pipeline can identify experimental units flagged as potential
outliers. The default option is to flag these units without automatically
removing them from the principal analysis.

A sensitivity analysis can alternatively be requested through the
`outlier_action` argument. When removal is requested, the package refits
the analysis after excluding the identified units and retains the results
of both the complete and sensitivity analyses.

The purpose of this procedure is to distinguish identification of an
unusual experimental unit from an automatic decision to discard an
observation.

# Estimated marginal means and temporal trends

Estimated marginal means are calculated from the GEE model containing
the temporal interactions.

For each assessment time, the package estimates marginal means for the
specified treatment structure. Pairwise comparisons are performed with
Tukey adjustment.

The package also estimates temporal trends using `emtrends()`. These
estimates represent the fitted temporal slopes for the treatment
combinations represented in the model. Pairwise comparisons among trends
are likewise adjusted using Tukey's method.

Thus, the two analyses answer different questions:

- estimated marginal means compare disease intensity at a particular
  assessment time;
- temporal trends compare rates of change over the assessment period.

# Model-based predictions

The package generates predictions from the GEE model for the observed
combinations of treatment factors and assessment times.

Predictions are initially obtained on the angular scale and subsequently
back-transformed to the original disease intensity scale using

$$
DI = \sin^2(\theta).
$$

Confidence limits are calculated on the angular scale and then transformed
back to the disease intensity scale.

# Graphical visualization

`plot_curves_by_trat()` provides a basic visualization of disease
progress curves by treatment. The current implementation intentionally
keeps this function simple; more extensive graphical options can be
introduced in future versions without changing the core analytical
workflow.

# Complete example

```{r setup, message=FALSE, warning=FALSE}
library(infectionIndex)

example_file <- system.file(
  "extdata",
  "example_long_data.xlsx",
  package = "infectionIndex"
)

if (!nzchar(example_file)) {
  example_file <- file.path(
    "..",
    "inst",
    "extdata",
    "example_long_data.xlsx"
  )
}

example_file <- normalizePath(
  example_file,
  mustWork = TRUE
)

example_file
```

The complete workflow can then be executed directly from the installed
package. The two examples below use the same example dataset but different
disease intensity indices. Each analysis is stored in a separate object
to make the correspondence between the index and the resulting outputs
explicit.

## Example 1 — Czermainski index

The first complete analysis uses the Czermainski disease intensity index.
The workflow includes longitudinal disease-intensity analysis, GEE models,
correlation-structure comparison using QIC/QICC, interaction testing,
model-based predictions, AUDPC/AUC calculation, outlier assessment,
and graphical outputs.

```{r pipeline_czermainski, message=TRUE, warning=FALSE}
res_ex1 <- run_di_pipeline(
  excel_file = example_file,
  index = "czermainski",
  corstr = "ar1",
  progress_metric = "audpc",
  save_outputs = FALSE,
  outlier_action = "flag"
)
```

The principal results from the Czermainski analysis can be inspected
through the `res_ex1$out` object:

```{r results_czermainski, message=FALSE, warning=FALSE}
nrow(res_ex1$out$auc$by_parcela)
nrow(res_ex1$out$auc$summary)
nrow(res_ex1$out$predictions)
nrow(res_ex1$outliers$detected)
res_ex1$out$interaction_test
```

## Example 2 — McKinney index

The second complete analysis uses the McKinney disease intensity index.
It follows the same analytical workflow, including longitudinal
disease-intensity analysis, GEE models, correlation-structure comparison
using QIC/QICC, interaction testing, model-based predictions, AUDPC/AUC
calculation, outlier assessment, and graphical outputs.

The analysis is stored separately in `res_ex2`, so that its results are
not confused with those obtained from the Czermainski analysis.

```{r pipeline_mckinney, message=TRUE, warning=FALSE}
res_ex2 <- run_di_pipeline(
  excel_file = example_file,
  index = "mckinney",
  corstr = "independence",
  progress_metric = "audpc",
  save_outputs = FALSE,
  outlier_action = "flag"
)
```

The principal results from the McKinney analysis can be inspected
through the `res_ex2$out` object:

```{r results_mckinney, message=FALSE, warning=FALSE}
nrow(res_ex2$out$auc$by_parcela)
nrow(res_ex2$out$auc$summary)
nrow(res_ex2$out$predictions)
nrow(res_ex2$outliers$detected)
res_ex2$out$interaction_test
```

# Reproducibility

The example data are distributed with the package so that the complete
workflow can be reproduced after installation without relying on a local
file path.

The package returns both the principal analysis and, when applicable,
the results of the sensitivity analysis. This structure allows users to
inspect intermediate objects rather than treating the pipeline as a
black-box calculation.

# References

Czermainski, A. B. C. (1999). Generalização de um índice de intensidade
de infecção em experimentos de avaliação de doenças em plantas.
*Pesquisa Agropecuária Brasileira*, 34(9), 1545–1555.

McKinney, H. H. (1923). Influence of soil temperature and moisture on
infection of wheat seedlings by *Helminthosporium sativum*.
*Journal of Agricultural Research*, 26, 195–217.

Simko, I., & Piepho, H.-P. (2012). The area under the disease progress
stairs: Calculation, advantage, and application. *Phytopathology*,
102, 381–389. https://doi.org/10.1094/PHYTO-07-11-0216.

# Citation

To cite the software, use the citation information provided by the
package. The citation metadata will be finalized before the first public
release.
