Пример #1
0
def test_compute_epi_mask():
    mean_image = np.ones((9, 9, 3))
    mean_image[3:-2, 3:-2, :] = 10
    mean_image[5, 5, :] = 11
    mean_image = Nifti1Image(mean_image, np.eye(4))
    mask1 = compute_epi_mask(mean_image, opening=False)
    mask2 = compute_epi_mask(mean_image, exclude_zeros=True, opening=False)
    # With an array with no zeros, exclude_zeros should not make
    # any difference
    np.testing.assert_array_equal(get_data(mask1), get_data(mask2))
    # Check that padding with zeros does not change the extracted mask
    mean_image2 = np.zeros((30, 30, 3))
    mean_image2[3:12, 3:12, :] = get_data(mean_image)
    mean_image2 = Nifti1Image(mean_image2, np.eye(4))
    mask3 = compute_epi_mask(mean_image2, exclude_zeros=True, opening=False)
    np.testing.assert_array_equal(get_data(mask1), get_data(mask3)[3:12, 3:12])
    # However, without exclude_zeros, it does
    mask3 = compute_epi_mask(mean_image2, opening=False)
    assert not np.allclose(get_data(mask1), get_data(mask3)[3:12, 3:12])

    # Check that we get a ValueError for incorrect shape
    mean_image = np.ones((9, 9))
    mean_image[3:-3, 3:-3] = 10
    mean_image[5, 5] = 100
    mean_image = Nifti1Image(mean_image, np.eye(4))
    pytest.raises(ValueError, compute_epi_mask, mean_image)

    # Check that we get a useful warning for empty masks
    mean_image = np.zeros((9, 9, 9))
    mean_image[0, 0, 1] = -1
    mean_image[0, 0, 0] = 1.2
    mean_image[0, 0, 2] = 1.1
    mean_image = Nifti1Image(mean_image, np.eye(4))
    with pytest.warns(MaskWarning, match='Computed an empty mask'):
        compute_epi_mask(mean_image, exclude_zeros=True)
Пример #2
0
def test_dict_learning():
    data, mask_img, components, rng = _make_canica_test_data(n_subjects=8)
    masker = NiftiMasker(mask_img=mask_img).fit()
    mask = get_data(mask_img) != 0
    flat_mask = mask.ravel()
    dict_init = masker.inverse_transform(components[:, flat_mask])
    dict_learning = DictLearning(n_components=4, random_state=0,
                                 dict_init=dict_init,
                                 mask=mask_img,
                                 smoothing_fwhm=0., alpha=1)

    dict_learning_auto_init = DictLearning(n_components=4, random_state=0,
                                           mask=mask_img,
                                           smoothing_fwhm=0., n_epochs=10,
                                           alpha=1)
    maps = {}
    for estimator in [dict_learning,
                      dict_learning_auto_init]:
        estimator.fit(data)
        maps[estimator] = get_data(estimator.components_img_)
        maps[estimator] = np.reshape(
                        np.rollaxis(maps[estimator], 3, 0)[:, mask],
                        (4, flat_mask.sum()))

    masked_components = components[:, flat_mask]
    for this_dict_learning in [dict_learning]:
        these_maps = maps[this_dict_learning]
        S = np.sqrt(np.sum(masked_components ** 2, axis=1))
        S[S == 0] = 1
        masked_components /= S[:, np.newaxis]

        S = np.sqrt(np.sum(these_maps ** 2, axis=1))
        S[S == 0] = 1
        these_maps /= S[:, np.newaxis]

        K = np.abs(masked_components.dot(these_maps.T))
        recovered_maps = np.sum(K > 0.9)
        assert(recovered_maps >= 2)

    # Smoke test n_epochs > 1
    dict_learning = DictLearning(n_components=4, random_state=0,
                                 dict_init=dict_init,
                                 mask=mask_img,
                                 smoothing_fwhm=0., n_epochs=2, alpha=1)
    dict_learning.fit(data)
