Last updated: 2025-04-30

Checks: 7 0

Knit directory: ATAC_learning/

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(20231016) 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 2275802. 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:    .RData
    Ignored:    .Rhistory
    Ignored:    .Rproj.user/
    Ignored:    data/ACresp_SNP_table.csv
    Ignored:    data/ARR_SNP_table.csv
    Ignored:    data/All_merged_peaks.tsv
    Ignored:    data/CAD_gwas_dataframe.RDS
    Ignored:    data/CTX_SNP_table.csv
    Ignored:    data/Collapsed_expressed_NG_peak_table.csv
    Ignored:    data/DEG_toplist_sep_n45.RDS
    Ignored:    data/FRiP_first_run.txt
    Ignored:    data/Final_four_data/
    Ignored:    data/Frip_1_reads.csv
    Ignored:    data/Frip_2_reads.csv
    Ignored:    data/Frip_3_reads.csv
    Ignored:    data/Frip_4_reads.csv
    Ignored:    data/Frip_5_reads.csv
    Ignored:    data/Frip_6_reads.csv
    Ignored:    data/GO_KEGG_analysis/
    Ignored:    data/HF_SNP_table.csv
    Ignored:    data/Ind1_75DA24h_dedup_peaks.csv
    Ignored:    data/Ind1_TSS_peaks.RDS
    Ignored:    data/Ind1_firstfragment_files.txt
    Ignored:    data/Ind1_fragment_files.txt
    Ignored:    data/Ind1_peaks_list.RDS
    Ignored:    data/Ind1_summary.txt
    Ignored:    data/Ind2_TSS_peaks.RDS
    Ignored:    data/Ind2_fragment_files.txt
    Ignored:    data/Ind2_peaks_list.RDS
    Ignored:    data/Ind2_summary.txt
    Ignored:    data/Ind3_TSS_peaks.RDS
    Ignored:    data/Ind3_fragment_files.txt
    Ignored:    data/Ind3_peaks_list.RDS
    Ignored:    data/Ind3_summary.txt
    Ignored:    data/Ind4_79B24h_dedup_peaks.csv
    Ignored:    data/Ind4_TSS_peaks.RDS
    Ignored:    data/Ind4_V24h_fraglength.txt
    Ignored:    data/Ind4_fragment_files.txt
    Ignored:    data/Ind4_fragment_filesN.txt
    Ignored:    data/Ind4_peaks_list.RDS
    Ignored:    data/Ind4_summary.txt
    Ignored:    data/Ind5_TSS_peaks.RDS
    Ignored:    data/Ind5_fragment_files.txt
    Ignored:    data/Ind5_fragment_filesN.txt
    Ignored:    data/Ind5_peaks_list.RDS
    Ignored:    data/Ind5_summary.txt
    Ignored:    data/Ind6_TSS_peaks.RDS
    Ignored:    data/Ind6_fragment_files.txt
    Ignored:    data/Ind6_peaks_list.RDS
    Ignored:    data/Ind6_summary.txt
    Ignored:    data/Knowles_4.RDS
    Ignored:    data/Knowles_5.RDS
    Ignored:    data/Knowles_6.RDS
    Ignored:    data/LiSiLTDNRe_TE_df.RDS
    Ignored:    data/MI_gwas.RDS
    Ignored:    data/SNP_GWAS_PEAK_MRC_id
    Ignored:    data/SNP_GWAS_PEAK_MRC_id.csv
    Ignored:    data/SNP_gene_cat_list.tsv
    Ignored:    data/SNP_supp_schneider.RDS
    Ignored:    data/TE_info/
    Ignored:    data/TFmapnames.RDS
    Ignored:    data/all_TSSE_scores.RDS
    Ignored:    data/all_four_filtered_counts.txt
    Ignored:    data/aln_run1_results.txt
    Ignored:    data/anno_ind1_DA24h.RDS
    Ignored:    data/anno_ind4_V24h.RDS
    Ignored:    data/annotated_gwas_SNPS.csv
    Ignored:    data/background_n45_he_peaks.RDS
    Ignored:    data/cardiac_muscle_FRIP.csv
    Ignored:    data/cardiomyocyte_FRIP.csv
    Ignored:    data/col_ng_peak.csv
    Ignored:    data/cormotif_full_4_run.RDS
    Ignored:    data/cormotif_full_4_run_he.RDS
    Ignored:    data/cormotif_full_6_run.RDS
    Ignored:    data/cormotif_full_6_run_he.RDS
    Ignored:    data/cormotif_probability_45_list.csv
    Ignored:    data/cormotif_probability_45_list_he.csv
    Ignored:    data/cormotif_probability_all_6_list.csv
    Ignored:    data/cormotif_probability_all_6_list_he.csv
    Ignored:    data/datasave.RDS
    Ignored:    data/embryo_heart_FRIP.csv
    Ignored:    data/enhancer_list_ENCFF126UHK.bed
    Ignored:    data/enhancerdata/
    Ignored:    data/filt_Peaks_efit2.RDS
    Ignored:    data/filt_Peaks_efit2_bl.RDS
    Ignored:    data/filt_Peaks_efit2_n45.RDS
    Ignored:    data/first_Peaksummarycounts.csv
    Ignored:    data/first_run_frag_counts.txt
    Ignored:    data/full_bedfiles/
    Ignored:    data/gene_ref.csv
    Ignored:    data/gwas_1_dataframe.RDS
    Ignored:    data/gwas_2_dataframe.RDS
    Ignored:    data/gwas_3_dataframe.RDS
    Ignored:    data/gwas_4_dataframe.RDS
    Ignored:    data/gwas_5_dataframe.RDS
    Ignored:    data/high_conf_peak_counts.csv
    Ignored:    data/high_conf_peak_counts.txt
    Ignored:    data/high_conf_peaks_bl_counts.txt
    Ignored:    data/high_conf_peaks_counts.txt
    Ignored:    data/hits_files/
    Ignored:    data/hyper_files/
    Ignored:    data/hypo_files/
    Ignored:    data/ind1_DA24hpeaks.RDS
    Ignored:    data/ind1_TSSE.RDS
    Ignored:    data/ind2_TSSE.RDS
    Ignored:    data/ind3_TSSE.RDS
    Ignored:    data/ind4_TSSE.RDS
    Ignored:    data/ind4_V24hpeaks.RDS
    Ignored:    data/ind5_TSSE.RDS
    Ignored:    data/ind6_TSSE.RDS
    Ignored:    data/initial_complete_stats_run1.txt
    Ignored:    data/left_ventricle_FRIP.csv
    Ignored:    data/median_24_lfc.RDS
    Ignored:    data/median_3_lfc.RDS
    Ignored:    data/mergedPeads.gff
    Ignored:    data/mergedPeaks.gff
    Ignored:    data/motif_list_full
    Ignored:    data/motif_list_n45
    Ignored:    data/motif_list_n45.RDS
    Ignored:    data/multiqc_fastqc_run1.txt
    Ignored:    data/multiqc_fastqc_run2.txt
    Ignored:    data/multiqc_genestat_run1.txt
    Ignored:    data/multiqc_genestat_run2.txt
    Ignored:    data/my_hc_filt_counts.RDS
    Ignored:    data/my_hc_filt_counts_n45.RDS
    Ignored:    data/n45_bedfiles/
    Ignored:    data/n45_files
    Ignored:    data/other_papers/
    Ignored:    data/peakAnnoList_1.RDS
    Ignored:    data/peakAnnoList_2.RDS
    Ignored:    data/peakAnnoList_24_full.RDS
    Ignored:    data/peakAnnoList_24_n45.RDS
    Ignored:    data/peakAnnoList_3.RDS
    Ignored:    data/peakAnnoList_3_full.RDS
    Ignored:    data/peakAnnoList_3_n45.RDS
    Ignored:    data/peakAnnoList_4.RDS
    Ignored:    data/peakAnnoList_5.RDS
    Ignored:    data/peakAnnoList_6.RDS
    Ignored:    data/peakAnnoList_Eight.RDS
    Ignored:    data/peakAnnoList_full_motif.RDS
    Ignored:    data/peakAnnoList_n45_motif.RDS
    Ignored:    data/siglist_full.RDS
    Ignored:    data/siglist_n45.RDS
    Ignored:    data/summarized_peaks_dataframe.txt
    Ignored:    data/summary_peakIDandReHeat.csv
    Ignored:    data/test.list.RDS
    Ignored:    data/testnames.txt
    Ignored:    data/toplist_6.RDS
    Ignored:    data/toplist_full.RDS
    Ignored:    data/toplist_full_DAR_6.RDS
    Ignored:    data/toplist_n45.RDS
    Ignored:    data/trimmed_seq_length.csv
    Ignored:    data/unclassified_full_set_peaks.RDS
    Ignored:    data/unclassified_n45_set_peaks.RDS
    Ignored:    data/xstreme/

Untracked files:
    Untracked:  analysis/Expressed_RNA_associations.Rmd
    Untracked:  analysis/LFC_corr.Rmd
    Untracked:  analysis/SVA.Rmd
    Untracked:  analysis/Tan2020.Rmd
    Untracked:  analysis/my_hc_filt_counts.csv
    Untracked:  code/IGV_snapshot_code.R
    Untracked:  code/LongDARlist.R
    Untracked:  code/just_for_Fun.R
    Untracked:  output/cormotif_probability_45_list.csv
    Untracked:  output/cormotif_probability_all_6_list.csv
    Untracked:  setup.RData

Unstaged changes:
    Modified:   ATAC_learning.Rproj
    Modified:   analysis/Correlation_of_SNPnPEAK.Rmd
    Modified:   analysis/GO_KEGG_analysis.Rmd
    Modified:   analysis/Raodah_mycount.Rmd
    Modified:   analysis/TE_analysis_ff.Rmd
    Modified:   analysis/final_plot_attempt.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/Figure_1.Rmd) and HTML (docs/Figure_1.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 2275802 reneeisnowhere 2025-04-30 update site yml file
html 3c8d60b E. Renee Matthews 2025-02-21 Build site.
Rmd 67b47a9 E. Renee Matthews 2025-02-21 wflow_publish("analysis/Figure_1.Rmd")
html 5a24a87 E. Renee Matthews 2025-02-21 Build site.
Rmd 80c0b6b E. Renee Matthews 2025-02-21 adding external image
html d82300d E. Renee Matthews 2025-02-21 Build site.
Rmd 19f89cc E. Renee Matthews 2025-02-21 adding external image
html 22b314f E. Renee Matthews 2025-02-21 Build site.
Rmd 0964e7c E. Renee Matthews 2025-02-21 adding external image
html 0872582 E. Renee Matthews 2025-02-21 Build site.
Rmd d0ac226 E. Renee Matthews 2025-02-21 adding external image
html 7db849f E. Renee Matthews 2025-02-21 Build site.
Rmd 25af13e E. Renee Matthews 2025-02-21 Adding first figure

package loading
library(tidyverse)
library(kableExtra)
library(broom)
library(RColorBrewer)
library("TxDb.Hsapiens.UCSC.hg38.knownGene")
library("org.Hs.eg.db")
library(rtracklayer)
library(ggfortify)
library(readr)
library(BiocGenerics)
library(gridExtra)
library(VennDiagram)
library(scales)
library(ggVennDiagram)
library(BiocParallel)
library(ggpubr)
library(edgeR)
library(genomation)
library(ggsignif)
library(plyranges)
library(ggrepel)
library(ComplexHeatmap)
library(cowplot)
library(smplot2)
library(readxl)
drug_pal <- c("#8B006D","#DF707E","#F1B72B", "#3386DD","#707031","#41B333")

pca_plot <-
  function(df,
           col_var = NULL,
           shape_var = NULL,
           title = "") {
    ggplot(df) + geom_point(aes_string(
      x = "PC1",
      y = "PC2",
      color = col_var,
      shape = shape_var
    ),
    size = 5) +
      labs(title = title, x = "PC 1", y = "PC 2") +
      scale_color_manual(values = c(
        "#8B006D",
        "#DF707E",
        "#F1B72B",
        "#3386DD",
        "#707031",
        "#41B333"
      ))
  }

calc_pca <- function(x) {
  # Performs principal components analysis with prcomp
  # x: a sample-by-gene numeric matrix
  prcomp(x, scale. = TRUE, retx = TRUE)
}
##counts table for part B:
filt_counts_raw <- readRDS("data/Final_four_data/ATAC_filtered_raw_counts_allsamples.RDS")

Figure 1.A & E: Schematic of experiment and genome browser of an ESR loci.

knitr::include_graphics("assets/Figure\ 1.png", error=FALSE)

Version Author Date
d64bc29 E. Renee Matthews 2025-02-21

Figure 1.B: PCA Plot of log2cpm open chromatin regions

n= 155,557

filt4_matrix_lcpm <- filt_counts_raw  %>%
  as.data.frame() %>% 
  rename_with(.,~gsub(pattern = "Ind1_75", replacement = "D_",.)) %>% 
  rename_with(.,~gsub(pattern = "Ind2_87", replacement = "A_",.)) %>% 
  rename_with(.,~gsub(pattern = "Ind3_77", replacement = "B_",.)) %>% 
  rename_with(.,~gsub(pattern = "Ind6_71", replacement = "C_",.)) %>% 
  rename_with(.,~gsub( "DX" ,'DOX',.)) %>% 
  rename_with(.,~gsub( "DA" ,'DNR',.)) %>% 
  rename_with(.,~gsub( "E" ,'EPI',.)) %>% 
  rename_with(.,~gsub( "T" ,'TRZ',.)) %>%
  rename_with(.,~gsub( "M" ,'MTX',.)) %>% 
  rename_with(.,~gsub( "V" ,'VEH',.)) %>% 
  rename_with(.,~gsub("24h","_24h",.)) %>% 
  rename_with(.,~gsub("3h","_3h",.)) %>% 
  as.matrix() %>% 
  cpm(., log = TRUE) 
annotation_mat <- data.frame(timeset=colnames(filt_counts_raw)) %>% 
  mutate(sample = timeset) %>% 
  mutate(timeset=gsub("Ind1_75","D_",timeset)) %>% 
  mutate(timeset=gsub("Ind2_87","A_",timeset)) %>% 
  mutate(timeset=gsub("Ind3_77","B_",timeset)) %>% 
  mutate(timeset=gsub("Ind6_71","C_",timeset)) %>% 
  mutate(timeset = gsub("24h","_24h",timeset), 
       timeset = gsub("3h","_3h",timeset)) %>%
  separate(timeset, into = c("indv","trt","time"), sep= "_") %>% 
  mutate(trt= case_match(trt, 'DX' ~'DOX', 'E'~'EPI', 'DA'~'DNR', 'M'~'MTX', 'T'~'TRZ', 'V'~'VEH',.default = trt)) %>% 
  mutate(time = factor(time, levels = c("3h", "24h"), labels= c("3 hours","24 hours"))) %>% 
  mutate(trt = factor(trt, levels = c("DOX","EPI", "DNR", "MTX", "TRZ", "VEH"))) 


pca_final_four <- calc_pca(t(filt4_matrix_lcpm))
pca_final_four_anno <- data.frame(annotation_mat, pca_final_four$x)


pca_final_four_anno %>%
  ggplot(.,aes(x = PC1, y = PC2, col=trt, shape=time, group=indv))+
  geom_point(size= 5)+
  scale_color_manual(values=drug_pal)+
   ggrepel::geom_text_repel(aes(label = indv))+
   ggtitle(expression("PCA of log"[2]*"(cpm) of open chromatin regions"))+
  theme_bw()+
  guides(col="none", size =4)+
  labs(y = "PC 2 (13.5%)", x ="PC 1 (22.3%)")+
  theme(plot.title=element_text(size= 14,hjust = 0.5),
        axis.title = element_text(size = 12, color = "black"))

Version Author Date
7db849f E. Renee Matthews 2025-02-21

Figure 1.C: Cormotif plot without the decorations

## Fit limma model using code as it is found in the original cormotif code. It has
## only been modified to add names to the matrix of t values, as well as the
## limma fits

limmafit.default <- function(exprs,groupid,compid) {
  limmafits  <- list()
  compnum    <- nrow(compid)
  genenum    <- nrow(exprs)
  limmat     <- matrix(0,genenum,compnum)
  limmas2    <- rep(0,compnum)
  limmadf    <- rep(0,compnum)
  limmav0    <- rep(0,compnum)
  limmag1num <- rep(0,compnum)
  limmag2num <- rep(0,compnum)

  rownames(limmat)  <- rownames(exprs)
  colnames(limmat)  <- rownames(compid)
  names(limmas2)    <- rownames(compid)
  names(limmadf)    <- rownames(compid)
  names(limmav0)    <- rownames(compid)
  names(limmag1num) <- rownames(compid)
  names(limmag2num) <- rownames(compid)

  for(i in 1:compnum) {
    selid1 <- which(groupid == compid[i,1])
    selid2 <- which(groupid == compid[i,2])
    eset   <- new("ExpressionSet", exprs=cbind(exprs[,selid1],exprs[,selid2]))
    g1num  <- length(selid1)
    g2num  <- length(selid2)
    designmat <- cbind(base=rep(1,(g1num+g2num)), delta=c(rep(0,g1num),rep(1,g2num)))
    fit <- lmFit(eset,designmat)
    fit <- eBayes(fit)
    limmat[,i] <- fit$t[,2]
    limmas2[i] <- fit$s2.prior
    limmadf[i] <- fit$df.prior
    limmav0[i] <- fit$var.prior[2]
    limmag1num[i] <- g1num
    limmag2num[i] <- g2num
    limmafits[[i]] <- fit

    # log odds
    # w<-sqrt(1+fit$var.prior[2]/(1/g1num+1/g2num))
    # log(0.99)+dt(fit$t[1,2],g1num+g2num-2+fit$df.prior,log=TRUE)-log(0.01)-dt(fit$t[1,2]/w, g1num+g2num-2+fit$df.prior, log=TRUE)+log(w)
  }
  names(limmafits) <- rownames(compid)
  limmacompnum<-nrow(compid)
  result<-list(t       = limmat,
               v0      = limmav0,
               df0     = limmadf,
               s20     = limmas2,
               g1num   = limmag1num,
               g2num   = limmag2num,
               compnum = limmacompnum,
               fits    = limmafits)
}

limmafit.counts <-
  function (exprs, groupid, compid, norm.factor.method = "TMM", voom.normalize.method = "none")
  {
    limmafits  <- list()
    compnum    <- nrow(compid)
    genenum    <- nrow(exprs)
    limmat     <- matrix(NA,genenum,compnum)
    limmas2    <- rep(0,compnum)
    limmadf    <- rep(0,compnum)
    limmav0    <- rep(0,compnum)
    limmag1num <- rep(0,compnum)
    limmag2num <- rep(0,compnum)

    rownames(limmat)  <- rownames(exprs)
    colnames(limmat)  <- rownames(compid)
    names(limmas2)    <- rownames(compid)
    names(limmadf)    <- rownames(compid)
    names(limmav0)    <- rownames(compid)
    names(limmag1num) <- rownames(compid)
    names(limmag2num) <- rownames(compid)

    for (i in 1:compnum) {
      message(paste("Running limma for comparision",i,"/",compnum))
      selid1 <- which(groupid == compid[i, 1])
      selid2 <- which(groupid == compid[i, 2])
      # make a new count data frame
      counts <- cbind(exprs[, selid1], exprs[, selid2])

      # remove NAs
      not.nas <- which(apply(counts, 1, function(x) !any(is.na(x))) == TRUE)

      # runn voom/limma
      d <- DGEList(counts[not.nas,])
      d <- calcNormFactors(d, method = norm.factor.method)
      g1num <- length(selid1)
      g2num <- length(selid2)
      designmat <- cbind(base = rep(1, (g1num + g2num)), delta = c(rep(0,
                                                                       g1num), rep(1, g2num)))

      y <- voom(d, designmat, normalize.method = voom.normalize.method)
      fit <- lmFit(y, designmat)
      fit <- eBayes(fit)

      limmafits[[i]] <- fit
      limmat[not.nas, i] <- fit$t[, 2]
      limmas2[i] <- fit$s2.prior
      limmadf[i] <- fit$df.prior
      limmav0[i] <- fit$var.prior[2]
      limmag1num[i] <- g1num
      limmag2num[i] <- g2num
    }
    limmacompnum <- nrow(compid)
    names(limmafits) <- rownames(compid)
    result <- list(t       = limmat,
                   v0      = limmav0,
                   df0     = limmadf,
                   s20     = limmas2,
                   g1num   = limmag1num,
                   g2num   = limmag2num,
                   compnum = limmacompnum,
                   fits    = limmafits)
  }

limmafit.list <-
  function (fitlist, cmp.idx=2)
  {
    compnum    <- length(fitlist)

    genes <- c()
    for (i in 1:compnum) genes <- unique(c(genes, rownames(fitlist[[i]])))

    genenum    <- length(genes)
    limmat     <- matrix(NA,genenum,compnum)
    limmas2    <- rep(0,compnum)
    limmadf    <- rep(0,compnum)
    limmav0    <- rep(0,compnum)
    limmag1num <- rep(0,compnum)
    limmag2num <- rep(0,compnum)

    rownames(limmat)  <- genes
    colnames(limmat)  <- names(fitlist)
    names(limmas2)    <- names(fitlist)
    names(limmadf)    <- names(fitlist)
    names(limmav0)    <- names(fitlist)
    names(limmag1num) <- names(fitlist)
    names(limmag2num) <- names(fitlist)

    for (i in 1:compnum) {
      this.t <- fitlist[[i]]$t[,cmp.idx]
      limmat[names(this.t),i] <- this.t

      limmas2[i]    <- fitlist[[i]]$s2.prior
      limmadf[i]    <- fitlist[[i]]$df.prior
      limmav0[i]    <- fitlist[[i]]$var.prior[cmp.idx]
      limmag1num[i] <- sum(fitlist[[i]]$design[,cmp.idx]==0)
      limmag2num[i] <- sum(fitlist[[i]]$design[,cmp.idx]==1)
    }

    limmacompnum <- compnum
    result <- list(t       = limmat,
                   v0      = limmav0,
                   df0     = limmadf,
                   s20     = limmas2,
                   g1num   = limmag1num,
                   g2num   = limmag2num,
                   compnum = limmacompnum,
                   fits    = limmafits)

  }

## Rank genes based on statistics
generank<-function(x) {
  xcol<-ncol(x)
  xrow<-nrow(x)
  result<-matrix(0,xrow,xcol)
  z<-(1:1:xrow)
  for(i in 1:xcol) {
    y<-sort(x[,i],decreasing=TRUE,na.last=TRUE)
    result[,i]<-match(x[,i],y)
    result[,i]<-order(result[,i])
  }
  result
}

## Log-likelihood for moderated t under H0
modt.f0.loglike<-function(x,df) {
  a<-dt(x, df, log=TRUE)
  result<-as.vector(a)
  flag<-which(is.na(result)==TRUE)
  result[flag]<-0
  result
}

## Log-likelihood for moderated t under H1
## param=c(df,g1num,g2num,v0)
modt.f1.loglike<-function(x,param) {
  df<-param[1]
  g1num<-param[2]
  g2num<-param[3]
  v0<-param[4]
  w<-sqrt(1+v0/(1/g1num+1/g2num))
  dt(x/w, df, log=TRUE)-log(w)
  a<-dt(x/w, df, log=TRUE)-log(w)
  result<-as.vector(a)
  flag<-which(is.na(result)==TRUE)
  result[flag]<-0
  result
}

## Correlation Motif Fit
cmfit.X<-function(x, type, K=1, tol=1e-3, max.iter=100) {
  ## initialize
  xrow <- nrow(x)
  xcol <- ncol(x)
  loglike0 <- list()
  loglike1 <- list()
  p <- rep(1, K)/K
  q <- matrix(runif(K * xcol), K, xcol)
  q[1, ] <- rep(0.01, xcol)
  for (i in 1:xcol) {
    f0 <- type[[i]][[1]]
    f0param <- type[[i]][[2]]
    f1 <- type[[i]][[3]]
    f1param <- type[[i]][[4]]
    loglike0[[i]] <- f0(x[, i], f0param)
    loglike1[[i]] <- f1(x[, i], f1param)
  }
  condlike <- list()
  for (i in 1:xcol) {
    condlike[[i]] <- matrix(0, xrow, K)
  }
  loglike.old <- -1e+10
  for (i.iter in 1:max.iter) {
    if ((i.iter%%50) == 0) {
      print(paste("We have run the first ", i.iter, " iterations for K=",
                  K, sep = ""))
    }
    err <- tol + 1
    clustlike <- matrix(0, xrow, K)
    #templike <- matrix(0, xrow, 2)
    templike1 <- rep(0, xrow)
    templike2 <- rep(0, xrow)
    for (j in 1:K) {
      for (i in 1:xcol) {
        templike1 <- log(q[j, i]) + loglike1[[i]]
        templike2 <- log(1 - q[j, i]) + loglike0[[i]]
        tempmax <- Rfast::Pmax(templike1, templike2)

        templike1 <- exp(templike1 - tempmax)
        templike2 <- exp(templike2 - tempmax)

        tempsum <- templike1 + templike2
        clustlike[, j] <- clustlike[, j] + tempmax +
          log(tempsum)
        condlike[[i]][, j] <- templike1/tempsum
      }
      clustlike[, j] <- clustlike[, j] + log(p[j])
    }
    #tempmax <- apply(clustlike, 1, max)
    tempmax <- Rfast::rowMaxs(clustlike, value=TRUE)
    for (j in 1:K) {
      clustlike[, j] <- exp(clustlike[, j] - tempmax)
    }
    #tempsum <- apply(clustlike, 1, sum)
    tempsum <- Rfast::rowsums(clustlike)
    for (j in 1:K) {
      clustlike[, j] <- clustlike[, j]/tempsum
    }
    #p.new <- (apply(clustlike, 2, sum) + 1)/(xrow + K)
    p.new <- (Rfast::colsums(clustlike) + 1)/(xrow + K)
    q.new <- matrix(0, K, xcol)
    for (j in 1:K) {
      clustpsum <- sum(clustlike[, j])
      for (i in 1:xcol) {
        q.new[j, i] <- (sum(clustlike[, j] * condlike[[i]][,
                                                           j]) + 1)/(clustpsum + 2)
      }
    }
    err.p <- max(abs(p.new - p)/p)
    err.q <- max(abs(q.new - q)/q)
    err <- max(err.p, err.q)
    loglike.new <- (sum(tempmax + log(tempsum)) + sum(log(p.new)) +
                      sum(log(q.new) + log(1 - q.new)))/xrow
    p <- p.new
    q <- q.new
    loglike.old <- loglike.new
    if (err < tol) {
      break
    }
  }
  clustlike <- matrix(0, xrow, K)
  for (j in 1:K) {
    for (i in 1:xcol) {
      templike1 <- log(q[j, i]) + loglike1[[i]]
      templike2 <- log(1 - q[j, i]) + loglike0[[i]]
      tempmax <- Rfast::Pmax(templike1, templike2)

      templike1 <- exp(templike1 - tempmax)
      templike2 <- exp(templike2 - tempmax)

      tempsum <- templike1 + templike2
      clustlike[, j] <- clustlike[, j] + tempmax + log(tempsum)
      condlike[[i]][, j] <- templike1/tempsum
    }
    clustlike[, j] <- clustlike[, j] + log(p[j])
  }
  #tempmax <- apply(clustlike, 1, max)
  tempmax <- Rfast::rowMaxs(clustlike, value=TRUE)
  for (j in 1:K) {
    clustlike[, j] <- exp(clustlike[, j] - tempmax)
  }
  #tempsum <- apply(clustlike, 1, sum)
  tempsum <- Rfast::rowsums(clustlike)
  for (j in 1:K) {
    clustlike[, j] <- clustlike[, j]/tempsum
  }
  p.post <- matrix(0, xrow, xcol)
  for (j in 1:K) {
    for (i in 1:xcol) {
      p.post[, i] <- p.post[, i] + clustlike[, j] * condlike[[i]][,
                                                                  j]
    }
  }
  loglike.old <- loglike.old - (sum(log(p)) + sum(log(q) +
                                                    log(1 - q)))/xrow
  loglike.old <- loglike.old * xrow
  result <- list(p.post = p.post, motif.prior = p, motif.q = q,
                 loglike = loglike.old, clustlike=clustlike, condlike=condlike)
}

## Fit using (0,0,...,0) and (1,1,...,1)
cmfitall<-function(x, type, tol=1e-3, max.iter=100) {
  ## initialize
  xrow<-nrow(x)
  xcol<-ncol(x)
  loglike0<-list()
  loglike1<-list()
  p<-0.01

  ## compute loglikelihood
  L0<-matrix(0,xrow,1)
  L1<-matrix(0,xrow,1)
  for(i in 1:xcol) {
    f0<-type[[i]][[1]]
    f0param<-type[[i]][[2]]
    f1<-type[[i]][[3]]
    f1param<-type[[i]][[4]]
    loglike0[[i]]<-f0(x[,i],f0param)
    loglike1[[i]]<-f1(x[,i],f1param)
    L0<-L0+loglike0[[i]]
    L1<-L1+loglike1[[i]]
  }


  ## EM algorithm to get MLE of p and q
  loglike.old <- -1e10
  for(i.iter in 1:max.iter) {
    if((i.iter%%50) == 0) {
      print(paste("We have run the first ", i.iter, " iterations",sep=""))
    }
    err<-tol+1

    ## compute posterior cluster membership
    clustlike<-matrix(0,xrow,2)
    clustlike[,1]<-log(1-p)+L0
    clustlike[,2]<-log(p)+L1

    tempmax<-apply(clustlike,1,max)
    for(j in 1:2) {
      clustlike[,j]<-exp(clustlike[,j]-tempmax)
    }
    tempsum<-apply(clustlike,1,sum)

    ## update motif occurrence rate
    for(j in 1:2) {
      clustlike[,j]<-clustlike[,j]/tempsum
    }

    p.new<-(sum(clustlike[,2])+1)/(xrow+2)

    ## evaluate convergence
    err<-abs(p.new-p)/p

    ## evaluate whether the log.likelihood increases
    loglike.new<-(sum(tempmax+log(tempsum))+log(p.new)+log(1-p.new))/xrow

    loglike.old<-loglike.new
    p<-p.new

    if(err<tol) {
      break;
    }
  }

  ## compute posterior p
  clustlike<-matrix(0,xrow,2)
  clustlike[,1]<-log(1-p)+L0
  clustlike[,2]<-log(p)+L1

  tempmax<-apply(clustlike,1,max)
  for(j in 1:2) {
    clustlike[,j]<-exp(clustlike[,j]-tempmax)
  }
  tempsum<-apply(clustlike,1,sum)

  for(j in 1:2) {
    clustlike[,j]<-clustlike[,j]/tempsum
  }

  p.post<-matrix(0,xrow,xcol)
  for(i in 1:xcol) {
    p.post[,i]<-clustlike[,2]
  }

  ## return

  #calculate back loglikelihood
  loglike.old<-loglike.old-(log(p)+log(1-p))/xrow
  loglike.old<-loglike.old*xrow
  result<-list(p.post=p.post, motif.prior=p, loglike=loglike.old)
}

## Fit each dataset separately
cmfitsep<-function(x, type, tol=1e-3, max.iter=100) {
  ## initialize
  xrow<-nrow(x)
  xcol<-ncol(x)
  loglike0<-list()
  loglike1<-list()
  p<-0.01*rep(1,xcol)
  loglike.final<-rep(0,xcol)

  ## compute loglikelihood
  for(i in 1:xcol) {
    f0<-type[[i]][[1]]
    f0param<-type[[i]][[2]]
    f1<-type[[i]][[3]]
    f1param<-type[[i]][[4]]
    loglike0[[i]]<-f0(x[,i],f0param)
    loglike1[[i]]<-f1(x[,i],f1param)
  }

  p.post<-matrix(0,xrow,xcol)

  ## EM algorithm to get MLE of p
  for(coli in 1:xcol) {
    loglike.old <- -1e10
    for(i.iter in 1:max.iter) {
      if((i.iter%%50) == 0) {
        print(paste("We have run the first ", i.iter, " iterations",sep=""))
      }
      err<-tol+1

      ## compute posterior cluster membership
      clustlike<-matrix(0,xrow,2)
      clustlike[,1]<-log(1-p[coli])+loglike0[[coli]]
      clustlike[,2]<-log(p[coli])+loglike1[[coli]]

      tempmax<-apply(clustlike,1,max)
      for(j in 1:2) {
        clustlike[,j]<-exp(clustlike[,j]-tempmax)
      }
      tempsum<-apply(clustlike,1,sum)

      ## evaluate whether the log.likelihood increases
      loglike.new<-sum(tempmax+log(tempsum))/xrow

      ## update motif occurrence rate
      for(j in 1:2) {
        clustlike[,j]<-clustlike[,j]/tempsum
      }

      p.new<-(sum(clustlike[,2]))/(xrow)

      ## evaluate convergence
      err<-abs(p.new-p[coli])/p[coli]
      loglike.old<-loglike.new
      p[coli]<-p.new

      if(err<tol) {
        break;
      }
    }

    ## compute posterior p
    clustlike<-matrix(0,xrow,2)
    clustlike[,1]<-log(1-p[coli])+loglike0[[coli]]
    clustlike[,2]<-log(p[coli])+loglike1[[coli]]

    tempmax<-apply(clustlike,1,max)
    for(j in 1:2) {
      clustlike[,j]<-exp(clustlike[,j]-tempmax)
    }
    tempsum<-apply(clustlike,1,sum)

    for(j in 1:2) {
      clustlike[,j]<-clustlike[,j]/tempsum
    }

    p.post[,coli]<-clustlike[,2]
    loglike.final[coli]<-loglike.old
  }


  ## return
  loglike.final<-loglike.final*xrow
  result<-list(p.post=p.post, motif.prior=p, loglike=loglike.final)
}

## Fit the full model
cmfitfull<-function(x, type, tol=1e-3, max.iter=100) {
  ## initialize
  xrow<-nrow(x)
  xcol<-ncol(x)
  loglike0<-list()
  loglike1<-list()
  K<-2^xcol
  p<-rep(1,K)/K
  pattern<-rep(0,xcol)
  patid<-matrix(0,K,xcol)

  ## compute loglikelihood
  for(i in 1:xcol) {
    f0<-type[[i]][[1]]
    f0param<-type[[i]][[2]]
    f1<-type[[i]][[3]]
    f1param<-type[[i]][[4]]
    loglike0[[i]]<-f0(x[,i],f0param)
    loglike1[[i]]<-f1(x[,i],f1param)
  }
  L<-matrix(0,xrow,K)
  for(i in 1:K)
  {
    patid[i,]<-pattern
    for(j in 1:xcol) {
      if(pattern[j] < 0.5) {
        L[,i]<-L[,i]+loglike0[[j]]
      } else {
        L[,i]<-L[,i]+loglike1[[j]]
      }
    }

    if(i < K) {
      pattern[xcol]<-pattern[xcol]+1
      j<-xcol
      while(pattern[j] > 1) {
        pattern[j]<-0
        j<-j-1
        pattern[j]<-pattern[j]+1
      }
    }
  }

  ## EM algorithm to get MLE of p and q
  loglike.old <- -1e10
  for(i.iter in 1:max.iter) {
    if((i.iter%%50) == 0) {
      print(paste("We have run the first ", i.iter, " iterations",sep=""))
    }
    err<-tol+1

    ## compute posterior cluster membership
    clustlike<-matrix(0,xrow,K)
    for(j in 1:K) {
      clustlike[,j]<-log(p[j])+L[,j]
    }

    tempmax<-apply(clustlike,1,max)
    for(j in 1:K) {
      clustlike[,j]<-exp(clustlike[,j]-tempmax)
    }
    tempsum<-apply(clustlike,1,sum)

    ## update motif occurrence rate
    for(j in 1:K) {
      clustlike[,j]<-clustlike[,j]/tempsum
    }

    p.new<-(apply(clustlike,2,sum)+1)/(xrow+K)

    ## evaluate convergence
    err<-max(abs(p.new-p)/p)

    ## evaluate whether the log.likelihood increases
    loglike.new<-(sum(tempmax+log(tempsum))+sum(log(p.new)))/xrow

    loglike.old<-loglike.new
    p<-p.new

    if(err<tol) {
      break;
    }
  }

  ## compute posterior p
  clustlike<-matrix(0,xrow,K)
  for(j in 1:K) {
    clustlike[,j]<-log(p[j])+L[,j]
  }

  tempmax<-apply(clustlike,1,max)
  for(j in 1:K) {
    clustlike[,j]<-exp(clustlike[,j]-tempmax)
  }
  tempsum<-apply(clustlike,1,sum)

  for(j in 1:K) {
    clustlike[,j]<-clustlike[,j]/tempsum
  }

  p.post<-matrix(0,xrow,xcol)
  for(j in 1:K) {
    for(i in 1:xcol) {
      if(patid[j,i] > 0.5) {
        p.post[,i]<-p.post[,i]+clustlike[,j]
      }
    }
  }

  ## return
  #calculate back loglikelihood
  loglike.old<-loglike.old-sum(log(p))/xrow
  loglike.old<-loglike.old*xrow
  result<-list(p.post=p.post, motif.prior=p, loglike=loglike.old)
}

generatetype<-function(limfitted)
{
  jtype<-list()
  df<-limfitted$g1num+limfitted$g2num-2+limfitted$df0
  for(j in 1:limfitted$compnum)
  {
    jtype[[j]]<-list(f0=modt.f0.loglike, f0.param=df[j], f1=modt.f1.loglike, f1.param=c(df[j],limfitted$g1num[j],limfitted$g2num[j],limfitted$v0[j]))
  }
  jtype
}

cormotiffit <- function(exprs, groupid=NULL, compid=NULL, K=1, tol=1e-3,
                        max.iter=100, BIC=TRUE, norm.factor.method="TMM",
                        voom.normalize.method = "none", runtype=c("logCPM","counts","limmafits"), each=3)
{
  # first I want to do some typechecking. Input can be either a normalized
  # matrix, a count matrix, or a list of limma fits. Dispatch the correct
  # limmafit accordingly.
  # todo: add some typechecking here
  limfitted <- list()
  if (runtype=="counts") {
    limfitted <- limmafit.counts(exprs,groupid,compid, norm.factor.method, voom.normalize.method)
  } else if (runtype=="logCPM") {
    limfitted <- limmafit.default(exprs,groupid,compid)
  } else if (runtype=="limmafits") {
    limfitted <- limmafit.list(exprs)
  } else {
    stop("runtype must be one of 'logCPM', 'counts', or 'limmafits'")
  }


  jtype<-generatetype(limfitted)
  fitresult<-list()
  ks <- rep(K, each = each)
  fitresult <- bplapply(1:length(ks), function(i, x, type, ks, tol, max.iter) {
    cmfit.X(x, type, K = ks[i], tol = tol, max.iter = max.iter)
  }, x=limfitted$t, type=jtype, ks=ks, tol=tol, max.iter=max.iter)

  best.fitresults <- list()
  for (i in 1:length(K)) {
    w.k <- which(ks==K[i])
    this.bic <- c()
    for (j in w.k) this.bic[j] <- -2 * fitresult[[j]]$loglike + (K[i] - 1 + K[i] * limfitted$compnum) * log(dim(limfitted$t)[1])
    w.min <- which(this.bic == min(this.bic, na.rm = TRUE))[1]
    best.fitresults[[i]] <- fitresult[[w.min]]
  }
  fitresult <- best.fitresults

  bic <- rep(0, length(K))
  aic <- rep(0, length(K))
  loglike <- rep(0, length(K))
  for (i in 1:length(K)) loglike[i] <- fitresult[[i]]$loglike
  for (i in 1:length(K)) bic[i] <- -2 * fitresult[[i]]$loglike + (K[i] - 1 + K[i] * limfitted$compnum) * log(dim(limfitted$t)[1])
  for (i in 1:length(K)) aic[i] <- -2 * fitresult[[i]]$loglike + 2 * (K[i] - 1 + K[i] * limfitted$compnum)
  if(BIC==TRUE) {
    bestflag=which(bic==min(bic))
  }
  else {
    bestflag=which(aic==min(aic))
  }
  result<-list(bestmotif=fitresult[[bestflag]],bic=cbind(K,bic),
               aic=cbind(K,aic),loglike=cbind(K,loglike), allmotifs=fitresult)

}

cormotiffitall<-function(exprs,groupid,compid, tol=1e-3, max.iter=100)
{
  limfitted<-limmafit(exprs,groupid,compid)
  jtype<-generatetype(limfitted)
  fitresult<-cmfitall(limfitted$t,type=jtype,tol=1e-3,max.iter=max.iter)
}

cormotiffitsep<-function(exprs,groupid,compid, tol=1e-3, max.iter=100)
{
  limfitted<-limmafit(exprs,groupid,compid)
  jtype<-generatetype(limfitted)
  fitresult<-cmfitsep(limfitted$t,type=jtype,tol=1e-3,max.iter=max.iter)
}

cormotiffitfull<-function(exprs,groupid,compid, tol=1e-3, max.iter=100)
{
  limfitted<-limmafit(exprs,groupid,compid)
  jtype<-generatetype(limfitted)
  fitresult<-cmfitfull(limfitted$t,type=jtype,tol=1e-3,max.iter=max.iter)
}

plotIC<-function(fitted_cormotif)
{
  oldpar<-par(mfrow=c(1,2))
  plot(fitted_cormotif$bic[,1], fitted_cormotif$bic[,2], type="b",xlab="Motif Number", ylab="BIC", main="BIC")
  plot(fitted_cormotif$aic[,1], fitted_cormotif$aic[,2], type="b",xlab="Motif Number", ylab="AIC", main="AIC")
}

plotMotif<-function(fitted_cormotif,title="")
{
  layout(matrix(1:2,ncol=2))
  u<-1:dim(fitted_cormotif$bestmotif$motif.q)[2]
  v<-1:dim(fitted_cormotif$bestmotif$motif.q)[1]
  image(u,v,t(fitted_cormotif$bestmotif$motif.q),
        col=gray(seq(from=1,to=0,by=-0.1)),xlab="Study",yaxt = "n",
        ylab="Corr. Motifs",main=paste(title,"pattern",sep=" "))
  axis(2,at=1:length(v))
  for(i in 1:(length(u)+1))
  {
    abline(v=(i-0.5))
  }
  for(i in 1:(length(v)+1))
  {
    abline(h=(i-0.5))
  }
  Ng=10000
  if(is.null(fitted_cormotif$bestmotif$p.post)!=TRUE)
    Ng=nrow(fitted_cormotif$bestmotif$p.post)
  genecount=floor(fitted_cormotif$bestmotif$motif.p*Ng)
  NK=nrow(fitted_cormotif$bestmotif$motif.q)
  plot(0,0.7,pch=".",xlim=c(0,1.2),ylim=c(0.75,NK+0.25),
       frame.plot=FALSE,axes=FALSE,xlab="No. of genes",ylab="", main=paste(title,"frequency",sep=" "))
  segments(0,0.7,fitted_cormotif$bestmotif$motif.p[1],0.7)
  rect(0,1:NK-0.3,fitted_cormotif$bestmotif$motif.p,1:NK+0.3,
       col="dark grey")
  mtext(1:NK,at=1:NK,side=2,cex=0.8)
  text(fitted_cormotif$bestmotif$motif.p+0.15,1:NK,
       labels=floor(fitted_cormotif$bestmotif$motif.p*Ng))
}
group <- c( rep(c(1,2,3,4,5,6,7,8,9,10,11,12),4))
group <- factor(group, levels =c("1","2","3","4","5","6","7","8","9","10","11","12"))


group_fac_ff <- group
groupid_ff <- as.numeric(group_fac_ff)

compid_ff <- data.frame(c1= c(2,4,6,8,10,1,3,5,7,9), c2 = c( 12,12,12,12,12,11,11,11,11,11))

y_TMM_cpm_ff <- cpm(filt_counts_raw, log = TRUE)

colnames(y_TMM_cpm_ff) <- colnames(filt_counts_raw)

set.seed(31415)
cormotif_initial_ff <- cormotiffit(exprs = y_TMM_cpm_ff, groupid = groupid_ff, compid = compid_ff, K=1:8, max.iter = 500, runtype = "logCPM")

# saveRDS(cormotif_initial_ff,"data/Final_four_data/cormotif_ff_4_run.RDS")
cormotif_initial_ff <-  readRDS("data/Final_four_data/cormotif_ff_4_run.RDS")
motif_prob_ff <- cormotif_initial_ff$bestmotif$clustlike
rownames(motif_prob_ff) <- rownames(filt4_matrix_lcpm)
plotMotif(cormotif_initial_ff)

Version Author Date
7db849f E. Renee Matthews 2025-02-21
myColors <-  rev(c("#FFFFFF", "#E6E6E6" ,"#CCCCCC", "#B3B3B3", "#999999", "#808080", "#666666","#4C4C4C", "#333333", "#191919","#000000"))

plot.new()
legend('center',fill=myColors, legend =rev(c("0", "0.1", "0.2", "0.3", "0.4",  "0.5", "0.6", "0.7", "0.8","0.9", "1")), box.col="white",title = "Probability\nlegend", horiz=FALSE,title.cex=.8)

Version Author Date
7db849f E. Renee Matthews 2025-02-21

Code for making response clusters

motif_prob_ff <- readRDS("data/Final_four_data/motif_prob_ff.RDS")


NR_ff <- motif_prob_ff %>%
  as.data.frame() %>% 
  dplyr::filter(V1>.5 & V2<.5 & V3 <.5& V4<0.5) %>% 
  rownames_to_column("Peakid") %>% 
  dplyr::select(Peakid) %>% 
  separate(Peakid, into=c("chr","start","end"),remove = FALSE)
 
LR_ff <- motif_prob_ff %>%
   as.data.frame() %>% 
  dplyr::filter(V1<.5 & V2>.5 & V3 <.5& V4<0.5) %>% 
  rownames_to_column("Peakid") %>% 
  dplyr::select(Peakid) %>% 
  separate(Peakid, into=c("chr","start","end"),remove = FALSE)
 
 
ESR_ff <- motif_prob_ff %>%
  as.data.frame() %>% 
  dplyr::filter(V1<.5 & V2<.5 & V3 >.5& V4<0.5) %>% 
  rownames_to_column("Peakid") %>% 
  dplyr::select(Peakid) %>% 
  separate(Peakid, into=c("chr","start","end"),remove = FALSE)
 
EAR_ff <- motif_prob_ff %>%
  as.data.frame() %>% 
  dplyr::filter(V1<.5 & V2<.5 & V3 <.5& V4>0.5) %>% 
  rownames_to_column("Peakid") %>% 
  dplyr::select(Peakid) %>% 
  separate(Peakid, into=c("chr","start","end"),remove = FALSE)

Code for making median dataframes and the division of Response clusters

### making median lfc (toplist_ff is a dataframe that contains all the DAR columns from the edgeR-limma-voom pipeline. There are 1,866,720 rows which are all 155,560 open chromatin regions and log2FC with respect to the Vehicle for each time and treatment(12 time-treatment combinations))

median_df <- toplist_ff %>% 
  pivot_wider(., id_cols=c(time,peak), names_from = trt, values_from = logFC) %>% 
  rowwise() %>% 
  mutate(median_lfc= median(c_across(DNR:TRZ)))

median_3_lfc <-   median_df %>%
    dplyr::filter(time == "3 hours") %>% 
  ungroup() %>% 
  dplyr::select(time, peak,median_lfc) %>% 
  dplyr::rename("med_3h_lfc"=median_lfc)
  

median_24_lfc <- median_df %>%
    dplyr::filter(time == "24 hours") %>% 
  ungroup() %>% 
  dplyr::select(time, peak,median_lfc) %>% 
  dplyr::rename("med_24h_lfc"=median_lfc)
median_24_lfc <- read_csv("data/Final_four_data/median_24_lfc.csv") 
median_3_lfc <- read_csv("data/Final_four_data/median_3_lfc.csv")
open_3med <- median_3_lfc %>% 
  dplyr::filter(med_3h_lfc > 0)

close_3med <- median_3_lfc %>% 
  dplyr::filter(med_3h_lfc < 0)

open_24med <- median_24_lfc %>% 
  dplyr::filter(med_24h_lfc > 0)

close_24med <- median_24_lfc %>% 
  dplyr::filter(med_24h_lfc < 0)
####four different clusters for ESR
medA <- median_3_lfc %>% 
  left_join(median_24_lfc, by=c("peak"="peak")) %>% 
  dplyr::filter(med_3h_lfc > 0 & med_24h_lfc>0)

medB <- median_3_lfc %>% 
  left_join(median_24_lfc, by=c("peak"="peak")) %>% 
  dplyr::filter(med_3h_lfc < 0 & med_24h_lfc < 0)
 
medC <- median_3_lfc %>% 
  left_join(median_24_lfc, by=c("peak"="peak")) %>% 
  dplyr::filter(med_3h_lfc > 0& med_24h_lfc <0)
  

medD <- median_3_lfc %>% 
 left_join(median_24_lfc, by=c("peak"="peak"))%>% 
  dplyr::filter(med_3h_lfc < 0 & med_24h_lfc > 0)
 


EAR_open <- EAR_ff %>%
  dplyr::filter(Peakid %in% open_3med$peak)

EAR_close <- EAR_ff %>%
  dplyr::filter(Peakid %in% close_3med$peak) 

LR_open <- LR_ff %>%
  dplyr::filter(Peakid %in% open_24med$peak) 

LR_close <- LR_ff %>%
  dplyr::filter(Peakid %in% close_24med$peak) 

NR_gr <- NR_ff %>% 
   GRanges()

ESR_open <- ESR_ff %>% 
  dplyr::filter(Peakid %in% medA$peak)  
 
ESR_close <- ESR_ff %>% 
  dplyr::filter(Peakid %in% medB$peak)  

ESR_opcl <- ESR_ff %>% 
  dplyr::filter(Peakid %in% medC$peak) 

ESR_clop <- ESR_ff %>% 
  dplyr::filter(Peakid %in% medD$peak) 

Nine_group_list <- list("EAR_open"=EAR_open,"EAR_close"=EAR_close, "LR_open"=LR_open, "LR_close"=LR_close,"ESR_open"=ESR_open,"ESR_close"=ESR_close,"ESR_opcl"=ESR_opcl,"ESR_clop"=ESR_clop, "NR"=NR_ff)
# saveRDS(Nine_group_list,"data/Final_four_data/Nine_group_list.RDS")

Figure 1.D: mean Log FC across response clusters

toplist_ff <- readRDS("data/Final_four_data/toplist_ff.RDS")

  
### loading
mean_lfc <-   toplist_ff %>%
  mutate(EAR_open = if_else(peak %in% EAR_open$Peakid, "y", "no")) %>%
  mutate(EAR_close = if_else(peak %in% EAR_close$Peakid, "y", "no")) %>%
  mutate(ESR_open = if_else(peak %in% ESR_open$Peakid, "y", "no")) %>%
  mutate(ESR_close= if_else(peak %in% ESR_close$Peakid, "y", "no")) %>%
  mutate(ESR_opcl= if_else(peak %in% ESR_opcl$Peakid, "y", "no")) %>%
  mutate(ESR_clop= if_else(peak %in% ESR_clop$Peakid, "y", "no")) %>%
    mutate(LR_open= if_else(peak %in% LR_open$Peakid, "y", "no")) %>%
    mutate(LR_close= if_else(peak %in% LR_close$Peakid, "y", "no")) %>%
    mutate(NR = if_else(peak %in% NR_ff$Peakid, "y", "no"))%>%
  mutate(trt = factor(trt,levels=c("DOX","EPI","DNR","MTX","TRZ","VEH"))) %>%
  group_by(trt, time) %>%
  mutate(absFC = (logFC)) %>%
  dplyr::select(trt, time, absFC, EAR_open:NR) %>%
  dplyr::summarize(
    EAR_op = mean(absFC[EAR_open == "y"]),
    EAR_cl = mean(absFC[EAR_close == "y"]),
    ESR_op = mean(absFC[ESR_open == "y"]),
    ESR_cl = mean(absFC[ESR_close == "y"]),
    ESR_opcl = mean(absFC[ESR_opcl == "y"]),
    ESR_clop = mean(absFC[ESR_clop == "y"]),
    LR_op = mean(absFC[LR_open == "y"]),
    LR_cl = mean(absFC[LR_close == "y"]),
    NR = mean(absFC[NR == "y"])
  ) %>%
  as.data.frame()


mean_lfc %>%
  ungroup() %>%
  pivot_longer(!c(trt, time), names_to = "Motif",
               values_to = "meanLFC") %>%
   ggplot(., aes(x = time,y = meanLFC,col = trt,
    group = trt
  )) +
  geom_point(size = 2) +
  geom_line(linewidth = 2) +
  ggpubr::fill_palette(drug_pal) +
  # guides(fill=guide_legend(title = "Treatment"))+
  facet_wrap( ~ Motif, nrow = 2) +
  theme_bw() +
  xlab("Time (hours)") +
  scale_color_manual(values = drug_pal) +
  ylab(" Avg. Log Fold Change") +
  theme_bw() +
  # ggtitle(" average |Log Fold| for genes across treatment each motif")+
  theme(
    plot.title = element_text(size = rel(1.0), hjust = 0.5),
    axis.title = element_text(size = 15, color = "black"),
    axis.line = element_line(linewidth = 1.0),
    strip.background = element_rect(fill = "transparent"),
    axis.text = element_text(
      size = 10,
      color = "black",
      angle = 0
    ),
    strip.text.x = element_text(
      size = 11,
      color = "black",
      face = "bold"
    )
  )

Version Author Date
7db849f E. Renee Matthews 2025-02-21

Figure 1.E: genomebrowser of ESR loci (see image above)


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

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] grid      stats4    stats     graphics  grDevices utils     datasets 
[8] methods   base     

other attached packages:
 [1] readxl_1.4.5                            
 [2] smplot2_0.2.5                           
 [3] cowplot_1.1.3                           
 [4] ComplexHeatmap_2.22.0                   
 [5] ggrepel_0.9.6                           
 [6] plyranges_1.26.0                        
 [7] ggsignif_0.6.4                          
 [8] genomation_1.38.0                       
 [9] edgeR_4.4.2                             
[10] limma_3.62.2                            
[11] ggpubr_0.6.0                            
[12] BiocParallel_1.40.0                     
[13] ggVennDiagram_1.5.2                     
[14] scales_1.3.0                            
[15] VennDiagram_1.7.3                       
[16] futile.logger_1.4.3                     
[17] gridExtra_2.3                           
[18] ggfortify_0.4.17                        
[19] rtracklayer_1.66.0                      
[20] org.Hs.eg.db_3.20.0                     
[21] TxDb.Hsapiens.UCSC.hg38.knownGene_3.20.0
[22] GenomicFeatures_1.58.0                  
[23] AnnotationDbi_1.68.0                    
[24] Biobase_2.66.0                          
[25] GenomicRanges_1.58.0                    
[26] GenomeInfoDb_1.42.3                     
[27] IRanges_2.40.1                          
[28] S4Vectors_0.44.0                        
[29] BiocGenerics_0.52.0                     
[30] RColorBrewer_1.1-3                      
[31] broom_1.0.7                             
[32] kableExtra_1.4.0                        
[33] lubridate_1.9.4                         
[34] forcats_1.0.0                           
[35] stringr_1.5.1                           
[36] dplyr_1.1.4                             
[37] purrr_1.0.4                             
[38] readr_2.1.5                             
[39] tidyr_1.3.1                             
[40] tibble_3.2.1                            
[41] ggplot2_3.5.1                           
[42] tidyverse_2.0.0                         
[43] workflowr_1.7.1                         

