#! /opt/gensoft/exe/blastTaxoAnalysis/1.0/venv/bin/python2.7

# Corinne Maufrais
# Institut Pasteur, Groupe Logisiels et Banques de sonnees
# maufrais@pasteur.fr
#
# blast2taxoclass filter blast with taxonomic hierarchy information  

# version 1.0


import os, sys, getopt
from subprocess import *

import Golden

try:
    GOLDENDATA =  os.environ['GOLDENDATA']
except:
    GOLDENDATA = "/local/databases/index/golden"
    os.environ['GOLDENDATA'] = GOLDENDATA

try:
    LIB = os.environ['BLAST2TC_LIB']
except:
    LIB = '/usr/local/bin'

if LIB not in sys.path:
    sys.path.append( LIB )

try:
    TABLE = os.environ['TAXOBDBDATA']
except:
    TABLE = '/local/databases/rel/taxodb/current/bdb/'

TAXODB_BDB = 'taxodb.bdb'

import xml.sax, sys, copy
from xml.sax.handler import ContentHandler

import BlastParser 

####################    blast2taxoclass.py

class ParserError:
    def __init__(self,err):
        self.err = err

    def __repr__(self):
        return "[ParserError] " + self.err

class ParserWarning:
    def __init__(self,err):
        self.err = err

    def __repr__(self):
        return "[ParserWarning] " + self.err



# organisme name only
def parseUniprot( flatFile ):
    """
    parse uniprot or embl like flat file
    """
    taxId= ''
    taxoLight = ''
    orgName = ''
    lineFld= flatFile.split('\n')
    for line in lineFld:
        if line =='\n':
            continue
        tag = line[0:2].strip()
        value = line[5:-1]
        if tag == 'OS':
            orgName += value
        elif tag == 'OC':
            taxoLight += value
        elif tag == 'OX':
            taxId += value
        elif tag in ['RN', 'DR','CC', 'FH', 'SQ']:
            return orgName, taxId, taxoLight
    return orgName, taxId, taxoLight

def parseGenbank( flatFile ):
    """
    parse genbank like flat file
    """
    description = ''
    taxId= ''
    taxoLight = ''
    orgName = ''
    taxoL = False
    lineFld= flatFile.split('\n')
    for line in lineFld:
        if line =='\n':
            continue
        tag = line[0:12].strip()
        value = line[12:]
        if tag == 'ORGANISM': # one line
            orgName += value
            taxoL=True
        elif taxoL and not tag: # multiple line without tag
            taxoLight += value
        elif tag == 'TaxID': # gi number
            taxId += value
        elif tag in ['REFERENCE','COMMENT', 'FEATURES', 'ORIGIN']:
            return orgName, taxId, taxoLight
        elif not tag: # fin taxonomy
            taxoL = False
    return orgName, taxId, taxoLight
        

def parse( flatFile  ):
    """
    parse db flat file ( uniprot, embl, genbank) into a DBRecord object
    """
    if flatFile[:2] == 'ID':
        return parseUniprot( flatFile )
    elif flatFile[:5] == 'LOCUS':
        return parseGenbank( flatFile )
    return '','',''

class DBRecord: 
    def __init__( self , database ):
        """
        Holds informations from a db flat file (uniprot, embl, genbank)
        """
        self.database = database
        self.taxId = None
        self.classification = None
        self.species = None
        self.accession = None
        self.taxonomy = None #### new 18/11/10
        
    def exist( self ): #### new 18/11/10
        return self.classification != None or self.species != None or self.accession != None or self.taxonomy != None
    
class Blast2TaxoClassError:
    def __init__( self, err ):
        self.err = err

    def __repr__( self ):
        return "[Blast2taxoClassError] " + self.err

##############################################################################
#
#            Golden
#
##############################################################################