Пример #3
0
def significance_map(subject_scores, mask):
    """
    Parameters
    ----------
    subject_scores : list
        list of niimgs or paths to NIfTI files representing the MVPA scores for
        each subject
    mask : Niimg-like object
        boolean image giving location of voxels containing usable signals

    Returns
    -------
    t_map : numpy.ndarray
        array of t-statistic values indicating the significance of each voxel
        for condition A; same shape as the mask
    p_map : numpy.ndarray
        array of p-values associated with the t-statistics in t_map
    """

    score_maps = []
    for score_map in subject_scores:
        if isinstance(score_map, str):
            score_map = get_data(load_img(score_map))
        else:
            score_map = get_data(score_map)

        score_maps.append(np.expand_dims(score_map, axis=3))

    mask = np.mean(score_maps, axis=0).astype(bool)
    score_maps = np.concatenate(score_maps, axis=-1)
    t_map = np.zeros_like(mask, dtype=np.float64)
    p_map = np.zeros_like(mask, dtype=np.float64)
    for x in range(mask.shape[0]):
        for y in range(mask.shape[1]):
            for z in range(mask.shape[2]):
                if not mask[x][y][z]:
                    continue

                # Significance values from each subject for one voxel
                sample = score_maps[x][y][z]
                test = stats.ttest_1samp(sample, popmean=0.0)
                t_map[x][y][z] = test.statistic
                p_map[x][y][z] = test.pvalue

    return t_map, p_map
Пример #4
0
def test_pd_index_img():
    # confirm indices from pandas dataframes are handled correctly
    if 'pandas' not in sys.modules:
        raise pytest.skip(msg='Pandas not available')

    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]

    rng = np.random.RandomState(42)
    arr = rng.uniform(size=fourth_dim_size) > 0.5
    df = pd.DataFrame({"arr": arr})

    np_index_img = image.index_img(img_4d, arr)
    pd_index_img = image.index_img(img_4d, df)
    assert_array_equal(get_data(np_index_img), get_data(pd_index_img))
Пример #5
0
def test_compute_multi_gray_matter_mask():
    pytest.raises(TypeError, compute_multi_gray_matter_mask, [])

    # Check error raised if images with different shapes are given as input
    imgs = [Nifti1Image(np.ones((9, 9, 9)), np.eye(4)),
            Nifti1Image(np.ones((9, 9, 8)), np.eye(4))]
    pytest.raises(ValueError, compute_multi_gray_matter_mask, imgs)

    # Check results are the same if affine is the same
    imgs1 = [Nifti1Image(np.random.randn(9, 9, 9), np.eye(4)),
             Nifti1Image(np.random.randn(9, 9, 9), np.eye(4))]
    mask1 = compute_multi_gray_matter_mask(imgs1)

    imgs2 = [Nifti1Image(np.random.randn(9, 9, 9), np.eye(4)),
             Nifti1Image(np.random.randn(9, 9, 9), np.eye(4))]
    mask2 = compute_multi_gray_matter_mask(imgs2)

    assert_array_equal(get_data(mask1), get_data(mask2))
Пример #6
0
def get_block(image, block_height):
    N = image.get_data().astype(float)
    N -= N.min()
    if N.max() > 0: N /= N.max()
    N = (N * 256).astype('uint16')
    # ^ normalize into 0 - 256 range
    mid = len(N) // 2
    half = block_height // 2
    return N[mid - half:mid + half]
Пример #7
0
def test_mean_img_resample():
    # Test resampling in mean_img with a permutation of the axes
    rng = np.random.RandomState(42)
    data = rng.rand(5, 6, 7, 40)
    affine = np.diag((4, 3, 2, 1))
    img = nibabel.Nifti1Image(data, affine=affine)
    mean_img = nibabel.Nifti1Image(data.mean(axis=-1), affine=affine)

    target_affine = affine[:, [1, 0, 2, 3]]  # permutation of axes
    mean_img_with_resampling = image.mean_img(img,
                                              target_affine=target_affine)
    resampled_mean_image = resampling.resample_img(mean_img,
                                              target_affine=target_affine)
    assert_array_equal(get_data(resampled_mean_image),
                       get_data(mean_img_with_resampling))
    assert_array_equal(resampled_mean_image.affine,
                       mean_img_with_resampling.affine)
    assert_array_equal(mean_img_with_resampling.affine, target_affine)
