view TEisotools-1.1.a/TEisotools-1.1.a/TEiso/Bowtie_build.py @ 14:ecf2861ecee1 draft

Uploaded
author urgi-team
date Thu, 21 Jul 2016 05:31:00 -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 Bowtie_build(object):
         
    def __init__(self, input_reference = "", output_prefix= "", workingDir = "", verbosity = 3):
       
        self._inputRef = input_reference
        self._outPrefix = output_prefix
        self._outputDir = workingDir
        self._verbosity = verbosity
        
    def setAttributesFromCmdLine(self):
        description = "Create index for refrence file with bowtie-build.\n" 
        usage = "Bowtie_build -i <reference_in> -o <ebwt_outfile_base>\n"
        print usage
        parser = RepetOptionParser(description = description, usage = usage)
        parser.add_option( '-i', '--input_reference', dest='input_reference', help='comma-separated list of files with ref sequences' )
        parser.add_option( '-p', '--output_prefix', dest='output_prefix', help=' write Ebwt data to files with this dir/basename' )
        parser.add_option( '-o', '--outputDir', dest='outputDir', help='result directory name', default = "")
        options, args = parser.parse_args()
        self.setAttributesFromOptions(options)
    
    def setAttributesFromOptions(self, options):
        self._inputRef = options.input_reference
        self._outPrefix = options.output_prefix
        self._outputDir = options.outputDir
        
    def checkExecutables(self):
        if not CheckerUtils.isExecutableInUserPath("bowtie2-build"):
            raise Exception("ERROR: bowtie2-build must be in your path")
    
    def checkOptions(self):   
        if self._inputRef != "":
            if not FileUtils.isRessourceExists(self._inputRef):
                raise Exception("ERROR: reference file %s does not exist!" % self._inputRef)
        else:
            raise Exception("ERROR: No specified -i option!")
        
        if self._outPrefix == "":
            raise Exception("ERROR: No specified -o option!")
    
   
    def getBowtie2buildCmd(self, inputRef, outPrefix ): 
        cmd = 'bowtie2-build %s %s' % (inputRef, self._outPrefix )
        #print cmd
        return cmd
    
    def run(self):
        
        self.checkExecutables()
        self.checkOptions()
        try:
            workingDir = self._outputDir
            if os.path.exists(workingDir):
                raise Exception("ERROR: %s already exists." % workingDir)
            os.mkdir(workingDir)
            os.chdir(workingDir)
            os.symlink("%s" % self._inputRef,"%s.fa" % self._outPrefix)
            cmd_bowtie = self.getBowtie2buildCmd(self._inputRef, self._outPrefix)
            ## hide output of subprocess: stdout = index_dir_stderr
            fstdout = open( "bowtie2_build.log" , 'w' )
            process = subprocess.Popen(cmd_bowtie, shell = True, stdout = fstdout, stderr=subprocess.STDOUT)
            returncode = process.wait()
            fstdout.close()
            # get stderr, allowing for case where it's very large
            fstdout = open("bowtie2_build.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
        except Exception:
            raise Exception("ERROR in %s " % cmd_bowtie)
        
                
if __name__ == "__main__":
    print "heloo"
    iLaunch = Bowtie_build()
    iLaunch.setAttributesFromCmdLine()
    iLaunch.run()