本文整理汇总了Python中nilearn._utils.testing.assert_raises_regex函数的典型用法代码示例。如果您正苦于以下问题:Python assert_raises_regex函数的具体用法?Python assert_raises_regex怎么用?Python assert_raises_regex使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了assert_raises_regex函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_design_matrix0c
def test_design_matrix0c():
# test design matrix creation when regressors are provided manually
tr = 1.0
frame_times = np.linspace(0, 127 * tr, 128)
ax = np.random.randn(128, 4)
_, X, names = check_design_matrix(
make_design_matrix(frame_times, drift_model="polynomial", drift_order=3, add_regs=ax)
)
assert_almost_equal(X[:, 0], ax[:, 0])
ax = np.random.randn(127, 4)
assert_raises_regex(
AssertionError,
"Incorrect specification of additional regressors:.",
make_design_matrix,
frame_times,
add_regs=ax,
)
ax = np.random.randn(128, 4)
assert_raises_regex(
ValueError,
"Incorrect number of additional regressor names.",
make_design_matrix,
frame_times,
add_regs=ax,
add_reg_names="",
)
示例2: test_small_radius
def test_small_radius():
affine = np.eye(4)
shape = (3, 3, 3)
data = np.random.random(shape)
mask = np.zeros(shape)
mask[1, 1, 1] = 1
mask[2, 2, 2] = 1
affine = np.eye(4) * 1.2
seed = (1.4, 1.4, 1.4)
masker = NiftiSpheresMasker([seed], radius=0.1,
mask_img=nibabel.Nifti1Image(mask, affine))
masker.fit_transform(nibabel.Nifti1Image(data, affine))
# Test if masking is taken into account
mask[1, 1, 1] = 0
mask[1, 1, 0] = 1
masker = NiftiSpheresMasker([seed], radius=0.1,
mask_img=nibabel.Nifti1Image(mask, affine))
assert_raises_regex(ValueError, 'Sphere around seed #0 is empty',
masker.fit_transform,
nibabel.Nifti1Image(data, affine))
masker = NiftiSpheresMasker([seed], radius=1.6,
mask_img=nibabel.Nifti1Image(mask, affine))
masker.fit_transform(nibabel.Nifti1Image(data, affine))
示例3: test_check_parameters_transform
def test_check_parameters_transform():
rng = np.random.RandomState(0)
data = np.ones((10, 11, 12, 10))
data[6, 7, 8] = 2
data[9, 10, 11] = 3
# single image
fmri_img = nibabel.Nifti1Image(data, affine=np.eye(4))
# single confound
confounds = rng.randn(*(10, 3))
# Tests to check whether imgs, confounds returned are
# list or not. Pre-check in parameters to work for list
# of multi images and multi confounds
imgs, confounds, single_subject = _check_parameters_transform(fmri_img,
confounds)
assert_true(isinstance(imgs, (list, tuple)))
assert_true(isinstance(confounds, (list, tuple)))
assert_true(single_subject, True)
# multi images
fmri_imgs = [fmri_img, fmri_img, fmri_img]
confounds_list = [confounds, confounds, confounds]
imgs, confounds, _ = _check_parameters_transform(fmri_imgs, confounds_list)
assert_equal(imgs, fmri_imgs)
assert_equal(confounds_list, confounds)
# Test the error when length of images and confounds are not same
msg = ("Number of confounds given does not match with the "
"given number of images")
not_match_confounds_list = [confounds, confounds]
assert_raises_regex(ValueError, msg, _check_parameters_transform,
fmri_imgs, not_match_confounds_list)
示例4: test_get_dataset_dir
def test_get_dataset_dir():
# testing folder creation under different environments, enforcing
# a custom clean install
os.environ.pop('NILEARN_DATA', None)
os.environ.pop('NILEARN_SHARED_DATA', None)
expected_base_dir = os.path.expanduser('~/nilearn_data')
data_dir = datasets._get_dataset_dir('test', verbose=0)
assert_equal(data_dir, os.path.join(expected_base_dir, 'test'))
assert os.path.exists(data_dir)
shutil.rmtree(data_dir)
expected_base_dir = os.path.join(tmpdir, 'test_nilearn_data')
os.environ['NILEARN_DATA'] = expected_base_dir
data_dir = datasets._get_dataset_dir('test', verbose=0)
assert_equal(data_dir, os.path.join(expected_base_dir, 'test'))
assert os.path.exists(data_dir)
shutil.rmtree(data_dir)
expected_base_dir = os.path.join(tmpdir, 'nilearn_shared_data')
os.environ['NILEARN_SHARED_DATA'] = expected_base_dir
data_dir = datasets._get_dataset_dir('test', verbose=0)
assert_equal(data_dir, os.path.join(expected_base_dir, 'test'))
assert os.path.exists(data_dir)
shutil.rmtree(data_dir)
expected_base_dir = os.path.join(tmpdir, 'env_data')
os.environ['MY_DATA'] = expected_base_dir
data_dir = datasets._get_dataset_dir('test', env_vars=['MY_DATA'],
verbose=0)
assert_equal(data_dir, os.path.join(expected_base_dir, 'test'))
assert os.path.exists(data_dir)
shutil.rmtree(data_dir)
no_write = os.path.join(tmpdir, 'no_write')
os.makedirs(no_write)
os.chmod(no_write, 0o400)
# Verify that default is used if non writeable dir
os.environ['MY_DATA'] = no_write
expected_base_dir = os.path.join(tmpdir, 'nilearn_shared_data')
os.environ['NILEARN_SHARED_DATA'] = expected_base_dir
data_dir = datasets._get_dataset_dir('test', env_vars=['MY_DATA'],
verbose=0)
assert_equal(data_dir, os.path.join(expected_base_dir, 'test'))
assert os.path.exists(data_dir)
shutil.rmtree(data_dir)
# Verify exception is raised on read-only directories
assert_raises_regex(OSError, 'Permission denied',
datasets._get_dataset_dir, 'test', no_write,
verbose=0)
# Verify exception for a path which exists and is a file
test_file = os.path.join(tmpdir, 'some_file')
with open(test_file, 'w') as out:
out.write('abcfeg')
assert_raises_regex(OSError, 'Not a directory',
datasets._get_dataset_dir, 'test', test_file,
verbose=0)
示例5: test_plot_surf_error
def test_plot_surf_error():
# Axes3DSubplot has no attribute 'plot_trisurf' for older versions of
# matplotlib
if LooseVersion(matplotlib.__version__) <= LooseVersion('1.3.1'):
raise SkipTest
mesh = _generate_surf()
rng = np.random.RandomState(0)
# Wrong inputs for view or hemi
assert_raises_regex(ValueError, 'view must be one of',
plot_surf, mesh, view='middle')
assert_raises_regex(ValueError, 'hemi must be one of',
plot_surf, mesh, hemi='lft')
# Wrong size of background image
assert_raises_regex(ValueError,
'bg_map does not have the same number of vertices',
plot_surf, mesh,
bg_map=rng.randn(mesh[0].shape[0] - 1, ))
# Wrong size of surface data
assert_raises_regex(ValueError,
'surf_map does not have the same number of vertices',
plot_surf, mesh,
surf_map=rng.randn(mesh[0].shape[0] + 1, ))
assert_raises_regex(ValueError,
'surf_map can only have one dimension', plot_surf,
mesh, surf_map=rng.randn(mesh[0].shape[0], 2))
示例6: test_plot_surf_error
def test_plot_surf_error():
mesh = _generate_surf()
rng = np.random.RandomState(0)
# Wrong inputs for view or hemi
assert_raises_regex(ValueError, 'view must be one of',
plot_surf, mesh, view='middle')
assert_raises_regex(ValueError, 'hemi must be one of',
plot_surf, mesh, hemi='lft')
# Wrong size of background image
assert_raises_regex(ValueError,
'bg_map does not have the same number of vertices',
plot_surf, mesh,
bg_map=rng.randn(mesh[0].shape[0] - 1, ))
# Wrong size of surface data
assert_raises_regex(ValueError,
'surf_map does not have the same number of vertices',
plot_surf, mesh,
surf_map=rng.randn(mesh[0].shape[0] + 1, ))
assert_raises_regex(ValueError,
'surf_map can only have one dimension', plot_surf,
mesh, surf_map=rng.randn(mesh[0].shape[0], 2))
示例7: test_check_threshold
def test_check_threshold():
adjacency_matrix = np.array([[1., 2.],
[2., 1.]])
name = 'edge_threshold'
calculate = 'fast_abs_percentile'
# a few not correctly formatted strings for 'edge_threshold'
wrong_edge_thresholds = ['0.1', '10', '10.2.3%', 'asdf%']
for wrong_edge_threshold in wrong_edge_thresholds:
assert_raises_regex(ValueError,
'{0}.+should be a number followed by '
'the percent sign'.format(name),
check_threshold,
wrong_edge_threshold, adjacency_matrix,
calculate, name)
threshold = object()
assert_raises_regex(TypeError,
'{0}.+should be either a number or a string'.format(name),
check_threshold,
threshold, adjacency_matrix,
calculate, name)
# To check if it also gives the score which is expected
assert_true(1. < check_threshold("50%", adjacency_matrix,
percentile_calculate=fast_abs_percentile,
name='threshold') <= 2.)
示例8: test_index_img
def test_index_img():
img_3d = nibabel.Nifti1Image(np.ones((3, 4, 5)), np.eye(4))
testing.assert_raises_regex(TypeError, '4D Niimg-like',
image.index_img, img_3d, 0)
affine = np.array([[1., 2., 3., 4.],
[5., 6., 7., 8.],
[9., 10., 11., 12.],
[0., 0., 0., 1.]])
img_4d, _ = testing.generate_fake_fmri(affine=affine)
fourth_dim_size = img_4d.shape[3]
tested_indices = (list(range(fourth_dim_size)) +
[slice(2, 8, 2), [1, 2, 3, 2], [],
(np.arange(fourth_dim_size) % 3) == 1])
for i in tested_indices:
this_img = image.index_img(img_4d, i)
expected_data_3d = img_4d.get_data()[..., i]
assert_array_equal(this_img.get_data(),
expected_data_3d)
assert_array_equal(this_img.get_affine(),
img_4d.get_affine())
for i in [fourth_dim_size, - fourth_dim_size - 1,
[0, fourth_dim_size],
np.repeat(True, fourth_dim_size + 1)]:
testing.assert_raises_regex(
IndexError,
'out of bounds|invalid index|out of range',
image.index_img, img_4d, i)
示例9: test_fail_fetch_atlas_harvard_oxford
def test_fail_fetch_atlas_harvard_oxford():
# specify non-existing atlas item
assert_raises_regex(ValueError, 'Invalid atlas name',
atlas.fetch_atlas_harvard_oxford,
'not_inside')
# specify existing atlas item
target_atlas = 'cort-maxprob-thr0-1mm'
target_atlas_fname = 'HarvardOxford-' + target_atlas + '.nii.gz'
ho_dir = os.path.join(tst.tmpdir, 'fsl', 'data', 'atlases')
os.makedirs(ho_dir)
nifti_dir = os.path.join(ho_dir, 'HarvardOxford')
os.makedirs(nifti_dir)
target_atlas_nii = os.path.join(nifti_dir, target_atlas_fname)
struct.load_mni152_template().to_filename(target_atlas_nii)
dummy = open(os.path.join(ho_dir, 'HarvardOxford-Cortical.xml'), 'w')
dummy.write("<?xml version='1.0' encoding='us-ascii'?> "
"<metadata>"
"</metadata>")
dummy.close()
ho = atlas.fetch_atlas_harvard_oxford(target_atlas,
data_dir=tst.tmpdir)
assert_true(isinstance(nibabel.load(ho.maps), nibabel.Nifti1Image))
assert_true(isinstance(ho.labels, np.ndarray))
assert_true(len(ho.labels) > 0)
示例10: test_nifti_maps_masker_overlap
def test_nifti_maps_masker_overlap():
# Test resampling in NiftiMapsMasker
affine = np.eye(4)
shape = (5, 5, 5)
length = 10
fmri_img, _ = generate_random_img(shape, affine=affine,
length=length)
non_overlapping_maps = np.zeros(shape + (2,))
non_overlapping_maps[:2, :, :, 0] = 1.
non_overlapping_maps[2:, :, :, 1] = 1.
non_overlapping_maps_img = nibabel.Nifti1Image(non_overlapping_maps,
affine)
overlapping_maps = np.zeros(shape + (2,))
overlapping_maps[:3, :, :, 0] = 1.
overlapping_maps[2:, :, :, 1] = 1.
overlapping_maps_img = nibabel.Nifti1Image(overlapping_maps, affine)
overlapping_masker = NiftiMapsMasker(non_overlapping_maps_img,
allow_overlap=True)
overlapping_masker.fit_transform(fmri_img)
overlapping_masker = NiftiMapsMasker(overlapping_maps_img,
allow_overlap=True)
overlapping_masker.fit_transform(fmri_img)
non_overlapping_masker = NiftiMapsMasker(non_overlapping_maps_img,
allow_overlap=False)
non_overlapping_masker.fit_transform(fmri_img)
non_overlapping_masker = NiftiMapsMasker(overlapping_maps_img,
allow_overlap=False)
assert_raises_regex(ValueError, 'Overlap detected',
non_overlapping_masker.fit_transform, fmri_img)
示例11: test_load_surf_data_file_glob
def test_load_surf_data_file_glob():
data2D = np.ones((20, 3))
fnames = []
for f in range(3):
fnames.append(tempfile.mktemp(prefix='glob_%s_' % f, suffix='.gii'))
data2D[:, f] *= f
if LooseVersion(nb.__version__) > LooseVersion('2.0.2'):
darray = gifti.GiftiDataArray(data=data2D[:, f])
else:
# Avoid a bug in nibabel 1.2.0 where GiftiDataArray were not
# initialized properly:
darray = gifti.GiftiDataArray.from_array(data2D[:, f],
intent='t test')
gii = gifti.GiftiImage(darrays=[darray])
gifti.write(gii, fnames[f])
assert_array_equal(load_surf_data(os.path.join(os.path.dirname(fnames[0]),
"glob*.gii")), data2D)
# make one more gii file that has more than one dimension
fnames.append(tempfile.mktemp(prefix='glob_3_', suffix='.gii'))
if LooseVersion(nb.__version__) > LooseVersion('2.0.2'):
darray1 = gifti.GiftiDataArray(data=np.ones((20, )))
darray2 = gifti.GiftiDataArray(data=np.ones((20, )))
darray3 = gifti.GiftiDataArray(data=np.ones((20, )))
else:
# Avoid a bug in nibabel 1.2.0 where GiftiDataArray were not
# initialized properly:
darray1 = gifti.GiftiDataArray.from_array(np.ones((20, )),
intent='t test')
darray2 = gifti.GiftiDataArray.from_array(np.ones((20, )),
intent='t test')
darray3 = gifti.GiftiDataArray.from_array(np.ones((20, )),
intent='t test')
gii = gifti.GiftiImage(darrays=[darray1, darray2, darray3])
gifti.write(gii, fnames[-1])
data2D = np.concatenate((data2D, np.ones((20, 3))), axis=1)
assert_array_equal(load_surf_data(os.path.join(os.path.dirname(fnames[0]),
"glob*.gii")), data2D)
# make one more gii file that has a different shape in axis=0
fnames.append(tempfile.mktemp(prefix='glob_4_', suffix='.gii'))
if LooseVersion(nb.__version__) > LooseVersion('2.0.2'):
darray = gifti.GiftiDataArray(data=np.ones((15, 1)))
else:
# Avoid a bug in nibabel 1.2.0 where GiftiDataArray were not
# initialized properly:
darray = gifti.GiftiDataArray.from_array(np.ones(15, 1),
intent='t test')
gii = gifti.GiftiImage(darrays=[darray])
gifti.write(gii, fnames[-1])
assert_raises_regex(ValueError,
'files must contain data with the same shape',
load_surf_data,
os.path.join(os.path.dirname(fnames[0]), "*.gii"))
for f in fnames:
os.remove(f)
示例12: test_iter_check_niimgs
def test_iter_check_niimgs():
no_file_matching = "No files matching path: %s"
affine = np.eye(4)
img_4d = Nifti1Image(np.ones((10, 10, 10, 4)), affine)
img_2_4d = [[img_4d, img_4d]]
for empty in ((), [], (i for i in ()), [i for i in ()]):
assert_raises_regex(ValueError,
"Input niimgs list is empty.",
list, _iter_check_niimg(empty))
nofile_path = "/tmp/nofile"
assert_raises_regex(ValueError,
no_file_matching % nofile_path,
list, _iter_check_niimg(nofile_path))
# Create a test file
filename = tempfile.mktemp(prefix="nilearn_test",
suffix=".nii",
dir=None)
img_4d.to_filename(filename)
niimgs = list(_iter_check_niimg([filename]))
assert_array_equal(niimgs[0].get_data(),
_utils.check_niimg(img_4d).get_data())
del img_4d
del niimgs
os.remove(filename)
# Regular case
niimgs = list(_iter_check_niimg(img_2_4d))
assert_array_equal(niimgs[0].get_data(),
_utils.check_niimg(img_2_4d).get_data())
示例13: test_auto_mask
def test_auto_mask():
# This mostly a smoke test
data = np.zeros((9, 9, 9))
data[2:-2, 2:-2, 2:-2] = 10
img = Nifti1Image(data, np.eye(4))
masker = MultiNiftiMasker(mask_args=dict(opening=0))
# Check that if we have not fit the masker we get a intelligible
# error
assert_raises(ValueError, masker.transform, [[img, ]])
# Check error return due to bad data format
assert_raises(ValueError, masker.fit, img)
# Smoke test the fit
masker.fit([[img]])
# Test mask intersection
data2 = np.zeros((9, 9, 9))
data2[1:-3, 1:-3, 1:-3] = 10
img2 = Nifti1Image(data2, np.eye(4))
masker.fit([[img, img2]])
assert_array_equal(masker.mask_img_.get_data(),
np.logical_or(data, data2))
# Smoke test the transform
masker.transform([[img, ]])
# It should also work with a 3D image
masker.transform(img)
# check exception when transform() called without prior fit()
masker2 = MultiNiftiMasker(mask_img=img)
assert_raises_regex(
ValueError,
'has not been fitted. ', masker2.transform, img2)
示例14: test_base_decomposition
def test_base_decomposition():
shape = (6, 8, 10, 5)
affine = np.eye(4)
rng = np.random.RandomState(0)
data = []
for i in range(8):
this_data = rng.normal(size=shape)
# Create fake activation to get non empty mask
this_data[2:4, 2:4, 2:4, :] += 10
data.append(nibabel.Nifti1Image(this_data, affine))
mask = nibabel.Nifti1Image(np.ones(shape[:3], dtype=np.int8), affine)
masker = MultiNiftiMasker(mask_img=mask)
base_decomposition = BaseDecomposition(mask=masker, n_components=3)
base_decomposition.fit(data)
assert_true(base_decomposition.mask_img_ == mask)
assert_true(base_decomposition.mask_img_ ==
base_decomposition.masker_.mask_img_)
# Testing fit on data
masker = MultiNiftiMasker()
base_decomposition = BaseDecomposition(mask=masker, n_components=3)
base_decomposition.fit(data)
assert_true(base_decomposition.mask_img_ ==
base_decomposition.masker_.mask_img_)
assert_raises_regex(ValueError,
"Object has no components_ attribute. "
"This may be because "
"BaseDecomposition is directly "
"being used.",
base_decomposition.transform, data)
assert_raises_regex(ValueError,
'Need one or more Niimg-like objects as input, '
'an empty list was given.',
base_decomposition.fit, [])
示例15: test_fail_fetch_harvard_oxford
def test_fail_fetch_harvard_oxford():
# specify non-existing atlas item
assert_raises_regex(ValueError, 'Invalid atlas name',
datasets.fetch_harvard_oxford, 'not_inside')
# specify existing atlas item
target_atlas = 'cort-maxprob-thr0-1mm'
target_atlas_fname = 'HarvardOxford-' + target_atlas + '.nii.gz'
HO_dir = os.path.join(tmpdir, 'harvard_oxford')
os.mkdir(HO_dir)
nifti_dir = os.path.join(HO_dir, 'HarvardOxford')
os.mkdir(nifti_dir)
target_atlas_nii = os.path.join(nifti_dir, target_atlas_fname)
datasets.load_mni152_template().to_filename(target_atlas_nii)
dummy = open(os.path.join(HO_dir, 'HarvardOxford-Cortical.xml'), 'w')
dummy.write("<?xml version='1.0' encoding='us-ascii'?> "
"<metadata>"
"</metadata>")
dummy.close()
out_nii, arr = datasets.fetch_harvard_oxford(target_atlas, data_dir=tmpdir)
assert_true(isinstance(nibabel.load(out_nii), nibabel.Nifti1Image))
assert_true(isinstance(arr, np.ndarray))
assert_true(len(arr) > 0)