view TEisotools-1.0/TEiso/Tophat.py @ 6:20ec0d14798e draft

Uploaded
author urgi-team
date Wed, 20 Jul 2016 05:00:24 -0400
parents
children
line wrap: on
line source

#!/usr/bin/env python

# Copyright INRA (Institut National de la Recherche Agronomique)
# http://www.inra.fr
# http://urgi.versailles.inra.fr
#
# 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, glob
import subprocess
import time
from commons.core.checker.CheckerUtils import CheckerUtils
from commons.core.utils.RepetOptionParser import RepetOptionParser
from commons.core.LoggerFactory import LoggerFactory
from commons.core.utils.FileUtils import FileUtils

LOG_DEPTH = "repet.RNAseq_pipe"


class Tophat(object):
    
    def __init__(self, workingDir = "", index_genome = "", single_paired = "", single_read = "", left_read ="", right_read = "", verbosity = 3):
        #self._transcripts = input_transcripts
        self._outputDir = workingDir
        self._bowtie_index = index_genome
        self._type = single_paired
        self._single_read = single_read
        self._left_read = left_read
        self._right_read = right_read
        self._verbosity = verbosity
        self._log = LoggerFactory.createLogger("%s.%s" % (LOG_DEPTH, self.__class__.__name__), self._verbosity)
    def setAttributesFromCmdLine(self):
        description = "TopHat maps short sequences from spliced transcripts to whole genomes..\n" 
        usage = "if reads are single:/n Tophat.py -G <GTF/GFF with known transcripts> -b <bowtie_index> -t single -r <single_read> \n"
        usage +="if reads are paired:/n Tophat.py -G <GTF/GFF with known transcripts> -b <bowtie_index> -t paired -r1 <reads_left> -r2 <reads_right>\n"
        parser = RepetOptionParser(description = description, usage = usage)
       # parser.add_option( '-G', '--input_transcripts', dest='input_transcripts', help='GTF/GFF with known transcripts', default = "")
        parser.add_option( '-o', '--outputDir', dest='outputDir', help='write all output files to this directory', default = "")
        parser.add_option( '-b', '--index_genome', dest='index_genome', help='Indexing reference genome', default = "")
        parser.add_option( '-e', '--single_paired', dest='single_paired', help='types of input reads', default = "paired")
        parser.add_option( '-s', '--single_read', dest = 'single_read', help='a single input read', default = "" )
        parser.add_option( '-l', '--left_read', dest='left_read', help='left reads', default = "" )
        parser.add_option( '-r', '--right_read', dest='right_read', help='right reads', default = "" )
        options, args = parser.parse_args()
        self.setAttributesFromOptions(options)
        
    def setAttributesFromOptions(self, options):
##        self._transcripts = options.input_transcripts
        self._outputDir = options.outputDir
        self._bowtie_index = options.index_genome
        self._type = options.single_paired
        self._single_read = options.single_read
        self._left_read = options.left_read
        self._right_read = options.right_read
        
        
    def checkExecutables(self):
   
        if not CheckerUtils.isExecutableInUserPath("tophat2"):
            raise Exception("ERROR: tophat must be in your path")
    
    def checkOptions(self):   
        if self._bowtie_index == "":
            raise Exception("ERROR: No specified -b option!")
        
  ##      if self._transcripts != "":
  ##          if not FileUtils.isRessourceExists(self._transcripts):
  ##              raise Exception("ERROR: %s does not exist!" % self._transcripts)
    
        if self._type == "paired":
            for f in self._left_read:
                if not FileUtils.isRessourceExists(f):
                    raise Exception("ERROR: %s does not exist!" % f)
            for f in self._right_read:
                if not FileUtils.isRessourceExists(f):
                    raise Exception("ERROR: %s does not exist!" % f)   
        elif self._type == "single":
            for f in self._single_read: 
                if not FileUtils.isRessourceExists(f):
                    raise Exception("ERROR: %s does not exist!" % f)
        else:
            raise Exception("ERROR: No specified -t option!")
        
    def getTophatCmd_single(self, out_tophat, BowtiePrefix, single_read):
        cmd = "tophat2 -p 8 -o %s %s %s" % (out_tophat, BowtiePrefix, ",".join(single_read))
        return cmd
    
    def getTophatCmd_paired(self, out_tophat, BowtiePrefix, left_read, right_read):
	####sur SGE comme saruman
        #cmd = "echo " + "'tophat -p 8 -o %s ../%s %s %s'" % (out_tophat, prefix, ",".join(left_Read), ",".join(right_Read))+ "|qsub -V -cwd -pe multithread 8"
        cmd = "tophat2 -p 8 -o %s %s %s %s" % (out_tophat, BowtiePrefix, ",".join(left_read), ",".join(right_read))
	#print cmd
        return cmd
    
    def run(self):
        self.checkExecutables()
        self.checkOptions()
        try:
            if os.path.exists(self._outputDir):
                raise Exception("ERROR: %s already exists." % self._outputDir)
            if self._type == "single":
                cmd_tophat = self.getTophatCmd_single(self._outputDir, self._bowtie_index, self._single_read)
            if self._type == "paired":
                cmd_tophat = self.getTophatCmd_paired(self._outputDir, self._bowtie_index, self._left_read, self._right_read)
            #print cmd_tophat
            ## hide output of subprocess: stdout = index_dir_stderr
            fstdout = open( "tophat.log" , 'w' )
            process = subprocess.Popen(cmd_tophat, shell = True, stdout = fstdout, stderr=subprocess.STDOUT)
            returncode = process.wait()
            fstdout.close()
            # get stderr, allowing for case where it's very large
            fstdout = open("tophat.log", 'rb' )
            stderr = ''
            buffsize = 1048576
            try:
                while True:
                    stderr += fstdout.read( buffsize )
                    if not stderr or len( stderr ) % buffsize != 0:
                        break
            except OverflowError:
                    pass
            fstdout.close()
            if returncode != 0:
                    raise Exception, stderr
        
            os.system("mv tophat.log  %s/tophat.log " % self._outputDir) 
        except Exception:
            raise Exception("ERROR in %s " % cmd_tophat)
        
        
          
                  
if __name__ == "__main__":
    iLaunch = Tophat()
    iLaunch.setAttributesFromCmdLine()
    iLaunch.run()