---
title: "The built-in application"
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 built-in application}
  %\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_app()` opens an application in the web browser that runs every analysis of the package without code. This
vignette describes its pages and how it keeps its results reproducible.

# Starting the application

```{r launch, eval = FALSE}
bam_app(
    launch.browser = TRUE
  )
```

The application needs the suggested packages **shiny**, **bslib** and **DT**. **magick** with WebP support is
optional: with it the plots are sent to the browser as lossless WebP images, about half the size of the same PNG.

```{r webp}
isTRUE(tryCatch(requireNamespace("magick", quietly = TRUE) && isTRUE(magick::magick_config()$webp),
                error = function(e) FALSE))
```

`TRUE` means WebP is available. A magick installation that no longer loads, because the ImageMagick libraries of the
system were removed or upgraded, gives `FALSE`, and the application then sends PNG images; reinstalling magick
restores WebP.

# The pages

| Page | What it does |
|---|---|
| Home | what the application does and the order of the pages |
| Data | the `Maiz` example or a CSV file with one row per plot; choice of the response, genotype, environment and replicate columns |
| Model | AMMI or GGE, number of terms, common or environment-specific variances, iterations, burn-in, thinning, chains, seed and priors; then the summary, traces and densities |
| Biplot | the biplot with HPD regions, for genotypes, environments or both |
| Decisions | winners, probabilities of superior performance, ranks, stability and predictions |
| Stability | Bayesian Eberhart-Russell, Finlay-Wilkinson and Shukla models; classical and AMMI-based stability indices |
| Model choice | posterior predictive checks and a comparison of the fits of the session |

Every result page has the same tabs:

* **Interpretation** gives the plain-language reading of `bam_interpret()`, with a button that copies it, and the
  sources of the method.
* **Plot** shows the figure, which can be saved as PNG, PDF or WebP.
* **Table** shows the numbers, rounded, in a sortable table with buttons to copy them or save them as CSV or Excel.
* **Output** shows the printed result as text, with a button that copies it.

The model page has a further tab, **R code**, with the code that reproduces the fit outside the application.

The model page after a fit, with the interpretation tab open:

```{r shot-model, echo = FALSE, out.width = "100%"}
knitr::include_graphics(path = if (knitr::is_latex_output()) "figures/app-model.jpg" else "figures/app-model.webp")
```

The plot tab of the Bayesian Eberhart-Russell model on the Stability menu:

```{r shot-stab, echo = FALSE, out.width = "100%"}
knitr::include_graphics(path = if (knitr::is_latex_output()) "figures/app-stability.jpg" else "figures/app-stability.webp")
```

The screenshots are lossless WebP in the HTML version: `r round(file.size("figures/app-model.webp") / 1024)` KB for the
first, against `r round(file.size("figures/app-model.jpg") / 1024)` KB for the lossy JPEG of the PDF version.

# Reproducibility

For the default settings with environment-specific variances, the R code tab shows:

```{r code}
settings <-
  list(
      .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   = 1
    , .model  = "AMMI"
    , .het    = TRUE
    )
cat(bayesammi:::.bam_app_code(a = settings, source = "maiz"))
```

The seed fixes the draws, so the code returns the same numbers as the application.

# Deploying

`bam_app_object()` returns the application object without running it, for a server:

```{r deploy, eval = FALSE}
# app.R on a Shiny server
bayesammi::bam_app_object()
```

# 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
