## ----opts, include = FALSE----------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")

## ----install, eval = FALSE----------------------------------------------------
# if (!requireNamespace("BiocManager", quietly = TRUE))
#     install.packages("BiocManager")
# BiocManager::install("BreedingExperiment")

## ----install-dev, eval = FALSE------------------------------------------------
# BiocManager::install("mqfarooqi1/BreedingExperiment")

## ----setup, message = FALSE---------------------------------------------------
library(BreedingExperiment)

## ----demo-data----------------------------------------------------------------
data(demoBreeding)
be <- demoBreeding
be

## ----demo-features------------------------------------------------------------
table(SummarizedExperiment::colData(be)$generation)
summary(SummarizedExperiment::colData(be)$yield)   # females only

## ----accessors----------------------------------------------------------------
dim(be)
genotypes(be)[1:4, 1:5]
head(SummarizedExperiment::colData(be), 3)
head(pedigree(be), 3)

## ----subset-region------------------------------------------------------------
chr1 <- be[as.character(GenomicRanges::seqnames(
  SummarizedExperiment::rowRanges(be))) == "chr1", ]
dim(chr1)

## ----your-data, eval = FALSE--------------------------------------------------
# be <- BreedingExperiment(
#   genotypes  = dosage_matrix,          # markers x individuals, 0/1/2
#   phenotypes = phenotype_data_frame,   # one row per individual
#   pedigree   = pedigree_data_frame,    # id, sire, dam
#   rowRanges  = marker_granges)         # optional, but worth having

## ----qc-summaries-------------------------------------------------------------
nrow(be)
summary(alleleFrequency(be)$callRate)

## ----qc-----------------------------------------------------------------------
be <- filterMarkers(be, min_maf = 0.05, min_call_rate = 0.9)
be <- imputeMarkers(be)
nrow(be)
head(alleleFrequency(be), 3)

## ----qc-sensitivity-----------------------------------------------------------
# on the unfiltered data, so that every threshold has markers to remove
round(t(vapply(c(0, 0.01, 0.05, 0.20), function(m) {
  G <- Gmatrix(demoBreeding, min_maf = m)
  c(min_maf = m, mean_diagonal = mean(diag(G)),
    sd_offdiagonal = stats::sd(G[upper.tri(G)]))
}, numeric(3))), 3)

## ----imputed-assay------------------------------------------------------------
SummarizedExperiment::assayNames(be)
mean(SummarizedExperiment::assay(be, "imputed"))   # proportion imputed

## ----amatrix------------------------------------------------------------------
A <- Amatrix(be)
round(A[1:5, 1:5], 3)

## ----inbreeding---------------------------------------------------------------
summary(inbreeding(be))

## ----gmatrix------------------------------------------------------------------
G <- Gmatrix(be)
round(G[1:5, 1:5], 3)

## ----ag-agreement-------------------------------------------------------------
gen <- colnames(be)
A22 <- A[gen, gen]
cor(A22[upper.tri(A22)], G[upper.tri(G)])

## ----ag-plot, fig.wide = TRUE, fig.height = 4, fig.cap = "Pedigree and genomic relationships for the same pairs of individuals. The pedigree gives a few discrete values; the markers spread each of them out, and that spread is the Mendelian sampling a pedigree cannot see."----
plot(A22[upper.tri(A22)], G[upper.tri(G)], pch = 16, cex = 0.3,
     col = grDevices::adjustcolor("steelblue", alpha.f = 0.3),
     xlab = "pedigree relationship", ylab = "genomic relationship")
abline(0, 1, col = "firebrick", lwd = 2)

## ----dmatrix------------------------------------------------------------------
D <- Dmatrix(be)
round(D[1:4, 1:4], 3)

## ----hmatrix------------------------------------------------------------------
H <- Hmatrix(be, blend = 0.05)
dim(H)
length(attr(H, "genotyped"))

## ----hmatrix-checks-----------------------------------------------------------
H1 <- Hmatrix(be, blend = 1, tune = FALSE)
max(abs(H1[gen, gen] - A22))
min(eigen(H, only.values = TRUE)$values) > 0

## ----blend-sweep--------------------------------------------------------------
vapply(c(0.02, 0.05, 0.20), function(b) {
  Hb <- Hmatrix(be, blend = b)
  min(eigen(Hb, only.values = TRUE)$values)
}, numeric(1))

## ----blup-setup---------------------------------------------------------------
ph  <- SummarizedExperiment::colData(be)
ids <- rownames(H)

train  <- ph$generation != 5                 # records we are allowed to use
target <- colnames(be)[ph$generation == 5]   # the ones we must predict
y <- ph$stature[train]

X <- matrix(1, length(y), 1)                 # an intercept only
Z <- matrix(0, length(y), length(ids))       # records to individuals
Z[cbind(seq_along(y), match(colnames(be)[train], ids))] <- 1
c(records = length(y), predicted = length(target))

## ----blup-solve---------------------------------------------------------------
blup <- function(K, h2) {
  lambda <- (1 - h2) / h2
  lhs <- rbind(cbind(crossprod(X),    crossprod(X, Z)),
               cbind(crossprod(Z, X), crossprod(Z) + solve(K) * lambda))
  rhs <- rbind(crossprod(X, y), crossprod(Z, y))
  stats::setNames(solve(lhs, rhs)[-1, 1], ids)
}

ebv_pedigree   <- blup(A[ids, ids], h2 = 0.6)
ebv_singlestep <- blup(H,           h2 = 0.6)

## ----blup-accuracy------------------------------------------------------------
true <- stats::setNames(ph$trueBV_stature, colnames(be))
round(c(pedigree   = cor(ebv_pedigree[target],   true[target]),
        singlestep = cor(ebv_singlestep[target], true[target])), 3)

## ----blup-plot, fig.wide = TRUE, fig.height = 4.2, fig.cap = "Predicted against true breeding values for the youngest generation, whose records were withheld. Adding marker information tightens the relationship."----
op <- par(mfrow = c(1, 2), mar = c(4, 4, 3, 1))
for (nm in c("pedigree", "singlestep")) {
  e <- if (nm == "pedigree") ebv_pedigree else ebv_singlestep
  plot(true[target], e[target], pch = 16, col = "steelblue",
       xlab = "true breeding value", ylab = "predicted",
       main = sprintf("%s (r = %.3f)", nm, cor(e[target], true[target])))
  abline(lm(e[target] ~ true[target]), col = "firebrick", lwd = 2)
}
par(op)

## ----blup-ungenotyped---------------------------------------------------------
ungenotyped <- setdiff(ids, attr(H, "genotyped"))
length(ungenotyped)
summary(ebv_singlestep[ungenotyped])

## ----session------------------------------------------------------------------
sessionInfo()

