#! /opt/gensoft/exe/taxoptimizer/2.0/venv/bin/python2.7

# Corinne Maufrais
# Institut Pasteur, Centre d'informatique pour les biologistes
# maufrais@pasteur.fr
#

# version 1.6

import os, sys, getopt
try:
    LIB = os.environ['RANKOPTIMIZERLIB']
except:
    LIB = '/usr/local/bin'
    

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

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

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

import rankoptimizerlib


#import string


def cleanTaxo( sbjctTaxonomy ):
    #-r        ... Clean genbank taxonomy error format (default: false). Very very slow.
    fld1 = sbjctTaxonomy.split('Viruses')
    if len(fld1) > 1 and fld1[0]!= "''":
        if fld1[0] !="cellular organisms; " or (cleanCellular and fld1[0] =="cellular organisms; " ):
            sbjctTaxonomy = 'Viruses'+''.join(fld1[1:])
                        
    fld2 = sbjctTaxonomy.split('Bacteria')
    if len(fld2) > 1 and fld2[0]!= "''":
        if  fld2[0]!="cellular organisms; " or (cleanCellular and fld2[0] =="cellular organisms; "):
            sbjctTaxonomy = 'Bacteria'+''.join(fld2[1:])
    
    fld3 = sbjctTaxonomy.split('Eukaryota')
    if len(fld3) > 1 and fld3[0]!= "''":
        if  fld3[0]!="cellular organisms; " or (cleanCellular and fld3[0] =="cellular organisms; "):
            sbjctTaxonomy = 'Eukaryota'+ ''.join(fld3[1:])
    
    fld4 = sbjctTaxonomy.split('Archaea')
    if len(fld4) > 1 and fld4[0]!= "''":
        if fld4[0]!="cellular organisms; "  or (cleanCellular and fld4[0] =="cellular organisms; "):
            sbjctTaxonomy = 'Archaea'+ ''.join(fld4[1:])
    
    fld5 = sbjctTaxonomy.split('other sequences')
    if len(fld5) > 1 and fld5[0]!= "''":
        if fld5[0]!="cellular organisms; "  or (cleanCellular and fld5[0] =="cellular organisms; "):
            sbjctTaxonomy = 'other sequences'+ ''.join(fld5[1:])

    fld6 = sbjctTaxonomy.split('unclassified sequences')
    if len(fld6) > 1 and fld6[0]!= "''":
        if fld6[0]!="cellular organisms; "  or (cleanCellular and fld6[0] =="cellular organisms; "):
            sbjctTaxonomy = 'unclassified sequences'+ ''.join(fld6[1:])

    return sbjctTaxonomy


def extractTotRank( taxonomy ):
    rank_list = ['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']
    fld = taxonomy.split( ';' )
    all_nodes = []
    for node in fld:
        rank = ''
        fld_node = node.strip().split('(')
        name = fld_node[0].strip()
        if len (fld_node) == 2:
            rank = fld_node[1].split(')')[0].strip()
            rank = rank.replace(' ','_')     
        elif len (fld_node) > 2:
            rank = fld_node[-1].split(')')[0].strip()
            name = fld_node[0]+ fld_node[1].split(')')[0].strip()
            rank = rank.replace(' ','_')
        # suppression of irrelevant punctuation signe in name !!!!!!!!!! PERTE DE TEMPS !!!!
        #name=name.translate(string.maketrans("",""), string.punctuation)
                
        if rank and rank not in rank_list:
            name += '_'+rank
            rank = ''
        if name:
            all_nodes.append( (name, rank) )
    
    return all_nodes


