#! /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.
#
"""Get the distance between the transcripts of two lists"""

import os
import sys
from optparse import OptionParser
from SMART.Java.Python.structure.TranscriptListsComparator import TranscriptListsComparator
from SMART.Java.Python.structure.TranscriptContainer import TranscriptContainer
from SMART.Java.Python.misc.RPlotter import RPlotter
from commons.core.writer.Gff3Writer import Gff3Writer

class GetDistance(object):

    def __init__(self, verbosity = 0):
        self.verbosity      = verbosity
        self.writer         = None
        self.spearman       = False
        self.tlc            = TranscriptListsComparator(None, self.verbosity)
        self.strands        = (0, )
        self.buckets        = None
        self.title          = ""
        self.xMin           = None
        self.xMax           = None
        self.proportion     = False
        self.outputFileName = None
        self.keep           = False

    def __del__(self):
        pass

    def setQueryFile(self, fileName, format):
        self.transcriptContainer1 = TranscriptContainer(fileName, format, self.verbosity)
        
    def setReferenceFile(self, fileName, format):
        self.transcriptContainer2 = TranscriptContainer(fileName, format, self.verbosity)

    def setOutputFile(self, fileName):
        self.outputFileName = fileName
        
    def setOutputTranscriptFile(self, fileName):
        if fileName != None:
            self.writer = Gff3Writer(fileName, self.verbosity)
        
    def restrictQueryToStart(self, number):
        self.tlc.restrictToStart(self.tlc.QUERY, number)

    def restrictReferenceToStart(self, number):
        self.tlc.restrictToStart(self.tlc.REFERENCE, number)

    def restrictQueryToEnd(self, number):
        self.tlc.restrictToEnd(self.tlc.QUERY, number)

    def restrictReferenceToEnd(self, number):
        self.tlc.restrictToEnd(self.tlc.REFERENCE, number)

    def setAbsolute(self, boolean):
        self.tlc.setAbsolute(boolean)

    def setProportion(self, boolean):
        self.proportion = boolean

    def setColinear(self, boolean):
        self.tlc.getColinearOnly(boolean)

    def setAntisense(self, boolean):
        self.tlc.getAntisenseOnly(boolean)

    def setDistances(self, minDistance, maxDistance):
        self.tlc.setMinDistance(minDistance)
        self.tlc.setMaxDistance(maxDistance)

    def setStrands(self, boolean):
        self.tlc.setStrandedDistance(boolean)
        if boolean:
            self.strands = (-1, 1)

    def setUpstream(self, number):
        self.tlc.setUpstream(self.tlc.REFERENCE, number)

    def setDownstream(self, number):
        self.tlc.setDownstream(self.tlc.REFERENCE, number)

    def setBuckets(self, number):
        self.buckets = number

    def setTitle(self, title):
        self.title = title

    def setXValues(self, xMin, xMax):
        self.xMin, self.xMax = xMin, xMax

    def keepTmpValues(self, boolean):
        self.keep = boolean

    def getSpearman(self, boolean):
        self.spearman = True

    def compare(self):
        self.tlc.setInputTranscriptContainer(self.tlc.QUERY, self.transcriptContainer1)
        self.tlc.setInputTranscriptContainer(self.tlc.REFERENCE, self.transcriptContainer2)
        self.tlc.setOutputWriter(self.writer)
        self.distances = self.tlc.compareTranscriptListDistance()

    def checkEmptyDistances(self):
        return (sum([len(self.distances[strand].keys()) for strand in self.strands]) == 0)

    def setPlotterMinusStrand(self):
        if -1 in self.strands:
            for x, y in self.distances[-1].iteritems():
                self.distances[-1][x] = -y

    def setPlotterProportion(self):
        if not self.proportion:
            return
        self.nbElements = sum([abs(sum(self.distances[strand].values())) for strand in self.strands])
        for strand in self.strands:
            self.distances[strand] = dict([(distance, float(nb) / self.nbElements * 100) for distance, nb in self.distances[strand].iteritems()])

    def setPlotter(self):
        self.plotter = RPlotter(self.outputFileName, self.verbosity, self.keep)
        if self.buckets != None:
            self.plotter.setBarplot(True)
        self.plotter.setFill(0)
        self.plotter.setXLabel("distance")
        self.plotter.setYLabel("# elements")
        if self.proportion:
            self.plotter.setYLabel("%% elements (%d in toto)" % (self.nbElements))
        self.plotter.setBuckets(self.buckets)
        self.plotter.setMinimumX(self.xMin)
        self.plotter.setMaximumX(self.xMax)
        self.plotter.setTitle(self.title)

    def plot(self):
        if len(self.strands) == 1:
            self.distances = {0: self.distances}
        if self.checkEmptyDistances():
            print "No output."
            sys.exit()
        self.setPlotterMinusStrand()
        self.setPlotterProportion()
        if self.outputFileName == None:
            return
        self.setPlotter()
        for strand in self.strands:
            self.plotter.addLine(self.distances[strand])
        self.plotter.plot()

    def printSpearman(self):
        if self.spearman:
            print "Spearman's rho: %.5f" % (self.plotter.getSpearmanRho())

    def run(self):
        self.compare()
        self.plot()
        self.printSpearman()

