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

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

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

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

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

## ----result-components, results = "hide"----------------------------------------------------------
component_summary <- data.frame(
  Component = c(
    "se_proc",
    "DEPs_results",
    "BoxPlot_Input",
    "PCA_Input",
    "comparisons",
    "parameters"
  ),
  Rows = c(
    nrow(res$se_proc),
    nrow(res$DEPs_results),
    nrow(res$BoxPlot_Input),
    nrow(res$PCA_Input),
    length(res$comparisons),
    length(res$parameters)
  ),
  Columns = c(
    ncol(res$se_proc),
    ncol(res$DEPs_results),
    ncol(res$BoxPlot_Input),
    ncol(res$PCA_Input),
    "\u2014",
    "\u2014"
  ),
  Purpose = c(
    "Processed assays and sample metadata",
    "Differential-abundance statistics",
    "Long-format intensities for boxplots",
    "Long-format intensities and significance flags for PCA",
    "Available pairwise comparisons",
    "Analysis settings and recorded function call"
  ),
  check.names = FALSE
)

knitr::kable(
  component_summary,
  caption = "Main components returned by process_proteomics().",
  align = c("l", "r", "r", "l")
)

## ----result-components-table, echo = FALSE--------------------------------------------------------
knitr::kable(
  component_summary,
  caption = "Main components returned by process_proteomics().",
  align = c("l", "r", "r", "l")
)

## ----output-format-diagram, echo = FALSE, out.width = "100%", fig.align = "center", fig.cap = "Four complementary formats for exporting, preserving, or presenting NADIA results.", fig.alt = "A NADIA analysis branches into TSV files, Parquet files, a .nadia archive, and interactive HTML. Each output is described by its best use, main advantage, and main consideration."----
knitr::include_graphics("figures/results-export-formats.svg")

## ----format-comparison-code, results = "hide"-----------------------------------------------------
format_guide <- data.frame(
  Property = c(
    "File structure",
    "Readable as plain text",
    "Direct manual inspection",
    "Column types",
    "Storage requirement",
    "Repeated programmatic access",
    "Typical use"
  ),
  TSV = c(
    "Tab-delimited text",
    "Yes",
    "Text editor or spreadsheet",
    "Inferred when imported",
    "Larger for substantial tables",
    "Requires parsing the text",
    "Review, exchange, and small analyses"
  ),
  Parquet = c(
    "Compressed columnar binary",
    "No",
    "Requires Parquet-aware software",
    "Stored in the file schema",
    "Usually smaller",
    "Fast, including selected-column reads",
    "Data analytics and automated workflows"
  ),
  check.names = FALSE
)

knitr::kable(
  format_guide,
  caption = "Practical differences between TSV and Parquet exports.",
  align = c("l", "l", "l")
)

## ----format-comparison-table, echo = FALSE--------------------------------------------------------
knitr::kable(
  format_guide,
  caption = "Practical differences between TSV and Parquet exports.",
  align = c("l", "l", "l")
)

## ----export-formats, eval = FALSE-----------------------------------------------------------------
# # Export one TSV file for every enabled output.
# process_proteomics(
#   nadia_dia,
#   export_dir = "results/tsv",
#   export_format = "tsv",
#   verbose = FALSE
# )
# 
# # Export the same outputs only as compressed Parquet files.
# process_proteomics(
#   nadia_dia,
#   export_dir = "results/parquet",
#   export_format = "parquet",
#   verbose = FALSE
# )
# 
# # Export matched TSV and Parquet copies of every enabled output.
# process_proteomics(
#   nadia_dia,
#   export_dir = "results/tsv_and_parquet",
#   export_format = "both",
#   verbose = FALSE
# )

## ----export-tsv-code, results = "hide"------------------------------------------------------------
export_dir <- file.path(tempdir(), "nadia_vignette_tables")
unlink(export_dir, recursive = TRUE)

invisible(process_proteomics(
  nadia_dia,
  export_dir = export_dir,
  export_format = "tsv",
  verbose = FALSE
))

exported_files <- list.files(export_dir, full.names = TRUE)

