def test_unsupported_alignment():
    img1, mask_img = random_niimg((8, 7, 6, 10))
    img2, _ = random_niimg((7, 6, 8, 5))
    args = {'alignment_method': 'scaled_procrustes', 'mask': mask_img}
    algo = PairwiseAlignment(**args)
    with pytest.raises(NotImplementedError):
        algo.fit(img1, img2)
示例#2
0
def test_template_closer_to_target():
    n_samples = 6

    subject_1, mask_img = random_niimg((6, 5, 3, n_samples))
    subject_2, _ = random_niimg((6, 5, 3, n_samples))

    masker = NiftiMasker(mask_img=mask_img)
    masker.fit()

    # Calculate metric between each subject and the average

    sub_1 = masker.transform(subject_1)
    sub_2 = masker.transform(subject_2)
    subs = [subject_1, subject_2]
    average_img = _rescaled_euclidean_mean(subs, masker)
    avg_data = masker.transform(average_img)
    mean_distance_1 = zero_mean_coefficient_determination(sub_1, avg_data)
    mean_distance_2 = zero_mean_coefficient_determination(sub_2, avg_data)

    for alignment_method in [
            'permutation', 'ridge_cv', 'scaled_orthogonal',
            'optimal_transport', 'diagonal'
    ]:
        algo = TemplateAlignment(alignment_method=alignment_method,
                                 n_pieces=3,
                                 n_bags=2,
                                 mask=masker)
        # Learn template
        algo.fit(subs)
        # Assess template is closer to mean than both images
        template_data = masker.transform(algo.template)
        template_mean_distance = zero_mean_coefficient_determination(
            avg_data, template_data)
        assert template_mean_distance >= mean_distance_1
        assert template_mean_distance >= mean_distance_2
def test_pairwise_identity():
    img1, mask_img = random_niimg((8, 7, 6, 10))

    args_list = [{
        'alignment_method': 'identity',
        'mask': mask_img
    }, {
        'alignment_method': 'identity',
        'n_pieces': 3,
        'mask': mask_img
    }, {
        'alignment_method': 'identity',
        'n_pieces': 3,
        'n_bags': 4,
        'mask': mask_img
    }, {
        'alignment_method': 'identity',
        'n_pieces': 3,
        'n_bags': 3,
        'mask': mask_img,
        'n_jobs': 2
    }, {
        'alignment_method': 'identity',
        'n_pieces': 3,
        'n_bags': 2,
        'mask': mask_img,
        'n_jobs': 2,
        'parallel_backend': 'multiprocessing'
    }]
    for args in args_list:
        algo = PairwiseAlignment(**args)
        assert_algo_transform_almost_exactly(algo, img1, img1, mask=mask_img)
def test_models_against_identity():
    img1, mask_img = random_niimg((7, 6, 8, 5))
    img2, _ = random_niimg((7, 6, 8, 5))
    masker = NiftiMasker(mask_img=mask_img)
    masker.fit()
    ground_truth = masker.transform(img2)
    identity_baseline_score = zero_mean_coefficient_determination(
        ground_truth, masker.transform(img1))
    for alignment_method in [
            'permutation', 'ridge_cv', 'scaled_orthogonal',
            'optimal_transport', 'diagonal'
    ]:
        algo = PairwiseAlignment(alignment_method=alignment_method,
                                 mask=mask_img,
                                 n_pieces=2,
                                 n_bags=1,
                                 n_jobs=1)
        algo.fit(img1, img2)
        im_test = algo.transform(img1)
        algo_score = zero_mean_coefficient_determination(
            ground_truth, masker.transform(im_test))
        assert_greater(algo_score, identity_baseline_score)
def test_pairwise_identity():
    img1, mask_img = random_niimg((8, 7, 6, 10))

    args_list = [{
        'alignment_method': 'identity',
        'mask': mask_img
    }, {
        'alignment_method': 'identity',
        'n_pieces': 3,
        'mask': mask_img
    }, {
        'alignment_method': 'identity',
        'n_pieces': 3,
        'n_bags': 4,
        'mask': mask_img
    }, {
        'alignment_method': 'identity',
        'n_pieces': 3,
        'n_bags': 3,
        'mask': mask_img,
        'n_jobs': 2
    }]
    for args in args_list:
        algo = PairwiseAlignment(**args)
        assert_algo_transform_almost_exactly(algo, img1, img1, mask=mask_img)

    # test intersection of clustering and mask
    data_mask = copy.deepcopy(mask_img.get_fdata())
    data_mask[0] = 0
    # create ground truth
    clustering_mask = new_img_like(mask_img, data_mask)
    data_clust = copy.deepcopy(data_mask)
    data_clust[1] = 3
    # create 2-parcels clustering, smaller than background
    clustering = new_img_like(mask_img, data_clust)

    # clustering is smaller than mask
    assert (mask_img.get_fdata() > 0).sum() > (clustering.get_data() > 0).sum()
    algo = PairwiseAlignment(alignment_method='identity',
                             mask=mask_img,
                             clustering=clustering)
    with pytest.warns(UserWarning):
        algo.fit(img1, img1)
    assert (algo.mask.get_fdata() > 0).sum() == (clustering.get_fdata() >
                                                 0).sum()

    # test warning raised if parcel is 0 :
    null_im = new_img_like(img1, np.zeros_like(img1.get_fdata()))
    with pytest.warns(UserWarning):
        algo.fit(null_im, null_im)
