#!/opt/gensoft/exe/ELP/3.0/venv/bin/python2.7

"""
ELP - the Evolutionary Landscape Painter - v3.0
"""

########

import getopt
from os.path import isfile, isdir, exists
from os import makedirs
import sys
from time import localtime
from pyELP import elp_var
from pyELP import elp_data

########

version = '3.0.4'
output_directory = "./Outputs"


def usage():
    print """
-----------------------------------------------------
  ELP - the Evolutionary Landscape Painter (v%s)
-----------------------------------------------------

 elp [-n <sequence>][-g <%%gc>][-f <forbiden,>][-c][-s <structure>][-i <start>] <DNA seq>

 -h                print this message
 
 -n <sequence>     the number of synonymous sequences to generate
                   default and minimum is 1, maximum is 3
                   
 -g <%%gc>          the required G+C content of the output sequences

 -f <forbiden,>    the forbiden codons (separated by comma)

 -c                force to maximize Codon Adaptation Index of the generated sequences
                   override the -g option
                   
 -s <structure>    to minimize structure in the initiation region.
                   provide the minimal free energy, the start and end position of the window to consider
                   (positions numbered according to coding sequence start - see option i) and finally the 
                   maximal number of iterations in the optimization process (limited to 100).
                   separate values by comma. Use d for default parameters: wt,-25,35,10
                   when minimal free energy is set to wt, the minimal free energy of the input sequence is
                   used as a threshold. Specifying a number higher than the wt leads to synonymous mutations
                   in the input sequence to lower initial structure below the provided threshold.

-i <start>         position of the coding sequence start
                   the sequence before that position is defined as the 5'UTR
                                 

 <DNA seq>         the file must be in fasta format
 
 For more information, please refer to:
    Cambray G. & Mazel D.
    Synonymous Genes Explore Different Evolutionary Landscapes
    PLoS Genetics, 2008
    """ % version


