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


suppressMessages(require(docopt))

## todo use textual input here for ease of use
doc <- '
Perform an enrichment analysis for a set of genes
Usage: plot_kegg_pathways.R <overlay_data_tsv> <pathways>...
'

opts <- docopt(doc, commandArgs(TRUE)) ## does not work when spining
# opts <- docopt(doc, "--overlay_expr_data ../plot_score_matrix.txt ../degs_by_contrast.txt contrast" )

Holger Brandl's avatar
Holger Brandl committed
16
if(!require(devtools)) install.packages("devtools")
17 18 19
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")
devtools::source_url("https://git.mpi-cbg.de/bioinfo/datautils/raw/v1.45/R/bio/diffex_commons.R")
20
devtools::source_url("https://git.mpi-cbg.de/bioinfo/ngs_tools/raw/v6/common/cp_utils.R")
21

22 23
load_pack(knitr)
load_pack(DT)
24 25


26
results_prefix = if(exists("reportName")) reportName else ""
27 28

## todo why is tidyr not processing an empty dataframe
Holger Brandl's avatar
Holger Brandl committed
29
keggPathways <- opts$pathways %>% str_split(",") %>% unlist()
30 31 32 33 34 35 36

##+ results='asis'
#if(!exists("keggPathways") | nrow(keggPathways)==0){
#    cat("No enriched pathways found")
#}

#+ echo=FALSE
37 38
load_pack(pathview)
load_pack(png)
39 40 41 42 43 44 45 46

# keggPathways <- keggPathways[1]

#if(nrow(keggPathways)==0){
#    echo("no enriched kegg pathways were found in the dataset")
#}else{

#keggOrCode <- "mmu"
47 48 49
overlayData <- read_tsv(opts$overlay_data_tsv)

keggOrCode <- guess_pathview_species(overlayData$ensembl_gene_id)
50 51

## prepare p-value data
52

53
sliceData <- overlayData  %>% as_df %>%
54 55 56 57 58 59 60 61 62
    #    dcast(ensembl_gene_id ~ comparison, value.var="plot_score") %>%
    column2rownames("ensembl_gene_id")

#sliceData <- sliceData[,1:5]

#sliceData %>% head %>% kable()

data.frame(set=names(sliceData)) %>% mutate(slice_index=row_number()) %>% kable()

63
pwPlotDir = add_prefix("pathways_pngs")
64 65 66 67

dir.create(pwPlotDir)

plot_pathway <- function(pathwayID, sliceData){
68
    #    pathwayID="hsa04080"; sliceData <- sliceData
69
    #    pathwayID="mmu04015"; sliceData <- sliceData
70
    #    pathwayID="hsa04145"; sliceData <- sliceData
71 72 73 74 75 76 77 78 79 80 81
    #    browser()
    #    echo("processing pathway", pathwayID)
    pv.out <- pathview(
    gene.data = sliceData,
    pathway.id = pathwayID,
    species = keggOrCode,
    #            out.suffix = pathwayID$kegg.description,
    #            out.suffix = pathwayID,
    multi.state = ncol(sliceData)>1,
    #            kegg.native=F,
    #            node.sum = "mean", # the method name to calculate node summary given that multiple genes or compounds are mapped to it
82
    node.sum = "max.abs", # the method name to calculate node summary given that multiple genes or compounds are mapped to it
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
    limit = list(gene = c(-4,4)),
    gene.idtype="ensembl"
    )

    if(is.numeric(pv.out) && pv.out==0) return(pathwayID) ## happens if pathview fails to parse xml e.g. for mmu01100

    outfile <- paste0(pathwayID, ".pathview", ifelse(ncol(sliceData)>1, ".multi", ""), ".png")

    ## move pathway plots into figures sub-directory
    figuresPlotFile <- file.path(pwPlotDir, outfile)
    system(paste("mv", outfile, figuresPlotFile))

    system(paste("rm", paste0(pathwayID, ".xml"), paste0(pathwayID, ".png")))

    ## interactive plotting
    #    ima <- readPNG(outfile)
    #    plot.new()
    #    lim <- par()
    #    rasterImage(ima, lim$usr[1], lim$usr[3], lim$usr[2], lim$usr[4])

    pv.out$plotfile=figuresPlotFile
    pv.out$pathway_id=pathwayID

    return(pv.out)
}

#keggPathways <- c("mmu04976", "mmu04972", "mmu04810", "mmu04520", "mmu04530", "mmu04270", "mmu04015")
#keggPathways <- c("mmu00830")


113 114 115
pathwayPlots <- keggPathways %>%
    # head(1) %>%
    map(function(pathwayID){
116
    # echo("processing pathway", pathwayID)
117 118 119 120 121 122 123 124 125 126
    plot_pathway(pathwayID, sliceData)
})


save(pathwayPlots, file=".pathwayPlots.RData")
# pathwayPlots <- local(get(load(".pathwayPlots.RData")))


## remove and report failed ones
failedPPs <- pathwayPlots[lapply(pathwayPlots, is.character) > 0]
127
echo("the following pathways failed to render:", paste(failedPPs, collapse = ", "))
128 129 130
pathwayPlots <- pathwayPlots[lapply(pathwayPlots, is.character) == 0]


