Debian Codegraph @

pymzml/utils/GSGW.py

raw symbols SCIP
1 #!/usr/bin/env python
2 # -*- coding: latin-1 -*-
3 """
4 Writer class for indexed gzipped files
5 """
6
7 # Python mzML module - pymzml
8 # Copyright (C) 2010-2019 M. Kösters, C. Fufezan
9 # The MIT License (MIT)
10
11 # Permission is hereby granted, free of charge, to any person obtaining a copy
12 # of this software and associated documentation files (the "Software"), to deal
13 # in the Software without restriction, including without limitation the rights
14 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15 # copies of the Software, and to permit persons to whom the Software is
16 # furnished to do so, subject to the following conditions:
17
18 # The above copyright notice and this permission notice shall be included in all
19 # copies or substantial portions of the Software.
20
21 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27 # SOFTWARE.
28
29 import struct
30 import time
31 import zlib
32 from collections import OrderedDict
33
34
35 class GSGW(object):
36 """
37
38 Generalized Gzip writer class with random access to indexed offsets.
39
40 Keyword Arguments:
41 file (string) : Filename for the resulting file
42 max_idx (int) : max number of indices which can be saved in
43 this file
44 max_idx_len (int) : maximal length of the index in bytes, must
45 be between 1 and 255
46 max_offset_len (int) : maximal length of the offset in bytes
47 output_path (str) : path to the output file
48
49 """
50
51 def __init__(
52 self,
53 file=None,
54 max_idx=10000,
55 max_idx_len=8,
56 max_offset_len=8,
57 output_path="./test.dat.igzip",
58 comp_str=-1,
59 ):
60 self.Lock = False
61 self._format_version = 1 # max 255!!!
62 self.file_name = output_path
63 self.max_idx_num = max_idx
64 self.max_idx_len = max_idx_len
65 self.max_offset_len = max_offset_len
66 self.generic_header = OrderedDict(
67 [
68 ("MAGIC_BYTE_1", b"\x1f"),
69 ("MAGIC_BYTE_2", b"\x8b"),
70 ("COMPRESSION", b"\x08"),
71 ("FLAGS", b"\x00"),
72 ("DATE", b"\x00\x00\x00\x00"),
73 ("XFL", b"\x02"),
74 ("OS", b"\x03"),
75 ]
76 )
77 self.index = OrderedDict()
78 self.first_header_set = False
79 self._file_out = None
80 self._encoding = "latin-1"
81 # magic bytes. FU+version
82 self.index_magic_bytes = b"FU" + struct.pack("<B", self._format_version)
83 self.crc32 = 0
84 self.isize = 0
85 self.comp_str = comp_str
86
87 def __del__(self):
88 """
89 Close the file object properly after this object is deleted
90 """
91 self.file_out.close()
92
93 def close(self):
94 """
95 Close the internal file object.
96 """
97 self.file_out.close()
98
99 @property
100 def file_out(self):
101 """
102 Output filehandler
103 """
104 if self._file_out is None:
105 self._file_out = open(self.file_name, "wb")
106 return self._file_out
107
108 @property
109 def encoding(self):
110 """
111 Returns the encoding used for this file
112 """
113 return self._encoding
114
115 @encoding.setter
116 def encoding(self, encoding):
117 """
118 Set the file encoding for the output file.
119 """
120 assert type(encoding) == str, "encoding must be a string"
121 self._encoding = encoding
122
123 def _write_gen_header(self, Index=False, FLAGS=None):
124 """
125 Write a valid gzip header with creation time, user defined flag fields
126 and allocated index.
127
128 Keyword Arguments:
129 Index (bool) : whether to or not to write an
130 index into this header.
131 FLAGS (list, optional) : list of flags (FTEXT, FHCRC, FEXTRA,
132 FNAME) to set for this header.
133
134 Returns:
135 offset (int): byte offset of the file pointer
136 """
137 if FLAGS is None:
138 FLAGS = []
139 FTEXT, FHCRC, FEXTRA, FNAME = 1, 2, 4, 8 # extra field bit flags
140 current_time = int(time.time())
141 time_byte = struct.pack("<L", current_time)
142 self.generic_header["DATE"] = time_byte
143 if Index:
144 self.generic_header["FLAGS"] = b"\x10"
145 if FLAGS is not None:
146 if "FTEXT" in FLAGS:
147 self.generic_header["FLAGS"] = self.generic_header["FLAGS"] & FTEXT
148
149 if "FHCRC" in FLAGS:
150 header_crc32 = 0
151 self.generic_header["FLAGS"] = self.generic_header["FLAGS"] & FHCRC
152 for byte in self.generic_header.values():
153 header_crc32 = zlib.crc32(byte, header_crc32)
154
155 if "FEXTRA" in FLAGS:
156 self.generic_header["FLAGS"] = self.generic_header["FLAGS"] & FEXTRA
157
158 if "FNAME" in FLAGS:
159 self.generic_header["FLAGS"] = self.generic_header["FLAGS"] & FNAME
160
161 for value in self.generic_header.values():
162 self.file_out.write(value)
163 if "FEXTRA" in FLAGS:
164 # WRITE EXTRA FIELD
165 pass
166
167 if "FNAME" in FLAGS:
168 # WRITE FNAME FIELD
169 fName = self.file_name.split("/")[-1]
170
171 if Index:
172 self.generic_header["FLAGS"] = b"\x00"
173 self.file_out.write(self.index_magic_bytes)
174 self.file_out.write(struct.pack("<B", self.max_idx_len))
175 self.file_out.write(struct.pack("<B", self.max_offset_len))
176 self.index_offset = self.file_out.tell()
177 self._allocate_index_bytes()
178
179 if "FHCRC" in FLAGS:
180 # WRITE checksum for header
181 pass
182
183 return self.file_out.tell()
184
185 def _allocate_index_bytes(self):
186 """
187 Allocate 'self.max_index_num' bytes of length 'self.max_idx_len'
188 in the header for inserting the index later on.
189 """
190 id_placeholder = self.max_idx_len * b"\x01"
191 offset_placeholder = self.max_offset_len * b"\x01"
192 for i in range(self.max_idx_num):
193 self.file_out.write(id_placeholder)
194 self.file_out.write(offset_placeholder)
195 self.file_out.write(b"\x00")
196 return
197
198 def _write_data(self, data):
199 """
200 Write data into file-stream.
201
202 Arguments:
203 data (str): uncompressed data
204 """
205 Compressor = zlib.compressobj(
206 self.comp_str, zlib.DEFLATED, -zlib.MAX_WBITS, zlib.DEF_MEM_LEVEL, 0
207 )
208 # compress data and flush (includes writing crc32 and isize)
209 if isinstance(data, bytes) is False:
210 data = bytes(data, "latin-1")
211 self.crc32 = zlib.crc32(data)
212 self.isize = len(data) % 2**32
213 comp_data = Compressor.compress(data) + Compressor.flush()
214 self.file_out.write(comp_data)
215 self.file_out.write(struct.pack("<L", self.crc32))
216 self.file_out.write(struct.pack("<L", self.isize))
217 return
218
219 def add_data(self, data, identifier):
220 """
221 Create a new gzip member with compressed 'data' indexed with 'index'.
222
223 Arguments:
224 data (str) : uncompressed data to write to file
225 index (str or int) : unique index for the data
226 """
227 if self.Lock is False:
228 if len(self.index) + 1 > self.max_idx_num:
229 print(
230 """
231 WARNING: Reached maximum number of indexed data blocks
232 '({0}), cannot add any more data!
233 """.format(
234 self.max_idx_num
235 )
236 )
237 return False
238
239 if not self.first_header_set:
240 self._write_gen_header(Index=True)
241 self.first_header_set = True
242 else:
243 # do we need this?
244 self._write_gen_header(Index=False)
245
246 self.index[identifier] = self.file_out.tell()
247 self._write_data(data)
248 return
249 else:
250 raise Exception("Cant add any more data if index is already written")
251
252 def _write_identifier(self, identifier):
253 """
254 Convert and write the identifier into output file.
255
256 Arguments:
257 identifier (str or int): identifier to write into index
258 """
259 id_format = "{0:\xAC>" + str(self.max_idx_len) + "}"
260 identifier = str(identifier)
261 identifier = id_format.format(identifier).encode("latin-1")
262 self.file_out.write(identifier)
263 return
264
265 def _write_offset(self, offset):
266 """
267 Convert and write offset to output file.
268
269 Arguments:
270 offset (int): offset which will be formatted and written
271 into file index
272 """
273 offset_format = "{0:\xAC>" + str(self.max_offset_len) + "}"
274 offset = str(offset)
275 offset = offset_format.format(offset).encode("latin-1")
276 self.file_out.write(offset)
277 return
278
279 def write_index(self):
280 """
281 Only called after all the data is written, i.e. all calls to
282 :func:`~GSGW.add_data` have been done.
283
284 Seek back to the beginning of the file and write the index into the
285 allocated comment bytes (see _write_gen_header(Index=True)).
286 """
287 self.Lock = True
288 self.file_out.seek(self.index_offset)
289 for identifier, offset in self.index.items():
290 self._write_identifier(identifier)
291 self._write_offset(offset)
292
293 def __enter__(self):
294 """
295 Enable the with syntax for this class (entry point).
296 """
297 return self
298
299 def __exit__(self, exc_type, exc_value, traceback):
300 """Destructor when using this class with 'with .. as'."""
301 self.file_out.close()
302
303
304 if __name__ == "__main__":
305 print(__doc__)