Last updated: 2025-12-12

Checks: 7 0

Knit directory: DXR_continue/

This reproducible R Markdown analysis was created with workflowr (version 1.7.1). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20250701) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version 110d7a8. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .Rhistory
    Ignored:    .Rproj.user/
    Ignored:    data/Bed_exports/
    Ignored:    data/Cormotif_data/
    Ignored:    data/DER_data/
    Ignored:    data/Other_paper_data/
    Ignored:    data/TE_annotation/
    Ignored:    data/alignment_summary.txt
    Ignored:    data/all_peak_final_dataframe.txt
    Ignored:    data/cell_line_info_.tsv
    Ignored:    data/full_summary_QC_metrics.txt
    Ignored:    data/motif_lists/
    Ignored:    data/number_frag_peaks_summary.txt

Untracked files:
    Untracked:  H3K27ac_all_regions_test.bed
    Untracked:  H3K27ac_consensus_clusters_test.bed
    Untracked:  analysis/Top2a_Top2b_expression.Rmd
    Untracked:  analysis/chromHMM.Rmd
    Untracked:  analysis/human_genome_composition.Rmd
    Untracked:  analysis/maps_and_plots.Rmd
    Untracked:  analysis/proteomics.Rmd
    Untracked:  code/making_analysis_file_summary.R
    Untracked:  other_analysis/

Unstaged changes:
    Modified:   analysis/Outlier_removal.Rmd
    Modified:   analysis/final_analysis.Rmd
    Modified:   analysis/multiQC_cut_tag.Rmd
    Modified:   analysis/summit_files_processing.Rmd

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the repository in which changes were made to the R Markdown (analysis/H3K27ac_summit_processing.Rmd) and HTML (docs/H3K27ac_summit_processing.html) files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view the files as they were in that past version.

File Version Author Date Message
Rmd 110d7a8 reneeisnowhere 2025-12-12 first commit

library(tidyverse)
library(GenomicRanges)
library(plyranges)
library(genomation)
library(readr)
library(rtracklayer)
library(stringr)
library(BiocParallel)
library(parallel)
library(future.apply)
sampleinfo <- read_delim("data/sample_info.tsv", delim = "\t")
##Path to histone summit files
H3K27ac_dir <- "C:/Users/renee/Other_projects_data/DXR_data/final_data/summit_files/H3K27ac" 

##pull all histone files together
H3K27ac_summit_files <- list.files(
  path = H3K27ac_dir,
  pattern = "\\.bed$",
  recursive = TRUE,
  full.names = TRUE
)
length(H3K27ac_summit_files)
[1] 30
# head(H3K27ac_summit_files)
peakAnnoList_H3K27ac <- readRDS("data/motif_lists/H3K27ac_annotated_peaks.RDS")
H3K27ac_sets_gr <- lapply(peakAnnoList_H3K27ac, function(df) {
  as_granges(df)
})

read_summit <- function(file){
  peaks <- read.table(file,header = FALSE)
  colnames(peaks) <- c("chr","start","end","name","score")
  GRanges(
    seqnames = peaks$chr,
    ranges = IRanges(start=peaks$start, end = peaks$start),
    score=peaks$score,
    file=basename(file),
    Library_ID = stringr::str_remove(basename(file), "_FINAL_summits\\.bed$")
  )
}

all_H3K27ac_summits_list<- lapply(H3K27ac_summit_files, read_summit)
all_H3K27ac_summits_gr <- do.call(c, all_H3K27ac_summits_list)  # combine into one GRanges object
H3K27ac_lookup <- imap_dfr(peakAnnoList_H3K27ac[1:3], ~
  tibble(Peakid = .x@anno$Peakid, cluster = .y)
)


###Adding in sampleinfo dataframe
meta <- as.data.frame(mcols(all_H3K27ac_summits_gr))
meta2 <- meta %>% 
  left_join(., sampleinfo, by=c("Library_ID"="Library ID"))

