%-------------------------------------------------------------------------------
%	Packages and other document configurations.
%-------------------------------------------------------------------------------
\documentclass[a4paper,11pt]{article}
% Package declaration.
%-------------------------------------------------------------------------------
% Specify input encoding.
\usepackage[utf8]{inputenc}

% For A4 paper set all margins.
\usepackage[paper=a4paper,left=1.5cm,top=2cm,right=1.5cm,bottom=2cm]{geometry}
% Set linespace, usage \doublespacing \singlespacing \onehalfspacing.
\usepackage{setspace}
% Set palatino font with small caps as default.
\usepackage[sc]{mathpazo}
% Rotation tools, including rotated full-page floats.
\usepackage{rotating}
% Create subfigures.
\usepackage{subfigure}
% Extensive support for hypertext in LaTeX.
\usepackage{hyperref}
% For adding bookmarks to the document.
\usepackage{bookmark}
% For adding time to the document.
\usepackage{datetime}
% For alignment of captions.
\usepackage{caption}
% For multiple columns.
\usepackage{multicol}
% For adding time to the document.
\usepackage{datetime}
% For left aligning captions
\captionsetup{justification=raggedright,singlelinecheck=false}

% Load required R packages.
<<label=setup, include=FALSE, cache=FALSE>>=
lapply(list("SpATS"), library, character.only = TRUE)
trial <- list(...)$trial
trait <- list(...)$trait
descending <- list(...)$descending
## helper function to display table rows starting with "BOLD" in bold.
boldRow <- function(x) {
  gsub(pattern = "BOLD(.*)", replacement = paste("\\\\textbf{\\1", "}"), x)
}
@

% Start header
%-------------------------------------------------------------------------------
% Title
\title{Single trial analysis for \Sexpr{escapeLatex(trait)} in \Sexpr{escapeLatex(trial)}}
% Authors
\author{\vspace{-5ex}}
%-------------------------------------------------------------------------------
% Dates
\date{\vspace{-5ex}}
%-------------------------------------------------------------------------------
% End header

% Start Document
%-------------------------------------------------------------------------------
\begin{document}

<<label=extractInfo, echo=FALSE, include=FALSE>>=
## Extract basic modelling information
engine <- x[[trial]]$engine
if (is.null(x[[trial]]$mFix)) {
  model <- x[[trial]]$mRand[[trait]]
  modelType <- "random"
  predName <- "BLUPs"
} else {
  model <- x[[trial]]$mFix[[trait]]
  modelType <- "fixed"
  predName <- "BLUEs"
}
## Get use of checkId from model call.
useCheckId <- x[[trial]]$useCheckId
@

% Article title, Authors and Affiliations
\maketitle

% Start single line spacing
\singlespacing

%-------------------------------------------------------------------------------
\section{General information}
%-------------------------------------------------------------------------------
<<label=general, echo=FALSE, results="asis">>=
bgItems <- c(format(attr(x, "timestamp"), "%y-%m-%d %H:%M:%S"),
             as.character(packageVersion("statgenSTA")),
             engine)
names(bgItems) <- c("Analysis done on",
                    "statgenSTA version",
                    "Mixed model engine")
print(xtable::xtable(x = data.frame(bgItems), label = "general",
                     align = c("l", "l")),
      latex.environments = "flushleft", hline.after = NULL,
      include.rownames = TRUE, include.colnames = FALSE)
@

%-------------------------------------------------------------------------------
\section{Description of the fitted model}
%-------------------------------------------------------------------------------

<<label=modelDescription, echo=FALSE, results="asis">>=
modelDesigns <- c("block (R)",
                  "replicate (F) + block(replicate) (R)",
                  "replicate (F)",
                  "row (R) + col (R)",
                  "replicate (F) + row(replicate) (R) + col(replicate) (R)")
names(modelDesigns) <- c("ibd", "res.ibd", "rcbd", "rowcol", "res.rowcol")
if (useCheckId) {
  modelDesigns <- paste("checkId (F) +", modelDesigns)
}
descrItems <- c(trial, trait, modelDesigns[x[[trial]]$design],
                if (!is.character(x[[trial]]$spatial[[trait]])) "none" else
                  x[[trial]]$spatial[[trait]],
                modelType)
names(descrItems) <- c("Trial", "Trait",
                       "Experimental design features",
                       "Spatial model",
                       "Genotype")
print(xtable::xtable(x = data.frame(descrItems), label = "modelDescription",
                     align = c("l", "l")),
      latex.environments = "flushleft", hline.after = NULL,
      include.rownames = TRUE, include.colnames = FALSE)

