domain_enrichment.R 8.73 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#!/usr/bin/env Rscript
#+ echo=FALSE, error=F


suppressMessages(require(docopt))

## todo use textual input here for ease of use
doc <- '
Perform an domain enrichment analysis for a set of genes
Usage: domain_enrichment.R.R [options] <gene_lists_tsv> <group_col>

Options:
--project <project_prefix>   Name to prefix all generated result files [default: ]
--qcutoff <qcutoff>             Use a q-value cutoff of 0.01 instead of a q-value cutoff [default: 0.01]
'

opts <- docopt(doc, commandArgs(TRUE)) ## does not work when spining


20 21
devtools::source_url("https://git.mpi-cbg.de/bioinfo/datautils/raw/v1.45/R/core_commons.R")
devtools::source_url("https://git.mpi-cbg.de/bioinfo/datautils/raw/v1.45/R/ggplot_commons.R")
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
devtools::source_url("https://git.mpi-cbg.de/bioinfo/ngs_tools/raw/v6/common/cp_utils.R")
# source(interp_from_env("${NGS_TOOLS}/common/cp_utils.R"))

## also load diffex helpers for guess_mart
# source(interp_from_env("${NGS_TOOLS}/dge_workflow/diffex_commons.R"))
devtools::source_url("https://git.mpi-cbg.de/bioinfo/ngs_tools/raw/v6/dge_workflow/diffex_commons.R")

load_pack(knitr)
load_pack(DT)

## load the data
geneLists <- read_tsv(opts$gene_lists_tsv)
group_col = opts$group_col
geneLists %<>% group_by_(.dots = group_col)


# resultsBaseName <- if (str_length(opts$project) > 0) paste0(opts$project, ".") else basename(opts$gene_lists_tsv) %>% trim_ext("txt") #%>% paste0(".")
resultsBaseName <- if (str_length(opts$project) > 0) paste0(opts$project, ".") else ""
#resultsBaseName=basename(opts$gene_lists_tsv) %>% trim_ext("txt") #%>% paste0(".")

q_cutoff <- as.numeric(opts$qcutoff)

########################################################################################################################
#' # Enrichment Analysis

#' Run configuration was
vec_as_df(unlist(opts)) %>%
    filter(! str_detect(name, "^[<-]")) %>%
    kable()

#' This analysis was performed using [clusterProfiler](http://bioconductor.org/packages/release/bioc/html/clusterProfiler.html). The following ontologies were tested: Kegg, Go, Reactome, Dose,

listLabels <- geneLists %>%
    select(- ensembl_gene_id) %>%
    distinct
listLabels %<>% transform(list_label = do.call(paste, c(listLabels, sep = "__")))

geneLists %>%
    inner_join(listLabels) %>%
    ggplot(aes(list_label)) +
    geom_bar() +
    coord_flip() +
    ggtitle("gene list sizes to be tested for term enrichment") +
    ylab("")


68
#' ## Load domains from intrpro
69

70
mart_db = guess_mart(geneLists)
71

72 73 74 75 76 77 78
domains = quote({
    ## mart = biomaRt::useDataset("drerio_gene_ensembl", mart = biomaRt::useMart("ensembl"))??
    #  mart = biomaRt::useDataset(guess_mart(countData$ensembl_gene_id), mart = biomaRt::useMart("ensembl"))
    ## todo fix this https://support.bioconductor.org/p/74322/
    # mart = biomaRt::useDataset(guess_mart(countData$ensembl_gene_id), mart = biomaRt::useMart("ENSEMBL_MART_ENSEMBL", host="www.ensembl.org"))
    # mart = biomaRt::useMart("ENSEMBL_MART_ENSEMBL", dataset = "mmusculus_gene_ensembl", host = "dec2016.archive.ensembl.org", path = "/biomart/martservice", archive = FALSE)
    mart = biomaRt::useMart("ENSEMBL_MART_ENSEMBL", dataset = mart_db, host = "aug2017.archive.ensembl.org", path = "/biomart/martservice", archive = FALSE)
79

80 81 82
    c("ensembl_gene_id" , "interpro" , "interpro_short_description" , "interpro_description" ) %>%
        biomaRt::getBM(mart = mart) %>% tbl_df
}) %>% cache_it("geneInfo")
83 84


85 86
domainsT2G = select(domains, interpro, ensembl_gene_id)
domainsT2N = transmute(domains, interpro, paste0(interpro_short_description, ": ", interpro_description)) %>% distinct_all()
87 88


89 90
domain_enr_test = function(geneIds, q_cutoff=0.05){
    # DEBUG geneIds = geneLists %>% group_by(contrast) %>% first_group() %$% ensembl_gene_id
91

92 93 94
    if(length(geneIds)>1500){
        geneIds <- sample(geneIds) %>% head(1500)
    }
95

96
    echo("testing", length(geneIds), " genes for enrichment")
97

98
    domainResults = clusterProfiler::enricher(gene = geneIds, qvalueCutoff = q_cutoff, TERM2GENE = domainsT2G, TERM2NAME = domainsT2N) %>% as.data.frame()
99 100


101 102 103 104 105
    enrResults <- bind_rows(
    mutate(domainResults, ontology="interpro"),
    )
    enrResults
}
106

107 108
enrResults <- quote(geneLists %>% do(domain_enr_test(.$ensembl_gene_id, q_cutoff = q_cutoff))) %>%
    cache_it(paste0("enrdata_", digest(geneLists)))
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232


# add information on GO levels:

