## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
  collapse   = TRUE,
  comment    = "#>",
  fig.width  = 7,
  fig.height = 5,
  warning    = FALSE,
  message    = FALSE
)

## ----install, eval = FALSE----------------------------------------------------
# if (!requireNamespace("BiocManager", quietly = TRUE))
#   install.packages("BiocManager")
# 
# BiocManager::install("MSstatsResponse")
# 
# # MSstats is only needed if you run the preprocessing in the next section
# BiocManager::install("MSstats")

## ----load_libraries, message = FALSE------------------------------------------
library(MSstatsResponse)
library(dplyr)
library(ggplot2)
library(data.table)

## ----msstats_preprocessing, eval = FALSE--------------------------------------
# library(MSstats)
# library(stringr)
# 
# input = data.table::fread("path/to/spectronaut_report.csv")
# 
# # Build the annotation from the report itself: one row per run (fraction)
# annotation = input %>%
#   distinct(Run = R.FileName, Fraction = R.Fraction, Condition = R.Condition) %>%
#   mutate(BioReplicate = Condition)
# 
# # Keep peptides with 0 or 1 leucine in the sequence:
# #   0 L -> can never pick up the heavy label. MSstats marks these LABEL = NA,
# #          and they're exactly the peptides `nameStandards = "unlabeled"` uses
# #          as normalization standards below, so they need to be kept here.
# #   1 L -> one leucine, so the heavy version is fully labeled and the light
# #          version has none. A clean heavy/light pair.
# #  >=2 L -> dropped. A peptide with 2+ leucines that shows only 1 [Leu6] is
# #          partially labeled, not fully labeled, so counting it as "heavy"
# #          would understate how much protein actually turned over.
# input_proper = input %>%
#   filter(str_count(str_remove_all(FG.LabeledSequence, "\\[.*?\\]"), "L") <= 1)
# 
# msstats_input = SpectronauttoMSstatsFormat(
#   input_proper,
#   annotation             = annotation,
#   intensity              = "FG.MS1Quantity",
#   peptideSequenceColumn  = "FG.LabeledSequence",
#   heavyLabels            = c("L[Leu6]"),
#   filter_with_Qvalue     = TRUE,
#   removeFewMeasurements  = FALSE,
#   calculateAnomalyScores = FALSE
# )
# 
# quant_data = dataProcess(msstats_input,
#                          normalization = "globalStandards",
#                          nameStandards = "unlabeled",
#                          featureSubset = "all",
#                          numberOfCores = 4)
# 
# feature_data = quant_data$FeatureLevelData

## ----load_example_data--------------------------------------------------------
data("simulated_turnover_data", package = "MSstatsResponse")

# To analyze your own data, use the output of dataProcess() instead:
# df_feat = quant_data$FeatureLevelData
df_feat = simulated_turnover_data

## ----data_overview------------------------------------------------------------
df_feat %>%
  summarize(proteins   = n_distinct(PROTEIN),
            peptides   = n_distinct(PEPTIDE),
            timepoints = n_distinct(GROUP),
            runs       = n_distinct(originalRUN))

table(df_feat$GROUP, df_feat$LABEL, useNA = "ifany")

## ----calc_qc------------------------------------------------------------------
qc = calculateQCScore(df_feat)

## ----show_qc------------------------------------------------------------------
qc %>% head(n = 10)

## ----prepare_data-------------------------------------------------------------
tracer_constants = c(
  `1`  = 0.11, `2`  = 0.10, `6`   = 0.11, `12`  = 0.12,
  `24` = 0.12, `48` = 0.13, `100` = 0.15, `170` = 0.17
)

ratios = calculateTurnoverRatios(df_feat, normalize_tracer = TRUE,
                                 tracer_constants = tracer_constants)

## ----format_for_fit-----------------------------------------------------------
ratios = ratios %>%
  mutate(protein = Protein, drug = "Synthesis", dose = TimeVal,
         response = H_frac)

table(ratios$TimeVal)

## ----show_ratios--------------------------------------------------------------
ratios %>% head(10)

## ----calc_weights-------------------------------------------------------------
ratios_weighted = calculatePeptideWeights(
  ratios,
  validity_threshold = 1.3, # adjustable to any value
  top_n_peptides     = NULL # NULL uses all peptides; a number keeps only the
                            # top n peptides by light-channel intensity
)

## ----show_weights-------------------------------------------------------------
ratios_weighted %>% data.frame() %>% head(10)

## ----fit, results = "hide"----------------------------------------------------
fit = doseResponseFit(ratios_weighted,
                      weights              = ratios_weighted$weight,
                      increasing           = TRUE,
                      transform_dose       = FALSE,
                      precalculated_ratios = TRUE)

