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

Annotation of /Babel/bin/source2ach.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.3 - (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 : tharriso 1.3 # only one entry on rec (first feat is source and is not a feature), use first real feature, no contig data
103 :     if len(rec.features) == 2:
104 :     md5 = hashlib.md5(str(rec.seq)).hexdigest()
105 :     func = ''
106 :     if 'product' in rec.features[1].qualifiers:
107 :     func = rec.features[1].qualifiers['product'][0]
108 :     seq_f.write("%s\t%s\n" %(md5, rec.seq))
109 :     data_f.write("\t".join([md5, rec.name, func, org, source]) + "\n")
110 :     return
111 :     # multiple entries on rec, use CDS features, get contig data
112 : tharriso 1.1 for feat in rec.features:
113 :     if feat.type == 'CDS':
114 :     if ( (not feat.qualifiers) or (not feat.location) or
115 :     ('translation' not in feat.qualifiers) or
116 :     ('protein_id' not in feat.qualifiers) or
117 :     ('product' not in feat.qualifiers) ): continue
118 :     seq = feat.qualifiers['translation'][0]
119 :     md5 = hashlib.md5(seq).hexdigest()
120 :     fid = feat.qualifiers['protein_id'][0]
121 :     func = feat.qualifiers['product'][0]
122 :     beg = feat.location.start.position
123 :     end = feat.location.end.position
124 :     if feat.strand:
125 :     strd = feat.strand
126 :     else:
127 :     strd = 1
128 :     if (beg > end):
129 :     strd = -1
130 :     beg = feat.location.end.position
131 :     end = feat.location.start.position
132 :     seq_f.write("%s\t%s\n" %(md5, seq))
133 :     data_f.write("\t".join([md5, fid, func, org, source, str(beg), str(end), str(strd), cid, cdesc, str(clen)]) + "\n")
134 :     if ('db_xref' in feat.qualifiers) and (len(feat.qualifiers['db_xref']) > 0):
135 :     ref_f.write(fid + "\t" + "\t".join(feat.qualifiers['db_xref']) + "\n")
136 :     return parse_genbank
137 :    
138 :     elif form == 'swiss':
139 : tharriso 1.2 def parse_swiss(rec, amap):
140 : tharriso 1.1 if (not rec) or (not rec.id) or (not rec.seq): return
141 :     md5 = hashlib.md5(str(rec.seq)).hexdigest()
142 :     func = rec.description
143 :     srch = desc_re.search(func)
144 : tharriso 1.2 if srch: func = srch.group(2)
145 : tharriso 1.1 seq_f.write("%s\t%s\n" %(md5, str(rec.seq)))
146 :     data_f.write("\t".join([md5, rec.id, func, rec.annotations['organism'], source]) + "\n")
147 :     if len(rec.dbxrefs) > 0:
148 :     ref_str = rec.id
149 :     for ref in rec.dbxrefs:
150 :     go_m = go_re.match(ref)
151 :     if get_go and go_m:
152 :     # create seperate entry for GO ids
153 :     data_f.write("\t".join([md5, go_m.group(1), func, rec.annotations['organism'], "GO"]) + "\n")
154 :     ref_f.write(go_m.group(1) + "\t" + source + ":" + rec.id + "\n")
155 :     else:
156 :     ref_str += "\t" + ref
157 :     ref_f.write(ref_str + "\n")
158 :     return parse_swiss
159 :    
160 :     elif form == 'fasta':
161 : tharriso 1.2 def parse_fasta(rec, amap):
162 : tharriso 1.1 if (not rec) or (not rec.id) or (not rec.seq): return
163 : tharriso 1.2 desc = ''
164 :     hdrs = rec.description.split()
165 : tharriso 1.1 md5 = hashlib.md5(str(rec.seq)).hexdigest()
166 :     seq_f.write("%s\t%s\n" %(md5, str(rec.seq)))
167 : tharriso 1.2 if len(hdrs) > 1:
168 :     hdrs.pop(0)
169 :     desc = " ".join(hdrs)
170 :     if desc.startswith("("): desc = desc.strip(')(')
171 : tharriso 1.1 if org_desc:
172 : tharriso 1.2 if rec.id in amap:
173 :     for f in amap[rec.id]:
174 :     data_f.write("\t".join([md5, rec.id, f, desc, source]) + "\n")
175 :     else:
176 :     data_f.write("\t".join([md5, rec.id, '', desc, source]) + "\n")
177 : tharriso 1.1 else:
178 : tharriso 1.2 data_f.write("\t".join([md5, rec.id, desc, '', source]) + "\n")
179 : tharriso 1.1 return parse_fasta
180 :    
181 :     elif form == 'kegg':
182 : tharriso 1.2 def parse_kegg(text, amap):
183 : tharriso 1.1 rec = get_kegg_rec(text)
184 :     if (not rec.id) or (not rec.description) or (not rec.seq): return
185 :     md5 = hashlib.md5(str(rec.seq)).hexdigest()
186 :     org = rec.annotations['organism']
187 : tharriso 1.2 if org in amap:
188 :     org = amap[org]
189 : tharriso 1.1 seq_f.write("%s\t%s\n" %(md5, str(rec.seq)))
190 :     data_f.write("\t".join([md5, rec.id, rec.description, org, source]) + "\n")
191 :     if len(rec.dbxrefs) > 0:
192 :     ref_f.write(rec.id + "\t" + "\t".join(rec.dbxrefs) + "\n")
193 :     return parse_kegg
194 :    
195 :     else:
196 :     return None
197 :    
198 :    
199 :     usage = "usage: %prog [options] source input_file1 [input_file2 input_file3 ...]" + __doc__
200 :    
201 :     def main(args):
202 :     parser = OptionParser(usage=usage)
203 :     parser.add_option("-f", "--format", dest="format", metavar="FORMAT", default="fasta",
204 :     help="FORMAT inputed file is in. Must be one of following: genbank, kegg, swiss, fasta [default is fasta]")
205 : tharriso 1.2 parser.add_option("-k", "--kegg_map", dest="keggmap", metavar="FILE", default=None, help="Optional KEGG genome FILE for org name mapping")
206 :     parser.add_option("-e", "--eggnog_map", dest="eggnogmap", metavar="FILE", default=None, help="Optional eggNOG orthgroups tabed FILE for func mapping")
207 : tharriso 1.1 parser.add_option("-d", "--out_dir", dest="outdir", metavar="DIR", default=None, help="DIR to write output [default is current dir]")
208 :     parser.add_option("-o", "--org_header", dest="orgheader", action="store_true", default=False, help="For fasta files, header description is organism [default is function]")
209 :     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]")
210 :     parser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False, help="Wordy [default is off]")
211 :    
212 :     (opts, args) = parser.parse_args()
213 :     if len(args) < 2:
214 :     parser.error("Incorrect number of arguments")
215 :     source = args[0]
216 :     files = args[1:]
217 :     outdir = ''
218 :     if opts.outdir: outdir = opts.outdir
219 :    
220 : tharriso 1.2 keggmap = get_kegg_map(opts.keggmap)
221 :     eggnogmap = get_eggnog_map(opts.eggnogmap)
222 :    
223 : tharriso 1.1 data_file = open( os.path.join(outdir, source + ".md52id2func"), 'w' )
224 :     seq_file = open( os.path.join(outdir, source + ".md52seq"), 'w' )
225 :     ref_file = open( os.path.join(outdir, source + ".id2xref"), 'w' )
226 :    
227 :     parse_format = format_factory( data_file, seq_file, ref_file, source, opts.format, opts.orgheader, opts.goentry )
228 :     if not parse_format:
229 :     parser.error("Incorrect format entered")
230 :    
231 :     for f in files:
232 :     if opts.verbose:
233 :     sys.stdout.write("Parsing file %s ...\n" %f)
234 :     if (opts.format == 'kegg'):
235 :     for rec in kegg_iter(f):
236 : tharriso 1.2 parse_format(rec, keggmap)
237 : tharriso 1.1 else:
238 :     for rec in SeqIO.parse(f, opts.format):
239 : tharriso 1.2 parse_format(rec, eggnogmap)
240 : tharriso 1.1
241 :     data_file.close()
242 :     seq_file.close()
243 :     ref_file.close()
244 :     if opts.verbose:
245 :     sys.stdout.write("All Done\n")
246 :    
247 :     if __name__ == "__main__":
248 :     sys.exit(main(sys.argv))

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3