#!/usr/bin/env r

#----------------
## Load libraries
#----------------
library(tidyverse)
library(vroom)
library(DESeq2)


#------------------------
## Load data and metadata
#------------------------
# Annotation
annotation <- vroom(
  "../raw_data_processing/new_samples_2025/mapping_quantification/grape_pipeline/gene_annotation_v48.tsv",
  col_names = c("chr", "start", "end", "strand", "GeneID", "GeneType", "GeneName")
)

# Counts
counts_validation <- vroom(
  "../raw_data_processing/new_samples_2025/mapping_quantification/grape_pipeline/GeneQuantifications_raw.tsv"
)

counts <- vroom('../raw_data_processing/grape_pipeline_gencode.v48/GeneQuantifications_raw.tsv')
counts_old <- vroom('../raw_data_processing/old10/grape_pipeline_gencode.v48/GeneQuantifications_raw.tsv')
counts_original <-
  counts %>%
  full_join(counts_old)

rm(list = c("counts", "counts_old"))

runids <- vroom('../samples', col_names=c('RunID','SampleID'))
colnames(counts_original) <-
  colnames(counts_original) %>%
  as_tibble() %>%
  dplyr::rename(RunID = value) %>%
  left_join(runids) %>%
  mutate(
    SampleID = ifelse(is.na(SampleID), RunID, SampleID)
  ) %>%
  pull(SampleID)


# Metadata
meta_validation <-
  vroom("data/validation_set_metadata.tsv") %>%
  dplyr::rename(
    Sample = `id sample`, Group = `grado de enfermedad`
  ) %>%
  mutate(
    Group = as.factor(Group),
    Sample = as.character(Sample),
  ) %>%
  select(Sample, Group)

meta_original <-
  vroom("../Metadata_Marató_94samples_1.tsv") %>%
  dplyr::rename(
    Sample = `ID complet`, Group = `Grado enfermedad coronaria`
  ) %>%
  mutate(
    Sample=as.character(Sample),
    Group=as.factor(Group)
  ) %>%
  select(Sample, Group)

lane <-
  vroom(
    "../lane",
    col_names=c("Sample", "RunID", "lanes", "lanes_batch")
  ) %>%
  select(Sample, lanes_batch) %>%
  mutate(Sample=as.character(Sample))

meta_original <-
  meta_original %>%
  left_join(lane)

# merge metadata
meta <-
  meta_validation %>%
  mutate(Batch = "phase2_validation") %>%
  bind_rows(
    meta_original %>%
      mutate(
        Batch = ifelse(lanes_batch == 0, "phase1_pilot", "phase1")
      ) %>%
      select(-lanes_batch)
  ) %>%
  mutate(
    Batch = factor(
      Batch,
      levels = c("phase1_pilot", "phase1", "phase2_validation")
    ),
    batch = case_when(
      Batch == "phase1_pilot" ~ "original",
      Batch == "phase1" ~ "original",
      Batch == "phase2_validation" ~ "validation"
    ),
    batch = factor(batch, levels = c("original", "validation"))
  )

# merge count tables
counts <-
  counts_validation %>%
  inner_join(counts_original) %>%
  column_to_rownames("gene_id") %>%
  select(which(colnames(.) %in% meta$Sample)) %>%
  as.matrix()

meta <-
  meta %>%
  filter(Sample %in% colnames(counts)) %>%
  column_to_rownames("Sample")
meta <- meta[colnames(counts), , drop = FALSE]
all(rownames(meta) == colnames(counts))


#-------------
## Filter data
#-------------
cpm_filter <-
  counts %>%
  edgeR::cpm() %>%
  `>`(1) %>%
  rowSums %>%
  `>`(10)

table(cpm_filter)

counts <-
  counts[cpm_filter, ] %>%
  round


#----------------------
## Import Data to DESeq
#----------------------
dge0 <- DESeqDataSetFromMatrix(
  countData = counts,
  colData = meta,
  design = ~batch+Group
)

