annotate get_fasta_from_taxon.py @ 0:7ce8da107910 draft default tip

Uploaded
author crs4
date Wed, 11 Sep 2013 06:07:50 -0400
parents
children
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
0
7ce8da107910 Uploaded
crs4
parents:
diff changeset
1 # -*- coding: utf-8 -*-
7ce8da107910 Uploaded
crs4
parents:
diff changeset
2 """
7ce8da107910 Uploaded
crs4
parents:
diff changeset
3 From a taxonomy ID retrieves all the nucleotide sequences
7ce8da107910 Uploaded
crs4
parents:
diff changeset
4 It returns a multiFASTA nuc/prot file
7ce8da107910 Uploaded
crs4
parents:
diff changeset
5
7ce8da107910 Uploaded
crs4
parents:
diff changeset
6 Entrez Database UID common name E-utility Database Name
7ce8da107910 Uploaded
crs4
parents:
diff changeset
7 Nucleotide GI number nuccore
7ce8da107910 Uploaded
crs4
parents:
diff changeset
8 Protein GI number protein
7ce8da107910 Uploaded
crs4
parents:
diff changeset
9
7ce8da107910 Uploaded
crs4
parents:
diff changeset
10 Retrieve strategy:
7ce8da107910 Uploaded
crs4
parents:
diff changeset
11
7ce8da107910 Uploaded
crs4
parents:
diff changeset
12 esearch to get total number of UIDs (count)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
13 esearch to get UIDs in batches
7ce8da107910 Uploaded
crs4
parents:
diff changeset
14 loop untile end of UIDs list:
7ce8da107910 Uploaded
crs4
parents:
diff changeset
15 epost to put a batch of UIDs in the history server
7ce8da107910 Uploaded
crs4
parents:
diff changeset
16 efetch to retrieve info from previous post
7ce8da107910 Uploaded
crs4
parents:
diff changeset
17
7ce8da107910 Uploaded
crs4
parents:
diff changeset
18 retmax of efetch is 1/10 of declared value from NCBI
7ce8da107910 Uploaded
crs4
parents:
diff changeset
19
7ce8da107910 Uploaded
crs4
parents:
diff changeset
20 queries are 1 sec delayed, to satisfy NCBI guidelines (more than what they request)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
21
7ce8da107910 Uploaded
crs4
parents:
diff changeset
22
7ce8da107910 Uploaded
crs4
parents:
diff changeset
23 python get_fasta_from_taxon.py -i 1638 -o test.out -d protein
7ce8da107910 Uploaded
crs4
parents:
diff changeset
24 python get_fasta_from_taxon.py -i 327045 -o test.out -d nuccore # 556468 UIDs
7ce8da107910 Uploaded
crs4
parents:
diff changeset
25 """
7ce8da107910 Uploaded
crs4
parents:
diff changeset
26
7ce8da107910 Uploaded
crs4
parents:
diff changeset
27 import logging
7ce8da107910 Uploaded
crs4
parents:
diff changeset
28 import optparse
7ce8da107910 Uploaded
crs4
parents:
diff changeset
29 import time
7ce8da107910 Uploaded
crs4
parents:
diff changeset
30 import urllib
7ce8da107910 Uploaded
crs4
parents:
diff changeset
31 import urllib2
7ce8da107910 Uploaded
crs4
parents:
diff changeset
32
7ce8da107910 Uploaded
crs4
parents:
diff changeset
33 class Eutils:
7ce8da107910 Uploaded
crs4
parents:
diff changeset
34
7ce8da107910 Uploaded
crs4
parents:
diff changeset
35 def __init__(self, options, logger):
7ce8da107910 Uploaded
crs4
parents:
diff changeset
36 self.logger = logger
7ce8da107910 Uploaded
crs4
parents:
diff changeset
37 self.base = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/"
7ce8da107910 Uploaded
crs4
parents:
diff changeset
38 self.taxid = options.taxid
7ce8da107910 Uploaded
crs4
parents:
diff changeset
39 self.dbname = options.dbname
7ce8da107910 Uploaded
crs4
parents:
diff changeset
40 if options.outname:
7ce8da107910 Uploaded
crs4
parents:
diff changeset
41 self.outname = options.outname
7ce8da107910 Uploaded
crs4
parents:
diff changeset
42 else:
7ce8da107910 Uploaded
crs4
parents:
diff changeset
43 self.outname = 'taxid' + self.taxid + '.' + self.dbname + '.fasta'
7ce8da107910 Uploaded
crs4
parents:
diff changeset
44 self.ids = []
7ce8da107910 Uploaded
crs4
parents:
diff changeset
45 self.retmax_esearch = 100000
7ce8da107910 Uploaded
crs4
parents:
diff changeset
46 self.retmax_efetch = 1000
7ce8da107910 Uploaded
crs4
parents:
diff changeset
47 self.count = 0
7ce8da107910 Uploaded
crs4
parents:
diff changeset
48 self.webenv = ""
7ce8da107910 Uploaded
crs4
parents:
diff changeset
49 self.query_key = ""
7ce8da107910 Uploaded
crs4
parents:
diff changeset
50
7ce8da107910 Uploaded
crs4
parents:
diff changeset
51 def retrieve(self):
7ce8da107910 Uploaded
crs4
parents:
diff changeset
52 """ """
7ce8da107910 Uploaded
crs4
parents:
diff changeset
53 self.get_count_value()
7ce8da107910 Uploaded
crs4
parents:
diff changeset
54 self.get_uids_list()
7ce8da107910 Uploaded
crs4
parents:
diff changeset
55 self.get_sequences()
7ce8da107910 Uploaded
crs4
parents:
diff changeset
56
7ce8da107910 Uploaded
crs4
parents:
diff changeset
57 def get_count_value(self):
7ce8da107910 Uploaded
crs4
parents:
diff changeset
58 """
7ce8da107910 Uploaded
crs4
parents:
diff changeset
59 just to retrieve Count (number of UIDs)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
60 Total number of UIDs from the retrieved set to be shown in the XML
7ce8da107910 Uploaded
crs4
parents:
diff changeset
61 output (default=20). By default, ESearch only includes the first 20
7ce8da107910 Uploaded
crs4
parents:
diff changeset
62 UIDs retrieved in the XML output. If usehistory is set to 'y',
7ce8da107910 Uploaded
crs4
parents:
diff changeset
63 the remainder of the retrieved set will be stored on the History server;
7ce8da107910 Uploaded
crs4
parents:
diff changeset
64
7ce8da107910 Uploaded
crs4
parents:
diff changeset
65 http://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.EFetch
7ce8da107910 Uploaded
crs4
parents:
diff changeset
66 """
7ce8da107910 Uploaded
crs4
parents:
diff changeset
67 self.logger.info("retrieving data from %s" % self.base)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
68 self.logger.info("for TaxID: %s and database: %s" %
7ce8da107910 Uploaded
crs4
parents:
diff changeset
69 (self.taxid, self.dbname))
7ce8da107910 Uploaded
crs4
parents:
diff changeset
70 querylog = self.esearch(self.dbname, "txid%s[Organism:exp]" % self.taxid, '', '', "count")
7ce8da107910 Uploaded
crs4
parents:
diff changeset
71 self.logger.debug("taxonomy response:")
7ce8da107910 Uploaded
crs4
parents:
diff changeset
72 for line in querylog:
7ce8da107910 Uploaded
crs4
parents:
diff changeset
73 self.logger.debug(line.rstrip())
7ce8da107910 Uploaded
crs4
parents:
diff changeset
74 if '</Count>' in line:
7ce8da107910 Uploaded
crs4
parents:
diff changeset
75 self.count = int(line[line.find('<Count>')+len('<Count>') : line.find('</Count>')])
7ce8da107910 Uploaded
crs4
parents:
diff changeset
76 self.logger.info("Founded %d UIDs" % self.count)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
77
7ce8da107910 Uploaded
crs4
parents:
diff changeset
78 def get_uids_list(self):
7ce8da107910 Uploaded
crs4
parents:
diff changeset
79 """
7ce8da107910 Uploaded
crs4
parents:
diff changeset
80 Increasing retmax allows more of the retrieved UIDs to be included in the XML output,
7ce8da107910 Uploaded
crs4
parents:
diff changeset
81 up to a maximum of 100,000 records.
7ce8da107910 Uploaded
crs4
parents:
diff changeset
82 from http://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESearch
7ce8da107910 Uploaded
crs4
parents:
diff changeset
83 """
7ce8da107910 Uploaded
crs4
parents:
diff changeset
84 retmax = self.retmax_esearch
7ce8da107910 Uploaded
crs4
parents:
diff changeset
85 if (self.count > retmax):
7ce8da107910 Uploaded
crs4
parents:
diff changeset
86 num_batches = (self.count / retmax) + 1
7ce8da107910 Uploaded
crs4
parents:
diff changeset
87 else:
7ce8da107910 Uploaded
crs4
parents:
diff changeset
88 num_batches = 1
7ce8da107910 Uploaded
crs4
parents:
diff changeset
89 self.logger.info("Batch size for esearch action: %d UIDs" % retmax)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
90 self.logger.info("Number of batches for esearch action: %d " % num_batches)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
91 for n in range(num_batches):
7ce8da107910 Uploaded
crs4
parents:
diff changeset
92 querylog = self.esearch(self.dbname, "txid%s[Organism:exp]" % self.taxid, n*retmax, retmax, '')
7ce8da107910 Uploaded
crs4
parents:
diff changeset
93 for line in querylog:
7ce8da107910 Uploaded
crs4
parents:
diff changeset
94 if '<Id>' in line and '</Id>' in line:
7ce8da107910 Uploaded
crs4
parents:
diff changeset
95 uid = (line[line.find('<Id>')+len('<Id>') : line.find('</Id>')])
7ce8da107910 Uploaded
crs4
parents:
diff changeset
96 self.ids.append(uid)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
97 self.logger.info("Retrieved %d UIDs" % len(self.ids))
7ce8da107910 Uploaded
crs4
parents:
diff changeset
98
7ce8da107910 Uploaded
crs4
parents:
diff changeset
99 def esearch(self, db, term, retstart, retmax, rettype):
7ce8da107910 Uploaded
crs4
parents:
diff changeset
100 url = self.base + "esearch.fcgi"
7ce8da107910 Uploaded
crs4
parents:
diff changeset
101 self.logger.debug("url: %s" % url)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
102 values = {'db': db,
7ce8da107910 Uploaded
crs4
parents:
diff changeset
103 'term': term,
7ce8da107910 Uploaded
crs4
parents:
diff changeset
104 'rettype': rettype,
7ce8da107910 Uploaded
crs4
parents:
diff changeset
105 'retstart': retstart,
7ce8da107910 Uploaded
crs4
parents:
diff changeset
106 'retmax': retmax}
7ce8da107910 Uploaded
crs4
parents:
diff changeset
107 data = urllib.urlencode(values)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
108 self.logger.debug("data: %s" % str(data))
7ce8da107910 Uploaded
crs4
parents:
diff changeset
109 req = urllib2.Request(url, data)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
110 response = urllib2.urlopen(req)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
111 querylog = response.readlines()
7ce8da107910 Uploaded
crs4
parents:
diff changeset
112 time.sleep(1)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
113 return querylog
7ce8da107910 Uploaded
crs4
parents:
diff changeset
114
7ce8da107910 Uploaded
crs4
parents:
diff changeset
115 def epost(self, db, ids):
7ce8da107910 Uploaded
crs4
parents:
diff changeset
116 url = self.base + "epost.fcgi"
7ce8da107910 Uploaded
crs4
parents:
diff changeset
117 self.logger.debug("url_epost: %s" % url)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
118 values = {'db': db,
7ce8da107910 Uploaded
crs4
parents:
diff changeset
119 'id': ids}
7ce8da107910 Uploaded
crs4
parents:
diff changeset
120 data = urllib.urlencode(values)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
121 req = urllib2.Request(url, data)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
122 #self.logger.debug("data: %s" % str(data))
7ce8da107910 Uploaded
crs4
parents:
diff changeset
123 req = urllib2.Request(url, data)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
124 response = urllib2.urlopen(req)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
125 querylog = response.readlines()
7ce8da107910 Uploaded
crs4
parents:
diff changeset
126 self.logger.debug("taxonomy response:")
7ce8da107910 Uploaded
crs4
parents:
diff changeset
127 for line in querylog:
7ce8da107910 Uploaded
crs4
parents:
diff changeset
128 self.logger.debug(line.rstrip())
7ce8da107910 Uploaded
crs4
parents:
diff changeset
129 if '</QueryKey>' in line:
7ce8da107910 Uploaded
crs4
parents:
diff changeset
130 self.query_key = str(line[line.find('<QueryKey>')+len('<QueryKey>'):line.find('</QueryKey>')])
7ce8da107910 Uploaded
crs4
parents:
diff changeset
131 if '</WebEnv>' in line:
7ce8da107910 Uploaded
crs4
parents:
diff changeset
132 self.webenv = str(line[line.find('<WebEnv>')+len('<WebEnv>'):line.find('</WebEnv>')])
7ce8da107910 Uploaded
crs4
parents:
diff changeset
133 self.logger.debug("*** epost action ***")
7ce8da107910 Uploaded
crs4
parents:
diff changeset
134 self.logger.debug("query_key: %s" % self.query_key)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
135 self.logger.debug("webenv: %s" % self.webenv)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
136 time.sleep(1)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
137
7ce8da107910 Uploaded
crs4
parents:
diff changeset
138 def efetch(self, db, query_key, webenv):
7ce8da107910 Uploaded
crs4
parents:
diff changeset
139 url = self.base + "efetch.fcgi"
7ce8da107910 Uploaded
crs4
parents:
diff changeset
140 self.logger.debug("url_efetch: %s" % url)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
141 values = {'db': db,
7ce8da107910 Uploaded
crs4
parents:
diff changeset
142 'query_key': query_key,
7ce8da107910 Uploaded
crs4
parents:
diff changeset
143 'webenv': webenv,
7ce8da107910 Uploaded
crs4
parents:
diff changeset
144 'rettype': "fasta",
7ce8da107910 Uploaded
crs4
parents:
diff changeset
145 'retmode': "text"}
7ce8da107910 Uploaded
crs4
parents:
diff changeset
146 data = urllib.urlencode(values)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
147 req = urllib2.Request(url, data)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
148 self.logger.debug("data: %s" % str(data))
7ce8da107910 Uploaded
crs4
parents:
diff changeset
149 req = urllib2.Request(url, data)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
150 response = urllib2.urlopen(req)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
151 fasta = response.read()
7ce8da107910 Uploaded
crs4
parents:
diff changeset
152 assert fasta.startswith(">"), fasta
7ce8da107910 Uploaded
crs4
parents:
diff changeset
153 time.sleep(1)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
154 return fasta
7ce8da107910 Uploaded
crs4
parents:
diff changeset
155
7ce8da107910 Uploaded
crs4
parents:
diff changeset
156 def get_sequences(self):
7ce8da107910 Uploaded
crs4
parents:
diff changeset
157 """
7ce8da107910 Uploaded
crs4
parents:
diff changeset
158 Total number of records from the input set to be retrieved, up to a maximum
7ce8da107910 Uploaded
crs4
parents:
diff changeset
159 of 10,000. Optionally, for a large set the value of retstart can be iterated
7ce8da107910 Uploaded
crs4
parents:
diff changeset
160 while holding retmax constant, thereby downloading the entire set in batches
7ce8da107910 Uploaded
crs4
parents:
diff changeset
161 of size retmax.
7ce8da107910 Uploaded
crs4
parents:
diff changeset
162
7ce8da107910 Uploaded
crs4
parents:
diff changeset
163 http://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.EFetch
7ce8da107910 Uploaded
crs4
parents:
diff changeset
164
7ce8da107910 Uploaded
crs4
parents:
diff changeset
165 """
7ce8da107910 Uploaded
crs4
parents:
diff changeset
166 batch_size = self.retmax_efetch
7ce8da107910 Uploaded
crs4
parents:
diff changeset
167 count = self.count
7ce8da107910 Uploaded
crs4
parents:
diff changeset
168 uids_list = self.ids
7ce8da107910 Uploaded
crs4
parents:
diff changeset
169 self.logger.info("Batch size for efetch action: %d" % batch_size)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
170 self.logger.info("Number of batches for efetch action: %d" % ((count / batch_size) + 1))
7ce8da107910 Uploaded
crs4
parents:
diff changeset
171 with open(self.outname, 'w') as out:
7ce8da107910 Uploaded
crs4
parents:
diff changeset
172 for start in range(0, count, batch_size):
7ce8da107910 Uploaded
crs4
parents:
diff changeset
173 end = min(count, start+batch_size)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
174 batch = uids_list[start:end]
7ce8da107910 Uploaded
crs4
parents:
diff changeset
175 self.epost(self.dbname, ",".join(batch))
7ce8da107910 Uploaded
crs4
parents:
diff changeset
176 self.logger.info("retrieving batch %d" % ((start / batch_size) + 1))
7ce8da107910 Uploaded
crs4
parents:
diff changeset
177 mfasta = self.efetch(self.dbname, self.query_key, self.webenv)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
178 out.write(mfasta + '\n')
7ce8da107910 Uploaded
crs4
parents:
diff changeset
179
7ce8da107910 Uploaded
crs4
parents:
diff changeset
180
7ce8da107910 Uploaded
crs4
parents:
diff changeset
181 LOG_FORMAT = '%(asctime)s|%(levelname)-8s|%(message)s'
7ce8da107910 Uploaded
crs4
parents:
diff changeset
182 LOG_DATEFMT = '%Y-%m-%d %H:%M:%S'
7ce8da107910 Uploaded
crs4
parents:
diff changeset
183 LOG_LEVELS = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']
7ce8da107910 Uploaded
crs4
parents:
diff changeset
184
7ce8da107910 Uploaded
crs4
parents:
diff changeset
185
7ce8da107910 Uploaded
crs4
parents:
diff changeset
186 def __main__():
7ce8da107910 Uploaded
crs4
parents:
diff changeset
187 """ main function """
7ce8da107910 Uploaded
crs4
parents:
diff changeset
188 parser = optparse.OptionParser(description='Retrieve data from NCBI')
7ce8da107910 Uploaded
crs4
parents:
diff changeset
189 parser.add_option('-i', dest='taxid', help='taxonomy ID mandatory')
7ce8da107910 Uploaded
crs4
parents:
diff changeset
190 parser.add_option('-o', dest='outname', help='output file name')
7ce8da107910 Uploaded
crs4
parents:
diff changeset
191 parser.add_option('-l', '--logfile', help='log file (default=stderr)')
7ce8da107910 Uploaded
crs4
parents:
diff changeset
192 parser.add_option('--loglevel', choices=LOG_LEVELS, default='INFO', help='logging level (default: INFO)')
7ce8da107910 Uploaded
crs4
parents:
diff changeset
193 parser.add_option('-d', dest='dbname', help='database type')
7ce8da107910 Uploaded
crs4
parents:
diff changeset
194 (options, args) = parser.parse_args()
7ce8da107910 Uploaded
crs4
parents:
diff changeset
195 if len(args) > 0:
7ce8da107910 Uploaded
crs4
parents:
diff changeset
196 parser.error('Wrong number of arguments')
7ce8da107910 Uploaded
crs4
parents:
diff changeset
197
7ce8da107910 Uploaded
crs4
parents:
diff changeset
198 log_level = getattr(logging, options.loglevel)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
199 kwargs = {'format': LOG_FORMAT,
7ce8da107910 Uploaded
crs4
parents:
diff changeset
200 'datefmt': LOG_DATEFMT,
7ce8da107910 Uploaded
crs4
parents:
diff changeset
201 'level': log_level}
7ce8da107910 Uploaded
crs4
parents:
diff changeset
202 if options.logfile:
7ce8da107910 Uploaded
crs4
parents:
diff changeset
203 kwargs['filename'] = options.logfile
7ce8da107910 Uploaded
crs4
parents:
diff changeset
204 logging.basicConfig(**kwargs)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
205 logger = logging.getLogger('data_from_NCBI')
7ce8da107910 Uploaded
crs4
parents:
diff changeset
206
7ce8da107910 Uploaded
crs4
parents:
diff changeset
207 E = Eutils(options, logger)
7ce8da107910 Uploaded
crs4
parents:
diff changeset
208 E.retrieve()
7ce8da107910 Uploaded
crs4
parents:
diff changeset
209
7ce8da107910 Uploaded
crs4
parents:
diff changeset
210
7ce8da107910 Uploaded
crs4
parents:
diff changeset
211 if __name__ == "__main__":
7ce8da107910 Uploaded
crs4
parents:
diff changeset
212 __main__()