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

View of /Babel/bin/source2ach.py

Parent Directory Parent Directory | Revision Log Revision Log

Revision 1.1 - (download) (as text) (annotate)
Thu Sep 16 21:31:24 2010 UTC (9 years, 10 months ago) by tharriso
Branch: MAIN
*** empty log message ***

#!/usr/bin/env python

import os, sys, re, hashlib
from optparse import OptionParser
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import IUPAC

__doc__ = """

Script to take a repository file from the following formats:
   genbank, kegg, swiss, fasta
and output the following tab seperated files:

   md5, id, function, organism, source, beg_pos*, end_pos*, strand*, contig_id*, contig_desc*, contig_length*
   md5, sequence
   id, external refrence 1, [external refrence 2, external refrence 3, ...]

Values with * are optional, only genbank files contain that data."""

desc_re  = re.compile('RecName: Full=(.*?);')
entry_re = re.compile('^ENTRY\s+(\S+)\s+CDS\s+(.*)$', re.MULTILINE)
name_re  = re.compile('^NAME\s+(.*)$', re.MULTILINE)
func_re  = re.compile('^DEFINITION\s+(.*?)^\S', re.DOTALL | re.MULTILINE)
dbref_re = re.compile('^DBLINKS\s+(.*?)^\S', re.DOTALL | re.MULTILINE)
seq_re   = re.compile('^AASEQ\s+\d+\s+(.*?)^\S', re.DOTALL | re.MULTILINE)
go_re    = re.compile('^GO:(.*)')

def get_org_map(filename):
    omap = {}
    if filename is None:
        return omap
    for text in kegg_iter(filename):
        rec = get_kegg_rec(text)
        if (not rec.name) or (not rec.description): continue
        names = rec.name.split(', ')
        if len(names) > 1:
            omap[ names[1] ] = rec.description
    return omap

def kegg_iter(filename):
    fhdl = file(filename, 'rb')
    recs = ['']
    for data in iter(lambda: fhdl.read(100000), ''):
        recs = (recs[-1] + data).split("\n///\n")
        for rec in recs[:-1]:
            yield rec

def get_kegg_rec(text):
    record  = SeqRecord(Seq("",IUPAC.protein), id='', name='', description='', dbxrefs=[], annotations={'organism':''})
    entry_s = entry_re.search(text)
    name_s  = name_re.search(text)
    func_s  = func_re.search(text)
    dbref_s = dbref_re.search(text)
    seq_s   = seq_re.search(text)
    if entry_s:
        record.id = entry_s.group(1)
        record.annotations['organism'] = entry_s.group(2).strip()
    if name_s:
        record.name = name_s.group(1).strip()
    if func_s:
        record.description = re.sub('\s+', ' ', func_s.group(1).strip())
    if dbref_s:
        parts = dbref_s.group(1).split()
        if (len(parts) % 2) == 0:
            for i in range(0, len(parts)-1, 2):
                record.dbxrefs.append(parts[i].replace('NCBI-', '') + parts[i+1])
    if seq_s:
        record.seq = Seq( re.sub('\s+', '', seq_s.group(1)), IUPAC.protein )
    return record