if __name__ == "__main__":
    
    # parse command line
    description = "Get Distance v1.0.3: Compute the distance of a set of transcript with respect to a reference set. [Category: Visualization]"

    parser = OptionParser(description = description)
    parser.add_option("-i", "--input1",          dest="inputFileName1",  action="store",                    type="string", help="input file 1 [compulsory] [format: file in transcript format given by -f]")
    parser.add_option("-f", "--format1",         dest="format1",         action="store",                    type="string", help="format of file 1 [compulsory] [format: transcript file format]")
    parser.add_option("-j", "--input2",          dest="inputFileName2",  action="store",                    type="string", help="input file 2 [compulsory] [format: file in transcript format given by -g]")
    parser.add_option("-g", "--format2",         dest="format2",         action="store",                    type="string", help="format of file 2 [compulsory] [format: transcript file format]")
    parser.add_option("-o", "--output",          dest="outputFileName",  action="store",                    type="string", help="plot output file [format: output file in PNG format]")
    parser.add_option("-O", "--outputDistances", dest="outputDistances", action="store",      default=None, type="string", help="output file containing the distance for each element of the query [format: output file in GFF3 format] [default: None]")
    parser.add_option("-c", "--colinear",        dest="colinear",        action="store_true", default=False,               help="only consider features on the same strand [format: bool] [default: false]")
    parser.add_option("-a", "--antisense",       dest="antisense",       action="store_true", default=False,               help="only consider features on the opposite strand [format: bool] [default: false]")
    parser.add_option("-b", "--absolute",        dest="absolute",        action="store_true", default=False,               help="give the absolute value of the distance [format: bool] [default: false]")
    parser.add_option("-p", "--proportion",      dest="proportion",      action="store_true", default=False,               help="give the proportion on the y-axis instead of the number of distances [format: bool] [default: false]")
    parser.add_option("-s", "--start1",          dest="start1",          action="store",      default=None, type="int",    help="only consider the n first 5' nucleotides for list 1 [format: int]")
    parser.add_option("-S", "--start2",          dest="start2",          action="store",      default=None, type="int",    help="only consider the n first 5' nucleotides for list 2 [format: int]")
    parser.add_option("-e", "--end1",            dest="end1",            action="store",      default=None, type="int",    help="only consider the n last 3' nucleotides for list 1 [format: int]")
    parser.add_option("-E", "--end2",            dest="end2",            action="store",      default=None, type="int",    help="only consider the n last 3' nucleotides for list 2 [format: int]")
    parser.add_option("-m", "--minDistance",     dest="minDistance",     action="store",      default=None, type="int",    help="minimum distance considered between two transcripts [format: int] [default: None]")
    parser.add_option("-M", "--maxDistance",     dest="maxDistance",     action="store",      default=1000, type="int",    help="maximum distance considered between two transcripts [format: int] [default: 1000]")
    parser.add_option("-5", "--fivePrime",       dest="fivePrime",       action="store_true", default=False,               help="consider the elements from list 1 which are upstream of elements of list 2 [format: bool] [default: False]")
    parser.add_option("-3", "--threePrime",      dest="threePrime",      action="store_true", default=False,               help="consider the elements from list 1 which are downstream of elements of list 2 [format: bool] [default: False]")
    parser.add_option("-u", "--buckets",         dest="buckets",         action="store",      default=None, type="int",    help="plot histogram instead of line plot with given interval size [format: int] [default: None]")
    parser.add_option("-2", "--2strands",        dest="twoStrands",      action="store_true", default=False,               help="plot the distributions of each strand separately [format: bool] [default: False]")
    parser.add_option("-r", "--spearman",        dest="spearman",        action="store_true", default=False,               help="compute Spearman rho [format: bool] [default: False]")
    parser.add_option("-x", "--xMin",            dest="xMin",            action="store",      default=None, type="int",    help="minimum value on the x-axis to plot [format: int] [default: None]")
    parser.add_option("-X", "--xMax",            dest="xMax",            action="store",      default=None, type="int",    help="maximum value on the x-axis to plot [format: int] [default: None]")
    parser.add_option("-t", "--title",           dest="title",           action="store",      default=None, type="string", help="title for the graph [format: int] [default: None]")
    parser.add_option("-v", "--verbosity",       dest="verbosity",       action="store",      default=1,    type="int",    help="trace level [format: int]")
    parser.add_option("-k", "--keep",            dest="keep",            action="store_true", default=False,               help="keep temporary files [format: bool]")
    (options, args) = parser.parse_args()

    gd = GetDistance(options.verbosity)
    gd.setQueryFile(options.inputFileName1, options.format1)
    gd.setReferenceFile(options.inputFileName2, options.format2)
    gd.setOutputFile(options.outputFileName)
    gd.setOutputTranscriptFile(options.outputDistances)
    gd.setColinear(options.colinear)
    gd.setAntisense(options.antisense)
    gd.setAbsolute(options.absolute)
    gd.setProportion(options.proportion)
    gd.restrictQueryToStart(options.start1)
    gd.restrictReferenceToStart(options.start2)
    gd.restrictQueryToEnd(options.end1)
    gd.restrictReferenceToEnd(options.end2)
    gd.setDistances(options.minDistance, options.maxDistance)
    gd.setUpstream(options.fivePrime)
    gd.setDownstream(options.threePrime)
    gd.setStrands(options.twoStrands)
    gd.setBuckets(options.buckets)
    gd.setTitle(options.title)
    gd.setXValues(options.xMin, options.xMax)
    gd.keepTmpValues(options.keep)
    gd.run()