## ----show_fit-----------------------------------------------------------------
fit %>%
  select(Protein, SSE_Full, max_fitted_ratio) %>%
  head(10)

## ----calc_confidence----------------------------------------------------------
conf = calculateConfidence(ratios_weighted, fit, qc, df_feat, k_shrinkage = 2)

## ----show_confidence----------------------------------------------------------
conf %>%
  arrange(-confidence) %>%
  select(Protein, SSE_Full, max_fitted_ratio, mean_weight, qc_score,
         n_heavy_peptides, confidence) %>%
  head(10)

## ----classify-----------------------------------------------------------------
final = classifyTurnoverProteins(
  ratios_weighted,
  fit,
  qc,
  conf,
  high_quantile     = 0.85, # upper percentile cutoff for HIGH tier
  low_quantile      = 0.25, # lower percentile cutoff for LOW tier
  min_obs           = 3,    # minimum observations required for HIGH tier
  long_lived_cutoff = 0.3,  # max_fitted_ratio below this is long_lived
  fast_cutoff       = 0.9   # max_fitted_ratio above this is fast
)
final %>% count(category, tier)

## ----half_life----------------------------------------------------------------
final %>%
  filter(!is.na(half_life)) %>%
  arrange(half_life) %>%
  select(Protein, half_life, max_observed_heavy_ratio, confidence, category,
         tier) %>%
  head(10)

## ----example_protein_table----------------------------------------------------
example_protein = "Protein_072"

final %>%
  filter(Protein == example_protein) %>%
  select(Protein, half_life, max_observed_heavy_ratio, max_fitted_ratio,
         confidence, category, tier)

## ----example_protein_plot-----------------------------------------------------
visualizeResponseProtein(
  data                 = ratios_weighted,
  protein_name         = example_protein,
  drug_name            = "Synthesis",
  precalculated_ratios = TRUE,
  ratio_response       = FALSE,
  transform_dose       = FALSE,
  weights              = ratios_weighted$weight,
  increasing           = TRUE,
  show_ic50            = TRUE,
  ic50_label           = "t50",
  add_ci               = FALSE,
  target_response      = 0.5,
  show_weights         = TRUE,
  y_lab                = "Synthesis Ratio",
  title                = paste(example_protein, "turnover"),
  x_lab                = "Time (hrs)",
  color_by             = "BaseSequence"
)

## ----save_turnover_curves, eval = FALSE---------------------------------------
# library(gridExtra)
# 
# output_dir = tempdir()
# 
# # fast, high-confidence proteins
# protein_list = final %>% filter(category == "fast", tier == "HIGH") %>% pull(Protein)
# 
# # fast, medium-confidence proteins
# protein_list = final %>% filter(category == "fast", tier == "MEDIUM") %>% pull(Protein)
# 
# # medium-lived, high-confidence proteins
# protein_list = final %>% filter(category == "medium_lived", tier == "HIGH") %>% pull(Protein)
# 
# # potential long-lived proteins (no detectable heavy signal), high-confidence
# protein_list = final %>% filter(category == "no_heavy", tier == "HIGH") %>% pull(Protein)
# 
# plots = lapply(protein_list, function(p) {
#   tryCatch({
#     visualizeResponseProtein(
#       data                 = ratios_weighted,
#       protein_name         = p,
#       drug_name            = "Synthesis",
#       precalculated_ratios = TRUE,
#       ratio_response       = FALSE,
#       transform_dose       = FALSE,
#       weights              = ratios_weighted$weight,
#       increasing           = TRUE,
#       show_ic50            = TRUE,
#       add_ci               = FALSE,
#       ic50_label           = "t50",
#       target_response      = 0.5,
#       show_weights         = TRUE,
#       y_lab                = "Turnover Ratio",
#       x_lab                = "time (hrs)",
#       color_by             = "BaseSequence"
#     ) +
#       ggtitle(p) +
#       theme(aspect.ratio = 1) +
#       scale_y_continuous(limits = c(0, 1.5))
#   }, error = function(e) {
#     ggplot() + ggtitle(paste0(p, " (error)")) + theme_void()
#   })
# })
# 
# ggsave(
#   filename = file.path(output_dir, "turnover_proteins.pdf"),
#   plot     = marrangeGrob(plots, nrow = 3, ncol = 3, top = NULL),
#   width    = 20, height = 16
# )
# 
# write.csv(final, file.path(output_dir, "turnover_results.csv"),
#           row.names = FALSE)

## ----session_info-------------------------------------------------------------
sessionInfo()