file_contents <- ifelse(
  grepl("matrix_log2.*Imp", basename(exported_files)),
  "Imputed intensity matrix",
  ifelse(
    grepl("matrix_log2", basename(exported_files)),
    "Normalised intensity matrix",
    ifelse(
      grepl("VolcanoPlot", basename(exported_files)),
      "Differential-abundance results",
      ifelse(
        grepl("BoxPlot", basename(exported_files)),
        "Long-format boxplot input",
        "Long-format PCA input"
      )
    )
  )
)

export_manifest <- data.frame(
  File = basename(exported_files),
  Contents = file_contents,
  Size = sprintf("%.1f KB", file.info(exported_files)$size / 1024),
  check.names = FALSE
)

knitr::kable(
  export_manifest,
  caption = "Files created by the default TSV export.",
  align = c("l", "l", "r")
)

## ----export-tsv-table, echo = FALSE---------------------------------------------------------------
knitr::kable(
  export_manifest,
  caption = "Files created by the default TSV export.",
  align = c("l", "l", "r")
)

## ----selective-export, eval = FALSE---------------------------------------------------------------
# process_proteomics(
#   nadia_dia,
#   export_dir = "results/selected_tables",
#   export_format = "both",
#   export_normalized = FALSE,
#   export_imputed = TRUE,
#   export_volcano = TRUE,
#   export_boxplot = FALSE,
#   export_pca = FALSE,
#   verbose = FALSE
# )

## ----write-nadia-code, eval = requireNamespace("duckdb", quietly = TRUE), results = "hide"--------
nadia_file <- file.path(tempdir(), "nadia_vignette_analysis.nadia")
unlink(c(nadia_file, paste0(nadia_file, ".wal")))

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

db <- read_nadia(nadia_file)

archive_summary <- data.frame(
  Property = c(
    "Archive size",
    "Samples",
    "Proteins",
    "Normalised assay",
    "Imputed assay",
    "Pattern Profiler stored"
  ),
  Value = c(
    sprintf("%.1f MB", file.size(nadia_file) / 1024^2),
    db$meta[["n_samples"]],
    db$meta[["n_proteins"]],
    db$meta[["norm_assay"]],
    db$meta[["imputed_assay"]],
    db$meta[["has_pattern_profiler"]]
  ),
  check.names = FALSE
)

knitr::kable(
  archive_summary,
  caption = "Summary of the example .nadia archive.",
  align = c("l", "l")
)

## ----write-nadia-table, echo = FALSE, eval = requireNamespace("duckdb", quietly = TRUE)-----------
knitr::kable(
  archive_summary,
  caption = "Summary of the example .nadia archive.",
  align = c("l", "l")
)

## ----verify-roundtrip-code, eval = requireNamespace("duckdb", quietly = TRUE), results = "hide"----
restored <- nadia_result(db)

roundtrip_check <- data.frame(
  Component = c(
    "Differential-abundance results",
    "PCA input",
    "Final imputed assay"
  ),
  Identical = c(
    identical(restored$DEPs_results, res$DEPs_results),
    identical(restored$PCA_Input, res$PCA_Input),
    identical(
      SummarizedExperiment::assay(restored$se_proc, "Impseqrob_min"),
      SummarizedExperiment::assay(res$se_proc, "Impseqrob_min")
    )
  ),
  check.names = FALSE
)

knitr::kable(
  roundtrip_check,
  caption = "Round-trip verification after restoring the archive.",
  align = c("l", "c")
)

## ----verify-roundtrip-table, echo = FALSE, eval = requireNamespace("duckdb", quietly = TRUE)------
knitr::kable(
  roundtrip_check,
  caption = "Round-trip verification after restoring the archive.",
  align = c("l", "c")
)

## ----nadia-views-code, eval = requireNamespace("duckdb", quietly = TRUE), results = "hide"--------
archive_views <- subset(nadia_tables(nadia_file), type == "view")

view_description <- c(
  v_boxplot_input = "Boxplot input",
  v_deps_results = "Differential-abundance results",
  v_matrix_imputed = "Final imputed matrix",
  v_matrix_norm = "Normalised matrix",
  v_metadata = "Sample metadata",
  v_pca_input = "PCA input",
  v_protein_id = "Protein identification table",
  v_protein_quant = "Protein quantification table"
)

archive_views$Contents <- unname(view_description[archive_views$name])

