def test_iconic(): """ Test the iconic registration class. """ I = Image(make_data_int16(), dummy_affine) J = Image(I.data.copy(), dummy_affine) regie = IconicRegistration(I, J) assert_raises(ValueError, regie.set_source_fov, spacing=[0,1,3])
def test_histogram_registration(): """ Test the histogram registration class. """ I = AffineImage(make_data_int16(), dummy_affine, 'ijk') J = AffineImage(I.get_data().copy(), dummy_affine, 'ijk') R = HistogramRegistration(I, J) assert_raises(ValueError, R.subsample, spacing=[0,1,3])
def test_iconic(): """ Test the iconic class. """ I = Image(make_data_int16()) J = Image(I.array.copy()) IM = IconicMatcher(I.array, J.array, I.toworld, J.toworld) assert_raises(ValueError, IM.set_field_of_view, subsampling=[0,1,3])
def test_calling_shapes(): cs2d = CS("ij") cs1d = CS("i") cm2d = CoordinateMap(cs2d, cs2d, lambda x: x + 1) cm1d2d = CoordinateMap(cs1d, cs2d, lambda x: np.concatenate((x, x), axis=-1)) at2d = AffineTransform(cs2d, cs2d, np.array([[1, 0, 1], [0, 1, 1], [0, 0, 1]])) at1d2d = AffineTransform(cs1d, cs2d, np.array([[1, 0], [0, 1], [0, 1]])) # test coordinate maps and affine transforms for xfm2d, xfm1d2d in ((cm2d, cm1d2d), (at2d, at1d2d)): arr = np.array([0, 1]) yield assert_array_equal(xfm2d(arr), [1, 2]) # test lists work too res = xfm2d([0, 1]) yield assert_array_equal(res, [1, 2]) # and return arrays (by checking shape attribute) yield assert_equal(res.shape, (2,)) # maintaining input shape arr_long = arr[None, None, :] yield assert_array_equal(xfm2d(arr_long), arr_long + 1) # wrong shape array raises error yield assert_raises(CoordinateSystemError, xfm2d, np.zeros((3,))) yield assert_raises(CoordinateSystemError, xfm2d, np.zeros((3, 3))) # 1d to 2d arr = np.array(1) yield assert_array_equal(xfm1d2d(arr), [1, 1]) arr_long = arr[None, None, None] yield assert_array_equal(xfm1d2d(arr_long), np.ones((1, 1, 2))) # wrong shape array raises error. Note 1d input requires size 1 # as final axis yield assert_raises(CoordinateSystemError, xfm1d2d, np.zeros((3,))) yield assert_raises(CoordinateSystemError, xfm1d2d, np.zeros((3, 2)))
def test_PCAMask(): # for 2 and 4D case ntotal = data['nimages'] - 1 ncomp = 5 arr4d = data['fmridata'] mask3d = data['mask'] arr2d = arr4d.reshape((-1, data['nimages'])) mask1d = mask3d.reshape((-1)) for arr, mask in (arr4d, mask3d), (arr2d, mask1d): p = pca(arr, -1, mask, ncomp=ncomp) assert_equal(p['basis_vectors'].shape, (data['nimages'], ntotal)) assert_equal(p['basis_projections'].shape, mask.shape + (ncomp,)) assert_equal(p['pcnt_var'].shape, (ntotal,)) assert_almost_equal(p['pcnt_var'].sum(), 100.) # Any reasonable datatype for mask for dt in ([np.bool_] + np.sctypes['int'] + np.sctypes['uint'] + np.sctypes['float']): p = pca(arr4d, -1, mask3d.astype(dt), ncomp=ncomp) assert_equal(p['basis_vectors'].shape, (data['nimages'], ntotal)) assert_equal(p['basis_projections'].shape, mask3d.shape + (ncomp,)) assert_equal(p['pcnt_var'].shape, (ntotal,)) assert_almost_equal(p['pcnt_var'].sum(), 100.) # Mask data shape must match assert_raises(ValueError, pca, arr4d, -1, mask1d)
def test_badfile(): filename = "bad_file.foo" # nibabel prior 2.1.0 was throwing a ImageFileError for the not-recognized # file type. >=2.1.0 give a FileNotFoundError. try: from nibabel.py3k import FileNotFoundError except ImportError: FileNotFoundError = IOError assert_raises((ImageFileError, FileNotFoundError), load_image, filename)
def test_output_dtypes(): shape = (4, 2, 3) rng = np.random.RandomState(19441217) # IN-S BD data = rng.normal(4, 20, size=shape) aff = np.diag([2.2, 3.3, 4.1, 1]) cmap = vox2mni(aff) img = Image(data, cmap) fname_root = 'my_file' with InTemporaryDirectory(): for ext in 'img', 'nii': out_fname = fname_root + '.' + ext # Default is for data to come from data dtype save_image(img, out_fname) img_back = load_image(out_fname) hdr = img_back.metadata['header'] assert_dt_no_end_equal(hdr.get_data_dtype(), np.float) del img_back # lets window re-use the file # All these types are OK for both output formats for out_dt in 'i2', 'i4', np.int16, '<f4', '>f8': # Specified output dtype save_image(img, out_fname, out_dt) img_back = load_image(out_fname) hdr = img_back.metadata['header'] assert_dt_no_end_equal(hdr.get_data_dtype(), out_dt) del img_back # windows file re-use # Output comes from data by default data_typed = data.astype(out_dt) img_again = Image(data_typed, cmap) save_image(img_again, out_fname) img_back = load_image(out_fname) hdr = img_back.metadata['header'] assert_dt_no_end_equal(hdr.get_data_dtype(), out_dt) del img_back # Even if header specifies otherwise in_hdr = Nifti1Header() in_hdr.set_data_dtype(np.dtype('c8')) img_more = Image(data_typed, cmap, metadata={'header': in_hdr}) save_image(img_more, out_fname) img_back = load_image(out_fname) hdr = img_back.metadata['header'] assert_dt_no_end_equal(hdr.get_data_dtype(), out_dt) del img_back # But can come from header if specified save_image(img_more, out_fname, dtype_from='header') img_back = load_image(out_fname) hdr = img_back.metadata['header'] assert_dt_no_end_equal(hdr.get_data_dtype(), 'c8') del img_back # u2 only OK for nifti save_image(img, 'my_file.nii', 'u2') img_back = load_image('my_file.nii') hdr = img_back.metadata['header'] assert_dt_no_end_equal(hdr.get_data_dtype(), 'u2') # Check analyze can't save u2 datatype assert_raises(HeaderDataError, save_image, img, 'my_file.img', 'u2') del img_back
def test_image_list(): img = load_image(funcfile) exp_shape = (17, 21, 3, 20) imglst = ImageList.from_image(img, axis=-1) # Test empty ImageList emplst = ImageList() yield assert_equal(len(emplst.list), 0) # Test non-image construction a = np.arange(10) yield assert_raises(ValueError, ImageList, a) yield assert_raises(ValueError, ImageList.from_image, img, None) # check all the axes for i in range(4): order = range(4) order.remove(i) order.insert(0,i) img_re_i = img.reordered_reference(order).reordered_axes(order) imglst_i = ImageList.from_image(img, axis=i) yield assert_equal(imglst_i.list[0].shape, img_re_i.shape[1:]) # check the affine as well yield assert_almost_equal(imglst_i.list[0].affine, img_re_i.affine[1:,1:]) yield assert_equal(img.shape, exp_shape) # length of image list should match number of frames yield assert_equal(len(imglst.list), img.shape[3]) # check the affine A = np.identity(4) A[:3,:3] = img.affine[:3,:3] A[:3,-1] = img.affine[:3,-1] yield assert_almost_equal(imglst.list[0].affine, A) # Slicing an ImageList should return an ImageList sublist = imglst[2:5] yield assert_true(isinstance(sublist, ImageList)) # Except when we're indexing one element yield assert_true(isinstance(imglst[0], Image)) # Verify array interface # test __array__ yield assert_true(isinstance(np.asarray(sublist), np.ndarray)) # Test __setitem__ sublist[2] = sublist[0] yield assert_equal(np.asarray(sublist[0]).mean(), np.asarray(sublist[2]).mean()) # Test iterator for x in sublist: yield assert_true(isinstance(x, Image)) yield assert_equal(x.shape, exp_shape[:3])
def test_drop_io_dim(): aff = np.diag([1,2,3,1]) in_dims = list('ijk') out_dims = list('xyz') cm = Affine.from_params(in_dims, out_dims, aff) yield assert_raises(ValueError, drop_io_dim, cm, 'q') for i, d in enumerate(in_dims): cm2 = drop_io_dim(cm, d) yield assert_equal(cm2.ndim, (2,2)) ods = out_dims[:] ids = in_dims[:] ods.pop(i) ids.pop(i) yield assert_equal(ods, cm2.output_coords.coord_names) yield assert_equal(ids, cm2.input_coords.coord_names) a2 = cm2.affine yield assert_equal(a2.shape, (3,3)) ind_a = np.ones((4,4), dtype=np.bool) ind_a[:,i] = False ind_a[i,:] = False aff2 = cm.affine[ind_a].reshape((3,3)) yield assert_array_equal(aff2, a2) # Check non-orth case waff = np.diag([1,2,3,1]) wrong_i = (i+1) % 3 waff[wrong_i,i] = 2 # not OK if in same column as that being removed wcm = Affine.from_params(in_dims, out_dims, waff) yield assert_raises(ValueError, drop_io_dim, wcm, d) raff = np.diag([1,2,3,1]) raff[i,wrong_i] = 2 # is OK if in same row rcm = Affine.from_params(in_dims, out_dims, raff) cm2 = drop_io_dim(rcm, d) # dims out of range give error yield assert_raises(ValueError, drop_io_dim, cm, 'p') # only works for affine case cm = CoordinateMap(lambda x:x, cm.input_coords, cm.output_coords) yield assert_raises(AttributeError, drop_io_dim, cm, 'i') # Check non-square case aff = np.array([[1.,0,0,0], [0,2,0,0], [0,0,3,0], [0,0,0,1], [0,0,0,1]]) cm = Affine.from_params(in_dims, out_dims + ['t'], aff) cm2 = drop_io_dim(cm, 'i') yield assert_array_equal(cm2.affine, [[2,0,0], [0,3,0], [0,0,1], [0,0,1]]) yield assert_raises(ValueError, drop_io_dim, cm, 't')
def test_input_effects(): # Test effects of axis specifications ntotal = data['nimages'] - 1 # return full rank - mean PCA over last axis p = pos1pca(data['fmridata'], -1) assert_equal(p['basis_vectors'].shape, (data['nimages'], ntotal)) assert_equal(p['basis_projections'].shape, data['mask'].shape + (ntotal,)) assert_equal(p['pcnt_var'].shape, (ntotal,)) # Reconstructed data lacks only mean rarr = reconstruct(p['basis_vectors'], p['basis_projections'], -1) rarr = rarr + data['fmridata'].mean(-1)[...,None] # same effect if over axis 0, which is the default arr = data['fmridata'] arr = np.rollaxis(arr, -1) # Same basis once we've normalized the signs pr = pos1pca(arr) out_arr = np.rollaxis(pr['basis_projections'], 0, 4) assert_almost_equal(out_arr, p['basis_projections']) assert_almost_equal(p['basis_vectors'], pr['basis_vectors']) assert_almost_equal(p['pcnt_var'], pr['pcnt_var']) # Check axis None raises error assert_raises(ValueError, pca, data['fmridata'], None)
def test_call(): value = 10 yield assert_true(np.allclose(E.a(value), 2*value)) yield assert_true(np.allclose(E.b(value), 2*value)) # FIXME: this shape just below is not # really expected for a CoordinateMap yield assert_true(np.allclose(E.b([value]), 2*value)) yield assert_true(np.allclose(E.c(value), value/2)) yield assert_true(np.allclose(E.d(value), value/2)) value = np.array([1., 2., 3.]) yield assert_true(np.allclose(E.e(value), value)) # check that error raised for wrong shape value = np.array([1., 2.,]) yield assert_raises(CoordinateSystemError, E.e, value)
def test_input_effects(): ntotal = data['nimages'] - 1 # return full rank - mean PCA over last axis p = pca(data['fmridata'], -1) yield assert_equal( p['basis_vectors'].shape, (data['nimages'], ntotal)) yield assert_equal( p['basis_projections'].shape, data['mask'].shape + (ntotal,)) yield assert_equal(p['pcnt_var'].shape, (ntotal,)) # Reconstructed data lacks only mean rarr = reconstruct(p['basis_vectors'], p['basis_projections'], -1) rarr = rarr + data['fmridata'].mean(-1)[...,None] # same effect if over axis 0, which is the default arr = data['fmridata'] arr = np.rollaxis(arr, -1) pr = pca(arr) out_arr = np.rollaxis(pr['basis_projections'], 0, 4) yield assert_array_equal(out_arr, p['basis_projections']) yield assert_array_equal(p['basis_vectors'], pr['basis_vectors']) yield assert_array_equal(p['pcnt_var'], pr['pcnt_var']) # Check axis None raises error yield assert_raises(ValueError, pca, data['fmridata'], None)
def test_badfile(): filename = "bad_file.foo" # nibabel prior 2.1.0 was throwing ImageFileError and then more specific # FileNotFileNotFoundError which should be a subclass of IOError. # To not mess with version specific imports, checking for IOError assert_raises((ImageFileError, IOError), load_image, filename)
def test_func_smooth(): func = load_image(funcfile) smoother = LinearFilter(func.coordmap, func.shape) # should work, but currently broken : sfunc = smoother.smooth(func) assert_raises(NotImplementedError, smoother.smooth, func)
def test_no_minc(): # We can't yet get good axis names for MINC files. Check we reject these assert_raises(ValueError, load_image, 'nofile.mnc') data_path = pjoin(dirname(nib.__file__), 'tests', 'data') assert_raises(ValueError, load_image, pjoin(data_path, 'tiny.mnc'))
def test_badfile(): filename = "bad_file.foo" assert_raises(ImageFileError, load_image, filename)