Repository navigation
Expand file tree
/
Copy pathsource2ach.py
More file actions
executable file
·538 lines (503 loc) · 22.9 KB
/
Copy pathsource2ach.py
File metadata and controls
executable file
·538 lines (503 loc) · 22.9 KB
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
#!/usr/bin/env python
import os, sys, shutil, re, hashlib, json
from optparse import OptionParser
from multiprocessing import Pool
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import IUPAC
__doc__ = """
Script to take a repository file from the following formats:
genbank, kegg, swiss, fasta
and output the following tab seperated files:
SOURCE.md52id2func:
md5, id, function, organism, source, beg_pos*, end_pos*, strand*, contig_id*, contig_desc*, contig_length*
SOURCE.ms52id2ont:
md5, id, function, ontology, source
SOURCE.md52seq:
md5, sequence
SOURCE.id2xref:
id, external refrence 1, [external refrence 2, external refrence 3, ...]
SOURCE.id2tax:
id, genbank tax string
Values with * are optional, only genbank files contain that data."""
class Info:
def __init__(self):
self.source = ''
self.format = 'fasta'
self.verbose = False
self.outdir = ''
self.annhead = ''
self.getont = False
self.getctg = False
self.gettax = False
self.amap = {}
self.interpro = False
func_map = {'LSU': '23S/28S ribosomal RNA', 'SSU': '16S/18S ribosomal RNA'}
desc_re = re.compile('(Rec|Sub)Name: Full=(.*?);')
entry_re = re.compile('^ENTRY\s+(\S+)\s+CDS\s+(.*)$', re.MULTILINE)
name_re = re.compile('^NAME\s+(.*)$', re.MULTILINE)
func_re = re.compile('^DEFINITION\s+(.*?)^\S', re.DOTALL | re.MULTILINE)
orth_re = re.compile('^ORTHOLOGY\s+(.*?)^\S', re.DOTALL | re.MULTILINE)
dbref_re = re.compile('^DBLINKS\s+(.*?)^\S', re.DOTALL | re.MULTILINE)
seq_re = re.compile('^AASEQ\s+\d+\s+(.*?)^\S', re.DOTALL | re.MULTILINE)
up_ip_re = re.compile('^InterPro:(.*)')
up_go_re = re.compile('^GO:(GO:.*)')
gb_go_re = re.compile('^(GO:\d+)\s+-\s+(.*)')
gb_go_rm = re.compile('( \[Evidence [A-Z]+\])')
gg_re = re.compile('^[kpcofgs]__(\S+)$')
ko_re = re.compile('^(K\d+)\s+(.*)')
ogid_re = re.compile('^(\S+?OG)\d+')
nr_re = re.compile('^gi\|(\d+)\|(\w+)\|(\S+)\|\S*?\s+(.*\])$')
nr_types = {'ref': 'RefSeq', 'gb': 'GenBank', 'emb': 'EMBL', 'dbj': 'DDBJ', 'pir': 'PIR', 'prf': 'PRF', 'pdb': 'PDB'}
go_types = ['GO_function', 'GO_process', 'GO_component']
file_ext = [".md52id2func", ".md52id2ont", ".md52seq", ".id2xref", ".id2tax"]
params = Info()
def parse_nr_header(line):
items = []
hdr_set = nr_re.match(line)
if hdr_set:
(gi_id, nrdb, nrdb_id, func_org) = hdr_set.groups()
if nrdb in params.amap:
func_txt, org_txt = parse_bracket_line(func_org, '[', ']', 1)
items = [ gi_id, params.amap[nrdb], nrdb_id, func_txt, org_txt ]
return items
def parse_bracket_line(line, beg_delim, end_delim, rev):
in_bracket = ''
if rev:
line = reverse_string(line)
end_break = 0
beg_break = 0
for i, c in enumerate(line):
if c == end_delim: end_break += 1
if c == beg_delim: beg_break += 1
if beg_break == end_break: break
if i > 0: in_bracket += c
if rev:
bracket_txt = reverse_string(in_bracket).strip()
remain_txt = reverse_string(line[i+1:]).strip()
return remain_txt, bracket_txt
else:
bracket_txt = in_bracket.strip()
remain_txt = line[i+1:].strip()
return bracket_txt, remain_txt
def reverse_string(string):
return string[::-1]
def get_interpro_map(filename):
imap = {}
if filename is None:
return imap
if params.verbose: sys.stdout.write("Parsing file %s ... " %filename)
fhdl = open(filename, 'r')
try:
for line in fhdl:
parts = line.strip().split("\t")
imap[ parts[0] ] = parts[1]
finally:
fhdl.close()
if params.verbose: sys.stdout.write("Done\n")
return imap
def get_eggnog_map(filename):
emap = {}
if filename is None:
return emap
if params.verbose: sys.stdout.write("Parsing file %s ... " %filename)
fhdl = open(filename, 'r')
try:
for line in fhdl:
if line.startswith("#"): continue
parts = line.strip().split("\t")
if parts[0] in emap:
emap[ parts[0] ].append( [parts[3], parts[4]] )
else :
emap[ parts[0] ] = [ [parts[3], parts[4]] ]
finally:
fhdl.close()
if params.verbose: sys.stdout.write("Done\n")
return emap
def get_kegg_map(filename):
kmap = {}
if filename is None:
return kmap
if params.verbose: sys.stdout.write("Parsing file %s ... " %filename)
for text in kegg_iter(filename):
rec = get_kegg_rec(text)
if (not rec.name) or (not rec.description): continue
names = rec.name.split(', ')
if len(names) > 1:
kmap[ names[1] ] = [ rec.description, names[0] ]
if params.verbose: sys.stdout.write("Done\n")
return kmap
def kegg_iter(filename):
fhdl = file(filename, 'rb')
recs = ['']
for data in iter(lambda: fhdl.read(100000), ''):
recs = (recs[-1] + data).split("\n///\n")
for rec in recs[:-1]:
yield rec
def get_kegg_rec(text):
record = SeqRecord(Seq("",IUPAC.protein), id='', name='', description='', dbxrefs=[], annotations={'organism':''})
entry_s = entry_re.search(text)
name_s = name_re.search(text)
func_s = func_re.search(text)
orth_s = orth_re.search(text)
dbref_s = dbref_re.search(text)
seq_s = seq_re.search(text)
if entry_s:
record.id = entry_s.group(1)
record.annotations['organism'] = entry_s.group(2).strip()
if name_s:
record.name = name_s.group(1).strip()
if func_s:
record.description = re.sub('\s+', ' ', func_s.group(1).strip())
if orth_s:
orths = {}
for o in filter( lambda y: y, map(lambda x: ko_re.search(x.strip()), orth_s.group(1).strip().split("\n")) ):
orths[ o.group(1) ] = o.group(2)
record.annotations['orthology'] = orths
if dbref_s:
parts = dbref_s.group(1).split()
if (len(parts) % 2) == 0:
for i in range(0, len(parts)-1, 2):
record.dbxrefs.append(parts[i].replace('NCBI-', '') + parts[i+1])
if seq_s:
record.seq = Seq( re.sub('\s+', '', seq_s.group(1)), IUPAC.protein )
return record
def format_factory(out_files):
(prot_f, ont_f, seq_f, ref_f, tax_f) = out_files
source = params.source
form = params.format
ann_desc = params.annhead
get_ont = params.getont
get_ctg = params.getctg
get_tax = params.gettax
get_ip = params.interpro
amap = params.amap
if form == 'genbank':
def parse_genbank(rec):
if (not rec) or (not rec.id) or (not rec.seq): return
cid = rec.id
cdesc = rec.description.rstrip('.')
seq = str(rec.seq).upper()
clen = len(seq)
if 'organism' in rec.annotations:
org = rec.annotations['organism']
elif (rec.features[0].type == 'source') and ('organism' in rec.features[0].qualifiers):
org = rec.features[0].qualifiers['organism'][0]
else:
return
# only one entry on rec (first feat is source and is not a feature), use first real feature, no contig data
if len(rec.features) == 2:
md5 = hashlib.md5(seq).hexdigest()
func = ''
if 'product' in rec.features[1].qualifiers:
func = rec.features[1].qualifiers['product'][0]
seq_f.write("%s\t%s\n" %(md5, seq))
prot_f.write("\t".join([md5, rec.name, func, org, source]) + "\n")
if get_tax and ('taxonomy' in rec.annotations):
if rec.annotations['taxonomy'][0] == 'Root':
x = rec.annotations['taxonomy'].pop(0)
tax_f.write("%s\t%s;%s\n" %(rec.name, ";".join(rec.annotations['taxonomy']), org))
return
# multiple entries on rec, use CDS features, get contig data
for feat in rec.features:
if feat.type == 'CDS':
if ( (not feat.qualifiers) or (not feat.location) or
('translation' not in feat.qualifiers) or
('product' not in feat.qualifiers) ): continue
fid = ''
if 'protein_id' in feat.qualifiers:
fid = feat.qualifiers['protein_id'][0]
elif 'locus_tag' in feat.qualifiers:
fid = feat.qualifiers['locus_tag'][0]
else:
continue
seq = feat.qualifiers['translation'][0]
md5 = hashlib.md5(seq).hexdigest()
func = feat.qualifiers['product'][0]
beg = feat.location.start.position
end = feat.location.end.position
if feat.strand:
strd = feat.strand
else:
strd = 1
if (beg > end):
strd = -1
beg = feat.location.end.position
end = feat.location.start.position
"""
# output GO ontology
if get_ont:
for gtype in go_types:
if gtype in feat.qualifiers:
for goid in feat.qualifiers[gtype]:
go_m = gb_go_re.match(goid)
if go_m:
desc = gb_go_rm.sub('', go_m.group(2))
ont_f.write("\t".join([md5, go_m.group(1), desc, 'GO']) + "\n")
"""
seq_f.write("%s\t%s\n" %(md5, seq))
if get_ctg:
prot_f.write("\t".join([md5, fid, func, org, source, str(beg), str(end), str(strd), cid, cdesc, str(clen)]) + "\n")
else:
prot_f.write("\t".join([md5, fid, func, org, source]) + "\n")
if ('db_xref' in feat.qualifiers) and (len(feat.qualifiers['db_xref']) > 0):
ref_f.write(fid + "\t" + "\t".join(feat.qualifiers['db_xref']) + "\n")
return parse_genbank
elif form == 'swiss':
def parse_swiss(rec):
if (not rec) or (not rec.id) or (not rec.seq): return
seq = str(rec.seq).upper()
md5 = hashlib.md5(seq).hexdigest()
if not get_ip:
func = rec.description
srch = desc_re.search(func)
if srch: func = srch.group(2)
seq_f.write("%s\t%s\n" %(md5, seq))
prot_f.write("\t".join([md5, rec.id, func, rec.annotations['organism'], source]) + "\n")
if len(rec.dbxrefs) > 0:
ref_str = rec.id
for ref in rec.dbxrefs:
"""
go_m = up_go_re.match(ref)
# output GO ontology
if go_m and get_ont:
ont_f.write("\t".join([md5, go_m.group(1), func, 'GO']) + "\n")
else:
ref_str += "\t" + ref
"""
ref_str += "\t" + ref
ref_f.write(ref_str + "\n")
elif get_ip and (len(rec.dbxrefs) > 0):
has_ip = 0
for ref in rec.dbxrefs:
ip_m = up_ip_re.match(ref)
if ip_m and (ip_m.group(1) in amap):
has_ip = 1
prot_f.write("\t".join([md5, ip_m.group(1), amap[ip_m.group(1)], rec.annotations['organism'], source]) + "\n")
if has_ip:
seq_f.write("%s\t%s\n" %(md5, seq))
return parse_swiss
elif form == 'fasta':
def parse_fasta(rec):
if (not rec) or (not rec.id) or (not rec.seq): return
desc = ''
org = ''
func = ''
hdrs = rec.description.split()
seq = str(rec.seq).upper()
md5 = hashlib.md5(seq).hexdigest()
seq_f.write("%s\t%s\n" %(md5, seq))
if ann_desc == 'greengenes':
hdrs.pop(0)
hdrs.pop(0)
hdrs.pop()
tax_list = []
org_list = []
for x in hdrs:
gg_m = gg_re.match(x)
if gg_m: tax_list.append(gg_m.group(1))
else: org_list.append(x)
org = " ".join(org_list).split(";")[0]
func = "16S/18S ribosomal RNA"
if get_tax:
tax_f.write("%s\t%s;%s\n" %(rec.id, "".join(tax_list), org))
elif ann_desc == 'fungal':
hdrs.pop(0)
tax_id = 0
if hdrs[0].isdigit():
tax_id = int( hdrs.pop(0) )
tax_str = " ".join(hdrs).rstrip('.')
org = tax_str.split(";")[-1]
func = "ITS ribosomal RNA"
if get_tax:
if tax_id > 0:
tax_f.write("%s\t%d\n" %(rec.id, tax_id))
else:
tax_f.write("%s\t%s\n" %(rec.id, tax_str))
else:
if len(hdrs) > 1:
hdrs.pop(0)
desc = " ".join(hdrs)
if desc.startswith("("): desc = desc.strip(')(')
if desc.startswith("|"): desc = desc.strip('| ')
if ann_desc == 'img':
hdrs.pop(0)
desc = " ".join(hdrs)
if desc[-1] != ']':
return
func, org = parse_bracket_line(desc, '[', ']', 1)
elif ann_desc == 'seed':
if desc[-1] != ')':
return
func, org = parse_bracket_line(desc, '(', ')', 1)
elif ann_desc == 'phantome':
if (desc[-1] != ']') and (desc[0] != '['):
return
_junk, org = parse_bracket_line(desc, '[', ']', 1)
func, _junk = parse_bracket_line(desc, '[', ']', 0)
elif ann_desc == 'organism':
org = desc
if source in func_map:
func = func_map[source]
elif ann_desc == 'function':
func = desc
if get_ont and (rec.id in amap):
for f in amap[rec.id]:
prot_f.write("\t".join([md5, rec.id, f[1], org, source]) + "\n")
ogid_m = ogid_re.match(f[0])
if ogid_m:
ont_f.write("\t".join([md5, f[0], f[1], ogid_m.group(1)]) + "\n")
else:
prot_f.write("\t".join([md5, rec.id, func, org, source]) + "\n")
return parse_fasta
elif form == 'nr':
def parse_nr(rec):
if (not rec) or (not rec.description) or (not rec.seq): return
get_seq = False
hdrs = rec.description.split('\x01')
seq = str(rec.seq).upper()
md5 = hashlib.md5(seq).hexdigest()
if len(hdrs) > 0:
for h in hdrs:
info = parse_nr_header(h)
if len(info) > 0:
(gi_id, nrdb, nrdb_id, func, org) = info
get_seq = True
prot_f.write("\t".join([md5, nrdb_id, func, org, nrdb]) + "\n")
ref_f.write("%s\tGI:%s\n"%(nrdb_id, gi_id))
if get_seq:
seq_f.write("%s\t%s\n" %(md5, seq))
return parse_nr
elif form == 'kegg':
def parse_kegg(text):
rec = get_kegg_rec(text)
if (not rec.id) or (not rec.description) or (not rec.seq): return
seq = str(rec.seq).upper()
md5 = hashlib.md5(seq).hexdigest()
org = rec.annotations['organism']
code = ""
orth = []
if org in amap:
(org, code) = amap[org]
code += ":"
# output KO ontology
if get_ont and ('orthology' in rec.annotations):
orth = rec.annotations['orthology']
for oid, odesc in orth.iteritems():
ont_f.write("\t".join([md5, oid, odesc, 'KO']) + "\n")
seq_f.write("%s\t%s\n" %(md5, seq))
prot_f.write("\t".join([md5, code + rec.id, rec.description, org, source]) + "\n")
if len(rec.dbxrefs) > 0:
ref_f.write(rec.id + "\t" + "\t".join(rec.dbxrefs) + "\n")
return parse_kegg
else:
return None
def process_file(infile):
o_files = []
o_hdls = []
fformat = params.format
fname = os.path.basename(infile)
for e in file_ext: o_files.append( os.path.join(params.outdir, fname + e) )
for f in o_files: o_hdls.append( open(f, 'w') )
parse_format = format_factory( o_hdls )
if not parse_format:
sys.stderr.write("Invalid format %s\n"%fformat)
sys.exit(1)
if params.verbose: sys.stdout.write("Parsing file %s ...\n" %infile)
if fformat == 'kegg':
for rec in kegg_iter(infile):
parse_format(rec)
else:
if fformat == 'nr': fformat = 'fasta'
try:
for rec in SeqIO.parse(infile, fformat):
parse_format(rec)
except Exception as ex:
sys.stderr.write("Unable to parse %s file %s: %s %s\n"%(fformat, infile, type(ex).__name__, ex.args))
for h in o_hdls: h.close()
return os.path.join(params.outdir, fname)
usage = "usage: %prog [options] source input_file1 [input_file2 input_file3 ...]" + __doc__
def main(args):
global params
parser = OptionParser(usage=usage)
parser.add_option("-f", "--format", dest="format", metavar="FORMAT", default="fasta",
help="FORMAT inputed file is in. Must be one of following: genbank, kegg, swiss, nr, fasta [default is 'fasta']")
parser.add_option("-n", "--nr_dbs", dest="nrdbs", metavar="DBs", default="ref,gb",
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']")
parser.add_option("-p", "--processes", dest="processes", metavar="NUM_PROCESSES", type="int", default=4, help="Number of processes to use [default '4']")
parser.add_option("-i", "--interpro_map", dest="intermap", metavar="FILE", default=None, help="Optional InterPro names FILE for func mapping with UniProt")
parser.add_option("-k", "--kegg_map", dest="keggmap", metavar="FILE", default=None, help="Optional KEGG genome FILE for org name mapping")
parser.add_option("-e", "--eggnog_map", dest="eggnogmap", metavar="FILE", default=None, help="Optional eggNOG orthgroups tabed FILE for func mapping")
parser.add_option("-d", "--out_dir", dest="outdir", metavar="DIR", default="", help="DIR to write output [default is current dir]")
parser.add_option("-a", "--annotation_header", dest="annheader", metavar="ANNOTATION", default="function",
help="For fasta files, header description contains annotation. Must be one of following: greengenes, fungal, seed, img, phantome, organism, function [default is function]")
parser.add_option("-o", "--get_ontology", dest="getont", action="store_true", default=False, help="Output ontology (id, type) for proteins with mapped ontology [default is off]")
parser.add_option("-c", "--get_contig", dest="getcontig", action="store_true", default=False, help="Output contig info for organism genbank files [default is off]")
parser.add_option("-t", "--get_tax", dest="gettax", action="store_true", default=False, help="Output taxonomy string for genbank files [default is off]")
parser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False, help="Wordy [default is off]")
parser.add_option("-s", "--sort_dir", dest="sortdir", metavar="DIR", default="/tmp", help="temp DIR to use for sorting [default is /tmp]")
(opts, args) = parser.parse_args()
if len(args) < 2:
parser.error("Incorrect number of arguments")
sfiles = filter(lambda x: os.path.isfile(x), args[1:])
scount = len(sfiles)
if scount == 0:
parser.error("No valid input files found")
params.source = args[0]
params.format = opts.format
params.verbose = opts.verbose
params.outdir = opts.outdir
params.annhead = opts.annheader
params.getont = opts.getont
params.getctg = opts.getcontig
params.gettax = opts.gettax
if (params.format == 'nr') and opts.nrdbs:
for d in opts.nrdbs.split(','):
if d in nr_types:
params.amap[d] = nr_types[d]
elif (params.format == 'kegg') and opts.keggmap and os.path.isfile(opts.keggmap):
params.amap = get_kegg_map(opts.keggmap)
elif (params.format == 'fasta') and opts.eggnogmap and os.path.isfile(opts.eggnogmap):
params.amap = get_eggnog_map(opts.eggnogmap)
elif (params.format == 'swiss') and opts.intermap and os.path.isfile(opts.intermap):
params.amap = get_interpro_map(opts.intermap)
params.interpro = True
if scount < opts.processes:
min_proc = scount
else:
min_proc = opts.processes
if min_proc == 1:
if params.verbose: sys.stdout.write("Parsing %d %s files, single threaded\n"%(scount, params.format))
rfiles = []
for f in sfiles:
r = process_file(f)
rfiles.append(r)
elif min_proc > 1:
if params.verbose: sys.stdout.write("Parsing %d %s files using %d threades\n"%(scount, params.format, min_proc))
pool = Pool(processes=min_proc)
rfiles = pool.map(process_file, sfiles, 1)
pool.close()
pool.join()
else:
parser.error("Invalid processer number: "+min_proc)
if params.verbose: sys.stdout.write("Done\n")
if params.verbose: sys.stdout.write("Merging %d files ... "%len(rfiles))
for e in file_ext:
out_file = os.path.join(params.outdir, params.source + e)
out_tmp = open(out_file+'.tmp', 'w')
file_set = map( lambda x: x + e, rfiles )
if os.path.isfile(out_file):
os.remove(out_file)
for f in file_set:
shutil.copyfileobj( open(f, 'r'), out_tmp )
os.remove(f)
out_tmp.close()
os.system( "sort -T %s -u %s.tmp > %s"%(opts.sortdir, out_file, out_file) )
os.remove(out_file+'.tmp')
if os.path.isfile(out_file) and (os.path.getsize(out_file) == 0):
os.remove(out_file)
if params.verbose: sys.stdout.write("Done\n")
if params.verbose: sys.stdout.write("All Done\n")
if __name__ == "__main__":
sys.exit( main(sys.argv) )