36
|
1 #
|
|
2 # Copyright INRA-URGI 2009-2010
|
|
3 #
|
|
4 # This software is governed by the CeCILL license under French law and
|
|
5 # abiding by the rules of distribution of free software. You can use,
|
|
6 # modify and/ or redistribute the software under the terms of the CeCILL
|
|
7 # license as circulated by CEA, CNRS and INRIA at the following URL
|
|
8 # "http://www.cecill.info".
|
|
9 #
|
|
10 # As a counterpart to the access to the source code and rights to copy,
|
|
11 # modify and redistribute granted by the license, users are provided only
|
|
12 # with a limited warranty and the software's author, the holder of the
|
|
13 # economic rights, and the successive licensors have only limited
|
|
14 # liability.
|
|
15 #
|
|
16 # In this respect, the user's attention is drawn to the risks associated
|
|
17 # with loading, using, modifying and/or developing or reproducing the
|
|
18 # software by the user in light of its specific status of free software,
|
|
19 # that may mean that it is complicated to manipulate, and that also
|
|
20 # therefore means that it is reserved for developers and experienced
|
|
21 # professionals having in-depth computer knowledge. Users are therefore
|
|
22 # encouraged to load and test the software's suitability as regards their
|
|
23 # requirements in conditions enabling the security of their systems and/or
|
|
24 # data to be ensured and, more generally, to use and operate it in the
|
|
25 # same conditions as regards security.
|
|
26 #
|
|
27 # The fact that you are presently reading this means that you have had
|
|
28 # knowledge of the CeCILL license and that you accept its terms.
|
|
29 #
|
|
30 import re
|
|
31 import sys
|
|
32 import os.path
|
|
33 import struct
|
|
34 from commons.core.parsing.TranscriptListParser import TranscriptListParser
|
|
35 from SMART.Java.Python.structure.Transcript import Transcript
|
|
36
|
|
37 STRANDTOSTR = {1: "(+)", 0: "(=)", None: "(=)", -1: "(-)"}
|
|
38
|
|
39 nbOpenHandles = 30
|
|
40
|
|
41
|
|
42 class WigParser(TranscriptListParser):
|
|
43 """A class that parses a big WIG file, creates an index and make it possible to quickly retrieve some data"""
|
|
44
|
|
45 def __init__(self, fileName, verbosity = 1):
|
|
46 self.fileName = fileName
|
|
47 self.filler = "\xFF" * struct.calcsize('Q')
|
|
48 self.strands = False
|
|
49 self.indexFiles = {}
|
|
50 self.indexBuilt = False
|
|
51 self.defaultValue = 0.0
|
|
52 self.currentChromosome = None
|
|
53 self.currentStrand = 1
|
|
54 self.verbosity = verbosity
|
|
55 super(WigParser, self).__init__(fileName, verbosity)
|
|
56
|
|
57
|
|
58 def __def__(self):
|
|
59 for file in self.indexFiles.values():
|
|
60 file.close()
|
|
61
|
|
62
|
|
63 def setStrands(self, strands):
|
|
64 self.strands = strands
|
|
65
|
|
66
|
|
67 def setDefaultValue(self, value):
|
|
68 self.defaultValue = value
|
|
69
|
|
70
|
|
71 def getFileFormats():
|
|
72 return ["wig"]
|
|
73 getFileFormats = staticmethod(getFileFormats)
|
|
74
|
|
75
|
|
76 def setStrands(self, strands):
|
|
77 """
|
|
78 Consider both strands separately
|
|
79 """
|
|
80 self.strands = strands
|
|
81
|
|
82
|
|
83 def makeIndexName(self, chromosome, strand = None):
|
|
84 """
|
|
85 Create an index name for a file
|
|
86 """
|
|
87 directoryName = os.path.dirname(self.fileName)
|
46
|
88 baseName = os.path.splitext(os.path.basename(self.fileName))[0]
|
36
|
89 if strand == None:
|
|
90 strandName = ""
|
|
91 else:
|
|
92 strandName = "+" if strand == 1 else "-"
|
46
|
93 indexName = os.path.join(directoryName, ".%s.%s%s.index" % (baseName, chromosome, strandName))
|
36
|
94 return indexName
|
|
95
|
|
96
|
|
97 def findIndexFile(self, chromosome, strand = None):
|
|
98 """
|
|
99 Check if the index of a file exists
|
|
100 """
|
|
101 indexName = self.makeIndexName(chromosome, strand)
|
|
102 if os.path.exists(indexName):
|
|
103 return indexName
|
|
104 return False
|
|
105
|
|
106
|
|
107 def makeIndexFile(self):
|
|
108 """
|
|
109 Create the index for a file
|
|
110 """
|
|
111 if self.indexBuilt:
|
|
112 return
|
|
113
|
|
114 inputFile = open(self.fileName)
|
|
115 outputFile = None
|
|
116 index = 0
|
|
117 mark = inputFile.tell()
|
|
118 line = inputFile.readline().strip()
|
|
119 chromosome = None
|
|
120
|
|
121 while line != "":
|
|
122 m1 = re.search(r"^\s*-?\d+\.?\d*\s*$", line)
|
|
123 m2 = re.search(r"^\s*(\d+)\s+-?\d+\.?\d*\s*$", line)
|
|
124 m3 = re.search(r"^\s*fixedStep\s+chrom=(\S+)\s+start=(\d+)\s+step=1\s*$", line)
|
|
125 m4 = re.search(r"^\s*fixedStep\s+chrom=\S+\s+start=\d+\s+step=\d+\s+span=\d+\s*$", line)
|
|
126 m5 = re.search(r"^\s*variableStep\s+chrom=(\S+)\s*$", line)
|
|
127 m6 = re.search(r"^\s*variableStep\s+chrom=(\S+)\s+span=(\d+)\s*$", line)
|
|
128
|
|
129 if m1 != None:
|
|
130 outputFile.write(struct.pack("Q", mark))
|
|
131 index += 1
|
|
132 elif m2 != None:
|
|
133 nextIndex = int(m2.group(1))
|
|
134 if index < nextIndex - 1:
|
|
135 outputFile.write(self.filler * (nextIndex - index - 1))
|
|
136 outputFile.write(struct.pack("Q", mark))
|
|
137 index = nextIndex
|
|
138 elif m3 != None:
|
|
139 newChromosome = m3.group(1)
|
|
140 if newChromosome != chromosome:
|
|
141 if outputFile != None:
|
|
142 outputFile.close()
|
|
143 outputFile = open(self.makeIndexName(newChromosome), "wb")
|
|
144 chromosome = newChromosome
|
|
145 nextIndex = int(m3.group(2))
|
|
146 outputFile.write(self.filler * (nextIndex - index))
|
|
147 index = nextIndex
|
|
148 elif m4 != None:
|
|
149 raise Exception("Error! Cannot parse fixed step WIG files with step > 1 or span > 1")
|
|
150 elif m5 != None:
|
|
151 newChromosome = m5.group(1)
|
|
152 if newChromosome != chromosome:
|
|
153 if outputFile != None:
|
|
154 outputFile.close()
|
|
155 outputFile = open(self.makeIndexName(newChromosome), "wb")
|
|
156 index = 0
|
|
157 outputFile.write(self.filler)
|
|
158 chromosome = newChromosome
|
|
159 elif m6 != None:
|
|
160 if m6.group(2) != "1":
|
|
161 raise Exception("Error! Cannot parse variable step WIG files with step > 1 or span > 1")
|
|
162 newChromosome = m6.group(1)
|
|
163 if newChromosome != chromosome:
|
|
164 if outputFile != None:
|
|
165 outputFile.close()
|
|
166 outputFile = open(self.makeIndexName(newChromosome), "wb")
|
|
167 index = 0
|
|
168 outputFile.write(self.filler)
|
|
169 chromosome = newChromosome
|
|
170 elif (len(line) == 0) or line[0] == "#" or line.startswith("track"):
|
|
171 pass
|
|
172 else:
|
|
173 raise Exception("Error! Cannot understand line '%s' of WIG file while creating index file! Aborting." % (line))
|
|
174
|
|
175 mark = inputFile.tell()
|
|
176 line = inputFile.readline().strip()
|
|
177
|
|
178 inputFile.close
|
|
179 if outputFile != None:
|
|
180 outputFile.close()
|
|
181 self.indexBuilt = True
|
|
182
|
|
183
|
|
184 def getIndexFileHandle(self, chromosome, strand = None):
|
|
185 """
|
|
186 Get the handle of an index file
|
|
187 """
|
|
188 indexFileKey = chromosome
|
|
189 if strand != None:
|
|
190 indexFileKey += "+" if strand == 1 else "-"
|
|
191 if indexFileKey in self.indexFiles:
|
|
192 return self.indexFiles[indexFileKey]
|
|
193
|
|
194 indexFileName = self.makeIndexName(chromosome, strand)
|
|
195 if not self.findIndexFile(chromosome, strand):
|
|
196 self.makeIndexFile()
|
|
197
|
|
198 if not os.path.exists(indexFileName):
|
|
199 print "Warning! Index for chromosome %s, strand %s does not exist." % (chromosome, STRANDTOSTR[strand])
|
|
200 return False
|
|
201 indexFile = open(indexFileName, "rb")
|
|
202
|
|
203 if len(self.indexFiles.keys()) > nbOpenHandles:
|
|
204 removedKey = set(self.indexFiles.keys()).pop()
|
|
205 self.indexFiles[removedKey].close()
|
|
206 del self.indexFiles[removedKey]
|
|
207 self.indexFiles[indexFileKey] = indexFile
|
|
208 return indexFile
|
|
209
|
|
210
|
|
211
|
|
212 def findIndex(self, chromosome, start, strand = None):
|
|
213 """
|
|
214 Find the point where to start reading file
|
|
215 """
|
|
216
|
|
217 sizeOfLong = struct.calcsize("Q")
|
|
218 empty = int(struct.unpack("Q", self.filler)[0])
|
|
219 offset = empty
|
|
220 indexFile = self.getIndexFileHandle(chromosome, strand)
|
|
221
|
|
222 if not indexFile:
|
|
223 return (None, None)
|
|
224
|
|
225 while offset == empty:
|
|
226 address = start * sizeOfLong
|
|
227 indexFile.seek(address, os.SEEK_SET)
|
|
228
|
|
229 buffer = indexFile.read(sizeOfLong)
|
|
230 if len(buffer) != sizeOfLong:
|
|
231 if buffer == "":
|
|
232 print "Warning! Index position %d of chromosome %s on strand %s seems out of range!" % (start, chromosome, STRANDTOSTR[strand])
|
|
233 return (None, None)
|
|
234 else:
|
|
235 raise Exception("Problem fetching position %d of chromosome %s on strand %s seems out of range!" % (start, chromosome, STRANDTOSTR[strand]))
|
|
236
|
|
237 offset = int(struct.unpack("Q", buffer)[0])
|
|
238 start += 1
|
|
239
|
|
240 start -= 1
|
|
241 return (offset, start)
|
|
242
|
|
243
|
|
244
|
|
245 def getRange(self, chromosome, start, end):
|
|
246 """
|
|
247 Parse a wig file and output a range
|
|
248 """
|
|
249 arrays = {}
|
|
250 strands = {1: "+", -1: "-"} if self.strands else {0: ""}
|
|
251
|
|
252 for strand in strands:
|
|
253
|
|
254 array = [self.defaultValue] * (end - start + 1)
|
|
255 file = open(self.fileName)
|
|
256 offset, index = self.findIndex(chromosome, start, strand if self.strands else None)
|
|
257 if offset == None:
|
|
258 arrays[strand] = array
|
|
259 continue
|
|
260 file.seek(offset, os.SEEK_SET)
|
|
261
|
|
262 for line in file:
|
|
263 line = line.strip()
|
|
264
|
|
265 m1 = re.search(r"^\s*(-?\d+\.?\d*)\s*$", line)
|
|
266 m2 = re.search(r"^\s*(\d+)\s+(-?\d+\.?\d*)\s*$", line)
|
|
267 m3 = re.search(r"^\s*fixedStep\s+chrom=(\S+)\s+start=(\d+)\s+step=\d+\s*$", line)
|
|
268 m4 = re.search(r"^\s*variableStep\s+chrom=(\S+)\s*$", line)
|
|
269
|
|
270 if m1 != None:
|
|
271 if index > end:
|
|
272 break
|
|
273 if index >= start:
|
|
274 array[index - start] = float(m1.group(1))
|
|
275 index += 1
|
|
276 elif m2 != None:
|
|
277 index = int(m2.group(1))
|
|
278 if index > end:
|
|
279 break
|
|
280 if index >= start:
|
|
281 array[index - start] = float(m2.group(2))
|
|
282 index += 1
|
|
283 elif m3 != None:
|
|
284 if m3.group(1) != "%s%s" % (chromosome, strands[strand]):
|
|
285 break
|
|
286 index = int(m3.group(2))
|
|
287 elif m4 != None:
|
|
288 if m4.group(1) != "%s%s" % (chromosome, strands[strand]):
|
|
289 break
|
|
290 elif (len(line) == 0) or (line[0] == "#") or line.startswith("track"):
|
|
291 pass
|
|
292 else:
|
|
293 raise Exception("Error! Cannot read line '%s' of wig file" % (line))
|
|
294
|
|
295 file.close()
|
|
296
|
|
297 arrays[strand] = array
|
|
298
|
|
299 if self.strands:
|
|
300 return arrays
|
|
301 return array
|
|
302
|
|
303
|
|
304 def skipFirstLines(self):
|
|
305 return
|
|
306
|
|
307
|
|
308 def parseLine(self, line):
|
|
309 if line.startswith("track"):
|
|
310 return None
|
|
311 m = re.search(r"^\s*variableStep\s+chrom=(\S+)", line)
|
|
312 if m != None:
|
|
313 chromosome = m.group(1)
|
|
314 if chromosome.endswith("+"):
|
|
315 self.currentStrand = 1
|
|
316 self.currentChromosome = chromosome[:-1]
|
|
317 elif chromosome.endswith("-"):
|
|
318 self.currentStrand = -1
|
|
319 self.currentChromosome = chromosome[:-1]
|
|
320 else:
|
|
321 self.currentStrand = 1
|
|
322 self.currentChromosome = chromosome
|
|
323 return None
|
|
324 position, value = line.split()
|
|
325 position = int(position)
|
|
326 value = float(value)
|
|
327 transcript = Transcript()
|
|
328 transcript.setChromosome(self.currentChromosome)
|
|
329 transcript.setStart(position)
|
|
330 transcript.setEnd(position)
|
|
331 transcript.setDirection(self.currentStrand)
|
|
332 transcript.setTagValue("ID", "wig_%s_%d_%d" % (self.currentChromosome, self.currentStrand, position))
|
|
333 transcript.setTagValue("nbElements", value)
|
|
334 return transcript
|