## ----setup, include = FALSE---------------------------------------------------
# fig.ext has to be set alongside dev: pkgdown fixes the figure extension at
# "png" for articles, so with dev = "svg" alone knitr writes SVG documents into
# files named *.png and the browser refuses to decode them. BiocStyle never
# showed it, because a self-contained render embeds the image and the file name
# stops mattering.
knitr::opts_chunk$set(collapse = TRUE, comment = "#>", crop = NULL,
                      dev = "svg", fig.ext = "svg")

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

## ----library, message = FALSE-------------------------------------------------
library(NADIA)
data(nadia_dia)

## ----deps---------------------------------------------------------------------
have_bert <- requireNamespace("BERT", quietly = TRUE)
have_lme4 <- requireNamespace("lme4", quietly = TRUE)
c(BERT = have_bert, lme4 = have_lme4)

## ----flags, include = FALSE---------------------------------------------------
run_bc  <- have_bert
run_all <- have_bert && have_lme4

## ----covariates---------------------------------------------------------------
md <- nadia_dia$metadata

covariates <- data.frame(
    Column    = md$Coding,
    Digestion = rep(c("d1", "d2"),             length.out = nrow(md)),
    Injection = rep(c("i1", "i1", "i2", "i2"), length.out = nrow(md)),
    Subject   = rep(paste0("s", 1:4),          length.out = nrow(md)),
    stringsAsFactors = FALSE)

covariates

## ----inject-------------------------------------------------------------------
batched <- nadia_dia
qcols   <- grep("^PG.Quantity_", colnames(batched$protein_quant))
samples <- sub("^PG.Quantity_", "", colnames(batched$protein_quant)[qcols])
d2_cols <- qcols[samples %in% covariates$Column[covariates$Digestion == "d2"]]

set.seed(1)
up     <- sample(c(TRUE, FALSE), nrow(batched$protein_quant), replace = TRUE)
batch_multiplier <- ifelse(up, 6, 1 / 6)
batched$protein_quant[, d2_cols] <-
    batched$protein_quant[, d2_cols] * batch_multiplier

length(d2_cols)   # the six samples digested on day 2

## ----design-------------------------------------------------------------------
table(Digestion = covariates$Digestion, Injection = covariates$Injection)
table(Condition = md$R.Condition,       Digestion = covariates$Digestion)

## ----process, eval = run_bc---------------------------------------------------
res <- process_proteomics(batched, covariate_df = covariates, verbose = FALSE)

## ----pvca-default, eval = run_all, message = FALSE, warning = FALSE-----------
pvca_default <- pvca_analysis(
    res$se_proc,
    assay_name         = "Impseqrob_min",
    technical_factors  = c("Digestion", "Injection"),
    biological_factors = "Condition",
    verbose            = FALSE)

pvca_default$variance_components

## ----pvca-before, eval = run_all, message = FALSE, warning = FALSE------------
pvca_before <- pvca_analysis(
    res$se_proc,
    assay_name         = "Impseqrob_min",
    technical_factors  = c("Digestion", "Injection"),
    biological_factors = "Condition",
    pca_threshold      = 0.95,
    variance_threshold = 0,
    verbose            = FALSE)

pvca_before$variance_components

## ----pvca-before-plot, eval = run_all, message = FALSE, warning = FALSE, fig.width = 7, fig.height = 4.5, fig.cap = "PVCA before correction, using enough principal components to explain 95% of the variance.", fig.alt = "Variance decomposition before batch correction"----
pvca_before$plot

## ----batch-arguments-diagram, echo = FALSE, out.width = "100%", fig.cap = "The three arguments act at different stages: batch_column modifies the quantitative matrix, whereas covariate_column and bio_replicate_column act during differential abundance analysis.", fig.alt = "Workflow diagram comparing batch_column, covariate_column and bio_replicate_column. Batch_column removes a technical effect from the normalized matrix before imputation. Covariate_column adds nuisance variables to the limma model without changing the matrix. Bio_replicate_column models correlation between paired, repeated or technical replicate samples."----
knitr::include_graphics("figures/Batch_Correction_Arguments.svg")

## ----correct, eval = run_bc, message = FALSE, warning = FALSE, results = "hide"----
res_bc <- process_proteomics(
    batched,
    covariate_df         = covariates,
    batch_correct        = TRUE,
    batch_column         = "Digestion",
    batch_algorithm      = "ComBat",
    batch_ComBat_mode    = 1,
    covariate_column     = "Injection",
    bio_replicate_column = "Subject",
    verbose              = FALSE)

## ----correct-assays, eval = run_bc--------------------------------------------
SummarizedExperiment::assayNames(res_bc$se_proc)

