#! /usr/bin/env python
#
# Copyright INRA-URGI 2009-2011
# 
# 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.
#
from optparse import OptionParser
from commons.core.parsing.ParserChooser import ParserChooser
from commons.core.writer.TranscriptWriter import TranscriptWriter
from SMART.Java.Python.structure.Interval import Interval
from SMART.Java.Python.structure.Transcript import Transcript
from SMART.Java.Python.structure.Mapping import Mapping
from SMART.Java.Python.misc.Progress import Progress
from SMART.Java.Python.misc.UnlimitedProgress import UnlimitedProgress

MINBIN = 3
MAXBIN = 7
REFERENCE = 0
QUERY = 1

def getBin(start, end):
	for i in range(MINBIN, MAXBIN + 1):
		binLevel = 10 ** i
		if int(start / binLevel) == int(end / binLevel):
			return int(i * 10 ** (MAXBIN + 1) + int(start / binLevel))
	return int((MAXBIN + 1) * 10 ** (MAXBIN + 1))

def getOverlappingBins(start, end):
	array	= []
	bigBin = int((MAXBIN + 1) * 10 ** (MAXBIN + 1))
	for i in range(MINBIN, MAXBIN + 1):
		binLevel = 10 ** i
		array.append((int(i * 10 ** (MAXBIN + 1) + int(start / binLevel)), int(i * 10 ** (MAXBIN + 1) + int(end / binLevel))))
	array.append((bigBin, bigBin))
	return array


class GetIntersection(object):

	def __init__(self, verbosity):
		self.verbosity              = verbosity
		self.nbQueries              = 0
		self.nbRefs	                = 0
		self.nbWritten              = 0
		self.bins	                = {}

	def setReferenceFile(self, fileName, format):
		chooser = ParserChooser(self.verbosity)
		chooser.findFormat(format)
		self.refParser = chooser.getParser(fileName)

	def setQueryFile(self, fileName, format):
		chooser = ParserChooser(self.verbosity)
		chooser.findFormat(format)
		self.queryParser = chooser.getParser(fileName)

	def setOutputFile(self, fileName):
		self.writer = TranscriptWriter(fileName, "gff3", self.verbosity)

	def loadRef(self):
		progress = UnlimitedProgress(10000, "Reading references", self.verbosity)
		for transcript in self.refParser.getIterator():
			if transcript.__class__.__name__ == "Mapping":
				transcript = transcript.getTranscript()
			chromosome = transcript.getChromosome()
			bin		   = getBin(transcript.getStart(), transcript.getEnd())
			if chromosome not in self.bins:
				self.bins[chromosome] = {}
			if bin not in self.bins[chromosome]:
				self.bins[chromosome][bin] = []
			self.bins[chromosome][bin].append(transcript)
			self.nbRefs += 1
			progress.inc()
		progress.done()

	def _compareTranscript(self, queryTranscript):
		queryChromosome = queryTranscript.getChromosome()
		if queryChromosome not in self.bins:
			return None
		queryStart = queryTranscript.getStart()
		queryEnd   = queryTranscript.getEnd()
		bins	   = getOverlappingBins(queryStart, queryEnd)
		overlaps   = []
		for binRange in bins:
			for bin in range(binRange[0], binRange[1]+1):
				if bin not in self.bins[queryChromosome]:
					continue
				for refTranscript in self.bins[queryChromosome][bin]:
					newTranscript = queryTranscript.getIntersection(refTranscript)
					if newTranscript != None:
						overlaps.append(newTranscript)
		if not overlaps:
			return None
		newTranscript = overlaps[0]
		for transcript in overlaps[1:]:
			newTranscript.merge(transcript)
		return newTranscript

	def compare(self):
		progress = UnlimitedProgress(10000, "Comparing queries", self.verbosity)
		for queryTranscript in self.queryParser.getIterator():
			if queryTranscript.__class__.__name__ == "Mapping":
				queryTranscript = queryTranscript.getTranscript()
			progress.inc()
			self.nbQueries += 1
			newTranscript = self._compareTranscript(queryTranscript)
			if newTranscript != None:
				self.writer.addTranscript(queryTranscript)
				self.nbWritten += 1
		progress.done()
		self.writer.close()

	def displayResults(self):
		print "# queries:  %d" % (self.nbQueries)
		print "# refs:     %d" % (self.nbRefs)
		print "# written:  %d" % (self.nbWritten)

	def run(self):
		self.loadRef()
		self.compare()
		self.displayResults()

if __name__ == "__main__":
	
	description = "Get Intersection v1.0.0: Shrink the first data set so that all bases covered by the first data set is also covered by the second data set. [Category: Data Comparison]"

	parser = OptionParser(description = description)
	parser.add_option("-i", "--input1",	        dest="inputFileName1", action="store",			           type="string", help="query input file [compulsory] [format: file in transcript format given by -f]")
	parser.add_option("-f", "--format1",        dest="format1",		  action="store",			           type="string", help="format of previous file [compulsory] [format: transcript file format]")
	parser.add_option("-j", "--input2",	        dest="inputFileName2", action="store",			           type="string", help="reference input file [compulsory] [format: file in transcript format given by -g]")
	parser.add_option("-g", "--format2",        dest="format2",		  action="store",			           type="string", help="format of previous file [compulsory] [format: transcript file format]")
	parser.add_option("-o", "--output",	        dest="outputFileName", action="store",			           type="string", help="output file [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()

	gi = GetIntersection(options.verbosity)
	gi.setQueryFile(options.inputFileName1, options.format1)
	gi.setReferenceFile(options.inputFileName2, options.format2)
	gi.setOutputFile(options.outputFileName)
	gi.run()
