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

options(width = 100)

have_heatmap <- all(vapply(
  c("ComplexHeatmap", "tidyHeatmap", "circlize"),
  requireNamespace,
  logical(1),
  quietly = TRUE
))

have_pattern_profiler <- all(vapply(
  c("Mfuzz", "Biobase", "e1071"),
  requireNamespace,
  logical(1),
  quietly = TRUE
))

# prepare_vignette_highchart(): see highcharts-setup.R, shared with the other
# vignettes that render Highcharts widgets.
source("highcharts-setup.R")

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

## ----load-data------------------------------------------------------------------------------------
library(NADIA)
data(nadia_dia)

res <- process_proteomics(nadia_dia, verbose = FALSE)

## ----example-design, results="hide"---------------------------------------------------------------
sample_design <- unique(
  res$PCA_Input[c("SampleID", "Condition", "Replicate")]
)

design_summary <- as.data.frame(table(sample_design$Condition))
names(design_summary) <- c("Condition", "Samples")

knitr::kable(
  design_summary,
  row.names = FALSE,
  caption = "Number of samples in each condition of the example experiment."
)

## ----example-design-table, echo=FALSE-------------------------------------------------------------
knitr::kable(
  design_summary,
  row.names = FALSE,
  caption = "Number of samples in each condition of the example experiment."
)

## ----visualization-inputs, results="hide"---------------------------------------------------------
input_summary <- data.frame(
  Object = c("DEPs_results", "BoxPlot_Input", "PCA_Input", "se_proc"),
  Rows = c(
    nrow(res$DEPs_results),
    nrow(res$BoxPlot_Input),
    nrow(res$PCA_Input),
    nrow(res$se_proc)
  ),
  Columns = c(
    ncol(res$DEPs_results),
    ncol(res$BoxPlot_Input),
    ncol(res$PCA_Input),
    ncol(res$se_proc)
  ),
  Used_by = c(
    "Volcano plots and Pattern Profiler",
    "Boxplots",
    "PCA and heatmaps",
    "Pattern Profiler"
  )
)

knitr::kable(
  input_summary,
  row.names = FALSE,
  caption = "Objects returned by process_proteomics() for visualization."
)

## ----visualization-inputs-table, echo=FALSE-------------------------------------------------------
knitr::kable(
  input_summary,
  row.names = FALSE,
  caption = "Objects returned by process_proteomics() for visualization."
)

## ----visualization-workflow, echo=FALSE, fig.align="center", out.width="100%", fig.cap="From analytical question to visual output in NADIA. Each row links a recommended view to its input, plotting function or returned object, and graphical unit.", fig.alt="Five-row workflow for choosing a NADIA visualization. Volcano plots use DEPs_results and show one protein per comparison. Boxplots use BoxPlot_Input and show one distribution per sample. PCA uses PCA_Input and shows one point per sample. Heatmaps use PCA_Input and show proteins by samples. Pattern Profiler uses se_proc and DEPs_results to produce long_output and displays protein trajectories and cluster centroids."----
knitr::include_graphics("figures/visualization-workflow.svg")

## ----named-lists, eval=FALSE----------------------------------------------------------------------
# volcanoes <- volcano_highchart_list(res$DEPs_results)
# names(volcanoes)
# volcanoes[["B-A"]]
# 
# boxplots <- boxplot_highchart_list(res$BoxPlot_Input)
# names(boxplots)
# boxplots[["Impseqrob_min"]]
# 
# pcas <- pca_highchart_list(res$PCA_Input, modes = c("all", "any"))
# names(pcas)
# pcas[["all"]]

## ----volcano-summary, results="hide"--------------------------------------------------------------
de_ba <- res$DEPs_results[
  res$DEPs_results$Comparison == "B-A",
  ,
  drop = FALSE
]

volcano_class <- ifelse(
  !is.na(de_ba$adj.P.Val) & de_ba$adj.P.Val < 0.05 & de_ba$logFC >= 1,
  "Up",
  ifelse(
    !is.na(de_ba$adj.P.Val) & de_ba$adj.P.Val < 0.05 & de_ba$logFC <= -1,
    "Down",
    "Not significant"
  )
)

volcano_counts <- as.data.frame(table(
  factor(volcano_class, levels = c("Up", "Down", "Not significant"))
))
names(volcano_counts) <- c("Classification", "Proteins")

