Skip to content

Commit b4bd9d6

Browse files
committed
RF+BF - non-doctests now all pass on py3k
1 parent d6a11e6 commit b4bd9d6

File tree

14 files changed

+205
-58
lines changed

14 files changed

+205
-58
lines changed

nibabel/batteryrunners.py

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -211,8 +211,17 @@ def __init__(self,
211211
self.problem_msg = problem_msg
212212
self.fix_msg = fix_msg
213213

214-
def __cmp__(self, other):
215-
''' Compare two BatteryRunner-like objects
214+
def __getstate__(self):
215+
""" State that defines object
216+
217+
Returns
218+
-------
219+
tup : tuple
220+
"""
221+
return self.error, self.problem_level, self.problem_msg, self.fix_msg
222+
223+
def __eq__(self, other):
224+
''' are two BatteryRunner-like objects equal?
216225
217226
Parameters
218227
----------
@@ -229,7 +238,14 @@ def __cmp__(self, other):
229238
>>> rep == rep3
230239
False
231240
'''
232-
return cmp(self.__dict__, other.__dict__)
241+
return self.__getstate__() == other.__getstate__()
242+
243+
def __ne__(self, other):
244+
""" are two BatteryRunner-like objects not equal?
245+
246+
See docstring for __eq__
247+
"""
248+
return not self == other
233249

234250
def __str__(self):
235251
''' Printable string for object '''

nibabel/externals/netcdf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -731,7 +731,7 @@ def _pack_int(self, value):
731731
_pack_int32 = _pack_int
732732

733733
def _unpack_int(self):
734-
return fromstring(self.fp.read(4), '>i')[0]
734+
return int(fromstring(self.fp.read(4), '>i')[0])
735735
_unpack_int32 = _unpack_int
736736

737737
def _pack_int64(self, value):

nibabel/externals/tests/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# Make externals tests a package
1.7 KB
Binary file not shown.
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
''' Tests for netcdf '''
2+
3+
import os
4+
from os.path import join as pjoin, dirname
5+
import shutil
6+
import tempfile
7+
from glob import glob
8+
9+
import numpy as np
10+
11+
from ...py3k import BytesIO, asbytes
12+
from ..netcdf import netcdf_file
13+
14+
from nose.tools import assert_true, assert_false, assert_equal, assert_raises
15+
16+
TEST_DATA_PATH = pjoin(dirname(__file__), 'data')
17+
18+
N_EG_ELS = 11 # number of elements for example variable
19+
VARTYPE_EG = 'b' # var type for example variable
20+
21+
22+
def make_simple(*args, **kwargs):
23+
f = netcdf_file(*args, **kwargs)
24+
f.history = 'Created for a test'
25+
f.createDimension('time', N_EG_ELS)
26+
time = f.createVariable('time', VARTYPE_EG, ('time',))
27+
time[:] = np.arange(N_EG_ELS)
28+
time.units = 'days since 2008-01-01'
29+
f.flush()
30+
return f
31+
32+
33+
def gen_for_simple(ncfileobj):
34+
''' Generator for example fileobj tests '''
35+
yield assert_equal, ncfileobj.history, asbytes('Created for a test')
36+
time = ncfileobj.variables['time']
37+
yield assert_equal, time.units, asbytes('days since 2008-01-01')
38+
yield assert_equal, time.shape, (N_EG_ELS,)
39+
yield assert_equal, time[-1], N_EG_ELS-1
40+
41+
42+
def test_read_write_files():
43+
# test round trip for example file
44+
cwd = os.getcwd()
45+
try:
46+
tmpdir = tempfile.mkdtemp()
47+
os.chdir(tmpdir)
48+
f = make_simple('simple.nc', 'w')
49+
f.close()
50+
# To read the NetCDF file we just created::
51+
f = netcdf_file('simple.nc')
52+
# Using mmap is the default
53+
yield assert_true, f.use_mmap
54+
for testargs in gen_for_simple(f):
55+
yield testargs
56+
f.close()
57+
# Now without mmap
58+
f = netcdf_file('simple.nc', mmap=False)
59+
# Using mmap is the default
60+
yield assert_false, f.use_mmap
61+
for testargs in gen_for_simple(f):
62+
yield testargs
63+
f.close()
64+
# To read the NetCDF file we just created, as file object, no
65+
# mmap. When n * n_bytes(var_type) is not divisible by 4, this
66+
# raised an error in pupynere 1.0.12 and scipy rev 5893, because
67+
# calculated vsize was rounding up in units of 4 - see
68+
# http://www.unidata.ucar.edu/software/netcdf/docs/netcdf.html
69+
fobj = open('simple.nc', 'rb')
70+
f = netcdf_file(fobj)
71+
# by default, don't use mmap for file-like
72+
yield assert_false, f.use_mmap
73+
for testargs in gen_for_simple(f):
74+
yield testargs
75+
f.close()
76+
except:
77+
os.chdir(cwd)
78+
shutil.rmtree(tmpdir)
79+
raise
80+
os.chdir(cwd)
81+
shutil.rmtree(tmpdir)
82+
83+
84+
def test_read_write_sio():
85+
eg_sio1 = BytesIO()
86+
f1 = make_simple(eg_sio1, 'w')
87+
str_val = eg_sio1.getvalue()
88+
f1.close()
89+
eg_sio2 = BytesIO(str_val)
90+
f2 = netcdf_file(eg_sio2)
91+
for testargs in gen_for_simple(f2):
92+
yield testargs
93+
f2.close()
94+
# Test that error is raised if attempting mmap for sio
95+
eg_sio3 = BytesIO(str_val)
96+
yield assert_raises, ValueError, netcdf_file, eg_sio3, 'r', True
97+
# Test 64-bit offset write / read
98+
eg_sio_64 = BytesIO()
99+
f_64 = make_simple(eg_sio_64, 'w', version=2)
100+
str_val = eg_sio_64.getvalue()
101+
f_64.close()
102+
eg_sio_64 = BytesIO(str_val)
103+
f_64 = netcdf_file(eg_sio_64)
104+
for testargs in gen_for_simple(f_64):
105+
yield testargs
106+
yield assert_equal, f_64.version_byte, 2
107+
# also when version 2 explicitly specified
108+
eg_sio_64 = BytesIO(str_val)
109+
f_64 = netcdf_file(eg_sio_64, version=2)
110+
for testargs in gen_for_simple(f_64):
111+
yield testargs
112+
yield assert_equal, f_64.version_byte, 2
113+
114+
115+
def test_read_example_data():
116+
# read any example data files
117+
for fname in glob(pjoin(TEST_DATA_PATH, '*.nc')):
118+
f = netcdf_file(fname, 'r')
119+
f = netcdf_file(fname, 'r', mmap=False)
120+

nibabel/loadsave.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
#
88
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
99
# module imports
10+
from .py3k import asbytes
1011
from .filename_parser import types_filenames, splitext_addext
1112
from . import volumeutils as vu
1213
from . import spm2analyze as spm2
@@ -44,7 +45,7 @@ def load(filename):
4445
hdr = nifti1.Nifti1Header.from_fileobj(
4546
vu.allopen(filenames['header']),
4647
check=False)
47-
if hdr['magic'] in ('ni1', 'n+1'):
48+
if hdr['magic'] in (asbytes('ni1'), asbytes('n+1')):
4849
# allow goofy nifti single magic for pair
4950
klass = nifti1.Nifti1Pair
5051
else:

nibabel/minc.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
from .externals.netcdf import netcdf_file
1212

13+
from .py3k import asbytes, asstr
1314
from .spatialimages import SpatialImage
1415

1516
_dt_dict = {
@@ -52,7 +53,7 @@ def __init__(self, mincfile):
5253
# We don't currently support irregular spacing
5354
# http://www.bic.mni.mcgill.ca/software/minc/minc1_format/node15.html
5455
for dim in self._dims:
55-
if dim.spacing != 'regular__':
56+
if dim.spacing != asbytes('regular__'):
5657
raise ValueError('Irregular spacing not supported')
5758
self._spatial_dims = [name for name in self._dim_names
5859
if name.endswith('space')]
@@ -64,7 +65,7 @@ def get_data_dtype(self):
6465
elif typecode == 'd':
6566
dtt = np.dtype(np.float64)
6667
else:
67-
signtype = self._image.signtype
68+
signtype = asstr(self._image.signtype)
6869
dtt = _dt_dict[(typecode, signtype)]
6970
return np.dtype(dtt).newbyteorder('>')
7071

nibabel/nifti1.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
import numpy as np
1212
import numpy.linalg as npl
1313

14-
from .py3k import ZEROB, ints2bytes, asbytes
14+
from .py3k import ZEROB, ints2bytes, asbytes, asstr
1515
from .volumeutils import Recoder, make_dt_codes, endian_codes
1616
from .spatialimages import HeaderDataError, ImageFileError
1717
from .batteryrunners import Report
@@ -276,9 +276,11 @@ def __repr__(self):
276276
s = "Nifti1Extension('%s', '%s')" % (code, self._content)
277277
return s
278278

279-
def __cmp__(self, other):
280-
return cmp((self._code, self._content),
281-
(other._code, other._content))
279+
def __eq__(self, other):
280+
return (self._code, self._content) == (other._code, other._content)
281+
282+
def __ne__(self, other):
283+
return not self == other
282284

283285
def write_to(self, fileobj, byteswap):
284286
''' Write header extensions to fileobj
@@ -919,7 +921,7 @@ def get_intent(self, code_repr='label'):
919921
raise TypeError('repr can be "label" or "code"')
920922
n_params = len(recoder.parameters[code])
921923
params = (float(hdr['intent_p%d' % (i+1)]) for i in range(n_params))
922-
return label, tuple(params), str(hdr['intent_name'])
924+
return label, tuple(params), np.asscalar(hdr['intent_name'])
923925

924926
def set_intent(self, code, params=(), name=''):
925927
''' Set the intent code, parameters and name
@@ -1281,7 +1283,8 @@ def _chk_qfac(hdr, fix=False):
12811283
@staticmethod
12821284
def _chk_magic_offset(hdr, fix=False):
12831285
rep = Report(HeaderDataError)
1284-
magic = hdr['magic']
1286+
# for ease of later string formatting, use scalar of byte string
1287+
magic = np.asscalar(hdr['magic'])
12851288
offset = hdr['vox_offset']
12861289
if magic == asbytes('n+1'): # one file
12871290
if offset >= 352:
@@ -1304,7 +1307,8 @@ def _chk_magic_offset(hdr, fix=False):
13041307
rep.fix_msg = 'setting to minimum value of 352'
13051308
elif magic != asbytes('ni1'): # two files
13061309
# unrecognized nii magic string, oh dear
1307-
rep.problem_msg = 'magic string "%s" is not valid' % magic
1310+
rep.problem_msg = ('magic string "%s" is not valid' %
1311+
asstr(magic))
13081312
rep.problem_level = 45
13091313
if fix:
13101314
rep.fix_msg = 'leaving as is, but future errors are likely'

nibabel/tests/test_image_load_save.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from os.path import join as pjoin
1212
import shutil
1313
from tempfile import mkdtemp
14-
from ..py3k import BytesIO
14+
from ..py3k import BytesIO, asbytes
1515

1616
import numpy as np
1717

@@ -103,7 +103,7 @@ def test_save_load_endian():
103103
m_img2 = round_trip(mixed_img)
104104
assert_equal(m_img2.get_header().endianness, native_code)
105105
assert_array_equal(m_img2.get_data(), data)
106-
106+
107107

108108
def test_save_load():
109109
shape = (2, 4, 6)
@@ -156,12 +156,12 @@ def test_two_to_one():
156156
affine[:3,3] = [3,2,1]
157157
# single file format
158158
img = ni1.Nifti1Image(data, affine)
159-
assert_equal(img.get_header()['magic'], 'n+1')
159+
assert_equal(img.get_header()['magic'], asbytes('n+1'))
160160
str_io = BytesIO()
161161
img.file_map['image'].fileobj = str_io
162162
# check that the single format vox offset is set correctly
163163
img.to_file_map()
164-
assert_equal(img.get_header()['magic'], 'n+1')
164+
assert_equal(img.get_header()['magic'], asbytes('n+1'))
165165
assert_equal(img.get_header()['vox_offset'], 352)
166166
# make a new pair image, with the single image header
167167
pimg = ni1.Nifti1Pair(data, affine, img.get_header())
@@ -171,7 +171,7 @@ def test_two_to_one():
171171
pimg.file_map['header'].fileobj = hsio
172172
pimg.to_file_map()
173173
# the offset remains the same
174-
assert_equal(pimg.get_header()['magic'], 'ni1')
174+
assert_equal(pimg.get_header()['magic'], asbytes('ni1'))
175175
assert_equal(pimg.get_header()['vox_offset'], 352)
176176
assert_array_equal(pimg.get_data(), data)
177177
# same for from_image, going from single image to pair format

0 commit comments

Comments
 (0)