• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python testing.assert_raises_regex函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中nilearn._utils.testing.assert_raises_regex函数的典型用法代码示例。如果您正苦于以下问题:Python assert_raises_regex函数的具体用法?Python assert_raises_regex怎么用?Python assert_raises_regex使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了assert_raises_regex函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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="",
    )
开发者ID:mrahim,项目名称:nistats,代码行数:26,代码来源:test_dmtx.py


示例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))
开发者ID:jeromedockes,项目名称:nilearn,代码行数:28,代码来源:test_nifti_spheres_masker.py


示例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)
开发者ID:bthirion,项目名称:nilearn,代码行数:32,代码来源:test_parcellations.py


示例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)
开发者ID:DavidDJChen,项目名称:nilearn,代码行数:60,代码来源:test_datasets.py


示例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))
开发者ID:robbisg,项目名称:nilearn,代码行数:29,代码来源:test_surf_plotting.py


示例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))
开发者ID:miykael,项目名称:nilearn,代码行数:25,代码来源:test_surf_plotting.py


示例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.)
开发者ID:carlosf,项目名称:nilearn,代码行数:26,代码来源:test_displays.py


示例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)
开发者ID:carlosf,项目名称:nilearn,代码行数:30,代码来源:test_image.py


示例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)
开发者ID:GaelVaroquaux,项目名称:nilearn,代码行数:30,代码来源:test_atlas.py


示例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)
开发者ID:AlexandreAbraham,项目名称:nilearn,代码行数:33,代码来源:test_nifti_maps_masker.py


示例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)
开发者ID:mrahim,项目名称:nilearn,代码行数:60,代码来源:test_surface.py


示例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())
开发者ID:GaelVaroquaux,项目名称:nilearn,代码行数:32,代码来源:test_niimg_conversions.py


示例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)
开发者ID:AlexandreAbraham,项目名称:nilearn,代码行数:32,代码来源:test_multi_nifti_masker.py


示例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, [])
开发者ID:GaelVaroquaux,项目名称:nilearn,代码行数:35,代码来源:test_base.py


示例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)
开发者ID:DavidDJChen,项目名称:nilearn,代码行数:28,代码来源:test_datasets.py


示例16: test_masker_attributes_with_fit

def test_masker_attributes_with_fit():
    # Test base module at sub-class
    data, mask_img, components, rng = _make_canica_test_data(n_subjects=3)
    # Passing mask_img
    canica = CanICA(n_components=3, mask=mask_img, random_state=0)
    canica.fit(data)
    assert_true(canica.mask_img_ == mask_img)
    assert_true(canica.mask_img_ == canica.masker_.mask_img_)
    # Passing masker
    masker = MultiNiftiMasker(mask_img=mask_img)
    canica = CanICA(n_components=3, mask=masker, random_state=0)
    canica.fit(data)
    assert_true(canica.mask_img_ == canica.masker_.mask_img_)
    canica = CanICA(mask=mask_img, n_components=3)
    assert_raises_regex(ValueError,
                        "Object has no components_ attribute. "
                        "This is probably because fit has not been called",
                        canica.transform, data)
    # Test if raises an error when empty list of provided.
    assert_raises_regex(ValueError,
                        'Need one or more Niimg-like objects as input, '
                        'an empty list was given.',
                        canica.fit, [])
    # Test passing masker arguments to estimator
    canica = CanICA(n_components=3,
                    target_affine=np.eye(4),
                    target_shape=(6, 8, 10),
                    mask_strategy='background')
    canica.fit(data)
开发者ID:bthirion,项目名称:nilearn,代码行数:29,代码来源:test_canica.py


示例17: test_check_niimg

def test_check_niimg():
    affine = np.eye(4)
    img_3d = Nifti1Image(np.ones((10, 10, 10)), affine)
    img_4d = Nifti1Image(np.ones((10, 10, 10, 4)), affine)
    img_3_3d = [[[img_3d, img_3d]]]
    img_2_4d = [[img_4d, img_4d]]

    assert_raises_regex(
        DimensionError,
        "Input data has incompatible dimensionality: "
        "Expected dimension is 2D and you provided "
        "a list of list of list of 3D images \(6D\)",
        _utils.check_niimg, img_3_3d, ensure_ndim=2)

    assert_raises_regex(
        DimensionError,
        "Input data has incompatible dimensionality: "
        "Expected dimension is 4D and you provided "
        "a list of list of 4D images \(6D\)",
        _utils.check_niimg, img_2_4d, ensure_ndim=4)

    # check data dtype equal with dtype='auto'
    img_3d_check = _utils.check_niimg(img_3d, dtype='auto')
    assert_equal(img_3d.get_data().dtype.kind, img_3d_check.get_data().dtype.kind)

    img_4d_check = _utils.check_niimg(img_4d, dtype='auto')
    assert_equal(img_4d.get_data().dtype.kind, img_4d_check.get_data().dtype.kind)
