#! /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.
#
"""
Merge sliding windows of two different clusterings
"""

import sys
import re
import os
from optparse import OptionParser
from SMART.Java.Python.structure.TranscriptContainer import TranscriptContainer
from commons.core.writer.Gff3Writer import Gff3Writer
from SMART.Java.Python.misc.Progress import Progress
from SMART.Java.Python.structure.Transcript import Transcript

class MergeSlidingWindowsClusters(object):
    """
    Merge the ouptput of several sets of sliding windows
    """

    def __init__(self, verbosity = 0):
        self.verbosity     = verbosity
        self.inputs        = []
        self.outputData    = {}
        self.nbData        = 0
        self.nbWrittenData = 0
        self.chromosomes   = []
        self.writer        = None

    def __del__(self):
        if self.writer != None:
            self.writer.close()

    def addInput(self, fileName, fileFormat):
        self.inputs.append(TranscriptContainer(fileName, fileFormat, self.verbosity))
        self.chromosomes = list(set(self.chromosomes).union(set(self.inputs[-1].getChromosomes())))

    def setOutput(self, fileName):
        self.writer = Gff3Writer(fileName, self.verbosity)

    def readInput(self, i, chromosome):
        progress = Progress(self.inputs[i].getNbTranscripts(), "Reading file #%d -- chromosome %s" % (i+1, chromosome), self.verbosity)
        for transcript in self.inputs[i].getIterator():
            progress.inc()
            if chromosome != transcript.getChromosome(): continue
            start     = transcript.getStart()
            end       = transcript.getEnd()
            direction = transcript.getDirection()
            tags      = transcript.tags
            if chromosome not in self.outputData:
                self.outputData[chromosome] = {}
            if direction not in self.outputData[chromosome]:
                self.outputData[chromosome][direction] = {}
            if start not in self.outputData[chromosome][direction]:
                self.outputData[chromosome][direction][start] = {}
            if end in self.outputData[chromosome][direction][start]:
                ends = self.outputData[chromosome][direction][start].keys()
                if ends[0] != end:
                    sys.exit("Error! Two regions starting at %d end are not consistent (%d and %d) in %s on strand %d" % (start, end, ends[0], chromosome, direction))
                self.outputData[chromosome][direction][start][end].update(tags)
            else:
                self.outputData[chromosome][direction][start][end] = tags
                self.nbData += 1
        progress.done()


    def writeOutput(self, chromosome):
        progress = Progress(self.nbData - self.nbWrittenData, "Writing output for chromosome %s" % (chromosome), self.verbosity)
        for direction in self.outputData[chromosome]:
            for start in self.outputData[chromosome][direction]:
                for end in self.outputData[chromosome][direction][start]:
                    transcript = Transcript()
                    transcript.setChromosome(chromosome)
                    transcript.setStart(start)
                    transcript.setEnd(end)
                    transcript.setDirection(direction)
                    transcript.tags = self.outputData[chromosome][direction][start][end]
                    transcript.setName("region_%d" % (self.nbWrittenData + 1))
                    tags = transcript.getTagNames()
                    for tag in tags:
                        if tag.startswith("Name_") or tag.startswith("ID_"):
                            del transcript.tags[tag]
                    self.nbWrittenData += 1
                    self.writer.addTranscript(transcript)
                    progress.inc()
        self.writer.write()
        progress.done()
        self.outputData = {}

    def merge(self):
        for chromosome in self.chromosomes:
            for i, input in enumerate(self.inputs):
                self.readInput(i, chromosome)
            self.writeOutput(chromosome)
        self.writer.close()


if __name__ == "__main__":
    
    # parse command line
    description = "Merge Sliding Windows Clusters v1.0.2: Merge two files containing the results of a sliding windows clustering. [Category: Sliding Windows]"

    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", "--inputFormat1", dest="inputFormat1",   action="store",                     type="string", help="format of the input 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", "--inputFormat2", dest="inputFormat2",   action="store",                     type="string", help="format of the input file 2 [compulsory] [format: transcript file format]")
    parser.add_option("-o", "--output",       dest="outputFileName", action="store",                     type="string", help="output file [compulsory] [format: output file in GFF3 format]")
    parser.add_option("-v", "--verbosity",    dest="verbosity",      action="store",      default=1,     type="int",    help="trace level [format: int]")
    (options, args) = parser.parse_args()

    merger = MergeSlidingWindowsClusters(options.verbosity)
    merger.addInput(options.inputFileName1, options.inputFormat1)
    merger.addInput(options.inputFileName2, options.inputFormat2)
    merger.setOutput(options.outputFileName)
    merger.merge()
