## ----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)

## ----three-proteome-design, echo = FALSE, fig.align = "center", out.width = "100%", fig.cap = "Complete three-proteome spike-in design underlying the example datasets. For distribution with NADIA, the datasets retain conditions A, B and D and 2,000 protein groups.", fig.alt = "Three-proteome spike-in experimental design with four conditions and four replicates per condition. HeLa proteins remain at 80 percent in all conditions. Escherichia coli proteins increase from 5 percent in A to 20 percent in D, while yeast proteins decrease from 15 percent in A to zero in D. Condition D therefore contains no yeast proteins and is expected to show the highest missingness for yeast-derived protein groups."----
knitr::include_graphics("figures/Three_Proteome_Experimental_Design.svg")

## ----data---------------------------------------------------------------------
report <- system.file("extdata", "nadia_dia_report.tsv.gz", package = "NADIA")
dia <- preprocess_spectronaut(report, condition_order = c("A", "B", "D"),
                              verbose = FALSE)
dia

## ----data-obj-----------------------------------------------------------------
data(nadia_dia)
identical(dim(nadia_dia$protein_quant), dim(dia$protein_quant))

## ----missing------------------------------------------------------------------
quant <- as.matrix(nadia_dia$protein_quant[
    grep("^PG.Quantity_", colnames(nadia_dia$protein_quant))])

round(100 * mean(is.na(quant)), 1)          # percentage of missing intensities
round(100 * mean(rowSums(is.na(quant)) == 0), 1)  # complete proteins

## ----filtering-combinations---------------------------------------------------
filter_grid <- expand.grid(
    min_reps_filter   = 1:4,
    min_groups_filter = 1:3
)

filter_counts <- do.call(rbind, lapply(seq_len(nrow(filter_grid)), function(i) {
    filtered <- normalize_proteomics(
        nadia_dia,
        min_reps    = filter_grid$min_reps_filter[i],
        min_groups  = filter_grid$min_groups_filter[i],
        norm_method = "log2",
        verbose     = FALSE
    )$filter_summary

    data.frame(
        min_reps_filter   = filter_grid$min_reps_filter[i],
        min_groups_filter = filter_grid$min_groups_filter[i],
        proteins_before   = filtered$n_total,
        proteins_retained = filtered$n_keep,
        proteins_filtered = filtered$n_drop
    )
}))

filter_counts

## ----process-defaults, eval = FALSE-------------------------------------------
# res <- process_proteomics(
#     preprocessing = nadia_dia,
# 
#     # File export
#     export_dir = NULL,
# 
#     # Filtering
#     min_reps_filter = NULL,
#     min_groups_filter = 1,
# 
#     # Normalization
#     norm_method = "cycloess",
#     cyclic_loess_method = "fast",
#     cyclic_loess_iterations = 3,
#     cyclic_loess_span = 0.7,
# 
#     # Optional batch correction
#     batch_correct = FALSE,
#     batch_column = "Batch",
#     batch_algorithm = "ComBat",
#     batch_ComBat_mode = 1,
#     batch_covariates = NULL,
#     batch_qualitycontrol = FALSE,
# 
#     # Imputation
#     imp_method = "combo",
#     mar_method = "Impseqrob",
#     mnar_method = "min",
#     prop_na_mnar = 0.51,
#     prop_present_mar = 0.5,
#     min_present_mar = 1,
#     require_n_conditions = 1,
#     max_na_prop = NULL,
#     method_args = list(),
#     with_value = NA_real_,
# 
#     # Differential abundance
#     comparisons = NULL,
#     control = NULL,
#     logFC_threshold = 0,
#     alpha = 0.05,
#     eBayes_trend = NULL,
#     eBayes_robust = NULL,
#     de_method = "limma",
# 
#     # Covariates, paired designs and blocking
#     covariate_df = NULL,
#     covariate_column = NULL,
#     bio_replicate_column = NULL,
# 
#     # Exported objects (used only when export_dir is supplied)
#     export_normalized = TRUE,
#     export_imputed = TRUE,
#     export_format = "tsv",
#     export_volcano = TRUE,
#     export_boxplot = TRUE,
#     export_pca = TRUE,
# 
#     # SummarizedExperiment input only (see "Using NADIA together with other
#     # packages")
#     assay_name = NULL,
#     log2_input = FALSE,
# 
#     # Progress messages
#     verbose = TRUE
# )

## ----process------------------------------------------------------------------
res <- process_proteomics(nadia_dia, verbose = FALSE)
res

## ----summarizedexperiment-schema, echo = FALSE, fig.align = "center", out.width = "82%", fig.cap = "Structure of a SummarizedExperiment object.", fig.alt = "Diagram of a SummarizedExperiment showing one or more assay matrices coordinated with rowData for feature annotations and colData for sample metadata."----
knitr::include_graphics("figures/SummarizedExperiment_Schema.svg")

