diff --git a/doc/source/coordinate_systems.rst b/doc/source/coordinate_systems.rst index ad17ee23ac..29c53472c7 100644 --- a/doc/source/coordinate_systems.rst +++ b/doc/source/coordinate_systems.rst @@ -55,7 +55,7 @@ the array. >>> slice_1 = epi_img_data[:, 30, :] >>> slice_2 = epi_img_data[:, :, 16] >>> show_slices([slice_0, slice_1, slice_2]) - >>> plt.suptitle("Center slices for EPI image") + >>> plt.suptitle("Center slices for EPI image") # doctest: +SKIP We collected an anatomical image in the same session. We can load that image and look at slices in the three axes: @@ -77,7 +77,7 @@ and look at slices in the three axes: >>> show_slices([anat_img_data[28, :, :], ... anat_img_data[:, 33, :], ... anat_img_data[:, :, 28]]) - >>> plt.suptitle("Center slices for anatomical image") + >>> plt.suptitle("Center slices for anatomical image") # doctest: +SKIP As is usually the case, we had a different field of view for the anatomical scan, and so the anatomical image has a different shape, size, and orientation diff --git a/doc/source/neuro_radio_conventions.rst b/doc/source/neuro_radio_conventions.rst index 47e3f23f18..eab46ce618 100644 --- a/doc/source/neuro_radio_conventions.rst +++ b/doc/source/neuro_radio_conventions.rst @@ -95,7 +95,7 @@ Here we are showing the middle slice of :download:`an image >>> img_data = img.get_data() >>> a_slice = img_data[:, :, 28] >>> # Need transpose to put first axis left-right, second bottom-top - >>> plt.imshow(a_slice.T, cmap="gray", origin="lower") + >>> plt.imshow(a_slice.T, cmap="gray", origin="lower") # doctest: +SKIP This slice does have the voxels from the right of isocenter towards the right of the screen, neurology style. diff --git a/nibabel/imageglobals.py b/nibabel/imageglobals.py index 1ec557ce48..0fc6dd3033 100644 --- a/nibabel/imageglobals.py +++ b/nibabel/imageglobals.py @@ -30,6 +30,7 @@ logger = logging.getLogger('nibabel.global') logger.addHandler(logging.StreamHandler()) + class ErrorLevel(object): """ Context manager to set log error level """ @@ -45,3 +46,15 @@ def __exit__(self, exc, value, tb): global error_level error_level = self._original_level return False + + +class LoggingOutputSuppressor(object): + """Context manager to prevent global logger from printing""" + def __enter__(self): + self.orig_handlers = logger.handlers + for handler in self.orig_handlers: + logger.removeHandler(handler) + + def __exit__(self, exc, value, tb): + for handler in self.orig_handlers: + logger.addHandler(handler) diff --git a/nibabel/nicom/dicomwrappers.py b/nibabel/nicom/dicomwrappers.py index 883541b09c..7822159b19 100644 --- a/nibabel/nicom/dicomwrappers.py +++ b/nibabel/nicom/dicomwrappers.py @@ -169,7 +169,7 @@ def rotation_matrix(self): """ iop = self.image_orient_patient s_norm = self.slice_normal - if None in (iop, s_norm): + if iop is None or s_norm is None: return None R = np.eye(3) # np.fliplr(iop) gives matrix F in @@ -235,7 +235,7 @@ def slice_indicator(self): """ ipp = self.image_position s_norm = self.slice_normal - if None in (ipp, s_norm): + if ipp is None or s_norm is None: return None return np.inner(ipp, s_norm) @@ -304,7 +304,7 @@ def get_affine(self): # column, slice) vox = self.voxel_sizes ipp = self.image_position - if None in (orient, vox, ipp): + if any(p is None for p in (orient, vox, ipp)): raise WrapperError('Not enough information for affine') aff = np.eye(4) aff[:3, :3] = orient * np.array(vox) @@ -786,7 +786,7 @@ def image_position(self): md_rows, md_cols = (self.get('Rows'), self.get('Columns')) iop = self.image_orient_patient pix_spacing = self.get('PixelSpacing') - if None in (ipp, md_rows, md_cols, iop, pix_spacing): + if any(x is None for x in (ipp, md_rows, md_cols, iop, pix_spacing)): return None # PixelSpacing values are python Decimal in pydicom 0.9.7 pix_spacing = np.array(list(map(float, pix_spacing))) @@ -881,8 +881,8 @@ def none_or_close(val1, val2, rtol=1e-5, atol=1e-6): >>> none_or_close([0,1], [0,2]) False """ - if (val1, val2) == (None, None): + if val1 is None and val2 is None: return True - if None in (val1, val2): + if val1 is None or val2 is None: return False return np.allclose(val1, val2, rtol, atol) diff --git a/nibabel/nifti1.py b/nibabel/nifti1.py index 55b48d4814..56c8ba7e13 100644 --- a/nibabel/nifti1.py +++ b/nibabel/nifti1.py @@ -1061,7 +1061,7 @@ def set_slope_inter(self, slope, inter=None): raise HeaderDataError('Slope cannot be 0 or infinite') if inter in (np.inf, -np.inf): raise HeaderDataError('Intercept cannot be infinite') - if np.diff(np.isnan([slope, inter])): + if np.isnan(slope) ^ np.isnan(inter): raise HeaderDataError('None or both of slope, inter should be nan') self._structarr['scl_slope'] = slope self._structarr['scl_inter'] = inter diff --git a/nibabel/testing/__init__.py b/nibabel/testing/__init__.py index a2b966335e..a0196ea1e4 100644 --- a/nibabel/testing/__init__.py +++ b/nibabel/testing/__init__.py @@ -10,6 +10,7 @@ from os.path import dirname, abspath, join as pjoin import numpy as np +from warnings import catch_warnings, simplefilter # set path to example data data_path = abspath(pjoin(dirname(__file__), '..', 'tests', 'data')) @@ -49,3 +50,12 @@ def assert_allclose_safely(a, b, match_nans=True): if b.dtype.kind in 'ui': b = b.astype(float) assert_true(np.allclose(a, b)) + + +class suppress_warnings(catch_warnings): + """ Version of ``catch_warnings`` class that suppresses warnings + """ + def __enter__(self): + res = super(suppress_warnings, self).__enter__() + simplefilter('ignore') + return res diff --git a/nibabel/tests/test_analyze.py b/nibabel/tests/test_analyze.py index 063be83bbf..03e4ad6faa 100644 --- a/nibabel/tests/test_analyze.py +++ b/nibabel/tests/test_analyze.py @@ -35,7 +35,8 @@ assert_array_almost_equal) from ..testing import (assert_equal, assert_not_equal, assert_true, - assert_false, assert_raises, data_path) + assert_false, assert_raises, data_path, + suppress_warnings) from .test_wrapstruct import _TestLabeledWrapStruct from . import test_spatialimages as tsi @@ -45,6 +46,7 @@ PIXDIM0_MSG = 'pixdim[1,2,3] should be non-zero; setting 0 dims to 1' + class TestAnalyzeHeader(_TestLabeledWrapStruct): header_class = AnalyzeHeader example_file = header_file @@ -97,7 +99,8 @@ def test_empty(self): def _set_something_into_hdr(self, hdr): # Called from test_bytes test method. Specific to the header data type - hdr.set_data_shape((1, 2, 3)) + with suppress_warnings(): + hdr.set_data_shape((1, 2, 3)) def test_checks(self): # Test header checks @@ -106,8 +109,9 @@ def test_checks(self): assert_equal(self._dxer(hdr_t), '') hdr = hdr_t.copy() hdr['sizeof_hdr'] = 1 - assert_equal(self._dxer(hdr), 'sizeof_hdr should be ' + - str(self.sizeof_hdr)) + with suppress_warnings(): + assert_equal(self._dxer(hdr), 'sizeof_hdr should be ' + + str(self.sizeof_hdr)) hdr = hdr_t.copy() hdr['datatype'] = 0 assert_equal(self._dxer(hdr), 'data code 0 not supported\n' @@ -125,8 +129,9 @@ def test_log_checks(self): HC = self.header_class # magic hdr = HC() - hdr['sizeof_hdr'] = 350 # severity 30 - fhdr, message, raiser = self.log_chk(hdr, 30) + with suppress_warnings(): + hdr['sizeof_hdr'] = 350 # severity 30 + fhdr, message, raiser = self.log_chk(hdr, 30) assert_equal(fhdr['sizeof_hdr'], self.sizeof_hdr) assert_equal(message, 'sizeof_hdr should be {0}; set sizeof_hdr to {0}'.format( @@ -139,7 +144,8 @@ def test_log_checks(self): # datatype not recognized hdr = HC() hdr['datatype'] = -1 # severity 40 - fhdr, message, raiser = self.log_chk(hdr, 40) + with suppress_warnings(): + fhdr, message, raiser = self.log_chk(hdr, 40) assert_equal(message, 'data code -1 not recognized; ' 'not attempting fix') assert_raises(*raiser) @@ -147,7 +153,7 @@ def test_log_checks(self): hdr['datatype'] = 255 # severity 40 fhdr, message, raiser = self.log_chk(hdr, 40) assert_equal(message, 'data code 255 not supported; ' - 'not attempting fix') + 'not attempting fix') assert_raises(*raiser) # bitpix hdr = HC() diff --git a/nibabel/tests/test_arraywriters.py b/nibabel/tests/test_arraywriters.py index e04177a341..46a8fe9f32 100644 --- a/nibabel/tests/test_arraywriters.py +++ b/nibabel/tests/test_arraywriters.py @@ -8,7 +8,6 @@ from platform import python_compiler, machine from distutils.version import LooseVersion import itertools - import numpy as np from ..externals.six import BytesIO @@ -28,7 +27,7 @@ assert_equal, assert_not_equal, assert_raises) -from ..testing import assert_allclose_safely +from ..testing import assert_allclose_safely, suppress_warnings from ..checkwarns import ErrorWarnings @@ -135,8 +134,9 @@ def test_no_scaling(): kwargs = (dict(check_scaling=False) if awt == ArrayWriter else dict(calc_scale=False)) aw = awt(arr, out_dtype, **kwargs) - back_arr = round_trip(aw) - exp_back = arr.astype(float) + with suppress_warnings(): # cast to real from cplx + back_arr = round_trip(aw) + exp_back = arr.astype(float) if out_dtype in IUINT_TYPES: exp_back = np.round(exp_back) if hasattr(aw, 'slope') and in_dtype in FLOAT_TYPES: @@ -642,7 +642,8 @@ def test_float_int_min_max(): continue for out_dt in IUINT_TYPES: try: - aw = SlopeInterArrayWriter(arr, out_dt) + with suppress_warnings(): # overflow + aw = SlopeInterArrayWriter(arr, out_dt) except ScalingError: continue arr_back_sc = round_trip(aw) diff --git a/nibabel/tests/test_casting.py b/nibabel/tests/test_casting.py index 859d20c4fe..2c1815f848 100644 --- a/nibabel/tests/test_casting.py +++ b/nibabel/tests/test_casting.py @@ -3,12 +3,12 @@ import os from platform import machine - import numpy as np from ..casting import (float_to_int, shared_range, CastingError, int_to_float, as_int, int_abs, floor_log2, able_int_type, best_float, ulp, longdouble_precision_improved) +from ..testing import suppress_warnings from numpy.testing import (assert_array_almost_equal, assert_array_equal) @@ -23,7 +23,8 @@ def test_shared_range(): # (if this system generates that) or something smaller (because of # overflow) mn, mx = shared_range(ft, it) - ovs = ft(mx) + np.arange(2048, dtype=ft) + with suppress_warnings(): + ovs = ft(mx) + np.arange(2048, dtype=ft) # Float16 can overflow to inf bit_bigger = ovs[np.isfinite(ovs)].astype(it) casted_mx = ft(mx).astype(it) @@ -51,7 +52,8 @@ def test_shared_range(): assert_equal(mn, 0) continue # And something larger for the minimum - ovs = ft(mn) - np.arange(2048, dtype=ft) + with suppress_warnings(): # overflow + ovs = ft(mn) - np.arange(2048, dtype=ft) # Float16 can overflow to inf bit_smaller = ovs[np.isfinite(ovs)].astype(it) casted_mn = ft(mn).astype(it) diff --git a/nibabel/tests/test_ecat.py b/nibabel/tests/test_ecat.py index 346b9afa4b..952b94e728 100644 --- a/nibabel/tests/test_ecat.py +++ b/nibabel/tests/test_ecat.py @@ -16,13 +16,12 @@ from ..ecat import EcatHeader, EcatMlist, EcatSubHeader, EcatImage from unittest import TestCase - from nose.tools import (assert_true, assert_false, assert_equal, assert_not_equal, assert_raises) from numpy.testing import assert_array_equal, assert_array_almost_equal -from ..testing import data_path +from ..testing import data_path, suppress_warnings from ..tmpdirs import InTemporaryDirectory from .test_wrapstruct import _TestWrapStructBase @@ -30,6 +29,7 @@ ecat_file = os.path.join(data_path, 'tinypet.v') + class TestEcatHeader(_TestWrapStructBase): header_class = EcatHeader example_file = ecat_file @@ -111,7 +111,8 @@ def test_mlist(self): 6.01670000e+04, 1.00000000e+00], [ 1.68427580e+07, 6.01680000e+04, 7.22000000e+04, 1.00000000e+00]]) - assert_true(badordermlist.get_frame_order()[0][0] == 1) + with suppress_warnings(): # STORED order + assert_true(badordermlist.get_frame_order()[0][0] == 1) def test_mlist_errors(self): fid = open(self.example_file, 'rb') @@ -130,18 +131,21 @@ def test_mlist_errors(self): 6.01670000e+04, 1.00000000e+00], [ 1.68427580e+07, 6.01680000e+04, 7.22000000e+04, 1.00000000e+00]]) - series_framenumbers = mlist.get_series_framenumbers() + with suppress_warnings(): # STORED order + series_framenumbers = mlist.get_series_framenumbers() # first frame stored was actually 2nd frame acquired assert_true(series_framenumbers[0] == 2) order = [series_framenumbers[x] for x in sorted(series_framenumbers)] # true series order is [2,1,3,4,5,6], note counting starts at 1 assert_true(order == [2, 1, 3, 4, 5, 6]) mlist._mlist[0,0] = 0 - frames_order = mlist.get_frame_order() + with suppress_warnings(): + frames_order = mlist.get_frame_order() neworder =[frames_order[x][0] for x in sorted(frames_order)] assert_true(neworder == [1, 2, 3, 4, 5]) - assert_raises(IOError, - mlist.get_series_framenumbers) + with suppress_warnings(): + assert_raises(IOError, + mlist.get_series_framenumbers) @@ -178,6 +182,7 @@ def test_subheader(self): ecat_calib_factor = self.hdr['ecat_calibration_factor'] assert_equal(ecat_calib_factor, 25007614.0) + class TestEcatImage(TestCase): image_class = EcatImage example_file = ecat_file diff --git a/nibabel/tests/test_floating.py b/nibabel/tests/test_floating.py index 83b391f9ba..26df376a05 100644 --- a/nibabel/tests/test_floating.py +++ b/nibabel/tests/test_floating.py @@ -10,6 +10,7 @@ int_to_float, floor_log2, type_info, _check_nmant, _check_maxexp, ok_floats, on_powerpc, have_binary128, longdouble_precision_improved) +from ..testing import suppress_warnings from nose import SkipTest from nose.tools import assert_equal, assert_raises, assert_true, assert_false @@ -92,9 +93,11 @@ def test_check_nmant_nexp(): assert_true(_check_nmant(t, nmant)) assert_false(_check_nmant(t, nmant - 1)) assert_false(_check_nmant(t, nmant + 1)) - assert_true(_check_maxexp(t, maxexp)) + with suppress_warnings(): # overflow + assert_true(_check_maxexp(t, maxexp)) assert_false(_check_maxexp(t, maxexp - 1)) - assert_false(_check_maxexp(t, maxexp + 1)) + with suppress_warnings(): + assert_false(_check_maxexp(t, maxexp + 1)) # Check against type_info for t in ok_floats(): ti = type_info(t) diff --git a/nibabel/tests/test_minc1.py b/nibabel/tests/test_minc1.py index 7d04a1340f..6ecdffa9ec 100644 --- a/nibabel/tests/test_minc1.py +++ b/nibabel/tests/test_minc1.py @@ -9,6 +9,7 @@ from __future__ import division, print_function, absolute_import from os.path import join as pjoin + import gzip import bz2 import warnings @@ -33,6 +34,7 @@ EG_FNAME = pjoin(data_path, 'tiny.mnc') + def test_old_namespace(): # Check old names are defined in minc1 module and top level # Check warnings raised diff --git a/nibabel/tests/test_nifti1.py b/nibabel/tests/test_nifti1.py index ab748b9920..a5b675db9a 100644 --- a/nibabel/tests/test_nifti1.py +++ b/nibabel/tests/test_nifti1.py @@ -32,7 +32,7 @@ from nose.tools import (assert_true, assert_false, assert_equal, assert_raises) -from ..testing import data_path +from ..testing import data_path, suppress_warnings from . import test_analyze as tana from . import test_spm99analyze as tspm @@ -256,7 +256,8 @@ def test_freesurfer_hack(self): hdr.set_data_shape((too_big-1, 1, 1)) assert_equal(hdr.get_data_shape(), (too_big-1, 1, 1)) # The freesurfer case - hdr.set_data_shape((too_big, 1, 1)) + with suppress_warnings(): + hdr.set_data_shape((too_big, 1, 1)) assert_equal(hdr.get_data_shape(), (too_big, 1, 1)) assert_array_equal(hdr['dim'][:4], [3, -1, 1, 1]) assert_equal(hdr['glmin'], too_big) @@ -270,7 +271,8 @@ def test_freesurfer_hack(self): assert_raises(HeaderDataError, hdr.set_data_shape, (1, 1, too_big)) # Outside range of glmin raises error far_too_big = int(np.iinfo(glmin).max) + 1 - hdr.set_data_shape((far_too_big-1, 1, 1)) + with suppress_warnings(): + hdr.set_data_shape((far_too_big-1, 1, 1)) assert_equal(hdr.get_data_shape(), (far_too_big-1, 1, 1)) assert_raises(HeaderDataError, hdr.set_data_shape, (far_too_big,1,1)) # glmin of zero raises error (implausible vector length) @@ -280,7 +282,8 @@ def test_freesurfer_hack(self): # Lists or tuples or arrays will work for setting shape for shape in ((too_big-1, 1, 1), (too_big, 1, 1)): for constructor in (list, tuple, np.array): - hdr.set_data_shape(constructor(shape)) + with suppress_warnings(): + hdr.set_data_shape(constructor(shape)) assert_equal(hdr.get_data_shape(), shape) def test_qform_sform(self): diff --git a/nibabel/tests/test_round_trip.py b/nibabel/tests/test_round_trip.py index 0b1a593afa..52c29c98cf 100644 --- a/nibabel/tests/test_round_trip.py +++ b/nibabel/tests/test_round_trip.py @@ -156,7 +156,8 @@ def check_arr(test_id, V_in, in_type, out_type, scaling_type): # Error from calculation of inter inter_err = ulp(scaling_type(inter)) # Max abs error from floating point - Ai = arr - scaling_type(inter) + with np.errstate(over='ignore'): + Ai = arr - scaling_type(inter) Ais = Ai / scaling_type(slope) exp_abs_err = inting_err + inter_err + ( big_bad_ulp(Ai) + big_bad_ulp(Ais)) diff --git a/nibabel/tests/test_scaling.py b/nibabel/tests/test_scaling.py index 29749a60ea..1554311231 100644 --- a/nibabel/tests/test_scaling.py +++ b/nibabel/tests/test_scaling.py @@ -15,6 +15,7 @@ from ..volumeutils import (calculate_scale, scale_min_max, finite_range, apply_read_scaling, array_to_file, array_from_file) from ..casting import type_info +from ..testing import suppress_warnings from numpy.testing import (assert_array_almost_equal, assert_array_equal) @@ -241,7 +242,8 @@ def test_scaling_in_abstract(): ): for in_type in np.sctypes[category0]: for out_type in np.sctypes[category1]: - check_int_a2f(in_type, out_type) + with suppress_warnings(): # overflow + check_int_a2f(in_type, out_type) def check_int_a2f(in_type, out_type): diff --git a/nibabel/tests/test_spatialimages.py b/nibabel/tests/test_spatialimages.py index 734768adbe..4ab1cd9f1f 100644 --- a/nibabel/tests/test_spatialimages.py +++ b/nibabel/tests/test_spatialimages.py @@ -10,7 +10,6 @@ """ from ..externals.six import BytesIO - import numpy as np from ..spatialimages import (Header, SpatialImage, HeaderDataError, @@ -24,6 +23,7 @@ from numpy.testing import assert_array_equal, assert_array_almost_equal from .test_helpers import bytesio_round_trip +from ..testing import suppress_warnings def test_header_init(): @@ -292,9 +292,10 @@ def test_get_shape(self): # Assumes all possible images support int16 # See https://github.com/nipy/nibabel/issues/58 img = img_klass(np.arange(1, dtype=np.int16), np.eye(4)) - assert_equal(img.get_shape(), (1,)) - img = img_klass(np.zeros((2,3,4), np.int16), np.eye(4)) - assert_equal(img.get_shape(), (2,3,4)) + with suppress_warnings(): + assert_equal(img.get_shape(), (1,)) + img = img_klass(np.zeros((2,3,4), np.int16), np.eye(4)) + assert_equal(img.get_shape(), (2,3,4)) def test_get_data(self): # Test array image and proxy image interface diff --git a/nibabel/tests/test_spm99analyze.py b/nibabel/tests/test_spm99analyze.py index 9f8df897a3..90185efcd6 100644 --- a/nibabel/tests/test_spm99analyze.py +++ b/nibabel/tests/test_spm99analyze.py @@ -32,7 +32,7 @@ from nose.tools import assert_true, assert_false, assert_equal, assert_raises -from ..testing import assert_allclose_safely +from ..testing import assert_allclose_safely, suppress_warnings from . import test_analyze from .test_helpers import (bytesio_round_trip, bytesio_filemap, bz2_mio_error) @@ -330,7 +330,8 @@ def test_no_scaling(self): img.set_data_dtype(out_dtype) img.header.set_slope_inter(slope, inter) rt_img = bytesio_round_trip(img) - back_arr = rt_img.get_data() + with suppress_warnings(): # invalid mult + back_arr = rt_img.get_data() exp_back = arr.copy() if in_dtype not in COMPLEX_TYPES: exp_back = arr.astype(float) @@ -341,8 +342,9 @@ def test_no_scaling(self): else: exp_back = exp_back.astype(out_dtype) # Allow for small differences in large numbers - assert_allclose_safely(back_arr, - exp_back * slope + inter) + with suppress_warnings(): # invalid value + assert_allclose_safely(back_arr, + exp_back * slope + inter) def test_write_scaling(self): # Check writes with scaling set diff --git a/nibabel/tests/test_utils.py b/nibabel/tests/test_utils.py index 47a3c77e23..c5abe762e8 100644 --- a/nibabel/tests/test_utils.py +++ b/nibabel/tests/test_utils.py @@ -48,7 +48,8 @@ from nose.tools import assert_true, assert_equal, assert_raises -from ..testing import assert_dt_equal, assert_allclose_safely +from ..testing import (assert_dt_equal, assert_allclose_safely, + suppress_warnings) #: convenience variables for numpy types FLOAT_TYPES = np.sctypes['float'] @@ -125,9 +126,9 @@ def test_array_to_file(): for code in '<>': ndt = dt.newbyteorder(code) for allow_intercept in (True, False): - scale, intercept, mn, mx = calculate_scale(arr, - ndt, - allow_intercept) + with suppress_warnings(): # deprecated + scale, intercept, mn, mx = \ + calculate_scale(arr, ndt, allow_intercept) data_back = write_return(arr, str_io, ndt, 0, intercept, scale) assert_array_almost_equal(arr, data_back) @@ -188,7 +189,8 @@ def test_a2f_min_max(): assert_array_equal(data_back * -0.5 + 1, [1, 1, 2, 2]) # Check complex numbers arr = np.arange(4, dtype=np.complex64) + 100j - data_back = write_return(arr, str_io, out_dt, 0, 0, 1, 1, 2) + with suppress_warnings(): # cast to real + data_back = write_return(arr, str_io, out_dt, 0, 0, 1, 1, 2) assert_array_equal(data_back, [1, 1, 2, 2]) @@ -307,8 +309,9 @@ def test_a2f_big_scalers(): # We check whether the routine correctly clips extreme values. # We need nan2zero=False because we can't represent 0 in the input, given # the scaling and the output range. - array_to_file(arr, str_io, np.int8, intercept=np.float32(2**120), - nan2zero=False) + with suppress_warnings(): # overflow + array_to_file(arr, str_io, np.int8, intercept=np.float32(2**120), + nan2zero=False) data_back = array_from_file(arr.shape, np.int8, str_io) assert_array_equal(data_back, [-128, -128, 127]) # Scales also if mx, mn specified? Same notes and complaints as for the test @@ -320,8 +323,9 @@ def test_a2f_big_scalers(): assert_array_equal(data_back, [-128, -128, 127]) # And if slope causes overflow? str_io.seek(0) - array_to_file(arr, str_io, np.int8, divslope=np.float32(0.5)) - data_back = array_from_file(arr.shape, np.int8, str_io) + with suppress_warnings(): # overflow in divide + array_to_file(arr, str_io, np.int8, divslope=np.float32(0.5)) + data_back = array_from_file(arr.shape, np.int8, str_io) assert_array_equal(data_back, [-128, 0, 127]) # with mn, mx specified? str_io.seek(0) @@ -370,25 +374,26 @@ def test_a2f_scaled_unscaled(): divslope=divslope, intercept=intercept) continue - back_arr = write_return(arr, fobj, - out_dtype=out_dtype, - divslope=divslope, - intercept=intercept) - exp_back = arr.copy() - if out_dtype in IUINT_TYPES: - exp_back[np.isnan(exp_back)] = 0 - if in_dtype not in COMPLEX_TYPES: - exp_back = exp_back.astype(float) - if intercept != 0: - exp_back -= intercept - if divslope != 1: - exp_back /= divslope - if out_dtype in IUINT_TYPES: - exp_back = np.round(exp_back).astype(float) - exp_back = np.clip(exp_back, *shared_range(float, out_dtype)) - exp_back = exp_back.astype(out_dtype) - else: - exp_back = exp_back.astype(out_dtype) + with suppress_warnings(): # cast to real + back_arr = write_return(arr, fobj, + out_dtype=out_dtype, + divslope=divslope, + intercept=intercept) + exp_back = arr.copy() + if out_dtype in IUINT_TYPES: + exp_back[np.isnan(exp_back)] = 0 + if in_dtype not in COMPLEX_TYPES: + exp_back = exp_back.astype(float) + if intercept != 0: + exp_back -= intercept + if divslope != 1: + exp_back /= divslope + if out_dtype in IUINT_TYPES: + exp_back = np.round(exp_back).astype(float) + exp_back = np.clip(exp_back, *shared_range(float, out_dtype)) + exp_back = exp_back.astype(out_dtype) + else: + exp_back = exp_back.astype(out_dtype) # Allow for small differences in large numbers assert_allclose_safely(back_arr, exp_back) diff --git a/nibabel/tests/test_wrapstruct.py b/nibabel/tests/test_wrapstruct.py index 17093e2553..ee3bfafde7 100644 --- a/nibabel/tests/test_wrapstruct.py +++ b/nibabel/tests/test_wrapstruct.py @@ -24,7 +24,7 @@ _field_recoders -> field_recoders ''' import logging - +import warnings import numpy as np from ..externals.six import BytesIO, StringIO @@ -169,7 +169,7 @@ def log_chk(self, hdr, level): logger.addHandler(handler) str_io.truncate(0) hdrc = hdr.copy() - if level == 0: # Should never log or raise error + if level == 0: # Should never log or raise error logger.setLevel(0) hdrc.check_fix(logger=logger, error_level=0) assert_equal(str_io.getvalue(), '') @@ -228,7 +228,8 @@ def test_bytes(self): bb_bad = self.get_bad_bb() if bb_bad is None: return - assert_raises(HeaderDataError, self.header_class, bb_bad) + with imageglobals.LoggingOutputSuppressor(): + assert_raises(HeaderDataError, self.header_class, bb_bad) # now slips past without check _ = self.header_class(bb_bad, check=False) diff --git a/nibabel/volumeutils.py b/nibabel/volumeutils.py index 3b34ae245d..1410b728f0 100644 --- a/nibabel/volumeutils.py +++ b/nibabel/volumeutils.py @@ -589,7 +589,7 @@ def array_to_file(data, fileobj, out_dtype=None, offset=0, # Shield special case div_none = divslope is None if not np.all( - np.isfinite((intercept, 1.0 if div_none else divslope))): + np.isfinite((intercept, 1.0 if div_none else divslope))): raise ValueError('divslope and intercept must be finite') if divslope == 0: raise ValueError('divslope cannot be zero') @@ -602,15 +602,14 @@ def array_to_file(data, fileobj, out_dtype=None, offset=0, if not offset is None: seek_tell(fileobj, offset) if (div_none or - (mn, mx) == (0, 0) or - (None not in (mn, mx) and mx < mn) - ): + (mn, mx) == (0, 0) or + ((mn is not None and mx is not None) and mx < mn)): write_zeros(fileobj, data.size * out_dtype.itemsize) return if not order in 'FC': raise ValueError('Order should be one of F or C') # Simple cases - pre_clips = None if (mn, mx) == (None, None) else (mn, mx) + pre_clips = None if (mn is None and mx is None) else (mn, mx) null_scaling = (intercept == 0 and divslope == 1) if in_dtype.type == np.void: if not null_scaling: