view TEisotools-1.0/TEisotools-1.0/TEiso/Cuffcompare.py @ 12:22b0494ec883 draft

Uploaded
author urgi-team
date Wed, 20 Jul 2016 08:18:51 -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
from commons.core.checker.CheckerUtils import CheckerUtils
from commons.core.utils.RepetOptionParser import RepetOptionParser
from commons.core.utils.FileUtils import FileUtils
import subprocess

class Cuffcompare(object):
         
    def __init__(self, reference = "", transcripts = "", outprefix ="" , workingDir = "", verbosity = 3):
        self._reference = reference
        self._transcripts = transcripts
        self._outprefix = outprefix
        self._output_Dir = workingDir
        self._verbosity = verbosity
        
    def setAttributesFromCmdLine(self):
        description = "Cuffcompare provides classification, reference annotation mapping and various statistics for Cufflinks transfrags.\n" 
        usage = " Cuffcompare -r <reference> -i <transcripts> -o <outprefix>\n"
        parser = RepetOptionParser(description = description, usage = usage)
        parser.add_option( '-r', '--reference', dest='reference', help='a set of known mRNAs to use as a reference for assessing the accuracy of mRNAs or gene models given in <input.gtf>' )
        parser.add_option( '-i', '--transcripts', dest='transcripts', help='input transfrags' )
        parser.add_option( '-o', '--outprefix', dest='outprefix', help='write all output files with out prefix', default = "cuffcompare")
        options, args = parser.parse_args()
        self.setAttributesFromOptions(options)
    
    def setAttributesFromOptions(self, options):
        self._reference = options.reference
        self._transcripts = options.transcripts
        self._outprefix = options.outprefix
        
    def checkExecutables(self):
        if not CheckerUtils.isExecutableInUserPath("cuffcompare"):
            raise Exception("ERROR: cuffcompare must be in your path")
    
    def checkOptions(self):   
        if self._transcripts != "":
            if not FileUtils.isRessourceExists(self._transcripts):
                raise Exception("ERROR: input file %s does not exist!" % self._transcripts)
        else:
            raise Exception("ERROR: No specified -i option!")
        
        if self._reference != "":
            if not FileUtils.isRessourceExists(self._reference):
                raise Exception("ERROR: reference file %s does not exist!" % self._reference)
        else:
            raise Exception("ERROR: No specified -r option!")
   
    def getCuffcompareCmd(self, reference, transcripts, outprefix):
        cmd = 'cuffcompare -R -C -r %s %s -o %s' % (reference, transcripts, outprefix)
        ##print cmd
        return cmd
    
    def run(self):
        self.checkExecutables()
        self.checkOptions()
        try:
            workingDir =  self._output_Dir
            if os.path.exists(workingDir):
                raise Exception("ERROR: %s already exists." % workingDir)
            cmd_cuffcompare = self.getCuffcompareCmd(self._reference, self._transcripts, self._outprefix)
            ## hide output of subprocess: stdout = index_dir_stderr
            fstdout = open( "cuffcompare.log" , 'w' )
            process = subprocess.Popen(cmd_cuffcompare, shell = True, stdout = fstdout, stderr=subprocess.STDOUT)
            returncode = process.wait()
            fstdout.close()
            # get stderr, allowing for case where it's very large
            fstdout = open("cuffcompare.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
            
            if not os.path.exists(workingDir):
                os.mkdir(workingDir)
                ##os.system("mv cuffcompare.log  %s/cuffcompare.log " % workingDir)
                os.system("mv cuffcompare.*  %s" % workingDir) 
        except Exception:
            raise Exception("ERROR in %s " % cmd_cuffcompare)
        
                
if __name__ == "__main__":
    iLaunch = Cuffcompare()
    iLaunch.setAttributesFromCmdLine()
    iLaunch.run()