Пример #8
0
def test_isnan_threshold_img_data():
    shape = (10, 10, 10)
    maps, _ = data_gen.generate_maps(shape, n_regions=2)
    data = get_data(maps)
    data[:, :, 0] = np.nan

    maps_img = nibabel.Nifti1Image(data, np.eye(4))
    # test threshold_img to converge properly when input image has nans.
    threshold_img(maps_img, threshold=0.8)
Пример #9
0
def test_crop():
    # Testing that padding of arrays and cropping of images work symmetrically
    shape = (4, 6, 2)
    data = np.ones(shape)
    padded = _pad_array(data, [3, 2, 4, 4, 5, 7])
    padd_nii = Nifti1Image(padded, np.eye(4))

    cropped = crop_img(padd_nii, pad=False)
    np.testing.assert_equal(get_data(cropped), data)
Пример #10
0
def test_smooth_img():
    # This function only checks added functionalities compared
    # to _smooth_array()
    shapes = ((10, 11, 12), (13, 14, 15))
    lengths = (17, 18)
    fwhm = (1., 2., 3.)

    img1, mask1 = data_gen.generate_fake_fmri(shape=shapes[0],
                                              length=lengths[0])
    img2, mask2 = data_gen.generate_fake_fmri(shape=shapes[1],
                                              length=lengths[1])

    for create_files in (False, True):
        with testing.write_tmp_imgs(img1, img2,
                                    create_files=create_files) as imgs:
            # List of images as input
            out = image.smooth_img(imgs, fwhm)
            assert isinstance(out, list)
            assert len(out) == 2
            for o, s, l in zip(out, shapes, lengths):
                assert o.shape == (s + (l, ))

            # Single image as input
            out = image.smooth_img(imgs[0], fwhm)
            assert isinstance(out, nibabel.Nifti1Image)
            assert out.shape == (shapes[0] + (lengths[0], ))

    # Check corner case situations when fwhm=0, See issue #1537
    # Test whether function smooth_img raises a warning when fwhm=0.
    with pytest.warns(UserWarning):
        image.smooth_img(img1, fwhm=0.)

    # Test output equal when fwhm=None and fwhm=0
    out_fwhm_none = image.smooth_img(img1, fwhm=None)
    out_fwhm_zero = image.smooth_img(img1, fwhm=0.)
    assert_array_equal(get_data(out_fwhm_none), get_data(out_fwhm_zero))

    data1 = np.zeros((10, 11, 12))
    data1[2:4, 1:5, 3:6] = 1
    data2 = np.zeros((13, 14, 15))
    data2[2:4, 1:5, 3:6] = 9
    img1_nifti2 = nibabel.Nifti2Image(data1, affine=np.eye(4))
    img2_nifti2 = nibabel.Nifti2Image(data2, affine=np.eye(4))
    out = image.smooth_img([img1_nifti2, img2_nifti2], fwhm=1.)
Пример #11
0
def test_resampling_error_checks():
    rng = np.random.RandomState(42)
    shape = (3, 2, 5, 2)
    target_shape = (5, 3, 2)
    affine = np.eye(4)
    data = rng.randint(0, 10, shape)
    img = Nifti1Image(data, affine)

    # Correct parameters: no exception
    resample_img(img, target_shape=target_shape, target_affine=affine)
    resample_img(img, target_affine=affine)

    with testing.write_tmp_imgs(img) as filename:
        resample_img(filename, target_shape=target_shape, target_affine=affine)

    # Missing parameter
    pytest.raises(ValueError, resample_img, img, target_shape=target_shape)

    # Invalid shape
    pytest.raises(ValueError, resample_img, img, target_shape=(2, 3),
                  target_affine=affine)

    # Invalid interpolation
    interpolation = 'an_invalid_interpolation'
    pattern = "interpolation must be either.+{0}".format(interpolation)
    with pytest.raises(ValueError, match=pattern):
        resample_img(img,
                     target_shape=target_shape,
                     target_affine=affine,
                     interpolation="an_invalid_interpolation"
                     )

    # Noop
    target_shape = shape[:3]

    img_r = resample_img(img, copy=False)
    assert img_r == img

    img_r = resample_img(img, copy=True)
    assert not np.may_share_memory(get_data(img_r), get_data(img))

    np.testing.assert_almost_equal(get_data(img_r), get_data(img))
    np.testing.assert_almost_equal(img_r.affine, img.affine)

    img_r = resample_img(img, target_affine=affine, target_shape=target_shape,
                         copy=False)
    assert img_r == img

    img_r = resample_img(img, target_affine=affine, target_shape=target_shape,
                         copy=True)
    assert not np.may_share_memory(get_data(img_r), get_data(img))
    np.testing.assert_almost_equal(get_data(img_r), get_data(img))
    np.testing.assert_almost_equal(img_r.affine, img.affine)