loaded via a namespace (and not attached):
  [1] later_1.4.1                 BiocIO_1.16.0              
  [3] bitops_1.0-9                cellranger_1.1.0           
  [5] rpart_4.1.24                XML_3.99-0.18              
  [7] lifecycle_1.0.4             rstatix_0.7.2              
  [9] doParallel_1.0.17           rprojroot_2.0.4            
 [11] vroom_1.6.5                 processx_3.8.6             
 [13] lattice_0.22-6              backports_1.5.0            
 [15] magrittr_2.0.3              Hmisc_5.2-2                
 [17] sass_0.4.9                  rmarkdown_2.29             
 [19] jquerylib_0.1.4             yaml_2.3.10                
 [21] plotrix_3.8-4               httpuv_1.6.15              
 [23] DBI_1.2.3                   abind_1.4-8                
 [25] zlibbioc_1.52.0             RCurl_1.98-1.16            
 [27] nnet_7.3-20                 git2r_0.35.0               
 [29] circlize_0.4.16             GenomeInfoDbData_1.2.13    
 [31] svglite_2.1.3               codetools_0.2-20           
 [33] DelayedArray_0.32.0         xml2_1.3.7                 
 [35] tidyselect_1.2.1            shape_1.4.6.1              
 [37] farver_2.1.2                UCSC.utils_1.2.0           
 [39] base64enc_0.1-3             matrixStats_1.5.0          
 [41] GenomicAlignments_1.42.0    jsonlite_1.9.1             
 [43] GetoptLong_1.0.5            Formula_1.2-5              
 [45] iterators_1.0.14            systemfonts_1.2.1          
 [47] foreach_1.5.2               tools_4.4.2                
 [49] Rcpp_1.0.14                 glue_1.8.0                 
 [51] SparseArray_1.6.2           xfun_0.51                  
 [53] MatrixGenerics_1.18.1       withr_3.0.2                
 [55] formatR_1.14                fastmap_1.2.0              
 [57] callr_3.7.6                 digest_0.6.37              
 [59] timechange_0.3.0            R6_2.6.1                   
 [61] seqPattern_1.38.0           colorspace_2.1-1           
 [63] RSQLite_2.3.9               generics_0.1.3             
 [65] data.table_1.17.0           htmlwidgets_1.6.4          
 [67] httr_1.4.7                  S4Arrays_1.6.0             
 [69] whisker_0.4.1               pkgconfig_2.0.3            
 [71] gtable_0.3.6                blob_1.2.4                 
 [73] impute_1.80.0               XVector_0.46.0             
 [75] htmltools_0.5.8.1           carData_3.0-5              
 [77] pwr_1.3-0                   clue_0.3-66                
 [79] png_0.1-8                   knitr_1.49                 
 [81] lambda.r_1.2.4              rstudioapi_0.17.1          
 [83] tzdb_0.4.0                  reshape2_1.4.4             
 [85] rjson_0.2.23                checkmate_2.3.2            
 [87] curl_6.2.1                  zoo_1.8-13                 
 [89] cachem_1.1.0                GlobalOptions_0.1.2        
 [91] KernSmooth_2.23-26          parallel_4.4.2             
 [93] foreign_0.8-88              restfulr_0.0.15            
 [95] pillar_1.10.1               vctrs_0.6.5                
 [97] promises_1.3.2              car_3.1-3                  
 [99] cluster_2.1.8.1             htmlTable_2.4.3            
[101] evaluate_1.0.3              cli_3.6.4                  
[103] locfit_1.5-9.12             compiler_4.4.2             
[105] futile.options_1.0.1        Rsamtools_2.22.0           
[107] rlang_1.1.5                 crayon_1.5.3               
[109] labeling_0.4.3              ps_1.9.0                   
[111] getPass_0.2-4               plyr_1.8.9                 
[113] fs_1.6.5                    stringi_1.8.4              
[115] viridisLite_0.4.2           gridBase_0.4-7             
[117] munsell_0.5.1               Biostrings_2.74.1          
[119] Matrix_1.7-3                BSgenome_1.74.0            
[121] patchwork_1.3.0             hms_1.1.3                  
[123] bit64_4.6.0-1               KEGGREST_1.46.0            
[125] statmod_1.5.0               SummarizedExperiment_1.36.0
[127] memoise_2.0.1               bslib_0.9.0                
[129] bit_4.6.0