view SMART/Java/Python/CollapseReads.py @ 6:769e306b7933

Change the repository level.
author yufei-luo
date Fri, 18 Jan 2013 04:54:14 -0500
parents
children 94ab73e8a190
line wrap: on
line source

#! /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.
#
import os
from optparse import OptionParser, OptionGroup
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.ncList.NCListFilePickle import NCListFileUnpickle
from SMART.Java.Python.ncList.FileSorter import FileSorter
from SMART.Java.Python.misc.Progress import Progress


class CollapseReads(object):
    """
    Merge two reads if they have exactly the same genomic coordinates
    """

    def __init__(self, verbosity = 0):
        self.verbosity         = verbosity
        self.inputReader       = None
        self.outputWriter      = None
        self.strands           = True
        self.nbRead            = 0
        self.nbWritten         = 0
        self.nbMerges          = 0
        self.splittedFileNames = {}

    def __del__(self):
        for fileName in self.splittedFileNames.values():
            os.remove(fileName)
            
    def close(self):
        self.outputWriter.close()
        
    def setInputFile(self, fileName, format):
        parserChooser = ParserChooser(self.verbosity)
        parserChooser.findFormat(format, "transcript")
        self.parser = parserChooser.getParser(fileName)
        self.sortedFileName = "%s_sorted.pkl" % (os.path.splitext(fileName)[0])

    def setOutputFile(self, fileName):
        self.outputWriter = Gff3Writer(fileName, self.verbosity)

    def getNbElements(self):
        return self.parser.getNbTranscripts()

    def _sortFile(self):
        fs = FileSorter(self.parser, self.verbosity-4)
        fs.perChromosome(True)
        fs.setOutputFileName(self.sortedFileName)
        fs.sort()
        self.splittedFileNames       = fs.getOutputFileNames()
        self.nbElementsPerChromosome = fs.getNbElementsPerChromosome()
        self.nbRead                  = fs.getNbElements()
        
    def _iterate(self, chromosome):
        progress    = Progress(self.nbElementsPerChromosome[chromosome], "Checking chromosome %s" % (chromosome), self.verbosity)
        transcripts = []
        parser      = NCListFileUnpickle(self.splittedFileNames[chromosome], self.verbosity)
        for newTranscript in parser.getIterator():
            newTranscripts = []
            for oldTranscript in transcripts:
                if self._checkOverlap(newTranscript, oldTranscript):
                    self._merge(newTranscript, oldTranscript)
                elif self._checkPassed(newTranscript, oldTranscript):
                    self._write(oldTranscript)
                else:
                    newTranscripts.append(oldTranscript)
            newTranscripts.append(newTranscript)
            transcripts = newTranscripts
            progress.inc()
        for transcript in transcripts:
            self._write(transcript)
        progress.done()

    def _merge(self, transcript1, transcript2):
        self.nbMerges += 1
        transcript2.setDirection(transcript1.getDirection())
        transcript1.merge(transcript2)

    def _write(self, transcript):
        self.nbWritten += 1
        self.outputWriter.addTranscript(transcript)

    def _checkOverlap(self, transcript1, transcript2):
        if transcript1.getStart() != transcript2.getStart() or transcript1.getEnd() != transcript2.getEnd():
            return False
        return (not self.strands or transcript1.getDirection() == transcript2.getDirection())

    def _checkPassed(self, transcript1, transcript2):
        return (transcript2.getStart() < transcript1.getStart())

    def collapseChromosome(self, chromosome):
        progress            = Progress(table.getNbElements(), "Analysing chromosome %s" % (chromosome), self.verbosity)
        command             = "SELECT * FROM %s ORDER BY start ASC, end DESC" % (table.name)
        transcriptStart     = None
        transcriptEnd       = None
        transcriptDirection = None
        currentTranscript   = None
        if self.strands:
            command += ", direction"
        for index, transcript in table.selectTranscripts(command, True):
            self.nbRead += 1
            if not self.strands:
                transcript.setDirection("+")
            if transcriptStart != transcript.getStart() or transcriptEnd != transcript.getEnd() or transcriptDirection != transcript.getDirection():
                self.writeTranscript(currentTranscript)
                transcriptStart     = transcript.getStart()
                transcriptEnd       = transcript.getEnd()
                transcriptDirection = transcript.getDirection()
                currentTranscript   = transcript
            else:
                currentTranscript.setTagValue("nbElements", (currentTranscript.getTagValue("nbElements") + 1) if "nbElements" in currentTranscript.getTagNames() else 1)
            progress.inc()
        self.writeTranscript(currentTranscript)
        progress.done()

    def collapse(self):
        self._sortFile()
        for chromosome in sorted(self.nbElementsPerChromosome.keys()):
            self._iterate(chromosome)
        self.outputWriter.close()
        if self.verbosity > 1:
            print "# reads read: %d" % (self.nbRead)
            print "# reads written: %d (%.2f%%)" % (self.nbWritten, float(self.nbWritten) / self.nbRead * 100)
            print "# reads merges: %d" % (self.nbMerges)

if __name__ == "__main__":
    
    # parse command line
    description = "Collapse Reads v1.0.3: Merge two reads if they have exactly the same genomic coordinates. [Category: Merge]"

    parser = OptionParser(description = description)
    parser.add_option("-i", "--input",     dest="inputFileName",  action="store",                     type="string", help="input file [compulsory] [format: file in mapping format given by -f]")
    parser.add_option("-f", "--format",    dest="format",         action="store",                     type="string", help="format of the file [compulsory] [format: mapping 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("-s", "--strands",   dest="strands",        action="store_true", default=False,                help="merge elements on 2 different strands [format: bool] [default: false]")
    parser.add_option("-v", "--verbosity", dest="verbosity",      action="store",      default=1,     type="int",    help="trace level [default: 1] [format: int]")
    (options, args) = parser.parse_args()

    collapser = CollapseReads(options.verbosity)
    collapser.setInputFile(options.inputFileName, options.format)
    collapser.setOutputFile(options.outputFileName)
    collapser.strands = not options.strands
    collapser.collapse()
    collapser.close()
zz&}x0% !stAJI*" =RRKj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