def format_factory(data_f, seq_f, ref_f, source, form, org_desc, get_go):
    if form == 'genbank':    
        def parse_genbank(rec):
            if (not rec) or (not rec.id) or (not rec.seq): return
            cid   = rec.id
            cdesc = rec.description.rstrip('.')
            clen  = len(rec.seq)
            org   = rec.annotations['organism']
            for feat in rec.features:
                if feat.type == 'CDS':
                    if ( (not feat.qualifiers) or (not feat.location) or
                         ('translation' not in feat.qualifiers) or
                         ('protein_id' not in feat.qualifiers) or
                         ('product' not in feat.qualifiers) ): continue
                    seq  = feat.qualifiers['translation'][0]
                    md5  = hashlib.md5(seq).hexdigest()
                    fid  = feat.qualifiers['protein_id'][0]
                    func = feat.qualifiers['product'][0]
                    beg  = feat.location.start.position
                    end  = feat.location.end.position
                    if feat.strand:
                        strd = feat.strand
                        strd = 1
                        if (beg > end):
                            strd = -1
                            beg  = feat.location.end.position
                            end  = feat.location.start.position
                    seq_f.write("%s\t%s\n" %(md5, seq))
                    data_f.write("\t".join([md5, fid, func, org, source, str(beg), str(end), str(strd), cid, cdesc, str(clen)]) + "\n")
                    if ('db_xref' in feat.qualifiers) and (len(feat.qualifiers['db_xref']) > 0):
                        ref_f.write(fid + "\t" + "\t".join(feat.qualifiers['db_xref']) + "\n")
        return parse_genbank
    elif form == 'swiss':
        def parse_swiss(rec):
            if (not rec) or (not rec.id) or (not rec.seq): return
            md5  = hashlib.md5(str(rec.seq)).hexdigest()
            func = rec.description
            srch = desc_re.search(func)
            if srch: func = srch.group(1)
            seq_f.write("%s\t%s\n" %(md5, str(rec.seq)))
            data_f.write("\t".join([md5, rec.id, func, rec.annotations['organism'], source]) + "\n")
            if len(rec.dbxrefs) > 0:
                ref_str = rec.id
                for ref in rec.dbxrefs:
                    go_m = go_re.match(ref)
                    if get_go and go_m:
                        # create seperate entry for GO ids
                        data_f.write("\t".join([md5, go_m.group(1), func, rec.annotations['organism'], "GO"]) + "\n")
                        ref_f.write(go_m.group(1) + "\t" + source + ":" + rec.id + "\n")
                        ref_str += "\t" + ref
                ref_f.write(ref_str + "\n")
        return parse_swiss
    elif form == 'fasta':
        def parse_fasta(rec):
            if (not rec) or (not rec.id) or (not rec.seq): return
            func = rec.description
            md5  = hashlib.md5(str(rec.seq)).hexdigest()
            seq_f.write("%s\t%s\n" %(md5, str(rec.seq)))
            if func.startswith("("): func = rec.description.strip(')(')
            if org_desc:
                data_f.write("\t".join([md5, rec.id, '', func, source]) + "\n")
                data_f.write("\t".join([md5, rec.id, func, '', source]) + "\n")
        return parse_fasta

    elif form == 'kegg':
        def parse_kegg(text, orgmap):
            rec = get_kegg_rec(text)
            if (not rec.id) or (not rec.description) or (not rec.seq): return
            md5 = hashlib.md5(str(rec.seq)).hexdigest()
            org = rec.annotations['organism']
            if org in orgmap:
                org = orgmap[org]
            seq_f.write("%s\t%s\n" %(md5, str(rec.seq)))
            data_f.write("\t".join([md5, rec.id, rec.description, org, source]) + "\n")
            if len(rec.dbxrefs) > 0:
                ref_f.write(rec.id + "\t" + "\t".join(rec.dbxrefs) + "\n")
        return parse_kegg

        return None

usage = "usage: %prog [options] source input_file1 [input_file2 input_file3 ...]" + __doc__

def main(args):
    parser = OptionParser(usage=usage)
    parser.add_option("-f", "--format", dest="format", metavar="FORMAT", default="fasta",
                      help="FORMAT inputed file is in. Must be one of following: genbank, kegg, swiss, fasta [default is fasta]")
    parser.add_option("-m", "--org_map", dest="orgmap", metavar="FILE", default=None, help="Optional KEGG genome FILE for org name mapping")
    parser.add_option("-d", "--out_dir", dest="outdir", metavar="DIR", default=None, help="DIR to write output [default is current dir]")
    parser.add_option("-o", "--org_header", dest="orgheader", action="store_true", default=False, help="For fasta files, header description is organism [default is function]")
    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]")
    parser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False, help="Wordy [default is off]")
    (opts, args) = parser.parse_args()
    if len(args) < 2:
        parser.error("Incorrect number of arguments")
    source = args[0]
    files  = args[1:]
    orgmap = get_org_map(opts.orgmap)
    outdir = ''
    if opts.outdir: outdir = opts.outdir

    data_file = open( os.path.join(outdir, source + ".md52id2func"), 'w' )
    seq_file  = open( os.path.join(outdir, source + ".md52seq"), 'w' )
    ref_file  = open( os.path.join(outdir, source + ".id2xref"), 'w' )
    parse_format = format_factory( data_file, seq_file, ref_file, source, opts.format, opts.orgheader, opts.goentry )
    if not parse_format:
        parser.error("Incorrect format entered")
    for f in files:
        if opts.verbose:
            sys.stdout.write("Parsing file %s ...\n" %f)
        if (opts.format == 'kegg'):
            for rec in kegg_iter(f):
                parse_format(rec, orgmap)
            for rec in SeqIO.parse(f, opts.format):

    if opts.verbose:
        sys.stdout.write("All Done\n")

if __name__ == "__main__":

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3