def get_arg():
    """
    Process the options and arguments
    Return a dictionnary of options and a Seq object corresponding to the input file
    """
    opt, arg = getopt.getopt(sys.argv[1:], 'n:g:f:t:chdi:s:')

    options  = {}
    for key,value in opt:
        options[key] = value
    if  options.has_key('-h'):
        usage()
        sys.exit(0)    
    if len(arg) != 1:
        usage()
        print >>sys.stderr, 'Only one argument, the input fasta file, should be specified'
        sys.exit(1)  
    seq_file = arg[0]
    
    
    # Handle option defaults
    if not options.has_key('-n'):
        options['-n'] = 1
        
    if not options.has_key('-g'):
        options['-g'] = '50.9' # E.coli's G+C content
        
    if not options.has_key('-f'):
        options['-f'] = 'CTG,AGG,ATA,TAG'
        
    if not options.has_key('-c'):
        options['-c'] = False
    else:
        options['-c'] = True
        
    if not options.has_key('-i'):
        options['-i'] = 1
        
    if not options.has_key('-s'):
        options['-s'] = False
    elif options['-s'] == "d":
        options['-s'] = "wt,-25,35,10"

        
    # Process options
    options['-n'] = int(options['-n'])
    if not 0 < options['-n'] < 4:
        print >>sys.stderr, "the '-n' option should specify a number of sequence between 1 and 3 included"
        usage()
        sys.exit(1)  
    
    try:
        options['-g'] = float(options['-g'])
    except:
        options['-g'] = options['-g'].replace(',','.')
        try:
            options['-g'] = float(options['-g'])
        except:
            print >>sys.stderr, "the '-g' option should specify the G+C% of the gene and should be a number, not %s options['-g']"
            usage()
            sys.exit(1)  
    
    options['-f'] = options['-f'].split(',')
    if not options['-f'] or 'no' in options['-f'] or 'No' in options['-f']:
        options['-f'] = []
    else:
        for codon in options['-f']:
            if codon not in elp_data.Dgenetic_code.keys():
                usage()
                print >>sys.stderr, "the '-f' option should specify codons: %s is not a codon" % codon          
                sys.exit(1)
    
    options['-i'] = int(options['-i'])-1 #convert to 0-based position numbering
    
    if options['-s']:
        # Path to folding programs
        options['hybrid_ss_min'] = "hybrid-ss-min"
        options['sir_graph'] = "sir_graph"
        
        # Process structure string
        options['-s'] = options['-s'].split(",")
        
        if len(options['-s']) != 4:
            print >>sys.stderr, "the '-s' option should specify 4 numbers: minimum allowed free energy, start and end of the sequence and number of optization iteration, separated by comma"
            usage()
            sys.exit(1)
        if options['-s'][0] == "wt":
            options["struct_min"] = options['-s'][0]
        else:
            try:
                options["struct_min"] = float(options['-s'][0])
            except:
                print >>sys.stderr, "the '-s' option should first specify minimum allowed free energy as wt or a floating number not %s" % options['-s'][0]
                usage()
                sys.exit(1)
            if options["struct_min"] > 0:
                print >>sys.stderr, "the minimum free energy specified in the '-s' option should be negative (not %.2f)" % options['-s'][0]
                usage()
                sys.exit(1)
        
        try:
            options["struct_win_start"] = options['-i']+int(options['-s'][1])
        except:
            print >>sys.stderr, "the '-s' option should specify the structure window start position as an integer"
            usage()
            sys.exit(1)
        if int(options['-s'][1]) == 0 :
            raise(">>sys.stderr, the window start position in the '-s' option cannot be 0")
        if int(options['-s'][1]) > 0 :
            options["struct_win_start"] -= 1
            
        try:
            options["struct_win_end"] = options['-i']+int(options['-s'][2])
        except:
            print >>sys.stderr, "the '-s' option should specify the structure window end position as an integer"
            usage()
            sys.exit(1)
        if int(options['-s'][1]) >= int(options['-s'][2]):
            print >>sys.stderr, "the structure window specified in the '-s' option is not valid (start %s located after end %s))" % (options['-s'][1], options['-s'][2])
            usage()
            sys.exit(1)
        
        try:
            options["iterations_nbr"] = int(options['-s'][3])
        except:
            print >>sys.stderr, "the '-s' option should specify a maximal iteration number for the optimization as an integer"
            usage()
            sys.exit(1)
        if options["iterations_nbr"] >100:
            print >>sys.stderr, "specified number of iterations for the optimization of structure is too large (%s): Set to 100" % options["iterations_nbr"] 
            options["iterations_nbr"] = 100
            
            
            
        # convert end coordinates to corresponding codon coordinates
        options["struct_win_end_cod"] = int(options['-s'][2])/3 + (int(options['-s'][2]) % 3 > 0)
            
    # Process fasta file
    if not isfile(seq_file):
        usage()
        print >>sys.stderr, 'the specified file (%s) does not exist' % seq_file
        sys.exit(1)   
    
    try:
        # file exist does not means we have rights to read it.
        f = open(seq_file)
    except IOError as msg:
        print >> sys.stderr, msg
        sys.exit(1)

    name    = ''
    seq     = ''
    removed = []
    pos     = 0
    for line in f:
        if not name and line[0] == '>':
            name = line[1:-1]
        elif name and line[0] == '>':
            break
        elif name:
            for c in line.strip():
                pos += 1
                if c in 'ATGCatgc':
                    seq += c.upper()
                else:
                    removed.append((c, pos)) 
    f.close()
    if removed:
        print 'Some characters were removed from the input sequence:'
        for c, pos in removed:
            print '%s at position %i' % (c, pos)
    
    utr = seq[:options['-i']]
    seq = seq[options['-i']:]
    valid_starts = ['ATG', 'GTG', 'TTG']
    if not seq[:3] in valid_starts:
        print >>sys.stderr, 'The specified gene does not begin by a valid initiation codon (i.e. %s)' % ' or '.join(valid_starts)
        sys.exit(1)
    trailing = len(seq)%3
    if trailing != 0:
        print 'The specified gene contains %i extra-bases that will be ignored at the end of the sequence (%s)' % (trailing, seq[-trailing:])
        seq = seq[:-trailing]
    if len(seq) < 3:
        print >>sys.stderr, 'No sequence were specified (the input is likely to be empty)'
        sys.exit(1)
    for i in range(0,len(seq)-3,3):
        if elp_data.Dgenetic_code[seq[i:i+3]] == '*':
            seq = seq[:i]
            print 'A stop codon was found at position %i - the downstream sequence was discarded' % i
            break
    in_seq = elp_var.Seq(name, seq, utr)
      
    # final checks and processing for structure options
    if options['-s']:        
        if options["struct_win_start"] < 0:
            print >>sys.stderr, "the '-s' option specify a window extending beyond the beginning of provided sequence  (starts at %i with respect to full input sequence)" % options["struct_win_start"]
            usage()
            sys.exit(1)
        if options["struct_win_end"] > in_seq.full_len():
            print >>sys.stderr, "the '-s' option specify a window extending beyond the end of provided sequence  (end at %i with respect to full input sequence of %i)" % (options["struct_win_end"], in_seq.full_len())
            usage()
            sys.exit(1)
        if options["struct_win_start"] > options["struct_win_end"]:
            print >>sys.stderr, "the '-s' option should specify valid window coordinates (not %i : %i with respect to full input sequence)" % (options["struct_win_start"], options["struct_win_end"])
            usage()
            sys.exit(1)
        
        # Check input sequence structure
        in_seq.check_structure(options)
        options["keep_ref"]  = True
        options["struct_wt"] = False
        options["struct_init"] = in_seq.mfe
        if options["struct_min"] == "wt":
             in_seq.struct_status = True
             options["struct_min"] = in_seq.mfe
             options["struct_wt"]  = True
        elif options["struct_min"] > in_seq.mfe:
             options["keep_ref"]   = False
        
        if options["struct_min"] > 0:
            print >>sys.stderr, "the '-s' option should specify a negative minimum allowed free energy, not %f" % options["struct_min"]
            usage()
            sys.exit(1)
            
    return options, in_seq


