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

Annotation of /Babel/bin/source2ach.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.7 - (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 :     from Bio import SeqIO
6 :     from Bio.Seq import Seq
7 :     from Bio.SeqRecord import SeqRecord
8 :     from Bio.Alphabet import IUPAC
9 :    
10 :     __doc__ = """
11 :     Script to take a repository file from the following formats:
12 :     genbank, kegg, swiss, fasta
13 :     and output the following tab seperated files:
14 :    
15 :     SOURCE.md52id2func:
16 :     md5, id, function, organism, source, beg_pos*, end_pos*, strand*, contig_id*, contig_desc*, contig_length*
17 : tharriso 1.5 SOURCE.ms52id2ont:
18 :     md5, id, function, ontology, source
19 : tharriso 1.1 SOURCE.md52seq:
20 :     md5, sequence
21 : tharriso 1.4 SOURCE.id2xref:
22 : tharriso 1.1 id, external refrence 1, [external refrence 2, external refrence 3, ...]
23 :    
24 :     Values with * are optional, only genbank files contain that data."""
25 :    
26 : tharriso 1.2 desc_re = re.compile('(Rec|Sub)Name: Full=(.*?);')
27 : tharriso 1.1 entry_re = re.compile('^ENTRY\s+(\S+)\s+CDS\s+(.*)$', re.MULTILINE)
28 :     name_re = re.compile('^NAME\s+(.*)$', re.MULTILINE)
29 :     func_re = re.compile('^DEFINITION\s+(.*?)^\S', re.DOTALL | re.MULTILINE)
30 : tharriso 1.5 orth_re = re.compile('^ORTHOLOGY\s+(.*?)^\S', re.DOTALL | re.MULTILINE)
31 : tharriso 1.1 dbref_re = re.compile('^DBLINKS\s+(.*?)^\S', re.DOTALL | re.MULTILINE)
32 :     seq_re = re.compile('^AASEQ\s+\d+\s+(.*?)^\S', re.DOTALL | re.MULTILINE)
33 : tharriso 1.5 up_go_re = re.compile('^GO:GO:(.*)')
34 :     gb_go_re = re.compile('^GO:(\d+)\s+-\s+(.*)')
35 : tharriso 1.6 gb_go_rm = re.compile('( \[Evidence [A-Z]+\])')
36 : tharriso 1.5 ko_re = re.compile('^(K\d+)\s+(.*)')
37 :     ogid_re = re.compile('^(\S+?OG)\d+')
38 :     go_types = ['GO_function', 'GO_process', 'GO_component']
39 : tharriso 1.1
40 : tharriso 1.6 def get_eggnog_map(filename, verb):
41 : tharriso 1.2 emap = {}
42 : tharriso 1.1 if filename is None:
43 : tharriso 1.2 return emap
44 : tharriso 1.6 if verb: sys.stdout.write("Parsing file %s ... " %filename)
45 : tharriso 1.2 fhdl = open(filename, 'r')
46 :     try:
47 :     for line in fhdl:
48 :     if line.startswith("#"): continue
49 :     parts = line.strip().split("\t")
50 :     if parts[0] in emap:
51 : tharriso 1.5 emap[ parts[0] ].append( [parts[3], parts[4]] )
52 : tharriso 1.2 else :
53 : tharriso 1.5 emap[ parts[0] ] = [ [parts[3], parts[4]] ]
54 : tharriso 1.2 finally:
55 :     fhdl.close()
56 : tharriso 1.6 if verb: sys.stdout.write("Done\n")
57 : tharriso 1.2 return emap
58 :    
59 : tharriso 1.6 def get_kegg_map(filename, verb):
60 : tharriso 1.2 kmap = {}
61 :     if filename is None:
62 :     return kmap
63 : tharriso 1.6 if verb: sys.stdout.write("Parsing file %s ... " %filename)
64 : tharriso 1.1 for text in kegg_iter(filename):
65 :     rec = get_kegg_rec(text)
66 :     if (not rec.name) or (not rec.description): continue
67 :     names = rec.name.split(', ')
68 :     if len(names) > 1:
69 : tharriso 1.2 kmap[ names[1] ] = rec.description
70 : tharriso 1.6 if verb: sys.stdout.write("Done\n")
71 : tharriso 1.2 return kmap
72 : tharriso 1.1
73 :     def kegg_iter(filename):
74 :     fhdl = file(filename, 'rb')
75 :     recs = ['']
76 :     for data in iter(lambda: fhdl.read(100000), ''):
77 :     recs = (recs[-1] + data).split("\n///\n")
78 :     for rec in recs[:-1]:
79 :     yield rec
80 :    
81 :     def get_kegg_rec(text):
82 :     record = SeqRecord(Seq("",IUPAC.protein), id='', name='', description='', dbxrefs=[], annotations={'organism':''})
83 :     entry_s = entry_re.search(text)
84 :     name_s = name_re.search(text)
85 :     func_s = func_re.search(text)
86 : tharriso 1.5 orth_s = orth_re.search(text)
87 : tharriso 1.1 dbref_s = dbref_re.search(text)
88 :     seq_s = seq_re.search(text)
89 :     if entry_s:
90 :     record.id = entry_s.group(1)
91 :     record.annotations['organism'] = entry_s.group(2).strip()
92 :     if name_s:
93 :     record.name = name_s.group(1).strip()
94 :     if func_s:
95 :     record.description = re.sub('\s+', ' ', func_s.group(1).strip())
96 : tharriso 1.5 if orth_s:
97 :     orths = {}
98 :     for o in filter( lambda y: y, map(lambda x: ko_re.search(x.strip()), orth_s.group(1).strip().split("\n")) ):
99 :     orths[ o.group(1) ] = o.group(2)
100 :     record.annotations['orthology'] = orths
101 : tharriso 1.1 if dbref_s:
102 :     parts = dbref_s.group(1).split()
103 :     if (len(parts) % 2) == 0:
104 :     for i in range(0, len(parts)-1, 2):
105 :     record.dbxrefs.append(parts[i].replace('NCBI-', '') + parts[i+1])
106 :     if seq_s:
107 :     record.seq = Seq( re.sub('\s+', '', seq_s.group(1)), IUPAC.protein )
108 :     return record
109 :    
110 : tharriso 1.5 def format_factory(prot_f, ont_f, seq_f, ref_f, source, form, org_desc, get_ont):
111 : tharriso 1.1 if form == 'genbank':
112 : tharriso 1.2 def parse_genbank(rec, amap):
113 : tharriso 1.1 if (not rec) or (not rec.id) or (not rec.seq): return
114 :     cid = rec.id
115 :     cdesc = rec.description.rstrip('.')
116 :     clen = len(rec.seq)
117 :     org = rec.annotations['organism']
118 : tharriso 1.3 # only one entry on rec (first feat is source and is not a feature), use first real feature, no contig data
119 :     if len(rec.features) == 2:
120 :     md5 = hashlib.md5(str(rec.seq)).hexdigest()
121 :     func = ''
122 :     if 'product' in rec.features[1].qualifiers:
123 :     func = rec.features[1].qualifiers['product'][0]
124 :     seq_f.write("%s\t%s\n" %(md5, rec.seq))
125 : tharriso 1.5 prot_f.write("\t".join([md5, rec.name, func, org, source]) + "\n")
126 : tharriso 1.3 return
127 :     # multiple entries on rec, use CDS features, get contig data
128 : tharriso 1.1 for feat in rec.features:
129 :     if feat.type == 'CDS':
130 :     if ( (not feat.qualifiers) or (not feat.location) or
131 :     ('translation' not in feat.qualifiers) or
132 :     ('product' not in feat.qualifiers) ): continue
133 : tharriso 1.6 fid = ''
134 :     if 'protein_id' in feat.qualifiers:
135 :     fid = feat.qualifiers['protein_id'][0]
136 :     elif 'locus_tag' in feat.qualifiers:
137 :     fid = feat.qualifiers['locus_tag'][0]
138 :     else:
139 :     continue
140 : tharriso 1.1 seq = feat.qualifiers['translation'][0]
141 :     md5 = hashlib.md5(seq).hexdigest()
142 :     func = feat.qualifiers['product'][0]
143 :     beg = feat.location.start.position
144 :     end = feat.location.end.position
145 :     if feat.strand:
146 :     strd = feat.strand
147 :     else:
148 :     strd = 1
149 :     if (beg > end):
150 :     strd = -1
151 :     beg = feat.location.end.position
152 :     end = feat.location.start.position
153 : tharriso 1.5 # output GO ontology
154 :     if get_ont:
155 :     for gtype in go_types:
156 :     if gtype in feat.qualifiers:
157 :     for goid in feat.qualifiers[gtype]:
158 :     go_m = gb_go_re.match(goid)
159 :     if go_m:
160 : tharriso 1.6 desc = gb_go_rm.sub('', go_m.group(2))
161 : tharriso 1.7 ont_f.write("\t".join([md5, go_m.group(1), desc, gtype.replace('_',':')]) + "\n")
162 : tharriso 1.1 seq_f.write("%s\t%s\n" %(md5, seq))
163 : tharriso 1.5 prot_f.write("\t".join([md5, fid, func, org, source, str(beg), str(end), str(strd), cid, cdesc, str(clen)]) + "\n")
164 : tharriso 1.1 if ('db_xref' in feat.qualifiers) and (len(feat.qualifiers['db_xref']) > 0):
165 :     ref_f.write(fid + "\t" + "\t".join(feat.qualifiers['db_xref']) + "\n")
166 :     return parse_genbank
167 :    
168 :     elif form == 'swiss':
169 : tharriso 1.2 def parse_swiss(rec, amap):
170 : tharriso 1.1 if (not rec) or (not rec.id) or (not rec.seq): return
171 :     md5 = hashlib.md5(str(rec.seq)).hexdigest()
172 :     func = rec.description
173 :     srch = desc_re.search(func)
174 : tharriso 1.2 if srch: func = srch.group(2)
175 : tharriso 1.1 seq_f.write("%s\t%s\n" %(md5, str(rec.seq)))
176 : tharriso 1.5 prot_f.write("\t".join([md5, rec.id, func, rec.annotations['organism'], source]) + "\n")
177 : tharriso 1.1 if len(rec.dbxrefs) > 0:
178 :     ref_str = rec.id
179 :     for ref in rec.dbxrefs:
180 : tharriso 1.5 go_m = up_go_re.match(ref)
181 :     # output GO ontology
182 :     if go_m and get_ont:
183 : tharriso 1.7 ont_f.write("\t".join([md5, go_m.group(1), '', 'GO']) + "\n")
184 : tharriso 1.1 else:
185 :     ref_str += "\t" + ref
186 :     ref_f.write(ref_str + "\n")
187 :     return parse_swiss
188 :    
189 :     elif form == 'fasta':
190 : tharriso 1.2 def parse_fasta(rec, amap):
191 : tharriso 1.1 if (not rec) or (not rec.id) or (not rec.seq): return
192 : tharriso 1.2 desc = ''
193 : tharriso 1.6 org = ''
194 :     func = ''
195 : tharriso 1.2 hdrs = rec.description.split()
196 : tharriso 1.1 md5 = hashlib.md5(str(rec.seq)).hexdigest()
197 :     seq_f.write("%s\t%s\n" %(md5, str(rec.seq)))
198 : tharriso 1.2 if len(hdrs) > 1:
199 :     hdrs.pop(0)
200 :     desc = " ".join(hdrs)
201 :     if desc.startswith("("): desc = desc.strip(')(')
202 : tharriso 1.6 if org_desc: org = desc
203 :     else: func = desc
204 :     if get_ont and (rec.id in amap):
205 :     for f in amap[rec.id]:
206 :     prot_f.write("\t".join([md5, rec.id, f[1], org, source]) + "\n")
207 :     ogid_m = ogid_re.match(f[0])
208 :     if ogid_m:
209 : tharriso 1.7 ont_f.write("\t".join([md5, f[0], f[1], ogid_m.group(1)]) + "\n")
210 : tharriso 1.1 else:
211 : tharriso 1.6 prot_f.write("\t".join([md5, rec.id, func, org, source]) + "\n")
212 : tharriso 1.1 return parse_fasta
213 :    
214 :     elif form == 'kegg':
215 : tharriso 1.2 def parse_kegg(text, amap):
216 : tharriso 1.1 rec = get_kegg_rec(text)
217 :     if (not rec.id) or (not rec.description) or (not rec.seq): return
218 : tharriso 1.5 md5 = hashlib.md5(str(rec.seq)).hexdigest()
219 :     org = rec.annotations['organism']
220 :     orth = []
221 : tharriso 1.2 if org in amap:
222 :     org = amap[org]
223 : tharriso 1.5 # output KO ontology
224 :     if get_ont and ('orthology' in rec.annotations):
225 :     orth = rec.annotations['orthology']
226 :     for oid, odesc in orth.iteritems():
227 : tharriso 1.7 ont_f.write("\t".join([md5, oid, odesc, 'KO']) + "\n")
228 : tharriso 1.1 seq_f.write("%s\t%s\n" %(md5, str(rec.seq)))
229 : tharriso 1.5 prot_f.write("\t".join([md5, rec.id, rec.description, org, source]) + "\n")
230 : tharriso 1.1 if len(rec.dbxrefs) > 0:
231 :     ref_f.write(rec.id + "\t" + "\t".join(rec.dbxrefs) + "\n")
232 :     return parse_kegg
233 :    
234 :     else:
235 :     return None
236 :    
237 :    
238 :     usage = "usage: %prog [options] source input_file1 [input_file2 input_file3 ...]" + __doc__
239 :    
240 :     def main(args):
241 :     parser = OptionParser(usage=usage)
242 :     parser.add_option("-f", "--format", dest="format", metavar="FORMAT", default="fasta",
243 :     help="FORMAT inputed file is in. Must be one of following: genbank, kegg, swiss, fasta [default is fasta]")
244 : tharriso 1.2 parser.add_option("-k", "--kegg_map", dest="keggmap", metavar="FILE", default=None, help="Optional KEGG genome FILE for org name mapping")
245 :     parser.add_option("-e", "--eggnog_map", dest="eggnogmap", metavar="FILE", default=None, help="Optional eggNOG orthgroups tabed FILE for func mapping")
246 : tharriso 1.1 parser.add_option("-d", "--out_dir", dest="outdir", metavar="DIR", default=None, help="DIR to write output [default is current dir]")
247 :     parser.add_option("-o", "--org_header", dest="orgheader", action="store_true", default=False, help="For fasta files, header description is organism [default is function]")
248 : 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]")
249 : tharriso 1.1 parser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False, help="Wordy [default is off]")
250 :    
251 :     (opts, args) = parser.parse_args()
252 :     if len(args) < 2:
253 :     parser.error("Incorrect number of arguments")
254 :     source = args[0]
255 :     files = args[1:]
256 :     outdir = ''
257 :     if opts.outdir: outdir = opts.outdir
258 :    
259 : tharriso 1.6 keggmap = get_kegg_map(opts.keggmap, opts.verbose)
260 :     eggnogmap = get_eggnog_map(opts.eggnogmap, opts.verbose)
261 : tharriso 1.2
262 : tharriso 1.5 prot_file = open( os.path.join(outdir, source + ".md52id2func"), 'w' )
263 :     ont_file = open( os.path.join(outdir, source + ".md52id2ont"), 'w' )
264 : tharriso 1.1 seq_file = open( os.path.join(outdir, source + ".md52seq"), 'w' )
265 :     ref_file = open( os.path.join(outdir, source + ".id2xref"), 'w' )
266 :    
267 : tharriso 1.5 parse_format = format_factory( prot_file, ont_file, seq_file, ref_file, source, opts.format, opts.orgheader, opts.getont )
268 : tharriso 1.1 if not parse_format:
269 :     parser.error("Incorrect format entered")
270 :    
271 :     for f in files:
272 :     if opts.verbose:
273 :     sys.stdout.write("Parsing file %s ...\n" %f)
274 :     if (opts.format == 'kegg'):
275 :     for rec in kegg_iter(f):
276 : tharriso 1.2 parse_format(rec, keggmap)
277 : tharriso 1.1 else:
278 :     for rec in SeqIO.parse(f, opts.format):
279 : tharriso 1.2 parse_format(rec, eggnogmap)
280 : tharriso 1.1
281 : tharriso 1.5 prot_file.close()
282 :     ont_file.close()
283 : tharriso 1.1 seq_file.close()
284 :     ref_file.close()
285 :     if opts.verbose:
286 :     sys.stdout.write("All Done\n")
287 :    
288 :     if __name__ == "__main__":
289 :     sys.exit(main(sys.argv))

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3