-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhuffman_coding.py
235 lines (159 loc) · 4.99 KB
/
huffman_coding.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
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import random
# In[2]:
def xor(actual, random, j):
result = ''
n=len(actual)
k=0
for i in range(j,n+j):
if actual[k] == random[i]:
result += "0"
else:
result += "1"
k=k+1
return result
# In[3]:
def random_pattern(k, n):
output = 0
for d in random.sample(range(n), k):
output += (1 << d)
temp = bin(output)[2:]
if len(temp) < n:
temp = temp[::-1]
temp1 = temp + '0' * (n - len(temp))
temp1 = temp1[::-1]
return temp1
else:
return temp
# In[4]:
class Nodes:
def __init__(self, probability, symbol, left = None, right = None):
# probability of the symbol
self.probability = probability
# the symbol
self.symbol = symbol
# the left node
self.left = left
# the right node
self.right = right
# the tree direction (0 or 1)
self.code = ''
# In[5]:
def CalculateProbability(the_data):
the_symbols = dict()
for item in the_data:
if the_symbols.get(item) == None:
the_symbols[item] = 1
else:
the_symbols[item] += 1
return the_symbols
the_codes = dict()
def CalculateCodes(node, value = ''):
# a huffman code for current node
newValue = value + str(node.code)
if(node.left):
CalculateCodes(node.left, newValue)
if(node.right):
CalculateCodes(node.right, newValue)
if(not node.left and not node.right):
the_codes[node.symbol] = newValue
return the_codes
def OutputEncoded(the_data, coding):
encodingOutput = []
for element in the_data:
encodingOutput.append(coding[element])
the_string = ''.join([str(item) for item in encodingOutput])
return the_string
# In[6]:
def HuffmanEncoding(the_data):
symbolWithProbs = CalculateProbability(the_data)
the_symbols = symbolWithProbs.keys()
the_probabilities = symbolWithProbs.values()
the_nodes = []
# converting symbols and probabilities into huffman tree nodes
for symbol in the_symbols:
the_nodes.append(Nodes(symbolWithProbs.get(symbol), symbol))
while len(the_nodes) > 1:
the_nodes = sorted(the_nodes, key = lambda x: x.probability)
right = the_nodes[0]
left = the_nodes[1]
left.code = 0
right.code = 1
newNode = Nodes(left.probability + right.probability, left.symbol + right.symbol, left, right)
the_nodes.remove(left)
the_nodes.remove(right)
the_nodes.append(newNode)
huffmanEncoding = CalculateCodes(the_nodes[0])
encoded_output = OutputEncoded(the_data,huffmanEncoding)
return encoded_output, the_nodes[0]
# In[7]:
def HuffmanDecoding(encodedData, huffmanTree):
treeHead = huffmanTree
decodedOutput = []
for x in encodedData:
if x == '1':
huffmanTree = huffmanTree.right
elif x == '0':
huffmanTree = huffmanTree.left
try:
if huffmanTree.left.symbol == None and huffmanTree.right.symbol == None:
pass
except AttributeError:
decodedOutput.append(huffmanTree.symbol)
huffmanTree = treeHead
string = "".join(decodedOutput)
return string
# In[8]:
def binarytoascii(str2):
message = ""
while str2 != "":
i = chr(int(str2[:8], 2))
message = message + i
str2 = str2[8:]
return message
# In[9]:
f = open("text_pattern.txt")
original = f.read()
x = ''.join(format(ord(i), '08b') for i in original)
# In[10]:
test_str = x
chnk_len = 24
res = [test_str[idx : idx + chnk_len] for idx in range(0, len(test_str), chnk_len)]
# In[11]:
# encode the data
encoded_chunks=[]
tree_chunks=[]
M=0
for value in res:
encoding, the_tree = HuffmanEncoding(value)
encoded_chunks.append(encoding)
tree_chunks.append(the_tree)
M = M+len(encoding)
# In[12]:
print("Space used in bits before compression:", len(x))
print("Space used in bits after compression:", M)
# In[13]:
dist = [0,10,100,200,500,5000]
print("Original text")
print(original)
print()
for d in dist:
print('d = ', d)
# generate random binary string of length M' : CHANNEL ERROR
M_error = random_pattern(d, M)
# print('random ', rand)
j=0
d_temp=[]
for i in range(0,len(encoded_chunks)):
# take xor of text file and random string : RECEIVED MESSAGE
y = xor(encoded_chunks[i], M_error, j)
j=j+len(encoded_chunks[i])
# print('received ', y)
decoded_str = HuffmanDecoding(y, tree_chunks[i])
d_temp.append(decoded_str)
decoded="".join(d_temp)
final=binarytoascii(decoded)
print(final)
print()