-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLempel_Ziv_Welch.py
455 lines (355 loc) · 17.7 KB
/
Lempel_Ziv_Welch.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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 17 21:06:56 2017
@author: Isik
"""
import Reader_Writer as RW
from enum import Enum
CONST_CHUNK_SIZE = 1024
CONST_NUM_BITS_ASCII = 8
class lzw(RW.Reader_Writer):
""" Lempel-Ziv-Welch compression & decompression.
Properties:
FileFormat:
An enumerator detailing various file formats. Currently supported:
ASCII: ASCII formatted text
strbin: ASCII formatted binary
file_format: A string that is used to index the enumerator
FileFormat.
LZWDictionary: A dictionary of values and indices used to keep track
of the patterns found during a run of LZW compression
or decompression.
pattern: The current pattern being matched against the
LZWDictionary keys.
incr_mem_ele: A count of the number of input elements being held
in memory. Used for decoding.
next_file_obj: A variable that holds the next object after a found
decode pattern. Used for decoding.
w: Minimum number of bits required to represent
largest LZW index.
"""
class FileFormat(Enum):
ASCII = 1
strbin = 2
def __init__(self, FileFormat = "ASCII"):
""" Default constructor, sets self.file_format """
self.file_format = FileFormat
self.LZWDictionary = dict()
self.pattern = None
LZWDictionaryLength = len(self.LZWDictionary)
self.w = self.calculate_w( LZWDictionaryLength )
self.incr_mem_ele = 0
self.next_file_obj = ""
self.num_bits_file_obj = self.get_num_bits_file_obj()
def compress(self,
InputFileName = "DEFAULT.txt",
OutputFileName = "DEFAULT.txt",
):
""" Compresses an input file using lzw and outputs to another file.
Arguments:
InputFileName: The name of the file to be compressed
OutputFileName: The name of the compressed file
"""
self.LZWDictionary = self.default_compression_LZWDictionary()
self.pattern = self.default_pattern()
LZWDictionaryLength = len(self.LZWDictionary)
self.w = self.calculate_w( LZWDictionaryLength )
RF = self.set_ReadFormat()
self.open_files(InputFileName, OutputFileName,
ReadFormat = RF)
OutputBuffer = ""
InputBuffer = self.set_InputBuffer()
while True:
PeekBuffer = self.set_InputBuffer()
#End Condition: If we read in the empty string, we're done'
if PeekBuffer == "":
Output = self.lzw_encode(InputBuffer, OutputBuffer,
EOF = True)
self.ofs.write(Output)
break
Output = self.lzw_encode(InputBuffer, OutputBuffer)
self.ofs.write(Output)
InputBuffer = PeekBuffer
self.close_files()
def lzw_encode(self, InputBuffer, OutputBuffer, EOF = False ):
""" The MEAT of the Lempel-Ziv-Welch compression schema.
LZWDictionary uses LZW Patterns as keys and their index as values.
w keeps track of the necessary length of the key as it gets encoded.
Arguments:
InputBuffer: A chunk of data read from the input file.
OutputBuffer: A chunk of lzw encoded data.
EOF: Signals if this is the last chunk of data.
Return:
OutputBuffer: An chunk of lzw encoded data.
"""
for element in InputBuffer:
LastPattern = self.pattern
self.add_element_to_pattern( element )
# If we see a new pattern
if self.pattern not in self.LZWDictionary.keys():
LenLZWDictionary = len(self.LZWDictionary)
LZWIndex = '{:b}'.format(LenLZWDictionary)
self.LZWDictionary[self.pattern] = LZWIndex
LastIndex = self.LZWDictionary[LastPattern]
OutputBuffer = self.append_encode_OutputBuffer(OutputBuffer,
LastIndex,
element
)
LenLZWDictionary = len(self.LZWDictionary)
self.w = self.calculate_w( LenLZWDictionary )
#Reset the pattern
self.pattern = self.default_pattern()
# Our last encoding, if there is a message to encode.
if EOF and (self.pattern != self.default_pattern()):
Index = self.LZWDictionary[self.pattern]
OutputBuffer = self.append_encode_OutputBuffer(OutputBuffer,
Index,
""
)
return OutputBuffer
def decompress(self,
InputFileName = "DEFAULT.txt",
OutputFileName = "DEFAULT.txt",
):
""" Decompresses an input file using lzw and outputs to another file.
Arguments:
InputFileName: The name of the file to be decompressed
OutputFileName: The name of the decompressed file
"""
""" CURRENTLY UNUSED, HERE FOR FUTURE EXPANSION
-----------------------------------------------------------------------
if self.FileFormat[FileFormat] == self.FileFormat["binary"]:
BITS_IN_CHUNK = CONST_CHUNK_SIZE * CONST_NUM_BITS_ASCII
DefaultByteArray = bytearray(BITS_IN_CHUNK)
-----------------------------------------------------------------------
"""
self.LZWDictionary = self.default_decompression_LZWDictionary()
self.pattern = self.default_pattern()
LZWDictionaryLength = len(self.LZWDictionary)
self.w = self.calculate_w( LZWDictionaryLength )
self.incr_mem_ele = 0
self.next_file_obj = ""
RF = self.set_ReadFormat()
self.open_files(InputFileName, OutputFileName, ReadFormat = RF)
OutputBuffer = ""
InputBuffer = self.set_InputBuffer()
while True:
PeekBuffer = self.set_InputBuffer()
#End Condition: If we read in the empty string, we're done
if PeekBuffer == "":
Output = self.lzw_decode(InputBuffer, OutputBuffer,
EOF = True)
self.ofs.write(Output)
break
Output = self.lzw_decode(InputBuffer, OutputBuffer)
self.ofs.write(Output)
InputBuffer = PeekBuffer
self.close_files()
def lzw_decode(self, InputBuffer, OutputBuffer,
EOF = False ):
""" The MEAT of the Lempel-Ziv-Welch decompression schema.
LZWDictionary uses binary indices as keys and their interpreted
encodings as values. w keeps track of the necessary length of the key
as it gets encoded so that the correct number of bits can be read in.
Arguments:
InputBuffer:
A chunk of data read from the input file.
OutputBuffer:
A chunk of lzw decoded data.
EOF:
Signals if this is the last chunk of data.
Return:
OutputBuffer:
An chunk of lzw decoded data.
"""
for element in InputBuffer:
#Get w characters to find what the index is
if self.incr_mem_ele < self.w:
#To preserve key patterning
if not (len(self.pattern) == 0 and element == '0'):
self.add_element_to_pattern( element )
self.incr_mem_ele += 1
elif self.incr_mem_ele < \
(self.w + self.get_num_bits_file_obj()):
self.next_file_obj = ''.join([self.next_file_obj, element])
self.incr_mem_ele += 1
#Once we have w characters, we're good.
else:
#Handle the degenerate case of all zeros key
if self.pattern == '':
self.pattern = '0'
self.convert_next_file_obj()
LenLZWDictionary = len(self.LZWDictionary)
LZWIndex = '{:b}'.format(LenLZWDictionary)
DictValue = self.LZWDictionary[self.pattern]
NewDictValue = ''.join([DictValue, self.next_file_obj])
self.LZWDictionary[LZWIndex] = NewDictValue
LastIndex = self.LZWDictionary[self.pattern]
OutputBuffer = self.append_decode_OutputBuffer(OutputBuffer,
LastIndex)
LenLZWDictionary = len(self.LZWDictionary)
self.w = self.calculate_w( LenLZWDictionary )
#Reset iteration values
self.pattern = self.default_pattern()
self.next_file_obj = ""
self.incr_mem_ele = 0
# Because we are in a for loop, we are still reading data
if not (len(self.pattern) == 0 and element == '0'):
self.add_element_to_pattern( element )
self.incr_mem_ele += 1
# Our last encoding, if there is a message to encode.
if EOF and (self.pattern != self.default_pattern()):
if self.pattern == '':
self.pattern = '0'
self.convert_next_file_obj()
Index = self.LZWDictionary[str(int(self.pattern))]
OutputBuffer = self.append_decode_OutputBuffer(OutputBuffer,
Index)
return OutputBuffer
def calculate_w(self, LEN_LZWDICTIONARY):
""" Sets the self value of w based on the length of the LZW dictionary.
Arguments:
LEN_LZWDICTIONARY: Self explanatory
Return:
w: Smallest number of bits needed to display the largest code.
"""
POWER_OF_TWO = 1
w = 1
while( POWER_OF_TWO * 2 < LEN_LZWDICTIONARY ):
POWER_OF_TWO *= 2
w += 1
return w
def set_ReadFormat(self):
""" Use FileFormat to determine how to read from the file
Return:
RF: The parameter needed for the Input File Stream to read the
data in the input file properly.
"""
if self.FileFormat[self.file_format] == self.FileFormat["ASCII"]:
RF = 'r'
elif self.FileFormat[self.file_format] == self.FileFormat["strbin"]:
RF = 'r'
return RF
def set_InputBuffer(self):
""" Use FileFormat to determine how to put data in InputBuffer
Return:
InputBuffer: A buffered chunk of data pulled from the input file.
"""
if self.FileFormat[self.file_format] == self.FileFormat["ASCII"]:
InputBuffer = self.ifs.read(CONST_CHUNK_SIZE)
elif self.FileFormat[self.file_format] == self.FileFormat["strbin"]:
InputBuffer = self.ifs.read(CONST_CHUNK_SIZE)
return InputBuffer
def default_compression_LZWDictionary(self):
""" Use FileFormat to determine how to initialize LZWDictionary
Return:
LZWDictionary: An initialized dictionary for LZW compression
"""
LZWDictionary = dict()
if self.FileFormat[self.file_format] == self.FileFormat["ASCII"]:
for ASCII_ORDINAL in range(0,128):
LZWIndex = '{:b}'.format(ASCII_ORDINAL)
LZWDictionary[chr(ASCII_ORDINAL)] = LZWIndex
elif self.FileFormat[self.file_format] == self.FileFormat["strbin"]:
LZWDictionary[""] = '0'
return LZWDictionary
def default_decompression_LZWDictionary(self):
""" Use FileFormat to determine how to initialize LZWDictionary
Return:
LZWDictionary: An initialized dictionary for LZW compression
"""
LZWDictionary = dict()
if self.FileFormat[self.file_format] == self.FileFormat["ASCII"]:
for ASCII_ORDINAL in range(0,128):
LZWIndex = '{:b}'.format(ASCII_ORDINAL)
LZWDictionary[LZWIndex] = chr(ASCII_ORDINAL)
elif self.FileFormat[self.file_format] == self.FileFormat["strbin"]:
LZWDictionary['0'] = ""
return LZWDictionary
def default_pattern(self):
""" Use FileFormat to determine how to initialize LZWDictionary
Return:
pattern: The initialized pattern
"""
if self.FileFormat[self.file_format] == self.FileFormat["ASCII"]:
pattern = ""
elif self.FileFormat[self.file_format] == self.FileFormat["strbin"]:
pattern = ""
return pattern
def add_element_to_pattern(self, element ):
""" Use FileFormat to determine how to add an element to the pattern
Arguments:
element: The element to be added to the pattern.
"""
if self.FileFormat[self.file_format] == self.FileFormat["ASCII"]:
self.pattern = ''.join([self.pattern, element])
elif self.FileFormat[self.file_format] == self.FileFormat["strbin"]:
self.pattern = ''.join([self.pattern, element])
def append_encode_OutputBuffer(self, OutputBuffer, Index, element,
NoPad = False):
""" Use FileFormat to determine how to add an element to the pattern
Arguments:
OutputBuffer: The current state of the output buffer
Index: The lzw value of the last recognized pattern.
Element: The new element to be appended to OutputBuffer
NoPad: Prevents padding
Return:
OutputBuffer:
The new state of the output buffer.
"""
if NoPad:
w = 0
else:
w = self.w
if self.FileFormat[self.file_format] == self.FileFormat["ASCII"]:
if element != "":
ASCII_ORDINAL = ord(element)
BINARY_ASCII = '{:b}'.format(ASCII_ORDINAL).zfill(7)
else:
BINARY_ASCII = ""
PADDED_INDEX = Index.zfill(w)
OutputBuffer = ''.join([OutputBuffer,
PADDED_INDEX,
BINARY_ASCII])
elif self.FileFormat[self.file_format] == self.FileFormat["strbin"]:
PADDED_INDEX = Index.zfill(w)
OutputBuffer = ''.join([OutputBuffer, PADDED_INDEX, element])
return OutputBuffer
def append_decode_OutputBuffer(self, OutputBuffer, Index):
""" Use FileFormat to determine how to add an element to the pattern
Arguments:
OutputBuffer: The current state of the output buffer
Index: The lzw value of the last recognized pattern.
Return:
OutputBuffer:
The new state of the output buffer.
"""
element = self.next_file_obj
if self.FileFormat[self.file_format] == self.FileFormat["ASCII"]:
OutputBuffer = ''.join([OutputBuffer,
Index,
element])
elif self.FileFormat[self.file_format] == self.FileFormat["strbin"]:
OutputBuffer = ''.join([OutputBuffer, Index, element])
return OutputBuffer
def get_num_bits_file_obj(self):
""" Use FileFormat to determine how many bits in a file object
Bits, char, etc.
"""
if self.FileFormat[self.file_format] == self.FileFormat["ASCII"]:
return CONST_NUM_BITS_ASCII - 1
elif self.FileFormat[self.file_format] == self.FileFormat["strbin"]:
return 1
def convert_next_file_obj(self):
""" Convert the binary file object to the character it represents.
Main function: With strbin, 7 binary characters will be read and
converted to a character.
"""
if self.FileFormat[self.file_format] == self.FileFormat["ASCII"]:
if self.next_file_obj != '':
self.next_file_obj = self.next_file_obj.lstrip('0')
if self.next_file_obj == '':
self.next_file_obj = '0'
self.next_file_obj = self.LZWDictionary[self.next_file_obj]
elif self.FileFormat[self.file_format] == self.FileFormat["strbin"]:
pass