示例#6
0
def test_make_parcellation():
    # make_parcellation is built on Nilearn which already has several test for its Parcellation class
    # here we test just the call of the API is right on a simple example
    img, mask_img = random_niimg((7, 6, 8, 5))
    indexes = np.arange(img.shape[-1])
    masker = NiftiMasker(mask_img=mask_img).fit()

    methods = ["kmeans", "ward", "hierarchical_kmeans"]

    # check rena only if nilearn version allow it
    if version.parse(nilearn.__version__) <= version.parse("0.5.2"):
        with pytest.raises(Exception):
            assert _make_parcellation(img, "rena", n_pieces, masker)
    else:
        methods.append("rena")

    for clustering_method in methods:
        # check n_pieces = 1 gives out ones of right shape
        assert (_make_parcellation(
            img, indexes, clustering_method, 1,
            masker) == masker.transform(mask_img)).all()

        # check n_pieces = 2 find right clustering
        labels = _make_parcellation(img, indexes, clustering_method, 2, masker)
        assert (len(np.unique(labels)) == 2)

        # check that not inputing n_pieces yields problems
        with pytest.raises(Exception):
            assert _make_parcellation(img, indexes, clustering_method, 0,
                                      masker)

    clustering = nibabel.Nifti1Image(
        np.hstack([np.ones((7, 3, 8)), 2 * np.ones((7, 3, 8))]), np.eye(4))

    # check 3D Niimg clusterings
    for n_pieces in [0, 1, 2]:
        labels = _make_parcellation(img, indexes, clustering, n_pieces, masker)
        assert (len(np.unique(labels)) == 2)

    # check warning if a parcel is too big
    with pytest.warns(UserWarning):
        clustering = nibabel.Nifti1Image(
            np.hstack([np.ones(2000), 4 * np.ones(800)]), np.eye(4))
        _make_parcellation(img, indexes, clustering_method, n_pieces, masker)
示例#7
0
def test_template_identity():

    n = 10
    im, mask_img = random_niimg((6, 5, 3))

    sub_1 = concat_imgs(n * [im])
    sub_2 = math_img("2 * img", img=sub_1)
    sub_3 = math_img("3 * img", img=sub_1)

    ref_template = sub_2
    masker = NiftiMasker(mask_img=mask_img)
    masker.fit()

    subs = [sub_1, sub_2, sub_3]

    # test euclidian mean function
    euclidian_template = _rescaled_euclidean_mean(subs, masker)
    assert_array_almost_equal(ref_template.get_fdata(),
                              euclidian_template.get_fdata())

    # test different fit() accept list of list of 3D Niimgs as input.
    algo = TemplateAlignment(alignment_method='identity', mask=masker)
    algo.fit([n * [im]] * 3)
    # test template
    assert_array_almost_equal(sub_1.get_fdata(), algo.template.get_fdata())

    # test fit() transform() with 4D Niimgs input for several params set
    args_list = [{
        'alignment_method': 'identity',
        'mask': masker
    }, {
        'alignment_method': 'identity',
        'mask': masker,
        'n_jobs': 2
    }, {
        'alignment_method': 'identity',
        'n_pieces': 3,
        'mask': masker
    }, {
        'alignment_method': 'identity',
        'n_pieces': 3,
        'n_bags': 2,
        'mask': masker
    }]

    for args in args_list:
        algo = TemplateAlignment(**args)
        # Learning a template which is
        algo.fit(subs)
        # test template
        assert_array_almost_equal(ref_template.get_fdata(),
                                  algo.template.get_fdata())
        predicted_imgs = algo.transform([index_img(sub_1, range(8))],
                                        train_index=range(8),
                                        test_index=range(8, 10))
        ground_truth = index_img(ref_template, range(8, 10))
        assert_array_almost_equal(ground_truth.get_fdata(),
                                  predicted_imgs[0].get_fdata())

    # test transform() with wrong indexes length or content (on previous fitted algo)
    train_inds, test_inds = [[0, 1], [1, 10], [4, 11], [0, 1, 2]], [[6, 8, 29],
                                                                    [4, 6],
                                                                    [4, 11],
                                                                    [4, 5]]

    for train_ind, test_ind in zip(train_inds, test_inds):
        with pytest.raises(Exception):
            assert algo.transform([index_img(sub_1, range(2))],
                                  train_index=train_ind,
                                  test_index=test_ind)

    # test wrong images input in fit() and transform method
    with pytest.raises(Exception):
        assert algo.transform([n * [im]] * 2,
                              train_index=train_inds[-1],
                              test_index=test_inds[-1])
        assert algo.fit([im])
        assert algo.transform([im],
                              train_index=train_inds[-1],
                              test_index=test_inds[-1])