Пример #12
0
def test_new_img_like_mgz():
    """Check that new images can be generated with bool MGZ type
    This is usually when computing masks using MGZ inputs, e.g.
    when using plot_stap_map
    """

    ref_img = nibabel.load(os.path.join(datadir, 'test.mgz'))
    data = np.ones(get_data(ref_img).shape, dtype=bool)
    affine = ref_img.affine
    new_img_like(ref_img, data, affine, copy_header=False)
Пример #13
0
def test_threshold_img_copy():
    """Test the behavior of threshold_img's copy parameter."""
    img_ones = Nifti1Image(np.ones((10, 10, 10, 10)), np.eye(4))

    # Check that copy does not mutate. It returns modified copy.
    thresholded = threshold_img(img_ones, 2)  # threshold 2 > 1

    # Original img_ones should have all ones.
    assert_array_equal(get_data(img_ones), np.ones((10, 10, 10, 10)))
    # Thresholded should have all zeros.
    assert_array_equal(get_data(thresholded), np.zeros((10, 10, 10, 10)))

    # Check that not copying does mutate.
    img_to_mutate = Nifti1Image(np.ones((10, 10, 10, 10)), np.eye(4))
    thresholded = threshold_img(img_to_mutate, 2, copy=False)
    # Check that original mutates
    assert_array_equal(get_data(img_to_mutate), np.zeros((10, 10, 10, 10)))
    # And that returned value is also thresholded.
    assert_array_equal(get_data(img_to_mutate), get_data(thresholded))
Пример #14
0
def test_mask_4d():
    # Dummy mask
    mask = np.zeros((10, 10, 10), dtype=int)
    mask[3:7, 3:7, 3:7] = 1
    mask_bool = mask.astype(bool)
    mask_img = Nifti1Image(mask, np.eye(4))

    # Dummy data
    data = np.zeros((10, 10, 10, 5), dtype=int)
    data[..., 0] = 1
    data[..., 1] = 2
    data[..., 2] = 3
    data_img_4d = Nifti1Image(data, np.eye(4))
    data_imgs = [
        index_img(data_img_4d, 0),
        index_img(data_img_4d, 1),
        index_img(data_img_4d, 2)
    ]

    # check whether transform is indeed selecting niimgs subset
    sample_mask = np.array([0, 2])
    masker = NiftiMasker(mask_img=mask_img)
    masker.fit()
    data_trans = masker.transform(data_imgs, sample_mask=sample_mask)
    data_trans_img = index_img(data_img_4d, sample_mask)
    data_trans_direct = get_data(data_trans_img)[mask_bool, :]
    data_trans_direct = np.swapaxes(data_trans_direct, 0, 1)
    assert_array_equal(data_trans, data_trans_direct)

    masker = NiftiMasker(mask_img=mask_img)
    masker.fit()
    data_trans2 = masker.transform(data_img_4d, sample_mask=sample_mask)
    assert_array_equal(data_trans2, data_trans_direct)

    diff_sample_mask = np.array([2, 4])
    data_trans_img_diff = index_img(data_img_4d, diff_sample_mask)
    data_trans_direct_diff = get_data(data_trans_img_diff)[mask_bool, :]
    data_trans_direct_diff = np.swapaxes(data_trans_direct_diff, 0, 1)
    masker = NiftiMasker(mask_img=mask_img)
    masker.fit()
    data_trans3 = masker.transform(data_img_4d, sample_mask=diff_sample_mask)
    assert_array_equal(data_trans3, data_trans_direct_diff)