## ----batch-covariates-decision, echo = FALSE, out.width = "100%", fig.cap = "Choosing batch_covariates. A known biological variable should normally be protected when batch and biology can be estimated separately. NULL is not a remedy for confounding or insufficient replication.", fig.alt = "Decision guide for batch_covariates. Use a protected covariate for a known biological variable when the design is estimable. Reassess the design rather than falling back to NULL when batch and biology are confounded or replication is insufficient. NULL may be appropriate when no biological variable needs protection or when all batch-associated variation is deliberately removed."----
knitr::include_graphics("figures/Batch_Covariates_Decision.svg")

## ----protected-batch-example, eval = FALSE------------------------------------
# # The sample annotation contains Column, Batch, Injection and Subject.
# sample_annotation <- read.delim("sample_annotation.tsv")
# 
# # Check that Condition is represented at least twice in every batch.
# design_check <- merge(
#     data.frame(
#         Column    = my_data$metadata$Coding,
#         Condition = my_data$metadata$R.Condition),
#     sample_annotation,
#     by = "Column")
# 
# batch_condition_counts <- with(
#     design_check,
#     table(Batch = Batch, Condition = Condition))
# batch_condition_counts
# stopifnot(all(batch_condition_counts >= 2))
# 
# res_bc <- process_proteomics(
#     my_data,
#     covariate_df         = sample_annotation,
#     batch_correct        = TRUE,
#     batch_column         = "Batch",       # remove from the matrix
#     batch_covariates     = "Condition",   # protect during correction
#     covariate_column     = "Injection",   # adjust the limma model
#     bio_replicate_column = "Subject")     # paired/repeated samples

## ----verify-direct, eval = run_bc---------------------------------------------
grp <- covariates$Digestion[
    match(colnames(SummarizedExperiment::assay(res_bc$se_proc, "cycloess")),
          covariates$Column)]

delta <- function(assay_name) {
    m <- SummarizedExperiment::assay(res_bc$se_proc, assay_name)
    rowMeans(m[, grp == "d1", drop = FALSE], na.rm = TRUE) -
    rowMeans(m[, grp == "d2", drop = FALSE], na.rm = TRUE)
}

data.frame(
    assay      = c("cycloess (before)", "BERT (after)"),
    median_abs_difference = c(median(abs(delta("cycloess")), na.rm = TRUE),
                              median(abs(delta("BERT")),     na.rm = TRUE)),
    sd         = c(sd(delta("cycloess"), na.rm = TRUE),
                   sd(delta("BERT"),     na.rm = TRUE)))

## ----pvca-after, eval = run_all, message = FALSE, warning = FALSE-------------
pvca_after <- pvca_analysis(
    res_bc$se_proc,
    assay_name         = "BERT",
    technical_factors  = c("Digestion", "Injection"),
    biological_factors = "Condition",
    pca_threshold      = 0.95,
    variance_threshold = 0,
    verbose            = FALSE)

pvca_comparison <- merge(
    pvca_before$variance_components,
    pvca_after$variance_components,
    by = "label",
    suffixes = c("_before", "_after"))[, c(1, 2, 4)]

# Use fixed decimal notation so that the proportions can be read directly.
pvca_comparison$weights_before <- formatC(
    pvca_comparison$weights_before, format = "f", digits = 8)
pvca_comparison$weights_after <- formatC(
    pvca_comparison$weights_after, format = "f", digits = 8)

pvca_comparison

## ----de-effect, eval = run_bc-------------------------------------------------
table(uncorrected = res$DEPs_results$Change)
table(corrected   = res_bc$DEPs_results$Change)

## ----cascade, eval = run_bc, message = FALSE, warning = FALSE, results = "hide"----
se1 <- batch_correct_proteomics(
    res$se_proc,
    assay_name           = "cycloess",
    batch_column         = "Digestion",
    corrected_assay_name = "BERT",
    verbose              = FALSE)

se2 <- batch_correct_proteomics(
    se1,
    assay_name           = "BERT",       # the already-corrected matrix
    batch_column         = "Injection",
    corrected_assay_name = "BERT_2",
    verbose              = FALSE)

## ----cascade-assays, eval = run_bc--------------------------------------------
SummarizedExperiment::assayNames(se2)

## ----pca-cov, eval = run_bc, message = FALSE, fig.show = "hide"---------------
pca_grid <- pca_covariates_plot(
    res_bc$se_proc,
    assay_name = "BERT",
    covariates = c("Condition", "Digestion", "Injection", "Subject"),
    scale.     = TRUE,
    verbose    = FALSE)

pca_grid$grid +
    ggplot2::theme(panel.spacing = grid::unit(1.2, "lines"))

## ----pca-cov-styled, eval = run_bc, echo = FALSE, message = FALSE, warning = FALSE, fig.width = 7, fig.height = 6.2, fig.cap = "PCA of the simulated example after correction, colored in turn by each biological or technical variable.", fig.alt = "PCA colored by condition, digestion, injection and subject using distinct colors and shapes"----
pca_colors <- c(
    A  = "#0072B2", B  = "#D55E00", D  = "#009E73",
    d1 = "#CC79A7", d2 = "#E69F00",
    i1 = "#56B4E9", i2 = "#333333",
    s1 = "#8C564B", s2 = "#6A3D9A", s3 = "#E41A1C", s4 = "#607D8B")

pca_shapes <- c(
    A = 16, B = 17, D = 15,
    d1 = 16, d2 = 17,
    i1 = 16, i2 = 17,
    s1 = 16, s2 = 17, s3 = 15, s4 = 18)

pca_grid$grid +
    ggplot2::aes(shape = Value) +
    ggplot2::scale_color_manual(
        values = pca_colors,
        breaks = names(pca_colors),
        name = NULL) +
    ggplot2::scale_shape_manual(
        values = pca_shapes,
        breaks = names(pca_shapes),
        guide = "none") +
    ggplot2::guides(
        color = ggplot2::guide_legend(
            nrow = 2, byrow = TRUE,
            override.aes = list(size = 3, alpha = 1))) +
    ggplot2::theme(
        panel.spacing = grid::unit(1.2, "lines"),
        legend.position = "bottom",
        legend.box = "horizontal")

## ----tmt-design-diagram, echo = FALSE, out.width = "100%", fig.cap = "Three-proteome TMT design. Conditions A, B and D retain an 80% human background while the proportions of *E. coli* and yeast vary. Replicates 1–4 of each condition are assigned to mix 1 and replicates 5–8 to mix 2.", fig.alt = "Experimental design of the TMT spike-in study. Condition A contains 80 percent human, 5 percent E. coli and 15 percent yeast; condition B contains 80, 10 and 10 percent; condition D contains 80 percent human, 20 percent E. coli and no yeast. Mix 1 contains replicates 1 to 4 of A, B and D plus internal standards 1 and 2. Mix 2 contains replicates 5 to 8 plus internal standards 3 and 4."----
knitr::include_graphics("figures/TMT_Batch_Experimental_Design.svg")

## ----tmt-data-----------------------------------------------------------------
tmt <- preprocess_tmt(
    system.file("extdata", "nadia_tmt_report.tsv.gz", package = "NADIA"),
    condition_order = c("A", "B", "D"), verbose = FALSE)

tmt_cov <- data.frame(
    Column = tmt$metadata$Coding,
    Mix    = ifelse(tmt$metadata$R.Replicate <= 4, "mix1", "mix2"),
    stringsAsFactors = FALSE)

table(Condition = tmt$metadata$R.Condition, Mix = tmt_cov$Mix)

## ----tmt-process, eval = run_bc, message = FALSE------------------------------
tmt_res <- process_proteomics(tmt, covariate_df = tmt_cov, verbose = FALSE)

## ----tmt-pvca, eval = run_all, message = FALSE, warning = FALSE---------------
tmt_pvca_before <- pvca_analysis(
    tmt_res$se_proc,
    assay_name         = "Impseqrob_min",
    technical_factors  = "Mix",
    biological_factors = "Condition",
    pca_threshold      = 0.95,
    variance_threshold = 0,
    verbose            = FALSE)

tmt_pvca_before$variance_components

## ----tmt-correct, eval = run_bc, message = FALSE, warning = FALSE, results = "hide"----
tmt_bc <- process_proteomics(
    tmt, covariate_df = tmt_cov,
    batch_correct = TRUE, batch_column = "Mix",
    batch_algorithm = "ComBat", batch_ComBat_mode = 1,
    verbose = FALSE)

## ----tmt-correct-protected, eval = run_bc, message = FALSE, warning = FALSE, results = "hide"----
tmt_bc_prot <- process_proteomics(
    tmt, covariate_df = tmt_cov,
    batch_correct = TRUE, batch_column = "Mix",
    batch_covariates = "Condition",
    batch_algorithm = "ComBat", batch_ComBat_mode = 1,
    verbose = FALSE)

## ----tmt-pvca-after, eval = run_all, message = FALSE, warning = FALSE---------
tmt_pvca_after <- pvca_analysis(
    tmt_bc$se_proc,
    assay_name         = "BERT",
    technical_factors  = "Mix",
    biological_factors = "Condition",
    pca_threshold      = 0.95,
    variance_threshold = 0,
    verbose            = FALSE)

tmt_pvca_comparison <- merge(
    tmt_pvca_before$variance_components,
    tmt_pvca_after$variance_components,
    by = "label",
    suffixes = c("_before", "_after"))[, c(1, 2, 4)]

tmt_pvca_comparison$weights_before <- formatC(
    tmt_pvca_comparison$weights_before, format = "f", digits = 8)
tmt_pvca_comparison$weights_after <- formatC(
    tmt_pvca_comparison$weights_after, format = "f", digits = 8)

tmt_pvca_comparison

## ----tmt-verify, eval = run_bc------------------------------------------------
species <- sub(".*OS=(.+?)\\s+[A-Za-z]+=.*", "\\1",
               tmt$protein_id$PG.ProteinDescriptions)
names(species) <- tmt$protein_id$PG.ProteinGroups

directional_performance <- function(res, comparison) {
    d  <- res$DEPs_results
    d  <- d[d$Comparison == comparison, ]
    sp <- species[match(d$Protein.IDs, names(species))]
    c(`E. coli called up` = mean(d$Change[grepl("^Escherichia", sp)] == "Up"),
      `yeast called down` = mean(d$Change[grepl("^Saccharomyces", sp)] == "Down"),
      `human unchanged`   = mean(d$Change[grepl("^Homo", sp)] == "No Change"))
}

round(100 * cbind(
    uncorrected = directional_performance(tmt_res,     "D-A"),
    corrected   = directional_performance(tmt_bc,      "D-A"),
    protected   = directional_performance(tmt_bc_prot, "D-A")), 1)

## ----tmt-pca-before, eval = run_bc, message = FALSE, fig.width = 8.5, fig.height = 4, fig.cap = "TMT experiment before correction. The same PCA is colored by biological condition and TMT mix.", fig.alt = "PCA of the TMT experiment before correction, colored by condition and by TMT mix. The samples separate by mix along the first component."----
tmt_pca_before <- pca_covariates_plot(
    tmt_res$se_proc,
    assay_name = "Impseqrob_min",
    covariates = c("Condition", "Mix"),
    scale. = TRUE,
    verbose = FALSE)$grid

tmt_pca_before +
    ggplot2::theme(panel.spacing.x = grid::unit(2, "lines"))

## ----tmt-pca-after, eval = run_bc, message = FALSE, fig.width = 8.5, fig.height = 4, fig.cap = "TMT experiment after correction. Mix-related separation is no longer visible and condition becomes the main source of structure.", fig.alt = "PCA of the TMT experiment after correction, colored by condition and by TMT mix. The mix panel has no structure left and the conditions separate along the first component."----
tmt_pca_after <- pca_covariates_plot(
    tmt_bc$se_proc,
    assay_name = "BERT",
    covariates = c("Condition", "Mix"),
    scale. = TRUE,
    verbose = FALSE)$grid

tmt_pca_after +
    ggplot2::theme(panel.spacing.x = grid::unit(2, "lines"))

## ----tmt-de-effect, eval = run_bc---------------------------------------------
table(uncorrected = tmt_res$DEPs_results$Change)
table(corrected   = tmt_bc$DEPs_results$Change)

## ----tmt-effect-size, eval = run_bc-------------------------------------------
fold_change_summary <- function(res, organism) {
    d  <- res$DEPs_results
    d  <- d[d$Comparison == "D-A", ]
    sp <- species[match(d$Protein.IDs, names(species))]
    d  <- d[grepl(organism, sp) & d$Change != "No Change", ]
    c(significant      = nrow(d),
      median_abs_logFC = median(abs(d$logFC)),
      p90_abs_logFC    = quantile(abs(d$logFC), 0.9, names = FALSE))
}

round(rbind(
    `human, uncorrected`   = fold_change_summary(tmt_res, "^Homo"),
    `human, corrected`     = fold_change_summary(tmt_bc,  "^Homo"),
    `E. coli, uncorrected` = fold_change_summary(tmt_res, "^Escherichia"),
    `E. coli, corrected`   = fold_change_summary(tmt_bc,  "^Escherichia")), 2)

## ----tmt-threshold-table, echo = FALSE, out.width = "100%", fig.cap = "Benchmarking of the D-A comparison across log2 fold-change thresholds. Sensitivity, specificity and MCC are colored on a common scale from 0 (red) to 1 (green); the 0.3 threshold is highlighted because it provides the best overall balance in this experiment.", fig.alt = "Table comparing true positives, false positives, sensitivity, specificity and Matthews correlation coefficient for uncorrected, corrected and condition-protected analyses at log2 fold-change thresholds of zero, 0.2, 0.3, 0.5 and 1. True positives are expected E. coli and yeast changes and false positives are unchanged human proteins called differential. Sensitivity, specificity and MCC cells are colored from red at zero to green at one. The cells for threshold 0.3 are bold and outlined."----
knitr::include_graphics("figures/TMT_Benchmarking_Thresholds.svg")

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

