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

Annotation of /Babel/bin/source2ach.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.2 - (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 :    
11 :     __doc__ = """
12 :    
13 :     Script to take a repository file from the following formats:
14 :     genbank, kegg, swiss, fasta
15 :     and output the following tab seperated files:
16 :    
17 :     SOURCE.md52id2func:
18 :     md5, id, function, organism, source, beg_pos*, end_pos*, strand*, contig_id*, contig_desc*, contig_length*
19 :     SOURCE.md52seq:
20 :     md5, sequence
21 :     SOURCE.id2xref
22 :     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 :     dbref_re = re.compile('^DBLINKS\s+(.*?)^\S', re.DOTALL | re.MULTILINE)
31 :     seq_re = re.compile('^AASEQ\s+\d+\s+(.*?)^\S', re.DOTALL | re.MULTILINE)
32 :     go_re = re.compile('^GO:(.*)')
33 :    
34 : tharriso 1.2 def get_eggnog_map(filename):
35 :     emap = {}
36 : tharriso 1.1 if filename is None:
37 : tharriso 1.2 return emap
38 :     fhdl = open(filename, 'r')
39 :     try:
40 :     for line in fhdl:
41 :     if line.startswith("#"): continue
42 :     parts = line.strip().split("\t")
43 :     if parts[0] in emap:
44 :     emap[ parts[0] ].append( "%s (%s)"%(parts[4], parts[3]) )
45 :     else :
46 :     emap[ parts[0] ] = [ "%s (%s)"%(parts[4], parts[3]) ]
47 :     finally:
48 :     fhdl.close()
49 :     return emap
50 :    
51 :     def get_kegg_map(filename):
52 :     kmap = {}
53 :     if filename is None:
54 :     return kmap
55 : tharriso 1.1 for text in kegg_iter(filename):
56 :     rec = get_kegg_rec(text)
57 :     if (not rec.name) or (not rec.description): continue
58 :     names = rec.name.split(', ')
59 :     if len(names) > 1:
60 : tharriso 1.2 kmap[ names[1] ] = rec.description
61 :     return kmap
62 : tharriso 1.1
63 :     def kegg_iter(filename):
64 :     fhdl = file(filename, 'rb')
65 :     recs = ['']
66 :     for data in iter(lambda: fhdl.read(100000), ''):
67 :     recs = (recs[-1] + data).split("\n///\n")
68 :     for rec in recs[:-1]:
69 :     yield rec
70 :    
71 :     def get_kegg_rec(text):
72 :     record = SeqRecord(Seq("",IUPAC.protein), id='', name='', description='', dbxrefs=[], annotations={'organism':''})
73 :     entry_s = entry_re.search(text)
74 :     name_s = name_re.search(text)
75 :     func_s = func_re.search(text)
76 :     dbref_s = dbref_re.search(text)
77 :     seq_s = seq_re.search(text)
78 :     if entry_s:
79 :     record.id = entry_s.group(1)
80 :     record.annotations['organism'] = entry_s.group(2).strip()
81 :     if name_s:
82 :     record.name = name_s.group(1).strip()
83 :     if func_s:
84 :     record.description = re.sub('\s+', ' ', func_s.group(1).strip())
85 :     if dbref_s:
86 :     parts = dbref_s.group(1).split()
87 :     if (len(parts) % 2) == 0:
88 :     for i in range(0, len(parts)-1, 2):
89 :     record.dbxrefs.append(parts[i].replace('NCBI-', '') + parts[i+1])
90 :     if seq_s:
91 :     record.seq = Seq( re.sub('\s+', '', seq_s.group(1)), IUPAC.protein )
92 :     return record
93 :    
94 :     def format_factory(data_f, seq_f, ref_f, source, form, org_desc, get_go):
95 :     if form == 'genbank':
96 : tharriso 1.2 def parse_genbank(rec, amap):
97 : tharriso 1.1 if (not rec) or (not rec.id) or (not rec.seq): return
98 :     cid = rec.id
99 :     cdesc = rec.description.rstrip('.')
100 :     clen = len(rec.seq)
101 :     org = rec.annotations['organism']
102 :     for feat in rec.features:
103 :     if feat.type == 'CDS':
104 :     if ( (not feat.qualifiers) or (not feat.location) or
105 :     ('translation' not in feat.qualifiers) or
106 :     ('protein_id' not in feat.qualifiers) or
107 :     ('product' not in feat.qualifiers) ): continue
108 :     seq = feat.qualifiers['translation'][0]
109 :     md5 = hashlib.md5(seq).hexdigest()
110 :     fid = feat.qualifiers['protein_id'][0]
111 :     func = feat.qualifiers['product'][0]
112 :     beg = feat.location.start.position
113 :     end = feat.location.end.position
114 :     if feat.strand:
115 :     strd = feat.strand
116 :     else:
117 :     strd = 1
118 :     if (beg > end):
119 :     strd = -1
120 :     beg = feat.location.end.position
121 :     end = feat.location.start.position
122 :     seq_f.write("%s\t%s\n" %(md5, seq))
123 :     data_f.write("\t".join([md5, fid, func, org, source, str(beg), str(end), str(strd), cid, cdesc, str(clen)]) + "\n")
124 :     if ('db_xref' in feat.qualifiers) and (len(feat.qualifiers['db_xref']) > 0):
125 :     ref_f.write(fid + "\t" + "\t".join(feat.qualifiers['db_xref']) + "\n")
126 :     return parse_genbank
127 :    
128 :     elif form == 'swiss':
129 : tharriso 1.2 def parse_swiss(rec, amap):
130 : tharriso 1.1 if (not rec) or (not rec.id) or (not rec.seq): return
131 :     md5 = hashlib.md5(str(rec.seq)).hexdigest()
132 :     func = rec.description
133 :     srch = desc_re.search(func)
134 : tharriso 1.2 if srch: func = srch.group(2)
135 : tharriso 1.1 seq_f.write("%s\t%s\n" %(md5, str(rec.seq)))
136 :     data_f.write("\t".join([md5, rec.id, func, rec.annotations['organism'], source]) + "\n")
137 :     if len(rec.dbxrefs) > 0:
138 :     ref_str = rec.id
139 :     for ref in rec.dbxrefs:
140 :     go_m = go_re.match(ref)
141 :     if get_go and go_m:
142 :     # create seperate entry for GO ids
143 :     data_f.write("\t".join([md5, go_m.group(1), func, rec.annotations['organism'], "GO"]) + "\n")
144 :     ref_f.write(go_m.group(1) + "\t" + source + ":" + rec.id + "\n")
145 :     else:
146 :     ref_str += "\t" + ref
147 :     ref_f.write(ref_str + "\n")
148 :     return parse_swiss
149 :    
150 :     elif form == 'fasta':
151 : tharriso 1.2 def parse_fasta(rec, amap):
152 : tharriso 1.1 if (not rec) or (not rec.id) or (not rec.seq): return
153 : tharriso 1.2 desc = ''
154 :     hdrs = rec.description.split()
155 : tharriso 1.1 md5 = hashlib.md5(str(rec.seq)).hexdigest()
156 :     seq_f.write("%s\t%s\n" %(md5, str(rec.seq)))
157 : tharriso 1.2 if len(hdrs) > 1:
158 :     hdrs.pop(0)
159 :     desc = " ".join(hdrs)
160 :     if desc.startswith("("): desc = desc.strip(')(')
161 : tharriso 1.1 if org_desc:
162 : tharriso 1.2 if rec.id in amap:
163 :     for f in amap[rec.id]:
164 :     data_f.write("\t".join([md5, rec.id, f, desc, source]) + "\n")
165 :     else:
166 :     data_f.write("\t".join([md5, rec.id, '', desc, source]) + "\n")
167 : tharriso 1.1 else:
168 : tharriso 1.2 data_f.write("\t".join([md5, rec.id, desc, '', source]) + "\n")
169 : tharriso 1.1 return parse_fasta
170 :    
171 :     elif form == 'kegg':
172 : tharriso 1.2 def parse_kegg(text, amap):
173 : tharriso 1.1 rec = get_kegg_rec(text)
174 :     if (not rec.id) or (not rec.description) or (not rec.seq): return
175 :     md5 = hashlib.md5(str(rec.seq)).hexdigest()
176 :     org = rec.annotations['organism']
177 : tharriso 1.2 if org in amap:
178 :     org = amap[org]
179 : tharriso 1.1 seq_f.write("%s\t%s\n" %(md5, str(rec.seq)))
180 :     data_f.write("\t".join([md5, rec.id, rec.description, org, source]) + "\n")
181 :     if len(rec.dbxrefs) > 0:
182 :     ref_f.write(rec.id + "\t" + "\t".join(rec.dbxrefs) + "\n")
183 :     return parse_kegg
184 :    
185 :     else:
186 :     return None
187 :    
188 :    
189 :     usage = "usage: %prog [options] source input_file1 [input_file2 input_file3 ...]" + __doc__
190 :    
191 :     def main(args):
192 :     parser = OptionParser(usage=usage)
193 :     parser.add_option("-f", "--format", dest="format", metavar="FORMAT", default="fasta",
194 :     help="FORMAT inputed file is in. Must be one of following: genbank, kegg, swiss, fasta [default is fasta]")
195 : tharriso 1.2 parser.add_option("-k", "--kegg_map", dest="keggmap", metavar="FILE", default=None, help="Optional KEGG genome FILE for org name mapping")
196 :     parser.add_option("-e", "--eggnog_map", dest="eggnogmap", metavar="FILE", default=None, help="Optional eggNOG orthgroups tabed FILE for func mapping")
197 : tharriso 1.1 parser.add_option("-d", "--out_dir", dest="outdir", metavar="DIR", default=None, help="DIR to write output [default is current dir]")
198 :     parser.add_option("-o", "--org_header", dest="orgheader", action="store_true", default=False, help="For fasta files, header description is organism [default is function]")
199 :     parser.add_option("-g", "--go_entry", dest="goentry", action="store_true", default=False, help="For swiss files, output for each GO alias in entry [default is off]")
200 :     parser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False, help="Wordy [default is off]")
201 :    
202 :     (opts, args) = parser.parse_args()
203 :     if len(args) < 2:
204 :     parser.error("Incorrect number of arguments")
205 :     source = args[0]
206 :     files = args[1:]
207 :     outdir = ''
208 :     if opts.outdir: outdir = opts.outdir
209 :    
210 : tharriso 1.2 keggmap = get_kegg_map(opts.keggmap)
211 :     eggnogmap = get_eggnog_map(opts.eggnogmap)
212 :    
213 : tharriso 1.1 data_file = open( os.path.join(outdir, source + ".md52id2func"), 'w' )
214 :     seq_file = open( os.path.join(outdir, source + ".md52seq"), 'w' )
215 :     ref_file = open( os.path.join(outdir, source + ".id2xref"), 'w' )
216 :    
217 :     parse_format = format_factory( data_file, seq_file, ref_file, source, opts.format, opts.orgheader, opts.goentry )
218 :     if not parse_format:
219 :     parser.error("Incorrect format entered")
220 :    
221 :     for f in files:
222 :     if opts.verbose:
223 :     sys.stdout.write("Parsing file %s ...\n" %f)
224 :     if (opts.format == 'kegg'):
225 :     for rec in kegg_iter(f):
226 : tharriso 1.2 parse_format(rec, keggmap)
227 : tharriso 1.1 else:
228 :     for rec in SeqIO.parse(f, opts.format):
229 : tharriso 1.2 parse_format(rec, eggnogmap)
230 : tharriso 1.1
231 :     data_file.close()
232 :     seq_file.close()
233 :     ref_file.close()
234 :     if opts.verbose:
235 :     sys.stdout.write("All Done\n")
236 :    
237 :     if __name__ == "__main__":
238 :     sys.exit(main(sys.argv))

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3