knitr::kable(
  archive_views[, c("name", "rows", "Contents")],
  col.names = c("View", "Rows", "Reconstructed contents"),
  caption = "Canonical views available in the example archive.",
  align = c("l", "r", "l"),
  row.names = FALSE
)

## ----nadia-views-table, echo = FALSE, eval = requireNamespace("duckdb", quietly = TRUE)-----------
knitr::kable(
  archive_views[, c("name", "rows", "Contents")],
  col.names = c("View", "Rows", "Reconstructed contents"),
  caption = "Canonical views available in the example archive.",
  align = c("l", "r", "l"),
  row.names = FALSE
)

## ----nadia-provenance-code, eval = requireNamespace("duckdb", quietly = TRUE), results = "hide"----
provenance_parameters <- subset(
  db$parameters,
  name %in% c(
    "norm_method", "imp_method", "mar_method", "mnar_method",
    "de_method", "alpha", "logFC_threshold"
  )
)

knitr::kable(
  provenance_parameters[, c("step", "name", "value")],
  col.names = c("Stage", "Parameter", "Recorded value"),
  caption = "Selected parameters stored in the .nadia archive.",
  align = c("l", "l", "l"),
  row.names = FALSE
)

## ----nadia-provenance-table, echo = FALSE, eval = requireNamespace("duckdb", quietly = TRUE)------
knitr::kable(
  provenance_parameters[, c("step", "name", "value")],
  col.names = c("Stage", "Parameter", "Recorded value"),
  caption = "Selected parameters stored in the .nadia archive.",
  align = c("l", "l", "l"),
  row.names = FALSE
)

## ----nadia-sql-code, eval = requireNamespace("duckdb", quietly = TRUE), results = "hide"----------
con <- nadia_connect(nadia_file)

sql_summary <- DBI::dbGetQuery(
  con,
  paste(
    'SELECT "Comparison", "Change", COUNT(*) AS "Proteins"',
    'FROM v_deps_results',
    'GROUP BY "Comparison", "Change"',
    'ORDER BY "Comparison", "Change"'
  )
)

DBI::dbDisconnect(con, shutdown = TRUE)

knitr::kable(
  sql_summary,
  caption = "Protein counts queried directly from the .nadia archive.",
  align = c("l", "l", "r")
)

## ----nadia-sql-table, echo = FALSE, eval = requireNamespace("duckdb", quietly = TRUE)-------------
knitr::kable(
  sql_summary,
  caption = "Protein counts queried directly from the .nadia archive.",
  align = c("l", "l", "r")
)

## ----nadia-to-parquet-code, eval = requireNamespace("duckdb", quietly = TRUE), results = "hide"----
parquet_dir <- file.path(tempdir(), "nadia_vignette_parquet")
unlink(parquet_dir, recursive = TRUE)
invisible(nadia_export_parquet(db, parquet_dir, verbose = FALSE))

parquet_manifest <- data.frame(
  File = list.files(parquet_dir),
  check.names = FALSE
)

knitr::kable(
  parquet_manifest,
  caption = "Parquet tables extracted from the .nadia archive.",
  align = "l"
)

## ----nadia-to-parquet-table, echo = FALSE, eval = requireNamespace("duckdb", quietly = TRUE)------
knitr::kable(
  parquet_manifest,
  caption = "Parquet tables extracted from the .nadia archive.",
  align = "l"
)

## ----run-pattern-profiler, eval = have_pattern_profiler && requireNamespace("duckdb", quietly = TRUE), results = "hide"----
# Generate expression-pattern clusters. Fuzzy c-means starts from a random
# partition, so set.seed() makes the clusters reproducible.
set.seed(123)
pp <- pattern_profiler_analysis(
  res$se_proc,
  res$DEPs_results,
  assay_name = "Impseqrob_min",
  verbose    = FALSE
)

# Add the clustering results to the existing .nadia file.
nadia_add_pattern_profiler(
  nadia_file,
  pattern_profiler = pp,
  verbose = FALSE
)

## ----functional-input, eval = have_pattern_profiler && requireNamespace("duckdb", quietly = TRUE), results = "hide"----
functional_input <- deps_with_clusters(
  res$DEPs_results,
  pp,
  assignment = "primary"
)

