Skip to content

Commit ebc54da

Browse files
committed
RF(no functional changes): flake8 nib-ls
1 parent b956a26 commit ebc54da

File tree

1 file changed

+49
-42
lines changed

1 file changed

+49
-42
lines changed

bin/nib-ls

Lines changed: 49 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -12,25 +12,27 @@ Output a summary table for neuroimaging files (resolution, dimensionality, etc.)
1212
"""
1313
from __future__ import division, print_function, absolute_import
1414

15-
__author__ = 'Yaroslav Halchenko'
16-
__copyright__ = 'Copyright (c) 2011-2016 Yaroslav Halchenko ' \
17-
'and NiBabel contributors'
18-
__license__ = 'MIT'
19-
2015
import re
2116
import sys
17+
18+
import numpy as np
19+
import nibabel as nib
20+
2221
from math import ceil
2322
from optparse import OptionParser, Option
2423
from io import StringIO
24+
from nibabel.py3k import asunicode
2525

26-
import numpy as np
26+
__author__ = 'Yaroslav Halchenko'
27+
__copyright__ = 'Copyright (c) 2011-2016 Yaroslav Halchenko ' \
28+
'and NiBabel contributors'
29+
__license__ = 'MIT'
2730

28-
import nibabel as nib
29-
from nibabel.py3k import asunicode
3031

3132
# global verbosity switch
3233
verbose_level = 0
3334

35+
3436
def verbose(l, msg):
3537
"""Print `s` if `l` is less than the `verbose_level`
3638
"""
@@ -40,11 +42,10 @@ def verbose(l, msg):
4042

4143

4244
def error(msg, exit_code):
43-
print >> sys.stderr, msg
45+
print >> sys.stderr, msg
4446
sys.exit(exit_code)
4547

4648

47-
4849
def table2string(table, out=None):
4950
"""Given list of lists figure out their common widths and print to out
5051
@@ -65,18 +66,19 @@ def table2string(table, out=None):
6566
out = StringIO()
6667

6768
# equalize number of elements in each row
68-
Nelements_max = len(table) \
69-
and max(len(x) for x in table)
69+
nelements_max = \
70+
len(table) and \
71+
max(len(x) for x in table)
7072

7173
for i, table_ in enumerate(table):
72-
table[i] += [''] * (Nelements_max - len(table_))
74+
table[i] += [''] * (nelements_max - len(table_))
7375

7476
# figure out lengths within each column
7577
atable = np.asarray(table)
7678
# eat whole entry while computing width for @w (for wide)
7779
markup_strip = re.compile('^@([lrc]|w.*)')
78-
col_width = [ max( [len(markup_strip.sub('', x))
79-
for x in column] ) for column in atable.T ]
80+
col_width = [max([len(markup_strip.sub('', x))
81+
for x in column]) for column in atable.T]
8082
string = ""
8183
for i, table_ in enumerate(table):
8284
string_ = ""
@@ -85,26 +87,26 @@ def table2string(table, out=None):
8587
if item.startswith('@'):
8688
align = item[1]
8789
item = item[2:]
88-
if not align in ['l', 'r', 'c', 'w']:
90+
if align not in ['l', 'r', 'c', 'w']:
8991
raise ValueError('Unknown alignment %s. Known are l,r,c' %
9092
align)
9193
else:
9294
align = 'c'
9395

94-
NspacesL = max(ceil((col_width[j] - len(item))/2.0), 0)
95-
NspacesR = max(col_width[j] - NspacesL - len(item), 0)
96+
nspacesl = max(ceil((col_width[j] - len(item)) / 2.0), 0)
97+
nspacesr = max(col_width[j] - nspacesl - len(item), 0)
9698

9799
if align in ['w', 'c']:
98100
pass
99101
elif align == 'l':
100-
NspacesL, NspacesR = 0, NspacesL + NspacesR
102+
nspacesl, nspacesr = 0, nspacesl + nspacesr
101103
elif align == 'r':
102-
NspacesL, NspacesR = NspacesL + NspacesR, 0
104+
nspacesl, nspacesr = nspacesl + nspacesr, 0
103105
else:
104106
raise RuntimeError('Should not get here with align=%s' % align)
105107

106108
string_ += "%%%ds%%s%%%ds " \
107-
% (NspacesL, NspacesR) % ('', item, '')
109+
% (nspacesl, nspacesr) % ('', item, '')
108110
string += string_.rstrip() + '\n'
109111
out.write(asunicode(string))
110112

@@ -113,15 +115,17 @@ def table2string(table, out=None):
113115
out.close()
114116
return value
115117

