---
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 _baystability-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("baystability", quietly = TRUE)) library(baystability) else
  pkgload::load_all(export_all = FALSE, helpers = FALSE, quiet = TRUE)
```

# Abstract

`bys_app()` opens an application in the web browser that runs the analyses of the package without code: the trial,
the earlier trial as prior, the Bayesian AMMI or SREG model, the biplot with HPD regions and a comparison of models.
This vignette describes its pages and how it keeps its results reproducible.

# Starting the application

```{r launch, eval = FALSE}
bys_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, smaller than 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; otherwise the application sends PNG images.

# The pages

| Page | What it does |
|---|---|
| Home | what the application does and the order of the pages |
| Data | the `cultivo2009` example or a CSV file with one row per plot; the response, genotype, environment and replicate columns; the earlier trial as prior: none, `cultivo2008` or a CSV file with the same columns |
| Model | AMMI or SREG, number of terms (0 for all), weight of the earlier trial, iterations, burn-in, thinning, chains, seed and vague priors; then the summary, traces, densities, the biplot of posterior means and the main effects |
| Biplot | the biplot with HPD regions, for genotypes, environments or both |
| Model choice | DIC and WAIC of models with different numbers of terms, with the earlier trial and, on request, without it |
| References | the articles behind the methods, as `bys_cite()` prints them |

Every result page has the same tabs:

* **Interpretation** gives the plain-language reading of `bys_interpret()`, with a button that copies it.
* **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 of `cultivo2009` with `cultivo2008` as prior and two terms:

```{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 biplot page of the same fit:

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

# Reproducibility

For the settings of the screenshots, the R code tab shows:

```{r code}
settings <-
  list(
      .y      = "y"
    , .gen    = "entry"
    , .env    = "site"
    , .rep    = "rep"
    , .nIter  = 3000
    , .n0     = NULL
    , .model  = "AMMI"
    , .k      = 2
    , .burnin = 1000
    , .thin   = 1
    , .chains = 2
    , .priors = bys_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
    )
cat(baystability:::.bys_app_code(a = settings, source = "cultivo", prior_source = "cultivo"))
```

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

# Deploying

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

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

# 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(1), 15--37. doi:10.1007/s13253-011-0063-9