mcols(all_H3K27ac_summits_gr) <- meta2

mcols(all_H3K27ac_summits_gr)$group <- 
  paste(all_H3K27ac_summits_gr$Treatment,
        all_H3K27ac_summits_gr$Timepoint,
        sep = "_")
ROIs <-  H3K27ac_sets_gr$all_H3K27ac
# -------------------------
# Step 1: Reduce within groups (parallel, Windows-safe)
# -------------------------
get_highest_per_group_parallel <- function(summits_gr, group_col = "group",
                                           score_col = "score", min_gap_within = 100,
                                           workers = 2) {
  # Split GRanges by group to reduce memory per worker
  group_list <- split(summits_gr, mcols(summits_gr)[[group_col]])
  
  plan(multisession, workers = workers)  # Windows-compatible
  results <- future_lapply(group_list, function(gr_sub) {
    if (length(gr_sub) == 0) return(GRanges())
    
    red <- GenomicRanges::reduce(gr_sub, min.gapwidth = min_gap_within, ignore.strand = TRUE, with.revmap = TRUE)
    revmap <- mcols(red)$revmap
    
    idx <- unlist(lapply(revmap, function(x) {
      scores <- mcols(gr_sub)[[score_col]][x]
      x[which.max(scores)]
    }))
    
    gr_sub[idx]
  }, future.seed = TRUE)
  
  do.call(c, results)
}

# -------------------------
# Step 2: Reduce across groups (parallel, Windows-safe)
# -------------------------
get_consensus_summits_parallel <- function(highest_per_group_gr, score_col = "score",
                                           min_gap_across = 400, workers = 2) {
  if (length(highest_per_group_gr) == 0) return(GRanges())
  
  # Split by chromosome to reduce memory per worker
  chr_list <- split(highest_per_group_gr, seqnames(highest_per_group_gr))
  
  plan(multisession, workers = workers)
  results <- future_lapply(chr_list, function(gr_sub) {
    red <- GenomicRanges::reduce(gr_sub, min.gapwidth = min_gap_across, ignore.strand = TRUE, with.revmap = TRUE)
    revmap <- mcols(red)$revmap
    
    idx <- unlist(lapply(revmap, function(x) {
      scores <- mcols(gr_sub)[[score_col]][x]
      x[which.max(scores)]
    }))
    
    gr_sub[idx]
  }, future.seed = TRUE)
  
  do.call(c, results)
}

