6
|
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+)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 raise Exception("Error! Cannot parse variable step WIG files with step > 1 or span > 1")
|
|
160 elif (len(line) == 0) or line[0] == "#" or line.startswith("track"):
|
|
161 pass
|
|
162 else:
|
|
163 raise Exception("Error! Cannot understand line '%s' of WIG file while creating index file! Aborting." % (line))
|
|
164
|
|
165 mark = inputFile.tell()
|
|
166 line = inputFile.readline().strip()
|
|
167
|
|
168 inputFile.close
|
|
169 if outputFile != None:
|
|
170 outputFile.close()
|
|
171 self.indexBuilt = True
|
|
172
|
|
173
|
|
174 def getIndexFileHandle(self, chromosome, strand = None):
|
|
175 """
|
|
176 Get the handle of an index file
|
|
177 """
|
|
178 indexFileKey = chromosome
|
|
179 if strand != None:
|
|
180 indexFileKey += "+" if strand == 1 else "-"
|
|
181 if indexFileKey in self.indexFiles:
|
|
182 return self.indexFiles[indexFileKey]
|
|
183
|
|
184 indexFileName = self.makeIndexName(chromosome, strand)
|
|
185 if not self.findIndexFile(chromosome, strand):
|
|
186 self.makeIndexFile()
|
|
187
|
|
188 if not os.path.exists(indexFileName):
|
|
189 print "Warning! Index for chromosome %s, strand %s does not exist." % (chromosome, STRANDTOSTR[strand])
|
|
190 return False
|
|
191 indexFile = open(indexFileName, "rb")
|
|
192
|
|
193 if len(self.indexFiles.keys()) > nbOpenHandles:
|
|
194 removedKey = set(self.indexFiles.keys()).pop()
|
|
195 self.indexFiles[removedKey].close()
|
|
196 del self.indexFiles[removedKey]
|
|
197 self.indexFiles[indexFileKey] = indexFile
|
|
198 return indexFile
|
|
199
|
|
200
|
|
201
|
|
202 def findIndex(self, chromosome, start, strand = None):
|
|
203 """
|
|
204 Find the point where to start reading file
|
|
205 """
|
|
206
|
|
207 sizeOfLong = struct.calcsize("Q")
|
|
208 empty = int(struct.unpack("Q", self.filler)[0])
|
|
209 offset = empty
|
|
210 indexFile = self.getIndexFileHandle(chromosome, strand)
|
|
211
|
|
212 if not indexFile:
|
|
213 return (None, None)
|
|
214
|
|
215 while offset == empty:
|
|
216 address = start * sizeOfLong
|
|
217 indexFile.seek(address, os.SEEK_SET)
|
|
218
|
|
219 buffer = indexFile.read(sizeOfLong)
|
|
220 if len(buffer) != sizeOfLong:
|
|
221 if buffer == "":
|
|
222 print "Warning! Index position %d of chromosome %s on strand %s seems out of range!" % (start, chromosome, STRANDTOSTR[strand])
|
|
223 return (None, None)
|
|
224 else:
|
|
225 raise Exception("Problem fetching position %d of chromosome %s on strand %s seems out of range!" % (start, chromosome, STRANDTOSTR[strand]))
|
|
226
|
|
227 offset = int(struct.unpack("Q", buffer)[0])
|
|
228 start += 1
|
|
229
|
|
230 start -= 1
|
|
231 return (offset, start)
|
|
232
|
|
233
|
|
234
|
|
235 def getRange(self, chromosome, start, end):
|
|
236 """
|
|
237 Parse a wig file and output a range
|
|
238 """
|
|
239 arrays = {}
|
|
240 strands = {1: "+", -1: "-"} if self.strands else {0: ""}
|
|
241
|
|
242 for strand in strands:
|
|
243
|
|
244 array = [self.defaultValue] * (end - start + 1)
|
|
245 file = open(self.fileName)
|
|
246 offset, index = self.findIndex(chromosome, start, strand if self.strands else None)
|
|
247 if offset == None:
|
|
248 arrays[strand] = array
|
|
249 continue
|
|
250 file.seek(offset, os.SEEK_SET)
|
|
251
|
|
252 for line in file:
|
|
253 line = line.strip()
|
|
254
|
|
255 m1 = re.search(r"^\s*(-?\d+\.?\d*)\s*$", line)
|
|
256 m2 = re.search(r"^\s*(\d+)\s+(-?\d+\.?\d*)\s*$", line)
|
|
257 m3 = re.search(r"^\s*fixedStep\s+chrom=(\S+)\s+start=(\d+)\s+step=\d+\s*$", line)
|
|
258 m4 = re.search(r"^\s*variableStep\s+chrom=(\S+)\s*$", line)
|
|
259
|
|
260 if m1 != None:
|
|
261 if index > end:
|
|
262 break
|
|
263 if index >= start:
|
|
264 array[index - start] = float(m1.group(1))
|
|
265 index += 1
|
|
266 elif m2 != None:
|
|
267 index = int(m2.group(1))
|
|
268 if index > end:
|
|
269 break
|
|
270 if index >= start:
|
|
271 array[index - start] = float(m2.group(2))
|
|
272 index += 1
|
|
273 elif m3 != None:
|
|
274 if m3.group(1) != "%s%s" % (chromosome, strands[strand]):
|
|
275 break
|
|
276 index = int(m3.group(2))
|
|
277 elif m4 != None:
|
|
278 if m4.group(1) != "%s%s" % (chromosome, strands[strand]):
|
|
279 break
|
|
280 elif (len(line) == 0) or (line[0] == "#") or line.startswith("track"):
|
|
281 pass
|
|
282 else:
|
|
283 raise Exception("Error! Cannot read line '%s' of wig file" % (line))
|
|
284
|
|
285 file.close()
|
|
286
|
|
287 arrays[strand] = array
|
|
288
|
|
289 if self.strands:
|
|
290 return arrays
|
|
291 return array
|
|
292
|
|
293
|
|
294 def skipFirstLines(self):
|
|
295 return
|
|
296
|
|
297
|
|
298 def parseLine(self, line):
|
|
299 if line.startswith("track"):
|
|
300 return None
|
|
301 m = re.search(r"^\s*variableStep\s+chrom=(\S+)", line)
|
|
302 if m != None:
|
|
303 chromosome = m.group(1)
|
|
304 if chromosome.endswith("+"):
|
|
305 self.currentStrand = 1
|
|
306 self.currentChromosome = chromosome[:-1]
|
|
307 elif chromosome.endswith("-"):
|
|
308 self.currentStrand = -1
|
|
309 self.currentChromosome = chromosome[:-1]
|
|
310 else:
|
|
311 self.currentStrand = 1
|
|
312 self.currentChromosome = chromosome
|
|
313 return None
|
|
314 position, value = line.split()
|
|
315 position = int(position)
|
|
316 value = float(value)
|
|
317 transcript = Transcript()
|
|
318 transcript.setChromosome(self.currentChromosome)
|
|
319 transcript.setStart(position)
|
|
320 transcript.setEnd(position)
|
|
321 transcript.setDirection(self.currentStrand)
|
|
322 transcript.setTagValue("ID", "wig_%s_%d_%d" % (self.currentChromosome, self.currentStrand, position))
|
|
323 transcript.setTagValue("nbElements", value)
|
|
324 return transcript
|