library(tidyverse) library(janitor) library(GenomicRanges) library(here) exclude_regions <- rtracklayer::import(here("data/ChExMix_Peak_Filter_List_190612.bed")) seqlevels(exclude_regions)[which(seqlevels(exclude_regions) == "chr2-micron")] <- "2-micron" brentlab_features <- read_csv("~/projects/huggingface/yeast_genome_resources/brentlab_features.csv.gz") promoters <- list( bp500 = rtracklayer::import("~/projects/huggingface/yeast_genome_resources/start_codon_500bp_upstream_promoters.bed"), mindel = GenomicRanges::GRanges(read_csv("~/projects/huggingface/yeast_genome_resources/mindel_promoters.csv.gz")), kang = rtracklayer::import("~/projects/huggingface/yeast_genome_resources/yiming_promoters.bed"), intergenic = rtracklayer::import("~/projects/huggingface/yeast_genome_resources/intergenic_regions_5_1.bed") ) GenomicRanges::mcols(promoters$mindel) <- GenomicRanges::mcols(promoters$mindel) |> as.data.frame() |> dplyr::transmute(name = target_locus_tag) |> S4Vectors::DataFrame() read_in_annotated_peaks <- function(peak_path) { df <- read_tsv(peak_path, show_col_types = FALSE) # Skip empty annotations if (nrow(df) == 0) { warning(sprintf("Skipping empty annotation file: %s", basename(peak_path))) return(NULL) } tryCatch( { # Convert peaks to GRanges for overlap detection peaks_gr <- GenomicRanges::GRanges( seqnames = df$Chr, ranges = IRanges::IRanges(start = df$Start, end = df$End), strand = df$Strand ) # Find overlaps with exclude regions overlaps <- GenomicRanges::findOverlaps(peaks_gr, exclude_regions) # Label peaks that overlap with exclude regions df <- df |> mutate( in_exclude_region = seq_len(nrow(df)) %in% S4Vectors::queryHits(overlaps) ) |> janitor::clean_names() return(df) }, error = function(e) { warning(sprintf("Error processing: %s. Error: %s", basename(peak_path), e$message)) return(NULL) } ) } score_targets <- function(df, min_dist = 0, max_dist = 700) { df |> filter(!in_exclude_region) |> filter( peak_score > -log10(0.1), str_detect(nearest_promoter_id, "mRNA"), between(distance_to_tss, min_dist, max_dist) ) |> group_by(entrez_id) |> reframe( n_peaks = n(), nearest_score = peak_score[which.min(abs(distance_to_tss))], median_score = median(peak_score), max_score = max(peak_score) ) } annotated_peaks <- list( files = list.files(here("data/chipexo_macs3/annotated_peaks"), "_annotated_peaks.txt", full.names = TRUE, recursive = TRUE ) ) names(annotated_peaks$files) <- str_remove( basename(annotated_peaks$files), "_annotated_peaks.txt" ) annotated_peaks$df <- map(annotated_peaks$files, read_in_annotated_peaks) annotated_peaks$dfcomp annotated_peaks$target_score <- map(compact(annotated_peaks$df), score_targets) peaks_df <- bind_rows(annotated_peaks$target_score, .id = "tmp") |> separate_wider_delim(tmp, delim = "_", names = c( "regulator_locus_tag", "regulator_symbol", "treatment", "growth_media" ), too_few = "align_start" ) |> mutate( treatment = ifelse(treatment == "Heat", "Heat Shock", treatment), growth_media = ifelse(is.na(growth_media), "YPD", growth_media) ) annotate_peaks_to_promoters <- function(peaks_df, promoters_gr) { peaks_gr <- GenomicRanges::GRanges( seqnames = peaks_df$chr, ranges = IRanges::IRanges(start = peaks_df$start, end = peaks_df$end) ) hits <- GenomicRanges::findOverlaps(peaks_gr, promoters_gr, ignore.strand = TRUE) if (length(hits) == 0) { return(peaks_df |> dplyr::slice(0) |> dplyr::mutate(promoter_id = character(), distance_to_tss = numeric())) } promoter_strand <- as.character(GenomicRanges::strand(promoters_gr)) promoter_start <- GenomicRanges::start(promoters_gr) promoter_end <- GenomicRanges::end(promoters_gr) promoter_name <- promoters_gr$name peaks_df[S4Vectors::queryHits(hits), ] |> dplyr::mutate( promoter_id = promoter_name[S4Vectors::subjectHits(hits)], .promoter_strand = promoter_strand[S4Vectors::subjectHits(hits)], .promoter_start = promoter_start[S4Vectors::subjectHits(hits)], .promoter_end = promoter_end[S4Vectors::subjectHits(hits)], .peak_mid = (start + end) / 2, # TSS-proximal edge of the promoter interval .tss_pos = dplyr::if_else(.promoter_strand == "+", .promoter_end, .promoter_start), distance_to_tss = abs(.peak_mid - .tss_pos) ) |> dplyr::select(-dplyr::starts_with("."), distance_to_tss, promoter_id) } score_targets_promoters <- function(df, promoters_gr, peak_score_thresh = -log10(0.1)) { df |> dplyr::filter(!in_exclude_region) |> annotate_peaks_to_promoters(promoters_gr) |> dplyr::filter(peak_score > peak_score_thresh) |> dplyr::group_by(promoter_id) |> dplyr::reframe( n_peaks = n(), nearest_score = peak_score[which.min(distance_to_tss)], median_score = median(peak_score), max_score = max(peak_score) ) } chrmap <- read_csv("~/projects/huggingface/yeast_genome_resources/chrmap.csv.gz") reduce_peak_cols <- function(df) { df |> dplyr::rename(peak_id = 1) |> dplyr::select(peak_id, chr, start, end, strand, peak_score, in_exclude_region) |> left_join(dplyr::select(chrmap, chr, ucsc)) |> mutate(chr = ucsc) |> dplyr::select(-ucsc) } annotated_peaks$df_reduced <- map( compact(annotated_peaks$df), reduce_peak_cols ) annotated_peaks_by_promoter <- map(promoters, ~ { map( annotated_peaks$df_reduced, score_targets_promoters, promoters_gr = . ) }) intergenic_meta <- read_csv("~/projects/huggingface/yeast_genome_resources/intergenic_regions_metadata_5_1.csv") annotated_peaks_by_promoter_df <- map(annotated_peaks_by_promoter, bind_rows, .id = "tmp" ) annotated_peaks_by_promoter_df$intergenic <- annotated_peaks_by_promoter_df$intergenic |> left_join(intergenic_meta |> dplyr::select( promoter_id = ir_name, feature_left, feature_right ) |> pivot_longer(-promoter_id, values_to = "target_locus_tag") |> dplyr::select(-name), relationship = "many-to-many") |> dplyr::select(-promoter_id) |> mutate(promoter_id = target_locus_tag) chec_meta <- arrow::read_parquet("~/projects/huggingface/rossi_2021/rossi_2021_metadata_sample.parquet") reformat_tmp <- function(df) { df |> separate_wider_delim(tmp, delim = "_", names = c( "regulator_locus_tag", "regulator_symbol", "treatment", "growth_media" ), too_few = "align_start" ) |> mutate( treatment = ifelse(treatment == "Heat", "Heat Shock", treatment), growth_media = ifelse(is.na(growth_media), "YPD", growth_media) ) |> mutate(target_locus_tag = promoter_id) |> dplyr::select(-promoter_id) |> left_join(dplyr::select(brentlab_features, target_locus_tag = locus_tag, target_symbol = symbol )) |> dplyr::relocate(regulator_locus_tag, regulator_symbol, treatment, growth_media, target_locus_tag, target_symbol) |> group_by(regulator_locus_tag, treatment, growth_media) |> arrange(desc(max_score)) |> ungroup() |> filter( !is.na(target_locus_tag), !is.na(target_symbol) ) |> left_join(dplyr::select( chec_meta, sample_id, regulator_locus_tag, treatment, growth_media )) |> dplyr::relocate(sample_id) } annotated_peaks_by_promoter_df_out <- map(annotated_peaks_by_promoter_df, reformat_tmp) write_out_promoter_intersect_peaks <- function(name, df) { output_path <- file.path( "~/projects/huggingface/rossi_2021", paste0("macs_", name, ".parquet") ) df |> dplyr::select(-c(regulator_locus_tag, regulator_symbol, treatment, growth_media)) |> arrow::write_parquet(output_path) } # map2(names(annotated_peaks_by_promoter_df_out), # annotated_peaks_by_promoter_df_out, # write_out_promoter_intersect_peaks) rossi_sample_meta <- arrow::read_parquet("~/projects/huggingface/rossi_2021/rossi_2021_metadata_sample.parquet") brentlab_features <- read_csv("~/projects/huggingface/yeast_genome_resources/brentlab_features.csv.gz") peaks_df_to_hf <- peaks_df |> left_join(rossi_sample_meta) |> dplyr::select(sample_id, regulator_locus_tag, regulator_symbol, target_locus_tag = entrez_id, n_peaks, nearest_score, median_score, max_score ) |> left_join(dplyr::select(brentlab_features, target_locus_tag = locus_tag, target_symbol = symbol )) |> dplyr::relocate( sample_id, regulator_locus_tag, regulator_symbol, target_locus_tag, target_symbol ) # peaks_df_to_hf |> # arrow::write_parquet("~/projects/huggingface/rossi_2021/macs2_annotated_peaks.parquet") # mcisaac_responsive <- arrow::read_parquet("~/projects/huggingface/hackett_2020/hackett_2020_analysis_set.parquet") # # peaks_with_mcisaac <- peaks_df |> # dplyr::rename(target_locus_tag = entrez_id) |> # filter( # treatment == "Normal", # growth_media == "YPD", # median_score >= -log10(0.1) # ) |> # left_join(dplyr::select( # mcisaac_responsive, # regulator_locus_tag, # target_locus_tag, # time, # responsive # )) |> # filter(!is.na(responsive)) # # peaks_with_mcisaac |> # filter(time == 30) |> # group_by(regulator_locus_tag) |> # nest() |> # mutate( # rr_nearest = map_dbl(data, ~ { # .x |> # arrange(desc(nearest_score)) |> # slice_head(n = 25) |> # summarise(sum(responsive) / n()) |> # pull() # }), # rr_max = map_dbl(data, ~ { # .x |> # arrange(desc(max_score)) |> # slice_head(n = 25) |> # summarise(sum(responsive) / n()) |> # pull() # }), # rr_median = map_dbl(data, ~ { # .x |> # arrange(desc(median_score)) |> # slice_head(n = 25) |> # summarise(sum(responsive) / n()) |> # pull() # }) # ) |> # dplyr::select(-data) |> # pivot_longer( # cols = starts_with("rr_"), # names_to = "score_type", # values_to = "rr" # ) |> # ggplot(aes(x = score_type, y = rr)) + # geom_boxplot() # # library(patchwork) # library(gridExtra) # # score_summary <- peaks_with_mcisaac |> # filter(time == 30) |> # group_by(regulator_locus_tag) |> # reframe( # score_type = c("nearest", "max", "median"), # n_targets = c( # n_distinct(target_locus_tag), # n_distinct(target_locus_tag), # n_distinct(target_locus_tag) # ), # n_peaks = c(n(), n(), n()), # min = c(min(nearest_score), min(max_score), min(median_score)), # max = c(max(nearest_score), max(max_score), max(median_score)), # median = c(median(nearest_score), median(max_score), median(median_score)), # mean = c(mean(nearest_score), mean(max_score), mean(median_score)) # ) # # # p1 <- score_summary |> # ggplot(aes(x = score_type, y = mean, fill = score_type)) + # geom_boxplot(alpha = 0.7) + # labs(title = "Mean Score Distribution", y = "Mean Score", x = "") + # theme_minimal() + # theme(legend.position = "none") # # p3 <- score_summary |> # ggplot(aes(x = n_targets, y = mean, color = score_type)) + # geom_point(alpha = 0.6) + # facet_wrap(~score_type) + # scale_x_log10() + # labs(title = "Number of Targets vs Mean Score", x = "N Targets (log10)", y = "Mean") + # theme_minimal() + # theme(legend.position = "none") # # # Calculate stats for table # n_targets_summary <- score_summary |> # dplyr::select(n_targets) |> # distinct() |> # pull(n_targets) %>% # { # tibble( # Min = round(quantile(., probs = 0), 2), # Q25 = round(quantile(., probs = 0.25), 2), # Median = round(quantile(., probs = 0.5), 2), # Q75 = round(quantile(., probs = 0.75), 2), # Max = round(quantile(., probs = 1), 2) # ) # } # # # Vertical boxplot # p4_plot <- score_summary |> # dplyr::select(regulator_locus_tag, n_targets) |> # distinct() |> # ggplot(aes(x = "", y = n_targets)) + # geom_boxplot(width = 0.3) + # scale_y_log10() + # labs(title = "Distribution of Targets per Regulator", y = "N Targets (log10)", x = "") + # theme_minimal() + # theme(legend.position = "none") # # # Summary table # p4_table <- gridExtra::tableGrob(n_targets_summary, # rows = NULL, # theme = ttheme_minimal(base_size = 10) # ) # # (p1 + p3) / (p4_plot + p4_table) # # authors_orig_peaks <- arrow::read_parquet("~/projects/huggingface/rossi_2021/yep_filtered_peaks.parquet") |> # mutate(yeastepigenome_id = as.integer(yeastepigenome_id)) # authors_orig_peaks_meta <- arrow::read_parquet("~/projects/huggingface/rossi_2021/rossi_2021_metadata.parquet") # # authors_orig_peaks_normal_conds <- authors_orig_peaks |> # left_join(authors_orig_peaks_meta) |> # filter(treatment == "Normal", growth_media == "YPD") # # find_nearest_peaks <- function(macs_peaks, yep_chexmix_peaks, chrmap) { # library(GenomicRanges) # # Prepare MACS peaks (convert chr names) # macs_gr <- macs_peaks |> # left_join(chrmap |> dplyr::select(ucsc, chr)) |> # dplyr::select(-chr) |> # dplyr::rename(seqnames = ucsc) |> # filter(!is.na(seqnames)) |> # dplyr::select(seqnames, start, end, macs_score = peak_score) |> # GRanges() # # # Prepare YEP ChExMix peaks (convert chr names) # yep_gr <- yep_chexmix_peaks |> # dplyr::select(seqnames = chr, start, end, yeastepigenome_id, yep_score = score) |> # GRanges() # # # Find nearest neighbors # hits <- distanceToNearest(yep_gr, macs_gr) # # # Add results back to YEP peaks # yep_with_nearest <- yep_chexmix_peaks |> # mutate( # query_idx = 1:n(), # subject_idx = subjectHits(hits), # distance = mcols(hits)$distance # ) |> # left_join( # macs_peaks |> # mutate(subject_idx = 1:n()) |> # dplyr::select(subject_idx, macs_score = peak_score, nearest_promoter_id), # by = "subject_idx" # ) |> # mutate( # macs_score_percentile = percent_rank(macs_score) # ) # # return(yep_with_nearest) # } # # chrmap <- read_csv("~/projects/huggingface/yeast_genome_resources/chrmap.csv.gz") # # # Usage: # authors_with_nearest <- find_nearest_peaks( # annotated_peaks$df$YJR060W_CBF1_Normal_YPD, # authors_orig_peaks_normal_conds |> filter(regulator_symbol == "CBF1"), # chrmap # ) # # norm_cond_reg_syms <- intersect( # str_extract(names(compact(annotated_peaks$df))[str_detect(names(compact(annotated_peaks$df)), "Normal")], "(?<=_)[^_]+(?=_)"), # unique(authors_orig_peaks_normal_conds$regulator_symbol) # ) # # # results <- map(norm_cond_reg_syms, ~ { # yep_df <- filter(authors_orig_peaks_normal_conds, regulator_symbol == .x) # rlt <- unique(yep_df$regulator_locus_tag) # macs_df <- annotated_peaks$df[[paste(rlt, .x, "Normal_YPD", sep = "_")]] |> # filter(peak_score > -log10(0.05)) # # find_nearest_peaks( # macs_df, # yep_df, # chrmap # ) # }) # # names(results) <- norm_cond_reg_syms # results_df <- bind_rows(results) # # summary(results_df$macs_score_percentile)