####### step 3 #####################3
assign_best_summit_to_ROI_parallel <- function(consensus_gr, ROIs_gr, max_dist = 500, workers = 2) {
  # Split ROIs by chromosome
  roi_list <- split(ROIs_gr, seqnames(ROIs_gr))
  cons_list <- split(consensus_gr, seqnames(consensus_gr))
  
  plan(multisession, workers = workers)
  
  results <- future_lapply(names(roi_list), function(chr) {
    rois_chr <- roi_list[[chr]]
    cons_chr <- cons_list[[chr]]
    nROIs <- length(rois_chr)
    
    if (nROIs == 0) return(tibble())
    
    # --- 1) Exact overlaps ---
    ov <- findOverlaps(rois_chr, cons_chr)
    assigned_df <- if(length(ov) > 0) {
      tibble(
        roi_idx = queryHits(ov),
        cons_idx = subjectHits(ov),
        summit_pos = start(cons_chr)[subjectHits(ov)],
        summit_score = mcols(cons_chr)$score[subjectHits(ov)]
      ) %>%
        group_by(roi_idx) %>%
        slice_max(summit_score, with_ties = FALSE) %>%
        ungroup()
    } else {
      tibble()
    }
    
    # --- 2) Nearest fallback for unassigned ---
    assigned_idx <- assigned_df$roi_idx %||% integer(0)
    roi_unassigned <- setdiff(seq_len(nROIs), assigned_idx)
    
    if(length(roi_unassigned) > 0 && length(cons_chr) > 0) {
      dn <- distanceToNearest(rois_chr[roi_unassigned], cons_chr)
      dn_df <- tibble(
        roi_idx = queryHits(dn),
        cons_idx = subjectHits(dn),
        distance = mcols(dn)$distance,
        summit_pos = start(cons_chr)[subjectHits(dn)],
        summit_score = mcols(cons_chr)$score[subjectHits(dn)]
      ) %>%
        filter(distance <= max_dist) %>%
        group_by(roi_idx) %>%
        slice_max(summit_score, with_ties = FALSE) %>%
        ungroup()
      
      assigned_df <- bind_rows(assigned_df, dn_df)
    }
    
    # --- 3) Attach ROI metadata ---
    roi_meta <- tibble(
      roi_idx = seq_len(nROIs),
      Peakid = rois_chr$Peakid,
      roi_seqname = as.character(seqnames(rois_chr)),
      roi_start = start(rois_chr),
      roi_end = end(rois_chr)
    )
    
    out_df <- left_join(roi_meta, assigned_df, by = "roi_idx") %>%
      mutate(
        dist_center = summit_pos - (roi_start + (roi_end - roi_start)/2),
        rel_pos = (summit_pos - roi_start)/(roi_end - roi_start)
      )
    
    out_df
  }, future.seed = TRUE)
  
  final_df <- bind_rows(results) %>% arrange(roi_idx)
  
  # --- 4) Create GRanges of assigned summits ---
  assigned_rows <- final_df %>% filter(!is.na(cons_idx))
  assigned_gr <- if(nrow(assigned_rows) > 0) {
    gr <- GRanges(
      seqnames = assigned_rows$roi_seqname,
      ranges = IRanges(start = assigned_rows$summit_pos, end = assigned_rows$summit_pos),
      Peakid = assigned_rows$Peakid
    )
    
    meta_cols <- setdiff(colnames(assigned_rows),
                         c("roi_idx","cons_idx","summit_pos","summit_score",
                           "Peakid","roi_seqname","roi_start","roi_end","dist_center","rel_pos","distance"))
    if(length(meta_cols) > 0) mcols(gr)[, meta_cols] <- assigned_rows[, meta_cols, drop = FALSE]
    gr
  } else {
    GRanges()
  }
  
  list(df = final_df, gr = assigned_gr)
}
options(future.globals.maxSize = 10 * 1024^3)
workers <- parallel::detectCores() - 1
### Step 1
temp_highest_per_group <- get_highest_per_group_parallel(all_H3K27ac_summits_gr,
                                                         group_col = "group",
                                                         score_col = "score",
                                                         min_gap_within = 100,
                                                         workers = workers)


# Concatenate into one GRanges (Step 1.2)
flat_highest_gr <- (c(temp_highest_per_group$DOX_144R, temp_highest_per_group$DOX_24R,temp_highest_per_group$DOX_24T,temp_highest_per_group$VEH_144R,temp_highest_per_group$VEH_24R,temp_highest_per_group$VEH_24T))

### STep 2
consensus_summits <- get_consensus_summits_parallel(
  flat_highest_gr,
  score_col = "score",
  min_gap_across = 400,
  workers = workers
)

####Concatenate into one GRanges
consensus_summits_gr <- (c(consensus_summits$chr1,consensus_summits$chr2,
                           consensus_summits$chr3,consensus_summits$chr4,
                           consensus_summits$chr5,consensus_summits$chr6,
                           consensus_summits$chr7,consensus_summits$chr8,
                           consensus_summits$chr9,consensus_summits$chr10,
                           consensus_summits$chr11,consensus_summits$chr12,
                           consensus_summits$chr13,consensus_summits$chr14,
                           consensus_summits$chr15,consensus_summits$chr16,
                           consensus_summits$chr17,consensus_summits$chr18,
                           consensus_summits$chr19,consensus_summits$chr20,
                           consensus_summits$chr21,consensus_summits$chr22))