def doGolden( db,ac ):
    ########################### db ref
    if db in[ 'sp', 'sw','swissprot','tr', 'trembl']:
        db = 'uniprot'
    elif db in ['emb', 'dbj']:
        db = 'embl'
    elif db in ['gb']:
        db = 'genbank'
    elif db in ['gp']:
        db = 'genpept'
    elif db in ['ref']:
        db = 'refseq'
    #elif db in ['pir','pdb','tpg', 'tpe', 'tpd', 'prf']:
    #    return '','',''
    try:
        flatFile = Golden.access(db,ac)
    except IOError:
        return '','',''
    if flatFile:
        return parse( flatFile ) #orgName, taxId, taxoLight
    else:
        return '','',''

##############################################################################
#
#            TaxoDB
#
##############################################################################

def extractDBrecord( blastHitRecord, allDBRecord ):
    
    db, acc = blastHitRecord.extractDBinfo()
    
    if not acc or not db:
        print >>sys.stderr, Blast2TaxoClassError ( 'Hit information not well parsed: %s ' % blastHitRecord.comment )
        return None, allDBRecord     
    if allDBRecord.has_key( acc ):
        return allDBRecord[acc], allDBRecord
    acc = acc.split('.')[0]
    ## extract db and acc from blast
    dbRecord = None        
    try:
        # species name extraction from blast pairwise info
        orgName = blastHitRecord.comment.split('[')[1].split(']')[0]
    except:
        orgName, taxId, taxoLight = doGolden( db,acc )
############ Mettre l'acc en error pour ne par refaire un golden
        if not orgName:
            return None, allDBRecord
        
        dbRecord = DBRecord( db )
        dbRecord.accession = acc
        dbRecord.taxId = taxId
        dbRecord.classification = taxoLight
        dbRecord.species = orgName
    
    taxoFull = osVSocBDB.get( str(orgName) )
    if not taxoFull:
        orgName =  orgName.split('(')[0].strip()
        taxoFull = osVSocBDB.get( str(orgName) )
        if not taxoFull:
            orgName =  orgName.split('.')[0].strip()
            taxoFull = osVSocBDB.get( str(orgName) )
            if not taxoFull:
                if dbRecord:
                    allDBRecord[ acc ] = dbRecord
                    return dbRecord, allDBRecord
                else:
                    return None, allDBRecord
           
    if not dbRecord:
        dbRecord = DBRecord( db )
        dbRecord.accession = acc
        dbRecord.species = orgName
    
    if taxoFull:
        dbRecord.classification = taxoFull
    
        fld = dbRecord.classification.split(';')
        if fld[-1] == '':
            dbRecord.classification = ';'.join( fld[:-1])
        
        fld = dbRecord.classification.split(';')
        name, rank = extractRank( fld[0].strip() )
        if name == 'cellular organisms':
            oc = ';'.join( fld[1:] )
            dbRecord.classification = oc.strip()
    allDBRecord[ acc ] = dbRecord
    return dbRecord, allDBRecord


def extractRank( node ):
    rank = ''
    fld = node.split('(')
    name = fld[0].strip()
    if len (fld) > 1:
        rank = fld[1].split(')')[0].strip()
    return name, rank

def outPutFile( lat, vlat, blastoutput=True, format='m0', queryoutput=True ):
    if lat == 'noHit':
        return
    lat = lat.replace('/', '-')
    lat = lat.replace(' ', '-')
    if lat[-1]==';':
        lat = lat[:-1]   
    fld = lat.split(';')
    if len( fld )==1:
        if blastoutput:
            if format == 'm7':
                fhout = open('%s.xml' % (fld[0]), 'w')
            else:
                fhout = open('%s.blast' % (fld[0]), 'w')
        if queryoutput:
            fhoutctg = open('%s.qry' % (fld[0]), 'w') # liste des query
    else:
        if blastoutput:
            if format == 'm7':
                fhout = open('%s_%s.xml' % (fld[0], fld[-1]), 'w')
            else:
                fhout = open('%s_%s.blast' % (fld[0], fld[-1]), 'w')
        if queryoutput:
            fhoutctg = open('%s_%s.qry' % (fld[0], fld[-1]), 'w') # liste des query
    
    for blr in vlat['blastrecord']:
        if blastoutput:
            if format == 'm0':
                BlastParser.PairwiseBlastPrinter( blr, fhout )
            if format == 'm7':
                BlastParser.XMLBlastPrinter( blr, fhout )
        if queryoutput:
            print >>fhoutctg, blr.queryDef
    if blastoutput and format == 'm0':
        print >>fhout, '  Database: %s version' % blr.database.capitalize()
        fhout.close()
    if queryoutput: 
        fhoutctg.close()        