Пример #15
0
def test_resampling_result_axis_permutation():
    # Transform real data using easily checkable transformations
    # For now: axis permutations
    # create a cuboid full of deterministic data, padded with one
    # voxel thickness of zeros
    core_shape = (3, 5, 4)
    core_data = np.arange(np.prod(core_shape)).reshape(core_shape)
    full_data_shape = np.array(core_shape) + 2
    full_data = np.zeros(full_data_shape)
    full_data[[slice(1, 1 + s) for s in core_shape]] = core_data

    source_img = Nifti1Image(full_data, np.eye(4))

    axis_permutations = [[0, 1, 2], [1, 0, 2], [2, 1, 0], [0, 2, 1]]

    # check 3x3 transformation matrix
    for ap in axis_permutations:
        target_affine = np.eye(3)[ap]
        resampled_img = resample_img(source_img, target_affine=target_affine)

        resampled_data = get_data(resampled_img)
        what_resampled_data_should_be = full_data.transpose(ap)
        assert_array_almost_equal(resampled_data,
                                  what_resampled_data_should_be)

    # check 4x4 transformation matrix
    offset = np.array([-2, 1, -3])
    for ap in axis_permutations:
        target_affine = np.eye(4)
        target_affine[:3, :3] = np.eye(3)[ap]
        target_affine[:3, 3] = offset

        resampled_img = resample_img(source_img, target_affine=target_affine)
        resampled_data = get_data(resampled_img)
        offset_cropping = np.vstack(
            [-offset[ap][np.newaxis, :],
             np.zeros([1, 3])]).T.ravel().astype(int)
        what_resampled_data_should_be = _pad_array(full_data.transpose(ap),
                                                   list(offset_cropping))

        assert_array_almost_equal(resampled_data,
                                  what_resampled_data_should_be)
Пример #16
0
def test_mean_img():
    rng = np.random.RandomState(42)
    data1 = np.zeros((5, 6, 7))
    data2 = rng.rand(5, 6, 7)
    data3 = rng.rand(5, 6, 7, 3)
    affine = np.diag((4, 3, 2, 1))
    img1 = nibabel.Nifti1Image(data1, affine=affine)
    img2 = nibabel.Nifti1Image(data2, affine=affine)
    img3 = nibabel.Nifti1Image(data3, affine=affine)
    for imgs in ([img1, ],
                   [img1, img2],
                   [img2, img1, img2],
                   [img3, img1, img2],  # Mixture of 4D and 3D images
                  ):

        arrays = list()
        # Ground-truth:
        for img in imgs:
            img = get_data(img)
            if img.ndim == 4:
                img = np.mean(img, axis=-1)
            arrays.append(img)
        truth = np.mean(arrays, axis=0)

        mean_img = image.mean_img(imgs)
        assert_array_equal(mean_img.affine, affine)
        assert_array_equal(get_data(mean_img), truth)

        # Test with files
        with testing.write_tmp_imgs(*imgs) as imgs:
            mean_img = image.mean_img(imgs)
            assert_array_equal(mean_img.affine, affine)
            if X64:
                assert_array_equal(get_data(mean_img), truth)
            else:
                # We don't really understand but arrays are not
                # exactly equal on 32bit. Given that you can not do
                # much real world data analysis with nilearn on a
                # 32bit machine it is not worth investigating more
                assert_allclose(get_data(mean_img), truth,
                                rtol=np.finfo(truth.dtype).resolution,
                                atol=0)
