#! /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.
#
"""Compare overlap of two transcript lists"""
import sys
import os
from optparse import OptionParser
from SMART.Java.Python.misc import Utils
from SMART.Java.Python.structure.TranscriptContainer import TranscriptContainer
from commons.core.writer.TranscriptWriter import TranscriptWriter
from SMART.Java.Python.structure.TranscriptListsComparator import TranscriptListsComparator
from SMART.Java.Python.misc.RPlotter import RPlotter
from commons.core.writer.Gff3Writer import Gff3Writer

class CompareOverlapping(object):

    def __init__(self):
        self._options = None


    def setAttributesFromCmdLine(self):
        description = "Compare Overlapping v1.0.3: Get the data which overlap with a reference set. [Category: Data Comparison]"

        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="output",         action="store",      default=None,  type="string", help="output file [compulsory] [format: output file in GFF3 format]")
        parser.add_option("-S", "--start1",           dest="start1",         action="store",      default=None,  type="int",    help="only consider the n first nucleotides of the transcripts in file 1 (do not use it with -U) [format: int]")
        parser.add_option("-s", "--start2",           dest="start2",         action="store",      default=None,  type="int",    help="only consider the n first nucleotides of the transcripts in file 2 (do not use it with -u) [format: int]")
        parser.add_option("-U", "--end1",             dest="end1",           action="store",      default=None,  type="int",    help="only consider the n last nucleotides of the transcripts in file 1 (do not use it with -S) [format: int]")
        parser.add_option("-u", "--end2",             dest="end2",           action="store",      default=None,  type="int",    help="only consider the n last nucleotides of the transcripts in file 2 (do not use it with -s) [format: int]")
        parser.add_option("-t", "--intron",           dest="introns",        action="store_true", default=False,                help="also report introns [format: bool] [default: false]")
        parser.add_option("-E", "--5primeExtension1", dest="fivePrime1",     action="store",      default=None,  type="int",    help="extension towards 5' in file 1 [format: int]")
        parser.add_option("-e", "--5primeExtension2", dest="fivePrime2",     action="store",      default=None,  type="int",    help="extension towards 5' in file 2 [format: int]")
        parser.add_option("-N", "--3primeExtension1", dest="threePrime1",    action="store",      default=None,  type="int",    help="extension towards 3' in file 1 [format: int]")
        parser.add_option("-n", "--3primeExtension2", dest="threePrime2",    action="store",      default=None,  type="int",    help="extension towards 3' in file 2 [format: int]")
        parser.add_option("-c", "--colinear",         dest="colinear",       action="store_true", default=False,                help="colinear only [format: bool] [default: false]")
        parser.add_option("-a", "--antisense",        dest="antisense",      action="store_true", default=False,                help="antisense only [format: bool] [default: false]")
        parser.add_option("-d", "--distance",         dest="distance",       action="store",      default=None,  type="int",    help="accept some distance between query and reference [format: int]")
        parser.add_option("-k", "--included",         dest="included",       action="store_true", default=False,                help="keep only elements from file 1 which are included in an element of file 2 [format: bool] [default: false]")
        parser.add_option("-K", "--including",        dest="including",      action="store_true", default=False,                help="keep only elements from file 2 which are included in an element of file 1 [format: bool] [default: false]")
        parser.add_option("-m", "--minOverlap",       dest="minOverlap",     action="store",      default=1,     type="int",    help="minimum number of nucleotides overlapping to declare an overlap [format: int] [default: 1]")
        parser.add_option("-p", "--pcOverlap",        dest="pcOverlap",      action="store",      default=None,  type="int",    help="minimum percentage of nucleotides to overlap to declare an overlap [format: int]")
        parser.add_option("-O", "--notOverlapping",   dest="notOverlapping", action="store_true", default=False,                help="also output not overlapping data [format: bool] [default: false]")
        parser.add_option("-x", "--exclude",          dest="exclude",        action="store_true", default=False,                help="invert the match [format: bool] [default: false]")
        parser.add_option("-v", "--verbosity",        dest="verbosity",      action="store",      default=1,     type="int",    help="trace level [format: int]")
        parser.add_option("-l", "--log",              dest="log",            action="store_true", default=False,                help="write a log file [format: bool] [default: false]")
        (self._options, args) = parser.parse_args()


    def run(self):             
        logHandle = None
        if self._options.log:
            logHandle = open(self._options.output, "w")

        transcriptContainer1 = TranscriptContainer(self._options.inputFileName1, self._options.format1, self._options.verbosity)
        transcriptContainer2 = TranscriptContainer(self._options.inputFileName2, self._options.format2, self._options.verbosity)
        writer               = TranscriptWriter(self._options.output, "gff3", self._options.verbosity)

        transcriptListComparator = TranscriptListsComparator(logHandle, self._options.verbosity)
        transcriptListComparator.restrictToStart(transcriptListComparator.QUERY, self._options.start1)
        transcriptListComparator.restrictToStart(transcriptListComparator.REFERENCE, self._options.start2)
        transcriptListComparator.restrictToEnd(transcriptListComparator.QUERY, self._options.end1)
        transcriptListComparator.restrictToEnd(transcriptListComparator.REFERENCE, self._options.end2)
        transcriptListComparator.extendFivePrime(transcriptListComparator.QUERY, self._options.fivePrime1)
        transcriptListComparator.extendFivePrime(transcriptListComparator.REFERENCE, self._options.fivePrime2)
        transcriptListComparator.extendThreePrime(transcriptListComparator.QUERY, self._options.threePrime1)
        transcriptListComparator.extendThreePrime(transcriptListComparator.REFERENCE, self._options.threePrime2)
        transcriptListComparator.acceptIntrons(transcriptListComparator.QUERY, self._options.introns)
        transcriptListComparator.acceptIntrons(transcriptListComparator.REFERENCE, self._options.introns)
        transcriptListComparator.getAntisenseOnly(self._options.antisense)
        transcriptListComparator.getColinearOnly(self._options.colinear)
        transcriptListComparator.getInvert(self._options.exclude)
        transcriptListComparator.setMaxDistance(self._options.distance)
        transcriptListComparator.setMinOverlap(self._options.minOverlap)
        transcriptListComparator.setPcOverlap(self._options.pcOverlap)
        transcriptListComparator.setIncludedOnly(self._options.included)
        transcriptListComparator.setIncludingOnly(self._options.including)
        transcriptListComparator.includeNotOverlapping(self._options.notOverlapping)
        transcriptListComparator.computeOdds(True)
        transcriptListComparator.setInputTranscriptContainer(transcriptListComparator.QUERY, transcriptContainer1)
        transcriptListComparator.setInputTranscriptContainer(transcriptListComparator.REFERENCE, transcriptContainer2)
        transcriptListComparator.setOutputWriter(writer)
        transcriptListComparator.compareTranscriptList()

        if self._options.log:
            logHandle.close()

        if not self._options.exclude:
            odds = transcriptListComparator.getOdds()
            if self._options.verbosity > 0 and odds:
                print "min/avg/med/max transcripts: %d/%.2f/%.1f/%d" % Utils.getMinAvgMedMax(odds)
                
if __name__ == "__main__":
    icompareOverlapping = CompareOverlapping()
    icompareOverlapping.setAttributesFromCmdLine()
    icompareOverlapping.run()