##############################################################################
#
#            MAIN
#
##############################################################################


def usage():
    print """
usage: blast2taxoclass [options] -i <blast(s) output file>

options:
   -h  ... Print this message and exit.
   -i  ... Blast(s) output file. One or more blast in one file. Mandatory option.

Blast filtering options:
   -M/F   ... Find Lower Ancestor Taxon of:
               M ... best hit (default).
               F ... most frequent hits. 
    
   -x <int> ...  Number of hits to concider by blast (default: 10, all hits: 0 )

Taxonomic hierarchy option:
   -p/n/r <val>  ...   Taxonomy filter 
                 p <int> ... Relative position in taxonomic hierarchy (default: 0, root)
                 n <str> ... Taxonomic Name (replace space by _ in name, ssRNA_viruses instead of ssRNA viruses) 
                 r <str> ... Taxonomic rank of Lower Ancestor Taxon (superkingdom, kingdom, ...)
                            If Taxonomic rank is not defined for one hit, it is not treated.
      
Output:
    -b ... Blast output file matching "Taxonomic hierarchy option" are extract from input "blast output 
            file" and reformat in new blast file with ".blast" suffix.
    -q ... Query name(s) matching "Taxonomic hierarchy option" are save in file with ".qry" suffix. 

    
Only pairwise and XML Blast output are supported (BLAST 2.2.20 ):

descriptions:

   blast2taxoclass filter blast with taxonomic hierarchy information

requirements:

   blast2taxoclass use Golden program a Databank flat files entry retriever program wrote by Nicolas Joly (njoly@pasteur.fr) at Institut Pasteur.
"""