def insertTaxoTot(taxoTree, query, posLine, taxonomy, rankInTree, identicalRead ):  
    all_nodes = extractTotRank(taxonomy)
    if taxoTree.name == 'root':  
        if identicalRead and '_' in query: ## supposed name_n
            n = query.split('_')[-1]
            try:
                nb = int(n)
            except:
                nb=1
            taxoTree.nbQuerys +=nb
        else:
            taxoTree.nbQuerys +=1
    
    try:
        name, rank = all_nodes[0]
    except:
        return taxoTree    
    
    if not taxoTree.hasChild( name ):
        if rankInTree:
            taxoTree.addChild( name, rank )
        else:
            taxoTree.addChild( name, '' )
    child = taxoTree.getChild( name )
    
    #child.addQueries( ( query,  posLine )  )
    
    if identicalRead and '_' in query: ## supposed name_n
        n = query.split('_')[-1]
        try:
            nb = int(n)
        except:
            nb=1
        child.nbQuerys +=nb
    else:
        child.nbQuerys +=1
    for name, rank in all_nodes[1:-1]:
        parent = child
        if name:
            if not parent.hasChild( name ):
                if rankInTree:
                    parent.addChild( name, rank )
                else:
                    parent.addChild( name, '' )
            child = parent.getChild( name )
            #child.addQueries( ( query,  posLine) )
            if identicalRead and '_' in query: ## supposed name_n
                n = query.split('_')[-1]
                try:
                    nb = int(n)
                except:
                    nb=1
                child.nbQuerys +=nb 
            else:
                child.nbQuerys +=1  
            if not child.hasRank() and rankInTree and rank:
                child.rank = rank
    
    # add query name, only on the leaf   
    name, rank = all_nodes[-1]
    parent = child
    if name:
        if not parent.hasChild( name ):
            if rankInTree:
                parent.addChild( name, rank )
            else:
                parent.addChild( name, '' )
        child = parent.getChild( name )
        child.addQueries( ( query,  posLine)  )
        if identicalRead and '_' in query: ## supposed name_n
            n = query.split('_')[-1]
            try:
                nb = int(n)
            except:
                nb=1
            child.nbQuerys +=nb 
        else:
            child.nbQuerys +=1
        if not child.hasRank() and rankInTree and rank:
            child.rank = rank 
    
    return taxoTree 

def insertTaxoTotDelta(taxoTree, query, posLine, taxonomy, rankInTree, identicalRead ):   ### idem que insertTaxoTot why ???????
    all_nodes = extractTotRank(taxonomy)
    if taxoTree.name == 'root':  
        if identicalRead and '_' in query: ## supposed name_n
            n = query.split('_')[-1]
            try:
                nb = int(n)
            except:
                nb=1
            taxoTree.nbQuerys +=nb
        else:
            taxoTree.nbQuerys +=1
    
    try:
        name, rank = all_nodes[0]
    except:
        return taxoTree    
    
    if not taxoTree.hasChild( name ):
        if rankInTree:
            taxoTree.addChild( name, rank )
        else:
            taxoTree.addChild( name, '' )
    child = taxoTree.getChild( name )
    
    #child.addQueries( ( query,  posLine )  )
    if identicalRead and '_' in query: ## supposed name_n
        n = query.split('_')[-1]
        try:
            nb = int(n)
        except:
            nb=1
        child.nbQuerys +=nb
    else:
        child.nbQuerys +=1
    for name, rank in all_nodes[1:-1]:
        parent = child
        if name:
            if not parent.hasChild( name ):
                if rankInTree:
                    parent.addChild( name, rank )
                else:
                    parent.addChild( name, '' )
            child = parent.getChild( name )
            #child.addQueries( ( query,  posLine) )
            if identicalRead and '_' in query: ## supposed name_n
                n = query.split('_')[-1]
                try:
                    nb = int(n)
                except:
                    nb=1
                child.nbQuerys +=nb 
            else:
                child.nbQuerys +=1
            if not child.hasRank() and rankInTree and rank:
                child.rank = rank
    
    # add query name, only on the leaf   
    name, rank = all_nodes[-1]
    parent = child
    if name:
        if not parent.hasChild( name ):
            if rankInTree:
                parent.addChild( name, rank )
            else:
                parent.addChild( name, '' )
        child = parent.getChild( name )
        child.addQueries( ( query,  posLine)  )
        if identicalRead and '_' in query: ## supposed name_n
            n = query.split('_')[-1]
            try:
                nb = int(n)
            except:
                nb=1
            child.nbQuerys +=nb 
        else:
            child.nbQuerys +=1
        if not child.hasRank() and rankInTree and rank:
            child.rank = rank 
    
    return taxoTree 




def reduceBydelta( oneQuery, query, deltaScore ):
    
    # allBYquery[query]['delta'] = [(hspScore, sbjctTaxonomy, posLine )]
    # allBYquery[query]['maxScore'] = (hspScore, sbjctTaxonomy, posLine )
    
    # kept only bline in a delta range
    indx=[]
    for i in range( len(oneQuery['delta']) ):
        if oneQuery['delta'][i][0]> (oneQuery['maxScore'][0] * ( 1 + (deltaScore*0.01) )):
            indx.append(i)
    n = 0
    for j in indx:
        j -= n
        oneQuery['delta'].pop(j)
        n+=1
    
    return oneQuery


def lca( tree ):
    if tree.hasOneChild():
        tree = tree.childs[0]
        return lca( tree )
    else:
        return tree.name
    
##############################################################################
#
#            MAIN
#
##############################################################################