def write_output(path):
    """
    write output to sequences.fas and stat.txt
    """
    
    time = (version,)+localtime()[:5]
    
    try:
        f = open(str(path)+'/stat.txt', 'w')
        s = open(str(path)+'/sequences.fas', 'w')
    except IOError as msg:
        print >> sys.stderr, msg
        sys.exit(1)

    f.write('ELP - The Evolutionary Landscape Painter v%s (%i.%i.%i %i:%i)\n\n' % time)
    f.write('Please cite:\n')
    f.write('  Cambray G. and Mazel D.\n')
    f.write('  Synonymous Genes Explore Different Evolutionary Landscapes\n')
    f.write('  PLoS Genetics, 2008\n')
    f.write('\n\n-------------------------------------------------------\n')
    f.write(' Synonymous sequences with best evolutionary landscape\n')
    f.write('-------------------------------------------------------\n\n')
    
    for seq in seqs.seqs:
        f.write('%s\n' % seq.__str__())
        s.write('>%s\n%s\n' % (seq.name,seq.seq))
    s.close()
    f.write('\n------------------\n\n')
    if options["-s"]:
        f.write('Structures\n\n')
        if options["struct_wt"]:
            f.write("Threshold set to value of the input sequence (%.1f kcal/mole)\n\n" % options["struct_init"])
        if not options["keep_ref"]:
            f.write("Input sequence modified because its structure was stronger than the specified threshold (%.1f < %.1f)\n\n" % (options["struct_init"], options["struct_min"]))
        for seq in seqs:
            f.write("%s : %.1f kcal/mole\n" % (seq.name, seq.mfe))
        f.write('\n')
    f.write('G+C% and Codon Adaptation Index (E.coli)\n')
    for seq in seqs.seqs:
        seq.print_stat(f)
    f.write('\nPairwise identities:\n')
    seqs.print_id(f)
    f.write('\nPairwise Relative Evolutionary Potentials:\n')
    seqs.rep.print_rep(f)
    f.write('\n\n-----------------------------------------------------\n')
    f.write(' Overall evolutionary landscape for pooled sequences\n')
    f.write('-----------------------------------------------------\n\n')
    seqs.print_aa_landscape(f)
    f.write('\n\n-----------------------------------------------------\n')
    f.write(' Evolutionary landscapes of each individual sequence\n')
    f.write('-----------------------------------------------------\n\n')
    for seq in seqs:
        f.write('* %s\n'%seq.name.split('_')[-1])
        seq.print_aa_landscape(f)
        f.write('\n')
    f.close()