#----------------------------------
## Differential expression analysis
#----------------------------------
dge <- DESeq(
  dge0,
  fitType = "parametric",
  minReplicatesForReplace = Inf,
  parallel = FALSE
)
    #dds,
    #test = opt\$test,
    #fitType = opt\$fit_type,
    #minReplicatesForReplace = opt\$min_replicates_for_replace,
    #useT = opt\$use_t,
    #sfType = opt\$sf_type,
    #parallel=TRUE, BPPARAM=MulticoreParam(opt\$cores)

res <- results(
  dge,
  alpha=0.05,
  independentFiltering = TRUE
)
    #lfcThreshold         = opt\$lfc_threshold,
    #altHypothesis        = opt\$alt_hypothesis,
    #independentFiltering = opt\$independent_filtering,
    #alpha                = opt\$alpha,
    #pAdjustMethod        = opt\$p_adjust_method,
    #minmu                = opt\$minmu,

#res[which(mcols(dge)$fullBetaConv == F), "padj"] <- NA
summary(res)
res_3vs1 <- res

res_2vs1 <- results(
  dge,
  contrast=c("Group","2","1"),
  alpha=0.05,
  independentFiltering = TRUE
)
summary(res_2vs1)

res_3vs2 <- results(
  dge,
  contrast=c("Group","3","2"),
  alpha=0.05,
  independentFiltering = TRUE
)
summary(res_3vs2)

#resultsNames(dge)
#resLFC <- lfcShrink(dge, coef="Group_3_vs_1",
#                    type="apeglm", lfcThreshold=0.5)

ntd <- normTransform(dge)
#vsd <- vst(dge)

ntd %>%
  assay() %>%
  as.data.frame() %>%
  rownames_to_column("GeneID") %>%
  vroom_write("reports/ntd_merged.tsv")

# Use an interaction model to filter out batch specific effects
dgeInt <- dge0
design(dgeInt) <- ~ batch + Group + batch:Group
dgeInt <- DESeq(
  dgeInt, test = "LRT", reduced = ~ batch + Group,
  fitType = "parametric",
  minReplicatesForReplace = Inf,
  parallel = FALSE
)
resInt <- results(
  dgeInt,
  alpha=0.05,
  independentFiltering = TRUE
)
degs_batchSpecific <-
  resInt %>%
  as.data.frame() %>%
  filter(!is.na(padj)) %>%
  filter(padj <= 0.05 & abs(log2FoldChange) >= 0.5) %>%
  rownames() %>%
  tibble(GeneID = .)

degs_batchSpecific %>%
  vroom_write("reports/degs/final/degs_batch_specific.tsv")



##------------------
### Diagnostic plots
##------------------
#
#pdf('diagnostics.pdf')
#
#plotDispEsts(dge)
#
#plotCounts(dge,
#           gene=which(rank(res_3vs1$padj, ties.method="first") == 1),
#           intgroup="Group")
#
#plotMA(res_3vs1, ylim=c(-2,2))
#
#plotMA(resLFC, ylim=c(-2,2))
#
#ggpoint <- function(x){
#
#  ggplot(x$gg$data, aes(x=px, y=py)) +
#    geom_pointdensity() +
#    geom_line(data=tibble(rank=x$rank, sd=x$sd),
#              aes(rank,sd), color='red') +
#    scale_color_viridis() +
#    labs(x='rank(mean)', y='sd') %>%
#    print
#
#}
#
#x <- meanSdPlot(assay(ntd), plot=F)
#ggpoint(x)
#x <- meanSdPlot(assay(vsd), plot=F)
#ggpoint(x)
##meanSdPlot(assay(rld))
#
#boxplot(log10(assays(dge)[["cooks"]]), range=0, las=2)
#
#plot(metadata(res_3vs1)$filterNumRej,
#     type="b", ylab="number of rejections",
#     xlab="quantiles of filter")
#lines(metadata(res_3vs1)$lo.fit, col="red")
#abline(v=metadata(res_3vs1)$filterTheta)
#
#dev.off()
#
#
#
#----------
## DEG list
#----------
res <- list()
res[['3vs1']] <- res_3vs1
res[['2vs1']] <- res_2vs1
res[['3vs2']] <- res_3vs2


