---
title: "Interpreting the results"
author: "Muhammad Yaseen"
date: last-modified
format:
  html:
    self-contained: true
    number-sections: true
    toc: true
    toc-depth: 3
    highlight-style: pygments
    code-tools: true
    html-math-method: mathjax
vignette: >
  %\VignetteIndexEntry{Interpreting the results}
  %\VignetteEngine{quarto::html}
  %\VignetteEncoding{UTF-8}
execute:
  echo: true
  warning: false
  message: false
---

{{< include _bayesammi-macros.txt >}}

```{r setup, include = FALSE}
# HTML figures are drawn as PNG and kept as WebP: lossless (the same pixels in about half the space of PNG), or
# lossy at quality 90 when that is less than half the size, as for traces and densities of thousands of draws. The
# PDF figures stay vector graphics. Any failure of magick (not installed, no WebP, or a broken installation whose
# system libraries are missing) keeps the PNG
webp <- function(path) {
  if (knitr::is_latex_output() || !grepl(pattern = "[.]png$", x = path)) return(path)
  tryCatch(
      {
        if (!requireNamespace("magick", quietly = TRUE) || !isTRUE(magick::magick_config()$webp)) return(path)
        img <- magick::image_read(path)
        out <- sub(pattern = "[.]png$", replacement = ".webp", x = path)
        tmp <- tempfile(fileext = ".webp")
        magick::image_write(
            image   = img
          , path    = out
          , format  = "webp"
          , quality = 100
          , defines = c(`webp:lossless` = "true")
          )
        magick::image_write(image = img, path = tmp, format = "webp", quality = 90)
        if (file.size(tmp) < file.size(out) / 2) file.copy(from = tmp, to = out, overwrite = TRUE)
        unlink(c(path, tmp))
        out
      }
    , error = function(e) path
    )
}
knitr::opts_chunk$set(collapse = FALSE, comment = "", fig.width = 7, fig.height = 4.2,
                      dev = if (knitr::is_latex_output()) "cairo_pdf" else "ragg_png", dpi = 96,
                      fig.process = webp)
if (requireNamespace("bayesammi", quietly = TRUE)) library(bayesammi) else
  pkgload::load_all(export_all = FALSE, helpers = FALSE, quiet = TRUE)
```

# Abstract

`bam_interpret()` writes a plain-language interpretation of a result of `bayes_ammi()`, `biplots()` or `ge_ammi()`.
Every sentence is computed from the numbers of the result. This vignette shows the interpretations and the rules
behind them.

```{r fit}
fit <-
  bayes_ammi(
      .data   = Maiz
    , .y      = y
    , .gen    = entry
    , .env    = site
    , .rep    = rep
    , .nIter  = 4000
    , .k      = 2
    , .burnin = 1000
    , .thin   = 1
    , .chains = 2
    , .priors = bam_priors(
          mu_mean     = 0
        , mu_var      = 1e+8
        , tau_mean    = 0
        , tau_var     = 1e+8
        , delta_mean  = 0
        , delta_var   = 1e+8
        , lambda_mean = 0
        , lambda_var  = 1e+8
        , nu          = 1
        , s2          = NULL
        )
    , .level  = 0.95
    , .seed   = 8
    , .align  = TRUE
    , .model  = "AMMI"
    , .het    = FALSE
    , .waic   = TRUE
    )
```

# The Bayesian AMMI fit

```{r int1}
txt <-
  bam_interpret(
      x             = fit
    , higher_better = TRUE
    , top           = 5
    )
txt
```

The rules:

* **Convergence**: potential scale reduction factor below 1.1, effective sample size of the main parameters at least
  400, Raftery-Lewis dependence factor below 5, and no more than 10% of the Heidelberger-Welch tests failed.
* **Main effects**: a genotype or environment differs from the average when the HPD interval of its effect excludes
  zero.
* **Bilinear terms**: a term whose HPD interval of $\lambda_k$ reaches below a tenth of its posterior mean is weakly
  supported.
* **Interaction**: significant first scores of the same sign mean a positive interaction.

# The facts behind the sentences

```{r facts}
str(object = txt$facts[c("converged", "max_rhat", "genotypes_above", "axis1_genotypes_positive",
                          "axis1_environments_positive", "weak_terms")])
```

# The biplot

```{r int2}
bp <-
  biplots(
      model         = fit
    , burnin        = 0
    , thin          = 0.5
    , pb            = 0.05
    , plot_stable   = TRUE
    , plot_unstable = TRUE
    , ncolors       = 5
    , .which        = "both"
    , .grid         = 100
    )
bam_interpret(
    x             = bp
  , higher_better = TRUE
  , top           = 5
  )
```

# Stability models

```{r int-stab}
fs <-
  bayes_stability(
      .data   = Maiz
    , .y      = y
    , .gen    = entry
    , .env    = site
    , .rep    = rep
    , .model  = "ER"
    , .nIter  = 2000
    , .burnin = 500
    , .thin   = 1
    , .chains = 2
    , .priors = bam_stab_priors(
          mu_var = NULL
        , g_var  = NULL
        , h_var  = NULL
        , b_var  = 100
        , nu     = 1
        , s2     = NULL
        , nu_d   = 1
        , s2_d   = NULL
        )
    , .level  = 0.95
    , .alpha  = 0.05
    , .seed   = 8
    , .waic   = TRUE
    )
bam_interpret(
    x             = fs
  , higher_better = TRUE
  , top           = 5
  )
```

Every interpretation ends with the sources of the method; `bam_cite()` gives them as BibTeX.

# Decisions and model choice

The results of the decision tools and of the model choice functions have interpretations too:

```{r int3}
bam_interpret(
    x             = bam_superiority(
        fit           = fit
      , .s            = 0.2
      , higher_better = TRUE
      )
  , higher_better = TRUE
  , top           = 5
  )
bam_interpret(
    x             = bam_ppc(
        fit    = fit
      , .draws = 300
      , .seed  = 1
      )
  , higher_better = TRUE
  , top           = 5
  )
```

# Markdown for reports

```{r md, results = "asis"}
cat(format(x = txt, style = "markdown"), sep = "\n")
```

# How each method is read

```{r guide}
cat(strwrap(x = txt$guide, width = 80), sep = "\n")
```

# References

Crossa, J., Perez-Elizalde, S., Jarquin, D., Cotes, J. M., Viele, K., Liu, G. and Cornelius, P. L. (2011). Bayesian estimation of the additive main effects and multiplicative interaction model. *Crop Science*, 51(4), 1458--1469. doi:10.2135/cropsci2010.06.0343
