-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph
executable file
·247 lines (212 loc) · 7.87 KB
/
graph
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
#!/usr/bin/env python
# coding: utf-8
# GY190923
''' graph: basic plotting in the terminal '''
from argparse import ArgumentParser, FileType, SUPPRESS
from bisect import bisect_left
from collections import defaultdict as dd
from math import floor, log10
import platform
from signal import signal, SIGPIPE, SIG_DFL
import struct
from sys import stdin
signal(SIGPIPE, SIG_DFL) # Gracefully handle downstream PIPE closure
# Functions ###################################################################
def charlookup(i, j):
''' Return character representing i/j '''
if i <= 0:
return ' '
if i / j <= 0.25:
return '░'
if i / j <= 0.5:
return '▒'
if i / j <= 0.75:
return '▓'
return '█'
def round_to(x, n):
''' Round `x` to `n` significant figures '''
if not x:
return 0
power = -int(floor(log10(abs(x)))) + (n - 1)
factor = (10 ** power)
return round(x * factor) / factor
def get_terminal_size():
''' Return the width and height of the current unix terminal
Adapted from https://gist.github.com/jtriley/1108174 '''
def _linux():
def ioctl_GWINSZ(fd):
try:
import fcntl
import termios
return struct.unpack('hh',
fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
except:
return None
cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
if not cr:
try:
import os
fd = os.open(os.ctermid(), os.O_RDONLY)
cr = ioctl_GWINSZ(fd)
os.close(fd)
except:
pass
if not cr:
try:
cr = (os.environ['LINES'], os.environ['COLUMNS'])
except:
return None
return int(cr[1]), int(cr[0])
def _windows():
try:
from ctypes import windll, create_string_buffer
h = windll.kernel32.GetStdHandle(-12) # -12 == stderr
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
if res:
(bufx, bufy, curx, cury, wattr,
left, top, right, bottom,
maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
sizex = right - left + 1
sizey = bottom - top + 1
return sizex, sizey
except:
return None
def _tput():
try:
import subprocess
import shlex
cols = int(subprocess.check_call(shlex.split('tput cols')))
rows = int(subprocess.check_call(shlex.split('tput lines')))
return cols, rows
except:
return None
if platform.system() == 'Windows':
area = _windows()
if area is None:
area = _tput()
elif platform.system() in ['Linux', 'Darwin'] \
or platform.system().startswith('CYGWIN'):
area = _linux()
if area:
return area
return 80, 20 # default value
def plot(x_vals, y_vals):
''' ASCII-art plotting '''
n_cols, n_rows = get_terminal_size()
n_cols -= 8 # {0:5.3g} number formatting with 1 trailing space
n_rows -= 2 # single line to display x axis values
x_min, x_max = args.xmin, x_vals[-1]
x_bin_width = (x_max - x_min) / n_cols
x_bins = [x_min + i * x_bin_width for i in range(1, n_cols + 2)]
if 'xy' not in args:
cols = [0 for i in x_bins]
for x, y in zip(x_vals, y_vals):
cols[bisect_left(x_bins, x)] += y
cols = cols[:-1]
y_min, y_max = args.ymin, max(cols)
y_bin_width = (y_max - y_min) / n_rows
y_bins = [y_min + i * y_bin_width for i in range(1, n_rows + 2)]
for i, y_val in enumerate(cols):
chars = [' ' for _ in y_bins]
if y_val:
chars[bisect_left(y_bins, y_val)] = '█'
cols[i] = chars[:-1][::-1]
else:
cols = [[] for i in range(len(x_bins))]
for x, y in zip(x_vals, y_vals):
cols[bisect_left(x_bins, x)].append(y)
cols = cols[:-1]
y_min, y_max = args.ymin, max(max(c) if c else 0 for c in cols)
y_bin_width = (y_max - y_min) / n_rows
y_bins = [y_min + i * y_bin_width for i in range(1, n_rows + 2)]
for i, y_vals in enumerate(cols):
chars = [0 for _ in y_bins]
for y_val in y_vals:
chars[bisect_left(y_bins, y_val)] += 1
chars = chars[:-1]
chars = [charlookup(float(c), sum(chars)) for c in chars]
cols[i] = chars[::-1]
for i, y_bin in enumerate(y_bins[-2::-1]):
y_bin -= y_bin_width
print('{0:7.3g}'.format(round_to(y_bin, 2)),
''.join(col[i] for col in cols))
x_axis_labs = [x_bin - x_bin_width for x_bin in x_bins[:-2:10]]
lab_string = ''
for lab in x_axis_labs:
if len(lab_string) + 10 <= n_cols:
lab_string += '{0:<10.3g}'.format(round_to(lab, 3))
print(' '*8 + lab_string)
###############################################################################
if __name__ == "__main__":
parser = ArgumentParser(
description='Basic plotting in the terminal',
argument_default=SUPPRESS)
parser.add_argument(
'input', nargs='*', type=FileType('r'), default=[stdin],
help='Input file(s) (use "-" or leave blank for stdin)')
parser.add_argument(
'--xy', nargs='?', type=str, const="1,2",
help='Form a scatterplot using these (comma-separated) columns \
(default "%(const)s" when supplied alone)')
parser.add_argument(
'--col', type=int, default=1,
help='Form a histogram with column `col` (default %(default)s)')
parser.add_argument(
'--delim', type=str, default="\t",
help='Column delimiter (default TAB)')
parser.add_argument(
'--perc', action="store_true",
help='Express histogram y values as percentages')
parser.add_argument(
'--header', nargs='?', type=int, const=1,
help='Skip `header` rows in each file (default %(const)s when \
supplied alone)')
parser.add_argument(
'--xmin', type=float, default=0.0,
help='X axis lower limit (x > `xmin`) (default %(default)s)')
parser.add_argument(
'--xmax', type=float, default=float('inf'),
help='X axis upper limit, above which values are discarded \
(default %(default)s)')
parser.add_argument(
'--ymin', type=float, default=0.0,
help='Y axis lower limit (y > `ymin`) (default %(default)s)')
parser.add_argument(
'--ymax', type=float, default=float('inf'),
help='Y axis upper limit, above which values are discarded \
(default %(default)s)')
args = parser.parse_args()
if 'xy' in args:
data = []
xcol, ycol = eval(args.xy)
xcol, ycol = xcol - 1, ycol - 1
else:
data = dd(int)
args.col = args.col - 1
for f in args.input:
for i in range(args.header if 'header' in args else 0):
f.readline()
for l in f:
l = l.rstrip('\r\n')
if not l:
continue
l = l.split(args.delim)
try:
if 'xy' in args:
x, y = float(l[xcol]), float(l[ycol])
if args.xmin < x <= args.xmax and \
args.ymin < y <= args.ymax:
data.append((x, y))
else:
x = float(l[args.col])
if args.xmin < x <= args.xmax:
data[x] += 1
except ValueError:
pass
if 'xy' not in args:
data = data.items()
if 'perc' in args:
y_sum = sum(y for x, y in data)
data = [(x, float(y) / y_sum * 100) for x, y in data]
plot(*zip(*sorted(data)))