## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>", crop = NULL)
# have_highcharter and prepare_vignette_highchart()
source("highcharts-setup.R")

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

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

## ----benchmark-three-proteome-design, echo = FALSE, fig.align = "center", out.width = "100%", fig.cap = "Complete three-proteome spike-in design underlying the benchmark dataset. HeLa remains constant at 80%, while E. coli increases and yeast decreases across conditions. The dataset distributed with NADIA retains conditions A, B, and D and 2,000 protein groups.", fig.alt = "Three-proteome spike-in experimental design with conditions A to D and four replicates per condition. HeLa proteins remain at 80 percent, Escherichia coli proteins increase from 5 to 20 percent, and yeast proteins decrease from 15 percent to zero. NADIA retains conditions A, B, and D for the example benchmark."----
knitr::include_graphics("figures/Three_Proteome_Experimental_Design.svg")

## ----species------------------------------------------------------------------
spikein <- read.delim(system.file("extdata", "nadia_dia_spikein.tsv.gz",
                                  package = "NADIA"))
species_df <- data.frame(Protein.IDs = spikein$PG.ProteinGroups,
                         Species     = spikein$PG.OrganismId)

species_example <- do.call(rbind, lapply(c("HUMAN", "ECOLI", "YEAST"),
    function(species) head(species_df[species_df$Species == species, ], 2)))
rownames(species_example) <- NULL

species_example
table(species_df$Species)

## ----expected, results = "hide"-----------------------------------------------
# Option 1: base R data.frame
expected <- data.frame(
    Comparison     = rep(c("B-A", "D-A", "D-B"), each = 2),
    Species        = rep(c("ECOLI", "YEAST"), times = 3),
    expected_logFC = c(1, -0.58, 2, -3.3, 1, -2.72))

# Option 2: equivalent row-wise tibble
# expected <- tibble::tribble(
#     ~Comparison, ~Species, ~expected_logFC,
#     "B-A",       "ECOLI",             1,
#     "B-A",       "YEAST",         -0.58,
#     "D-A",       "ECOLI",             2,
#     "D-A",       "YEAST",          -3.3,
#     "D-B",       "ECOLI",             1,
#     "D-B",       "YEAST",         -2.72
# )

expected

## ----expected-table, echo = FALSE---------------------------------------------
expected

## ----benchmarking-outputs, echo = FALSE, fig.align = "center", out.width = "100%", fig.cap = "Inputs, classification steps, and output families produced by benchmarking_proteomics().", fig.alt = "Workflow diagram showing differential-expression results, expected changes, species annotation, and analysis settings entering benchmarking_proteomics. The function returns TP, FP, TN and FN counts; sensitivity, specificity, precision, F1 and MCC; ROC, AUC and partial AUC; fold-change recovery statistics; classified proteins; and diagnostic plots."----
knitr::include_graphics("figures/Benchmarking_Proteomics_Outputs.svg")

## ----bench, message = FALSE, warning = FALSE----------------------------------
res <- process_proteomics(nadia_dia, verbose = FALSE)

bench <- benchmarking_proteomics(res$DEPs_results, expected,
                                 species_df = species_df,
                                 output_dir = NULL, verbose = FALSE)

## ----bench-metrics------------------------------------------------------------
metric_cols <- c("Comparison", "Sensitivity", "Specificity", "Precision",
                 "F1", "MCC", "AUC")
knitr::kable(bench$metrics_table[, metric_cols], digits = 3,
             caption = "Classification and ranking metrics by comparison.")

## ----classification-calculate, results = "hide"-------------------------------
wrong_sign <- subset(bench$classified_df, direction_error)
wrong_sign <- merge(wrong_sign, expected,
                    by = c("Comparison", "Species"))

nrow(wrong_sign)
table(wrong_sign$Comparison, wrong_sign$Species)
wrong_sign[, c("Protein.IDs", "Comparison", "Species", "logFC",
               "expected_logFC", "adj.P.Val", "is_significant",
               "direction_error", "classification")]

## ----classification-results, echo = FALSE-------------------------------------
nrow(wrong_sign)
table(wrong_sign$Comparison, wrong_sign$Species)
wrong_sign[, c("Protein.IDs", "Comparison", "Species", "logFC",
               "expected_logFC", "adj.P.Val", "is_significant",
               "direction_error", "classification")]

## ----signif-direction, fig.width = 7.5, fig.height = 4.5, fig.alt = "Significant proteins by species, comparison, and observed direction"----
bench$gg_signif_bars

## ----conf-species, fig.width = 7.5, fig.height = 5, fig.alt = "Confusion matrix by species and comparison"----
bench$gg_confusion_by_species

## ----conf-species-tbl---------------------------------------------------------
species_cols <- c("Comparison", "Species", "N", "TP_pct", "FP_pct",
                  "FN_pct", "TN_pct")
knitr::kable(bench$confusion_by_species[, species_cols], digits = 1,
             caption = "Classification percentages within each species.")

## ----conf-overall, fig.width = 7.5, fig.height = 4.5, fig.alt = "Overall confusion matrix by comparison"----
bench$gg_confusion_overall

## ----conf-overall-tbl---------------------------------------------------------
overall_cols <- c("Comparison", "N", "TP", "FP", "FN", "TN", "Accuracy")
knitr::kable(bench$confusion_overall[, overall_cols], digits = 3,
             caption = "Classification counts across all scored proteins.")

## ----bench-heatmap, fig.width = 7.5, fig.height = 4, fig.alt = "Heatmap of the benchmark metrics by comparison"----
bench$gg_heatmap

## ----opdea--------------------------------------------------------------------
knitr::kable(bench$opdea_metrics, digits = 3,
             caption = "OpDEA metrics by comparison.")

## ----roc, fig.width = 6.5, fig.height = 5, fig.alt = "ROC curves for the three comparisons"----
bench$gg_roc

## ----roc-zoom, fig.width = 6.5, fig.height = 5, out.width = "110%", fig.alt = "ROC curves zoomed into the low false-positive region"----
bench$gg_roc_zoom

## ----operating-point-calculate, results = "hide"------------------------------
op <- do.call(rbind, lapply(unique(bench$classified_df$Comparison), function(comp) {
    d <- subset(bench$classified_df, Comparison == comp)
    called_positive <- !is.na(d$adj.P.Val) & d$adj.P.Val <= 0.05
    data.frame(
        Comparison = comp,
        FPR_at_adjP005 = sum(called_positive & d$truth == 0) / sum(d$truth == 0),
        TPR_at_adjP005 = sum(called_positive & d$truth == 1) / sum(d$truth == 1))
}))

knitr::kable(op, digits = 4,
             col.names = c("Comparison", "FPR", "TPR"),
             caption = "Observed ROC operating points at adj.P.Val <= 0.05.")

## ----operating-point-table, echo = FALSE--------------------------------------
knitr::kable(op, digits = 4,
             col.names = c("Comparison", "FPR", "TPR"),
             caption = "Observed ROC operating points at adj.P.Val <= 0.05.")

## ----engines-bench, message = FALSE, warning = FALSE, results = "hide"--------
diann <- preprocess_diann(
    system.file("extdata", "nadia_diann_report.tsv.gz", package = "NADIA"),
    condition_order = c("A", "B", "D"), verbose = FALSE)

species_dn <- data.frame(
    Protein.IDs = diann$protein_id$PG.ProteinGroups,
    Species = toupper(sub(".*_", "",
                          sub(";.*", "", diann$protein_id$PG.ProteinNames))))

bench_dn <- benchmarking_proteomics(
    process_proteomics(diann, verbose = FALSE)$DEPs_results,
    expected, species_df = species_dn, output_dir = NULL, verbose = FALSE)

engine_auc <- rbind(
    cbind(Engine = "Spectronaut",
          bench$metrics_table[, c("Comparison", "TP", "FP", "TN", "FN", "AUC")]),
    cbind(Engine = "DIA-NN",
          bench_dn$metrics_table[, c("Comparison", "TP", "FP", "TN", "FN", "AUC")]))

engine_auc$N <- rowSums(engine_auc[, c("TP", "FP", "TN", "FN")])
engine_auc <- engine_auc[, c("Engine", "Comparison", "N", "AUC")]

knitr::kable(engine_auc, digits = 3,
             caption = "Full ROC AUC by search engine and comparison.")

## ----engines-auc-table, echo = FALSE------------------------------------------
knitr::kable(engine_auc, digits = 3,
             caption = "Full ROC AUC by search engine and comparison.")

## ----engines-pauc-------------------------------------------------------------
engine_pauc <- cbind(
    Engine = rep(c("Spectronaut", "DIA-NN"), each = 3),
    rbind(bench$opdea_metrics, bench_dn$opdea_metrics)[
        , c("Comparison", "pAUC_001", "pAUC_005", "pAUC_010")])

