---
title: 'The `ammistability` Package: A Brief Introduction'
author: "Ajay, B. C.^1^, Aravind, J.^2^, and Abdul Fiyaz, R.^3^"
date: "`r Sys.Date()`"
classoption: table, twoside
header-includes:
- \usepackage{fancyhdr}
- \usepackage{wrapfig}
- \pagestyle{fancy}
- \fancyhead[LE,RO]{\slshape \rightmark}
- \fancyfoot[C]{\thepage}
- \usepackage{xcolor}
- \usepackage{hyperref}
- \hypersetup{colorlinks=true}
- \hypersetup{linktoc=all}
- \hypersetup{linkcolor=blue}
- \usepackage{pdflscape}
- \usepackage{booktabs}
- \newcommand{\blandscape}{\begin{landscape}}
- \newcommand{\elandscape}{\end{landscape}}
- \fancyhead[LO,RE]{The -\texttt{ammistability} Package{:} A Brief Introduction}
output:
  pdf_document:
    fig_caption: no
    toc: no
  html_document:
    df_print: paged
    toc: yes
csl: frontiers.csl
bibliography: REFERENCES.bib
link-citations: yes
vignette: |
  %\VignetteIndexEntry{Introduction}
  %\usepackage[utf8]{inputenc}
  %\VignetteEngine{knitr::rmarkdown_notangle}
---

```{r, echo=FALSE}
out_type <- knitr::opts_knit$get("rmarkdown.pandoc.to")

r = getOption("repos")
r["CRAN"] = "https://cran.rstudio.com/"
#r["CRAN"] = "https://cloud.r-project.org/"
#r["CRAN"] = "https://ftp.iitm.ac.in/cran/"
options(repos = r)
# options(citation.bibtex.max=999)

# Workaround for missing pandoc in CRAN OSX build machines
out_type <- ifelse(out_type == "", "latex", out_type)

# Workaround for missing pandoc in Solaris build machines
out_type <- ifelse(identical (out_type, vector(mode = "logical", length = 0)),
                   "latex", out_type)
```

```{r, results='asis', echo=FALSE}
switch(out_type,
    html = {cat("<p>1. RRS, ICAR-Directorate of Groundnut Research, Anantapur.</p>

<p>2. ICAR-National Bureau of Plant Genetic Resources, New Delhi.</p>

<p>3. ICAR-Indian Institute of Rice Research, Hyderabad.</p>")},
    latex = cat("\\begin{center}
1. RRS, ICAR-Directorate of Groundnut Research, Anantapur.

2. ICAR-National Bureau of Plant Genetic Resources, New Delhi.

3. ICAR-Indian Institute of Rice Research, Hyderabad.

\\end{center}" )
)
```

\begin{center}
\vspace{6pt}
\hrule
\end{center}

```{r, echo = FALSE}
knitr::opts_chunk$set(
  comment = "",
  fig.cap = ""
)
```

\tableofcontents

\begin{wrapfigure}{r}{0.35\textwidth}
  \vspace{-20pt}
  \begin{center}
    \includegraphics[width=0.33\textwidth]{`r system.file("extdata", "ammistability.png", package = "ammistability")`}
  \end{center}
    \vspace{-20pt}
\end{wrapfigure}

<img src="https://raw.githubusercontent.com/ajaygpb/ammistability/master/inst/extdata/ammistability.png" align="right" alt="logo" width="173" height = "200" style = "padding: 10px; border: none; float: right;">

## Overview