131 132 133 134 135 136 137
# print names of pathways which could not be rendered
# pathwayPlots[!map_lgl(pathwayPlots, ~ file.exists(.$plotfile))] %>% map("pathway_id")
# purriefied solution: discard(pathwayPlots, ~ file.exists(.$plotfile)) %>% map("pathway_id")

# make sure that all files exist
stopifnot(map_lgl(pathwayPlots, ~ file.exists(.$plotfile)) %>% all)

138

139
install_package("biomaRt")
140 141 142 143 144

## prepare tooltips with expression scores
ens2entrez <- quote({
    #    mart <- biomaRt::useDataset(guess_mart(geneLists$ensembl_gene_id), mart = biomaRt::useMart("ensembl"))
    ## todo fix this https://support.bioconductor.org/p/74322/
145 146 147 148 149 150 151 152
    # mart <- biomaRt::useDataset(guess_mart(overlayData$ensembl_gene_id), mart = biomaRt::useMart("ENSEMBL_MART_ENSEMBL", host="www.ensembl.org"))
    mart = biomaRt::useMart("ENSEMBL_MART_ENSEMBL",
        dataset = guess_mart(overlayData$ensembl_gene_id),
        host = "aug2017.archive.ensembl.org",
        path = "/biomart/martservice",
        archive = FALSE
    )

153 154

    biomaRt::getBM(attributes=c('ensembl_gene_id', 'entrezgene', 'external_gene_name'), mart=mart) %>% filter(!is.na(entrezgene))
155
}) %>% cache_it("ens2entrez") %>% distinct_all(ensembl_gene_id)
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
#unlen(ens2entrez$ensembl_gene_id)

toolTipData <- overlayData %>% left_join(ens2entrez)

makeTooltip <- function(entrez_id){
    toolTipData %>% filter(entrezgene==entrez_id) %>% dplyr::select(-entrezgene) %>% gather() %$% paste(key, value, sep=": ") %>% paste(collapse="\n") #%>% cat
}
#entrez_id=14679
#entrez_id=34234234234234
#makeTooltip("14679")



#+ results="asis", echo=FALSE

## simple non-clickable plots
## http://stackoverflow.com/questions/12588323/r-how-to-extract-values-for-the-same-named-elements-across-multiple-objects-of
#unlist(lapply(pathwayPlots, "[[", "plotfile"))
# unlist(lapply(pathwayPlots, "[[", "plotfile")) %>% l_ply(function(pngFile){ cat(paste0("<img src='", pngFile, "'><br>"))})

#cat("
#<style type='text/css'>
# img {
#   max-width: 100%;
# }
#</style>
#")

## todo add tooltips with additinal info
## http://stackoverflow.com/questions/5478940/how-to-create-a-html-tooltip-on-top-of-image-map

## extended version with clickable links
createImgMap <- function(plotData){
    #browser()
    warning("compiling overlay toolips...")
    #pngFile="mmu04015.pathview.png"
    #plotData <- pathwayPlots[[1]]
    #plotData <- unlist(pathwayPlots)
    #    pathway_id=(basename(pngFile) %>% str_split_fixed("[.]", 2))[,1]
    pngFile <- plotData$plotfile
    stopifnot(file.exists(pngFile))
197
    pathway_id = plotData$pathway_id
198 199 200

    ## create link for image map
    keggNodes <- plotData$plot.data.gene %>%
201 202 203 204 205
    ## remove box offset
        mutate(x = x - 22, y = y - 8) %>% ## todo does not work for non-gene elements
        mutate(link = paste0("http://www.kegg.jp/dbget-bin/www_bget?", keggOrCode, ":", kegg.names)) %>%
        rowwise() %>%
        do({ curNode = .; mutate(as_df(curNode), tooltip = makeTooltip(as.integer(curNode$kegg.names)))})
206 207 208 209 210 211 212 213 214 215

    ## create tooltip by using mapping to


    #    "http://www.kegg.jp/dbget-bin/www_bget?mmu:16412

    ## first the image itself
    #    cat(paste0("<img usemap='#", pathway_id,"' src='", pngFile, "'><br>"))
    #    cat(paste0("<p><div style='width: 2000px'><img style='float: left' usemap='#", pathway_id,"' src='", pngFile, "'></div><br>"))
    ## it seems that formatting works better without the left alignment
216 217
    cat(paste0("<p><div style='width: 2000px'><img usemap='#", pathway_id, "' src='", pngFile, "'></div><br>"))
    cat(paste0("<map name='", pathway_id, "'>"))
218 219 220
    #keggNodes %>% rowwise() %>% {curNode=.; cat(curNode$name)}

    #see http://www.html-world.de/180/image-map/
221 222
    keggNodes %>% plyr::a_ply(1, function(curNode){
        rectDef = with(curNode, paste(x, y, x + width, y + height, sep = ","))
223
        #        paste0("<area href='", curNode$link, "' alt='Text' coords='", rectDef , "' shape='rect'>") %>% cat()
224
        paste0("<area href='", curNode$link, "' title='", curNode$tooltip, "' alt='Text' coords='", rectDef , "' shape='rect'>") %>% cat()
225 226 227 228
    })
    cat("</map></p><br>")
}

229
pathwayPlots %>% walk(createImgMap)
230 231 232

session::save.session(".plot_kegg_pathways.dat");
# session::restore.session(".plot_kegg_pathways.dat");