knitr::kable(engine_pauc, digits = 3,
             caption = "Partial AUC by search engine and FPR range.")

## ----bench-volcano, eval = FALSE----------------------------------------------
# bench$hc_volcano_list[["B-A"]]

## ----bench-volcano-plot, echo = FALSE, eval = have_highcharter----------------
prepare_vignette_highchart(bench$hc_volcano_list[["B-A"]])

## ----multiple, message = FALSE, warning = FALSE-------------------------------
pipelines <- list(
    cycloess_combo = list(norm_method = "cycloess", imp_method = "combo"),
    quantile_combo = list(norm_method = "quantile", imp_method = "combo"),
    cycloess_min   = list(norm_method = "cycloess", imp_method = "min"))

invisible(capture.output(
  scored <- lapply(names(pipelines), function(p) {
      processed <- do.call(
          process_proteomics,
          c(list(nadia_dia, verbose = FALSE), pipelines[[p]]))
      benchmark <- benchmarking_proteomics(
          processed$DEPs_results, expected,
          species_df = species_df,
          output_dir = NULL, verbose = FALSE)
      list(
          opdea = cbind(Assay = p, benchmark$opdea_metrics),
          confusion = cbind(Assay = p, benchmark$metrics_table))
  })))

opdea <- do.call(rbind, lapply(scored, `[[`, "opdea"))
confusion <- do.call(rbind, lapply(scored, `[[`, "confusion"))

multi_bench <- benchmarking_multiple(
    opdea_combined = opdea,
    confusion_combined = confusion,
    plots = "ranking_bars_mean",
    verbose = FALSE)

## ----multiple-counts----------------------------------------------------------
count_cols <- c("Assay", "Comparison", "TP", "FP", "TN", "FN")
knitr::kable(
    multi_bench$confusion_combined[, count_cols],
    caption = "Classification counts by pipeline and comparison.")

## ----multiple-confusion, fig.width = 8.5, fig.height = 5, out.width = "110%", fig.alt = "Confusion matrix counts per pipeline and comparison"----
confusion_plot <- multi_bench$gg_confusion_stacked
bar_total <- ave(
    confusion_plot$data$Count,
    confusion_plot$data$Assay,
    confusion_plot$data$Comparison,
    FUN = sum)
confusion_plot$data$label_text[
    confusion_plot$data$Count < 0.04 * bar_total] <- ""
confusion_plot

## ----multiple-rank------------------------------------------------------------
multi_bench$mean_ranking

## ----multiple-plot, fig.width = 7, fig.height = 4.5, out.width = "110%", fig.alt = "Ranking of the pipelines across the OpDEA metrics"----
multi_bench$gg_ranking_bars_mean

## ----adapt-msstats, eval = FALSE----------------------------------------------
# # msstats_result is the list returned by MSstats::groupComparison()
# msstats_source <- msstats_result$ComparisonResult
# 
# msstats_de <- data.frame(
#     Protein.IDs = msstats_source$Protein,
#     logFC = msstats_source$log2FC,
#     Comparison = msstats_source$Label,
#     P.Value = msstats_source$pvalue,
#     adj.P.Val = msstats_source$adj.pvalue,
#     stringsAsFactors = FALSE)

## ----multiple-from-files, eval = FALSE----------------------------------------
# results_root <- "benchmark_results"
# dir.create(results_root, recursive = TRUE, showWarnings = FALSE)
# 
# # Export one individual benchmark for each NADIA pipeline
# for (p in names(pipelines)) {
#     processed <- do.call(
#         process_proteomics,
#         c(list(nadia_dia, verbose = FALSE), pipelines[[p]]))
#     benchmarking_proteomics(
#         processed$DEPs_results, expected,
#         species_df = species_df,
#         output_dir = file.path(results_root, p),
#         verbose = FALSE)
# }
# 
# # Export the benchmark of the adapted external pipeline
# benchmarking_proteomics(
#     msstats_de, expected,
#     species_df = species_df,
#     output_dir = file.path(results_root, "MSstats"),
#     verbose = FALSE)
# 
# # Import, compare, and optionally export all individual benchmarks
# multi_from_files <- benchmarking_multiple(
#     results_dir = results_root,
#     output_dir = file.path(results_root, "multiple_summary"),
#     verbose = FALSE)

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

