-
Notifications
You must be signed in to change notification settings - Fork 1
/
npytools.py
161 lines (133 loc) · 4.92 KB
/
npytools.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
# -*- coding: utf-8 -*-
"""Core functions."""
#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------
import atexit
import logging
import os
from pathlib import Path
import subprocess
import click
import numpy as np
np.set_printoptions(precision=4, suppress=True, edgeitems=2, threshold=50)
def _git_version():
"""Return the git version."""
curdir = os.getcwd()
os.chdir(str(Path(__file__).parent))
try:
with open(os.devnull, 'w') as fnull:
version = ('-git-' + subprocess.check_output(
['git', 'describe', '--abbrev=8', '--dirty', '--always', '--tags'],
stderr=fnull).strip().decode('ascii'))
return version
except (OSError, subprocess.CalledProcessError): # pragma: no cover
return ""
finally:
os.chdir(curdir)
__author__ = 'Cyrille Rossant'
__email__ = 'cyrille.rossant at gmail.com'
__version__ = '0.1.0'
__version_git__ = __version__ + _git_version()
# Set a null handler on the root logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.NullHandler())
logger.propagate = False
@atexit.register
def on_exit(): # pragma: no cover
# Close the logging handlers.
for handler in logger.handlers:
handler.close()
logger.removeHandler(handler)
#------------------------------------------------------------------------------
# Utils
#------------------------------------------------------------------------------
def _sizeof(num, suffix=''):
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if abs(num) < 1000.0:
return "%.1f%s%s" % (num, unit, suffix)
num /= 1000.0
return "%.1f%s%s" % (num, 'Y', suffix)
def _tabulate(table):
a = max(len(str(x)) for x, _ in table)
b = max(len(str(x)) for _, x in table)
header = '+%s+%s+' % ('-' * (a + 2), '-' * (b + 2))
table_str = [
('| {0: <' + str(a) + '} | {1: <' + str(b) + '} |').format(name, str(value))
for name, value in table]
table_str = [header] + table_str + [header]
return '\n'.join(table_str)
def _array_info_table(arr, show_stats=False):
size = arr.size
table = [
('shape', arr.shape),
('dtype', arr.dtype),
('filesize', _sizeof(arr.size * arr.itemsize)),
('size', size),
]
if show_stats:
zero = size - np.count_nonzero(arr)
nan = np.isnan(arr).sum()
nonnan = arr[~np.isnan(arr)]
table += [
('min', '%.3e' % nonnan.min()),
('mean', '%.3e' % nonnan.mean()),
('median', '%.3e' % np.median(nonnan)),
('max', '%.3e' % nonnan.max()),
('zero', '%d (%d%%)' % (zero, 100 * float(zero) / size)),
('nan', '%d (%d%%)' % (nan, 100 * float(nan) / size)),
('inf', np.isinf(arr).sum()),
]
return table
#------------------------------------------------------------------------------
# CLI commands
#------------------------------------------------------------------------------
@click.command('npyshow')
@click.argument('paths', type=click.Path(exists=True), nargs=-1)
@click.option('-n', default=2, help="Number of first/last elements to show.")
@click.option('--show-array/--no-show-array', default=True, help="Whether to show the array.")
@click.option(
'--show-stats/--no-show-stats', default=False,
help="Whether to show basic statistics about the array "
"(requires to load the entire array in memory)")
@click.pass_context
def npyshow(ctx, paths, show_array=True, n=2, show_stats=False):
"""Show array information of a NPY file and possibly display it."""
np.set_printoptions(edgeitems=n)
for path in paths:
if not path.endswith('.npy'):
continue
arr = np.load(path, mmap_mode='r')
table = _array_info_table(arr, show_stats=show_stats)
click.echo(path)
click.echo(_tabulate(table))
if show_array:
click.echo(arr)
arr._mmap.close()
@click.command('npyplot')
@click.argument('path', type=click.Path(exists=True), nargs=1)
@click.pass_context
def npyplot(ctx, path):
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.style.use('dark_background')
mpl.rcParams['toolbar'] = 'None'
f, ax = plt.subplots()
arr = np.load(path).squeeze()
if arr.ndim == 1:
ax.plot(arr)
elif arr.ndim == 2:
m, M = min(arr.shape), max(arr.shape)
arr = arr.reshape((M, m))
if m == 2:
ax.plot(arr[:, 0], arr[:, 1])
if 3 <= m <= 5:
ax.plot(arr)
else:
ax.imshow(arr)
elif arr.ndim == 3:
arr = np.transpose(arr, np.argsort(arr.shape)[::-1])
ax.imshow(arr[..., :3].astype(np.float64), vmin=arr.min(), vmax=arr.max())
f.canvas.window().statusBar().setVisible(False)
plt.show()