---
title: "The Bayesian GGE (SREG) model"
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{The Bayesian GGE (SREG) model}
  %\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 = 5.5,
                      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

The GGE model, also called the sites regression (SREG) model, puts the genotype main effects into the bilinear terms.
Its biplot shows directly which genotype wins where (Yan et al. 2000). `bayes_ammi(.model = "GGE")` fits it by the
Gibbs sampler of Perez-Elizalde et al. (2012), and `bam_winners()` turns the draws into probabilities that each
genotype wins in each environment.

# Model

$$y_{ijl} = \mu + \delta_j + \sum_{k=1}^{K}\lambda_k\alpha_{ik}\gamma_{jk} + e_{ijl}.$$

There are no genotype effects $\tau_i$. The genotype scores $\va_k$ still sum to zero, but the environment scores
$\vg_k$ are only orthonormal: they need not sum to zero, because the bilinear terms now carry the genotype main
effects. The conditional of $\vg_k$ is therefore von Mises-Fisher on the sphere orthogonal to the other environment
vectors only.

# The fit

```{r gge}
fg <-
  bayes_ammi(
      .data   = Maiz
    , .y      = y
    , .gen    = entry
    , .env    = site
    , .rep    = rep
    , .nIter  = 3000
    , .k      = 2
    , .burnin = 500
    , .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   = 5
    , .align  = TRUE
    , .model  = "GGE"
    , .het    = FALSE
    , .waic   = TRUE
    )
fg
```

# The GGE biplot with HPD regions

```{r gge-bip, fig.width = 9}
bg <-
  biplots(
      model         = fg
    , burnin        = 0
    , thin          = 1
    , pb            = 0.05
    , plot_stable   = TRUE
    , plot_unstable = TRUE
    , ncolors       = 5
    , .which        = "both"
    , .grid         = 100
    )
bg$biplot
```

On a GGE biplot the first axis mostly reflects the genotype means. A genotype region that lies away from the origin
on the first axis therefore marks a genotype that is above or below average, rather than one with interaction.

# Which genotype wins where

The winner of environment $j$ is the genotype with the largest $\eta_{ij}$. Over the draws, $P_{ij}$ is the
posterior probability that genotype $i$ wins in environment $j$:

```{r winners}
wg <-
  bam_winners(
      fit           = fg
    , higher_better = TRUE
    )
wg
```

```{r winners-plot, fig.height = 4.8}
plot(x = wg)
```

```{r mega, include = FALSE}
mg <- wg$mega
```

The environments split into `r nrow(mg)` groups by their most probable winner. In a GGE analysis such groups are the
candidates for mega-environments. The probability column shows how sure each assignment is: a winner with probability
near one half has a close rival, given in `Second`.

# AMMI or GGE?

The two models describe the same cell means with different constraints, so they fit almost equally well:

```{r gge-ammi}
fa <-
  bayes_ammi(
      .data   = Maiz
    , .y      = y
    , .gen    = entry
    , .env    = site
    , .rep    = rep
    , .nIter  = 3000
    , .k      = 2
    , .burnin = 500
    , .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   = 5
    , .align  = TRUE
    , .model  = "AMMI"
    , .het    = FALSE
    , .waic   = TRUE
    )
bam_compare(
    AMMI = fa
  , GGE  = fg
  )
```

Choose AMMI to study interaction separately from the genotype means, and GGE to study which genotype wins where.

# Interpretation

```{r gge-int}
bam_interpret(
    x             = wg
  , higher_better = TRUE
  , top           = 5
  )
```

# References

Perez-Elizalde, S., Jarquin, D. and Crossa, J. (2012). A general Bayesian estimation method of linear-bilinear models applied to plant breeding trials with genotype x environment interaction. *Journal of Agricultural, Biological, and Environmental Statistics*, 17, 15--37. doi:10.1007/s13253-011-0063-9

Yan, W., Hunt, L. A., Sheng, Q. and Szlavnics, Z. (2000). Cultivar evaluation and mega-environment investigation based on the GGE biplot. *Crop Science*, 40(3), 597--605.

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

Wood, A. T. A. (1994). Simulation of the von Mises Fisher distribution. *Communications in Statistics - Simulation and Computation*, 23(1), 157--164.
