-
Notifications
You must be signed in to change notification settings - Fork 53
/
lzw.py
332 lines (277 loc) · 7.78 KB
/
lzw.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
""" Encoder and decoder of Lempel-Ziv-Welch algorithm for TIFF.
This module is obsolete, use tif_lzw extension module instead.
"""
# Author: Pearu Peterson
# Created: May 2010
import numpy
default_backend = 'bittools'
# default_backend='bittools'
if default_backend == 'bitarray':
from bitarray import bitarray
if default_backend == 'bittools':
from bittools import setword, getword
CODECLEAR = 256
CODEEOI = 257
CODESTART = 258
def encode_bitarray(seq, max_bits=12):
""" Compress sequence using Lempel-Ziv-Welch algorithm for TIFF.
Parameters
----------
seq : {str, numpy.ndarray}
max_bits : int
Specify maximum bits for encoding table.
Returns
-------
bseq : bitarray
See also
--------
decode_bitarray
"""
if isinstance(seq, numpy.ndarray):
seq = seq.tostring()
r = bitarray(0, endian='little')
write = r.fromword
init_table = [(chr(code), code) for code in range(256)]
table = {}
table_get = table.get
table_clear = table.clear
table_update = table.update
sup_code2 = (1 << max_bits) - 2
next_code = CODESTART
bits = 9
max_code = (1 << bits)
s = ''
table_update(init_table)
write(CODECLEAR, bits)
for c in seq:
s1 = s + c
if s1 in table:
s = s1
else:
write(table_get(s), bits)
table[s1] = next_code
next_code += 1
s = c
if next_code == sup_code2:
write(table_get(s), bits)
write(CODECLEAR, bits)
s = ''
table_clear()
table_update(init_table)
next_code = CODESTART
bits = 9
max_code = (1 << bits)
elif next_code == max_code:
bits += 1
max_code = (1 << bits)
if s:
write(table_get(s), bits)
write(CODEEOI, bits)
return r
def encode_bittools(seq, max_bits=12):
""" Compress sequence using Lempel-Ziv-Welch algorithm for TIFF.
Parameters
----------
seq : {str, numpy.ndarray}
max_bits : int
Specify maximum bits for encoding table.
Returns
-------
bseq : numpy.ndarray
See also
--------
decode_bittools
"""
if isinstance(seq, numpy.ndarray):
nbytes = seq.nbytes*2
seq = seq.tostring()
else:
nbytes = len(seq)*2
r = numpy.zeros((nbytes,), dtype=numpy.ubyte)
init_table = [(chr(code), code) for code in range(256)]
table = {}
table_get = table.get
table_clear = table.clear
table_update = table.update
sup_code2 = (1 << max_bits) - 2
next_code = CODESTART
bits = 9
max_code = (1 << bits)
s = ''
table_update(init_table)
index = setword(r, 0, bits, CODECLEAR, 1)
for c in seq:
s1 = s + c
if s1 in table:
s = s1
else:
index = setword(r, index, bits, table_get(s), 1)
table[s1] = next_code
next_code += 1
s = c
if next_code == sup_code2:
index = setword(r, index, bits, table_get(s), 1)
index = setword(r, index, bits, CODECLEAR, 1)
s = ''
table_clear()
table_update(init_table)
next_code = CODESTART
bits = 9
max_code = (1 << bits)
elif next_code == max_code:
bits += 1
max_code = (1 << bits)
if s:
index = setword(r, index, bits, table_get(s), 1)
index = setword(r, index, bits, CODEEOI)
bytes = index // 8
if 8*bytes < index:
bytes += 1
return r[:bytes]
def decode_bitarray(bseq):
""" Decompress Lempel-Ziv-Welch encoded sequence.
Parameters
----------
bseq : {bitarray, numpy.ndarray}
Returns
-------
seq : str
See also
--------
encode_bitarray
"""
if isinstance(bseq, numpy.ndarray):
bseq = bitarray(bseq, endian='little')
assert bseq.endian() == 'little', repr(bseq.endian())
read = bseq.toword
table = [chr(code) for code in range(256)] + ['CODECLEAR', 'CODEEOI']
table_append = table.append
table_len = table.__len__
bits = 9
max_code2 = (1 << bits) - 2
i = 0
seq = []
seq_append = seq.append
while True:
code = read(i, bits)
i += bits
if code == CODEEOI:
break
elif code == CODECLEAR:
del table[CODESTART:]
bits = 9
max_code2 = (1 << bits) - 2
code = read(i, bits)
i += bits
old_str = table[code]
seq_append(old_str)
else:
ln = table_len()
if code < ln:
s = table[code]
table_append(old_str + s[0])
old_str = s
else:
old_str = old_str + old_str[0]
table_append(old_str)
seq_append(old_str)
if ln == max_code2:
bits += 1
max_code2 = (1 << bits) - 2
return ''.join(seq)
def decode_bittools(bseq):
""" Decompress Lempel-Ziv-Welch encoded sequence.
Parameters
----------
bseq : numpy.ndarray
Returns
-------
seq : str
See also
--------
encode_bittools
"""
table = [chr(code) for code in range(256)] + ['CODECLEAR', 'CODEEOI']
table_append = table.append
table_len = table.__len__
bits = 9
max_code2 = (1 << bits) - 2
i = 0
seq = []
seq_append = seq.append
while True:
code, i = getword(bseq, i, bits)
if code == CODEEOI:
break
elif code == CODECLEAR:
del table[CODESTART:]
bits = 9
max_code2 = (1 << bits) - 2
code, i = getword(bseq, i, bits)
old_str = table[code]
seq_append(old_str)
else:
ln = table_len()
if code < ln:
s = table[code]
table_append(old_str + s[0])
old_str = s
else:
old_str = old_str + old_str[0]
table_append(old_str)
seq_append(old_str)
if ln == max_code2:
bits += 1
max_code2 = (1 << bits) - 2
return ''.join(seq)
# print 'backend:', default_backend
if default_backend == 'bitarray':
encode = encode_bitarray
decode = decode_bitarray
def encode_array(arr):
return encode_bitarray(arr).toarray()
if default_backend == 'bittools':
encode = encode_array = encode_bittools # noqa: F811
decode = decode_bittools
def test_lzw():
for s in ['TOBEORNOTTOBEORTOBEORNOT', '/WED/WE/WEE/WEB/WET'][:0]:
r = encode(s)
a = decode(r)
assert a == s, repr((a, s))
if 1:
f = open(__file__)
s = f.read()
f.close()
r = encode(s)
a = decode(r)
assert a == s
print('ok')
import sys
import os
import time
for fn in sys.argv[1:]:
if not os.path.exists(fn):
continue
t0 = time.time()
f = open(fn, 'rb')
s = f.read()
f.close()
t = time.time()-t0
print('Reading %s took %.3f seconds, bytes = %s' % (fn, t, len(s)))
t0 = time.time()
r = encode(s)
t = time.time()-t0
sz = len(r)
if default_backend == 'bitarray':
sz //= 8
print('Encoding took %.3f seconds, compress ratio = %.3f,'
' Kbytes per second = %.3f'
% (t, len(s)/sz, len(s)/t/1024))
t0 = time.time()
s1 = decode(r)
t = time.time()-t0
print('Decoding took %.3f seconds, Kbytes per second = %.3f'
% (t, (sz/t)/1024))
assert s1 == s
if __name__ == '__main__':
test_lzw()