def usage():
    print """
usage: rankoptimizer [options] -i <infile>

options:
   
   -i <file> ... [p]taxoptimizer output file (format: blast m8 + OC + taxonomy +/-  DE ). 

   -h        ... Print this message and exit.

output option:
   -k file      ... xml format with krona Specification
   -t file      ... simple text representation
   -v file      ... html format with krona Specification and krona javascript library
   -j file      ... json format output
   -a           ... Report lowest common ancestor of taxonomic abundance.

specific option:
   -u <str>     ... KronaTools-2.1 http server address (Default: 'http://bioweb2.pasteur.fr/krona').
   
   -d int    ... Percentage of score to be considered to be relevant (default: 0)
   -l        ... Remove 'cellular organism' from taxonomy.
   
   -R        ... Report rank information in xml krona (-k) and html krona (-v) formats. By default, "superkingdom, phylum, ..." information 
                 are not analyzed.
                 Note: If two queries have the same taxonomy but one has rank information [Bacteria (superkingdom); Proteobacteria (phylum); ...]
                 and not the other  [Bacteria; Proteobacteria; ...], they will be in two different nodes in tree and not deal together.
                 
   -c <int>  ... First column of taxonomy information (default column= 14)
   -C <int>  ... Column number of hsp score (default column=12)
    
   -U        ... Reintroduce abundance of identical reads in analyze. Identical reads are treat as unique sequence. The number of identical reads is put at the end of query name (separated by '_').  
   
definition:
    rankoptimizer report taxonomic abundance, based on BLAST hits. rankoptimizer analyze only (p)taxoptimizer output file.
    
    
    rankoptimizer use Krona 2.0 an interactive metagenomic visualization tool in a Web browser.  (http://sourceforge.net/p/krona/home/krona/):
    Ondov BD, Bergman NH, and Phillippy AM. Interactive metagenomic visualization in a Web browser. BMC Bioinformatics. 2011 Sep 30; 12(1):385.
    
"""