开发者ID:banilo,项目名称:nilearn,代码行数:27,代码来源:test_niimg_conversions.py


示例18: test_index_img

def test_index_img():
    img_3d = nibabel.Nifti1Image(np.ones((3, 4, 5)), np.eye(4))
    testing.assert_raises_regex(TypeError,
                                "Input data has incompatible dimensionality: "
                                "Expected dimension is 4D and you provided "
                                "a 3D image.",
                                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, _ = data_gen.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.affine, img_4d.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|boolean index',
            image.index_img, img_4d, i)
开发者ID:jeromedockes,项目名称:nilearn,代码行数:32,代码来源:test_image.py


示例19: test_vec_to_sym_matrix

def test_vec_to_sym_matrix():
    # Check error if unsuitable size
    vec = np.ones(31)
    assert_raises_regex(ValueError, 'Vector of unsuitable shape',
                        vec_to_sym_matrix, vec)

    # Check error if given diagonal shape incompatible with vec
    vec = np.ones(3)
    diagonal = np.zeros(4)
    assert_raises_regex(ValueError, 'incompatible with vector',
                        vec_to_sym_matrix, vec, diagonal)

    # Check output value is correct
    vec = np.ones(6, )
    sym = np.array([[sqrt(2), 1., 1.], [1., sqrt(2), 1.],
                    [1., 1., sqrt(2)]])
    assert_array_almost_equal(vec_to_sym_matrix(vec), sym)

    # Check output value is correct with seperate diagonal
    vec = np.ones(3, )
    diagonal = np.ones(3)
    assert_array_almost_equal(vec_to_sym_matrix(vec, diagonal=diagonal), sym)

    # Check vec_to_sym_matrix is the inverse function of sym_matrix_to_vec
    # when diagonal is included
    assert_array_almost_equal(vec_to_sym_matrix(sym_matrix_to_vec(sym)), sym)

    # when diagonal is discarded
    vec = sym_matrix_to_vec(sym, discard_diagonal=True)
    diagonal = np.diagonal(sym) / sqrt(2)
    assert_array_almost_equal(vec_to_sym_matrix(vec, diagonal=diagonal), sym)
开发者ID:bthirion,项目名称:nilearn,代码行数:31,代码来源:test_connectivity_matrices.py


示例20: test_load_surf_data_file_nii_gii

def test_load_surf_data_file_nii_gii():
    # test loading of fake data from gifti file
    filename_gii = tempfile.mktemp(suffix='.gii')
    if LooseVersion(nb.__version__) > LooseVersion('2.0.2'):
        darray = gifti.GiftiDataArray(data=np.zeros((20, )))
    else:
        # Avoid a bug in nibabel 1.2.0 where GiftiDataArray were not
        # initialized properly:
        darray = gifti.GiftiDataArray.from_array(np.zeros((20, )),
                                                 intent='t test')
    gii = gifti.GiftiImage(darrays=[darray])
    gifti.write(gii, filename_gii)
    assert_array_equal(load_surf_data(filename_gii), np.zeros((20, )))
    os.remove(filename_gii)

    # test loading of data from empty gifti file
    filename_gii_empty = tempfile.mktemp(suffix='.gii')
    gii_empty = gifti.GiftiImage()
    gifti.write(gii_empty, filename_gii_empty)
    assert_raises_regex(ValueError,
                        'must contain at least one data array',
                        load_surf_data, filename_gii_empty)
    os.remove(filename_gii_empty)

    # test loading of fake data from nifti file
    filename_nii = tempfile.mktemp(suffix='.nii')
    filename_niigz = tempfile.mktemp(suffix='.nii.gz')
    nii = nb.Nifti1Image(np.zeros((20, )), affine=None)
    nb.save(nii, filename_nii)
    nb.save(nii, filename_niigz)
    assert_array_equal(load_surf_data(filename_nii), np.zeros((20, )))
    assert_array_equal(load_surf_data(filename_niigz), np.zeros((20, )))
    os.remove(filename_nii)
    os.remove(filename_niigz)
开发者ID:mrahim,项目名称:nilearn,代码行数:34,代码来源:test_surface.py



注:本文中的nilearn._utils.testing.assert_raises_regex函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python testing.generate_fake_fmri函数代码示例发布时间:2022-05-27
下一篇:
Python utils.LOGGER类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap