## ----setup, include = FALSE-----------------------------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>", crop = NULL)
options(width = 100)

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

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

## ----mar-mnar-diagram, echo = FALSE, fig.align = "center", out.width = "100%", fig.cap = "Practical distinction between MAR and MNAR missing values in proteomics. MAR values are reconstructed from observed data structure, whereas MNAR values call for a low-value or detection-aware model.", fig.alt = "Two-panel diagram comparing MAR and MNAR missing values. MAR shows a missing replicate among similar observed intensities and recommends structure-based imputation. MNAR shows low values falling below a detection limit and recommends low-value or detection-aware imputation. A note states that an individual missing value does not reveal its cause and that both mechanisms can coexist."----
knitr::include_graphics("figures/MAR_MNAR_Missingness.svg")

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

round(100 * mean(is.na(quant)), 1)
table(missing_per_protein = rowSums(is.na(quant)))

## ----condition-dropout----------------------------------------------------------------------------
condition <- rep(c("A", "B", "D"), each = 4)
whole_condition_missing <- apply(
    quant, 1,
    function(x) any(tapply(is.na(x), condition, all)))

c(exactly_four_missing = sum(rowSums(is.na(quant)) == 4),
  whole_condition_missing = sum(rowSums(is.na(quant)) == 4 &
                                whole_condition_missing))

## ----intensity-vs-missing, fig.width = 6, fig.height = 4, fig.alt = "Mean log2 intensity against number of missing values"----
n_missing  <- rowSums(is.na(quant))
mean_log2  <- rowMeans(log2(quant), na.rm = TRUE)

boxplot(mean_log2 ~ n_missing,
        xlab = "missing values in the protein",
        ylab = "mean log2 intensity of the values present",
        main = "Missingness is concentrated at low abundance")

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

qd <- as.matrix(diann$protein_quant[
    grep("^PG.Quantity_", colnames(diann$protein_quant))])

shared_protein_groups <- length(intersect(
    nadia_dia$protein_quant$PG.ProteinGroups,
    diann$protein_quant$PG.ProteinGroups))

## ----engines-summary------------------------------------------------------------------------------
summarise_missingness <- function(q) {
    n_missing <- rowSums(is.na(q))
    grp <- rep(c("A", "B", "D"), each = 4)
    mean_log2 <- rowMeans(log2(q), na.rm = TRUE)
    median_complete <- median(mean_log2[n_missing == 0])
    median_incomplete <- median(mean_log2[n_missing > 0], na.rm = TRUE)

    c(
        missing_intensities_pct = round(100 * mean(is.na(q)), 1),
        condition_dropout_pct = round(100 * mean(apply(
            q, 1, function(r) any(tapply(is.na(r), grp, all)))), 1),
        median_complete_log2 = round(median_complete, 1),
        median_incomplete_log2 = round(median_incomplete, 1),
        complete_minus_incomplete_log2 = round(
            median_complete - median_incomplete, 1)
    )
}

rbind(
    spectronaut = summarise_missingness(quant),
    diann = summarise_missingness(qd)
)

## ----engines-shape--------------------------------------------------------------------------------
missing_per_protein <- function(q) {
    table(factor(rowSums(is.na(q)), levels = 0:12))
}
rbind(
    spectronaut = missing_per_protein(quant),
    diann = missing_per_protein(qd)
)

## ----combo-classification-diagram, echo = FALSE, fig.align = "center", out.width = "100%", fig.cap = "Examples of how the four combo arguments classify missing cells. A cell is assigned to the MNAR branch only when the missingness threshold and the evidence in other conditions are both satisfied; otherwise it enters the MAR branch or the protein may be removed by the preliminary combo filter.", fig.alt = "Four colored examples of combo classification with four replicates per condition. The first is assigned to MNAR because one condition is 75 percent missing and another is fully observed. The second is assigned to MAR because 50 percent missing is below the 51 percent threshold. The third protein is removed because no other condition has at least 50 percent observed values. The fourth uses three conditions and shows that one qualifying supporting condition is sufficient."----
knitr::include_graphics("figures/Combo_Classification_Examples.svg")

## ----combo, message = FALSE-----------------------------------------------------------------------
res <- process_proteomics(nadia_dia, verbose = FALSE)
imp <- impute_proteomics(res$se_proc, "cycloess", verbose = FALSE)
x_combo <- SummarizedExperiment::assay(res$se_proc, "cycloess")

c(
    proteins_before = nrow(nadia_dia$protein_quant),
    proteins_after_combo_rules = nrow(res$se_proc),
    MAR_missing_values = sum(imp$mar_mask & is.na(x_combo)),
    MNAR_missing_values = sum(imp$mnar_mask & is.na(x_combo))
)

## ----softhybrid-----------------------------------------------------------------------------------
imp_soft <- impute_proteomics(
    res$se_proc,
    normalized_assay_name = "cycloess",
    imp_method  = "softHybrid",
    mar_method  = "Impseqrob",
    mnar_method = "min",
    verbose     = FALSE)

grep("softHybrid", SummarizedExperiment::assayNames(imp_soft$se), value = TRUE)
imp_soft$imputation_summary

## ----limpa, eval = requireNamespace("limpa", quietly = TRUE)--------------------------------------
res_limpa <- process_proteomics(nadia_dia,
                                imp_method = "limpa",
                                de_method  = "limpa",
                                verbose    = FALSE)

class(S4Vectors::metadata(res_limpa$se_proc)$limpa_elist)
table(res_limpa$DEPs_results$Change)

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

