-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextractMWGeneSummary.R
341 lines (283 loc) · 17.1 KB
/
extractMWGeneSummary.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
#!/usr/bin/env Rscript
# THis script extracts the summary information pertaining to the gene input
# Call syntax: Rscript extractMWGeneSummary.R <species> <geneIDArr> <geneSymArr> <filename> <viewType>
# Input: species e.g. hsa, mmu
# geneIdArr : e.g. 3098, 6120 (ENTREZID of genes)
# geneStrArr : e.g. HK1, RPE
# filename: e.g. plot.png for the summary plot
# viewType : e.g. json, txt, png, bar, table, all (default is pie chart)
# Output: A table in json or txt format comprising of summary (Pathways, Reactions, Metabolites, Studies) information
# : A html table (if view type is table)
# : A bar plot (viewType is bar)
# : A pie chart, and table for all
################################################
# Restrictions due to the use of KEGG APIs (https://www.kegg.jp/kegg/legal.html, see also https://www.pathway.jp/en/academic.html)
# * Using this code to provide user's own web service
# The code we provide is free for non-commercial use (see LICENSE). While it is our understanding that no KEGG license is required to run the web app on user's local computer for personal use (e.g., access as localhost:install_location_withrespectto_DocumentRoot/MetGENE, or, restrict its access to the IP addresses belonging to their own research group), the users must understand the KEGG license terms (https://www.kegg.jp/kegg/legal.html, see also https://www.pathway.jp/en/academic.html) and decide for themselves. For example, if the user wishes to provide this tool (or their own tool based on a subset of MetGENE scripts with KEGG APIs) as a service (see LICENSE), they must obtain their own KEGG license with suitable rights.
# * Faster version of MetGENE
# If and only if the user has purchased license for KEGG FTP Data, they can activate a 'preCompute' mode to run faster version of MetGENE. To achieve this, please set preCompute = 1 in the file setPrecompute.R. Otherwise, please ensure that preCompute is set to 0 in the file setPrecompute.R. Further, to use the faster version, the user needs to run the R scripts in the 'data' folder first. Please see the respective R files in the 'data' folder for instructions to run them.
# Please see the files README.md and LICENSE for more details.
################################################
## Linux
library(KEGGREST);
library(rlang);
library(stringr);
library(data.table);
library(xtable);
library(jsonlite);
library(tictoc)
library(utils)
library(textutils)
library(tuple)
library(tidyr)
library(ggplot2)
library(reshape2)
library(ggrepel)
library(tidyverse)
source("setPrecompute.R")
list_of_list_to_df <- function(jslist) {
cols_needed = c("refmet_name", "kegg_id", "study", "study_title");
if (length(jslist) ==0) {
jsdf = NULL;
} else {
if (class(jslist[[1]])=="list") {
# loop over:
n= length(jslist);
for (i in 1:n) {
if (i == 1) {
jsdf = as.data.frame(t(as.data.frame(unlist(jslist[[i]]))));
jsdf = jsdf[,cols_needed];
} else {
jsdf_tmp = as.data.frame(t(as.data.frame(unlist(jslist[[i]]))));
jsdf_tmp = jsdf_tmp[,cols_needed];
jsdf = rbind(jsdf, jsdf_tmp);
}
}
rownames(jsdf) = as.character(c(1:n));
} else { # only one item
jsdf = as.data.frame(t(as.data.frame(unlist(jslist))));
jsdf = jsdf[,cols_needed];
rownames(jsdf) = "1";
}
}
return (jsdf);
}
printvar <- function(x,xpr=NA){
write(paste0(deparse(substitute(x)), ' = '), "");
if(!is.na(xpr)){
write(xpr, "");
}
print(x);
if(!is.na(xpr)){
write(xpr, "");
}
}
cleanFun <- function(htmlString) {
return(gsub("<.*?>", "", htmlString))
}
########################################################
plotSummary <- function(countMatrix, genesCnt, symbolStrArray, organism_name, pathwaysLinkStr, rxnsLinkStr, metsLinkStr, studiesLinkStr, plotFile, viewType) {
## create specified view type as an image
currDir = paste0("/",basename(getwd()));
if (nrow(countMatrix)==0) {
return(cat(paste0("<p> No summaries found in Metabolomics Workbench for the specified genes.</p>")));
}
categories <- c(rep("Pathways", genesCnt), rep("Reactions", genesCnt), rep("Metabolites", genesCnt), rep("Studies", genesCnt) );
Genes <- rep(as.vector(symbolStrArray),4);
values = as.vector(countMatrix);
data <- data.frame(categories,Genes,values);
titleStr = organism_name;;
if (genesCnt > 0) {
rplot = ggplot(data, aes(x = "", y = values, fill = Genes )) +
geom_bar(stat = "identity", position = position_fill()) +
geom_text(aes(label = values), position = position_fill(vjust = 0.5), size = 6) +
theme_void() +
theme(plot.title = element_text(color = "blue",size = 20, face = "bold")) +
theme(plot.title = element_text(hjust = 0.5)) +
theme(plot.title = element_text(vjust = 0.75)) +
theme(strip.text.x = element_text(size = 20)) +
labs(title=titleStr) +
facet_wrap(~ categories) +
theme(axis.title.x = element_blank(),
axis.title.y = element_blank()) +
theme(legend.position='bottom') +
theme(legend.text = element_text(size=20)) +
theme(legend.title=element_text(size=20)) +
guides(fill=guide_legend(ncol=4, byrow=TRUE));
tabDF = as.data.frame(countMatrix);
colnames(tabDF) = c(pathwaysLinkStr, rxnsLinkStr, metsLinkStr, studiesLinkStr);
rownames(tabDF) = symbolStrArray;
tabDF[] <- lapply(tabDF, function(x) {
as.integer(x)
});
nprint = nrow(tabDF);
vtFlag = tolower(viewType);
if (vtFlag == "all") {
rplot = rplot +
coord_polar(theta = "y");
ggplot2::ggsave(plotFile, plot=rplot, device="png");
cat(paste0("<table><tr><td><a href=\"", plotFile,"\" download>","<img src=",currDir,"/", plotFile, " height=300 width=320 alt = R Graph></a></td><td>"));
return(print(xtable(tabDF[1:nprint,]), type="html", include.rownames=TRUE, sanitize.text.function=function(x){x}, html.table.attributes="class='styled-table' id='Table1' "));
} else if (vtFlag == "bar") {
ggplot2::ggsave(plotFile, plot=rplot, device="png");
cat(paste0("<a href=\"", plotFile,"\" download>","<img src=",currDir,"/", plotFile, " height=300 width=320 alt = R Graph></a>"))
return(print(xtable(tabDF[1:nprint,]), type="html", include.rownames=TRUE, sanitize.text.function=function(x){x}, html.table.attributes="class='styled-table' style='display:none' id='Table1'"));
} else if (vtFlag == "json") {
colnames(tabDF) = cleanFun(colnames(tabDF));
tabDF$Genes = rownames(tabDF);
tabJson <- toJSON(x=tabDF, pretty=T);
return(cat(tabJson));
} else if (vtFlag == "txt") {
colnames(tabDF) = cleanFun(colnames(tabDF));
tabDF$Genes = rownames(tabDF);
return(cat(format_delim(tabDF,",")));
} else if(vtFlag == "png") {
rplot = rplot +
coord_polar(theta = "y");
ggplot2::ggsave(plotFile, plot=rplot, device="png");
return(cat(paste0("Image generated")));
} else if(vtFlag == "table") {
return(print(xtable(tabDF[1:nprint,]), type="html", include.rownames=TRUE, sanitize.text.function=function(x){x}, html.table.attributes="clas\
s='styled-table' id='Table1'"));
} else {
rplot = rplot +
coord_polar(theta = "y");
ggplot2::ggsave(plotFile, plot=rplot, device="png");
cat(paste0("<table><tr><td><a href=\"", plotFile,"\" download>","<img src=",currDir,"/", plotFile, " height=200 width=220 alt = R Graph></a></td><td>"));
return(print(xtable(tabDF[1:nprint,]), type="html", include.rownames=TRUE, sanitize.text.function=function(x){x}, html.table.attributes="class='styled-table' id='Table1'"));
}
} else {
return(print(paste0("<p><i>No genes specified</i></p>")));
}
}
getGeneSummaryInfoTable <- function(orgStr, geneIDArray, geneSymArray, plotFile, viewType) {
currDir = paste0("/",basename(getwd()));
## Do not unique here since NA will be uniqued
symbolStrArray = as.vector(strsplit(geneSymArray, split="__",fixed=TRUE)[[1]]);
# print(symbolStrArray)
geneArray = as.vector(strsplit(geneIDArray, split="__", fixed=TRUE)[[1]]);
countMatrix = matrix(ncol = 4, nrow=length(geneArray));
# obtain only metabolic genes
metGeneSYMBOLFileName = paste0("./data/",orgStr,"_metSYMBOLs.txt")
metGeneVec = readLines(metGeneSYMBOLFileName)
symbolStrArray <- symbolStrArray[symbolStrArray %in% metGeneVec]
if(orgStr %in% c("Human","human","hsa","Homo sapiens")){
organism_name = "Human";
} else if(orgStr %in% c("Mouse","mouse","mmu","Mus musculus")){
organism_name = "Mouse";
} else if(orgStr %in% c("Rat","rat","rno","Rattus norvegicus")){
organism_name = "Rat";
}
genesCnt = length(symbolStrArray);
rdsfilename = paste0("./data/",orgStr,"_summaryTable.RDS")
# print(rdsfilename)
sumTable = readRDS(rdsfilename)
# print(head(sumTable))
# print(symbolStrArray)
geneSumTable <- sumTable[sumTable$Genes %in% symbolStrArray, ]
# print(geneSumTable)
# Convert the columns Pathways, Reactions, Metabolites, and Studies to numeric
geneSumTable$Pathways <- as.numeric(geneSumTable$Pathways)
geneSumTable$Reactions <- as.numeric(geneSumTable$Reactions)
geneSumTable$Metabolites <- as.numeric(geneSumTable$Metabolites)
geneSumTable$Studies <- as.numeric(geneSumTable$Studies)
# Convert the subsetted dataframe to a matrix
countMatrix <- as.matrix(geneSumTable[, c("Pathways", "Reactions", "Metabolites", "Studies")])
# Transpose the matrix to match the desired format
countMatrix <- unname(countMatrix)
# print(countMatrix)
pathwaysLinkStr = paste0("<a href=\"",currDir,"/pathways.php?species=",orgStr,"&GeneIDType=ENTREZID","&anatomy=","NA","&disease=","NA","&phenotype=","NA","&GeneInfoStr=",geneIDArray,"\" target=\"_blank\">Pathways</a>");
rxnsLinkStr = paste0("<a href=\"",currDir,"/reactions.php?species=",orgStr,"&GeneIDType=ENTREZID","&anatomy=","NA","&disease=","NA","&phenotype=","NA","&GeneInfoStr=",geneIDArray,"\" target=\"blank\">Reactions</a>");
metsLinkStr = paste0("<a href=\"",currDir,"/metabolites.php?species=",orgStr,"&GeneIDType=ENTREZID","&anatomy=","NA","&disease=","NA","&phenotype=","NA","&GeneInfoStr=",geneIDArray,"\" target=\"blank\">Metabolites</a>");
studiesLinkStr = paste0("<a href=\"",currDir,"/studies.php?species=",orgStr,"&GeneIDType=ENTREZID","&anatomy=","NA","&disease=","NA","&phenotype=","NA","&GeneInfoStr=",geneIDArray,"\" target=\"blank\">Studies</a>");
plotSummary(countMatrix, genesCnt, symbolStrArray, organism_name, pathwaysLinkStr, rxnsLinkStr, metsLinkStr, studiesLinkStr, plotFile, viewType)
}
getGeneSummaryInfoTableWithKeggQuery <- function(orgStr, geneIDArray, geneSymArray, plotFile, viewType) {
## Do not unique here since NA will be uniqued
symbolStrArray = as.vector(strsplit(geneSymArray, split="__",fixed=TRUE)[[1]]);
geneArray = as.vector(strsplit(geneIDArray, split="__", fixed=TRUE)[[1]]);
countMatrix = matrix(ncol = 4, nrow=length(geneArray));
## Obtain base directory
currDir = paste0("/",basename(getwd()));
pathwayCnt = 0;
rxnsCnt = 0;
metabCnt = 0;
studyCnt = 0;
genesCnt = length(geneArray);
for (g in 1:genesCnt) {
genePthwyCnt = 0;
geneRxnsCnt = 0;
geneMetabCnt = 0;
geneIdStr = geneArray[g];
metabRxnList <- list();
reactionsList <- list();
#colnames(metdf) = c("KeGG Compound Id", "REFMET Name", "Reactions", "Study Statistics")
if(orgStr %in% c("Human","human","hsa","Homo sapiens")){
organism_name = "Human";
} else if(orgStr %in% c("Mouse","mouse","mmu","Mus musculus")){
organism_name = "Mouse";
} else if(orgStr %in% c("Rat","rat","rno","Rattus norvegicus")){
organism_name = "Rat";
}
queryStr = paste0(orgStr, ":", geneIdStr)
#Get all reactions for this gene
df <- keggLink(queryStr);
if (length(df) == 0) {
return(cat(paste0("<p>No entries found in MetGENE for organism ",organism_name," gene ", geneIdStr,".</p>")));
}
# All metabolites pertainin go the gene are prefixed as cpd:
cpds <- df[str_detect(df[,2],"cpd:"),2];
# All reactions pertaining to the gene are prefixed as rn:
rxns <- df[str_detect(df[,2],"rn:"),2];
pthwys <- df[str_detect(df[,2],"path:"),2];
pathwayList <- gsub("path:", "", pthwys);
metabList <- gsub("cpd:", "", cpds);
reactionsList <- gsub("rn:", "", rxns);
# metabCnt <- metabCnt+length(metabList);
rxnsCnt <- rxnsCnt+length(reactionsList);
pathwayCnt <- pathwayCnt+length(pathwayList);
geneRxnsCnt <- length(reactionsList);
genePthwyCnt <- length(pathwayList);
geneStudyCnt <- 0;
if (length(metabList) > 0) {
for (m in 1:length(metabList)){
metabStr = metabList[[m]];
# /rest/metstat/<ANALYSIS_TYPE>;<POLARITY>;<CHROMATOGRAPHY>;<SPECIES>;<SAMPLE SOURCE>;<DISEASE>;<KEGG_ID>;<REFMET_NAME>
# path = paste0("https://www.metabolomicsworkbench.org/rest/metstat/;;", organism_name, ";;;", metabStr);
path = paste0("https://www.metabolomicsworkbench.org/rest/metstat/;;;", organism_name, ";;;", metabStr);
jslist = read_json(path, simplifyVector = TRUE);
mydf_studies = list_of_list_to_df(jslist);
studiesVec <- mydf_studies$study;
refMetVec <- mydf_studies$refmet_name;
metabCnt <- metabCnt + length(unique(refMetVec));
geneMetabCnt <- geneMetabCnt + length(unique(refMetVec));
studyCnt = studyCnt + length(unique(studiesVec));
geneStudyCnt = geneStudyCnt + length(unique(studiesVec));
}
}
countMatrix[g,] = c(genePthwyCnt, geneRxnsCnt, geneMetabCnt, geneStudyCnt);
}
# print(countMatrix);
pathwaysLinkStr = paste0("<a href=\"",currDir,"/pathways.php?species=",orgStr,"&GeneIDType=ENTREZID","&anatomy=","NA","&disease=","NA","&phenotype=","NA","&GeneInfoStr=",geneIDArray,"\" target=\"_blank\">Pathways</a>");
# print(pathwaysLinkStr);
rxnsLinkStr = paste0("<a href=\"",currDir,"/reactions.php?species=",orgStr,"&GeneIDType=ENTREZID","&anatomy=","NA","&disease=","NA","&phenotype=","NA","&GeneInfoStr=",geneIDArray,"\" target=\"blank\">Reactions</a>");
metsLinkStr = paste0("<a href=\"",currDir,"/metabolites.php?species=",orgStr,"&GeneIDType=ENTREZID","&anatomy=","NA","&disease=","NA","&phenotype=","NA","&GeneInfoStr=",geneIDArray,"\" target=\"blank\">Metabolites</a>");
studiesLinkStr = paste0("<a href=\"",currDir,"/studies.php?species=",orgStr,"&GeneIDType=ENTREZID","&anatomy=","NA","&disease=","NA","&phenotype=","NA","&GeneInfoStr=",geneIDArray,"\" target=\"blank\">Studies</a>");
plotSummary(countMatrix, genesCnt, symbolStrArray, organism_name, pathwaysLinkStr, rxnsLinkStr, metsLinkStr, studiesLinkStr, plotFile, viewType)
}
args <- commandArgs(TRUE);
species <- args[1];
geneIDArr <- args[2];
geneSymArr = args[3];
filename <- args[4];
viewType <- args[5];
#tic("Total time elapsed = ");
if (preCompute == 1) {
getGeneSummaryInfoTable(species, geneIDArr, geneSymArr, filename, viewType)
} else {
getGeneSummaryInfoTableWithKeggQuery(species, geneIDArr, geneSymArr, filename, viewType)
}
#toc();
# Testing command example
# Rscript extraMWGeneSummary.R hsa 3098 HK1 foo.png json