-
Notifications
You must be signed in to change notification settings - Fork 0
/
getGeo.py
executable file
·181 lines (149 loc) · 4.94 KB
/
getGeo.py
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
#!/usr/bin/python
# getGeo.py
# Aryeh Hillman
#
# Gets data from GEO2R
#
# TODO: probably great to have some logging capabilities baked in (see below)
import httplib2
import json
import sys
from subprocess import Popen, PIPE, STDOUT
import StringIO
debug = 0
h = httplib2.Http(".cache")
USAGE = """%s accession platform featureOutfile dataOutfile""" % sys.argv[0]
USAGE = """Enter - to avoid specifying a platform"""
if len(sys.argv) != 5:
print USAGE
sys.exit(-1)
accession = sys.argv[1]
platform = sys.argv[2]
featureOutfile = sys.argv[3]
dataOutfile = sys.argv[4]
def generateRText(accession, platform, dataOutfile):
text = """
library(Biobase)
library(GEOquery)
gset <- getGEO("%s", GSEMatrix =TRUE)
if (length(gset) > 1) idx <- grep("%s", attr(gset, "names")) else idx <- 1
gset <- gset[[idx]]
write.table(gset, file="%s")
""" % (accession, platform, dataOutfile)
return text
def makeMetaURL(mode="geo2r", **kwargs):
metaURL = "http://www.ncbi.nlm.nih.gov/geo/tools/geometa.cgi?"
shortnames = { 'view':'view',
'series': 'series',
'accession': 'acc',
'platform': 'platform',
'mode': 'mode' }
for attr in kwargs:
firstAttr = False
if not firstAttr:
metaURL += "&"
shortname = attr
if (shortnames.has_key(attr)):
shortname = shortnames[attr]
metaURL += shortname + "=" + kwargs[attr]
return metaURL
def getPlatformList(accession):
#TODO: could check if accession starts with
#"GSE" or not... GPL implies platform, most likely
metaURL = makeMetaURL(accession=accession)
response, content = h.request(metaURL)
#TODO: pad this with error catching and probably log
metaJSON = json.loads(content)
platforms = metaJSON['GeoMetaData'][0]['entity']['series']['platforms']
return platforms
def getSamples(accession, platform):
metaURL = makeMetaURL(series=accession, platform=platform, view='samples', mode='geo2r')
if debug:
print metaURL
response, content = h.request(metaURL)
metaJSON = json.loads(content)
return metaJSON
def jsonSamplesString(j):
string = "accession title " + " ".join(j['GeoMetaData'][0]['entity']['sample'].keys()) + "\n"
for sample in j['GeoMetaData']:
string += "%s\t%s" % (sample['acc'], sample['title'])
string += '\t'.join(sample['entity']['sample']['channels'].values())
def getSampleHeader(sample):
headerString = "tite\tacc\t"
channelKeys = dict()
for channel in sample['entity']['sample']['channels']:
for key in channel.keys():
if channelKeys.has_key(key):
channelKeys[key] = d[key] + 1
else:
channelKeys[key] = 1
channelKeyString = ""
for key, numAppearances in channelKeys.iteritems():
for x in range(1,numAppearances + 1):
channelKeyString += key + str(x) + "\t"
headerString += channelKeyString
return headerString
#http://stackoverflow.com/questions/8477550/
#flattening-a-list-of-dicts-of-lists-of-dicts-etc-of-unknown-depth-in-python-n
keys = []
def flatten(l):
global keys
out = []
if isinstance(l, (list, tuple)):
for item in l:
keys.append(keys[-1])
out.extend(flatten(item))
elif isinstance(l, (dict)):
for dictkey in l.keys():
keys.append(dictkey)
out.extend(flatten(l[dictkey]))
elif isinstance(l, (str, int, unicode)):
keys.append(keys[-1])
out.append(l)
return out
def main():
global platform
platforms = getPlatformList(accession)
if platform == "-":
if len(platforms) != 1:
print "Multiple platforms exist for accession %s" % accession
sys.exit(-1)
platform = platforms[0]
# print platform
if len(platforms) == 0:
print "Accession %s does not exist" % accession
sys.exit(1)
if platforms.count(platform) == 0:
print "Platform %s does not exist for accession %s" % (platform, accession)
sys.exit(1)
samplesJSON = getSamples(accession, platform)
samples = flatten(samplesJSON)
line = []
lines = []
for item in samples:
if not isinstance(item, int):
if item[:3] == 'ftp':
continue
if item[:3] == 'GSM':
if line != []:
lines.append(line)
line = []
line.append(item)
featuresFile = open(featureOutfile, 'w')
for line in lines:
lineString = line.__repr__()[1:-1] + "\n"
featuresFile.write(lineString)
featuresFile.close()
rString = generateRText(accession, platform, dataOutfile)
# rfile = open("rfile.tmp", 'w')
# rfile.write(generateRText(accession, platform))
# rfile.close()
from subprocess import Popen, PIPE, STDOUT
p = Popen(['R', '--no-save'], stdin=PIPE, stderr=PIPE, stdout=PIPE)
print
print rString
print
print p.communicate(input=rString)
# print p.communicate(rString)
if __name__=="__main__":
main()