knitr::kable(
  head(functional_input[
    !is.na(functional_input$Cluster),
    c("Protein.IDs", "Comparison", "logFC", "adj.P.Val", "Change",
      "Cluster", "Membership")
  ], 6),
  caption = "Differential-abundance results with the dominant cluster of each protein.",
  align = c("l", "l", "r", "r", "l", "r", "r"),
  row.names = FALSE,
  digits = 4
)

## ----functional-input-table, echo = FALSE, eval = have_pattern_profiler && requireNamespace("duckdb", quietly = TRUE)----
knitr::kable(
  head(functional_input[
    !is.na(functional_input$Cluster),
    c("Protein.IDs", "Comparison", "logFC", "adj.P.Val", "Change",
      "Cluster", "Membership")
  ], 6),
  caption = "Differential-abundance results with the dominant cluster of each protein.",
  align = c("l", "l", "r", "r", "l", "r", "r"),
  row.names = FALSE,
  digits = 4
)

## ----assignment-modes, eval = have_pattern_profiler && requireNamespace("duckdb", quietly = TRUE), results = "hide"----
soft <- deps_with_clusters(res$DEPs_results, pp, assignment = "all")

assignment_summary <- data.frame(
  Table = c(
    "Differential-abundance results",
    "assignment = \"primary\"",
    "assignment = \"all\""
  ),
  Rows = c(nrow(res$DEPs_results), nrow(functional_input), nrow(soft)),
  Proteins_without_cluster = c(
    NA_integer_,
    length(unique(functional_input$Protein.IDs[is.na(functional_input$Cluster)])),
    length(unique(soft$Protein.IDs[is.na(soft$Cluster)]))
  ),
  check.names = FALSE
)

knitr::kable(
  assignment_summary,
  col.names = c("Table", "Rows", "Proteins without a cluster"),
  caption = "Effect of the assignment mode on the number of rows.",
  align = c("l", "r", "r")
)

## ----assignment-modes-table, echo = FALSE, eval = have_pattern_profiler && requireNamespace("duckdb", quietly = TRUE)----
knitr::kable(
  assignment_summary,
  col.names = c("Table", "Rows", "Proteins without a cluster"),
  caption = "Effect of the assignment mode on the number of rows.",
  align = c("l", "r", "r")
)

## ----functional-input-sql, eval = have_pattern_profiler && requireNamespace("duckdb", quietly = TRUE), results = "hide"----
con <- nadia_connect(nadia_file)

cluster_counts <- DBI::dbGetQuery(
  con,
  paste(
    'SELECT "Cluster", "Change", COUNT(*) AS "Proteins"',
    'FROM v_deps_pattern_profiler',
    'WHERE "ClusterRank" = 1 AND "Cluster" IS NOT NULL',
    'AND "Comparison" = \'B-A\'',
    'GROUP BY "Cluster", "Change"',
    'ORDER BY "Cluster", "Change"'
  )
)

DBI::dbDisconnect(con, shutdown = TRUE)

knitr::kable(
  cluster_counts,
  caption = "Differential-abundance categories per cluster in comparison B-A.",
  align = c("r", "l", "r")
)

## ----functional-input-sql-table, echo = FALSE, eval = have_pattern_profiler && requireNamespace("duckdb", quietly = TRUE)----
knitr::kable(
  cluster_counts,
  caption = "Differential-abundance categories per cluster in comparison B-A.",
  align = c("r", "l", "r")
)

## ----interactive-tables-diagram, echo = FALSE, out.width = "100%", fig.align = "left", fig.cap = "Four complementary interactive tables for reviewing a NADIA analysis.", fig.alt = "From top left to bottom right: sample summary, protein identification, protein quantification, and differential abundance. Each panel shows a schematic table layout, input objects, row units, and the available NADIA functions."----
knitr::include_graphics("figures/interactive-tables-overview.svg")

