@@ -12,25 +12,27 @@ Output a summary table for neuroimaging files (resolution, dimensionality, etc.)
12
12
"""
13
13
from __future__ import division , print_function , absolute_import
14
14
15
- __author__ = 'Yaroslav Halchenko'
16
- __copyright__ = 'Copyright (c) 2011-2016 Yaroslav Halchenko ' \
17
- 'and NiBabel contributors'
18
- __license__ = 'MIT'
19
-
20
15
import re
21
16
import sys
17
+
18
+ import numpy as np
19
+ import nibabel as nib
20
+
22
21
from math import ceil
23
22
from optparse import OptionParser , Option
24
23
from io import StringIO
24
+ from nibabel .py3k import asunicode
25
25
26
- import numpy as np
26
+ __author__ = 'Yaroslav Halchenko'
27
+ __copyright__ = 'Copyright (c) 2011-2016 Yaroslav Halchenko ' \
28
+ 'and NiBabel contributors'
29
+ __license__ = 'MIT'
27
30
28
- import nibabel as nib
29
- from nibabel .py3k import asunicode
30
31
31
32
# global verbosity switch
32
33
verbose_level = 0
33
34
35
+
34
36
def verbose (l , msg ):
35
37
"""Print `s` if `l` is less than the `verbose_level`
36
38
"""
@@ -40,11 +42,10 @@ def verbose(l, msg):
40
42
41
43
42
44
def error (msg , exit_code ):
43
- print >> sys .stderr , msg
45
+ print >> sys .stderr , msg
44
46
sys .exit (exit_code )
45
47
46
48
47
-
48
49
def table2string (table , out = None ):
49
50
"""Given list of lists figure out their common widths and print to out
50
51
@@ -65,18 +66,19 @@ def table2string(table, out=None):
65
66
out = StringIO ()
66
67
67
68
# 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 )
70
72
71
73
for i , table_ in enumerate (table ):
72
- table [i ] += ['' ] * (Nelements_max - len (table_ ))
74
+ table [i ] += ['' ] * (nelements_max - len (table_ ))
73
75
74
76
# figure out lengths within each column
75
77
atable = np .asarray (table )
76
78
# eat whole entry while computing width for @w (for wide)
77
79
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 ]
80
82
string = ""
81
83
for i , table_ in enumerate (table ):
82
84
string_ = ""
@@ -85,26 +87,26 @@ def table2string(table, out=None):
85
87
if item .startswith ('@' ):
86
88
align = item [1 ]
87
89
item = item [2 :]
88
- if not align in ['l' , 'r' , 'c' , 'w' ]:
90
+ if align not in ['l' , 'r' , 'c' , 'w' ]:
89
91
raise ValueError ('Unknown alignment %s. Known are l,r,c' %
90
92
align )
91
93
else :
92
94
align = 'c'
93
95
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 )
96
98
97
99
if align in ['w' , 'c' ]:
98
100
pass
99
101
elif align == 'l' :
100
- NspacesL , NspacesR = 0 , NspacesL + NspacesR
102
+ nspacesl , nspacesr = 0 , nspacesl + nspacesr
101
103
elif align == 'r' :
102
- NspacesL , NspacesR = NspacesL + NspacesR , 0
104
+ nspacesl , nspacesr = nspacesl + nspacesr , 0
103
105
else :
104
106
raise RuntimeError ('Should not get here with align=%s' % align )
105
107
106
108
string_ += "%%%ds%%s%%%ds " \
107
- % (NspacesL , NspacesR ) % ('' , item , '' )
109
+ % (nspacesl , nspacesr ) % ('' , item , '' )
108
110
string += string_ .rstrip () + '\n '
109
111
out .write (asunicode (string ))
110
112
@@ -113,15 +115,17 @@ def table2string(table, out=None):
113
115
out .close ()
114
116
return value
115
117
116
- def ap (l , format , sep = ', ' ):
118
+
119
+ def ap (l , format_ , sep = ', ' ):
117
120
"""Little helper to enforce consistency"""
118
121
if l == '-' :
119
122
return l
120
- ls = [format % x for x in l ]
123
+ ls = [format_ % x for x in l ]
121
124
return sep .join (ls )
122
125
126
+
123
127
def safe_get (obj , name ):
124
- """
128
+ """A getattr which would return '-' if getattr fails
125
129
"""
126
130
try :
127
131
f = getattr (obj , 'get_' + name )
@@ -130,11 +134,12 @@ def safe_get(obj, name):
130
134
verbose (2 , "get_%s() failed -- %s" % (name , e ))
131
135
return '-'
132
136
137
+
133
138
def get_opt_parser ():
134
139
# use module docstring for help output
135
140
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__ )
138
143
139
144
p .add_options ([
140
145
Option ("-v" , "--verbose" , action = "count" ,
@@ -151,15 +156,17 @@ def get_opt_parser():
151
156
152
157
Option ("-c" , "--counts" ,
153
158
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)" ),
155
161
156
162
Option ("-z" , "--zeros" ,
157
163
action = "store_true" , dest = 'stats_zeros' , default = False ,
158
164
help = "Include zeros into output basic data statistics (--stats, --counts)" ),
159
- ])
165
+ ])
160
166
161
167
return p
162
168
169
+
163
170
def proc_file (f , opts ):
164
171
verbose (1 , "Loading %s" % f )
165
172
@@ -172,21 +179,21 @@ def proc_file(f, opts):
172
179
verbose (2 , "Failed to gather information -- %s" % str (e ))
173
180
return row
174
181
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' )]
178
185
# 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 )]:
182
189
row += ['@l*%.3g+%.3g' % h .get_slope_inter ()]
183
190
else :
184
- row += [ '' ]
191
+ row += ['' ]
185
192
186
- if ( hasattr (h , 'extensions' ) and len (h .extensions ) ):
193
+ if hasattr (h , 'extensions' ) and len (h .extensions ):
187
194
row += ['@l#exts: %d' % len (h .extensions )]
188
195
else :
189
- row += [ '' ]
196
+ row += ['' ]
190
197
191
198
if opts .header_fields :
192
199
# signals "all fields"
@@ -198,16 +205,16 @@ def proc_file(f, opts):
198
205
header_fields = opts .header_fields .split (',' )
199
206
200
207
for f in header_fields :
201
- if not f : # skip empty
208
+ if not f : # skip empty
202
209
continue
203
210
try :
204
211
row += [str (h [f ])]
205
212
except (KeyError , ValueError ):
206
- row += [ 'error' ]
213
+ row += ['error' ]
207
214
208
215
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 ()):
211
218
row += ['sform' ]
212
219
else :
213
220
row += ['' ]
@@ -233,7 +240,7 @@ def proc_file(f, opts):
233
240
items , inv = np .unique (d , return_inverse = True )
234
241
freq = np .bincount (inv )
235
242
row += ["@l" + " " .join ("%g:%d" % (i , f ) for i , f in zip (items , freq ))]
236
- except Exception as e :
243
+ except IOError as e :
237
244
verbose (2 , "Failed to obtain stats/counts -- %s" % str (e ))
238
245
row += ['error' ]
239
246
return row
0 commit comments