if __name__=='__main__':
    from bsddb3 import db
    
    # tmp path
    try:
        TMP_PATH = os.environ[ 'TMPPATH' ]
    except:
        TMP_PATH = "/tmp"

    
    # ===== Command line parser
    try:
        opts, args = getopt.gnu_getopt( sys.argv[1:], "hr:n:MFi:bqp:x:",["help",] )
    except getopt.GetoptError:
        usage()
        sys.exit( 0 )


    rankList = ['superkingdom','kingdom','subkingdom','superphylum','phylum',
                'subphylum','superclass','class','subclass','infraclass', 
                'superorder','order','suborder','infraorder','parvorder', 
                'superfamily','family','subfamily','tribe','subtribe','genus',
                'subgenus','species group','species subgroup','species','subspecies',
                'varietas','forma']
    primary_rank=['kingdom', 'division', 'phylum', 'class', 'order', 'family', 'genus', 'species']
    
    blastf, rankName, taxoName = None, None, None
    MSP, mostFrequent = False, False
    Emin = 10000000
    fhout= sys.stdout
    rank_i = None
    blastoutput = False
    queryoutput = False
    hitNumber = 10
    for o, v in opts: #( opt, value )
        if o in ( "-h","--help" ):
            usage()
            sys.exit( 0 )
        elif o in ( "-i" , "--blast" ):
            blastf = v
        elif o in ( "-M" , "--MSP" ):
            MSP = True
        elif o in ( "-F" , "--MFrequent" ):
            mostFrequent = True
        elif o in ( "-x", "--hitNum" ):
            try:
                hitNumber = int(v)
            except:
                usage()
                sys.exit( 0 )
        elif o in ( "-p" , "--ranki" ):
            try:
                rank_i = int(v)
            except:
                usage()
                sys.exit( 0 )
        elif o in ( "-n" , "--taxoName" ):
            taxoName = v.replace('_',' ')
        elif o in ( "-r" , "--rank" ):
            rankName = v.lower()
            rankName = rankName.replace('_',' ')
        elif o in ( "-b" , "--blastout" ):
            blastoutput = True
        elif o in ( "-q" , "--qryout" ):
            queryoutput = True
        else:
            usage()
            sys.exit( 0 )

    
    # === mandatory files
    if not blastf:
        print >>sys.stderr, "Blast(s) output file is mandatory."
        usage()
        sys.exit( 0 )
    
    # === hit filter type
    
    if (MSP and mostFrequent):
        print >>sys.stderr, "Choose only one of Blast filtering options."
        usage()
        sys.exit( 0 )
    
    if not mostFrequent:  # Default MSP
        MSP = True
    
    # === taxonomic rank filter type

    if (rankName and taxoName and rank_i != None): 
        print >>sys.stderr, "Choose only one of taxonomic hierarchy filter option: Relative position, Taxonomic rank or Taxonomic name."
        usage()
        sys.exit( 0 )
    elif (rankName and taxoName) or (taxoName and rank_i != None) or (rankName and rank_i != None):
        print >>sys.stderr, "Choose only one of taxonomic hierarchy filter option: Relative position, Taxonomic rank or Taxonomic name"
        usage()
        sys.exit( 0 )
    elif not ( rankName or taxoName ):
        if rank_i == None:
            rank_i = 0
    
    if rankName and rankName not in rankList:
        print >>sys.stderr, '"%s" is not a taxonomic rank name (superkingdom, kingdom, ...)' % rankName
        usage()
        sys.exit( 0 )
    
    # ===== Blast parsing
    
        
    try:
        fhin = open( blastf )
    except IOError, err:
        print >>sys.stderr, err
        sys.exit( 0 )
        
        
    if os.path.exists( 'noHitinBlast.qry' ): #  Blast output: ***** No hits found ******
        os.unlink( 'noHitinBlast.qry' )
    nohitf = "noHitinBlast.qry"
    
    blastRecordS, format = BlastParser.parser( fhin )
    #if format == 'psiblast':
    #    print >>sys.stderr, Blast2TaxoClassError( 'psiblast output is not supported for now' )
    #    sys.exit()
    fhin.close()


    ## Check supported database
    if format not in ['m0','m8']:
        print >>sys.stderr, BlastParser.BlastError("Not an accepted blast format" )
        sys.exit()
    
    if format == 'm0' and blastRecordS.hasDatabase():
        supportedDB = ['imgt', 'tr', 'swissprot', 'sp', 'uniprot', 'uniprot_sprot','uniprot_trembl','emb', 'embl', 'embl_new', 'gp', 'gb', 'genbank', 'genpept', 'nr','nrprot']
        if blastRecordS.database not in supportedDB:
            inDb = False
            for i in supportedDB:
                if (i in blastRecordS.databaseAll.lower()):
                    inDb = True
                    break
            if not inDb:
                print >>sys.stderr, Blast2TaxoClassError( '-%s- database is not supported for now' % blastRecordS.database )
                sys.exit()
    elif format == 'm0':
        print >>sys.stderr, BlastParser.BlastError("Not a valid blast format" )
        sys.exit()
    

    ## for each blast report
    nbBlast = 0
    query = {}

    
    # Open Berkeley database and write its contents out
    # Get an instance of BerkeleyDB 
    osVSocBDB = db.DB()
    # Open database
    #       Access method: Hash
    #       set isolation level to "dirty read (read uncommited)"
    
    osVSocBDBfile = TABLE + TAXODB_BDB
    try:
        osVSocBDB.open(osVSocBDBfile, None, db.DB_HASH, db.DB_RDONLY)
    except StandardError, err:
        print >>sys.stderr, Blast2TaxoClassError("TaxoDB database error, %s" % err)
        sys.exit()
 
    # for all blast in file
    allLAT = {}
    bi = 0
    taxoNameLat = []
    rankNameLat = []
    allDbRecord = {}
    zz = 0
    for blastRecord in blastRecordS.blastS:
        bi +=1
        allHitOcRank = []
        Emin = 10000000
        MSP_hit = None
        MSP_dbRecord = None
        blastRecord.database = blastRecordS.database
        nbBlast += 1
        j = 0
        
        #BLAST Hits ANALYSE
        if hitNumber == 0:
            hitNumberN = len(blastRecord.hitS)
        else:
            hitNumberN = hitNumber
        for blastHitRecord in blastRecord.hitS[:hitNumberN]:   
            firstHSP = blastHitRecord.hspS[0]
            # ------------> blast's best hit
            if MSP and firstHSP.hspExpect < Emin:
                MSP_hit = blastHitRecord
                Emin = firstHSP.hspExpect
                # ----> parse oc, os with BerkeleyDB or golden for one hit
                dbRecord, allDbRecord = extractDBrecord( blastHitRecord, allDbRecord )
                if not dbRecord: ##### WARNING: golden error not well deal
                    
                    continue
                MSP_dbRecord = dbRecord
            elif not MSP:
                # parse oc, os with BerkeleyDB or golden
                dbRecord, allDbRecord = extractDBrecord( blastHitRecord, allDbRecord )
                if not dbRecord: ##### WARNING: golden error not well deal
                    continue
                # most frequent oc in blast
                ocRank = {}
                fld = dbRecord.classification.split( ';' )
                for f in range( len(fld) ):
                    name, rank = extractRank( fld[f].strip() )
                    ocRank[f] = (name,rank,dbRecord, blastRecord)
            
                allHitOcRank.append(ocRank)
        
        if MSP and MSP_dbRecord:
            ocRank = {}
            fld = MSP_dbRecord.classification.split( ';' )
            for f in range( len(fld) ):
                name, rank = extractRank( fld[f].strip() )
                ocRank[f] = (name,rank,MSP_dbRecord, blastRecord)
        
            allHitOcRank.append(ocRank)

        # one blast ANALYSE: best oc fo all hit
        analyseRank = {}
        if len( blastRecord.hitS) > 0: # Warning: Not hit found
            # stockage
            for ocHitR in allHitOcRank:
                vuTaxoName = False
                vuRankName = False
                lat = ''
                latr = ''
                nk = len(ocHitR.keys())-1
                if rank_i!= None:
                    if nk >= rank_i:
                        nk = rank_i
                
                for j in range( nk+1 ):
                    
                    if taxoName and taxoName.replace('_', ' ').lower() == ocHitR[j][0].lower():
                        vuTaxoName = True
                        #rank_i = j
                    if rankName and rankName == ocHitR[j][1].lower():
                        vuRankName= True
                        #rank_i = j
                    lat +=  ocHitR[j][0] + ';'
                    if ocHitR[j][1]:
                        latr += ocHitR[j][0] + ' (%s);' % ocHitR[j][1]
                    else:
                        latr += ocHitR[j][0] + ';'
                    if taxoName and vuTaxoName: # bug: Eukaryota;Fungi/Metazoa group;Metazoa(NCBI) // Eukaryota;Metazoa (golden)
                        taxoNameLat.append(lat)
                        break
                    if rankName and vuRankName:
                        rankNameLat.append(lat)
                        break
                if analyseRank.has_key( lat ):
                    analyseRank[ lat ]['nb'] += 1
                else:
                    analyseRank[ lat ]= {'nb': 1, 'blastrecord' : ocHitR[nk][3], 'latr': latr}
                    
                if (MSP and MSP_dbRecord) and ocHitR[nk][2] == MSP_dbRecord:
                    analyseRank[ lat ]['MSP'] = 1

            # analyse of stockage       
            m = 0
            dbr =[]
            lat_blastrecord = ''
            if mostFrequent:
                nm = ''
                for k,v in analyseRank.items():
                    if v['nb'] > m:
                        m = v['nb']
                        lat = k
                        lat_blastrecord = v['blastrecord']
                        latr = v['latr']
                   
            elif MSP:
                nm = ''
                for k,v in analyseRank.items():
                    if 'MSP' in v.keys():
                        lat_blastrecord = v['blastrecord']
                        lat = k
                        latr = v['latr']
            # stockage pour analyse de tous les blast      
            if lat_blastrecord and allLAT.has_key( lat ):
                allLAT[lat]['nb'] += 1
                allLAT[lat]['blastrecord'].append( lat_blastrecord )
                
            elif lat_blastrecord:
                allLAT[lat] = {'nb':1, 'blastrecord':[lat_blastrecord], 'latr': latr}
            else:
                if allLAT.has_key( 'No match found' ):
                    allLAT['No match found']['nb'] += 1
                    allLAT['No match found']['blastrecord'].append( blastRecord )
                else:
                    allLAT['No match found']={'nb':1, 'blastrecord': [blastRecord],'latr': 'No match found' }
                
        else:
            if allLAT.has_key( 'noHit' ):
                allLAT['noHit']['nb'] += 1
                allLAT['noHit']['blastrecord'].append( blastRecord )
            else:
                allLAT['noHit']= {'nb': 1, 'blastrecord':[blastRecord], 'latr': 'Blast: No hits found'}
            fhoutnoHit = open( nohitf , 'a') # liste des query
            print >>fhoutnoHit, blastRecord.queryDef
        
    ### OUTPUT RESULTS AND FILES FOR ALL BLAST
    newAll = {}
    for lat, vlat in allLAT.items():
        if taxoName:
            if lat in taxoNameLat:
                print >>sys.stdout, "%2.2f%%\t(%s query):\t%s" % ( float(vlat['nb'])*100/nbBlast, vlat['nb'], vlat['latr'] )
                outPutFile( lat, vlat, blastoutput, format, queryoutput )
            else:
                if newAll.has_key( 'No match found' ):
                    newAll['No match found']['nb'] += vlat['nb']
                    newAll['No match found']['blastrecord'].extend( vlat['blastrecord'] )
                else:
                    newAll['No match found']= {'nb': vlat['nb'], 'blastrecord':vlat['blastrecord'], 'latr': 'No match found'}
        elif rankName:
            if lat in rankNameLat:
                print >>sys.stdout, "%2.2f%%\t(%s query):\t%s" % ( float(vlat['nb'])*100/nbBlast, vlat['nb'], vlat['latr'])
                outPutFile( lat, vlat )
            else:
                if newAll.has_key( 'No match found' ):
                    newAll['No match found']['nb'] += vlat['nb']
                    newAll['No match found']['blastrecord'].extend( vlat['blastrecord'] )
                else:
                    newAll['No match found']= {'nb': vlat['nb'], 'blastrecord':vlat['blastrecord'], 'latr': 'No match found'}

        else:
            print >>sys.stdout,"%2.2f%%\t(%s query):\t%s" % ( float(vlat['nb'])*100/nbBlast, vlat['nb'], vlat['latr'] )
            outPutFile( lat, vlat, blastoutput, format, queryoutput )
    
    if newAll:
        print >>sys.stdout, "%2.2f%%\t(%s query):\t%s" % ( float(newAll['No match found']['nb'])*100/nbBlast, newAll['No match found']['nb'], newAll['No match found']['latr'] )
        outPutFile( 'No match found', newAll['No match found'], blastoutput, format, queryoutput )
    osVSocBDB.close()