Пример #17
0
def test_downsample():
    """ Test resampling with a 1/2 down-sampling affine.
    """
    rng = np.random.RandomState(42)
    shape = (6, 3, 6, 2)
    data = rng.random_sample(shape)
    affine = np.eye(4)
    rot_img = resample_img(Nifti1Image(data, affine),
                           target_affine=2 * affine,
                           interpolation='nearest')
    downsampled = data[::2, ::2, ::2, ...]
    x, y, z = downsampled.shape[:3]
    np.testing.assert_almost_equal(downsampled,
                                   get_data(rot_img)[:x, :y, :z, ...])

    rot_img_2 = resample_img(Nifti1Image(data, affine),
                             target_affine=2 * affine,
                             interpolation='nearest',
                             force_resample=True)
    np.testing.assert_almost_equal(get_data(rot_img_2), get_data(rot_img))
    # Test with non native endian data

    # Test to check that if giving non native endian data as input should
    # work as normal and expected to return the same output as above tests.

    # Big endian data ('>f8')
    for copy in [True, False]:
        rot_img = resample_img(Nifti1Image(data.astype('>f8'), affine),
                               target_affine=2 * affine,
                               interpolation='nearest',
                               copy=copy)
        np.testing.assert_almost_equal(downsampled,
                                       get_data(rot_img)[:x, :y, :z, ...])

    # Little endian data
    for copy in [True, False]:
        rot_img = resample_img(Nifti1Image(data.astype('<f8'), affine),
                               target_affine=2 * affine,
                               interpolation='nearest',
                               copy=copy)
        np.testing.assert_almost_equal(downsampled,
                                       get_data(rot_img)[:x, :y, :z, ...])
Пример #18
0
def test_compute_gray_matter_mask():
    image = Nifti1Image(np.ones((9, 9, 9)), np.eye(4))

    mask = compute_gray_matter_mask(image, threshold=-1)
    mask1 = np.zeros((9, 9, 9))
    mask1[2:-2, 2:-2, 2:-2] = 1

    np.testing.assert_array_equal(mask1, get_data(mask))

    # Check that we get a useful warning for empty masks
    with pytest.warns(masking.MaskWarning):
        compute_gray_matter_mask(image, threshold=1)

    # Check that masks obtained from same FOV are the same
    img1 = Nifti1Image(np.full((9, 9, 9), np.random.rand()), np.eye(4))
    img2 = Nifti1Image(np.full((9, 9, 9), np.random.rand()), np.eye(4))

    mask_img1 = compute_gray_matter_mask(img1)
    mask_img2 = compute_gray_matter_mask(img2)
    np.testing.assert_array_equal(get_data(mask_img1), get_data(mask_img2))
Пример #19
0
def make_timeseries_for_prf(bolds):
    """Takes a list of 4d nifti filenames, averages, cuts extra timepoints"""
    for i, bold_file in enumerate(bolds):
        img = load_img(bold_file)
        data = get_data(img)
        print(data.shape)
        if i == 0:
            all_data = np.empty((*data.shape, len(bolds)))
        all_data[:, :, :, :, i] = data
    mean_timeseries = np.average(all_data, -1)
    return nib.Nifti1Image(mean_timeseries[:, :, :, :138], img.affine)
Пример #20
0
def _testdata_3d_for_resampling(img, binary):
    """Returns testing data for resampling tests.
    Data can be binarize or not.
    """
    data = get_data(img)
    if binary:
        data[data > 0] = 1
        data[data < 0] = 0
    affine = np.array([[1., -1., 0., 0.], [1., 1., 0., 0.], [0., 0., 1., 0.],
                       [0., 0., 0., 1.]])
    return Nifti1Image(data, affine)
Пример #21
0
def test_compute_multi_gray_matter_mask():
    # Check mask is correctly is correctly calculated
    imgs = [Nifti1Image(np.random.rand(9, 9, 5), np.eye(4)),
            Nifti1Image(np.random.rand(9, 9, 5), np.eye(4))]

    masker = MultiNiftiMasker(mask_strategy='template')
    masker.fit(imgs)

    # Check that the order of the images does not change the output
    masker2 = MultiNiftiMasker(mask_strategy='template')
    masker2.fit(imgs[::-1])

    mask = masker.mask_img_
    mask2 = masker2.mask_img_

    mask_ref = np.zeros((9, 9, 5))
    mask_ref[2:7, 2:7, 2] = 1

    np.testing.assert_array_equal(get_data(mask), mask_ref)
    np.testing.assert_array_equal(get_data(mask2), mask_ref)