## ----assays-------------------------------------------------------------------
SummarizedExperiment::assayNames(res$se_proc)

## ----deps---------------------------------------------------------------------
head(res$DEPs_results, 4)

## ----contrasts----------------------------------------------------------------
res$comparisons
table(res$DEPs_results$Change, res$DEPs_results$Comparison)

## ----missing-scope------------------------------------------------------------
pid <- with(res$DEPs_results, Protein.IDs[MissGlobal != MissComp][1])
subset(res$DEPs_results, Protein.IDs == pid,
       c("Comparison", "MissGlobal", "MissComp", "MissCND1", "MissCND2"))

## ----missing-cols-------------------------------------------------------------
bins <- cut(res$DEPs_results$MissComp, c(-1, 0, 25, 50, 100),
            labels = c("0%", "1-25%", "26-50%", ">50%"))
table(missing = bins, res$DEPs_results$Change)

## ----onoff--------------------------------------------------------------------
onoff <- subset(res$DEPs_results,
                (MissCND1 == 100 & MissCND2 == 0) |
                (MissCND1 == 0   & MissCND2 == 100))
nrow(onoff)
head(onoff[, c("Protein.IDs", "Comparison", "logFC", "adj.P.Val",
               "MissCND1", "MissCND2")], 4)

## ----hc, eval = if (have_highcharter) 1:3 else FALSE--------------------------
volcano <- volcano_highchart_list(res$DEPs_results)
boxplot <- boxplot_highchart_list(res$BoxPlot_Input)
pca     <- pca_highchart_list(res$PCA_Input)

volcano[["B-A"]]

## ----volcano-ba, echo = FALSE, eval = have_highcharter------------------------
prepare_vignette_highchart(volcano[["B-A"]])

## ----heatmap, message = FALSE, warning = FALSE, fig.width = 6.5, fig.height = 5.5, fig.alt = "Heatmap of the proteins significant in the B-A comparison"----
hm <- proteomics_heatmap(
    res$PCA_Input,
    mode            = "target",
    comparison      = "B-A",
    scale_data      = "row",
    sample_order    = "condition",
    condition_order = c("A", "B", "D"),
    show_row_names  = FALSE,
    heatmap_title   = "Significant in B-A")
hm

## ----with-limpa, eval = FALSE-------------------------------------------------
# res_limpa <- process_proteomics(nadia_dia, imp_method = "limpa",
#                                 de_method = "limpa")

## ----with-proda-msqrob2, eval = FALSE-----------------------------------------
# library(QFeatures)   # also attaches SummarizedExperiment
# library(msqrob2)
# 
# x <- assay(res$se_proc, "cycloess")
# condition <- factor(res$se_proc$Condition, ordered = FALSE)
# 
# # proDA
# fit <- proDA::proDA(x, design = condition)
# proDA::test_diff(fit, B - A)
# 
# # msqrob2, through a QFeatures object
# coldata <- colData(res$se_proc)
# coldata$Condition <- condition
# qf <- QFeatures(list(proteins = SummarizedExperiment(list(cycloess = x))),
#                 colData = coldata)
# qf <- msqrob(qf, i = "proteins", formula = ~ Condition)
# qf <- hypothesisTest(qf, i = "proteins",
#                      contrast = makeContrast("ConditionB = 0", "ConditionB"))
# rowData(qf[["proteins"]])$ConditionB

## ----se-input-----------------------------------------------------------------
quant_cols <- grep("^PG.Quantity_", names(nadia_dia$protein_quant))
intensities <- as.matrix(nadia_dia$protein_quant[, quant_cols])
rownames(intensities) <- nadia_dia$protein_quant$PG.ProteinGroups

se <- SummarizedExperiment::SummarizedExperiment(
    assays  = list(intensity = intensities),
    colData = data.frame(Condition = nadia_dia$metadata$R.Condition,
                         Replicate = nadia_dia$metadata$R.Replicate),
    rowData = data.frame(Genes = nadia_dia$protein_quant$PG.Genes))

res_se <- process_proteomics(se, verbose = FALSE)
identical(res_se$DEPs_results, res$DEPs_results)

## ----se-from-other-tools, eval = FALSE----------------------------------------
# # QFeatures: the protein-level assay, with the condition added to its colData
# se <- qf[["proteins"]]
# se$Condition <- c("A", "A", "A", "B", "B", "B")
# res <- process_proteomics(se)
# 
# # limpa: precursors read from the DIA-NN report, summarized into proteins
# y   <- limpa::readDIANN("report.parquet")
# dpc <- limpa::dpcCN(y)
# yp  <- limpa::dpcQuant(y, protein.id = "Protein.Group", dpc = dpc)
# se  <- SummarizedExperiment::SummarizedExperiment(
#     assays  = list(log2 = yp$E),
#     colData = data.frame(Condition = c("A", "A", "A", "B", "B", "B")))
# res <- process_proteomics(se, log2_input = TRUE)

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