n_up <- volcano_counts$Proteins[volcano_counts$Classification == "Up"]
n_down <- volcano_counts$Proteins[volcano_counts$Classification == "Down"]
n_not_significant <- volcano_counts$Proteins[
  volcano_counts$Classification == "Not significant"
]

knitr::kable(
  volcano_counts,
  row.names = FALSE,
  caption = "Protein classification for B-A at adjusted p < 0.05 and |log2FC| >= 1."
)

## ----volcano-summary-table, echo=FALSE------------------------------------------------------------
knitr::kable(
  volcano_counts,
  row.names = FALSE,
  caption = "Protein classification for B-A at adjusted p < 0.05 and |log2FC| >= 1."
)

## ----volcano-plot---------------------------------------------------------------------------------
volcanoes <- volcano_highchart_list(
  res$DEPs_results,
  comparisons = "B-A",
  alpha = 0.05,
  lfc_thr = 1,
  p_col = "adj.P.Val",
  show_top_genes = 6,
  title = "Differential abundance: {comparison}"
)

prepare_vignette_highchart(volcanoes[["B-A"]])

## ----volcano-options, eval=FALSE------------------------------------------------------------------
# # Label proteins selected for their biological relevance.
# highlighted_volcanoes <- volcano_highchart_list(
#   res$DEPs_results,
#   comparisons = "B-A",
#   alpha = 0.05,
#   lfc_thr = 1,
#   highlight_genes = c("lamB", "yciU", "gltA")
# )
# 
# highlighted_volcanoes[["B-A"]]
# 
# # Build several charts with identical settings.
# volcanoes_all <- volcano_highchart_list(
#   res$DEPs_results,
#   comparisons = c("B-A", "D-A", "D-B"),
#   alpha = 0.05,
#   lfc_thr = 1,
#   title = "Differential abundance: {comparison}"
# )
# 
# names(volcanoes_all)
# 
# volcanoes_all[["B-A"]]
# volcanoes_all[["D-A"]]
# volcanoes_all[["D-B"]]

## ----boxplot-summary, results="hide"--------------------------------------------------------------
sample_medians <- aggregate(
  Intensity ~ Assay + Column + Condition,
  data = res$BoxPlot_Input,
  FUN = median,
  na.rm = TRUE
)

median_ranges <- do.call(
  rbind,
  lapply(split(sample_medians$Intensity, sample_medians$Assay), function(x) {
    data.frame(
      Minimum = min(x),
      Maximum = max(x),
      Range = max(x) - min(x)
    )
  })
)

median_ranges$Assay <- rownames(median_ranges)
rownames(median_ranges) <- NULL
median_ranges <- median_ranges[c("Assay", "Minimum", "Maximum", "Range")]
median_ranges[-1] <- lapply(median_ranges[-1], round, digits = 3)

knitr::kable(
  median_ranges,
  row.names = FALSE,
  caption = "Range of sample medians before and after processing."
)

## ----boxplot-summary-table, echo=FALSE------------------------------------------------------------
knitr::kable(
  median_ranges,
  row.names = FALSE,
  caption = "Range of sample medians before and after processing."
)

## ----boxplot-plot---------------------------------------------------------------------------------
set.seed(42)

boxplots <- boxplot_highchart_list(
  res$BoxPlot_Input,
  assays = "Impseqrob_min",
  color_by = "Condition",
  group_order = c("A", "B", "D"),
  horizontal = FALSE,
  show_outliers = TRUE,
  title = "Processed intensity distributions",
  subtitle = "Assay: {assay}",
  height = 560
)

prepare_vignette_highchart(boxplots[["Impseqrob_min"]])

## ----boxplot-options, eval=FALSE------------------------------------------------------------------
# # Display both stages as separate list elements.
# boxplots_both <- boxplot_highchart_list(
#   res$BoxPlot_Input,
#   assays = c("log2", "Impseqrob_min"),
#   group_order = c("A", "B", "D"),
#   show_outliers = TRUE,
#   outlier_size = 2,
#   box_width = 16
# )
# 
# boxplots_both[["log2"]]
# boxplots_both[["Impseqrob_min"]]

## ----pca-summary, results="hide"------------------------------------------------------------------
pca_scores_all <- build_pca_scores(
  res$PCA_Input,
  mode = "all",
  center = TRUE,
  scale. = TRUE
)

