view smart_toolShed/commons/core/parsing/BlatToGffForBesPaired.py @ 0:e0f8dcca02ed

Uploaded S-MART tool. A toolbox manages RNA-Seq and ChIP-Seq data.
author yufei-luo
date Thu, 17 Jan 2013 10:52:14 -0500
parents
children
line wrap: on
line source

# 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 optparse
import os
import sys
import re
import datetime
from commons.core.parsing.BlatParser import BlatParser
from commons.core.seq.FastaUtils import FastaUtils 

class BlatToGffForBesPaired(object):


    def __init__(self):
        pass
    
    def setAttributesFromCmdLine(self):
        help = '\
        \nThis Script Launch BlatToGffForBesPaired.\n\n\
        Example 1: python BlatToGffForBesPaired.py -i blatResultsFile.tab -f besSequences.fasta -o outputFile.gff3\n\
        Example 2: python BlatToGffForBesPaired.py -i blatResultsFile.tab -f besSequences.fasta -o outputFile.gff3 -n muscadine:filtre1\n\n\
        Note 1: In blat input file, all BAC-Ends must be paired. In addition, they must be one above the other.\nFor example, if you have the BES MRRE1H032F08FM1 (forward), we must have the BES MRRE1H032F08RM1 (reverse) just after, like:\n\
        554\t26\t0\t0\t1\t16\t1\t17\t+\tMRRE1H032F08FM1\t606\t10\t606\tchr11\t19818926\t3725876\t3726473\t2\t553,27,\t10,579,\t3725876,3726446,\n\
        620\t23\t0\t0\t0\t0\t0\t0\t-\tMRRE1H032F08RM1\t643\t0\t643\tchr11\t19818926\t3794984\t3795627\t1\t643,\t0,\t3794984,\n\
        Note 2: the header in Blat results output file must be present (5 lines).\n\n'
                
        parser = optparse.OptionParser(usage= help, version="CovertSamToFastq.py v1.0")
        parser.add_option( '-i', '--input', dest='inputBLAT', help='Blat Input File Name, with BES paired (1 Forward and 1 Reverse) [Format: tabular]', default= None )
        parser.add_option( '-f', '--fasta', dest='inputFASTA', help='Fasta Input File Name, with all sequences of BES [Format: fasta]', default= None )
        parser.add_option( '-o', '--output', dest='output', help='Output File Name [Format: GFF3]', default= None )
        parser.add_option( '-n', '--methodname', dest='methodName', help='Method name in col. 3 [Default: None]', default= None )
        ( options, args ) = parser.parse_args()
        self._options = options
    
    def checkOptions(self):
        if self._options.inputBLAT == '':
            raise Exception("ERROR: No Blat file specified for -i !")
        elif not os.path.exists(self._options.inputBLAT):
            raise Exception("ERROR: Blat Input File doesn't exist !")
        else:
            self._inputFileBlat = self._options.inputBLAT
            
        if self._options.inputFASTA == '':
            raise Exception("ERROR: No Fasta file specified for -f !")
        elif not os.path.exists(self._options.inputFASTA):
            raise Exception("ERROR: Fasta Input File doesn't exist !")
        else:
            self._inputFileFasta = self._options.inputFASTA
            
        if self._options.output == '':
            raise Exception("ERROR: No Output file specified for -o !")
        else:
            self._outputFileGFF = self._options.output
            
        self._methodName = self._options.methodName
            
    def run(self):
        self.checkOptions()
        self._createGFFOutputFile()
        BLATFile = open(self._inputFileBlat, 'r')
        
        headerBlatLine = BLATFile.readline()
        headerBlatLine = BLATFile.readline()
        headerBlatLine = BLATFile.readline()
        headerBlatLine = BLATFile.readline()
        headerBlatLine = BLATFile.readline()
        blatLine = BLATFile.readline()
        numberLine = 6
        while blatLine != '':
            lGffLines = []
            
            gffLineBes1, besName1, seqBes1, typeBes1 = self.convertBlatObjectToGffLine(blatLine, numberLine)
            lGffLines.append(gffLineBes1)
            
            blatLine = BLATFile.readline()
            numberLine = numberLine + 1
            
            gffLineBes2, besName2, seqBes2, typeBes2 = self.convertBlatObjectToGffLine(blatLine, numberLine)
            lGffLines.append(gffLineBes2)
            
            gffLineBac = self.createGffLineForBac(gffLineBes1, besName1, seqBes1, typeBes1, gffLineBes2, besName2, seqBes2, typeBes2, numberLine)
            lGffLines.append(gffLineBac)
            
            if gffLineBac != None:
                self._printGFFLinesToOutputFile(lGffLines)
                
            blatLine = BLATFile.readline()
            numberLine = numberLine + 1
            
    def convertBlatObjectToGffLine(self, blatLine, numberLine):
        iBlatHit = BlatParser()
        iBlatHit.setAttributesFromString(blatLine, numberLine)
        besName = iBlatHit.getQName()
        seqBes = self.extractBesSequenceFromFastaFile(besName, numberLine)
        
        typeBes = ''
        if re.match('^.+FM[0-9]$', besName):
            typeBes = 'FM'
        elif re.match('^.+RM[0-9]$', besName):
            typeBes = 'RM'
        
        col1 = iBlatHit.getTName()
        col2 = 'BlatToGffForBesPaired'
        if self._methodName == '' or self._methodName == None:
            col3 = 'BES'
        else:
            col3 = '%s:BES' % self._methodName
        col4 = iBlatHit.getTStart()
        col5 = iBlatHit.getTEnd()
        col6 = '.'
        col7 = '+'
        col8 = '.'
        col9 = 'ID=%s;Name=%s;bes_start=%s;bes_end=%s;bes_size=%s;muscadine_seq=%s' % (besName, besName, iBlatHit.getTStart(), iBlatHit.getTEnd(), iBlatHit.getTSize(), seqBes)
            
        gffLine = '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' % (col1, col2, col3, col4, col5, col6, col7, col8, col9)
        return gffLine, iBlatHit.getQName(),seqBes, typeBes
    
    def createGffLineForBac(self, gffLineBes1, besName1, seqBes1, typeBes1, gffLineBes2, besName2, seqBes2, typeBes2, numberLine):
        lGffLineBes1 = gffLineBes1.split('\t')
        lGffLineBes2 = gffLineBes2.split('\t')
        besName1 = self.getBesName(lGffLineBes1[8])
        besName2 = self.getBesName(lGffLineBes2[8])
        
        tBes1 = (lGffLineBes1[0], int(lGffLineBes1[3]), int(lGffLineBes1[4]))
        tBes2 = (lGffLineBes2[0], int(lGffLineBes2[3]), int(lGffLineBes2[4]))
        
        if self.checkBesNames(besName1, besName2, numberLine) == True and self.checkBesPositions(tBes1, tBes2) == True:
            startBacPos, endBacPos = self.getBacPositions(tBes1, tBes2)
            sizeBacPos = endBacPos - startBacPos + 1
            bacName = self.getBacName(besName1)
            nameBesFM, seqBesFM, nameBesRM, seqBesRM = self.getBesFmAndRmNamesAndSequences(besName1, seqBes1, typeBes1, besName2, seqBes2, typeBes2)
            
            col1 = lGffLineBes1[0]
            col2 = 'BlatToGffForBesPaired'
            if self._methodName == '' or self._methodName == None:
                col3 = 'BAC'
            else:
                col3 = '%s:BAC' % self._methodName
            col4 = startBacPos
            col5 = endBacPos
            col6 = '.'
            col7 = '.'
            col8 = '.'
            col9 = 'ID=%s;Name=%s;bac_start=%s;bac_end=%s;bac_size=%s;besFM_name=%s;muscadine_besFM_seq=%s;besRM_name=%s;muscadine_besRM_seq=%s' % (bacName, bacName, startBacPos, endBacPos, sizeBacPos, nameBesFM, seqBesFM, nameBesRM, seqBesRM)
            gffLine = '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' % (col1, col2, col3, col4, col5, col6, col7, col8, col9)
            return gffLine
        return None
    
    def getBesFmAndRmNamesAndSequences(self, besName1, seqBes1, typeBes1, besName2, seqBes2, typeBes2):
        if typeBes1 == 'FM' and typeBes2 == 'RM':
            return besName1, seqBes1, besName2, seqBes2
        elif typeBes1== 'RM' and typeBes2 == 'FM':
            return besName2, seqBes2, besName1, seqBes1

    def getBesName(self, col9):
        lCol9 = col9.split(';')
        ID = lCol9[0]
        besName = ID[3:]
        return besName
    
    def getBacName(self, besName):
        bacName = besName[:-3]
        return bacName

    def checkBesNames(self, besName1, besName2, line):
        bacName1 = besName1[:-3]
        bacName2 = besName2[:-3]
        if bacName1 == bacName2:
            return True
        else:
            sys.stderr.write("WARNING: Lines %s and %s the two Bes (%s AND %s) do not belong to the same BAC !!!\n  -> you have to filter this Blat file...\n" % (int(line)-1, line, besName1, besName2))
            return False
    
    def checkBesPositions(self, tBes1, tBes2):
        if tBes1[0] == tBes2[0]:
            minBes1 = min(tBes1[1], tBes1[2])
            maxBes1 = max(tBes1[1], tBes1[2])
            minBes2 = min(tBes2[1], tBes2[2])
            maxBes2 = max(tBes2[1], tBes2[2])
            if (minBes1 < minBes2 and maxBes1 < minBes2) or (minBes2 < minBes1 and maxBes2 < minBes1):
                return True
        return False
    
    def getBacPositions(self, tBes1, tBes2):
        startBacPos = 0
        endBacPos = 0
        minBes1 = min(tBes1[1], tBes1[2])
        maxBes1 = max(tBes1[1], tBes1[2])
        minBes2 = min(tBes2[1], tBes2[2])
        maxBes2 = max(tBes2[1], tBes2[2])
        if minBes1 < minBes2:
            startBacPos = minBes1
            endBacPos = maxBes2
        else:
            startBacPos = minBes2
            endBacPos = maxBes1
        return startBacPos, endBacPos
    
    def extractBesSequenceFromFastaFile(self, besName, numberLine):
        seq = ''
        date = datetime.datetime.now()
        date = date.strftime("%d%m%Y_%H%M%S")
        tmpFileName = 'tmp_BlatToGffForBesPaired_%s.fasta' % date
        iFastaUtils = FastaUtils()
        iFastaUtils.dbExtractByPattern(besName, self._inputFileFasta, tmpFileName)
        
        if os.path.exists(tmpFileName):
            newFastaFile = open(tmpFileName, 'r')
            line = newFastaFile.readline()
            if line != '':
                while line != '':
                    if line[0] != '>':
                        line = line.replace('\n', '')
                        seq += line
                    line = newFastaFile.readline()
                newFastaFile.close()
                os.remove(tmpFileName)
                return seq
            os.remove(tmpFileName)
        
        sys.stderr.write("WARNING: At line %s, the BAC-Ends (%s) hasn't got sequence in fasta file (%s) !!\n" % (numberLine, besName, os.path.basename(self._inputFileFasta)))
        return 'NA'
    
    def _createGFFOutputFile(self):
        GFFfile = open(self._outputFileGFF, 'w')
        GFFfile.write("##gff-version 3\n")
        GFFfile.close()
        
    def _printGFFLinesToOutputFile(self, lLines):
        GFFfile = open(self._outputFileGFF, 'a')
        for line in lLines:
            GFFfile.write(line)
        GFFfile.close()

if __name__ == '__main__':
    iBlatToGffForBesPaired = BlatToGffForBesPaired()
    iBlatToGffForBesPaired.setAttributesFromCmdLine()
    iBlatToGffForBesPaired.run()