final_data <- assign_best_summit_to_ROI_parallel(consensus_summits_gr, ROIs,max_dist = 500,workers = workers)
# data.frame with one row per ROI (assigned or NA)
final_df <- final_data$df

# GRanges of ROIs that received an assigned summit (with metadata)
assigned_summits_gr <- final_data$gr

# Quick checks
n_missing <- sum(is.na(final_df$summit_pos))
cat("ROIs lacking any summit within max_dist:", n_missing, "\n")
ROIs lacking any summit within max_dist: 13015 
na_rois <- final_df %>% filter(is.na(summit_pos)) 

na_rois_gr <- GRanges(
  seqnames = na_rois$roi_seqname,
  ranges = IRanges(start = na_rois$roi_start, end = na_rois$roi_end),
  Peakid = na_rois$Peakid
)
ov <- findOverlaps(na_rois_gr, flat_highest_gr)

overlap_df <- tibble(
  roi_idx = queryHits(ov),
  summit_idx = subjectHits(ov),
  summit_pos = start(all_H3K27ac_summits_gr)[subjectHits(ov)],
  summit_score = mcols(all_H3K27ac_summits_gr)$score[subjectHits(ov)]
)

best_summits <- overlap_df %>%
  group_by(roi_idx) %>%
  slice_max(summit_score, with_ties = FALSE) %>%
  ungroup()

assigned_df <- tibble(
  roi_idx = seq_along(na_rois_gr),
  Peakid = na_rois_gr$Peakid,
  roi_seqname = as.character(seqnames(na_rois_gr)),
  roi_start = start(na_rois_gr),
  roi_end = end(na_rois_gr)
) %>%
  left_join(best_summits, by = "roi_idx")

assigned_df_calc <- assigned_df %>% mutate(
        dist_center = summit_pos - (roi_start + (roi_end - roi_start)/2),
        rel_pos = (summit_pos - roi_start)/(roi_end - roi_start)
        
      )
complete_summit_df <- final_df %>% 
  dplyr::select(!distance) %>% 
   dplyr::filter(!is.na(summit_pos)) %>% 
  bind_rows(.,assigned_df_calc) %>% 
  left_join(., H3K27ac_lookup, by = "Peakid") %>% 
  dplyr::select(!summit_idx) %>% 
  dplyr::select(!cons_idx) %>% 
   group_by(Peakid) %>% 
  slice_min(order_by = abs(dist_center), n = 1) %>% 
  distinct

complete_summit_gr <- GRanges(
  seqnames=complete_summit_df$roi_seqname,
  ranges=IRanges(start= complete_summit_df$summit_pos, 
                 end= complete_summit_df$summit_pos)
)

# Columns to exclude from metadata (used to define GRanges)
exclude_cols <- c("roi_seqname", "summit_pos")

# Only keep columns that exist in df
meta_cols <- intersect(setdiff(colnames(complete_summit_df), exclude_cols), colnames(complete_summit_df))

# Assign metadata
mcols(complete_summit_gr) <- complete_summit_df[, meta_cols, drop = FALSE]
### adding in cluster membership for export

SET_1_gr <-   complete_summit_gr %>%
  as.data.frame() %>% 
  dplyr::filter(cluster=="Set_1") %>% 
  dplyr::select(seqnames, start, end,Peakid) %>% 
  na.omit() %>% 
  GRanges()


rtracklayer::export(SET_1_gr, "data/Bed_exports/H3K27ac_Set_1_summits.bed")


SET_2_gr <-   complete_summit_gr %>%
  as.data.frame() %>% 
  dplyr::filter(cluster=="Set_2") %>% 
  dplyr::select(seqnames, start, end,Peakid) %>% 
  na.omit() %>% 
  GRanges()



rtracklayer::export(SET_2_gr, "data/Bed_exports/H3K27ac_Set_2_summits.bed")

