view TEisotools-1.1.a/TEiso/Bedtools_closest.py @ 13:feef9a0db09d draft

Uploaded
author urgi-team
date Wed, 20 Jul 2016 09:04:42 -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 Bedtools_closest(object):
         
    def __init__(self, input_file_A = "", input_file_B = "", output_file = "", verbosity = 3):
        self._input_file_A = input_file_A
        self._input_file_B = input_file_B
        self._output_file = output_file
        self._verbosity = verbosity
        
    def setAttributesFromCmdLine(self):
        description = "For each feature in A, finds the closest feature (upstream or downstream) in B.\n" 
        usage = " Bedtools_closest [OPTIONS] -a <bed/gff/vcf> -b <bed/gff/vcf> -o <output_dir> \n"
        parser = RepetOptionParser(description = description, usage = usage)
        parser.add_option( '-a', '--input_file_A', dest='input_file_A', help='bed/gff/vcf' )
        parser.add_option( '-b', '--input_file_B', dest='input_file_B', help='bed/gff/vcf' )
        parser.add_option( '-o', '--output_file', dest='output_file', help='write all output in this file/bed/gff/vcf', default = "")
        options, args = parser.parse_args()
        self.setAttributesFromOptions(options)
    
    def setAttributesFromOptions(self, options):
        self._input_file_A = options.input_file_A
        self._input_file_B = options.input_file_B
        self._output_file = options.output_file
        
    def checkExecutables(self):
        if not CheckerUtils.isExecutableInUserPath("bedtools"):
            raise Exception("ERROR: bedtools must be in your path")
    
    def checkOptions(self):   
        if self._input_file_A != "":
            if not FileUtils.isRessourceExists(self._input_file_A ):
                raise Exception("ERROR: reference file %s does not exist!" % self._input_file_A )
        else:
            raise Exception("ERROR: No specified -a option!")
        
        if self._input_file_B != "":
            if not FileUtils.isRessourceExists(self._input_file_B):
                raise Exception("ERROR: reference file %s does not exist!" % self._input_file_B )
        else:
            raise Exception("ERROR: No specified -b option!")
   
    def getbedtoolsclosestCmd(self, file_A, file_B, output_file):
        cmd = 'bedtools closest -a %s -b %s -d -D a > %s' % (file_A,file_B, output_file)
        ##print cmd
        return cmd
    
    def run(self):
        self.checkExecutables()
        self.checkOptions()
        sortfileA = "%s.sorted" % self._input_file_A
        sortfileB = "%s.sorted" % self._input_file_B
        os.system("bedtools sort -i %s > %s " % (self._input_file_A, sortfileA))
        os.system("bedtools sort -i %s > %s " % (self._input_file_B, sortfileB))

        try:
            if os.path.exists(self._output_file):
                raise Exception("ERROR: %s already exists." % self._output_file)
           
            cmd_bedtoolsclosest = self.getbedtoolsclosestCmd(sortfileA, sortfileB, self._output_file)
            ## hide output of subprocess: stdout = index_dir_stderr
            fstdout = open( "bedtools_closest.log" , 'w' )
            process = subprocess.Popen(cmd_bedtoolsclosest, shell = True, stdout = fstdout, stderr=subprocess.STDOUT)
            returncode = process.wait()
            fstdout.close()
            # get stderr, allowing for case where it's very large
            fstdout = open("bedtools_closest.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 cufflinks.log  %s/cufflinks.log " % workingDir)
        except Exception:
            raise Exception("ERROR in %s " % cmd_bedtoolsclosest)
        
                
if __name__ == "__main__":
    iLaunch = Bedtools_closest()
    iLaunch.setAttributesFromCmdLine()
    iLaunch.run()