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

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

# have_highcharter and prepare_vignette_highchart()
source("highcharts-setup.R")
have_pp_charts <- have_pattern_profiler && have_highcharter

## ----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'---------------------------------------------------------------
design_table <- as.data.frame(SummarizedExperiment::colData(res$se_proc))
design_table <- as.data.frame(table(Condition = design_table$Condition))
names(design_table)[2] <- "Samples"

knitr::kable(
  design_table,
  caption = "Number of samples available for each condition."
)

## ----example-design-table, echo=FALSE-------------------------------------------------------------
knitr::kable(
  design_table,
  caption = "Number of samples available for each condition."
)

## ----run-pattern-profiler, eval=have_pattern_profiler, results='hide'-----------------------------
set.seed(42)
pp <- 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",
  c_range          = 2:5,
  auto_select_c    = TRUE,
  selection_method = "xb",
  min_membership   = 0.25,
  n_starts         = 3,
  verbose          = FALSE
)

## ----run-overview, eval=have_pattern_profiler, results='hide'-------------------------------------
run_overview <- data.frame(
  Measure = c(
    "Proteins selected",
    "Proteins clustered",
    "Rows in long_output",
    "Selected clusters",
    "Fuzzifier (m)"
  ),
  Value = c(
    format(pp$n_features_input, scientific = FALSE),
    format(pp$n_features_final, scientific = FALSE),
    format(pp$n_rows_output, scientific = FALSE),
    format(pp$optimal_c, scientific = FALSE),
    format(round(pp$m, 3), nsmall = 3)
  )
)

knitr::kable(
  run_overview,
  caption = "Overview of the Pattern Profiler run."
)

## ----run-overview-table, eval=have_pattern_profiler, echo=FALSE-----------------------------------
knitr::kable(
  run_overview,
  caption = "Overview of the Pattern Profiler run."
)

## ----filter-counts, results='hide'----------------------------------------------------------------
dep_assay <- as.data.frame(res$DEPs_results)
dep_assay <- dep_assay[dep_assay$Assay == "Impseqrob_min", ]

filter_counts <- data.frame(
  Setting = c(
    'filter_mode = "any"',
    'filter_mode = "specific", comparison = "B-A"',
    'filter_mode = "all"'
  ),
  Proteins = c(
    length(unique(dep_assay$Protein.IDs[dep_assay$adj.P.Val <= 0.05])),
    length(unique(dep_assay$Protein.IDs[
      dep_assay$Comparison == "B-A" & dep_assay$adj.P.Val <= 0.05
    ])),
    nrow(res$se_proc)
  )
)

knitr::kable(
  filter_counts,
  caption = "Number of proteins selected by three filtering strategies."
)

## ----filter-counts-table, echo=FALSE--------------------------------------------------------------
knitr::kable(
  filter_counts,
  caption = "Number of proteins selected by three filtering strategies."
)

## ----selection-metrics, eval=have_pattern_profiler, results='hide'--------------------------------
selection_table <- pp$selection_metrics
selection_table[c("XB", "XB_sd", "FPC", "AMM", "Dmin")] <- lapply(
  selection_table[c("XB", "XB_sd", "FPC", "AMM", "Dmin")],
  round,
  digits = 4
)

knitr::kable(
  selection_table,
  row.names = FALSE,
  caption = "Cluster-selection diagnostics for c = 2 to 5."
)

## ----selection-metrics-table, eval=have_pattern_profiler, echo=FALSE------------------------------
knitr::kable(
  selection_table,
  row.names = FALSE,
  caption = "Cluster-selection diagnostics for c = 2 to 5."
)

## ----long-output, eval=have_pattern_profiler, results='hide'--------------------------------------
knitr::kable(
  head(pp$long_output, 6),
  digits = 3,
  caption = "First rows of the long-format Pattern Profiler output."
)

## ----long-output-table, eval=have_pattern_profiler, echo=FALSE------------------------------------
knitr::kable(
  head(pp$long_output, 6),
  digits = 3,
  caption = "First rows of the long-format Pattern Profiler output."
)

## ----membership-summary, eval=have_pattern_profiler, results='hide'-------------------------------
pp_summary <- summarize_pattern_profiler(pp$long_output)

membership_overview <- data.frame(
  Measure = c(
    "Unique proteins",
    "Protein--cluster associations",
    "Proteins associated with multiple clusters"
  ),
  Value = c(
    pp_summary$n_unique_features,
    pp_summary$n_total_entries,
    pp_summary$n_multi_cluster_features
  )
)

knitr::kable(
  membership_overview,
  caption = "Summary of the soft-clustering assignments."
)

## ----membership-summary-table, eval=have_pattern_profiler, echo=FALSE-----------------------------
knitr::kable(
  membership_overview,
  caption = "Summary of the soft-clustering assignments."
)