if __name__=='__main__':
    # ===== Command line parser
    try:
        opts, args = getopt.gnu_getopt( sys.argv[1:], "hi:o:d:lp:k:t:v:V:c:C:u:j:RUas",["help",] )
    except getopt.GetoptError:
        usage()
        sys.exit( 0 )

    tabFile = None  
    outFile = None 
    deltaScore = 0
    repairGB = False
    cleanCellular = False
    dumpFile = None
    kronaFile = None
    treeFile = None
    jsonFile = None
    kronaHtmlFileWithXML = None
    kronaHtmlFileWithJSON = None
    kronaURLhome = 'http://krona.sourceforge.net'
    kronaURLhome = 'http://bioweb2.pasteur.fr/krona/src'
    kronaScriptOnServer = False #### Remove the possibility to change javascript location. Navigator pb....
    column = 13
    columnScore = 11
    rankInTree = False
    identicalRead = False
    find_lca = False
    
    for o, v in opts: #( opt, value )
        if o in ( "-h","--help" ):
            usage()
            sys.exit( 0 )
        elif o in ( "-i" , "--in" ):
            tabFile = v
        elif o in ( "-d" , "--delta" ):
            deltaScore = int(v)
        elif o in ( "-r" , "--repair" ):
            repairGB = True
        elif o in ( "-l" , "--cellu" ):
            cleanCellular = True
        elif o in ( "-p", "--dump"):
            dumpFile = v
        elif o in ("-k", "--krona"):
            kronaFile = v
        elif o in ("-t", "--tree"):
            treeFile = v
        elif o in ("-v", "--html"):
            kronaHtmlFileWithXML = v
        elif o in ("-V", "--htmlJ"):
            kronaHtmlFileWithJSON = v
        elif o in ("-R", "--html"):
            rankInTree = True
        elif o in ("-j", "--json"):
            jsonFile = v
        elif o in ("-u", "--url"):
            kronaURLhome = v
        elif o in ( "-c" , "--col" ):
            try:
                column = int(v) -1
            except:
                print >>sys.stderr, RankOptimizerError("Integer value is mandatory for column number")
                sys.exit( 0 )
        elif o in ( "-C" , "--coleval" ):
            try:
                columnScore = int(v) -1
            except:
                print >>sys.stderr, RankOptimizerError("Integer value is mandatory for column number")
                sys.exit( 0 )
        elif o in ("-U", "--identical"):
            identicalRead = True
        elif o in ("-a", "--lca"):
            find_lca = True
        elif o in ("-s", "--local_kronaJS"):
            kronaScriptOnServer = True
        else:
            usage()
            sys.exit( 0 )

    if not tabFile:
        usage()
        sys.exit( 0 )
        
        
    # ===== Tabulated file parsing
    try:
        tabfhin = open( tabFile )
    except IOError, err:
        print >>sys.stderr, err
        sys.exit(1)
        
    nbTaxo = 0
    allBYquery = {}
    
    #import time
    #print >>sys.stderr, 'beginning parsing taxoptimizer file', time.strftime("%y/%m/%d %H:%M:%S" , time.localtime(time.time()))
    
    try:
        posLine = tabfhin.tell()
        line = tabfhin.readline()
        blLine = 1
    except IOError, err:
        print >>sys.stderr, RankOptimizerError("readline error: %s line: %s" % (err,blLine) )
        sys.exit()
    
    while line:
        if line =='\n':
            try:
                posLine = tabfhin.tell()
                line = tabfhin.readline()
                blLine += 1
            except IOError, err:
                print >>sys.stderr, RankOptimizerError("readline error: %s line: %s" % (err,blLine) )
                sys.exit()
            continue
        fld = line.split('\t')
        try:
            query = fld[0]
        except StandardError, err:
            print >>sys.stderr, RankOptimizerError("query error: %s line: %s" % (err,blLine) )
            sys.exit()
        
        try:
            if fld[columnScore] and fld[columnScore][0] == 'e':
                num = '1'+ fld[columnScore]
            else:
                num = fld[columnScore]
            hspScore = float(num)
        except StandardError, err:
            print >>sys.stderr, RankOptimizerError("score column number error: -C %s in line %s: %s" % (columnScore+1, blLine, err) )
            sys.exit()
        try:
            sbjctTaxonomy = fld[column]
            sbjctTaxonomy = True
        except:
            sbjctTaxonomy = False
        
        
        
        #{'hspScore':hspScore, 'sbjctTaxonomy': sbjctTaxonomy, 'posLine': posLine }
        # ===> (hspScore,  sbjctTaxonomy, posLine)
        ###### Analyze and stock query
        if allBYquery.has_key(query):
            if not allBYquery[query]['maxScore'][1] or (sbjctTaxonomy and hspScore > allBYquery[query]['maxScore'][0] ):

                allBYquery[query]['maxScore'] = ( hspScore, sbjctTaxonomy, posLine) 
            elif (deltaScore and sbjctTaxonomy) and (hspScore > (allBYquery[query]['maxScore'][0] * ( 1 - (deltaScore*0.01) ))):
                # stock all at one moment. reduce after.
                if allBYquery[query].has_key('delta'):
                    allBYquery[query]['delta'].append((hspScore, sbjctTaxonomy, posLine ))
                else:
                    allBYquery[query]['delta'] = [(hspScore, sbjctTaxonomy, posLine )]
            #else:
            #    print ''
        else:
            allBYquery[query]= {'maxScore': (hspScore, sbjctTaxonomy, posLine )}
            
        
            
        try:
            posLine = tabfhin.tell()
            line = tabfhin.readline()
            blLine += 1
        except IOError, err:
            print >>sys.stderr, RankOptimizerError("%s line: %s" % (err,blLine) )
            sys.exit()

    #tabfhin.close()
    if deltaScore:
        for query in allBYquery.keys():
            if allBYquery[query].has_key('delta') and len(allBYquery[query]['delta']) > 1:
                #avant= len(allBYquery[query]['delta'])
                allBYquery[query] = reduceBydelta( allBYquery[query], query, deltaScore )
    
    ## Construct tree structure
    taxoTree = rankoptimizerlib.Taxon( 'root' )
    #print >>sys.stderr, 'beginning insert taxo', time.strftime("%y/%m/%d %H:%M:%S" , time.localtime(time.time()))
    
    #p = psutil.Process(os.getpid())
    for query,  allBYqueryValues in allBYquery.items():
        posLine = allBYqueryValues['maxScore'][2]
        tabfhin.seek( posLine )
        try:
            line = tabfhin.readline()
            fld = line.split('\t')
        except IOError, err:
            print >>sys.stderr, RankOptimizerError("%s line: %s" % (err,line) )
            sys.exit()
        try:
            sbjctTaxonomy = fld[column].strip() ### taxonomy begin at the 13 column separated by \t
            ####### Clean taxonomy 
            if sbjctTaxonomy[-1]=='.':
                sbjctTaxonomy = sbjctTaxonomy[:-1]+';'
            if cleanCellular:
                sbjctTaxonomy=sbjctTaxonomy.replace('cellular organisms ;', '').strip()
                sbjctTaxonomy=sbjctTaxonomy.replace('cellular organisms;', '').strip()
            #if repairGB and sbjctTaxonomy: ### slow
            #    sbjctTaxonomy = cleanTaxo(sbjctTaxonomy)
        
        except:
            print >>sys.stderr, 'no taxo found for %s' % query
            continue
        
        taxoTree = insertTaxoTot(taxoTree, query, posLine, sbjctTaxonomy, rankInTree, identicalRead)
        
        if allBYqueryValues.has_key('delta'):
            allDeltaTaxo = [sbjctTaxonomy]
            for qd in allBYqueryValues['delta']:
                posLine = qd[2]
                tabfhin.seek( posLine )
                blLine = tabfhin.readline()
                fld = blLine.split('\t')
                try:
                    sbjctTaxonomy = fld[column].strip()
                    ####### Clean taxonomy 
                    if sbjctTaxonomy[-1]=='.':
                        sbjctTaxonomy = sbjctTaxonomy[:-1]+';'
                    if cleanCellular:
                        sbjctTaxonomy=sbjctTaxonomy.replace('cellular organisms ;', '').strip()
                        sbjctTaxonomy=sbjctTaxonomy.replace('cellular organisms;', '').strip()
                    #if repairGB and sbjctTaxonomy: ### slow
                    #    sbjctTaxonomy = cleanTaxo(sbjctTaxonomy)
                except:
                    print >>sys.stderr, 'no taxo found for %s' % query
                    continue
                if sbjctTaxonomy not in allDeltaTaxo:
                    taxoTree = insertTaxoTotDelta(taxoTree, query, posLine, sbjctTaxonomy, rankInTree, identicalRead)
                    allDeltaTaxo.append(sbjctTaxonomy)
        #print >>sys.stderr, p.get_memory_info()
        allBYquery.pop( query )
    #print >>sys.stderr,  os.popen('ps -p %d -l' %(os.getpid())).read()
    #print >>sys.stderr,  int(os.popen('ps -p %d -o %s | tail -1' %(os.getpid(), "rss")).read())
    #print >>sys.stderr,  int(os.popen('ps -p %d -o %s | tail -1' %(os.getpid(), "vsz")).read())
    #print >>sys.stderr, p.get_memory_info()
    tabfhin.close()
    #### output
    if treeFile:
        #print >>sys.stderr, 'beginning tree file writing', time.strftime("%y/%m/%d %H:%M:%S" , time.localtime(time.time()))
        try:
            outfh = open( treeFile, 'w' )
            treeRepr =  rankoptimizerlib.toTree( taxoTree, qrName=False )
            print >>outfh, treeRepr
        except IOError, err: 
            print >>sys.stderr, err
    
    
    if jsonFile:
        try:
            outfh = open( jsonFile, 'w' )
            kronaJson = rankoptimizerlib.KronaJSON( outfh, tabFile, taxoTree) 
            kronaJson.krona()
        except IOError, err: 
            print >>sys.stderr, err
               
    if kronaFile:
        #print >>sys.stderr, 'beginning xml krona file writing', time.strftime("%y/%m/%d %H:%M:%S" , time.localtime(time.time()))
        try:
            outfh = open( kronaFile, 'w' )
            kronaXML = rankoptimizerlib.Krona( outfh, tabFile, taxoTree, kronaURLhome, kronaScriptOnServer=kronaScriptOnServer ) 
            kronaXML.krona()
        except IOError, err: 
            print >>sys.stderr, err
            
    if kronaHtmlFileWithXML:
        #print >>sys.stderr, 'beginning html krona file writing', time.strftime("%y/%m/%d %H:%M:%S" , time.localtime(time.time()))
        try:
            outfh = open( kronaHtmlFileWithXML, 'w' )
            kronaXML = rankoptimizerlib.Krona( outfh, tabFile, taxoTree, kronaURL=kronaURLhome, kronaScriptOnServer=kronaScriptOnServer ) 
            kronaXML.kronaHtml()
        except IOError, err: 
            print >>sys.stderr, err
    if kronaHtmlFileWithJSON:
        #print >>sys.stderr, 'beginning html krona file writing', time.strftime("%y/%m/%d %H:%M:%S" , time.localtime(time.time()))
        try:
            outfh = open( kronaHtmlFileWithJSON, 'w' )
            kronaJSON = rankoptimizerlib.KronaJSON( outfh, tabFile, taxoTree, kronaURL=kronaURLhome, kronaScriptOnServer=kronaScriptOnServer ) 
            kronaJSON.kronaHtml()
        except IOError, err: 
            print >>sys.stderr, err
    if dumpFile:
        import pickle
        txfh = open(dumpFile, 'w')
        pickle.dump(taxoTree, txfh)
        txfh.close()
    
    
    
    if find_lca:
        print 'Lowest common ancestor: ', lca(taxoTree)
