Last updated: 2021-01-22

Checks: 7 0

Knit directory: scATACseq-topics/

This reproducible R Markdown analysis was created with workflowr (version 1.6.2). 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(20200729) 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 8a44752. 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/

Untracked files:
    Untracked:  analysis/diff_count_Buenrostro2018_chomVAR_scPeaks.Rmd
    Untracked:  analysis/process_data_Buenrostro2018_Chen2019.Rmd
    Untracked:  analysis/single_cell_rnaseq_demo.Rmd
    Untracked:  output/Cusanovich2018/
    Untracked:  output/clustering-Cusanovich2018.rds
    Untracked:  output/gsea_topic_1_Cusanovich2018-k=13-TSS-sum.html
    Untracked:  output/gsea_topic_1_Cusanovich2018-k=13-TSS-sum.png
    Untracked:  output/gsea_topic_1_Cusanovich2018-k=13-TSS-sum_files/
    Untracked:  output/gsea_topic_1_Cusanovich2018-k=13-genebody-sum.html
    Untracked:  output/gsea_topic_1_Cusanovich2018-k=13-genebody-sum.png
    Untracked:  output/gsea_topic_1_Cusanovich2018-k=13-genebody-sum_files/
    Untracked:  output/plotly/
    Untracked:  output/volcano_topic_1_Cusanovich2018-k=13-TSS-sum.html
    Untracked:  output/volcano_topic_1_Cusanovich2018-k=13-TSS-sum.png
    Untracked:  output/volcano_topic_1_Cusanovich2018-k=13-TSS-sum_files/
    Untracked:  output/volcano_topic_1_Cusanovich2018-k=13-genebody-sum.html
    Untracked:  output/volcano_topic_1_Cusanovich2018-k=13-genebody-sum.png
    Untracked:  output/volcano_topic_1_Cusanovich2018-k=13-genebody-sum_files/
    Untracked:  scripts/fit_all_models_Buenrostro_2018_chromVar_scPeaks_filtered.sbatch