# Save DEG IDs
degIDs <- tibble(comparison=character(), ids=character())
for (comparison in names(res)){
  degIDs <-
    res[[comparison]] %>%
    as.data.frame() %>%
    filter(!is.na(padj)) %>%
    filter(padj <= 0.05 & abs(log2FoldChange) >= 0.5) %>%
    rownames %>%
    tibble(comparison=rep(comparison,length(.)), ids=.) %>%
    rbind(degIDs,.)
}

write.table(degIDs %>% separate(ids, into=c("ids", "x")) %>% select(-x),
            file="reports/degs/final/degs_merged_data.tsv", row.names=F, quote=F, sep = "\t")

# Annotated table
degs_annotated <-
  degIDs %>%
  select(ids) %>%
  distinct() %>%
  dplyr::rename(GeneID = ids) %>%
  left_join(
    res[["3vs1"]] %>%
      as.data.frame() %>%
      rownames_to_column("GeneID") %>%
      as_tibble() %>%
      select(
        GeneID, baseMean, log2FoldChange, padj
      ) %>%
      dplyr::rename(
        baseMean_3vs1 = baseMean,
        log2FoldChange_3vs1 = log2FoldChange,
        padj_3vs1 = padj
      )
  ) %>%
  left_join(
    res[["2vs1"]] %>%
      as.data.frame() %>%
      rownames_to_column("GeneID") %>%
      as_tibble() %>%
      select(
        GeneID, baseMean, log2FoldChange, padj
      ) %>%
      dplyr::rename(
        baseMean_2vs1 = baseMean,
        log2FoldChange_2vs1 = log2FoldChange,
        padj_2vs1 = padj
      )
  ) %>%
  left_join(
    res[["3vs2"]] %>%
      as.data.frame() %>%
      rownames_to_column("GeneID") %>%
      as_tibble() %>%
      select(
        GeneID, baseMean, log2FoldChange, padj
      ) %>%
      dplyr::rename(
        baseMean_3vs2 = baseMean,
        log2FoldChange_3vs2 = log2FoldChange,
        padj_3vs2 = padj
      )
  ) %>%
  left_join(
    annotation %>%
      select(GeneID, GeneName, GeneType)
  )

degs_annotated %>%
  vroom_write("reports/degs/final/degs_merged_data_annotated.tsv")


# DEGs per comparison
degIDs %>%
  group_by(comparison) %>%
  dplyr::count()

# Common DEGs between 3vs1 and 2vs1
degs_CADvsHealthy <-
  intersect(
    degIDs %>%
      filter(comparison == "3vs1") %>%
      pull(ids),
    degIDs %>%
      filter(comparison == "2vs1") %>%
      pull(ids)
  )

# Identify the ones for which the effect have the same direction
degs_CADvsHealthy <-
  degs_CADvsHealthy %>%
  tibble(GeneID = .) %>%
  filter(!(GeneID %in% degs_batchSpecific$GeneID)) %>%
  left_join(
    degs_annotated %>%
      select(
        GeneID, GeneName, GeneType,
        baseMean_3vs1, log2FoldChange_3vs1, padj_3vs1,
        baseMean_2vs1, log2FoldChange_2vs1, padj_2vs1
      )
  ) %>%
  filter(
    sign(log2FoldChange_3vs1) == sign(log2FoldChange_2vs1)
  ) %>%
  arrange(desc(log2FoldChange_3vs1))

degs_CADvsHealthy %>%
  vroom_write("reports/degs/final/degs_CADvsHealthy.tsv")

