comparison commons/core/parsing/WigParser.py @ 36:44d5973c188c

Uploaded
author m-zytnicki
date Tue, 30 Apr 2013 15:02:29 -0400
parents
children 169d364ddd91
comparison
equal deleted inserted replaced
35:d94018ca4ada 36:44d5973c188c
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)
88 if strand == None:
89 strandName = ""
90 else:
91 strandName = "+" if strand == 1 else "-"
92 indexName = os.path.join(directoryName, ".%s%s.index" % (chromosome, strandName))
93 return indexName
94
95
96 def findIndexFile(self, chromosome, strand = None):
97 """
98 Check if the index of a file exists
99 """
100 indexName = self.makeIndexName(chromosome, strand)
101 if os.path.exists(indexName):
102 return indexName
103 return False
104
105
106 def makeIndexFile(self):
107 """
108 Create the index for a file
109 """
110 if self.indexBuilt:
111 return
112
113 inputFile = open(self.fileName)
114 outputFile = None
115 index = 0
116 mark = inputFile.tell()
117 line = inputFile.readline().strip()
118 chromosome = None
119
120 while line != "":
121 m1 = re.search(r"^\s*-?\d+\.?\d*\s*$", line)
122 m2 = re.search(r"^\s*(\d+)\s+-?\d+\.?\d*\s*$", line)
123 m3 = re.search(r"^\s*fixedStep\s+chrom=(\S+)\s+start=(\d+)\s+step=1\s*$", line)
124 m4 = re.search(r"^\s*fixedStep\s+chrom=\S+\s+start=\d+\s+step=\d+\s+span=\d+\s*$", line)
125 m5 = re.search(r"^\s*variableStep\s+chrom=(\S+)\s*$", line)
126 m6 = re.search(r"^\s*variableStep\s+chrom=(\S+)\s+span=(\d+)\s*$", line)
127
128 if m1 != None:
129 outputFile.write(struct.pack("Q", mark))
130 index += 1
131 elif m2 != None:
132 nextIndex = int(m2.group(1))
133 if index < nextIndex - 1:
134 outputFile.write(self.filler * (nextIndex - index - 1))
135 outputFile.write(struct.pack("Q", mark))
136 index = nextIndex
137 elif m3 != None:
138 newChromosome = m3.group(1)
139 if newChromosome != chromosome:
140 if outputFile != None:
141 outputFile.close()
142 outputFile = open(self.makeIndexName(newChromosome), "wb")
143 chromosome = newChromosome
144 nextIndex = int(m3.group(2))
145 outputFile.write(self.filler * (nextIndex - index))
146 index = nextIndex
147 elif m4 != None:
148 raise Exception("Error! Cannot parse fixed step WIG files with step > 1 or span > 1")
149 elif m5 != None:
150 newChromosome = m5.group(1)
151 if newChromosome != chromosome:
152 if outputFile != None:
153 outputFile.close()
154 outputFile = open(self.makeIndexName(newChromosome), "wb")
155 index = 0
156 outputFile.write(self.filler)
157 chromosome = newChromosome
158 elif m6 != None:
159 if m6.group(2) != "1":
160 raise Exception("Error! Cannot parse variable step WIG files with step > 1 or span > 1")
161 newChromosome = m6.group(1)
162 if newChromosome != chromosome:
163 if outputFile != None:
164 outputFile.close()
165 outputFile = open(self.makeIndexName(newChromosome), "wb")
166 index = 0
167 outputFile.write(self.filler)
168 chromosome = newChromosome
169 elif (len(line) == 0) or line[0] == "#" or line.startswith("track"):
170 pass
171 else:
172 raise Exception("Error! Cannot understand line '%s' of WIG file while creating index file! Aborting." % (line))
173
174 mark = inputFile.tell()
175 line = inputFile.readline().strip()
176
177 inputFile.close
178 if outputFile != None:
179 outputFile.close()
180 self.indexBuilt = True
181
182
183 def getIndexFileHandle(self, chromosome, strand = None):
184 """
185 Get the handle of an index file
186 """
187 indexFileKey = chromosome
188 if strand != None:
189 indexFileKey += "+" if strand == 1 else "-"
190 if indexFileKey in self.indexFiles:
191 return self.indexFiles[indexFileKey]
192
193 indexFileName = self.makeIndexName(chromosome, strand)
194 if not self.findIndexFile(chromosome, strand):
195 self.makeIndexFile()
196
197 if not os.path.exists(indexFileName):
198 print "Warning! Index for chromosome %s, strand %s does not exist." % (chromosome, STRANDTOSTR[strand])
199 return False
200 indexFile = open(indexFileName, "rb")
201
202 if len(self.indexFiles.keys()) > nbOpenHandles:
203 removedKey = set(self.indexFiles.keys()).pop()
204 self.indexFiles[removedKey].close()
205 del self.indexFiles[removedKey]
206 self.indexFiles[indexFileKey] = indexFile
207 return indexFile
208
209
210
211 def findIndex(self, chromosome, start, strand = None):
212 """
213 Find the point where to start reading file
214 """
215
216 sizeOfLong = struct.calcsize("Q")
217 empty = int(struct.unpack("Q", self.filler)[0])
218 offset = empty
219 indexFile = self.getIndexFileHandle(chromosome, strand)
220
221 if not indexFile:
222 return (None, None)
223
224 while offset == empty:
225 address = start * sizeOfLong
226 indexFile.seek(address, os.SEEK_SET)
227
228 buffer = indexFile.read(sizeOfLong)
229 if len(buffer) != sizeOfLong:
230 if buffer == "":
231 print "Warning! Index position %d of chromosome %s on strand %s seems out of range!" % (start, chromosome, STRANDTOSTR[strand])
232 return (None, None)
233 else:
234 raise Exception("Problem fetching position %d of chromosome %s on strand %s seems out of range!" % (start, chromosome, STRANDTOSTR[strand]))
235
236 offset = int(struct.unpack("Q", buffer)[0])
237 start += 1
238
239 start -= 1
240 return (offset, start)
241
242
243
244 def getRange(self, chromosome, start, end):
245 """
246 Parse a wig file and output a range
247 """
248 arrays = {}
249 strands = {1: "+", -1: "-"} if self.strands else {0: ""}
250
251 for strand in strands:
252
253 array = [self.defaultValue] * (end - start + 1)
254 file = open(self.fileName)
255 offset, index = self.findIndex(chromosome, start, strand if self.strands else None)
256 if offset == None:
257 arrays[strand] = array
258 continue
259 file.seek(offset, os.SEEK_SET)
260
261 for line in file:
262 line = line.strip()
263
264 m1 = re.search(r"^\s*(-?\d+\.?\d*)\s*$", line)
265 m2 = re.search(r"^\s*(\d+)\s+(-?\d+\.?\d*)\s*$", line)
266 m3 = re.search(r"^\s*fixedStep\s+chrom=(\S+)\s+start=(\d+)\s+step=\d+\s*$", line)
267 m4 = re.search(r"^\s*variableStep\s+chrom=(\S+)\s*$", line)
268
269 if m1 != None:
270 if index > end:
271 break
272 if index >= start:
273 array[index - start] = float(m1.group(1))
274 index += 1
275 elif m2 != None:
276 index = int(m2.group(1))
277 if index > end:
278 break
279 if index >= start:
280 array[index - start] = float(m2.group(2))
281 index += 1
282 elif m3 != None:
283 if m3.group(1) != "%s%s" % (chromosome, strands[strand]):
284 break
285 index = int(m3.group(2))
286 elif m4 != None:
287 if m4.group(1) != "%s%s" % (chromosome, strands[strand]):
288 break
289 elif (len(line) == 0) or (line[0] == "#") or line.startswith("track"):
290 pass
291 else:
292 raise Exception("Error! Cannot read line '%s' of wig file" % (line))
293
294 file.close()
295
296 arrays[strand] = array
297
298 if self.strands:
299 return arrays
300 return array
301
302
303 def skipFirstLines(self):
304 return
305
306
307 def parseLine(self, line):
308 if line.startswith("track"):
309 return None
310 m = re.search(r"^\s*variableStep\s+chrom=(\S+)", line)
311 if m != None:
312 chromosome = m.group(1)
313 if chromosome.endswith("+"):
314 self.currentStrand = 1
315 self.currentChromosome = chromosome[:-1]
316 elif chromosome.endswith("-"):
317 self.currentStrand = -1
318 self.currentChromosome = chromosome[:-1]
319 else:
320 self.currentStrand = 1
321 self.currentChromosome = chromosome
322 return None
323 position, value = line.split()
324 position = int(position)
325 value = float(value)
326 transcript = Transcript()
327 transcript.setChromosome(self.currentChromosome)
328 transcript.setStart(position)
329 transcript.setEnd(position)
330 transcript.setDirection(self.currentStrand)
331 transcript.setTagValue("ID", "wig_%s_%d_%d" % (self.currentChromosome, self.currentStrand, position))
332 transcript.setTagValue("nbElements", value)
333 return transcript