SET_3_gr <-   complete_summit_gr %>%
  as.data.frame() %>% 
  dplyr::filter(cluster=="Set_3") %>% 
  dplyr::select(seqnames, start, end,Peakid) %>% 
  na.omit() %>% 
  GRanges()



rtracklayer::export(SET_3_gr, "data/Bed_exports/H3K27ac_Set_3_summits.bed")
  

rtracklayer::export(complete_summit_gr, "data/Bed_exports/H3K27ac_complete_final_summits.bed")


outdir <- "data/Bed_exports/summit_groups/"
dir.create(outdir, showWarnings = FALSE)

group_gr_list <- split(consensus_summits_gr, consensus_summits_gr$group)

for (nm in names(group_gr_list)) {
    outfile <- file.path(outdir, paste0(nm, "_summits.bed"))
    export(group_gr_list[[nm]], outfile, format = "BED")
}

sessionInfo()
R version 4.4.2 (2024-10-31 ucrt)
Platform: x86_64-w64-mingw32/x64
Running under: Windows 11 x64 (build 26200)

Matrix products: default


locale:
[1] LC_COLLATE=English_United States.utf8 
[2] LC_CTYPE=English_United States.utf8   
[3] LC_MONETARY=English_United States.utf8
[4] LC_NUMERIC=C                          
[5] LC_TIME=English_United States.utf8    

time zone: America/Chicago
tzcode source: internal

attached base packages:
 [1] parallel  grid      stats4    stats     graphics  grDevices utils    
 [8] datasets  methods   base     

other attached packages:
 [1] ChIPseeker_1.42.1    future.apply_1.20.0  future_1.67.0       
 [4] BiocParallel_1.40.2  rtracklayer_1.66.0   genomation_1.38.0   
 [7] plyranges_1.26.0     GenomicRanges_1.58.0 GenomeInfoDb_1.42.3 
[10] IRanges_2.40.1       S4Vectors_0.44.0     BiocGenerics_0.52.0 
[13] lubridate_1.9.4      forcats_1.0.0        stringr_1.5.1       
[16] dplyr_1.1.4          purrr_1.1.0          readr_2.1.5         
[19] tidyr_1.3.1          tibble_3.3.0         ggplot2_3.5.2       
[22] tidyverse_2.0.0      workflowr_1.7.1     

