/
entropy_calc.py
executable file
·207 lines (170 loc) · 6.05 KB
/
entropy_calc.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
#!/usr/bin/env python
'''
SYNOPSIS
entropy_calc.py [--blocksize=N] [-h,--help] [-v,--verbose] [--version]
DESCRIPTION
This script calculates the Shannon entropy over data read from stdin.
Entropy is calculated for blocks of data. The entropy is printed for each
block. The default blocksize is 0. Setting the blocksize to 0 will read
the stream until end of file and calculate the entropy for the entire
dataset.
This docstring will be printed by the script if there is an error
or if the user requests help (-h or --help).
EXAMPLES
The following are some examples of how to use this script.
$ dd if=/dev/urandom bs=1024 count=10 | ./entropy_calc.py
10+0 records in
10+0 records out
10240 bytes (10 kB) copied, 0.00236719 s, 4.3 MB/s
7.97868699469
$ dd if=/dev/urandom bs=1024 count=10 | ./entropy_calc.py --blocksize=1024
10+0 records in
10+0 records out
10240 bytes (10 kB) copied, 0.00253304 s, 4.0 MB/s
7.78113154233
7.81023909332
7.82709308603
7.80825125827
7.81572421929
7.77518144269
7.83449952802
7.81081381332
7.81897457133
7.80212491335
EXIT STATUS
This exits with status 0 on success and 1 otherwise.
This exits with a status greater than 1 if there was an
unexpected run-time error.
AUTHOR
Noah Spurrier <noah@noah.org>
LICENSE
This license is approved by the OSI and FSF as GPL-compatible.
http://opensource.org/licenses/isc-license.txt
Copyright (c) 2014, Noah Spurrier
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
VERSION
Version 1
'''
__version__ = 'Version 1'
__date__ = 'date'
__author__ = 'Noah Spurrier <noah@noah.org>'
import sys
import os
import traceback
import optparse
import time
import logging
import math
import random
import fileinput
logging.basicConfig(format='%(asctime)s %(message)s')
logger = logging.getLogger(__name__)
if os.getenv('PYTHONLOGGING') in logging._levelNames:
logger.setLevel(logging._levelNames[os.getenv('PYTHONLOGGING')])
# Uncomment the following section if you want readline history support.
#import readline, atexit
#histfile = os.path.join(os.environ['HOME'], '.TODO_history')
#try:
# readline.read_history_file(histfile)
#except IOError:
# pass
#atexit.register(readline.write_history_file, histfile)
class entropy_calc:
def __init__(self):
self.block = []
def update(self, vv):
# FIXME raise exception if vv cannot be added to block array.
if not hasattr(vv, "__iter__"):
if type(vv) is type(''):
for cc in vv:
self.block.extend([cc])
else:
self.block.extend([vv])
def entropy_shannon(self):
histogram = {}
for vv in self.block:
if vv in histogram:
histogram[vv] += 1
else:
histogram[vv] = 1
length = float(len(self.block))
ee = 0.0
for count in histogram.values():
cl = float(count/length)
ee += cl * math.log(cl, 2)
# Add zero to eliminate negative zeros (an IEEE quirk).
return -ee + 0.0
def read_blocks(fin, blocksize=1024):
while True:
block = fin.read(blocksize)
if block:
yield block
else:
return
def main(options=None, args=None):
ee = entropy_calc()
if len(args) > 0:
for filename in args:
fin = open(filename)
if options.blocksize == 0:
ee.update(fin.read())
print ee.entropy_shannon()
else:
for bb in read_blocks(fin, options.blocksize):
ee.update(bb)
print ee.entropy_shannon()
fin.close()
else:
if options.blocksize == 0:
ee.update(sys.stdin.read())
print ee.entropy_shannon()
else:
for bb in read_blocks(sys.stdin, options.blocksize):
ee.update(bb)
print ee.entropy_shannon()
if __name__ == '__main__':
try:
start_time = time.time()
parser = optparse.OptionParser(
formatter=optparse.TitledHelpFormatter(),
usage=globals()['__doc__'],
version='1'
)
parser.add_option('--blocksize', type='int',
default=0, help='set blocksize (default 0)')
parser.add_option('-v', '--verbose', action='store_true',
default=False, help='verbose output')
(options, args) = parser.parse_args()
#if len(args) < 1:
# parser.error ('missing argument')
if options.verbose:
print(time.asctime())
exit_code = main(options, args)
if exit_code is None:
exit_code = 0
if options.verbose:
print(time.asctime())
print('TOTAL TIME IN MINUTES: %f' %
((time.time() - start_time) / 60.0))
sys.exit(exit_code)
except KeyboardInterrupt as e:
# The user pressed Ctrl-C.
raise e
except SystemExit as e:
# The script called sys.exit() somewhere.
raise e
except Exception as e:
print('ERROR: Unexpected Exception')
print(str(e))
traceback.print_exc()
os._exit(2)
# vim:set ft=python fileencoding=utf-8 sr et ts=4 sw=4 : See help 'modeline'