comparison 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
comparison
equal deleted inserted replaced
-1:000000000000 0:e0f8dcca02ed
1 # Copyright INRA (Institut National de la Recherche Agronomique)
2 # http://www.inra.fr
3 # http://urgi.versailles.inra.fr
4 #
5 # This software is governed by the CeCILL license under French law and
6 # abiding by the rules of distribution of free software. You can use,
7 # modify and/ or redistribute the software under the terms of the CeCILL
8 # license as circulated by CEA, CNRS and INRIA at the following URL
9 # "http://www.cecill.info".
10 #
11 # As a counterpart to the access to the source code and rights to copy,
12 # modify and redistribute granted by the license, users are provided only
13 # with a limited warranty and the software's author, the holder of the
14 # economic rights, and the successive licensors have only limited
15 # liability.
16 #
17 # In this respect, the user's attention is drawn to the risks associated
18 # with loading, using, modifying and/or developing or reproducing the
19 # software by the user in light of its specific status of free software,
20 # that may mean that it is complicated to manipulate, and that also
21 # therefore means that it is reserved for developers and experienced
22 # professionals having in-depth computer knowledge. Users are therefore
23 # encouraged to load and test the software's suitability as regards their
24 # requirements in conditions enabling the security of their systems and/or
25 # data to be ensured and, more generally, to use and operate it in the
26 # same conditions as regards security.
27 #
28 # The fact that you are presently reading this means that you have had
29 # knowledge of the CeCILL license and that you accept its terms.
30
31 import optparse
32 import os
33 import sys
34 import re
35 import datetime
36 from commons.core.parsing.BlatParser import BlatParser
37 from commons.core.seq.FastaUtils import FastaUtils
38
39 class BlatToGffForBesPaired(object):
40
41
42 def __init__(self):
43 pass
44
45 def setAttributesFromCmdLine(self):
46 help = '\
47 \nThis Script Launch BlatToGffForBesPaired.\n\n\
48 Example 1: python BlatToGffForBesPaired.py -i blatResultsFile.tab -f besSequences.fasta -o outputFile.gff3\n\
49 Example 2: python BlatToGffForBesPaired.py -i blatResultsFile.tab -f besSequences.fasta -o outputFile.gff3 -n muscadine:filtre1\n\n\
50 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\
51 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\
52 620\t23\t0\t0\t0\t0\t0\t0\t-\tMRRE1H032F08RM1\t643\t0\t643\tchr11\t19818926\t3794984\t3795627\t1\t643,\t0,\t3794984,\n\
53 Note 2: the header in Blat results output file must be present (5 lines).\n\n'
54
55 parser = optparse.OptionParser(usage= help, version="CovertSamToFastq.py v1.0")
56 parser.add_option( '-i', '--input', dest='inputBLAT', help='Blat Input File Name, with BES paired (1 Forward and 1 Reverse) [Format: tabular]', default= None )
57 parser.add_option( '-f', '--fasta', dest='inputFASTA', help='Fasta Input File Name, with all sequences of BES [Format: fasta]', default= None )
58 parser.add_option( '-o', '--output', dest='output', help='Output File Name [Format: GFF3]', default= None )
59 parser.add_option( '-n', '--methodname', dest='methodName', help='Method name in col. 3 [Default: None]', default= None )
60 ( options, args ) = parser.parse_args()
61 self._options = options
62
63 def checkOptions(self):
64 if self._options.inputBLAT == '':
65 raise Exception("ERROR: No Blat file specified for -i !")
66 elif not os.path.exists(self._options.inputBLAT):
67 raise Exception("ERROR: Blat Input File doesn't exist !")
68 else:
69 self._inputFileBlat = self._options.inputBLAT
70
71 if self._options.inputFASTA == '':
72 raise Exception("ERROR: No Fasta file specified for -f !")
73 elif not os.path.exists(self._options.inputFASTA):
74 raise Exception("ERROR: Fasta Input File doesn't exist !")
75 else:
76 self._inputFileFasta = self._options.inputFASTA
77
78 if self._options.output == '':
79 raise Exception("ERROR: No Output file specified for -o !")
80 else:
81 self._outputFileGFF = self._options.output
82
83 self._methodName = self._options.methodName
84
85 def run(self):
86 self.checkOptions()
87 self._createGFFOutputFile()
88 BLATFile = open(self._inputFileBlat, 'r')
89
90 headerBlatLine = BLATFile.readline()
91 headerBlatLine = BLATFile.readline()
92 headerBlatLine = BLATFile.readline()
93 headerBlatLine = BLATFile.readline()
94 headerBlatLine = BLATFile.readline()
95 blatLine = BLATFile.readline()
96 numberLine = 6
97 while blatLine != '':
98 lGffLines = []
99
100 gffLineBes1, besName1, seqBes1, typeBes1 = self.convertBlatObjectToGffLine(blatLine, numberLine)
101 lGffLines.append(gffLineBes1)
102
103 blatLine = BLATFile.readline()
104 numberLine = numberLine + 1
105
106 gffLineBes2, besName2, seqBes2, typeBes2 = self.convertBlatObjectToGffLine(blatLine, numberLine)
107 lGffLines.append(gffLineBes2)
108
109 gffLineBac = self.createGffLineForBac(gffLineBes1, besName1, seqBes1, typeBes1, gffLineBes2, besName2, seqBes2, typeBes2, numberLine)
110 lGffLines.append(gffLineBac)
111
112 if gffLineBac != None:
113 self._printGFFLinesToOutputFile(lGffLines)
114
115 blatLine = BLATFile.readline()
116 numberLine = numberLine + 1
117
118 def convertBlatObjectToGffLine(self, blatLine, numberLine):
119 iBlatHit = BlatParser()
120 iBlatHit.setAttributesFromString(blatLine, numberLine)
121 besName = iBlatHit.getQName()
122 seqBes = self.extractBesSequenceFromFastaFile(besName, numberLine)
123
124 typeBes = ''
125 if re.match('^.+FM[0-9]$', besName):
126 typeBes = 'FM'
127 elif re.match('^.+RM[0-9]$', besName):
128 typeBes = 'RM'
129
130 col1 = iBlatHit.getTName()
131 col2 = 'BlatToGffForBesPaired'
132 if self._methodName == '' or self._methodName == None:
133 col3 = 'BES'
134 else:
135 col3 = '%s:BES' % self._methodName
136 col4 = iBlatHit.getTStart()
137 col5 = iBlatHit.getTEnd()
138 col6 = '.'
139 col7 = '+'
140 col8 = '.'
141 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)
142
143 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)
144 return gffLine, iBlatHit.getQName(),seqBes, typeBes
145
146 def createGffLineForBac(self, gffLineBes1, besName1, seqBes1, typeBes1, gffLineBes2, besName2, seqBes2, typeBes2, numberLine):
147 lGffLineBes1 = gffLineBes1.split('\t')
148 lGffLineBes2 = gffLineBes2.split('\t')
149 besName1 = self.getBesName(lGffLineBes1[8])
150 besName2 = self.getBesName(lGffLineBes2[8])
151
152 tBes1 = (lGffLineBes1[0], int(lGffLineBes1[3]), int(lGffLineBes1[4]))
153 tBes2 = (lGffLineBes2[0], int(lGffLineBes2[3]), int(lGffLineBes2[4]))
154
155 if self.checkBesNames(besName1, besName2, numberLine) == True and self.checkBesPositions(tBes1, tBes2) == True:
156 startBacPos, endBacPos = self.getBacPositions(tBes1, tBes2)
157 sizeBacPos = endBacPos - startBacPos + 1
158 bacName = self.getBacName(besName1)
159 nameBesFM, seqBesFM, nameBesRM, seqBesRM = self.getBesFmAndRmNamesAndSequences(besName1, seqBes1, typeBes1, besName2, seqBes2, typeBes2)
160
161 col1 = lGffLineBes1[0]
162 col2 = 'BlatToGffForBesPaired'
163 if self._methodName == '' or self._methodName == None:
164 col3 = 'BAC'
165 else:
166 col3 = '%s:BAC' % self._methodName
167 col4 = startBacPos
168 col5 = endBacPos
169 col6 = '.'
170 col7 = '.'
171 col8 = '.'
172 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)
173 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)
174 return gffLine
175 return None
176
177 def getBesFmAndRmNamesAndSequences(self, besName1, seqBes1, typeBes1, besName2, seqBes2, typeBes2):
178 if typeBes1 == 'FM' and typeBes2 == 'RM':
179 return besName1, seqBes1, besName2, seqBes2
180 elif typeBes1== 'RM' and typeBes2 == 'FM':
181 return besName2, seqBes2, besName1, seqBes1
182
183 def getBesName(self, col9):
184 lCol9 = col9.split(';')
185 ID = lCol9[0]
186 besName = ID[3:]
187 return besName
188
189 def getBacName(self, besName):
190 bacName = besName[:-3]
191 return bacName
192
193 def checkBesNames(self, besName1, besName2, line):
194 bacName1 = besName1[:-3]
195 bacName2 = besName2[:-3]
196 if bacName1 == bacName2:
197 return True
198 else:
199 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))
200 return False
201
202 def checkBesPositions(self, tBes1, tBes2):
203 if tBes1[0] == tBes2[0]:
204 minBes1 = min(tBes1[1], tBes1[2])
205 maxBes1 = max(tBes1[1], tBes1[2])
206 minBes2 = min(tBes2[1], tBes2[2])
207 maxBes2 = max(tBes2[1], tBes2[2])
208 if (minBes1 < minBes2 and maxBes1 < minBes2) or (minBes2 < minBes1 and maxBes2 < minBes1):
209 return True
210 return False
211
212 def getBacPositions(self, tBes1, tBes2):
213 startBacPos = 0
214 endBacPos = 0
215 minBes1 = min(tBes1[1], tBes1[2])
216 maxBes1 = max(tBes1[1], tBes1[2])
217 minBes2 = min(tBes2[1], tBes2[2])
218 maxBes2 = max(tBes2[1], tBes2[2])
219 if minBes1 < minBes2:
220 startBacPos = minBes1
221 endBacPos = maxBes2
222 else:
223 startBacPos = minBes2
224 endBacPos = maxBes1
225 return startBacPos, endBacPos
226
227 def extractBesSequenceFromFastaFile(self, besName, numberLine):
228 seq = ''
229 date = datetime.datetime.now()
230 date = date.strftime("%d%m%Y_%H%M%S")
231 tmpFileName = 'tmp_BlatToGffForBesPaired_%s.fasta' % date
232 iFastaUtils = FastaUtils()
233 iFastaUtils.dbExtractByPattern(besName, self._inputFileFasta, tmpFileName)
234
235 if os.path.exists(tmpFileName):
236 newFastaFile = open(tmpFileName, 'r')
237 line = newFastaFile.readline()
238 if line != '':
239 while line != '':
240 if line[0] != '>':
241 line = line.replace('\n', '')
242 seq += line
243 line = newFastaFile.readline()
244 newFastaFile.close()
245 os.remove(tmpFileName)
246 return seq
247 os.remove(tmpFileName)
248
249 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)))
250 return 'NA'
251
252 def _createGFFOutputFile(self):
253 GFFfile = open(self._outputFileGFF, 'w')
254 GFFfile.write("##gff-version 3\n")
255 GFFfile.close()
256
257 def _printGFFLinesToOutputFile(self, lLines):
258 GFFfile = open(self._outputFileGFF, 'a')
259 for line in lLines:
260 GFFfile.write(line)
261 GFFfile.close()
262
263 if __name__ == '__main__':
264 iBlatToGffForBesPaired = BlatToGffForBesPaired()
265 iBlatToGffForBesPaired.setAttributesFromCmdLine()
266 iBlatToGffForBesPaired.run()