#! /usr/bin/env python
#
# Copyright INRA-URGI 2009-2012
# 
# 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.
#
import os, struct, time, random
from optparse import OptionParser
from commons.core.parsing.ParserChooser import ParserChooser
from commons.core.writer.Gff3Writer import Gff3Writer
from SMART.Java.Python.structure.Transcript import Transcript
from SMART.Java.Python.structure.Interval import Interval
from SMART.Java.Python.ncList.NCList import NCList
from SMART.Java.Python.ncList.NCListCursor import NCListCursor
from SMART.Java.Python.ncList.NCListFilePickle import NCListFilePickle, NCListFileUnpickle
from SMART.Java.Python.ncList.FileSorter import FileSorter
from SMART.Java.Python.misc.Progress import Progress
from SMART.Java.Python.misc.UnlimitedProgress import UnlimitedProgress
from SMART.Java.Python.misc import Utils
try:
    import cPickle as pickle
except:
    import pickle

REFERENCE = 0
QUERY = 1
TYPES = (REFERENCE, QUERY)
TYPETOSTRING = {0: "reference", 1: "query"}

class RestrictFromCoverage(object):

    def __init__(self, verbosity = 1):
        self._verbosity               = verbosity
        self._randomNumber            = random.randint(0, 100000)
        self._nbWritten               = 0
        self._nbLines                 = dict([type, 0]  for type in TYPES)
        self._splittedFileNames       = dict([type, {}] for type in TYPES)
        self._nbElementsPerChromosome = dict([type, {}] for type in TYPES)
        self._nbElements              = dict([type, 0]  for type in TYPES)
        
    def __del__(self):
        pass

    def _close(self):
        self._writer.close()
        
    def setInputFileName(self, fileName, format, type):
        chooser = ParserChooser(self._verbosity)
        chooser.findFormat(format)
        parser = chooser.getParser(fileName)
        sortedFileName = "%s_%d_%d_sorted.pkl" % (os.path.splitext(fileName)[0], self._randomNumber, type)
        if self._verbosity > 2:
            print "Preparing %s file..." % (TYPETOSTRING[type])
        startTime = time.time()
        fs = FileSorter(parser, self._verbosity-1)
        fs.perChromosome(True)
        fs.setOutputFileName(sortedFileName)
        fs.sort()
        self._nbLines[type]                 = fs.getNbElements()
        self._splittedFileNames[type]       = fs.getOutputFileNames()
        self._nbElementsPerChromosome[type] = fs.getNbElementsPerChromosome()
        self._nbElements[type]              = fs.getNbElements()
        endTime = time.time()
        if self._verbosity > 2:
            print "    ...done (%ds)" % (endTime - startTime)
            
    def setOutputFileName(self, outputFileName):
        self._writer = Gff3Writer(outputFileName)

    def setPercent(self, minPercent, maxPercent):
        self._minPercent = minPercent
        self._maxPercent = maxPercent

    def setNbNucleotides(self, minNb, maxNb):
        self._minNucleotides = minNb
        self._maxNucleotides = maxNb

    def setOverlap(self, minOverlap, maxOverlap):
        self._minOverlap = minOverlap
        self._maxOverlap = maxOverlap

    def setStrands(self, boolean):
        self._twoStrands = boolean

    def _compareChromosome(self, chromosome):
        firstOverlap = 0
        parser1      = NCListFileUnpickle(self._splittedFileNames[QUERY][chromosome],     self._verbosity)
        parser2      = NCListFileUnpickle(self._splittedFileNames[REFERENCE][chromosome], self._verbosity)
        progress     = Progress(self._nbElementsPerChromosome[QUERY][chromosome], "Analyzing %s" % (chromosome), self._verbosity)
        for transcript1 in parser1.getIterator():
            firstOverlap = self._compareList(transcript1, parser2)
            parser2.setInitAddress(firstOverlap)
            progress.inc()
        progress.done()

    def _compareList(self, transcript1, parser2):
        values = []
        for exon in transcript1.getExons():
            values.append([0.0] * exon.getSize())
        firstOverlap = None
        for transcript2 in parser2.getIterator():
            address       = parser2.getCurrentTranscriptAddress()
            nbElements    = float(transcript2.getTagValue("nbElements"))    if "nbElements"    in transcript2.getTagNames() else 1.0
            nbOccurrences = float(transcript2.getTagValue("nbOccurrences")) if "nbOccurrences" in transcript2.getTagNames() else 1.0
            nbElements   /= nbOccurrences
            if transcript2.getStart() > transcript1.getEnd():
                if firstOverlap == None:
                    firstOverlap = address
                if self._checkValues(values):
                    self._printTranscript(transcript1)
                return firstOverlap
            elif transcript1.overlapWith(transcript2):
                if firstOverlap == None:
                    firstOverlap = address
                values = self._compareTranscript(transcript1, transcript2, values, nbElements)
        if self._checkValues(values):
            self._printTranscript(transcript1)
            return firstOverlap
    
    def _compareTranscript(self, transcript1, transcript2, values, nbElements):
        if not transcript1.overlapWith(transcript2) or ((self._twoStrands) and transcript1.getDirection() != transcript2.getDirection()):
            return values
        for id1, exon1 in enumerate(transcript1.getExons()):
            for exon2 in transcript2.getExons():
                values[id1] = map(sum, zip(values[id1], self._compareExon(exon1, exon2, nbElements)))
        return values
        
    def _compareExon(self, exon1, exon2, nbElements):
        array = [0.0] * exon1.getSize()
        if not exon1.overlapWith(exon2) or ((self._twoStrands) and exon1.getDirection() != exon2.getDirection()):
            return array
        for pos in range(max(exon1.getStart(), exon2.getStart()) - exon1.getStart(), min(exon1.getEnd(), exon2.getEnd()) - exon1.getStart()+1):
            array[pos] += nbElements
        return array

    def _filter(self, value):
        if self._minOverlap and self._maxOverlap:
            return self._minOverlap <= value <= self._maxOverlap
        if self._minOverlap:
            return self._minOverlap <= value
        if self._maxOverlap:
            return value <= self._maxOverlap
        return True

    def _checkValues(self, values):
        nbValues    = sum(map(len, values))
        nbPosValues = sum(map(len, [filter(self._filter, valuePart) for valuePart in values]))
        ratio       = float(nbPosValues) / nbValues * 100
        if self._minNucleotides and nbPosValues < self._minNucleotides:
            return False
        if self._maxNucleotides and nbPosValues > self._maxNucleotides:
            return False
        if self._minPercent and ratio < self._minPercent:
            return False
        if self._maxPercent and ratio > self._maxPercent:
            return False
        return True

    def _printTranscript(self, transcript):
        self._writer.addTranscript(transcript)
        self._nbWritten += 1

    def run(self):
        for chromosome in sorted(self._splittedFileNames[QUERY].keys()):
            self._compareChromosome(chromosome)
        self._close()
        if self._verbosity > 0:
            print "# queries: %d" % (self._nbElements[QUERY])
            print "# refs:    %d" % (self._nbElements[REFERENCE])
            print "# written: %d (%d%%)" % (self._nbWritten, 0 if self._nbElements[QUERY] == 0 else round(float(self._nbWritten) / self._nbElements[QUERY] * 100))
        