Unstaged changes:
    Modified:   analysis/cisTopic_Buenrostro2018_chomVAR_scPeaks.Rmd
    Modified:   analysis/motif_gene_analysis_Cusanovich2018.Rmd
    Modified:   analysis/plots_Lareau2019_bonemarrow.Rmd
    Modified:   scripts/fit_all_models_Buenrostro_2018.sbatch
    Modified:   scripts/fit_cisTopic_Buenrostro_2018_chromVAR_scPeaks.sh
    Modified:   scripts/postfit_Buenrostro2018.sh

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/gene_analysis_Cusanovich2018.Rmd) and HTML (docs/gene_analysis_Cusanovich2018.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 8a44752 kevinlkx 2021-01-22 minor update on highlighting the gene sets of GSEA results
html ca6ea6f kevinlkx 2021-01-22 Build site.
Rmd 8f3685f kevinlkx 2021-01-22 update figure directory and links to plotly html files

Here we perform gene analysis for the Cusanovich et al (2018) scATAC-seq result inferred from the multinomial topic model with \(k = 13\).

Load packages and some functions used in this analysis

library(Matrix)
library(fastTopics)
library(dplyr)
library(tidyr)
library(ggplot2)
library(ggrepel)
library(cowplot)
library(plotly)
library(htmlwidgets)
library(DT)
library(reshape)
source("code/plots.R")

Load data and topic model results

Load the data and the \(k = 13\) Poisson NMF fit results.

data.dir <- "/project2/mstephens/kevinluo/scATACseq-topics/data/Cusanovich_2018/processed_data"
load(file.path(data.dir, "Cusanovich_2018.RData"))
rm(counts)
fit.dir <- "/project2/mstephens/kevinluo/scATACseq-topics/output/Cusanovich_2018"
fit <- readRDS(file.path(fit.dir, "/fit-Cusanovich2018-scd-ex-k=13.rds"))$fit
fit_multinom <- poisson2multinom(fit)

Visualize by Structure plot grouped by tissues

set.seed(10)
colors_topics <- c("#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c",
                   "#fdbf6f","#ff7f00","#cab2d6","#6a3d9a","#ffff99","#b15928",
                   "gray")
rows <- sample(nrow(fit$L),4000)
samples$tissue <- as.factor(samples$tissue)

p.structure <- structure_plot(select(fit_multinom,loadings = rows),
                              grouping = samples[rows, "tissue"],n = Inf,gap = 40,
                              perplexity = 50,topics = 1:13,colors = colors_topics,
                              num_threads = 4,verbose = FALSE)

print(p.structure)

Version Author Date
ca6ea6f kevinlkx 2021-01-22

Gene score analysis

Set output directorry

out.dir <- "/project2/mstephens/kevinluo/scATACseq-topics/output/Cusanovich_2018"

fig.dir <- "output/plotly/Cusanovich2018"
dir.create(fig.dir, showWarnings = F, recursive = T)

TSS model

Gene scores were computed using TSS based method as in Lareau et al Nature Biotech, 2019 as well as the model 21 in archR paper. This model weights chromatin accessibility around gene promoters by using bi-directional exponential decays from the TSS,

  • Top genes
gene.dir <- paste0(out.dir, "/geneanalysis-Cusanovich2018-k=13-TSS-sum")
cat(sprintf("Directory of gene analysis result: %s \n", gene.dir))
genescore_res_tss <- readRDS(file.path(gene.dir, "genescore_result_topics.rds"))
genescore_res <- genescore_res_tss

genes <- genescore_res$genes
gene_mean_acc <- genescore_res$colmeans
gene_scores <- genescore_res$Z
gene_logFC <- genescore_res$beta

topics <- colnames(gene_scores)
top_genes <- data.frame(matrix(nrow=10, ncol = ncol(gene_scores)))
colnames(top_genes) <- topics

for (k in topics){
  top_genes[,k] <- genes$SYMBOL[head(order(abs(gene_scores[,k]), decreasing=TRUE), 10)]
}

DT::datatable(data.frame(rank = 1:10, top_genes), rownames = F, caption = "Top 10 genes by abs(gene z-scores)")
# Directory of gene analysis result: /project2/mstephens/kevinluo/scATACseq-topics/output/Cusanovich_2018/geneanalysis-Cusanovich2018-k=13-TSS-sum
  • Volcano plots

Topic 1

k <- 1
genescore_volcano_plot(genescore_res, k, label_above_quantile = 0.99,
                       labels = genescore_res$genes$SYMBOL, max.overlaps = 20,
                       subsample_below_quantile = 0.5, subsample_rate = 0.1)

Version Author Date
ca6ea6f kevinlkx 2021-01-22

Explore the volcano plot interactively

for ( k in 1:ncol(genescore_res$beta) ){
  p.volcano.plotly <- genescore_volcano_plotly(genescore_res,k,
                                             file = sprintf("%s/volcano_topic_%s_%s.html", fig.dir, k, "tss-sum"),
                                             labels = genescore_res$genes$SYMBOL)
}

Gene body model

Gene scores were computed using the gene score model (model 42) in the archR paper with some modifications. This model uses bi-directional exponential decays from the gene TSS (extended upstream by 5 kb by default) and the gene transcription termination site (TTS). Note: the current version of the function does not account for neighboring gene boundaries.

  • Top genes
gene.dir <- paste0(out.dir, "/geneanalysis-Cusanovich2018-k=13-genebody-sum")
cat(sprintf("Directory of gene analysis result: %s \n", gene.dir))
genescore_res_gb <- readRDS(file.path(gene.dir, "genescore_result_topics.rds"))
genescore_res <- genescore_res_gb

genes <- genescore_res$genes
gene_mean_acc <- genescore_res$colmeans
gene_scores <- genescore_res$Z
gene_logFC <- genescore_res$beta

topics <- colnames(gene_scores)
top_genes <- data.frame(matrix(nrow=10, ncol = ncol(gene_scores)))
colnames(top_genes) <- topics

for (k in topics){
  top_genes[,k] <- genes$SYMBOL[head(order(abs(gene_scores[,k]), decreasing=TRUE), 10)]
}

DT::datatable(data.frame(rank = 1:10, top_genes), rownames = F, caption = "Top 10 genes by abs(gene z-scores)")
# Directory of gene analysis result: /project2/mstephens/kevinluo/scATACseq-topics/output/Cusanovich_2018/geneanalysis-Cusanovich2018-k=13-genebody-sum
  • Volcano plots

Topic 1

k <- 1
genescore_volcano_plot(genescore_res, k, label_above_quantile = 0.99,
                       labels = genescore_res$genes$SYMBOL, max.overlaps = 20,
                       subsample_below_quantile = 0.5, subsample_rate = 0.1)

Version Author Date
ca6ea6f kevinlkx 2021-01-22

Explore the volcano plot interactively

for ( k in 1:ncol(genescore_res$beta) ){
  p.volcano.plotly <- genescore_volcano_plotly(genescore_res,k,
                                             file = sprintf("%s/volcano_topic_%s_%s.html", fig.dir, k, "genebody-sum"),
                                             labels = genescore_res$genes$SYMBOL)
}

Compare gene scores from the gene-body model vs. the TSS model.

m     <- ncol(genescore_res_gb$Z)
plots <- vector("list",m)
names(plots) <- colnames(genescore_res_gb$Z)
for (i in 1:m) {
  dat <- data.frame(genebody = genescore_res_gb$Z[,i], tss = genescore_res_tss$Z[,i])
  plots[[i]] <- 
    ggplot(dat,aes_string(x = "genebody",y = "tss")) +
    geom_point(shape = 21, na.rm = TRUE, size = 1, alpha = 1/10) +
    geom_abline(intercept = 0, slope = 1, color="blue") + 
    labs(x = "gene body model",y = "TSS model", 
         title = paste("topic",i)) +
    theme_cowplot(9)
}

do.call(plot_grid,plots)

Version Author Date
ca6ea6f kevinlkx 2021-01-22

Gene-set enrichment analysis (GSEA)

TSS model

Top gene sets/pathways

gene.dir <- paste0(out.dir, "/geneanalysis-Cusanovich2018-k=13-TSS-sum")
cat(sprintf("Directory of gene analysis result: %s \n", gene.dir))
load(file.path(gene.dir, "genescores_gsea.Rdata"))

top_pathways_up <- top_pathways_down <- data.frame(matrix(nrow=10, ncol = ncol(gsea_res$pval)))
colnames(top_pathways_up) <- colnames(top_pathways_down) <- colnames(gsea_res$pval)

for (k in 1:ncol(gsea_res$pval)){
  gsea_topic <- data.frame(pathway = rownames(gsea_res$pval),  
                           pval = gsea_res$pval[,k],
                           log2err = gsea_res$log2err[,k],
                           ES = gsea_res$ES[,k],
                           NES = gsea_res$NES[,k])
  gsea_up <- gsea_topic[gsea_topic$ES > 0,]
  top_IDs_up <- as.character(gsea_up[head(order(gsea_up$pval), 10), "pathway"])
  top_IDs_up <- gene_set_info[match(top_IDs_up, gene_set_info$id),c("name", "id")]
  top_pathways_up[,k] <- paste0(top_IDs_up$name, "(", top_IDs_up$id, ")")
  
  gsea_down <- gsea_topic[gsea_topic$ES < 0,]
  top_IDs_down <- as.character(gsea_down[head(order(gsea_down$pval), 10), "pathway"])
  top_IDs_down <- gene_set_info[match(top_IDs_down, gene_set_info$id),c("name", "id")]
  top_pathways_down[,k] <- paste0(top_IDs_down$name, "(", top_IDs_down$id, ")")
  
}

DT::datatable(data.frame(rank = 1:10, top_pathways_up), rownames = F,
              caption = "Top 10 pathways enriched at the top of the gene rank list.")
# Directory of gene analysis result: /project2/mstephens/kevinluo/scATACseq-topics/output/Cusanovich_2018/geneanalysis-Cusanovich2018-k=13-TSS-sum
  • Scatterplot of GSEA results Topic 1 (highlighting "Erythroblast" cells)
k   <- 1
name_interest <- "erythroblast"
label_geneset_ids <- gene_set_info[gsea_res$pval[,k] < 1e-6 & grepl(name_interest, gene_set_info$name, ignore.case = T), "id"]
cat(sprintf("highlighting %d %s gene sets \n", length(label_geneset_ids), name_interest))

create_genescore_gsea_plot(gene_set_info, gsea_res, k, label_geneset_ids, 
                                     title = sprintf("topic %d GSEA plot",k))

Version Author Date
ca6ea6f kevinlkx 2021-01-22
if(length(label_geneset_ids) > 0)
   DT::datatable(gene_set_info[gene_set_info$id %in% label_geneset_ids, 
                               c("name", "id", "database", "category_code", "description_brief")],  
                 rownames = F)
# highlighting 3 erythroblast gene sets

Explore the GSEA plot interactively

for ( k in 1:ncol(gsea_res$pval)){
  p.gsea.plotly <- create_genescore_gsea_plotly(gene_set_info, gsea_res, k)
  saveWidget(p.gsea.plotly,file = sprintf("%s/gsea_topic_%s_%s.html", fig.dir, k, "tss-sum"),
             selfcontained = TRUE,title = "GSEA")
}

Gene body model

  • Top gene sets
gene.dir <- paste0(out.dir, "/geneanalysis-Cusanovich2018-k=13-genebody-sum")
cat(sprintf("Directory of gene analysis result: %s \n", gene.dir))
load(file.path(gene.dir, "genescores_gsea.Rdata"))

top_pathways_up <- top_pathways_down <- data.frame(matrix(nrow=10, ncol = ncol(gsea_res$pval)))
colnames(top_pathways_up) <- colnames(top_pathways_down) <- colnames(gsea_res$pval)

for (k in 1:ncol(gsea_res$pval)){
  gsea_topic <- data.frame(pathway = rownames(gsea_res$pval),  
                           pval = gsea_res$pval[,k],
                           log2err = gsea_res$log2err[,k],
                           ES = gsea_res$ES[,k],
                           NES = gsea_res$NES[,k])
  gsea_up <- gsea_topic[gsea_topic$ES > 0,]
  top_IDs_up <- as.character(gsea_up[head(order(gsea_up$pval), 10), "pathway"])
  top_pathways_up[,k] <- gene_set_info[match(top_IDs_up, gene_set_info$id),c("name", "id")] %>% 
    unite("pathway", c("name", "id"), sep = ".", remove = TRUE)
  
  gsea_down <- gsea_topic[gsea_topic$ES < 0,]
  top_IDs_down <- as.character(gsea_down[head(order(gsea_down$pval), 10), "pathway"])
  top_pathways_down[,k] <- gene_set_info[match(top_IDs_down, gene_set_info$id),c("name", "id")] %>% 
    unite("pathway", c("name", "id"), sep = ".", remove = TRUE)
}

DT::datatable(data.frame(rank = 1:10, top_pathways_up), rownames = F,
              caption = "Top 10 pathways enriched at the top of the gene rank list.")
# Directory of gene analysis result: /project2/mstephens/kevinluo/scATACseq-topics/output/Cusanovich_2018/geneanalysis-Cusanovich2018-k=13-genebody-sum
  • Scatterplot of GSEA results Topic 1 (highlighting "Erythroblast" cells)
k   <- 1
name_interest <- "erythroblast"
label_geneset_ids <- gene_set_info[gsea_res$pval[,k] < 1e-6 & grepl(name_interest, gene_set_info$name, ignore.case = T), "id"]
cat(sprintf("highlighting %d %s gene sets \n", length(label_geneset_ids), name_interest))

create_genescore_gsea_plot(gene_set_info, gsea_res, k, label_geneset_ids, 
                                     title = sprintf("topic %d GSEA plot",k))

Version Author Date
ca6ea6f kevinlkx 2021-01-22
if(length(label_geneset_ids) > 0)
   DT::datatable(gene_set_info[gene_set_info$id %in% label_geneset_ids, 
                               c("name", "id", "database", "category_code", "description_brief")],  
                 rownames = F)
# highlighting 0 erythroblast gene sets

Explore the GSEA plot interactively

for ( k in 1:ncol(gsea_res$pval)){
  p.gsea.plotly <- create_genescore_gsea_plotly(gene_set_info, gsea_res, k)
saveWidget(p.gsea.plotly,file = sprintf("%s/gsea_topic_%s_%s.html", fig.dir, k, "genebody-sum"),
           selfcontained = TRUE,title = "GSEA")
}

sessionInfo()
# R version 3.6.1 (2019-07-05)
# Platform: x86_64-pc-linux-gnu (64-bit)
# Running under: Scientific Linux 7.4 (Nitrogen)
# 
# Matrix products: default
# BLAS/LAPACK: /software/openblas-0.2.19-el7-x86_64/lib/libopenblas_haswellp-r0.2.19.so
# 
# locale:
#  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
#  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
#  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
#  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
#  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
# [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       
# 
# attached base packages:
# [1] stats     graphics  grDevices utils     datasets  methods   base     
# 
# other attached packages:
#  [1] reshape_0.8.8     DT_0.16           htmlwidgets_1.5.3 plotly_4.9.2.1   
#  [5] cowplot_1.1.0     ggrepel_0.9.0     ggplot2_3.3.3     tidyr_1.1.2      
#  [9] dplyr_1.0.2       fastTopics_0.4-6  Matrix_1.2-18     workflowr_1.6.2  
# 
# loaded via a namespace (and not attached):
#  [1] Rcpp_1.0.6         lattice_0.20-41    prettyunits_1.1.1  rprojroot_2.0.2   
#  [5] digest_0.6.27      plyr_1.8.6         R6_2.5.0           MatrixModels_0.4-1
#  [9] evaluate_0.14      coda_0.19-4        httr_1.4.2         pillar_1.4.7      
# [13] rlang_0.4.10       progress_1.2.2     lazyeval_0.2.2     data.table_1.13.4 
# [17] irlba_2.3.3        SparseM_1.78       whisker_0.4        rmarkdown_2.6     
# [21] labeling_0.4.2     Rtsne_0.15         stringr_1.4.0      munsell_0.5.0     
# [25] compiler_3.6.1     httpuv_1.5.4       xfun_0.19          pkgconfig_2.0.3   
# [29] mcmc_0.9-7         htmltools_0.5.0    tidyselect_1.1.0   tibble_3.0.5      
# [33] quadprog_1.5-8     matrixStats_0.57.0 viridisLite_0.3.0  withr_2.4.0       
# [37] crayon_1.3.4       conquer_1.0.2      later_1.1.0.1      MASS_7.3-53       
# [41] grid_3.6.1         jsonlite_1.7.2     gtable_0.3.0       lifecycle_0.2.0   
# [45] git2r_0.27.1       magrittr_2.0.1     scales_1.1.1       RcppParallel_5.0.2
# [49] stringi_1.5.3      farver_2.0.3       fs_1.3.1           promises_1.1.1    
# [53] ellipsis_0.3.1     generics_0.1.0     vctrs_0.3.6        tools_3.6.1       
# [57] glue_1.4.2         purrr_0.3.4        crosstalk_1.1.0.1  hms_1.0.0         
# [61] yaml_2.2.1         colorspace_2.0-0   knitr_1.30         quantreg_5.75     
# [65] MCMCpack_1.4-9