116-
def ap(l, format, sep=', '):
118+
119+
def ap(l, format_, sep=', '):
117120
"""Little helper to enforce consistency"""
118121
if l == '-':
119122
return l
120-
ls = [format % x for x in l]
123+
ls = [format_ % x for x in l]
121124
return sep.join(ls)
122125

126+
123127
def safe_get(obj, name):
124-
"""
128+
"""A getattr which would return '-' if getattr fails
125129
"""
126130
try:
127131
f = getattr(obj, 'get_' + name)
@@ -130,11 +134,12 @@ def safe_get(obj, name):
130134
verbose(2, "get_%s() failed -- %s" % (name, e))
131135
return '-'
132136

137+
133138
def get_opt_parser():
134139
# use module docstring for help output
135140
p = OptionParser(
136-
usage="%s [OPTIONS] [FILE ...]\n\n" % sys.argv[0] + __doc__,
137-
version="%prog " + nib.__version__)
141+
usage="%s [OPTIONS] [FILE ...]\n\n" % sys.argv[0] + __doc__,
142+
version="%prog " + nib.__version__)
138143

139144
p.add_options([
140145
Option("-v", "--verbose", action="count",
@@ -151,15 +156,17 @@ def get_opt_parser():
151156

152157
Option("-c", "--counts",
153158
action="store_true", dest='counts', default=False,
154-
help="Output counts - number of entries for each numeric value (useful for int ROI maps)"),
159+
help="Output counts - number of entries for each numeric value "
160+
"(useful for int ROI maps)"),
155161

156162
Option("-z", "--zeros",
157163
action="store_true", dest='stats_zeros', default=False,
158164
help="Include zeros into output basic data statistics (--stats, --counts)"),
159-
])
165+
])
160166

161167
return p
162168

169+
163170
def proc_file(f, opts):
164171
verbose(1, "Loading %s" % f)
165172

@@ -172,21 +179,21 @@ def proc_file(f, opts):
172179
verbose(2, "Failed to gather information -- %s" % str(e))
173180
return row
174181

175-
row += [ str(safe_get(h, 'data_dtype')),
176-
'@l[%s]' %ap(safe_get(h, 'data_shape'), '%3g'),
177-
'@l%s' % ap(safe_get(h, 'zooms'), '%.2f', 'x') ]
182+
row += [str(safe_get(h, 'data_dtype')),
183+
'@l[%s]' % ap(safe_get(h, 'data_shape'), '%3g'),
184+
'@l%s' % ap(safe_get(h, 'zooms'), '%.2f', 'x')]
178185
# Slope
179-
if (hasattr(h, 'has_data_slope')
180-
and (h.has_data_slope or h.has_data_intercept)) \
181-
and not h.get_slope_inter() in [(1.0, 0.0), (None, None)]:
186+
if hasattr(h, 'has_data_slope') and \
187+
(h.has_data_slope or h.has_data_intercept) and \
188+
not h.get_slope_inter() in [(1.0, 0.0), (None, None)]:
182189
row += ['@l*%.3g+%.3g' % h.get_slope_inter()]
183190
else:
184-
row += [ '' ]
191+
row += ['']
185192

186-
if (hasattr(h, 'extensions') and len(h.extensions)):
193+
if hasattr(h, 'extensions') and len(h.extensions):
187194
row += ['@l#exts: %d' % len(h.extensions)]
188195
else:
189-
row += [ '' ]
196+
row += ['']
190197

191198
if opts.header_fields:
192199
# signals "all fields"
@@ -198,16 +205,16 @@ def proc_file(f, opts):
198205
header_fields = opts.header_fields.split(',')
199206

200207
for f in header_fields:
201-
if not f: # skip empty
208+
if not f: # skip empty
202209
continue
203210
try:
204211
row += [str(h[f])]
205212
except (KeyError, ValueError):
206-
row += [ 'error' ]
213+
row += ['error']
207214

208215
try:
209-
if (hasattr(h, 'get_qform') and hasattr(h, 'get_sform')
210-
and (h.get_qform() != h.get_sform()).any()):
216+
if (hasattr(h, 'get_qform') and hasattr(h, 'get_sform') and
217+
(h.get_qform() != h.get_sform()).any()):
211218
row += ['sform']
212219
else:
213220
row += ['']
@@ -233,7 +240,7 @@ def proc_file(f, opts):
233240
items, inv = np.unique(d, return_inverse=True)
234241
freq = np.bincount(inv)
235242
row += ["@l" + " ".join("%g:%d" % (i, f) for i, f in zip(items, freq))]
236-
except Exception as e:
243+
except IOError as e:
237244
verbose(2, "Failed to obtain stats/counts -- %s" % str(e))
238245
row += ['error']
239246
return row

0 commit comments

Comments
 (0)