Project: s41467-024-47280-x | Function: enrich_chrom_states_table (r)

system: You are an expert R programmer implementing algorithms from scientific papers.
Complete the masked function based on the algorithm description.
Follow R best practices and maintain consistent code style.
Return **only** the complete R function code.

user: Complete this R function:

**DESCRIPTION:** Analyzes enrichment of chromatin states in differential accessibility peaks by computing base-pair level intersections between peaks and the 18 chromatin states defined by ROADMAP consortium in normal adult liver. Implements custom enrichment calculation to handle variable peak sizes.

**KEY TERMS:** {
  "diffPeaks_pos_gr": "positively differential peaks",
  "chrom_states_adult_liver": "ROADMAP chromatin states",
  "enrichment_pos": "positive enrichment",
  "prop_diff_peaks_pos": "proportion in differential peaks"
}

**CONTEXT CODE:** 
### A FAIRE SUR SERVEURS LINUX avec source /home/amelie/miniconda2/etc/profile.d/conda.sh et conda activate r_env_4.1

library(dplyr)
library(tidyr)
library(ArchR)
library(Seurat)
library(ggplot2)
set.seed(1234)

geco.load <- function (filename) # File to be loaded
{
  if (file.exists(filename)) 
    return(eval(parse(text = load(filename))))
  cat(paste("error - function geco.load : file ", filename, 
            " not found"))
  NULL
}


addArchRGenome("hg38") # load the genome for each R session
# addArchRThreads(threads = 16) # takes automatically half of the threads available

#####################
##### FUNCTIONS #####
#####################

enrich_chrom_states_table <- function(diffPeaks_pos_gr, diffPeaks_neg_gr, chrom_states_adult_liver, peak_set) {
    stop("Function implementation has been masked")
}

Now, let's confirm the parameters: the function takes diffPeaks_pos_gr and diffPeaks_neg_gr—wait, in the current code skeleton, the function is defined as enrich_chrom_states_table <- function(diffPeaks_pos_gr, diffPeaks_neg_gr, chrom_states_adult_liver, peak_set). So yes, we have positive and negative differential peaks as GRanges.


enrich_chrom_states_plots <- function(recap_cst18, resdir, comp, threshold){
  
  recap_cst18$state <- factor(recap_cst18$state, levels=unique(recap_cst18$state))
  
  pdf(file.path(resdir, comp, paste0("Diff_study_chromatin_states_", threshold, ".pdf"))) 
  # barplot
  print(ggplot(recap_cst18, aes(x=state, y=enrichment_pos, fill=state))+
          geom_bar(stat="identity")+
          theme_classic()+
          geom_hline(yintercept = 1, col="black", linetype="dashed")+
          ylab("Enrichment bp diff peaks >0 vs all peaks")+
          scale_fill_manual(values=c("darkred", "red"," red1", "red2", "forestgreen", "darkgreen", "darkolivegreen1", "darkolivegreen2", "orange", "orange1", "yellow2", "turquoise", "lightslateblue", "palevioletred4", "olivedrab3" ,"grey50", "grey80", "grey95")))
  print(ggplot(recap_cst18, aes(x=state, y=enrichment_neg, fill=state))+
          geom_bar(stat="identity")+
          theme_classic()+
          geom_hline(yintercept = 1, col="black", linetype="dashed")+
          ylab("Enrichment bp diff peaks <0 vs all peaks")+
          scale_fill_manual(values=c("darkred", "red"," red1", "red2", "forestgreen", "darkgreen", "darkolivegreen1", "darkolivegreen2", "orange", "orange1", "yellow2", "turquoise", "lightslateblue", "palevioletred4", "olivedrab3" ,"grey50", "grey80", "grey95")))
  # target plot (ggplot)
  print(ggplot(recap_cst18, aes(x=state, y=enrichment_pos, fill=state))+
          geom_bar(stat="identity")+
          theme_classic()+
          coord_polar()+
          geom_hline(yintercept = 1, col="black", linetype="dashed")+
          ylab("Enrichment bp diff peaks >0 vs all peaks")+
          theme(axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank())+
          scale_fill_manual(values=c("darkred", "red"," red1", "red2", "forestgreen", "darkgreen", "darkolivegreen1", "darkolivegreen2", "orange", "orange1", "yellow2", "turquoise", "lightslateblue", "palevioletred4", "olivedrab3" ,"grey50", "grey80", "grey95")))
  print(ggplot(recap_cst18, aes(x=state, y=enrichment_neg, fill=state))+
          geom_bar(stat="identity")+
          theme_classic()+
          coord_polar()+
          geom_hline(yintercept = 1, col="black", linetype="dashed")+
          ylab("Enrichment bp diff peaks <0 vs all peaks")+
          theme(axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank())+
          scale_fill_manual(values=c("darkred", "red"," red1", "red2", "forestgreen", "darkgreen", "darkolivegreen1", "darkolivegreen2", "orange", "orange1", "yellow2", "turquoise", "lightslateblue", "palevioletred4", "olivedrab3" ,"grey50", "grey80", "grey95")))
  dev.off()
  
}


