forked from chrisamiller/davidapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
davidapi.rb
executable file
·415 lines (347 loc) · 10.9 KB
/
davidapi.rb
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
#!/usr/bin/env ruby
# Author: Chris Miller
# Contact: chrisamiller@gmail.com
#
# This program is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more
# details.
#
# The full text for the General Public License is here:
# http://www.gnu.org/licenses/gpl.html
#
require 'rubygems'
require 'mechanize'
require 'choice'
#------------------------------------------------------------------------------
# Takes an appropriately formatted API URL and retrieves the plaintext
# table returned by DAVD
#
def retrieveTable(url)
if url.length > 2048
raise "URL length is limited to 2048 characters. Use a smaller gene list and try again"
end
#retrieve the results page from the API
puts "calling the DAVID API with the following URL:"
puts url
puts ""
# WWW::Mechanize.html_parser = Nokogiri
mech = WWW::Mechanize.new { |agent|
agent.user_agent_alias = 'Mac Safari'
}
#get the page
page = mech.get(url)
# page = mech.get('http://127.0.0.1/asdf.html')
#parse out the script lines containing relevant variables
script = []
page.search("script").each do |input|
script << input.inner_html
# script << input.content
end
script = script[0].split(/\n/)
rowids = ""
annot = ""
action = ""
script.each{|line|
if line =~ /rowids/
rowids = line.split(/=/)[1].gsub(/\"/,"").gsub(/\;/,"")
rowids.strip!
elsif line =~/annot\.value/
annot = line.split(/=/)[1].gsub(/\"/,"").gsub(/\;/,"")
annot.strip!
elsif line =~/action/
action = line.split(/=/)[1].gsub(/\"/,"").gsub(/\;/,"")
action.strip!
end
}
# fill in the form, then submit it
dform = page.forms.first
dform.rowids=rowids
dform.annot=annot
dform.action=action
page2 = mech.submit(dform)
#parse out the download link
tableLink = nil
page2.links.each do |link|
if link.href =~/(UserDownload\/\w+.txt)/
tableLink = $1
end
end
raise "Table link not found" if (tableLink.nil? || tableLink == "")
link2 = 'http://david.abcc.ncifcrf.gov/'
link2 << "#{tableLink}"
puts "Table Link:"
puts link2
davidHash = {}
header = []
count = 0
return mech.get_file(link2)
end
#------------------------------------------------------------------------------
# takes a list of refseq gene names, returns a list of functional annotations
#
# inputs: an array of gene names [TP53,MDM2,CDKN2A]
# (optional) species name/code - default human
# (optional) an array of annotation types to retrieve
# see: http://david.abcc.ncifcrf.gov/content.jsp?file=DAVID_API.html
# (optional) custom type of gene names being input (default "OFFICIAL_GENE_SYMBOL")
#
# returns a hash of geneName -> annotation type -> array of annotations
#
# example hash returned:
# {"CDKN2A" ->
# {"GOTERM_BP_2" -> [GO:0005622~intracellular,
# GO:0005737~cytoplasm,
# GO:0031981~nuclear lumen]
# }
#
# {"KEGG_PATHWAY" -> [hsa04115:p53 signaling pathway,
# hsa05212:Pancreatic cancer,
# hsa05214:Glioma]
# }
# }
#
def getFuncAnnotations(geneList,species="9606:Homo sapiens",customAnnos=nil,customType=nil)
#create a DAVID url
url = "http://david.abcc.ncifcrf.gov/api.jsp?"
url << "type=OFFICIAL_GENE_SYMBOL"
url << "&ids=#{geneList.join(",")}"
url << "&tool=annotationReport"
if customAnnos.nil?
annotations = [
"GOTERM_BP_3", #only GO terms from level 3 and lower
"GOTERM_BP_4", #not interested in matching "biological process"
"GOTERM_BP_5",
"GOTERM_CC_3",
"GOTERM_CC_4",
"GOTERM_CC_5",
"GOTERM_MF_3",
"GOTERM_MF_4",
"GOTERM_MF_5",
"KEGG_PATHWAY", #two pathway DBs
"BIOCARTA"]
else
annotations = defaultAnnos
end
url << "&annot=" << annotations.join(",")
#retrieve the table
table = retrieveTable(url)
#parse the table
count = 0
header = nil
funcHash = {}
table.each{|line|
if count == 0
header = line.chomp.split(/\t/)
elsif line =~ /#{species}/
data = line.chomp.split(/\t/)
colsDone = []
#these three get special treatment
pos = header.index("GENE_SYMBOL")
name = data[pos]
funcHash[name] = {}
colsDone << pos
pos = header.index("Gene Name")
funcHash[name]["Gene Name"] = data[pos]
colsDone << pos
pos = header.index("Species")
funcHash[name]["Species"] = data[pos]
colsDone << pos
#now all the rest, comma sep lists -> arrays
data.each_index{|i|
unless colsDone.include?(i)
funcHash[name][header[i]] = data[i].split(/,/).collect{|x| x.strip}
funcHash[name][header[i]].delete_if {|x| x == "" }
end
}
end
count += 1
}
return funcHash
end #def
#------------------------------------------------------------------------------
# finds the functional annotations that are common between
# all genes in the davidHash
#
# input: a davidHash (results of getFuncAnnotations)
# output: a hash of fields containing arrays of
# common annotations
#
# {"GOTERM_BP_2" -> [GO:0005622~intracellular,
# GO:0005737~cytoplasm]
# }
#
def getCommonAnnos(davidHash)
commonHash = {}
fieldNames = davidHash[davidHash.keys.first].keys
genes = davidHash.keys
fieldNames.each{|field|
annos = {}
genes.each{|gene|
if davidHash[gene].key?(field)
davidHash[gene][field].each{|anno|
anno = "#{anno.strip}"
if annos.key?("#{anno}")
annos["#{anno}"] += 1
else
annos["#{anno}"] = 1
end
}
annos.each{|k,v|
#is the annotation found for every gene?
if v == genes.length
commonHash[field] = [] unless commonHash.key?(field)
commonHash[field] << k
end
}
end
}
}
return commonHash
end
#------------------------------------------------------------------------------
# retrieves the functional annotation clustering results
# for the given gene list (uses default values, since
# those options aren't exposed through the API )
#
# inputs: an array of gene names [TP53,MDM2,CDKN2A]
# (optional) an array of annotation types to cluster
# see: http://david.abcc.ncifcrf.gov/content.jsp?file=DAVID_API.html
# (optional) custom type of gene names being input (default "OFFICIAL_GENE_SYMBOL")
#
# returns a hash of terms -> hash of info for that term
#
# example:
# {"GO:0005488~binding" ->
# {"category" -> "GOTERM_MF_ALL",
# "count" -> "4"
# "PValue" -> "0.00000351590729492051"
# . . .
def getFuncClustering(geneList,customAnnos=nil,customType=nil)
#create a DAVID url
url = "http://david.abcc.ncifcrf.gov/api.jsp?"
if customType.nil?
url << "type=OFFICIAL_GENE_SYMBOL"
else
url << "type=#{customType}"
end
url << "&ids=#{geneList.join(",")}"
url << "&tool=term2term"
if customAnnos.nil?
annotations = ["GOTERM_BP_3", #only GO terms from level 3 and lower
"GOTERM_BP_4", #not interested in matching "biological process"
"GOTERM_BP_5",
"GOTERM_CC_3",
"GOTERM_CC_4",
"GOTERM_CC_5",
"GOTERM_MF_3",
"GOTERM_MF_4",
"GOTERM_MF_5",
"KEGG_PATHWAY", #two pathway DBs
"BIOCARTA"]
else
annotations = defaultAnnos
end
url << "&annot=" << annotations.join(",")
#retrieve the data from DAVID
table = retrieveTable(url)
#parse the table
clusterHash = {}
count = 0
header = []
table.each{|line|
if count == 0 #summary info, not returned for now
summary = line.chomp.split(/\t/)
elsif count == 1 #get header line
header = line.chomp.split(/\t/)
else
#extract the term
data = line.chomp.split(/\t/)
pos = header.index("Term")
name = data[pos]
clusterHash[name] = {}
#now add the rest of the terms
data.each_index{|i|
unless i == pos
#convert to comma-sep list, if appropriate
if data[i] =~ /,/
data[i] = data[i].split(/,/).collect{|x| x.strip}
#remove blank entries
data[i] = data[i].delete_if{|x| x == ""}
end
clusterHash[name][header[i]] = data[i]
end
}
end
count += 1
}
return clusterHash
end #def
##------------------------------------------------------------------------------
# retrieves full gene information for the given gene list
#
# inputs: an array of gene names [TP53,MDM2,CDKN2A]
# (optional) species name/code - default human
# (optional) custom type of gene names being input (default "OFFICIAL_GENE_SYMBOL")
#
#
# returns a hash of genes -> hash of info for that term
#
# example:
# {"MDM2" ->
# {"OMIM_DISEASE" -> "blah blah blah"
# {"ENTREZ_GENE_ID" -> "blah,blah,blah"
# . . .
#
def getGeneReport(geneList,species="9606:Homo sapiens",customType=nil)
#create a DAVID url
url = "http://david.abcc.ncifcrf.gov/api.jsp?"
if customType.nil?
url << "type=OFFICIAL_GENE_SYMBOL"
else
url << "type=#{customType}"
end
url << "&ids=#{geneList.join(",")}"
url << "&tool=geneReportFull"
#retrieve the data from DAVID
table = retrieveTable(url)
#parse the table
#there's a more elegant way to parse this, but this'll
#do for now (also a less mem-intensive way)
newAnno = true
blocks = []
current = -1
table.each{|line|
if line.chomp == ""
newAnno = true
elsif newAnno #first line in block
current += 1
blocks[current] = []
blocks[current] << line.chomp.split(/\t/)
newAnno = false
else
blocks[current] << line.chomp.split(/\t/)
end
}
infoHash = {}
blocks.each{|block|
if block[0][2] =~ /#{species}/
name = block[0][0]
infoHash[name] = {}
infoHash[name]["species"] = block[0][2]
infoHash[name]["description"] = block[0][1]
1.upto(block.length-1){|i|
line = block[i]
infoHash[name][line[0]] = line[1]
}
end
}
return infoHash
end