pca_scores_any <- build_pca_scores(
  res$PCA_Input,
  mode = "any",
  center = TRUE,
  scale. = TRUE
)

pca_summary <- data.frame(
  Subset = c("All proteins", "Significant in any comparison"),
  Proteins = c(
    length(unique(res$PCA_Input$FeatureID)),
    length(unique(res$PCA_Input$FeatureID[res$PCA_Input$sig_any %in% TRUE]))
  ),
  PC1 = c(unique(pca_scores_all$PC1_Perc), unique(pca_scores_any$PC1_Perc)),
  PC2 = c(unique(pca_scores_all$PC2_Perc), unique(pca_scores_any$PC2_Perc))
)

names(pca_summary)[3:4] <- c("PC1 variance (%)", "PC2 variance (%)")

knitr::kable(
  pca_summary,
  row.names = FALSE,
  digits = 2,
  caption = "Protein subsets and variance represented by the first two principal components."
)

## ----pca-summary-table, echo=FALSE----------------------------------------------------------------
knitr::kable(
  pca_summary,
  row.names = FALSE,
  digits = 2,
  caption = "Protein subsets and variance represented by the first two principal components."
)

## ----pca-plot-------------------------------------------------------------------------------------
condition_colours <- c(
  A = "#0072B2",
  B = "#D55E00",
  D = "#009E73"
)

pcas <- pca_highchart_list(
  res$PCA_Input,
  modes = "all",
  color_by = "Condition",
  group_order = c("A", "B", "D"),
  palette = condition_colours,
  addEllipses = TRUE,
  ellipse_type = "confidence",
  ellipse_level = 0.95,
  show_labels = TRUE,
  point_size = 5,
  center = TRUE,
  scale. = TRUE
)

prepare_vignette_highchart(pcas[["all"]])

## ----pca-options, eval=FALSE----------------------------------------------------------------------
# pca_ba <- pca_highchart_list(
#   res$PCA_Input,
#   modes = "B-A",
#   alpha = 0.05,
#   filter_samples_to_comparison = TRUE,
#   group_order = c("A", "B"),
#   palette = condition_colours[c("A", "B")],
#   addEllipses = FALSE,
#   show_labels = TRUE
# )
# 
# pca_ba[["B-A"]]

## ----heatmap-subsets, results="hide"--------------------------------------------------------------
n_all <- length(unique(res$PCA_Input$FeatureID))
n_any <- length(unique(
  res$PCA_Input$FeatureID[res$PCA_Input$sig_any %in% TRUE]
))
n_ba <- length(unique(
  res$PCA_Input$FeatureID[
    !is.na(res$PCA_Input[["adjP_B-A"]]) &
      res$PCA_Input[["adjP_B-A"]] < 0.05
  ]
))

heatmap_subsets <- data.frame(
  Request = c(
    'mode = "all"',
    'mode = "any"',
    'mode = "target", comparison = "B-A"'
  ),
  Proteins = c(n_all, n_any, n_ba),
  Samples = c(12, 12, 8),
  Interpretation = c(
    "All quantified proteins",
    "Significant in at least one comparison",
    "Significant in B-A; only A and B samples"
  )
)

knitr::kable(
  heatmap_subsets,
  row.names = FALSE,
  caption = "Available protein-filtering modes for the example heatmap."
)

## ----heatmap-subsets-table, echo=FALSE------------------------------------------------------------
knitr::kable(
  heatmap_subsets,
  row.names = FALSE,
  caption = "Available protein-filtering modes for the example heatmap."
)

## ----select-heatmap-proteins----------------------------------------------------------------------
de_ba_ordered <- de_ba[
  !is.na(de_ba$adj.P.Val) & de_ba$adj.P.Val < 0.05,
  ,
  drop = FALSE
]
de_ba_ordered <- de_ba_ordered[order(de_ba_ordered$adj.P.Val), , drop = FALSE]
ba_top_ids <- head(unique(de_ba_ordered$Protein.IDs), 30)