##--------------
### Volcano Plot
##--------------
pdf('plots/final/volcano_plot_CADvsHealthy.pdf')
for (comp in c("3vs1", "2vs1")){

  genes <-
    res[[comp]] %>%
    as.data.frame() %>%
    filter(!is.na(padj)) %>%
    rownames_to_column('GeneID') %>%
    as_tibble() %>%
    left_join(annotation) %>%
    mutate(
      Significant = ifelse(
        GeneID %in% (
          degIDs %>%
          filter(comparison == comp) %>%
          pull(ids)
        ),
      "Significant",
      "Not Significant"
      ),
      GeneType = case_when(
        Significant == "Not Significant" ~ " ",
        GeneType == "protein_coding" ~ "PC",
        GeneType == "lncRNA" ~ "LnC",
        .default = "Other"
      ),
      GeneType = factor(GeneType, levels = c("PC", "LnC", "Other", " "))
    )

  print(
    ggplot(genes, aes(x = log2FoldChange, y = -log10(padj))) +
    geom_point(
      aes(fill = Significant, color = GeneType),
      shape = 21, stroke = 1.5
    ) +
    scale_fill_manual(values = alpha(c("grey", "black"), 0.8)) +
    scale_color_manual(
      values = alpha(c("#1b9e77", "#d95f02", "#7570b3", "grey"), 1),
      breaks = c("PC", "LnC", "Other")
    ) +
    guides(fill = "none") +
    theme_bw(base_size = 12) +
    theme(legend.position = "top") +
    ggrepel::geom_text_repel(
      data = genes %>%
        filter(GeneID %in% degs_CADvsHealthy$GeneID) %>%
        arrange(desc(log2FoldChange)) %>%
        dplyr::slice(c(1:10, (nrow(.) - 9):nrow(.))),
      aes(label = GeneName),
      size = 4,
      min.segment.length = 0,
      max.overlaps = 15,
      box.padding = unit(0.35, "lines"),
      point.padding = unit(0.3, "lines")
    ) +
    ggtitle(comp)
  )

}
dev.off()


#------------------------
## Boxplots of Expression
#------------------------
source("~/bin/theme_publication.R")
to_plot <- ntd %>%
  assay() %>%
  as.data.frame() %>%
  rownames_to_column("GeneID") %>%
  as_tibble() %>%
  filter(GeneID %in% degs_CADvsHealthy$GeneID) %>%
  pivot_longer(!GeneID, values_to = "Expr", names_to = "Sample") %>%
  left_join(
    annotation %>%
      select(GeneID, GeneName, GeneType)
  ) %>%
  left_join(
    meta %>%
      rownames_to_column("Sample")
  ) %>%
  left_join(
    degs_CADvsHealthy %>%
      select(GeneID, log2FoldChange_3vs1, log2FoldChange_2vs1)
  ) %>%
  arrange(desc(abs(log2FoldChange_3vs1)), desc(abs(log2FoldChange_2vs1))) %>%
  mutate(
    Group = factor(Group, labels = c("Healthy", "Intermediate", "Severe")),
    strip_label = paste0(GeneName, " -- ", GeneType),
    strip_label = factor(strip_label, levels = unique(strip_label))
  )

pdf(
  "plots/final/boxplots_degs_CADvsHealthy.pdf",
  width = 10,
  height = 7
)

for(p in 1:ceiling(nrow(degs_CADvsHealthy) / 9)){
  print(to_plot %>%
    ggplot(aes(Group, Expr, fill = Group)) +
    geom_boxplot(outlier.shape = NA, alpha = 0.5) +
    geom_jitter(aes(color = Batch), size=0.5) +
    ggforce::facet_wrap_paginate(
      ~strip_label, scales = "free_y",
      ncol = 3, nrow = 3, page = p
    ) +
    theme_publication(
      font = "Helvetica",
      size_medium = 10,
      size_small = 9
    ) +
    theme(
      legend.position = "top",
      axis.text.x=element_blank(),
      axis.ticks.x=element_blank()
    ) +
    labs(
      x = "Patient Group",
      y = "Normalilzed Counts (log2 scale)",
      color = "Group:",
      fill = "Batch:"
    ) +
    scale_color_brewer(type = "qual", palette = "Dark2") +
    scale_fill_brewer(type = "qual", palette = "Set1", direction = -1))
}

dev.off()