## ----interactive-widget-examples, eval = FALSE----------------------------------------------------
# # 1. Sample metadata.
# sample_page <- summary_list_widget(nadia_dia$metadata)
# sample_page
# 
# # 2. Annotations for identified proteins.
# protein_page <- protein_list_widget(
#   nadia_dia$protein_id,
#   metadata = nadia_dia$metadata
# )
# protein_page
# 
# # 3. Quantification values: add the final processed matrix.
# imputed_matrix <- SummarizedExperiment::assay(
#   res$se_proc,
#   "Impseqrob_min"
# )
# matrix_data <- data.frame(
#   ProteinGroups = rownames(imputed_matrix),
#   imputed_matrix,
#   check.names = FALSE
# )
# 
# quantification_page <- quant_list_widget(
#   nadia_dia$protein_quant,
#   matrix_data = matrix_data,
#   metadata = nadia_dia$metadata
# )
# quantification_page
# 
# # 4. Differential-abundance results for comparison B-A.
# results_page <- results_list_widget(
#   res$DEPs_results,
#   protein_quant = nadia_dia$protein_quant,
#   comparisons = "B-A",
#   alpha = 0.05,
#   page_size = 15
# )
# results_page

## ----save-widget-page-code, results = "hide"------------------------------------------------------
widget_dir <- file.path(tempdir(), "nadia_vignette_widget")
dir.create(widget_dir, recursive = TRUE, showWarnings = FALSE)

results_page <- results_list_widget(
  res$DEPs_results,
  protein_quant = nadia_dia$protein_quant,
  comparisons = "B-A"
)

htmltools::save_html(
  results_page,
  file.path(widget_dir, "results_B-A.html")
)

## ----save-self-contained-widget-code, results = "hide"--------------------------------------------
result_table <- results_list_reactable(
  res$DEPs_results,
  protein_quant = nadia_dia$protein_quant,
  comparisons = "B-A"
)

htmlwidgets::saveWidget(
  result_table,
  file.path(widget_dir, "results_B-A_standalone.html"),
  selfcontained = TRUE
)

## ----save-highchart, eval = FALSE-----------------------------------------------------------------
# volcanoes <- volcano_highchart_list(
#   res$DEPs_results,
#   comparisons = "B-A",
#   alpha = 0.05,
#   lfc_thr = 1
# )
# 
# htmlwidgets::saveWidget(
#   volcanoes[["B-A"]],
#   "volcano_B-A.html",
#   selfcontained = TRUE
# )

## ----processing-parameters-code, results = "hide"-------------------------------------------------
selected_parameters <- data.frame(
  Parameter = c(
    "norm_method", "imp_method", "mar_method", "mnar_method",
    "de_method", "alpha", "logFC_threshold"
  ),
  Value = vapply(
    res$parameters[c(
      "norm_method", "imp_method", "mar_method", "mnar_method",
      "de_method", "alpha", "logFC_threshold"
    )],
    as.character,
    character(1)
  ),
  row.names = NULL,
  check.names = FALSE
)

knitr::kable(
  selected_parameters,
  caption = "Main processing parameters for the example analysis.",
  align = c("l", "l")
)

## ----processing-parameters-table, echo = FALSE----------------------------------------------------
knitr::kable(
  selected_parameters,
  caption = "Main processing parameters for the example analysis.",
  align = c("l", "l")
)

## ----reproducibility-checklist-code, results = "hide"---------------------------------------------
reproducibility_items <- data.frame(
  Keep = c(
    "Original proteomics report and sample metadata",
    "Analysis script or R Markdown document",
    "A .nadia archive or the exported result tables",
    "Processing parameters and software versions",
    "Any HTML dependency directory used for sharing"
  ),
  Reason = c(
    "Preserves the source measurements and experimental design",
    "Records the sequence of preprocessing and analysis steps",
    "Preserves the numerical outputs that were interpreted",
    "Identifies the exact methods, thresholds, and computational environment",
    "Keeps multi-file interactive pages functional offline"
  ),
  check.names = FALSE
)

knitr::kable(
  reproducibility_items,
  caption = "Recommended material to retain with a NADIA analysis.",
  align = c("l", "l")
)

## ----reproducibility-checklist-table, echo = FALSE------------------------------------------------
knitr::kable(
  reproducibility_items,
  caption = "Recommended material to retain with a NADIA analysis.",
  align = c("l", "l")
)

## ----cleanup, include = FALSE---------------------------------------------------------------------
cleanup_paths <- c(
  if (exists("export_dir")) export_dir,
  if (exists("nadia_file")) c(nadia_file, paste0(nadia_file, ".wal")),
  if (exists("parquet_dir")) parquet_dir,
  if (exists("widget_dir")) widget_dir
)

unlink(cleanup_paths, recursive = TRUE)

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