if __name__ == '__main__':
    ### var to implement
    # all optimsation is done codon by codon
    # structure can only be done after alt sequences are generated
    # need option to decide whether to optimize the original sequence as well
    # need to decide which metric to use: window   
    
    options, in_seq = get_arg()
    
    seqs = elp_var.Seqs(in_seq, options['-n']+1, options['-g'])
    alt_combi = []
    

    start = 1
    stop  = None
    if elp_data.Dgenetic_code[in_seq.seq[-3:stop]] == '*':
        stop = -1
    
    #  First optimize under structural constraints over the requested window
    if options["-s"]:
        for codon in in_seq.cod[start:options["struct_win_end_cod"]]:
            alt_combi.append(elp_var.best_combi(codon, seqs, options, struct=True, keep_ref = options["keep_ref"]))
        optimized = []
        best      = 0
        attempts  = 0
        # try optimizing several times but break if meet the thresholds 
        while attempts < options["iterations_nbr"]:
            optimized.append(elp_var.optimize_structures(seqs, alt_combi, options, cycle=50))
            print attempts, optimized[-1].mfes_mean, optimized[-1].mfes_var, optimized[-1].mfes
            if optimized[-1].struct_status:
                best = attempts
                break
            attempts += 1
        # if threshold not met, select the results with lowest average structure
        if not best:
            for i in range(1,len(optimized)):
                if optimized[i].mfes_mean >= optimized[best].mfes_mean:
                    best = i
        seqs = optimized[best]
        print seqs.mfes_mean, seqs.mfes_var, seqs.mfes
        if not seqs.struct_status:
            print >>sys.stderr, "WARNING: The structure threshold (%.1f) could not be met for all alternative sequences (%s)." % (options["struct_min"], ", ".join(["%.1f" % mfe for mfe in seqs.mfes]))  
        start = options["struct_win_end_cod"]
    
    # Optimize codon by codon
    for codon in in_seq.cod[start:stop]:
        alt_combi.append(elp_var.best_combi(codon, seqs, options))
        seqs + alt_combi[-1][0]
    if stop:
        seqs.add_stop()
    
    # OUTPUT
    # Check existence of Output directory and create one if none
    if not exists(output_directory):
        try:
            makedirs(output_directory)
        except IOError as msg:
            print >>sys.stderr, msg
            sys.exit(1)
    elif not isdir(output_directory):
        print >> sys.stderr, "Could not create %s, file exists" %(output_directory)
        sys.exit(1)

    
    # Text Files 
    write_output(output_directory)
    
    # Drawings
    if options['-s']:
        seqs.draw_structures(options, output_directory)
    
    if len(seqs[0]) > 10000:
        print >> sys.stderr , """The input sequence is too large (>10kb) to draw the graphical representations of the sequences evolutionary landscape.
Please refer to the text version of these landscapes in the stat.txt file"""
        sys.exit(0)
    seqs.draw(output_directory)
    