if __name__ == "__main__":
    description = "Restrict From Coverage v1.0.0: Select the elements from the first set which have a given coverage. [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("-n", "--minNucleotides",   dest="minNucleotides", action="store",      default=None,  type="int",    help="minimum number of nucleotides overlapping to declare an overlap [format: int]")
    parser.add_option("-N", "--maxNucleotides",   dest="maxNucleotides", action="store",      default=None,  type="int",    help="maximum number of nucleotides overlapping to declare an overlap [format: int]")
    parser.add_option("-p", "--minPercent",       dest="minPercent",     action="store",      default=None,  type="int",    help="minimum percentage of nucleotides overlapping to declare an overlap [format: int]")
    parser.add_option("-P", "--maxPercent",       dest="maxPercent",     action="store",      default=None,  type="int",    help="maximum percentage of nucleotides overlapping to declare an overlap [format: int]")
    parser.add_option("-e", "--minOverlap",       dest="minOverlap",     action="store",      default=None,  type="int",    help="minimum number of elements from 2nd file to declare an overlap [format: int]")
    parser.add_option("-E", "--maxOverlap",       dest="maxOverlap",     action="store",      default=None,  type="int",    help="maximum number of elements from 2nd file to declare an overlap [format: int]")
    parser.add_option("-s", "--strands",          dest="strands",        action="store_true", default=False,                help="consider the two strands separately [format: bool] [default: false]")
    parser.add_option("-v", "--verbosity",        dest="verbosity",      action="store",      default=1,     type="int",    help="trace level [format: int]")
    (options, args) = parser.parse_args()

    rfc = RestrictFromCoverage(options.verbosity)
    rfc.setInputFileName(options.inputFileName1, options.format1, QUERY)
    rfc.setInputFileName(options.inputFileName2, options.format2, REFERENCE)
    rfc.setOutputFileName(options.output)
    rfc.setNbNucleotides(options.minNucleotides, options.maxNucleotides)
    rfc.setPercent(options.minPercent, options.maxPercent)
    rfc.setOverlap(options.minOverlap, options.maxOverlap)
    rfc.setStrands(options.strands)
    rfc.run()