Пример #22
0
def test_fetch_atlas_pauli_2017():
    data_dir = os.path.join(tst.tmpdir, 'pauli_2017')

    data = atlas.fetch_atlas_pauli_2017('labels', data_dir)
    assert_equal(len(data.labels), 16)

    values = get_data(nibabel.load(data.maps))
    assert_equal(len(np.unique(values)), 17)

    data = atlas.fetch_atlas_pauli_2017('prob', data_dir)
    assert_equal(nibabel.load(data.maps).shape[-1], 16)
Пример #23
0
def test_logistic_path_scores():
    iris = load_iris()
    X, y = iris.data, iris.target
    _, mask = to_niimgs(X, [2, 2, 2])
    mask = get_data(mask).astype(bool)
    alphas = [1., .1, .01]
    test_scores, best_w = logistic_path_scores(_graph_net_logistic, X, y, mask,
                                               alphas, .5, np.arange(len(X)),
                                               np.arange(len(X)), {})[:2]
    test_scores = test_scores[0]
    assert len(test_scores) == len(alphas)
    assert X.shape[1] + 1 == len(best_w)
Пример #24
0
    def load_mask(self, mask):

        if mask is not None:
            if 'mask' in mask or 'lh_' in mask or 'rh_' in mask:
                fname = os.path.join(self.subj.masks, '%s.nii.gz' % (mask))
            else:
                fname = os.path.join(self.subj.masks, '%s_mask.nii.gz')

        if not os.path.exists(fname):
            fname = os.path.join(self.subj.masks, '%s.nii.gz' % (mask))

        return get_data(fname)
Пример #25
0
def test_matrix_orientation():
    """Test if processing is performed along the correct axis."""

    # the "step" kind generate heavyside-like signals for each voxel.
    # all signals being identical, standardizing along the wrong axis
    # would leave a null signal. Along the correct axis, the step remains.
    fmri, mask = data_gen.generate_fake_fmri(shape=(40, 41, 42), kind="step")
    masker = NiftiMasker(mask_img=mask, standardize=True, detrend=True)
    timeseries = masker.fit_transform(fmri)
    assert (timeseries.shape[0] == fmri.shape[3])
    assert (timeseries.shape[1] == get_data(mask).sum())
    std = timeseries.std(axis=0)
    assert (std.shape[0] == timeseries.shape[1])  # paranoid
    assert (not np.any(std < 0.1))

    # Test inverse transform
    masker = NiftiMasker(mask_img=mask, standardize=False, detrend=False)
    masker.fit()
    timeseries = masker.transform(fmri)
    recovered = masker.inverse_transform(timeseries)
    np.testing.assert_array_almost_equal(get_data(recovered), get_data(fmri))
Пример #26
0
def test_high_level_glm_with_paths():
    shapes, rk = ((7, 8, 7, 15), (7, 8, 7, 14)), 3
    with InTemporaryDirectory():
        mask_file, fmri_files, design_files = write_fake_fmri_data_and_design(shapes, rk)
        multi_session_model = FirstLevelModel(mask_img=None).fit(
            fmri_files, design_matrices=design_files)
        z_image = multi_session_model.compute_contrast(np.eye(rk)[1])
        assert_array_equal(z_image.affine, load(mask_file).affine)
        assert get_data(z_image).std() < 3.
        # Delete objects attached to files to avoid WindowsError when deleting
        # temporary directory (in Windows)
        del z_image, fmri_files, multi_session_model
Пример #27
0
def test_reorder_img_non_native_endianness():
    def _get_resampled_img(dtype):
        data = np.ones((10, 10, 10), dtype=dtype)
        data[3:7, 3:7, 3:7] = 2

        affine = np.eye(4)

        theta = math.pi / 6.
        c = math.cos(theta)
        s = math.sin(theta)

        affine = np.array([[1, 0, 0, 0], [0, c, -s, 0], [0, s, c, 0],
                           [0, 0, 0, 1]])

        img = Nifti1Image(data, affine)
        return resample_img(img, target_affine=np.eye(4))

    img_1 = _get_resampled_img('<f8')
    img_2 = _get_resampled_img('>f8')

    np.testing.assert_equal(get_data(img_1), get_data(img_2))
