-
Notifications
You must be signed in to change notification settings - Fork 0
/
using_EGID
166 lines (150 loc) · 4.21 KB
/
using_EGID
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
import pymysql
import cPickle
import Bio
from Bio import Entrez
import StringIO
import urllib
import urllib2
import socket
import sys
import os
import time
import numpy as np
from functools import wraps
from lxml import etree as ET
Entrez.email = "[email protected]"
socket.setdefaulttimeout(15)
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/536.30.1 (KHTML, like Gecko) Version/6.0.5 Safari/536.30.1')]
opener.addheaders = [('Connection', 'keep-alive')]
opener.addheaders = [('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')]
opener.addheaders = [('Accept-Language', 'en-us')]
def retry(ExceptionToCheck, tries=20, delay=4, backoff=2, logger=None):
def deco_retry(f):
@wraps(f)
def f_retry(*args, **kwargs):
mtries, mdelay = tries, delay
while mtries > 1:
try:
return f(*args, **kwargs)
except ExceptionToCheck, e:
msg = "\n" + time.ctime() + " %s, Retrying in %d seconds..." % (str(e), mdelay)
if logger:
print msg
logger.warning(msg)
else:
print msg
file = open('logger.txt', 'a')
file.write(msg)
file.close()
mtries -= 1
mdelay *= backoff
return f(*args, **kwargs)
return f_retry
return deco_retry
def retry2(ExceptionToCheck, tries=3, delay=2, backoff=2, logger=None):
def deco_retry(f):
@wraps(f)
def f_retry(*args, **kwargs):
mtries, mdelay = tries, delay
while mtries > 1:
try:
return f(*args, **kwargs)
except ExceptionToCheck, e:
msg = "\n" + time.ctime() + " %s, Retrying in %d seconds..." % (str(e), mdelay)
if logger:
logger.warning(msg)
else:
file = open('logger2.txt', 'a')
file.write(msg)
file.close()
mtries -= 1
mdelay *= backoff
return f(*args, **kwargs)
return f_retry
return deco_retry
@retry(Exception)
def esearch_retry(inp1,inp2):
record = Entrez.esearch(db=inp1, term=inp2, retmax = 99999)
return Entrez.read(record)
@retry(Exception)
def elink_retry(inp1,inp2,inp3):
record = Entrez.elink(dbfrom=inp1, db=inp2, id=inp3, retmax = 99999)
return Entrez.read(record)
@retry(Exception)
def urlopen_with_retry(url):
return opener.open(url, timeout=15)
@retry2(Exception)
def urlopen_with_retry2(url):
return opener.open(url, timeout=15)
def uniprot_mapping(fromtype, totype, identifier):
base = 'http://www.uniprot.org'
tool = 'mapping'
params = {'from':fromtype,
'to':totype,
'format':'tab',
'query':identifier,
}
data = urllib.urlencode(params)
url = base+'/'+tool+'?'+data
response = urlopen_with_retry(url)
dat = StringIO.StringIO(response.read())
page = np.loadtxt(dat,dtype=str)
try:
page = page[:,1][1:]
except IndexError:
return []
return page
def esearch_id(db,inp):
record = esearch_retry(db,inp)
return record["IdList"]
def elink_ids(inp,db1,db2):
ids = []
chunks = [inp[x:x+120] for x in xrange(0, len(inp), 120)]
for chunk in chunks:
record = elink_retry(db1,db2,",".join(map(str,chunk)))
try:
for i in record[0]['LinkSetDb'][0]['Link']:
ids.append(i['Id'])
except IndexError: pass
return list(set(ids) - set(inp))
def aid_cid(inp):
ids = []
chunks = [inp[x:x+40] for x in xrange(0, len(inp), 40)]
for chunk in chunks:
time.sleep(0.1)
ids += cid_pug(chunk)
ids = list(set(ids))
return list(set(ids) - set(inp))
def cid_pug(inp):
ids = []
url="https://pubchem.ncbi.nlm.nih.gov/rest/pug/assay/aid/" + ",".join(map(str,inp)) + "/cids/XML?cids_type=inactive"
try:
response = urlopen_with_retry2(url)
root = ET.fromstring(response.read())
for i in root.iterchildren():
for x in i.iterchildren():
ids.append(int(x.text))
except: pass
return ids
def uniprot_smiles(gene):
uniprots = uniprot_mapping("P_ENTREZGENEID","ACC",gene)
gids = []
for u in uniprots:
gids += uniprot_mapping("ACC","P_ENTREZGENEID",u)
gids += esearch_id("gene",u)
gids = list(set(gids))
pids = elink_ids(gids,"gene","protein")
aids = []
aids += elink_ids(gids,"gene","pcassay")
aids += elink_ids(pids,"protein","pcassay")
aids = list(set(aids))
if len(aids) == 0: return []
cids = aid_cid(aids)
return cids
def main():
x = uniprot_smiles(sys.argv[1])
return x
if __name__ == "__main__":
x= main()
print( x )