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

Annotation of /Babel/bin/source2ach.py

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3