Пример #28
0
def test_get_clusters_table_not_modifying_stat_image():
    shape = (9, 10, 11)
    data = np.zeros(shape)
    data[2:4, 5:7, 6:8] = 5.
    data[0:3, 0:3, 0:3] = 6.

    stat_img = nib.Nifti1Image(data, np.eye(4))
    data_orig = get_data(stat_img).copy()

    # test one cluster should be removed
    clusters_table = get_clusters_table(
        stat_img,
        4,
        cluster_threshold=10,
        two_sided=True
    )
    assert np.allclose(data_orig, get_data(stat_img))
    assert len(clusters_table) == 1

    # test no clusters should be removed
    stat_img = nib.Nifti1Image(data, np.eye(4))
    clusters_table = get_clusters_table(
        stat_img,
        4,
        cluster_threshold=7,
        two_sided=False
    )
    assert np.allclose(data_orig, get_data(stat_img))
    assert len(clusters_table) == 2

    # test cluster threshold is None
    stat_img = nib.Nifti1Image(data, np.eye(4))
    clusters_table = get_clusters_table(
        stat_img,
        4,
        cluster_threshold=None,
        two_sided=False
    )
    assert np.allclose(data_orig, get_data(stat_img))
    assert len(clusters_table) == 2
Пример #29
0
def test_clean_img():

    rng = np.random.RandomState(0)

    data = rng.randn(10, 10, 10, 100) + .5
    data_flat = data.T.reshape(100, -1)
    data_img = nibabel.Nifti1Image(data, np.eye(4))

    pytest.raises(
        ValueError, image.clean_img, data_img, t_r=None, low_pass=0.1)

    data_img_ = image.clean_img(
        data_img, detrend=True, standardize=False, low_pass=0.1, t_r=1.0)
    data_flat_ = signal.clean(
        data_flat, detrend=True, standardize=False, low_pass=0.1, t_r=1.0)

    np.testing.assert_almost_equal(get_data(data_img_).T.reshape(100, -1),
                                   data_flat_)
    # if NANs
    data[:, 9, 9] = np.nan
    # if infinity
    data[:, 5, 5] = np.inf
    nan_img = nibabel.Nifti1Image(data, np.eye(4))
    clean_im = image.clean_img(nan_img, ensure_finite=True)
    assert np.any(np.isfinite(get_data(clean_im))), True

    # test_clean_img_passing_nifti2image
    data_img_nifti2 = nibabel.Nifti2Image(data, np.eye(4))

    data_img_nifti2_ = image.clean_img(
        data_img_nifti2, detrend=True, standardize=False, low_pass=0.1, t_r=1.0)

    # if mask_img
    img, mask_img = data_gen.generate_fake_fmri(shape=(10, 10, 10), length=10)
    data_img_mask_ = image.clean_img(img, mask_img=mask_img)

    # Checks that output with full mask and without is equal
    data_img_ = image.clean_img(img)
    np.testing.assert_almost_equal(get_data(data_img_),
                                   get_data(data_img_mask_))
Пример #30
0
def test_view_img_on_surf():
    img = _get_img()
    surfaces = datasets.fetch_surf_fsaverage()
    html = html_surface.view_img_on_surf(img, threshold='92.3%')
    check_html(html)
    html = html_surface.view_img_on_surf(img, threshold=0, surf_mesh=surfaces)
    check_html(html)
    html = html_surface.view_img_on_surf(img, threshold=.4, title="SOME_TITLE")
    assert "SOME_TITLE" in html.html
    check_html(html)
    html = html_surface.view_img_on_surf(
        img, threshold=.4, cmap='hot', black_bg=True)
    check_html(html)
    with pytest.raises(DimensionError):
        html_surface.view_img_on_surf([img, img])
    img_4d = image.new_img_like(img, get_data(img)[:, :, :, np.newaxis])
    assert len(img_4d.shape) == 4
    html = html_surface.view_img_on_surf(img, threshold='92.3%')
    check_html(html)
    np.clip(get_data(img), 0, None, out=get_data(img))
    html = html_surface.view_img_on_surf(img, symmetric_cmap=False)
    check_html(html)