if (engine == "asreml" && !is.null(x[[trial]]$sumTab[[trait]])) {
  sumTab <- x[[trial]]$sumTab[[trait]]
  chMod <- attr(x = sumTab, which = "chosen")
  sumTab$AIC <- round(sumTab$AIC)
  sumTab$BIC <- round(sumTab$BIC)
  sumTab$H2 <- round(sumTab$H2, 2)
  sumTab$row <- round(sumTab$row, 2)
  sumTab$col <- round(sumTab$col, 2)
  sumTab$error <- round(sumTab$error, 1)
  sumTab$`correlated error` <- round(sumTab$`correlated error`, 1)
  sumTab[chMod, ][!is.na(sumTab[chMod, ])] <-
    paste0("BOLD", sumTab[chMod, ][!is.na(sumTab[chMod, ])])
  print(xtable::xtable(x = sumTab,
                       caption = paste("Overview of spatial models tried",
                                       "- selected model indicated in bold"),
                       label = "summaryTab",
                       digits = c(0, 0, 0, 0, 0, 2, 2, 2, 1, 1, 0)),
        latex.environments = "flushleft", caption.placement = "top",
        include.rownames = FALSE, include.colnames = TRUE,
        sanitize.text.function = boldRow)
}
@
\newpage
%-------------------------------------------------------------------------------
\section{Summary of the results}
%-------------------------------------------------------------------------------
<<label=extrSummary, echo=FALSE, results="hide">>=
## Create summary SpATS in separate chunk to suppress output.
if (engine == "SpATS") {
  SpATSSum <- summary(model)
}
@
<<label=summary, echo=FALSE, results="asis">>=
modSum <- as.data.frame(summary(x[[trial]]$TD, traits = trait)[, 1, 1])
modSum <- modSum[!is.na(modSum[[1]]), , drop = FALSE]
print(xtable::xtable(x = modSum,
                     caption = "Size of the dataset and eight number descriptives", label = "modelSummary", align = c("l", "r")),
      latex.environments = "flushleft", caption.placement = "top",
      include.rownames = TRUE, include.colnames = FALSE)
@
<<label=condNewpage, echo=FALSE, results="asis">>=
if (engine == "SpATS") {
  cat("\\newpage")
}
@
<<label=SpATSsummary, echo=FALSE, results="asis">>=
if (engine == "SpATS") {
  ## Print table of effective dimensions
  effDims <- SpATSSum$p.table.dim
  rownames(effDims)[is.na(rownames(effDims))] <- ""
  ## Rename rows for more user readable output.
  effDims <- renameRows(effDims)
  print(xtable::xtable(x = effDims, caption = "Effective dimensions",
                       label = "effDims",
                       align = c("l", "r", "r", "r", "r", "r")),
        latex.environments = "flushleft", caption.placement = "top",
        include.rownames = TRUE)
}
## Print variance components
vcWhat <- paste0("varComp", ifelse(modelType == "fixed", "F", "R"))
varComp <- extractSTA(x, trials = trial,
                      what = vcWhat, asDataFrame = FALSE)[[trial]][[vcWhat]][[trait]]
print(xtable::xtable(x = varComp, label = "varComps",
                     caption =  "Variance components",
                     align = c("l", rep(x = "r", times = ncol(varComp)))),
      latex.environments = "flushleft", caption.placement = "top",
      include.rownames = TRUE)
## Print generalized heritability
if (modelType == "random") {
  cat(paste("The generalized heritability is",
            extractSTA(x, trials = trial, what = "heritability")[trait]))
}
@
\clearpage

%-------------------------------------------------------------------------------
\section{Diagnostic plots}
%-------------------------------------------------------------------------------
<<label=spatialPlots, echo=FALSE, results="asis", out.width="90%">>=
if (all(c("colId", "rowId") %in% colnames(x[[trial]]$TD[[trial]]))) {
  plot(x, trials = trial, traits = trait, what = modelType,
       plotType = "spatial", outCols = 2)
}
@
<<label=basePlots, echo=FALSE, out.width="90%">>=
## Base diagnostic plots, identical for all models
plot(x, trials = trial, traits = trait, what = modelType, plotType = "base")
@
\newpage

%-------------------------------------------------------------------------------
\section{List of best 10\% genotypes with
\Sexpr{paste(ifelse(descending, "highest", "lowest"), predName)}}
%-------------------------------------------------------------------------------
<<label=best10perc, echo=FALSE, results="hide">>=
pred <- extractSTA(x, what = predName)[c("genotype", trait)]
predSE <- extractSTA(x, what = paste0("se", predName))[c("genotype", trait)]
predTot <- merge(x = pred, y = predSE, by = "genotype")
predTot <- predTot[order(predTot[[paste0(trait,".x")]],
                         decreasing = descending), ]
colnames(predTot) <- c("genotype", trait, "SE")
best <- predTot[1:ceiling(nrow(predTot) / 10), ]
@
\begin{multicols*}{2}
<<label=printBest10pct, echo=FALSE, results="asis">>=
print(xtable::xtable(x = best, label = "bestTab",
                     align = c("l", "l", "c", "c"), digits = c(0, 0, 2, 2)),
      latex.environments = "flushleft",
      include.rownames = FALSE, floating = FALSE)
@
\columnbreak
<<label=predPlot, echo=FALSE, out.width="90%">>=
## Plot of predictions, BLUEs or BLUPs
plot(rev(predTot[[trait]]), col = "#0080ff", xlab = "Genotypes", xaxt = "n",
     cex.lab = 1.5, ylab = trait, mar = c(5, 5, 4, 2) + 0.1)
abline(h = quantile(x = na.omit(predTot[[trait]]), probs = 0.9), col = "red")
abline(h = quantile(x = na.omit(predTot[[trait]]), probs = 0.1), col = "red")
@
\end{multicols*}
%-------------------------------------------------------------------------------
% End Document
\end{document}