The package `ammistability` [@ajay2019ammistability] is a collection of functions for the computation of various stability parameters from the results of Additive Main Effects and Multiplicative Interaction (AMMI) analysis computed by the  [`AMMI`](https://www.rdocumentation.org/packages/agricolae/versions/1.2-8/topics/AMMI) function of [`agricolae`](https://CRAN.R-project.org/package=agricolae) package.

The goal of this vignette is to introduce the users to these functions and give a primer in computation of various stability parameters/indices from a fitted AMMI model. This document assumes a basic knowledge of `R` programming language.

\clearpage

## Installation
The package can be installed from CRAN as follows:

```{r, eval=FALSE}
# Install from CRAN
install.packages('ammistability', dependencies=TRUE)
```

The development version can be installed from github as follows:

```{r, eval=FALSE}
# Install development version from Github
devtools::install_github("ajaygpb/ammistability")
```

Then the package can be loaded using the function
```{r, eval=TRUE}
library(ammistability)
```

## Version History
```{r, results='asis', echo=FALSE}

# Fetch release version
rver <- ifelse(test = gsub("(.\\.)(\\d+)(\\..)", "", getNamespaceVersion("ammistability")) == "",
               yes = getNamespaceVersion("ammistability"),
               no = ifelse("ammistability" %in% available.packages()[, 1],
                           as.vector(available.packages()["ammistability",]["Version"]),
                           getNamespaceVersion("ammistability")))

```
The current version of the package is `r rver`. The previous versions are as follows.

**Table 1.** Version history of `ammistability` `R` package.

```{r, echo=FALSE, message=FALSE}
if (requireNamespace("RCurl", quietly = TRUE) & requireNamespace("httr", quietly = TRUE) & requireNamespace("XML", quietly = TRUE)) {
pkg <- "ammistability"
link <- paste0("https://cran.r-project.org/src/contrib/Archive/", pkg, "/")

if (RCurl::url.exists(link)) {
  # cafile <- system.file("CurlSSL", "cacert.pem", package = "RCurl")
# page <- httr::GET(link, httr::config(cainfo = cafile))
page <- httr::GET(link)
page <- httr::content(page, as = 'text')
# page <- RCurl::getURL(link)

VerHistory <- XML::readHTMLTable(page)[[1]][,2:3]
colnames(VerHistory) <- c("Version", "Date")
VerHistory <- VerHistory[VerHistory$Version != "Parent Directory",]
VerHistory <- VerHistory[!is.na(VerHistory$Version), ]
VerHistory$Date <- as.Date(VerHistory$Date)
VerHistory$Version <- gsub("ammistability_", "", VerHistory$Version)
VerHistory$Version <- gsub(".tar.gz", "", VerHistory$Version)

VerHistory <- VerHistory[order(VerHistory$Date), c("Version", "Date")]
rownames(VerHistory) <- NULL

knitr::kable(VerHistory)

} else {
  print("Access to CRAN page for 'ammistability' is required to generate this table.'")
}

} else {
print("Packages 'RCurl', 'httr' and 'XML' are required to generate this table.")
}

```

To know detailed history of changes use `news(package='ammistability')`.

## AMMI model
The difference in response of genotypes to different environmental conditions is known as Genotype-Environment Interaction (GEI). Understanding the nature and structure of this interaction is critical for plant breeders to select for genotypes with wide or specific adaptability. One of the most popular techniques to achieve this is by fitting the Additive Main Effects and Multiplicative Interaction (AMMI) model to the results of multi environment trials [@gauch_model_1988; @gauch_statistical_1992]. 

The AMMI equation is described as follows.

$$Y_{ij} = \mu + \alpha_{i} + \beta_{j} + \sum_{n=1}^{N}\lambda_{n}\gamma_{in}\delta_{jn} + \rho_{ij}$$

Where, $Y_{ij}$ is the yield of the $i$th genotype in the $j$th environment, $\mu$ is the grand mean, $\alpha_{i}$ is the genotype deviation from the grand mean, $\beta_{j}$ is the environment deviation, $N$ is the total number of interaction principal components (IPCs), $\lambda_{n}$ is the is the singular value for $n$th IPC and correspondingly $\lambda_{n}^{2}$  is its eigen value, $\gamma_{in}$ is the eigenvector value for $i$th genotype, $\delta_{jn}$  is the eigenvector value for the $j$th environment and $\rho_{ij}$ is the residual.

## AMMI stability parameters

Although the AMMI model can aid in determining genotypes with wide or specific adaptability, it fails to rank genotypes according to their stability. Several measures have been developed over the years to indicate the stability of genotypes from the results of AMMI analysis (Table 1.).

The details about AMMI stability parameters/indices implemented in `ammistability` are described in Table 1.

\newpage
\blandscape

\rowcolors{2}{gray!25}{white}
\renewcommand{\arraystretch}{1.3}

**Table 1 :** AMMI stability parameters/indices implemented in `ammistability`.
\footnotesize
```{r, echo = FALSE, eval = TRUE}
load("stability.rda")

stabparams$`function` <- paste("`", stabparams$`function`, "`", sep = "")

# stabparams$Details <- gsub("\\r\\n\\r\\n", "$$\\\\, $$", stabparams$Details)
# stabparams$Details <- gsub("$$\\, $$$$", "$$", stabparams$Details, fixed = TRUE)
#stabparams$Details <- paste(stabparams$Details, "$$\\\\, $$", sep = "")

stabparams$Details <- gsub("\\r\\n", "\\\\\n", stabparams$Details)

#stabparams$Details <- gsub("\\r\\n\\r\\n", "##", stabparams$Details)
#stabparams$Details <- gsub("##", "\\\n", stabparams$Details)

stabparams$Reference <- gsub("\\[|\\]", "", stabparams$Reference)
stabparams <- stabparams[-c(1),]
rownames(stabparams) <- NULL


```

```{r, echo = FALSE, eval = TRUE}
pander::pander(stabparams, style = 'multiline',
               split.cell = c(15, 15, 50, 10),
               justify = c('left'), split.table = Inf, keep.line.breaks = TRUE,
               use.hyphening = FALSE, missing = "")
```

Where,
  $N$ is the total number of interaction principal components (IPCs);
  $N'$ is the number of significant IPCAs (number of IPC that were retained in the AMMI model via F tests);
  $\lambda_{n}$ is the is the singular value for $n$th IPC and correspondingly $\lambda_{n}^{2}$  is its eigen value;
  $\gamma_{in}$ is the eigenvector value for $i$th genotype;
  $\delta_{jn}$  is the eigenvector value for the $j$th environment;
  $SSIPC_{1}$, $SSIPC_{2}$, $\cdots$, $SSIPC_{n}$ are the sum of squares of the 1st, 2th, ..., and $n$th IPC;
  $PC_{1}$, $PC_{2}$, $\cdots$, $PC_{n}$ are the scores of 1st, 2th, ..., and $n$th IPC;
  $\theta_{n}$ is the percentage sum of squares explained by $n$th principal component interaction effect; and
  $E$ is the number of environments.

\elandscape

\newpage

#### Examples

```{r, echo = FALSE}
# Function saved in functions.R file
getCode <- function(myFunction, myPackage) {
  out <- example(myFunction, myPackage, ask = FALSE, character.only = TRUE,
          prompt.prefix = "", give.lines = TRUE)
  maxn <- grep(pattern = "### ** Examples", x = out, fixed = TRUE)
  out <- out[-(1:maxn)]
  
  return(out)
}
library(ammistability)
require(ammistability)
```

```{r, eval=TRUE, echo = FALSE}
library(ammistability)
```

#### AMMI model from `agricolae::AMMI`
```{r, runCode-AMMI, code = getCode("AMGE.AMMI", "ammistability")[(1:19)]}
```

#### `AMGE.AMMI()`
```{r, runCode-AMGE.AMMI, code = getCode("AMGE.AMMI", "ammistability")[-(1:19)]}
```

#### `ASI.AMMI()`
```{r, runCode-ASI.AMMI, code = getCode("ASI.AMMI", "ammistability")[-(1:19)]}
```

#### `ASTAB.AMMI()`
```{r, runCode-ASTAB.AMMI, code = getCode("ASTAB.AMMI", "ammistability")[-(1:19)]}
```

#### `AVAMGE.AMMI()`
```{r, runCode-AVAMGE.AMMI, code = getCode("AVAMGE.AMMI", "ammistability")[-(1:19)]}
```

#### `DA.AMMI()`
```{r, runCode-DA.AMMI, code = getCode("DA.AMMI", "ammistability")[-(1:19)]}
```

#### `DZ.AMMI()`
```{r, runCode-DZ.AMMI, code = getCode("DZ.AMMI", "ammistability")[-(1:19)]}
```

#### `EV.AMMI()`
```{r, runCode-EV.AMMI, code = getCode("EV.AMMI", "ammistability")[-(1:19)]}
```

#### `FA.AMMI()`
```{r, runCode-FA.AMMI, code = getCode("FA.AMMI", "ammistability")[-(1:19)]}
```

#### `MASV.AMMI()`
```{r, runCode-MASV.AMMI, code = getCode("MASV.AMMI", "ammistability")[-(1:19)]}
```

#### `SIPC.AMMI()`
```{r, runCode-SIPC.AMMI, code = getCode("SIPC.AMMI", "ammistability")[-(1:19)]}
```

#### `ZA.AMMI()`
```{r, runCode-ZA.AMMI, code = getCode("ZA.AMMI", "ammistability")[-(1:19)]}
```

## Simultaneous selection indices for yield and stability

The most stable genotype need not necessarily be the highest yielding genotype. Hence, simultaneous selection indices (SSIs) have been proposed for the selection of stable as well as high yielding genotypes.

A family of simultaneous selection indices ($I_{i}$) were proposed by @rao_use_2005 similar to those proposed by @bajpai_new_2000 by incorporating the AMMI Based Stability Parameter ($ASTAB$) and Yield as components. These indices consist of yield component, measured as the ratio of the average performance of the $i$th genotype to the overall mean performance of the genotypes under test and a stability component, measured as the ratio of stability information ($\frac{1}{ASTAB}$) of the $i$th genotype to the mean stability information of the genotypes under test.

$$I_{i} = \frac{\overline{Y}_{i}}{\overline{Y}_{..}} + \alpha \frac{\frac{1}{ASTAB_{i}}}{\frac{1}{T}\sum_{i=1}^{T}\frac{1}{ASTAB_{i}}}$$

Where $ASTAB_{i}$ is the stability measure of the $i$th genotype under AMMI procedure;  $Y_{i}$ is mean performance of $i$th genotype; $Y_{..}$ is the overall mean; $T$ is the number of genotypes under test and $\alpha$ is the ratio of the weights given to the stability components ($w_{2}$) and yield ($w_{1}$) with a restriction that $w_{1} + w_{2} = 1$. The weights can be specified as required (Table 2).

**Table 2 :** $\alpha$ and corresponding weights ($w_{1}$ and $w_{2}$)
```{r, echo = FALSE, eval = TRUE}
w1 = c(0.5, 0.6, 0.7, 0.8)
w2 = c(0.5, 0.4, 0.3, 0.2)
a = round(w2/w1, 2)

alph <- data.frame(alpha = a, w1, w2)

knitr::kable(alph, row.names = FALSE, col.names = c("$\\alpha$", "$w_{1}$", "$w_{2}$"))

``` 

In `ammistability`, the above expression has been implemented for all the stability parameters ($SP$) including ASTAB.

$$I_{i} = \frac{\overline{Y}_{i}}{\overline{Y}_{..}} + \alpha \frac{\frac{1}{SP_{i}}}{\frac{1}{T}\sum_{i=1}^{T}\frac{1}{SP_{i}}}$$

Genotype stability index ($GSI$) [@farshadfar_incorporation_2008] or Yield stability index ($YSI$) [@farshadfar_ammi_2011; @jambhulkar_stability_2017] is a simultaneous selection index for yield and yield stability which is computed by summation of the ranks of the stability index/parameter and the ranks of the mean yields. $YSI$ is computed for all the stability parameters/indices implemented in this package.

$$GSI = YSI = R_{SP} + R_{Y}$$

Where, $R_{SP}$ is the stability parameter/index rank of the genotype and $R_{Y}$ is the mean yield rank of the genotype.

The function `SSI` implements both these indices in `ammistability`. Further, for each of the stability parameter functions, the simultaneous selection index is also computed by either of these functions as specified by the argument `ssi.method`. 

#### Examples

```{r, echo = FALSE, eval = FALSE}
# Function saved in functions.R file
getCode <- function(myFunction, myPackage) {
  out <- example(myFunction, myPackage, ask = FALSE, character.only = TRUE,
          prompt.prefix = "", give.lines = TRUE)
  maxn <- grep(pattern = "### ** Examples", x = out, fixed = TRUE)
  out <- out[-(1:maxn)]
  
  return(out)
}
library(ammistability)
require(ammistability)
```

#### `SSI()`
```{r, runCode-SSI, code = getCode("SSI", "ammistability")}
```

## Wrapper function

A function `ammistability` has also been implemented which is a wrapper around all the available functions in the package to compute simultaneously multiple AMMI stability parameters along with the corresponding SSIs. Correlation among the computed values as well as visualization of the differences in genotype ranks for the computed parameters is also generated.

#### Examples

```{r, echo = FALSE, eval = FALSE}
# Function saved in functions.R file
getCode <- function(myFunction, myPackage) {
  out <- example(myFunction, myPackage, ask = FALSE, character.only = TRUE,
          prompt.prefix = "", give.lines = TRUE)
  maxn <- grep(pattern = "### ** Examples", x = out, fixed = TRUE)
  out <- out[-(1:maxn)]
  
  return(out)
}
library(ammistability)
require(ammistability)
```

#### `ammistability()`
```{r, runCode-ammistability, code = getCode("ammistability", "ammistability")}
```

## Citing `ammistability`

```{r, echo = FALSE, collapse = TRUE}
# detach("package:ammistability", unload=TRUE)
suppressPackageStartupMessages(library(ammistability))
cit <- citation("ammistability")
# yr <- format(Sys.Date(), "%Y")
# cit[1]$year <- yr
# oc <- class(cit)
# 
# cit <- unclass(cit)
# attr(cit[[1]],"textVersion") <- gsub("\\(\\)",
#                                      paste("\\(", yr, "\\)", sep = ""),
#                                      attr(cit[[1]],"textVersion"))
# class(cit) <- oc
cit
```

## Session Info

```{r}
sessionInfo()
```

## References
