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

Annotation of /Babel/bin/source2ach.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.8 - (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.8 def format_factory(prot_f, ont_f, seq_f, ref_f, source, form, org_desc, get_ont, get_ctg):
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.8 if get_ctg:
164 :     prot_f.write("\t".join([md5, fid, func, org, source, str(beg), str(end), str(strd), cid, cdesc, str(clen)]) + "\n")
165 :     else:
166 :     prot_f.write("\t".join([md5, fid, func, org, source]) + "\n")
167 : tharriso 1.1 if ('db_xref' in feat.qualifiers) and (len(feat.qualifiers['db_xref']) > 0):
168 :     ref_f.write(fid + "\t" + "\t".join(feat.qualifiers['db_xref']) + "\n")
169 :     return parse_genbank
170 :    
171 :     elif form == 'swiss':
172 : tharriso 1.2 def parse_swiss(rec, amap):
173 : tharriso 1.1 if (not rec) or (not rec.id) or (not rec.seq): return
174 :     md5 = hashlib.md5(str(rec.seq)).hexdigest()
175 :     func = rec.description
176 :     srch = desc_re.search(func)
177 : tharriso 1.2 if srch: func = srch.group(2)
178 : tharriso 1.1 seq_f.write("%s\t%s\n" %(md5, str(rec.seq)))
179 : tharriso 1.5 prot_f.write("\t".join([md5, rec.id, func, rec.annotations['organism'], source]) + "\n")
180 : tharriso 1.1 if len(rec.dbxrefs) > 0:
181 :     ref_str = rec.id
182 :     for ref in rec.dbxrefs:
183 : tharriso 1.5 go_m = up_go_re.match(ref)
184 :     # output GO ontology
185 :     if go_m and get_ont:
186 : tharriso 1.7 ont_f.write("\t".join([md5, go_m.group(1), '', 'GO']) + "\n")
187 : tharriso 1.1 else:
188 :     ref_str += "\t" + ref
189 :     ref_f.write(ref_str + "\n")
190 :     return parse_swiss
191 :    
192 :     elif form == 'fasta':
193 : tharriso 1.2 def parse_fasta(rec, amap):
194 : tharriso 1.1 if (not rec) or (not rec.id) or (not rec.seq): return
195 : tharriso 1.2 desc = ''
196 : tharriso 1.6 org = ''
197 :     func = ''
198 : tharriso 1.2 hdrs = rec.description.split()
199 : tharriso 1.1 md5 = hashlib.md5(str(rec.seq)).hexdigest()
200 :     seq_f.write("%s\t%s\n" %(md5, str(rec.seq)))
201 : tharriso 1.2 if len(hdrs) > 1:
202 :     hdrs.pop(0)
203 :     desc = " ".join(hdrs)
204 :     if desc.startswith("("): desc = desc.strip(')(')
205 : tharriso 1.6 if org_desc: org = desc
206 :     else: func = desc
207 :     if get_ont and (rec.id in amap):
208 :     for f in amap[rec.id]:
209 :     prot_f.write("\t".join([md5, rec.id, f[1], org, source]) + "\n")
210 :     ogid_m = ogid_re.match(f[0])
211 :     if ogid_m:
212 : tharriso 1.7 ont_f.write("\t".join([md5, f[0], f[1], ogid_m.group(1)]) + "\n")
213 : tharriso 1.1 else:
214 : tharriso 1.6 prot_f.write("\t".join([md5, rec.id, func, org, source]) + "\n")
215 : tharriso 1.1 return parse_fasta
216 :    
217 :     elif form == 'kegg':
218 : tharriso 1.2 def parse_kegg(text, amap):
219 : tharriso 1.1 rec = get_kegg_rec(text)
220 :     if (not rec.id) or (not rec.description) or (not rec.seq): return
221 : tharriso 1.5 md5 = hashlib.md5(str(rec.seq)).hexdigest()
222 :     org = rec.annotations['organism']
223 :     orth = []
224 : tharriso 1.2 if org in amap:
225 :     org = amap[org]
226 : tharriso 1.5 # output KO ontology
227 :     if get_ont and ('orthology' in rec.annotations):
228 :     orth = rec.annotations['orthology']
229 :     for oid, odesc in orth.iteritems():
230 : tharriso 1.7 ont_f.write("\t".join([md5, oid, odesc, 'KO']) + "\n")
231 : tharriso 1.1 seq_f.write("%s\t%s\n" %(md5, str(rec.seq)))
232 : tharriso 1.5 prot_f.write("\t".join([md5, rec.id, rec.description, org, source]) + "\n")
233 : tharriso 1.1 if len(rec.dbxrefs) > 0:
234 :     ref_f.write(rec.id + "\t" + "\t".join(rec.dbxrefs) + "\n")
235 :     return parse_kegg
236 :    
237 :     else:
238 :     return None
239 :    
240 :    
241 :     usage = "usage: %prog [options] source input_file1 [input_file2 input_file3 ...]" + __doc__
242 :    
243 :     def main(args):
244 :     parser = OptionParser(usage=usage)
245 :     parser.add_option("-f", "--format", dest="format", metavar="FORMAT", default="fasta",
246 :     help="FORMAT inputed file is in. Must be one of following: genbank, kegg, swiss, fasta [default is fasta]")
247 : tharriso 1.2 parser.add_option("-k", "--kegg_map", dest="keggmap", metavar="FILE", default=None, help="Optional KEGG genome FILE for org name mapping")
248 :     parser.add_option("-e", "--eggnog_map", dest="eggnogmap", metavar="FILE", default=None, help="Optional eggNOG orthgroups tabed FILE for func mapping")
249 : tharriso 1.1 parser.add_option("-d", "--out_dir", dest="outdir", metavar="DIR", default=None, help="DIR to write output [default is current dir]")
250 :     parser.add_option("-o", "--org_header", dest="orgheader", action="store_true", default=False, help="For fasta files, header description is organism [default is function]")
251 : 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]")
252 : 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]")
253 : tharriso 1.1 parser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False, help="Wordy [default is off]")
254 :    
255 :     (opts, args) = parser.parse_args()
256 :     if len(args) < 2:
257 :     parser.error("Incorrect number of arguments")
258 :     source = args[0]
259 :     files = args[1:]
260 :     outdir = ''
261 :     if opts.outdir: outdir = opts.outdir
262 :    
263 : tharriso 1.6 keggmap = get_kegg_map(opts.keggmap, opts.verbose)
264 :     eggnogmap = get_eggnog_map(opts.eggnogmap, opts.verbose)
265 : tharriso 1.2
266 : tharriso 1.5 prot_file = open( os.path.join(outdir, source + ".md52id2func"), 'w' )
267 :     ont_file = open( os.path.join(outdir, source + ".md52id2ont"), 'w' )
268 : tharriso 1.1 seq_file = open( os.path.join(outdir, source + ".md52seq"), 'w' )
269 :     ref_file = open( os.path.join(outdir, source + ".id2xref"), 'w' )
270 :    
271 : tharriso 1.8 parse_format = format_factory( prot_file, ont_file, seq_file, ref_file, source, opts.format, opts.orgheader, opts.getont, opts.getcontig )
272 : tharriso 1.1 if not parse_format:
273 :     parser.error("Incorrect format entered")
274 :    
275 :     for f in files:
276 :     if opts.verbose:
277 :     sys.stdout.write("Parsing file %s ...\n" %f)
278 :     if (opts.format == 'kegg'):
279 :     for rec in kegg_iter(f):
280 : tharriso 1.2 parse_format(rec, keggmap)
281 : tharriso 1.1 else:
282 :     for rec in SeqIO.parse(f, opts.format):
283 : tharriso 1.2 parse_format(rec, eggnogmap)
284 : tharriso 1.1
285 : tharriso 1.5 prot_file.close()
286 :     ont_file.close()
287 : tharriso 1.1 seq_file.close()
288 :     ref_file.close()
289 :     if opts.verbose:
290 :     sys.stdout.write("All Done\n")
291 :    
292 :     if __name__ == "__main__":
293 :     sys.exit(main(sys.argv))

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3