loaded via a namespace (and not attached):
  [1] RColorBrewer_1.1-3                     
  [2] rstudioapi_0.17.1                      
  [3] jsonlite_2.0.0                         
  [4] magrittr_2.0.3                         
  [5] ggtangle_0.0.7                         
  [6] GenomicFeatures_1.58.0                 
  [7] farver_2.1.2                           
  [8] rmarkdown_2.29                         
  [9] fs_1.6.6                               
 [10] BiocIO_1.16.0                          
 [11] zlibbioc_1.52.0                        
 [12] vctrs_0.6.5                            
 [13] memoise_2.0.1                          
 [14] Rsamtools_2.22.0                       
 [15] RCurl_1.98-1.17                        
 [16] ggtree_3.14.0                          
 [17] htmltools_0.5.8.1                      
 [18] S4Arrays_1.6.0                         
 [19] TxDb.Hsapiens.UCSC.hg19.knownGene_3.2.2
 [20] plotrix_3.8-4                          
 [21] curl_7.0.0                             
 [22] gridGraphics_0.5-1                     
 [23] SparseArray_1.6.2                      
 [24] sass_0.4.10                            
 [25] parallelly_1.45.1                      
 [26] KernSmooth_2.23-26                     
 [27] bslib_0.9.0                            
 [28] plyr_1.8.9                             
 [29] impute_1.80.0                          
 [30] cachem_1.1.0                           
 [31] GenomicAlignments_1.42.0               
 [32] igraph_2.1.4                           
 [33] whisker_0.4.1                          
 [34] lifecycle_1.0.4                        
 [35] pkgconfig_2.0.3                        
 [36] Matrix_1.7-3                           
 [37] R6_2.6.1                               
 [38] fastmap_1.2.0                          
 [39] GenomeInfoDbData_1.2.13                
 [40] MatrixGenerics_1.18.1                  
 [41] enrichplot_1.26.6                      
 [42] digest_0.6.37                          
 [43] aplot_0.2.8                            
 [44] colorspace_2.1-1                       
 [45] patchwork_1.3.2                        
 [46] AnnotationDbi_1.68.0                   
 [47] ps_1.9.1                               
 [48] rprojroot_2.1.1                        
 [49] RSQLite_2.4.3                          
 [50] timechange_0.3.0                       
 [51] httr_1.4.7                             
 [52] abind_1.4-8                            
 [53] compiler_4.4.2                         
 [54] bit64_4.6.0-1                          
 [55] withr_3.0.2                            
 [56] DBI_1.2.3                              
 [57] gplots_3.2.0                           
 [58] R.utils_2.13.0                         
 [59] rappdirs_0.3.3                         
 [60] DelayedArray_0.32.0                    
 [61] rjson_0.2.23                           
 [62] caTools_1.18.3                         
 [63] gtools_3.9.5                           
 [64] tools_4.4.2                            
 [65] ape_5.8-1                              
 [66] httpuv_1.6.16                          
 [67] R.oo_1.27.1                            
 [68] glue_1.8.0                             
 [69] restfulr_0.0.16                        
 [70] callr_3.7.6                            
 [71] nlme_3.1-168                           
 [72] GOSemSim_2.32.0                        
 [73] promises_1.3.3                         
 [74] getPass_0.2-4                          
 [75] gridBase_0.4-7                         
 [76] reshape2_1.4.4                         
 [77] fgsea_1.32.4                           
 [78] generics_0.1.4                         
 [79] gtable_0.3.6                           
 [80] BSgenome_1.74.0                        
 [81] tzdb_0.5.0                             
 [82] R.methodsS3_1.8.2                      
 [83] seqPattern_1.38.0                      
 [84] data.table_1.17.8                      
 [85] hms_1.1.3                              
 [86] XVector_0.46.0                         
 [87] ggrepel_0.9.6                          
 [88] pillar_1.11.0                          
 [89] yulab.utils_0.2.1                      
 [90] vroom_1.6.5                            
 [91] later_1.4.2                            
 [92] splines_4.4.2                          
 [93] treeio_1.30.0                          
 [94] lattice_0.22-7                         
 [95] bit_4.6.0                              
 [96] tidyselect_1.2.1                       
 [97] GO.db_3.20.0                           
 [98] Biostrings_2.74.1                      
 [99] knitr_1.50                             
[100] git2r_0.36.2                           
[101] SummarizedExperiment_1.36.0            
[102] xfun_0.52                              
[103] Biobase_2.66.0                         
[104] matrixStats_1.5.0                      
[105] stringi_1.8.7                          
[106] UCSC.utils_1.2.0                       
[107] lazyeval_0.2.2                         
[108] boot_1.3-32                            
[109] ggfun_0.2.0                            
[110] yaml_2.3.10                            
[111] evaluate_1.0.5                         
[112] codetools_0.2-20                       
[113] qvalue_2.38.0                          
[114] ggplotify_0.1.2                        
[115] cli_3.6.5                              
[116] processx_3.8.6                         
[117] jquerylib_0.1.4                        
[118] dichromat_2.0-0.1                      
[119] Rcpp_1.1.0                             
[120] globals_0.18.0                         
[121] png_0.1-8                              
[122] XML_3.99-0.18                          
[123] blob_1.2.4                             
[124] DOSE_4.0.1                             
[125] bitops_1.0-9                           
[126] listenv_0.9.1                          
[127] tidytree_0.4.6                         
[128] scales_1.4.0                           
[129] crayon_1.5.3                           
[130] rlang_1.1.6                            
[131] fastmatch_1.1-6                        
[132] cowplot_1.2.0                          
[133] KEGGREST_1.46.0