write_tsv(enrResults, path = paste0(resultsBaseName, "enrResults.txt"))
# enrResults <- read_tsv(paste0(resultsBaseName, "enrResults.txt"))
#'  [Enrichment Results](`r paste0(resultsBaseName, "enrResults.txt")`)

load_pack(DT)
datatable(enrResults)

#enrResults %>% ggplot(aes(pvalue)) + geom_histogram() + scale_x_log10()
#enrResults %>% ggplot(aes(ontology)) + facet_wrap(~cluster) + geom_bar() + rot_x_lab()
#facetSpecs <- paste("~", groups(geneLists) %>% ac %>% paste(collapse=" + "))
facetSpecs <- paste("~", group_col %>% ac %>% paste(collapse = " + "))

#' Visualize term-pvalues per list

#http://stackoverflow.com/questions/11028353/passing-string-variable-facet-wrap-in-ggplot-using-r
enrResults %>% ggplot(aes(ontology)) +
    facet_wrap(as.formula(facetSpecs), ncol = 3) +
    geom_bar() +
    rot_x_lab() +
    ggtitle("enriched term counts by cluster")

enrResults %<>% mutate(num_term_genes = str_split_fixed(BgRatio, fixed("/"), 2)[, 1] %>% as.numeric)

#' Keep at max 100 terms for visualzation per group
erPlotData <- enrResults %>%
    group_by_(.dots = c(group_col)) %>%
    arrange(qvalue) %>%
    slice(1 : 20) %>%
## regroup because otherwise dplyr complains about corrupt df (which looks like a bug)
    group_by_(.dots = c(group_col))


#' Gene Ratio:
#+ error=TRUE, echo=FALSE
warning("dropping levels")
erPlotData %<>% mutate(ontology = ac(ontology)) ## drop unsused level to get consistent color palette

erPlotData %<>% rename(Term = Description)


term_category_colors <- create_palette(unique(ac(erPlotData$ontology)))

figDir <- "enr_charts"
dir.create(figDir)


## chop and pad category names
erPlotData %<>% mutate(fixed_width_term = str_sub(Term, 1, 70) %>% str_pad(70))

## evaluate gene ratios strings into actual proportions
erPlotData %<>% mutate(gene_ratio = map_dbl(GeneRatio, ~ eval(parse(text = .x))))

term_barplot_files = erPlotData %>% do({
    # DEBUG enrResultsGrp <- erPlotData %>% first_group()
    enrResultsGrp <- .

    label = subset(enrResultsGrp, select = group_col)[1, 1] %>%
        as.matrix %>%
        ac

    ## old version
    # enrPlot <- enrResultsGrp %>%
    # ## fix factor order
    # #        mutate(Term=reorder(Term, -qvalue) %>% reorder(as.integer(as.factor(ontology)))) %>%
    #     mutate(fixed_width_term = reorder(fixed_width_term, - qvalue)) %>%
    #     ggplot(aes(fixed_width_term, num_term_genes, fill = - log10(qvalue), color = ontology)) +
    #     geom_bar(stat = "identity") +
    #     scale_color_manual(values = term_category_colors, drop = F, name = "Ontology") +
    #     coord_flip() +
    #     xlab("Enriched Terms") +
    #     ggtitle(label) +
    #     scale_y_log10()

    # print(enrPlot)

    ## new version using dotplot https://bioconductor.org/packages/devel/bioc/vignettes/clusterProfiler/inst/doc/clusterProfiler.html#dotplot
    enrPlot = enrResultsGrp %>% ungroup %>%
    ## fix factor order
        mutate(fixed_width_term = reorder(fixed_width_term, gene_ratio)) %>%
        ggplot(aes(fixed_width_term, gene_ratio, size=Count, fill = qvalue, color = ontology)) +
        # ggplot(aes(fixed_width_term, Count)) +
            geom_point(pch=21) +
            scale_color_manual(values = term_category_colors, drop = F, name = "Ontology") +
            scale_fill_gradient(low="red", high="white", name = "q-value", limits = c(min(erPlotData$qvalue), max(erPlotData$qvalue))) +
            coord_flip() +
            # xlab("Enriched Terms") +
            ggtitle(label)
            # scale_y_log10()

    ## todo  use builtin method to create filesystem-compatible name
    label <- gsub('[^a-zA-Z0-9.!=><&|]', '_', label)
    fileNameLabel <- label %>%
        str_replace_all("!=", "ne") %>%
        str_replace_all(">", "gt") %>%
        str_replace_all("<", "lt") %>%
        str_replace_all(fixed("&"), "AND") %>%
        str_replace_all(fixed("|"), "OR") %>%
        str_replace_all(fixed("/"), "_") %>%
        str_replace_all(" ", "_")

    #        ggsave(paste0("enrichmed_terms__", fileNameLabel, ".pdf"))
    #        print(enrPlot)

    stopifnot(str_length(fileNameLabel) > 0)
    tmpPng <- paste0(figDir, "/enrterms__", fileNameLabel, ".png")
    ggsave(tmpPng, enrPlot, width = 10, height = 2 + round(nrow(enrResultsGrp) / 5), limitsize = FALSE)
    data.frame(file = tmpPng)
})

#+ results="asis"
walk(term_barplot_files$file, function(pngFile){ cat(paste0("<img src='", pngFile, "'><br>"))})

# install.packages("session")
session::save.session(".cp_enrichment.dat");
# session::restore.session(".cp_enrichment.dat");

#' System info:
#+

devtools::session_info()