## ----heatmap-plot, eval=have_heatmap, fig.width=8, fig.height=7, fig.align="center", fig.cap="Row-scaled abundance profiles for the 30 proteins with the smallest adjusted p-values in the B-A comparison.", fig.alt="Row-scaled heatmap of the 30 most statistically significant proteins in the B-A comparison"----
proteomics_heatmap(
  res$PCA_Input,
  mode = "target",
  comparison = "B-A",
  feature_ids = ba_top_ids,
  scale_data = "row",
  sample_order = "clustering",
  condition_order = c("A", "B"),
  cluster_rows = TRUE,
  cluster_columns = TRUE,
  show_row_names = TRUE,
  palette_value = "brewer:RdBu",
  reverse_palette = TRUE,
  heatmap_title = "Top B-A protein profiles"
)

## ----heatmap-annotations, eval=have_heatmap, results="hide"---------------------------------------
ba_higher_b_ids <- head(unique(
  de_ba_ordered$Protein.IDs[de_ba_ordered$logFC > 0]
), 15)

ba_higher_a_ids <- head(unique(
  de_ba_ordered$Protein.IDs[de_ba_ordered$logFC < 0]
), 15)

ba_annotation_ids <- c(ba_higher_b_ids, ba_higher_a_ids)

direction <- ifelse(
  de_ba$logFC[match(ba_annotation_ids, de_ba$Protein.IDs)] > 0,
  "Higher in B",
  "Higher in A"
)

protein_annotation <- data.frame(
  FeatureID = ba_annotation_ids,
  Direction = direction
)

annotated_heatmap <- proteomics_heatmap(
  res$PCA_Input,
  mode = "target",
  comparison = "B-A",
  feature_ids = ba_annotation_ids,
  row_annotation = protein_annotation,
  row_annotation_cols = "Direction",
  row_annotation_palette = list(
    Direction = c("Higher in B" = "#D55E00", "Higher in A" = "#0072B2")
  ),
  split_rows_by = "Direction",
  scale_data = "row",
  sample_order = "condition",
  condition_order = c("A", "B")
)

## ----heatmap-annotations-plot, echo=FALSE, eval=have_heatmap, fig.width=8, fig.height=7, fig.align="center", fig.cap="Heatmap of 15 significant proteins with higher abundance in A and 15 with higher abundance in B, annotated and split by direction.", fig.alt="Row-scaled heatmap showing 15 significant proteins with higher abundance in condition A and 15 with higher abundance in condition B"----
annotated_heatmap

## ----heatmap-list-example, eval=FALSE-------------------------------------------------------------
# # Build a named list containing several heatmaps.
# heatmaps <- proteomics_heatmap_list(
#   res$PCA_Input,
#   modes = c("any", "B-A", "D-A"),
#   scale_data = "row",
#   sample_order = "condition",
#   condition_order = c("A", "B", "D")
# )
# 
# # Display the heatmaps individually.
# heatmaps[["any"]]
# heatmaps[["B-A"]]
# heatmaps[["D-A"]]

## ----pattern-profiler-run, eval=have_pattern_profiler, results="hide"-----------------------------
set.seed(42)
pp_vis <- pattern_profiler_analysis(
  se_proc = res$se_proc,
  DEPs_results = res$DEPs_results,
  assay_name = "Impseqrob_min",
  filter_mode = "any",
  alpha = 0.05,
  condition_order = c("A", "B", "D"),
  aggregate = "median",
  auto_select_c = FALSE,
  c = 2,
  min_membership = 0.25,
  verbose = FALSE
)

## ----pattern-profiler-summary, eval=have_pattern_profiler, results="hide"-------------------------
display_membership <- 0.70
pp_display <- pp_vis$long_output[
  pp_vis$long_output$Membership >= display_membership,
  ,
  drop = FALSE
]

pattern_summary <- do.call(
  rbind,
  lapply(split(pp_display, pp_display$Cluster), function(x) {
    data.frame(
      Cluster = paste("Cluster", unique(x$Cluster)),
      Proteins = length(unique(x$FeatureID)),
      `Median membership` = median(x$Membership),
      A = median(x$A),
      B = median(x$B),
      D = median(x$D),
      check.names = FALSE
    )
  })
)

pattern_summary[c("Median membership", "A", "B", "D")] <- lapply(
  pattern_summary[c("Median membership", "A", "B", "D")],
  round,
  digits = 3
)

knitr::kable(
  pattern_summary,
  row.names = FALSE,
  caption = paste0(
    "High-membership proteins and median z-score profiles at membership >= ",
    display_membership, "."
  )
)