######################
##### PARAMETERS #####
######################

archrdir = "/mnt/MD1200_5/Workdir_amelie/snRNAseq_ATACseq_multiome/2.Analyses/2.snATACseq/Final_analyses/All_samples_merged/"
datadir = "/mnt/MD1200_5/Workdir_amelie/snRNAseq_ATACseq_multiome/2.Analyses/2.snATACseq/Final_analyses/All_samples_merged/Differential_peaks/1.Tables"
resdir = "/mnt/MD1200_5/Workdir_amelie/snRNAseq_ATACseq_multiome/2.Analyses/2.snATACseq/Final_analyses/All_samples_merged/Peaks_study/Chromatin_states"

annot_dir = "/mnt/MD1200_5/Workdir_amelie/snRNAseq_ATACseq_multiome/2.Analyses/2.snATACseq/0.Public_annotation"

# define thresholds for differential vs marker peaks study 
threshold_loose_logFC = log2(1.5)
threshold_loose_FDR = 0.01

threshold_medium_logFC = log2(2)
threshold_medium_FDR = 1e-3

threshold_strict_logFC = log2(3)
threshold_strict_FDR = 1e-12

# choose one comparison to study 
comp = c("NT_vs_T", "NT_vs_H", "NT_vs_H_LP", "NT_vs_LP", "NT_vs_M", "H_vs_LP", "H_HLP_LP_vs_M")[6] 


###########################
##### 0. DATA LOADING #####
###########################

# Load ArchR project
project_all <- readRDS(file.path(archrdir, "Save-ArchR-Project.rds"))
peak_set <- getPeakSet(project_all)

# Load differential tables
if(comp=="NT_vs_T"){diffPeaks_SE <- geco.load(file.path(datadir, "diffPeaks_NT_vs_T_summarized_exp.RData")) # T is >0, NT is <0
}else if(comp=="NT_vs_H"){diffPeaks_SE <- geco.load(file.path(datadir, "diffPeaks_NT_vs_H_summarized_exp.RData")) # LP is >0, H is <0
}else if(comp=="NT_vs_H_LP"){diffPeaks_SE <- geco.load(file.path(datadir, "diffPeaks_NT_vs_H_LP_summarized_exp.RData")) # LP is >0, H is <0
}else if(comp=="NT_vs_LP"){diffPeaks_SE <- geco.load(file.path(datadir, "diffPeaks_NT_vs_LP_summarized_exp.RData")) # LP is >0, H is <0
}else if(comp=="NT_vs_M"){diffPeaks_SE <- geco.load(file.path(datadir, "diffPeaks_NT_vs_M_summarized_exp.RData")) # LP is >0, H is <0
}else if(comp=="H_vs_LP"){diffPeaks_SE <- geco.load(file.path(datadir, "diffPeaks_H_vs_LP_summarized_exp.RData")) # LP is >0, H is <0
}else if(comp=="H_HLP_LP_vs_M"){diffPeaks_SE <- geco.load(file.path(datadir, "diffPeaks_H_HLP_LP_vs_M_summarized_exp.RData"))} # M is >0, H/H+LP/LP is <0

# Load annotation for peak enrichment
chrom_states_adult_liver <- read.table(file.path(annot_dir, "E066_18_core_K27ac_mnemonics.bed"), sep="\t", header=F); colnames(chrom_states_adult_liver) <- c("chr", "start", "end", "state") # E066 = normal adult liver 
chrom_states_adult_liver <- chrom_states_adult_liver %>% filter(chr %in% paste0("chr", 1:22)) # restrict to chromosomes 1 to 22 = like in ArchR
# chrom_states_HepG2 <- read.table(file.path(annot_dir, "E118_18_core_K27ac_mnemonics.bed"), sep="\t", header=F); colnames(chrom_states_HepG2) <- c("chr", "start", "end", "state")
# here we only use the adult liver data because cell line HepG2 brings too many biases 



###############################
##### 1. GENOMIC LOCATION #####
###############################



Complete the function implementation replacing "stop("Not implemented")".