Last active
December 28, 2015 11:49
-
-
Save mogproject/7496075 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
""" | |
print_histo.py | |
Visualize histogram as text. | |
""" | |
import sys | |
import numpy | |
import exceptions | |
class State(object): | |
def __init__(self, limit=100000, bar_width=48): | |
self.limit = limit | |
self.bar_width = bar_width | |
self.count = 0 | |
self.xs = [] | |
def parse(self, s): | |
if self.limit <= self.count: | |
raise RuntimeError("Number of data is reached to limit: %d" % self.limit) | |
try: | |
self.xs.append(float(s)) | |
self.count += 1 | |
except exceptions.ValueError: | |
# Ignore input. | |
pass | |
def __str__(self): | |
freqs, bins = numpy.histogram(self.xs) | |
# Functions for string | |
justify = lambda ss, func: [func(s)(max(map(len, ss))) for s in ss] | |
rjust = lambda ss: justify(ss, lambda s: s.rjust) | |
ljust = lambda ss: justify(ss, lambda s: s.ljust) | |
# Labels | |
bs = rjust(['%.3f' % b for b in bins]) | |
labels = ['[%s, %s)' % x for x in zip(bs[:-1], bs[1:])] | |
labels[-1] = labels[-1][:-1] + ']' | |
# Frequency | |
f = lambda x: 0 if x == 0 else max(1, x * self.bar_width / max(freqs)) | |
bars = ljust(['*' * f(freq) for freq in freqs]) | |
# Assembles them. | |
buf = ('%s: %s %6d' % x for x in zip(labels, bars, freqs)) | |
return '\n'.join(buf) | |
def process(function): | |
paths = (sys.argv + [None])[1:max(2, len(sys.argv))] | |
for path in paths: | |
try: | |
fp = sys.stdin if path is None else open(path) | |
for line in fp: | |
function(line.rstrip("\n")) | |
except (KeyboardInterrupt, EOFError): | |
pass | |
except Exception: | |
exc_type, exc = sys.exc_info()[:2] | |
print('%s: %s: %s' % (sys.argv[0], exc_type.__name__, exc)) | |
return | |
if __name__ == '__main__': | |
s = State() | |
process(s.parse) | |
print(s) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment