[Bio] / Babel / bin / source2ach.py Repository:
ViewVC logotype

Annotation of /Babel/bin/source2ach.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.11 - (view) (download) (as text)

1 : tharriso 1.1 #!/usr/bin/env python
2 :    
3 :     import os, sys, re, hashlib
4 :     from optparse import OptionParser
5 : tharriso 1.10 from multiprocessing import Pool
6 : tharriso 1.1 from Bio import SeqIO
7 :     from Bio.Seq import Seq
8 :     from Bio.SeqRecord import SeqRecord
9 :     from Bio.Alphabet import IUPAC
10 :    
11 :     __doc__ = """
12 :     Script to take a repository file from the following formats:
13 :     genbank, kegg, swiss, fasta
14 :     and output the following tab seperated files:
15 :    
16 :     SOURCE.md52id2func:
17 :     md5, id, function, organism, source, beg_pos*, end_pos*, strand*, contig_id*, contig_desc*, contig_length*
18 : tharriso 1.5 SOURCE.ms52id2ont:
19 :     md5, id, function, ontology, source
20 : tharriso 1.1 SOURCE.md52seq:
21 :     md5, sequence
22 : tharriso 1.4 SOURCE.id2xref:
23 : tharriso 1.1 id, external refrence 1, [external refrence 2, external refrence 3, ...]
24 : tharriso 1.9 SOURCE.id2tax:
25 :     id, genbank tax string
26 : tharriso 1.1
27 :     Values with * are optional, only genbank files contain that data."""
28 :    
29 : tharriso 1.10 class Info:
30 :     def __init__(self):
31 :     self.source = ''
32 :     self.format = 'fasta'
33 :     self.verbose = False
34 :     self.outdir = ''
35 :     self.orghead = False
36 :     self.getont = False
37 :     self.getctg = False
38 :     self.gettax = False
39 :     self.amap = {}
40 :    
41 : tharriso 1.2 desc_re = re.compile('(Rec|Sub)Name: Full=(.*?);')
42 : tharriso 1.1 entry_re = re.compile('^ENTRY\s+(\S+)\s+CDS\s+(.*)$', re.MULTILINE)
43 :     name_re = re.compile('^NAME\s+(.*)$', re.MULTILINE)
44 :     func_re = re.compile('^DEFINITION\s+(.*?)^\S', re.DOTALL | re.MULTILINE)
45 : tharriso 1.5 orth_re = re.compile('^ORTHOLOGY\s+(.*?)^\S', re.DOTALL | re.MULTILINE)
46 : tharriso 1.1 dbref_re = re.compile('^DBLINKS\s+(.*?)^\S', re.DOTALL | re.MULTILINE)
47 :     seq_re = re.compile('^AASEQ\s+\d+\s+(.*?)^\S', re.DOTALL | re.MULTILINE)
48 : tharriso 1.5 up_go_re = re.compile('^GO:GO:(.*)')
49 :     gb_go_re = re.compile('^GO:(\d+)\s+-\s+(.*)')
50 : tharriso 1.6 gb_go_rm = re.compile('( \[Evidence [A-Z]+\])')
51 : tharriso 1.5 ko_re = re.compile('^(K\d+)\s+(.*)')
52 :     ogid_re = re.compile('^(\S+?OG)\d+')
53 : tharriso 1.10 nr_re = re.compile('^gi\|(\d+)\|(\w+)\|(\S+)\|\S*?\s+(.*)\]$')
54 :     nr_types = {'ref': 'RefSeq', 'gb': 'GenBank', 'emb': 'EMBL', 'dbj': 'DDBJ', 'pir': 'PIR', 'prf': 'PRF', 'pdb': 'PDB'}
55 : tharriso 1.5 go_types = ['GO_function', 'GO_process', 'GO_component']
56 : tharriso 1.9 file_ext = [".md52id2func", ".md52id2ont", ".md52seq", ".id2xref", ".id2tax"]
57 : tharriso 1.10 params = Info()
58 :    
59 :     def parse_nr_header(line):
60 :     items = []
61 :     hdr_set = nr_re.match(line)
62 :     if hdr_set:
63 :     (gi_id, nrdb, nrdb_id, func_org) = hdr_set.groups()
64 :     if nrdb in params.amap:
65 :     org_rev = ''
66 :     rev_fo = reverse_string(func_org)
67 :     end_brk = 1
68 :     beg_brk = 0
69 :     for i, c in enumerate(rev_fo):
70 :     if c == ']': end_brk += 1
71 :     if c == '[': beg_brk += 1
72 :     if beg_brk == end_brk: break
73 :     org_rev += c
74 :     org_txt = reverse_string( org_rev )
75 :     func_txt = reverse_string( rev_fo[i+1:] )
76 :     items = [ gi_id, params.amap[nrdb], nrdb_id, func_txt.strip(), org_txt.strip() ]
77 :     return items
78 :    
79 :     def reverse_string(string):
80 :     return string[::-1]
81 : tharriso 1.1
82 : tharriso 1.10 def get_eggnog_map(filename):
83 : tharriso 1.2 emap = {}
84 : tharriso 1.1 if filename is None:
85 : tharriso 1.2 return emap
86 : tharriso 1.10 if params.verbose: sys.stdout.write("Parsing file %s ... " %filename)
87 : tharriso 1.2 fhdl = open(filename, 'r')
88 :     try:
89 :     for line in fhdl:
90 :     if line.startswith("#"): continue
91 :     parts = line.strip().split("\t")
92 :     if parts[0] in emap:
93 : tharriso 1.5 emap[ parts[0] ].append( [parts[3], parts[4]] )
94 : tharriso 1.2 else :
95 : tharriso 1.5 emap[ parts[0] ] = [ [parts[3], parts[4]] ]
96 : tharriso 1.2 finally:
97 :     fhdl.close()
98 : tharriso 1.10 if params.verbose: sys.stdout.write("Done\n")
99 : tharriso 1.2 return emap
100 :    
101 : tharriso 1.10 def get_kegg_map(filename):
102 : tharriso 1.2 kmap = {}
103 :     if filename is None:
104 :     return kmap
105 : tharriso 1.10 if params.verbose: sys.stdout.write("Parsing file %s ... " %filename)
106 : tharriso 1.1 for text in kegg_iter(filename):
107 :     rec = get_kegg_rec(text)
108 :     if (not rec.name) or (not rec.description): continue
109 :     names = rec.name.split(', ')
110 :     if len(names) > 1:
111 : tharriso 1.11 kmap[ names[1] ] = [ rec.description, names[0] ]
112 : tharriso 1.10 if params.verbose: sys.stdout.write("Done\n")
113 : tharriso 1.2 return kmap
114 : tharriso 1.1
115 :     def kegg_iter(filename):
116 :     fhdl = file(filename, 'rb')
117 :     recs = ['']
118 :     for data in iter(lambda: fhdl.read(100000), ''):
119 :     recs = (recs[-1] + data).split("\n///\n")
120 :     for rec in recs[:-1]:
121 :     yield rec
122 :    
123 :     def get_kegg_rec(text):
124 :     record = SeqRecord(Seq("",IUPAC.protein), id='', name='', description='', dbxrefs=[], annotations={'organism':''})
125 :     entry_s = entry_re.search(text)
126 :     name_s = name_re.search(text)
127 :     func_s = func_re.search(text)
128 : tharriso 1.5 orth_s = orth_re.search(text)
129 : tharriso 1.1 dbref_s = dbref_re.search(text)
130 :     seq_s = seq_re.search(text)
131 :     if entry_s:
132 :     record.id = entry_s.group(1)
133 :     record.annotations['organism'] = entry_s.group(2).strip()
134 :     if name_s:
135 :     record.name = name_s.group(1).strip()
136 :     if func_s:
137 :     record.description = re.sub('\s+', ' ', func_s.group(1).strip())
138 : tharriso 1.5 if orth_s:
139 :     orths = {}
140 :     for o in filter( lambda y: y, map(lambda x: ko_re.search(x.strip()), orth_s.group(1).strip().split("\n")) ):
141 :     orths[ o.group(1) ] = o.group(2)
142 :     record.annotations['orthology'] = orths
143 : tharriso 1.1 if dbref_s:
144 :     parts = dbref_s.group(1).split()
145 :     if (len(parts) % 2) == 0:
146 :     for i in range(0, len(parts)-1, 2):
147 :     record.dbxrefs.append(parts[i].replace('NCBI-', '') + parts[i+1])
148 :     if seq_s:
149 :     record.seq = Seq( re.sub('\s+', '', seq_s.group(1)), IUPAC.protein )
150 :     return record
151 :    
152 : tharriso 1.10 def format_factory(out_files):
153 : tharriso 1.9 (prot_f, ont_f, seq_f, ref_f, tax_f) = out_files
154 : tharriso 1.10 source = params.source
155 :     form = params.format
156 :     org_desc = params.orghead
157 :     get_ont = params.getont
158 :     get_ctg = params.getctg
159 :     get_tax = params.gettax
160 :     amap = params.amap
161 : tharriso 1.1 if form == 'genbank':
162 : tharriso 1.10 def parse_genbank(rec):
163 : tharriso 1.1 if (not rec) or (not rec.id) or (not rec.seq): return
164 :     cid = rec.id
165 :     cdesc = rec.description.rstrip('.')
166 : tharriso 1.10 seq = str(rec.seq).upper()
167 :     clen = len(seq)
168 : tharriso 1.1 org = rec.annotations['organism']
169 : tharriso 1.3 # only one entry on rec (first feat is source and is not a feature), use first real feature, no contig data
170 :     if len(rec.features) == 2:
171 : tharriso 1.10 md5 = hashlib.md5(seq).hexdigest()
172 : tharriso 1.3 func = ''
173 :     if 'product' in rec.features[1].qualifiers:
174 :     func = rec.features[1].qualifiers['product'][0]
175 : tharriso 1.10 seq_f.write("%s\t%s\n" %(md5, seq))
176 : tharriso 1.5 prot_f.write("\t".join([md5, rec.name, func, org, source]) + "\n")
177 : tharriso 1.9 if get_tax and ('taxonomy' in rec.annotations):
178 :     if rec.annotations['taxonomy'][0] == 'Root':
179 :     x = rec.annotations['taxonomy'].pop(0)
180 :     tax_f.write("%s\t%s;%s\n" %(rec.name, ";".join(rec.annotations['taxonomy']), org))
181 : tharriso 1.3 return
182 :     # multiple entries on rec, use CDS features, get contig data
183 : tharriso 1.1 for feat in rec.features:
184 :     if feat.type == 'CDS':
185 :     if ( (not feat.qualifiers) or (not feat.location) or
186 :     ('translation' not in feat.qualifiers) or
187 :     ('product' not in feat.qualifiers) ): continue
188 : tharriso 1.6 fid = ''
189 :     if 'protein_id' in feat.qualifiers:
190 :     fid = feat.qualifiers['protein_id'][0]
191 :     elif 'locus_tag' in feat.qualifiers:
192 :     fid = feat.qualifiers['locus_tag'][0]
193 :     else:
194 :     continue
195 : tharriso 1.1 seq = feat.qualifiers['translation'][0]
196 :     md5 = hashlib.md5(seq).hexdigest()
197 :     func = feat.qualifiers['product'][0]
198 :     beg = feat.location.start.position
199 :     end = feat.location.end.position
200 :     if feat.strand:
201 :     strd = feat.strand
202 :     else:
203 :     strd = 1
204 :     if (beg > end):
205 :     strd = -1
206 :     beg = feat.location.end.position
207 :     end = feat.location.start.position
208 : tharriso 1.5 # output GO ontology
209 :     if get_ont:
210 :     for gtype in go_types:
211 :     if gtype in feat.qualifiers:
212 :     for goid in feat.qualifiers[gtype]:
213 :     go_m = gb_go_re.match(goid)
214 :     if go_m:
215 : tharriso 1.6 desc = gb_go_rm.sub('', go_m.group(2))
216 : tharriso 1.10 ont_f.write("\t".join([md5, go_m.group(1), desc, 'GO']) + "\n")
217 : tharriso 1.1 seq_f.write("%s\t%s\n" %(md5, seq))
218 : tharriso 1.8 if get_ctg:
219 :     prot_f.write("\t".join([md5, fid, func, org, source, str(beg), str(end), str(strd), cid, cdesc, str(clen)]) + "\n")
220 :     else:
221 :     prot_f.write("\t".join([md5, fid, func, org, source]) + "\n")
222 : tharriso 1.1 if ('db_xref' in feat.qualifiers) and (len(feat.qualifiers['db_xref']) > 0):
223 :     ref_f.write(fid + "\t" + "\t".join(feat.qualifiers['db_xref']) + "\n")
224 :     return parse_genbank
225 :    
226 :     elif form == 'swiss':
227 : tharriso 1.10 def parse_swiss(rec):
228 : tharriso 1.1 if (not rec) or (not rec.id) or (not rec.seq): return
229 : tharriso 1.10 seq = str(rec.seq).upper()
230 :     md5 = hashlib.md5(seq).hexdigest()
231 : tharriso 1.1 func = rec.description
232 :     srch = desc_re.search(func)
233 : tharriso 1.2 if srch: func = srch.group(2)
234 : tharriso 1.10 seq_f.write("%s\t%s\n" %(md5, seq))
235 : tharriso 1.5 prot_f.write("\t".join([md5, rec.id, func, rec.annotations['organism'], source]) + "\n")
236 : tharriso 1.1 if len(rec.dbxrefs) > 0:
237 :     ref_str = rec.id
238 :     for ref in rec.dbxrefs:
239 : tharriso 1.5 go_m = up_go_re.match(ref)
240 :     # output GO ontology
241 :     if go_m and get_ont:
242 : tharriso 1.10 ont_f.write("\t".join([md5, go_m.group(1), func, 'GO']) + "\n")
243 : tharriso 1.1 else:
244 :     ref_str += "\t" + ref
245 :     ref_f.write(ref_str + "\n")
246 :     return parse_swiss
247 :    
248 :     elif form == 'fasta':
249 : tharriso 1.10 def parse_fasta(rec):
250 : tharriso 1.1 if (not rec) or (not rec.id) or (not rec.seq): return
251 : tharriso 1.2 desc = ''
252 : tharriso 1.6 org = ''
253 :     func = ''
254 : tharriso 1.2 hdrs = rec.description.split()
255 : tharriso 1.10 seq = str(rec.seq).upper()
256 :     md5 = hashlib.md5(seq).hexdigest()
257 :     seq_f.write("%s\t%s\n" %(md5, seq))
258 : tharriso 1.2 if len(hdrs) > 1:
259 :     hdrs.pop(0)
260 :     desc = " ".join(hdrs)
261 :     if desc.startswith("("): desc = desc.strip(')(')
262 : tharriso 1.9 if desc.startswith("|"): desc = desc.strip('| ')
263 : tharriso 1.6 if org_desc: org = desc
264 :     else: func = desc
265 :     if get_ont and (rec.id in amap):
266 :     for f in amap[rec.id]:
267 :     prot_f.write("\t".join([md5, rec.id, f[1], org, source]) + "\n")
268 :     ogid_m = ogid_re.match(f[0])
269 :     if ogid_m:
270 : tharriso 1.7 ont_f.write("\t".join([md5, f[0], f[1], ogid_m.group(1)]) + "\n")
271 : tharriso 1.1 else:
272 : tharriso 1.6 prot_f.write("\t".join([md5, rec.id, func, org, source]) + "\n")
273 : tharriso 1.1 return parse_fasta
274 :    
275 : tharriso 1.10 elif form == 'nr':
276 :     def parse_nr(rec):
277 :     if (not rec) or (not rec.description) or (not rec.seq): return
278 :     get_seq = False
279 :     hdrs = rec.description.split('\x01')
280 :     seq = str(rec.seq).upper()
281 :     md5 = hashlib.md5(seq).hexdigest()
282 :     if len(hdrs) > 0:
283 :     for h in hdrs:
284 :     info = parse_nr_header(h)
285 :     if len(info) > 0:
286 :     (gi_id, nrdb, nrdb_id, func, org) = info
287 :     get_seq = True
288 :     prot_f.write("\t".join([md5, nrdb_id, func, org, nrdb]) + "\n")
289 :     ref_f.write("%s\tGI:%s\n"%(nrdb_id, gi_id))
290 :     if get_seq:
291 :     seq_f.write("%s\t%s\n" %(md5, seq))
292 :     return parse_nr
293 :    
294 : tharriso 1.1 elif form == 'kegg':
295 : tharriso 1.10 def parse_kegg(text):
296 : tharriso 1.1 rec = get_kegg_rec(text)
297 :     if (not rec.id) or (not rec.description) or (not rec.seq): return
298 : tharriso 1.10 seq = str(rec.seq).upper()
299 :     md5 = hashlib.md5(seq).hexdigest()
300 : tharriso 1.5 org = rec.annotations['organism']
301 : tharriso 1.11 code = ""
302 : tharriso 1.5 orth = []
303 : tharriso 1.2 if org in amap:
304 : tharriso 1.11 (org, code) = amap[org]
305 :     code += ":"
306 : tharriso 1.5 # output KO ontology
307 :     if get_ont and ('orthology' in rec.annotations):
308 :     orth = rec.annotations['orthology']
309 :     for oid, odesc in orth.iteritems():
310 : tharriso 1.7 ont_f.write("\t".join([md5, oid, odesc, 'KO']) + "\n")
311 : tharriso 1.10 seq_f.write("%s\t%s\n" %(md5, seq))
312 : tharriso 1.11 prot_f.write("\t".join([md5, code + rec.id, rec.description, org, source]) + "\n")
313 : tharriso 1.1 if len(rec.dbxrefs) > 0:
314 :     ref_f.write(rec.id + "\t" + "\t".join(rec.dbxrefs) + "\n")
315 :     return parse_kegg
316 :    
317 :     else:
318 :     return None
319 :    
320 : tharriso 1.10 def process_file(infile):
321 :     o_files = []
322 :     o_hdls = []
323 :     fformat = params.format
324 :     fname = os.path.basename(infile)
325 :     for e in file_ext: o_files.append( os.path.join(params.outdir, fname + e) )
326 :     for f in o_files: o_hdls.append( open(f, 'w') )
327 :    
328 :     parse_format = format_factory( o_hdls )
329 :     if not parse_format:
330 :     sys.stderr.write("Invalid format %s\n"%fformat)
331 :     sys.exit(1)
332 :    
333 :     if params.verbose: sys.stdout.write("Parsing file %s ...\n" %infile)
334 :     if fformat == 'kegg':
335 :     for rec in kegg_iter(infile):
336 :     parse_format(rec)
337 :     else:
338 :     if fformat == 'nr': fformat = 'fasta'
339 :     for rec in SeqIO.parse(infile, fformat):
340 :     parse_format(rec)
341 :    
342 :     for h in o_hdls: h.close()
343 :     return os.path.join(params.outdir, fname)
344 :    
345 : tharriso 1.1
346 :     usage = "usage: %prog [options] source input_file1 [input_file2 input_file3 ...]" + __doc__
347 :    
348 :     def main(args):
349 : tharriso 1.10 global params
350 : tharriso 1.1 parser = OptionParser(usage=usage)
351 :     parser.add_option("-f", "--format", dest="format", metavar="FORMAT", default="fasta",
352 : tharriso 1.10 help="FORMAT inputed file is in. Must be one of following: genbank, kegg, swiss, nr, fasta [default is 'fasta']")
353 :     parser.add_option("-n", "--nr_dbs", dest="nrdbs", metavar="DBs", default="ref,gb",
354 :     help="Comma seperated list of databases to parse out of ncbi nr, from following: ref, gb, emb, dbj, pir, prf, pdb [default is 'ref,gb']")
355 :     parser.add_option("-p", "--processes", dest="processes", metavar="NUM_PROCESSES", type="int", default=4, help="Number of processes to use [default '4']")
356 : tharriso 1.2 parser.add_option("-k", "--kegg_map", dest="keggmap", metavar="FILE", default=None, help="Optional KEGG genome FILE for org name mapping")
357 :     parser.add_option("-e", "--eggnog_map", dest="eggnogmap", metavar="FILE", default=None, help="Optional eggNOG orthgroups tabed FILE for func mapping")
358 : tharriso 1.10 parser.add_option("-d", "--out_dir", dest="outdir", metavar="DIR", default="", help="DIR to write output [default is current dir]")
359 : tharriso 1.1 parser.add_option("-o", "--org_header", dest="orgheader", action="store_true", default=False, help="For fasta files, header description is organism [default is function]")
360 : tharriso 1.5 parser.add_option("-g", "--get_ontology", dest="getont", action="store_true", default=False, help="Output ontology (id, type) for proteins with mapped ontology [default is off]")
361 : tharriso 1.8 parser.add_option("-c", "--get_contig", dest="getcontig", action="store_true", default=False, help="Output contig info for organism genbank files [default is off]")
362 : tharriso 1.9 parser.add_option("-t", "--get_tax", dest="gettax", action="store_true", default=False, help="Output taxonomy string for genbank files [default is off]")
363 : tharriso 1.1 parser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False, help="Wordy [default is off]")
364 :    
365 :     (opts, args) = parser.parse_args()
366 :     if len(args) < 2:
367 :     parser.error("Incorrect number of arguments")
368 : tharriso 1.10 sfiles = filter(lambda x: os.path.isfile(x), args[1:])
369 :     scount = len(sfiles)
370 :    
371 :     params.source = args[0]
372 :     params.format = opts.format
373 :     params.verbose = opts.verbose
374 :     params.outdir = opts.outdir
375 :     params.orghead = opts.orgheader
376 :     params.getont = opts.getont
377 :     params.getctg = opts.getcontig
378 :     params.gettax = opts.gettax
379 :    
380 :     if (params.format == 'nr') and opts.nrdbs:
381 :     for d in opts.nrdbs.split(','):
382 :     if d in nr_types:
383 :     params.amap[d] = nr_types[d]
384 :     elif (params.format == 'kegg') and opts.keggmap and os.path.isfile(opts.keggmap):
385 :     params.amap = get_kegg_map(opts.keggmap)
386 :     elif (params.format == 'fasta') and opts.eggnogmap and os.path.isfile(opts.eggnogmap):
387 :     params.amap = get_eggnog_map(opts.eggnogmap)
388 : tharriso 1.1
389 : tharriso 1.10 if scount < opts.processes:
390 :     min_proc = scount
391 :     else:
392 :     min_proc = opts.processes
393 : tharriso 1.2
394 : tharriso 1.10 if min_proc == 1:
395 :     if params.verbose: sys.stdout.write("Parsing %d %s files, single threaded\n"%(scount, params.format))
396 :     rfiles = []
397 :     for f in sfiles:
398 :     r = process_file(f)
399 :     rfiles.append(r)
400 :     else:
401 :     if params.verbose: sys.stdout.write("Parsing %d %s files using %d threades\n"%(scount, params.format, min_proc))
402 :     pool = Pool(processes=min_proc)
403 :     rfiles = pool.map(process_file, sfiles, 1)
404 :     pool.close()
405 :     pool.join()
406 :     if params.verbose: sys.stdout.write("Done\n")
407 : tharriso 1.9
408 : tharriso 1.10 if params.verbose: sys.stdout.write("Merging %d files ... "%len(rfiles))
409 : tharriso 1.9 for e in file_ext:
410 : tharriso 1.10 out_file = os.path.join(params.outdir, params.source + e)
411 :     file_set = map( lambda x: x + e, rfiles )
412 :     if os.path.isfile(out_file):
413 :     os.remove(out_file)
414 :     os.system( "cat %s | sort -u > %s"%(" ".join(file_set), out_file) )
415 :     for f in file_set:
416 : tharriso 1.9 os.remove(f)
417 : tharriso 1.10 if os.path.isfile(out_file) and (os.path.getsize(out_file) == 0):
418 :     os.remove(out_file)
419 :     if params.verbose: sys.stdout.write("Done\n")
420 : tharriso 1.9
421 : tharriso 1.10 if params.verbose: sys.stdout.write("All Done\n")
422 : tharriso 1.1
423 :     if __name__ == "__main__":
424 : tharriso 1.10 sys.exit( main(sys.argv) )

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3