## ----cluster-summary, eval=have_pattern_profiler, results='hide'----------------------------------
cluster_table <- as.data.frame(pp_summary$cluster_summary)
cluster_table[c("mean_membership", "min_membership", "max_membership")] <-
  lapply(
    cluster_table[c("mean_membership", "min_membership", "max_membership")],
    round,
    digits = 3
  )

knitr::kable(
  cluster_table,
  caption = "Membership summary for each cluster."
)

## ----cluster-summary-table, eval=have_pattern_profiler, echo=FALSE--------------------------------
knitr::kable(
  cluster_table,
  caption = "Membership summary for each cluster."
)

## ----membership-thresholds, eval=have_pattern_profiler, results='hide'----------------------------
thresholds <- c(0.25, 0.50, 0.70, 0.90)
threshold_table <- data.frame(
  Minimum_membership = thresholds,
  Associations_retained = vapply(
    thresholds,
    function(x) sum(pp$long_output$Membership >= x),
    numeric(1)
  )
)

knitr::kable(
  threshold_table,
  caption = "Effect of applying stricter membership thresholds."
)

## ----membership-thresholds-table, eval=have_pattern_profiler, echo=FALSE--------------------------
knitr::kable(
  threshold_table,
  caption = "Effect of applying stricter membership thresholds."
)

## ----individual-profile-code, eval = if (have_pp_charts) 1 else FALSE-----------------------------
profile_plots <- cluster_profile_highchart_list(
  pp$long_output,
  conditions = pp$conditions,
  min_membership = 0.70,
  centroid_summary = "median"
)

profile_plots[[1]]

## ----cluster-shapes, include = FALSE--------------------------------------------------------------
# Size and shape of each cluster at the 0.70 threshold, so that the text below
# follows the clustering rather than describing one particular run of it: the
# numbering of the clusters is arbitrary and changes with the random starts.
if (have_pattern_profiler) {
  strong <- pp$long_output[pp$long_output$Membership >= 0.70, ]
  n_cluster <- tapply(strong$FeatureID, strong$Cluster,
                      function(x) length(unique(x)))
  centroid <- sapply(split(strong[, pp$conditions], strong$Cluster),
                     function(d) apply(d, 2, median))
  falls <- centroid["D", ] < (centroid["A", ] + centroid["B", ]) / 2
} else {
  n_cluster <- c("1" = NA, "2" = NA)
  falls <- c("1" = TRUE, "2" = FALSE)
}
shape <- ifelse(
  falls,
  "remain relatively stable between `A` and `B` and then decrease in `D`",
  "rise from `A` to `D`"
)
cluster_down <- names(falls)[falls][1]
cluster_up <- names(falls)[!falls][1]

## ----cluster-profile-plot, echo = FALSE, eval = have_pp_charts------------------------------------
prepare_vignette_highchart(profile_plots[[1]])

## ----centroid-highchart-code, eval = if (have_pp_charts) 1 else FALSE-----------------------------
centroid_plot <- cluster_centroids_highchart(
  pp$long_output,
  conditions = pp$conditions,
  min_membership = 0.70,
  centroid_summary = "median",
  title = "Pattern Profiler cluster centroids"
)

centroid_plot

## ----centroid-plot, echo = FALSE, eval = have_pp_charts-------------------------------------------
prepare_vignette_highchart(centroid_plot)

## ----parquet-roundtrip, eval=have_pattern_profiler && requireNamespace("arrow", quietly=TRUE)-----
parquet_file <- file.path(tempdir(), "pattern_profiler.parquet")

set.seed(42)
invisible(capture.output(pp_saved <- pattern_profiler_analysis(
  se_proc          = res$se_proc,
  DEPs_results     = res$DEPs_results,
  assay_name       = "Impseqrob_min",
  filter_mode      = "any",
  condition_order  = c("A", "B", "D"),
  auto_select_c    = FALSE,
  c                = pp$optimal_c,
  min_membership   = 0.25,
  output_file      = parquet_file,
  verbose          = FALSE
)))

reloaded <- read_pattern_profiler_data(
  parquet_file,
  min_membership = 0.70
)

data.frame(
  Rows_saved = nrow(pp_saved$long_output),
  Rows_reloaded_at_0.70 = nrow(reloaded)
)

unlink(parquet_file)

## ----nadia-roundtrip, eval=have_pattern_profiler && requireNamespace("duckdb", quietly=TRUE)------
project_file <- file.path(tempdir(), "pattern_profiler_example.nadia")

write_nadia(
  project_file,
  preprocessing = nadia_dia,
  result = res,
  verbose = FALSE
)

nadia_add_pattern_profiler(
  project_file,
  pattern_profiler = pp,
  verbose = FALSE
)

stored_project <- read_nadia(project_file)
stored_profiles <- nadia_pattern_profiler(stored_project)

data.frame(
  Rows_original = nrow(pp$long_output),
  Rows_recovered = nrow(stored_profiles)
)

unlink(c(project_file, paste0(project_file, ".wal")))

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