## ----pattern-profiler-summary-table, echo=FALSE, eval=have_pattern_profiler-----------------------
knitr::kable(
  pattern_summary,
  row.names = FALSE,
  caption = paste0(
    "High-membership proteins and median z-score profiles at membership >= ",
    display_membership, "."
  )
)

## ----pattern-centroids, eval=have_pattern_profiler------------------------------------------------
centroid_plot <- cluster_centroids_highchart(
  pp_vis$long_output,
  conditions = pp_vis$conditions,
  min_membership = display_membership,
  centroid_summary = "median",
  title = "Pattern Profiler cluster centroids",
  height = 440
)

prepare_vignette_highchart(centroid_plot)

## ----pattern-profiles, eval=have_pattern_profiler-------------------------------------------------
cluster_one <- pp_display[pp_display$Cluster == 1, , drop = FALSE]
cluster_one <- cluster_one[order(cluster_one$Membership, decreasing = TRUE), ]
representative_positions <- unique(round(seq(
  from = 1,
  to = nrow(cluster_one),
  length.out = min(100, nrow(cluster_one))
)))
representative_ids <- cluster_one$FeatureID[representative_positions]
representative_profiles <- cluster_one[
  cluster_one$FeatureID %in% representative_ids,
  ,
  drop = FALSE
]

profile_plot <- cluster_profile_highchart(
  representative_profiles,
  cluster = 1,
  conditions = pp_vis$conditions,
  min_membership = display_membership,
  centroid_summary = "median",
  line_opacity = 0.35,
  title = "Cluster 1: 100 representative protein profiles",
  height = 440
)

prepare_vignette_highchart(profile_plot)

## ----pattern-profiles-all, eval=FALSE-------------------------------------------------------------
# all_profile_plots <- cluster_profile_highchart_list(
#   pp_vis$long_output,
#   conditions = pp_vis$conditions,
#   min_membership = 0.70,
#   centroid_summary = "median"
# )
# 
# all_profile_plots[["Cluster_1"]]

## ----colour-examples, eval=FALSE------------------------------------------------------------------
# # Pattern Profiler: one color for each cluster.
# cluster_colours <- c("#E63946", "#457B9D")
# 
# cluster_centroids_highchart(
#   pp_vis$long_output,
#   conditions = pp_vis$conditions,
#   min_membership = display_membership,
#   centroid_summary = "median",
#   palette = cluster_colours
# )
# 
# # Boxplot: colors follow the condition order.
# condition_colours <- c(
#   A = "#0072B2",
#   B = "#D55E00",
#   D = "#009E73"
# )
# 
# boxplot_highchart_list(
#   res$BoxPlot_Input,
#   assays = "Impseqrob_min",
#   group_order = c("A", "B", "D"),
#   palette = unname(condition_colours)
# )[["Impseqrob_min"]]
# 
# # Volcano plot: colors are named by significance category.
# volcano_colours <- list(
#   up = "#D55E00",
#   down = "#0072B2",
#   ns = "#BDBDBD"
# )
# 
# volcano_highchart_list(
#   res$DEPs_results,
#   comparisons = "B-A",
#   colors = volcano_colours
# )[["B-A"]]

## ----paletteer-example, eval=FALSE----------------------------------------------------------------
# volcano_jco <- volcano_highchart_list(
#   res$DEPs_results,
#   comparisons = "B-A",
#   palette = "ggsci::default_jco"
# )
# 
# volcano_jco[["B-A"]]

## ----export-interactive, eval=FALSE---------------------------------------------------------------
# htmlwidgets::saveWidget(
#   volcanoes[["B-A"]],
#   file = file.path(tempdir(), "volcano_B-A.html"),
#   selfcontained = TRUE
# )
# 
# htmlwidgets::saveWidget(
#   centroid_plot,
#   file = file.path(tempdir(), "pattern_centroids.html"),
#   selfcontained = TRUE
# )

## ----export-heatmap, eval=FALSE-------------------------------------------------------------------
# proteomics_heatmap(
#   res$PCA_Input,
#   mode = "target",
#   comparison = "B-A",
#   feature_ids = ba_top_ids,
#   scale_data = "row",
#   sample_order = "condition",
#   condition_order = c("A", "B"),
#   export_path = file.path(tempdir(), "heatmap_B-A_data.tsv"),
#   export_file = file.path(tempdir(), "heatmap_B-A.png"),
#   plot_width = 8,
#   plot_height = 7,
#   export_dpi = 300
# )

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

