#! /usr/bin/env python
#
# Copyright INRA-URGI 2009-2010
# 
# This software is governed by the CeCILL license under French law and
# abiding by the rules of distribution of free software. You can use,
# modify and/ or redistribute the software under the terms of the CeCILL
# license as circulated by CEA, CNRS and INRIA at the following URL
# "http://www.cecill.info".
# 
# As a counterpart to the access to the source code and rights to copy,
# modify and redistribute granted by the license, users are provided only
# with a limited warranty and the software's author, the holder of the
# economic rights, and the successive licensors have only limited
# liability.
# 
# In this respect, the user's attention is drawn to the risks associated
# with loading, using, modifying and/or developing or reproducing the
# software by the user in light of its specific status of free software,
# that may mean that it is complicated to manipulate, and that also
# therefore means that it is reserved for developers and experienced
# professionals having in-depth computer knowledge. Users are therefore
# encouraged to load and test the software's suitability as regards their
# requirements in conditions enabling the security of their systems and/or
# data to be ensured and, more generally, to use and operate it in the
# same conditions as regards security.
# 
# The fact that you are presently reading this means that you have had
# knowledge of the CeCILL license and that you accept its terms.
#
"""
Plot the data from the data files
"""
import os
from optparse import OptionParser
from commons.core.parsing.GffParser import GffParser
from SMART.Java.Python.misc.RPlotter import RPlotter
from SMART.Java.Python.misc.Progress import Progress


if __name__ == "__main__":
    
    # parse command line
    description = "Plot Repartition v1.0.1: Plot the repartition of different data on a whole genome. (This tool uses 1 input file only, the different values being stored in the tags.    See documentation to know more about it.) [Category: Visualization]"

    parser = OptionParser(description = description)
    parser.add_option("-i", "--input",     dest="inputFileName",  action="store",                           type="string", help="input file name [compulsory] [format: file in GFF3 format]")
    parser.add_option("-n", "--names",     dest="names",          action="store",      default=None,        type="string", help="name for the tags (separated by commas and no space) [default: None] [format: string]")
    parser.add_option("-o", "--output",    dest="outputFileName", action="store",                           type="string", help="output file [compulsory] [format: output file in PNG format]")
    parser.add_option("-c", "--color",     dest="colors",         action="store",      default=None,        type="string", help="color of the lines (separated by commas and no space) [format: string]")
    parser.add_option("-f", "--format",    dest="format",         action="store",      default="png",       type="string", help="format of the output file [format: string] [default: png]")
    parser.add_option("-r", "--normalize", dest="normalize",      action="store_true", default=False,                      help="normalize data (when panels are different) [format: bool] [default: false]")
    parser.add_option("-l", "--log",       dest="log",            action="store",      default="",          type="string", help="use log on x- or y-axis (write 'x', 'y' or 'xy') [format: string]")
    parser.add_option("-v", "--verbosity", dest="verbosity",      action="store",      default=1,           type="int",    help="trace level [format: int]")
    parser.add_option("-D", "--directory", dest="working_Dir",    action="store",      default=os.getcwd(), type="string", help="the directory to store the results [format: directory]")
    (options, args) = parser.parse_args()

    strands        = [1, -1]
    strandToString = {1: "+", -1: "-"}
    names          = [None] if options.names == None else options.names.split(",")
    maxs           = {}
    nbElements     = [0 for name in names]
    lines          = [{} for i in range(len(names))]
    if options.colors == None:
        colors = [None for i in range(len(names))]
    else:
        colors = options.colors.split(",")

    parser = GffParser(options.inputFileName, options.verbosity)
    progress = Progress(parser.getNbTranscripts(), "Reading %s" % (options.inputFileName), options.verbosity)
    for transcript in parser.getIterator():
        chromosome = transcript.getChromosome()
        direction  = transcript.getDirection()
        start      = transcript.getStart()
        for i, name in enumerate(names):
            if chromosome not in lines[i]:
                lines[i][chromosome] = dict([(strand, {}) for strand in strands])
            if chromosome not in maxs:
                maxs[chromosome] = transcript.getStart()
            else:
                maxs[chromosome] = max(maxs[chromosome], start)
            if start not in lines[i][chromosome][direction]:
                lines[i][chromosome][direction][start] = 0
            thisNbElements                          = float(transcript.getTagValue(name)) if name != None and name in transcript.getTagNames() else 1
            lines[i][chromosome][direction][start] += thisNbElements * direction
            nbElements[i]                          += thisNbElements
        progress.inc()
    progress.done()

    if options.normalize:
        if options.verbosity >= 10:
            print "Normalizing..."
        for i, linesPerCondition in enumerate(lines):
            for linesPerChromosome in linesPerCondition.values():
                for line in linesPerChromosome.values():
                    for key, value in line.iteritems():
                        line[key] = value / float(nbElements[i]) * max(nbElements)
    if options.verbosity >= 10:
        print "... done."

    progress = Progress(len(maxs.keys()), "Plotting", options.verbosity)
    for chromosome in maxs:
        plot = RPlotter("%s%s.%s" % (options.outputFileName, chromosome.capitalize(), options.format), options.verbosity)
        plot.setLog(options.log)
        plot.setImageSize(2000, 500)
        plot.setFormat(options.format)
        if maxs[chromosome] <= 1000:
            unit    = "nt."
            ratio = 1.0
        elif maxs[chromosome] <= 1000000:
            unit    = "kb"
            ratio = 1000.0
        else:
            unit    = "Mb"
            ratio = 1000000.0
        plot.setXLabel("Position on %s (in %s)" % (chromosome.replace("_", " "), unit))
        plot.setYLabel("# reads")
        plot.setLegend(True)
        for i, name in enumerate(names):
            for strand in strands:
                correctedLine = dict([(key / ratio, value) for key, value in lines[i][chromosome][strand].iteritems()])
                if name != None:
                    name = "%s (%s)" % (name.replace("_", " "), strandToString[strand])
                plot.addLine(correctedLine, None, colors[i])
        plot.plot()
        progress.inc()
    progress.done()

