Beispiel #1
0
def get_template(space='mni152_1mm', mask=None):
    if space == 'mni152_1mm':
        if mask is None:
            img = nib.load(datasets.fetch_icbm152_2009()['t1'])
        elif mask == 'brain':
            img = nib.load(datasets.fetch_icbm152_2009()['mask'])
        elif mask == 'gm':
            img = datasets.fetch_icbm152_brain_gm_mask(threshold=0.2)
        else:
            raise ValueError('Mask {0} not supported'.format(mask))
    elif space == 'mni152_2mm':
        if mask is None:
            img = datasets.load_mni152_template()
        elif mask == 'brain':
            img = datasets.load_mni152_brain_mask()
        elif mask == 'gm':
            # this approach seems to approximate the 0.2 thresholded
            # GM mask pretty well
            temp_img = datasets.load_mni152_template()
            data = temp_img.get_data()
            data = data * -1
            data[data != 0] += np.abs(np.min(data))
            data = (data > 1200).astype(int)
            img = nib.Nifti1Image(data, temp_img.affine)
        else:
            raise ValueError('Mask {0} not supported'.format(mask))
    else:
        raise ValueError('Space {0} not supported'.format(space))
    return img
Beispiel #2
0
def test_fail_fetch_atlas_harvard_oxford():
    # specify non-existing atlas item
    assert_raises_regex(ValueError, 'Invalid atlas name',
                        datasets.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(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)
    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()

    ho = datasets.fetch_atlas_harvard_oxford(target_atlas, data_dir=tmpdir)

    assert_true(isinstance(nibabel.load(ho.maps), nibabel.Nifti1Image))
    assert_true(isinstance(ho.labels, np.ndarray))
    assert_true(len(ho.labels) > 0)
Beispiel #3
0
def test_fail_fetch_atlas_harvard_oxford():
    # specify non-existing atlas item
    assert_raises_regex(ValueError, 'Invalid atlas name',
                        datasets.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(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)
    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()

    ho = datasets.fetch_atlas_harvard_oxford(target_atlas, data_dir=tmpdir)

    assert_true(isinstance(nibabel.load(ho.maps), nibabel.Nifti1Image))
    assert_true(isinstance(ho.labels, np.ndarray))
    assert_true(len(ho.labels) > 0)
Beispiel #4
0
def get_template(space='mni152_1mm', mask=None):
    """
    Load template file.

    Parameters
    ----------
    space : {'mni152_1mm', 'mni152_2mm', 'ale_2mm'}, optional
        Template to load. Default is 'mni152_1mm'.
    mask : {None, 'brain', 'gm'}, optional
        Whether to return the raw template (None), a brain mask ('brain'), or
        a gray-matter mask ('gm'). Default is None.

    Returns
    -------
    img : :obj:`nibabel.nifti1.Nifti1Image`
        Template image object.
    """
    if space == 'mni152_1mm':
        if mask is None:
            img = nib.load(datasets.fetch_icbm152_2009()['t1'])
        elif mask == 'brain':
            img = nib.load(datasets.fetch_icbm152_2009()['mask'])
        elif mask == 'gm':
            img = datasets.fetch_icbm152_brain_gm_mask(threshold=0.2)
        else:
            raise ValueError('Mask {0} not supported'.format(mask))
    elif space == 'mni152_2mm':
        if mask is None:
            img = datasets.load_mni152_template()
        elif mask == 'brain':
            img = datasets.load_mni152_brain_mask()
        elif mask == 'gm':
            # this approach seems to approximate the 0.2 thresholded
            # GM mask pretty well
            temp_img = datasets.load_mni152_template()
            data = temp_img.get_data()
            data = data * -1
            data[data != 0] += np.abs(np.min(data))
            data = (data > 1200).astype(int)
            img = nib.Nifti1Image(data, temp_img.affine)
        else:
            raise ValueError('Mask {0} not supported'.format(mask))
    elif space == 'ale_2mm':
        if mask is None:
            img = datasets.load_mni152_template()
        else:
            # Not the same as the nilearn brain mask, but should correspond to
            # the default "more conservative" MNI152 mask in GingerALE.
            img = nib.load(
                op.join(get_resource_path(),
                        'templates/MNI152_2x2x2_brainmask.nii.gz'))
    else:
        raise ValueError('Space {0} not supported'.format(space))
    return img
def test_view_img():
    mni = datasets.load_mni152_template()
    with warnings.catch_warnings(record=True) as w:
        # Create a fake functional image by resample the template
        img = image.resample_img(mni, target_affine=3 * np.eye(3))
        html_view = html_stat_map.view_img(img)
        _check_html(html_view)
        html_view = html_stat_map.view_img(img, threshold='95%')
        _check_html(html_view)
        html_view = html_stat_map.view_img(img, bg_img=mni)
        _check_html(html_view)
        html_view = html_stat_map.view_img(img, bg_img=None)
        _check_html(html_view)
        html_view = html_stat_map.view_img(img, threshold=2., vmax=4.)
        _check_html(html_view)
        html_view = html_stat_map.view_img(img, symmetric_cmap=False)
        img_4d = image.new_img_like(img, img.get_data()[:, :, :, np.newaxis])
        assert len(img_4d.shape) == 4
        html_view = html_stat_map.view_img(img_4d, threshold=2., vmax=4.)
        _check_html(html_view)

    # Check that all warnings were expected
    warnings_set = set(warning_.category for warning_ in w)
    expected_set = set([FutureWarning, UserWarning,
                       DeprecationWarning])
    assert warnings_set.issubset(expected_set), (
        "the following warnings were not expected: {}").format(
        warnings_set.difference(expected_set))
Beispiel #6
0
        def nsynth_vals_from_mni(self):
            """Get the data values at MNI_XYZ from a neurosynth map
            registered to the MNI template.

            Parameters
            ----------
            self.mni_xyz : numpy array
                MNI (x,y,z)-coordinates to look up in neurosynth map.

            self.nsynth_map : nibabel nifti object
                Neurosynth nifti file (loaded using nibabel.load)

            Returns
            -------
            nsynth_vals : numpy array
                Nx1 array of values at each MNI coordinate from
                neurosynth data map
            """
            nsynth_vals = np.zeros(self.mni_xyz.shape[0], dtype=int)
            mni152 = datasets.load_mni152_template()

            for i in range(self.mni_xyz.shape[0]):
                x, y, z = [
                    int(np.round(i))
                    for i in apply_affine(np.linalg.inv(mni152.affine), [
                        self.mni_xyz[i, 0], self.mni_xyz[i, 1], self.mni_xyz[i,
                                                                             2]
                    ])
                ]
                nsynth_vals[i] = self.nsynth_mat[x, y, z]

            return nsynth_vals
def test_user_given_cmap_with_colorbar():
    img = load_mni152_template()
    oslicer = OrthoSlicer(cut_coords=(0, 0, 0))

    # Test with cmap given as a string
    oslicer.add_overlay(img, cmap='Paired', colorbar=True)
    oslicer.close()
Beispiel #8
0
def test_view_img():
    mni = datasets.load_mni152_template()
    with warnings.catch_warnings(record=True) as w:
        # Create a fake functional image by resample the template
        img = image.resample_img(mni, target_affine=3 * np.eye(3))
        html_view = html_stat_map.view_img(img)
        _check_html(html_view, title="Slice viewer")
        html_view = html_stat_map.view_img(img,
                                           threshold='95%',
                                           title="SOME_TITLE")
        _check_html(html_view, title="SOME_TITLE")
        html_view = html_stat_map.view_img(img, bg_img=mni)
        _check_html(html_view)
        html_view = html_stat_map.view_img(img, bg_img=None)
        _check_html(html_view)
        html_view = html_stat_map.view_img(img, threshold=2., vmax=4.)
        _check_html(html_view)
        html_view = html_stat_map.view_img(img, symmetric_cmap=False)
        img_4d = image.new_img_like(img, get_data(img)[:, :, :, np.newaxis])
        assert len(img_4d.shape) == 4
        html_view = html_stat_map.view_img(img_4d, threshold=2., vmax=4.)
        _check_html(html_view)
        html_view = html_stat_map.view_img(img_4d, threshold=1e6)
        _check_html(html_view)

    # Check that all warnings were expected
    warnings_set = set(warning_.category for warning_ in w)
    expected_set = set([FutureWarning, UserWarning, DeprecationWarning])
    assert warnings_set.issubset(expected_set), (
        "the following warnings were not expected: {}").format(
            warnings_set.difference(expected_set))
Beispiel #9
0
def test_demo_ortho_slicer():
    # This is only a smoke test
    oslicer = OrthoSlicer(cut_coords=(0, 0, 0))
    img = load_mni152_template()
    oslicer.add_overlay(img, cmap=plt.cm.gray)
    oslicer.title("display mode is ortho")
    oslicer.close()
Beispiel #10
0
def test_user_given_cmap_with_colorbar():
    img = load_mni152_template()
    oslicer = OrthoSlicer(cut_coords=(0, 0, 0))

    # Test with cmap given as a string
    oslicer.add_overlay(img, cmap='Paired', colorbar=True)
    oslicer.close()
def test_contour_fillings_levels_in_add_contours():
    oslicer = OrthoSlicer(cut_coords=(0, 0, 0))
    img = load_mni152_template()
    # levels should be atleast 2
    # If single levels are passed then we force upper level to be inf
    oslicer.add_contours(img, filled=True, colors='r', alpha=0.2, levels=[0.])

    # If two levels are passed, it should be increasing from zero index
    # In this case, we simply omit appending inf
    oslicer.add_contours(img,
                         filled=True,
                         colors='b',
                         alpha=0.1,
                         levels=[0., 0.2])

    # without passing colors and alpha. In this case, default values are
    # chosen from matplotlib
    oslicer.add_contours(img, filled=True, levels=[0., 0.2])

    # levels with only one value
    oslicer.add_contours(img, filled=True, levels=[0.])

    # without passing levels, should work with default levels from
    # matplotlib
    oslicer.add_contours(img, filled=True)
Beispiel #12
0
def test_vol_to_surf():
    # test 3d niimg to cortical surface projection and invariance to a change
    # of affine
    mni = datasets.load_mni152_template()
    mesh = _generate_surf()
    _check_vol_to_surf_results(mni, mesh)
    fsaverage = datasets.fetch_surf_fsaverage5().pial_left
    _check_vol_to_surf_results(mni, fsaverage)
Beispiel #13
0
def test_demo_ortho_projector():
    # This is only a smoke test
    img = load_mni152_template()
    oprojector = OrthoProjector.init_with_figure(img=img)
    oprojector.add_overlay(img, cmap=plt.cm.gray)
    with tempfile.TemporaryFile() as fp:
        oprojector.savefig(fp)
    oprojector.close()
Beispiel #14
0
def test_vol_to_surf():
    # test 3d niimg to cortical surface projection and invariance to a change
    # of affine
    mni = datasets.load_mni152_template()
    mesh = generate_surf()
    _check_vol_to_surf_results(mni, mesh)
    fsaverage = datasets.fetch_surf_fsaverage().pial_left
    _check_vol_to_surf_results(mni, fsaverage)
Beispiel #15
0
def test_stacked_slicer():
    # Test stacked slicers, like the XSlicer
    img = load_mni152_template()
    slicer = XSlicer.init_with_figure(img=img, cut_coords=3)
    slicer.add_overlay(img, cmap=plt.cm.gray)
    # Forcing a layout here, to test the locator code
    with tempfile.TemporaryFile() as fp:
        slicer.savefig(fp)
    slicer.close()
Beispiel #16
0
def test_tiled_slicer():
    img = load_mni152_template()
    slicer = TiledSlicer.init_with_figure(img=img, cut_coords=(0, 0, 0),
                                          colorbar=True)
    slicer.add_overlay(img, cmap=plt.cm.gray, colorbar=True)
    # Forcing a layout here, to test the locator code
    with tempfile.TemporaryFile() as fp:
        slicer.savefig(fp)
    slicer.close()
Beispiel #17
0
def test_demo_ortho_slicer():
    # This is only a smoke test
    mp.use('template', warn=False)
    import pylab as pl
    pl.switch_backend('template')
    pl.clf()
    oslicer = OrthoSlicer(cut_coords=(0, 0, 0))
    img = load_mni152_template()
    oslicer.add_overlay(img, cmap=pl.cm.gray)
    oslicer.close()
Beispiel #18
0
def test_demo_ortho_slicer():
    # This is only a smoke test
    mp.use('template', warn=False)
    import matplotlib.pyplot as plt
    plt.switch_backend('template')
    plt.clf()
    oslicer = OrthoSlicer(cut_coords=(0, 0, 0))
    img = load_mni152_template()
    oslicer.add_overlay(img, cmap=plt.cm.gray)
    oslicer.close()
Beispiel #19
0
def test_demo_ortho_projector():
    # This is only a smoke test
    mp.use('template', warn=False)
    import pylab as pl
    pl.switch_backend('template')
    pl.clf()
    img = load_mni152_template()
    oprojector = OrthoProjector.init_with_figure(img=img)
    oprojector.add_overlay(img, cmap=pl.cm.gray)
    oprojector.savefig(tempfile.TemporaryFile())
    oprojector.close()
Beispiel #20
0
 def nilearn_resample(self, X):
     template = load_mni152_template()
     resampled_X = []
     for x in X:
         z = resample_to_img(x, template)
         z_affine = z.affine
         resampled_X.append(
             resample_img(x,
                          target_affine=z_affine,
                          target_shape=self.shape))
     return resampled_X
Beispiel #21
0
def resampling_MNI(image):
    """
    Resample Nifti image to MNI standard brain
    :param image: Nifti image to be resampled
    :return: Resampled Nifti image
    """

    template = load_mni152_template()
    resampled_img = resample_to_img(image, template)

    return resampled_img
Beispiel #22
0
def test_view_stat_map():
    mni = datasets.load_mni152_template()
    # Create a fake functional image by resample the template
    img = image.resample_img(mni, target_affine=3*np.eye(3))
    html = html_stat_map.view_stat_map(img)
    _check_html(html)
    html = html_stat_map.view_stat_map(img, threshold='95%')
    _check_html(html)
    html = html_stat_map.view_stat_map(img, bg_img=mni)
    _check_html(html)
    html = html_stat_map.view_stat_map(img, threshold=2., vmax=4.)
    _check_html(html)
Beispiel #23
0
def test_demo_ortho_projector():
    # This is only a smoke test
    mp.use('template', warn=False)
    import matplotlib.pyplot as plt
    plt.switch_backend('template')
    plt.clf()
    img = load_mni152_template()
    oprojector = OrthoProjector.init_with_figure(img=img)
    oprojector.add_overlay(img, cmap=plt.cm.gray)
    with tempfile.TemporaryFile() as fp:
        oprojector.savefig(fp)
    oprojector.close()
Beispiel #24
0
def test_stacked_slicer():
    # Test stacked slicers, like the XSlicer
    mp.use('template', warn=False)
    import pylab as pl
    pl.switch_backend('template')
    pl.clf()
    img = load_mni152_template()
    slicer = XSlicer.init_with_figure(img=img, cut_coords=3)
    slicer.add_overlay(img, cmap=pl.cm.gray)
    # Forcing a layout here, to test the locator code
    slicer.savefig(tempfile.TemporaryFile())
    slicer.close()
Beispiel #25
0
def test_plotting_functions_with_cmaps():
    img = load_mni152_template()
    cmaps = ['Paired', 'Set1', 'Set2', 'Set3']
    for cmap in cmaps:
        plot_roi(img, cmap=cmap, colorbar=True)
        plot_stat_map(img, cmap=cmap, colorbar=True)
        plot_glass_brain(img, cmap=cmap, colorbar=True)

    if LooseVersion(matplotlib.__version__) >= LooseVersion('2.0.0'):
        plot_stat_map(img, cmap='viridis', colorbar=True)

    plt.close()
def test_contour_fillings_levels_in_add_contours():
    oslicer = OrthoSlicer(cut_coords=(0, 0, 0))
    img = load_mni152_template()
    # levels should be atleast 2
    # If single levels are passed then we force upper level to be inf
    oslicer.add_contours(img, filled=True, colors='r',
                         alpha=0.2, levels=[0.])

    # If two levels are passed, it should be increasing from zero index
    # In this case, we simply omit appending inf
    oslicer.add_contours(img, filled=True, colors='b',
                         alpha=0.1, levels=[0., 0.2])
Beispiel #27
0
def test_stacked_slicer():
    # Test stacked slicers, like the XSlicer
    mp.use('template', warn=False)
    import matplotlib.pyplot as plt
    plt.switch_backend('template')
    plt.clf()
    img = load_mni152_template()
    slicer = XSlicer.init_with_figure(img=img, cut_coords=3)
    slicer.add_overlay(img, cmap=plt.cm.gray)
    # Forcing a layout here, to test the locator code
    with tempfile.TemporaryFile() as fp:
        slicer.savefig(fp)
    slicer.close()
def prepare():
    F = glob(DATA_PATH)
    N = [int(i.split('/')[-1].split('_')[0]) for i in F]
    print('loaded ukbb files')

    template = load_mni152_template()
    mask_img = MASK_PATH
    m = NiftiMasker(mask_img=mask_img)
    m.fit()
    dim = numpy.sum(m.mask_img_.get_data())
    print('fitted grey matter mask')

    with h5py.File(OUT_PATH, "a") as store:
        if 'name' in store:
            dname = store['name']
            ddata = store['data']
        else:
            dname = store.create_dataset('name', (0, ),
                                         maxshape=(None, ),
                                         dtype='i')
            ddata = store.create_dataset('data', (0, dim),
                                         maxshape=(None, dim),
                                         dtype='f')
        print('opened hdf5 storage')

        done = dname[:]
        for fn, sn in zip(F, N):
            if sn in done:
                print(sn, 'exists')
                continue

            r = resample_to_img(fn, template)
            s = smooth_img(r, 8)  # disabled for some subanalyses
            x = m.transform(s)

            try:
                i = dname.shape[0]
                dname.resize(i + 1, axis=0)
                ddata.resize(i + 1, axis=0)

                ddata[i] = x
                dname[i] = sn
                print(sn, 'processed')

            except:
                dname.resize(i - 1, axis=0)
                ddata.resize(i - 1, axis=0)
                print('roll back changes and exit')
                sys.exit()

    print('finished')
Beispiel #29
0
def test_plotting_functions_with_cmaps():
    img = load_mni152_template()
    # some cmaps such as 'viridis' (the new default in 2.0), 'magma', 'plasma',
    # and 'inferno' are not supported for older matplotlib version from < 1.5
    cmaps = ['Paired', 'Set1', 'Set2', 'Set3']
    for cmap in cmaps:
        plot_roi(img, cmap=cmap, colorbar=True)
        plot_stat_map(img, cmap=cmap, colorbar=True)
        plot_glass_brain(img, cmap=cmap, colorbar=True)

    if LooseVersion(matplotlib.__version__) >= LooseVersion('2.0.0'):
        plot_stat_map(img, cmap='viridis', colorbar=True)

    plt.close()
Beispiel #30
0
def test_contour_fillings_levels_in_add_contours():
    oslicer = OrthoSlicer(cut_coords=(0, 0, 0))
    img = load_mni152_template()
    # levels should be atleast 2
    # If single levels are passed then we force upper level to be inf
    oslicer.add_contours(img, filled=True, colors='r', alpha=0.2, levels=[0.])

    # If two levels are passed, it should be increasing from zero index
    # In this case, we simply omit appending inf
    oslicer.add_contours(img,
                         filled=True,
                         colors='b',
                         alpha=0.1,
                         levels=[0., 0.2])
Beispiel #31
0
def test_plotting_functions_with_cmaps():
    img = load_mni152_template()
    # some cmaps such as 'viridis' (the new default in 2.0), 'magma', 'plasma',
    # and 'inferno' are not supported for older matplotlib version from < 1.5
    cmaps = ['Paired', 'Set1', 'Set2', 'Set3']
    for cmap in cmaps:
        plot_roi(img, cmap=cmap, colorbar=True)
        plot_stat_map(img, cmap=cmap, colorbar=True)
        plot_glass_brain(img, cmap=cmap, colorbar=True)

    if LooseVersion(matplotlib.__version__) >= LooseVersion('2.0.0'):
        plot_stat_map(img, cmap='viridis', colorbar=True)

    plt.close()
Beispiel #32
0
def test_viewer_substitute():
    mni = datasets.load_mni152_template()
    with warnings.catch_warnings(record=True) as w:
        # Create a fake functional image by resample the template
        img = image.resample_img(mni, target_affine=3 * np.eye(3))
        file_template = (Path(__file__).resolve().parent.joinpath(
            "..", "data", "html", "viewer_template.html"))
        template = tempita.Template.from_filename(file_template,
                                                  encoding="utf-8")
        bsprite = bp.viewer_substitute(
            cmap="gray",
            symmetric_cmap=False,
            black_bg=True,
            threshold=None,
            vmax=250,
            title="Slice viewer",
            value=False,
        )
        bsprite.fit(img)
        viewer = bsprite.transform(template,
                                   javascript="js",
                                   html="html",
                                   library="bsprite")
        _check_html(viewer)

        bsprite.fit(img, bg_img=mni)
        viewer = bsprite.transform(template,
                                   javascript="js",
                                   html="html",
                                   library="bsprite")
        _check_html(viewer)

        bsprite.fit(img, bg_img=None)
        viewer = bsprite.transform(template,
                                   javascript="js",
                                   html="html",
                                   library="bsprite")
        _check_html(viewer)

        img_4d = image.new_img_like(img, get_data(img)[:, :, :, np.newaxis])
        assert len(img_4d.shape) == 4
        bsprite.fit(img_4d)

    # Check that all warnings were expected
    warnings_set = set(warning_.category for warning_ in w)
    expected_set = set([FutureWarning, UserWarning, DeprecationWarning])
    assert warnings_set.issubset(expected_set), (
        "the following warnings were not expected: {}").format(
            warnings_set.difference(expected_set))
Beispiel #33
0
def test_encode_nii():
    mni = datasets.load_mni152_template()
    encoded = html_stat_map._encode_nii(mni)
    decoded = html_stat_map._decode_nii(encoded)
    assert np.allclose(mni.get_data(), decoded.get_data())

    mni = image.new_img_like(mni, np.asarray(mni.get_data(), dtype='>f8'))
    encoded = html_stat_map._encode_nii(mni)
    decoded = html_stat_map._decode_nii(encoded)
    assert np.allclose(mni.get_data(), decoded.get_data())

    mni = image.new_img_like(mni, np.asarray(mni.get_data(), dtype='<i4'))
    encoded = html_stat_map._encode_nii(mni)
    decoded = html_stat_map._decode_nii(encoded)
    assert np.allclose(mni.get_data(), decoded.get_data())
def test_encode_nii():
    mni = datasets.load_mni152_template()
    encoded = html_stat_map._encode_nii(mni)
    decoded = html_stat_map._decode_nii(encoded)
    assert np.allclose(mni.get_data(), decoded.get_data())

    mni = image.new_img_like(mni, np.asarray(mni.get_data(), dtype='>f8'))
    encoded = html_stat_map._encode_nii(mni)
    decoded = html_stat_map._decode_nii(encoded)
    assert np.allclose(mni.get_data(), decoded.get_data())

    mni = image.new_img_like(mni, np.asarray(mni.get_data(), dtype='<i4'))
    encoded = html_stat_map._encode_nii(mni)
    decoded = html_stat_map._decode_nii(encoded)
    assert np.allclose(mni.get_data(), decoded.get_data())
Beispiel #35
0
def test_demo_mosaic_slicer():
    # cut_coords as tuple of length 3
    mslicer = MosaicSlicer(cut_coords=(1, 1, 1))
    img = load_mni152_template()
    mslicer.add_overlay(img, cmap=plt.cm.gray)
    # cut_coords as integer
    mslicer = MosaicSlicer(cut_coords=5)
    mslicer.add_overlay(img, cmap=plt.cm.gray)
    # cut_coords as dictionary
    mslicer = MosaicSlicer(cut_coords={'x': [10, 20],
                                       'y': [30, 40],
                                       'z': [15, 16]})
    mslicer.add_overlay(img, cmap=plt.cm.gray)
    assert mslicer.cut_coords == {'x': [10, 20], 'y': [30, 40], 'z': [15, 16]}
    # assert raises a ValueError
    pytest.raises(ValueError, MosaicSlicer, cut_coords=(2, 3))
    mslicer.close()
def anat_preproc(filename):

    from nilearn.datasets import fetch_localizer_button_task
    from nilearn.datasets import load_mni152_template
    from nilearn import plotting
    from nilearn.image import resample_to_img
    from nilearn.image import load_img

    template = load_mni152_template()
    localizer_dataset = fetch_localizer_button_task(get_anats=True)
    localizer_tmap_filename = localizer_dataset.tmaps[0]
    localizer_anat_filename = localizer_dataset.anats[0]

    resampled_localizer_tmap = resample_to_img(filename, template)

    tmap_img = load_img(filename)
    original_shape = tmap_img.shape
    original_affine = tmap_img.affine
    resampled_shape = resampled_localizer_tmap.shape
    resampled_affine = resampled_localizer_tmap.affine
    template_img = load_img(template)
    template_shape = template_img.shape
    template_affine = template_img.affine
    print("""Shape comparison:
	-Original t-map image shape: {0}
	-Resampled t-map image shape: {1}
	-Template image shape: {2}
	""".format(original_shape, resampled_shape, template_shape))
    print("""Affine comparison:
	-Original t-map image affine:\n{0}
	-Resampled t-map image:\n{0}
	-Template image affine:\n{2}
	""".format(original_affine, resampled_affine, template_affine))

    plotting.plot_stat_map(localizer_tmap_filename,
                           bg_img=localizer_anat_filename,
                           cut_coords=(36, -27, 66),
                           threshold=3,
                           title="t-map on original anat")
    plotting.plot_stat_map(resampled_localizer_tmap,
                           bg_img=template,
                           cut_coords=(36, -27, 66),
                           threshold=3,
                           title="Resampled t-map on MNI template anat")
    plotting.show()
Beispiel #37
0
def test_outlier_cut_coords():
    """Test to plot a subset of a large set of cuts found for a small area."""
    bg_img = load_mni152_template()
    data = np.zeros((79, 95, 79))
    affine = np.array([[-2., 0., 0., 78.],
                       [0., 2., 0., -112.],
                       [0., 0., 2., -70.],
                       [0., 0., 0., 1.]])
    # Color a cube around a corner area:
    x, y, z = 20, 22, 60
    x_map, y_map, z_map = coord_transform(x, y, z, np.linalg.inv(affine))
    data[int(x_map) - 1:int(x_map) + 1,
         int(y_map) - 1:int(y_map) + 1,
         int(z_map) - 1:int(z_map) + 1] = 1
    img = Nifti1Image(data, affine)
    cuts = find_cut_slices(img, n_cuts=20, direction='z')
    plot_stat_map(img, display_mode='z', cut_coords=cuts[-4:],
                  bg_img=bg_img)
def test_view_stat_map():
    mni = datasets.load_mni152_template()
    # Create a fake functional image by resample the template
    img = image.resample_img(mni, target_affine=3 * np.eye(3))
    html = html_stat_map.view_stat_map(img)
    _check_html(html)
    html = html_stat_map.view_stat_map(img, threshold='95%')
    _check_html(html)
    html = html_stat_map.view_stat_map(img, bg_img=mni)
    _check_html(html)
    html = html_stat_map.view_stat_map(img, bg_img=None)
    _check_html(html)
    html = html_stat_map.view_stat_map(img, threshold=2., vmax=4.)
    _check_html(html)
    html = html_stat_map.view_stat_map(img, symmetric_cmap=False)
    img_4d = image.new_img_like(img, img.get_data()[:, :, :, np.newaxis])
    assert len(img_4d.shape) == 4
    html = html_stat_map.view_stat_map(img_4d, threshold=2., vmax=4.)
    _check_html(html)
    def __init__(
        self,
        sessions=None,
        smoothing_fwhm=None,
        standardize=False,
        detrend=False,
        low_pass=None,
        high_pass=None,
        t_r=None,
        target_affine=None,
        target_shape=None,
        mask_strategy="background",
        mask_args=None,
        sample_mask=None,
        memory_level=1,
        memory=Memory(cachedir=None),
        verbose=0,
    ):

        # Create grey matter mask from mni template
        target_img = datasets.load_mni152_template()
        grey_voxels = (target_img.get_data() > 0).astype(int)
        mask_img = new_img_like(target_img, grey_voxels, copy_header=True)

        super(MniNiftiMasker, self).__init__(
            mask_img=mask_img,
            target_affine=mask_img.affine,
            target_shape=mask_img.shape,
            sessions=sessions,
            smoothing_fwhm=smoothing_fwhm,
            standardize=standardize,
            detrend=detrend,
            low_pass=low_pass,
            high_pass=high_pass,
            t_r=t_r,
            mask_strategy=mask_strategy,
            mask_args=mask_args,
            sample_mask=sample_mask,
            memory_level=memory_level,
            memory=memory,
            verbose=verbose,
        )
def plot_components(ica_image, hemi='', out_dir=None,
                    bg_img=datasets.load_mni152_template()):
    print("Plotting %s components..." % hemi)

    # Determine threshoold and vmax for all the plots
    # get nonzero part of the image for proper thresholding of
    # r- or l- only component
    nonzero_img = ica_image.get_data()[np.nonzero(ica_image.get_data())]
    thr = stats.scoreatpercentile(np.abs(nonzero_img), 90)
    vmax = stats.scoreatpercentile(np.abs(nonzero_img), 99.99)
    for ci, ic_img in enumerate(iter_img(ica_image)):

        title = _title_from_terms(terms=ica_image.terms, ic_idx=ci, label=hemi)
        fh = plt.figure(figsize=(14, 6))
        plot_stat_map(ic_img, axes=fh.gca(), threshold=thr, vmax=vmax,
                      colorbar=True, title=title, black_bg=True, bg_img=bg_img)

        # Save images instead of displaying
        if out_dir is not None:
            save_and_close(out_path=op.join(
                out_dir, '%s_component_%i.png' % (hemi, ci)))
Beispiel #41
0
def _load_bg_img(stat_map_img, bg_img="MNI152", black_bg="auto", dim="auto"):
    """ Load and resample bg_img in an isotropic resolution,
        with a positive diagonal affine matrix.
        Returns: bg_img, bg_min, bg_max, black_bg
    """
    if (bg_img is None or bg_img is False) and black_bg == "auto":
        black_bg = False

    if bg_img is not None and bg_img is not False:
        if isinstance(bg_img, str) and bg_img == "MNI152":
            bg_img = load_mni152_template()
        bg_img, black_bg, bg_min, bg_max = _load_anat(bg_img,
                                                      dim=dim,
                                                      black_bg=black_bg)
    else:
        bg_img = new_img_like(stat_map_img, np.zeros(stat_map_img.shape),
                              stat_map_img.affine)
        bg_min = 0
        bg_max = 0
    bg_img = reorder_img(bg_img, resample="nearest")
    return bg_img, bg_min, bg_max, black_bg
Beispiel #42
0
def test_mosaic_slicer():
    img = load_mni152_template()
    # default cut_coords=None
    slicer = MosaicSlicer.init_with_figure(img=img)
    slicer.add_overlay(img, cmap=plt.cm.gray, colorbar=True)
    # Forcing a layout here, to test the locator code
    with tempfile.TemporaryFile() as fp:
        slicer.savefig(fp)

    # cut_coords as an integer
    slicer = MosaicSlicer.init_with_figure(img=img, cut_coords=4)
    slicer.add_overlay(img, cmap=plt.cm.gray, colorbar=True)
    for d in ['x', 'y', 'z']:
        assert d in slicer.cut_coords
        assert len(slicer.cut_coords[d]) == 4
    # cut_coords as a tuple
    slicer = MosaicSlicer.init_with_figure(img=img, cut_coords=(4, 5, 2))
    slicer.add_overlay(img, cmap=plt.cm.gray, colorbar=True)
    assert len(slicer.cut_coords['x']) == 4
    assert len(slicer.cut_coords['y']) == 5
    assert len(slicer.cut_coords['z']) == 2
    # test title
    slicer.title('Showing mosaic mode')

    # test when img is None or False while initializing figure
    slicer = MosaicSlicer.init_with_figure(img=None, cut_coords=None)
    slicer.add_overlay(img, cmap=plt.cm.gray, colorbar=True)
    # same test but cut_coords as integer and tuple
    slicer = MosaicSlicer.init_with_figure(img=None, cut_coords=5)
    slicer.add_overlay(img, cmap=plt.cm.gray, colorbar=True)
    slicer = MosaicSlicer.init_with_figure(img=None, cut_coords=(1, 1, 1))
    slicer.add_overlay(img, cmap=plt.cm.gray, colorbar=True)

    # assert raises ValueError
    pytest.raises(ValueError,
                  MosaicSlicer.init_with_figure,
                  img=None,
                  cut_coords=(5, 4))

    slicer.close()
def test_outlier_cut_coords():
    """ Test to plot a subset of a large set of cuts found for a small area."""
    bg_img = load_mni152_template()

    data = np.zeros((79, 95, 79))
    affine = np.array([[  -2.,    0.,    0.,   78.],
                       [   0.,    2.,    0., -112.],
                       [   0.,    0.,    2.,  -70.],
                       [   0.,    0.,    0.,    1.]])

    # Color a cube around a corner area:
    x, y, z = 20, 22, 60
    x_map, y_map, z_map = coord_transform(x, y, z,
                                          np.linalg.inv(affine))

    data[int(x_map) - 1:int(x_map) + 1,
         int(y_map) - 1:int(y_map) + 1,
         int(z_map) - 1:int(z_map) + 1] = 1
    img = nibabel.Nifti1Image(data, affine)
    cuts = find_cut_slices(img, n_cuts=20, direction='z')

    p = plot_stat_map(img, display_mode='z', cut_coords=cuts[-4:],
                      bg_img=bg_img)
Beispiel #44
0
def test_contour_fillings_levels_in_add_contours():
    oslicer = OrthoSlicer(cut_coords=(0, 0, 0))
    img = load_mni152_template()
    # levels should be atleast 2
    # If single levels are passed then we force upper level to be inf
    oslicer.add_contours(img, filled=True, colors='r',
                         alpha=0.2, levels=[0.])

    # If two levels are passed, it should be increasing from zero index
    # In this case, we simply omit appending inf
    oslicer.add_contours(img, filled=True, colors='b',
                         alpha=0.1, levels=[0., 0.2])

    # without passing colors and alpha. In this case, default values are
    # chosen from matplotlib
    oslicer.add_contours(img, filled=True, levels=[0., 0.2])

    # levels with only one value
    oslicer.add_contours(img, filled=True, levels=[0.])

    # without passing levels, should work with default levels from
    # matplotlib
    oslicer.add_contours(img, filled=True)
def plot_components_summary(ica_image, hemi='', out_dir=None,
                            bg_img=datasets.load_mni152_template()):
    print("Plotting %s components summary..." % hemi)

    n_components = ica_image.get_data().shape[3]

    # Determine threshoold and vmax for all the plots
    # get nonzero part of the image for proper thresholding of
    # r- or l- only component
    nonzero_img = ica_image.get_data()[np.nonzero(ica_image.get_data())]
    thr = stats.scoreatpercentile(np.abs(nonzero_img), 90)
    vmax = stats.scoreatpercentile(np.abs(nonzero_img), 99.99)
    for ii, ic_img in enumerate(iter_img(ica_image)):

        ri = ii % 5  # row i
        ci = (ii / 5) % 5  # column i
        pi = ii % 25 + 1  # plot i
        fi = ii / 25  # figure i

        if ri == 0 and ci == 0:
            fh = plt.figure(figsize=(30, 20))
            print('Plot %03d of %d' % (fi + 1, np.ceil(n_components / 25.)))
        ax = fh.add_subplot(5, 5, pi)

        title = _title_from_terms(terms=ica_image.terms, ic_idx=ii, label=hemi)

        colorbar = ci == 4

        plot_stat_map(
            ic_img, axes=ax, threshold=thr, vmax=vmax, colorbar=colorbar,
            title=title, black_bg=True, bg_img=bg_img)

        if (ri == 4 and ci == 4) or ii == n_components - 1:
            out_path = op.join(
                out_dir, '%s_components_summary%02d.png' % (hemi, fi + 1))
            save_and_close(out_path)
Beispiel #46
0
n_permutations : int - how many permutations to test the classifier

radius : integer, cm - searchlight ragius.

cls : classifier object from sklearn, might conflict with impmap generation.

pathway options,
1 - single-subject analysis
0 - hyperclassification
2 - between-subject analysis

'''
# Examplary cfg that is used for our analysis
cfg = dict(TR = 1.7, nrun = 4, ncond = 3, convthresh = 0.6,
downsample = 1, target_affine = np.diag((4,4,4)),
anat = datasets.load_mni152_template(),
pathway = 3,
#partition='short',t='04:00:00',mem='8000',
partition='batch',t='23:00:00',mem='15000',
toolboxpath = 
'/triton/becs/scratch/braindata/shared/GraspHyperScan/tempanaconda/HCtool',
initfunc = 'initCLSpipeline.py',
dataroot = '/triton/becs/scratch/braindata/legarm1/FacialExpressions', 
niifilename = 'bramila/epi_STD_mask_detrend_fullreg.nii',
maskpath = 
'/triton/becs/scratch/braindata/anikins1/FacialExpressionPilot/masks/whole_GM.nii',
subject_train = 's4/Making',
subject_test = 's4/Observing',
regressorpath = 
'/triton/becs/scratch/braindata/anikins1/all the scripts/New_Hyperalignment/regressor_by_dima_make.mat',
n_permutations = 100,
def _get_img():
    return datasets.load_mni152_template()
Beispiel #48
0
def test_demo_ortho_slicer():
    # This is only a smoke test
    oslicer = OrthoSlicer(cut_coords=(0, 0, 0))
    img = load_mni152_template()
    oslicer.add_overlay(img, cmap=plt.cm.gray)
    oslicer.close()
def generate_components(
    images,
    hemi,
    term_scores=None,
    n_components=20,
    random_state=42,
    out_dir=None,
    memory=Memory(cachedir="nilearn_cache"),
):
    """
        images: list
            Can be nibabel images, can be file paths.
    """
    # Create grey matter mask from mni template
    target_img = datasets.load_mni152_template()

    # Reshape & mask images
    print("%s: Reshaping and masking images; may take time." % hemi)
    if hemi == "wb":
        masker = GreyMatterNiftiMasker(target_affine=target_img.affine, target_shape=target_img.shape, memory=memory)

    else:  # R and L maskers
        masker = HemisphereMasker(
            target_affine=target_img.affine, target_shape=target_img.shape, memory=memory, hemisphere=hemi
        )
    masker = masker.fit()

    # Images may fail to be transformed, and are of different shapes,
    # so we need to trasnform one-by-one and keep track of failures.
    X = []  # noqa
    xformable_idx = np.ones((len(images),), dtype=bool)
    for ii, im in enumerate(images):
        img = cast_img(im, dtype=np.float32)
        img = clean_img(img)
        try:
            X.append(masker.transform(img))
        except Exception as e:
            print("Failed to mask/reshape image %d/%s: %s" % (im.get("collection_id", 0), op.basename(im), e))
            xformable_idx[ii] = False

    # Now reshape list into 2D matrix
    X = np.vstack(X)  # noqa

    # Run ICA and map components to terms
    print("%s: Running ICA; may take time..." % hemi)
    fast_ica = FastICA(n_components=n_components, random_state=random_state)
    fast_ica = memory.cache(fast_ica.fit)(X.T)
    ica_maps = memory.cache(fast_ica.transform)(X.T).T

    # Tomoki's suggestion to normalize components_
    # X ~ ica_maps * fast_ica.components_
    #   = (ica_maps * f) * (fast_ica.components_ / f)
    #   = new_ica_map * new_components_
    C = fast_ica.components_
    factor = np.sqrt(np.multiply(C, C).sum(axis=1, keepdims=True))  # (n_components x 1)
    ica_maps = np.multiply(ica_maps, factor)
    fast_ica.components_ = np.multiply(C, 1.0 / (factor + 1e-12))

    if term_scores is not None:
        terms = term_scores.keys()
        term_matrix = np.asarray(term_scores.values())
        term_matrix[term_matrix < 0] = 0
        term_matrix = term_matrix[:, xformable_idx]  # terms x images
        # Don't use the transform method as it centers the data
        ica_terms = np.dot(term_matrix, fast_ica.components_.T).T

    # 2015/12/26 - sign matters for comparison, so don't do this!
    # 2016/02/01 - sign flipping is ok for R-L comparison, but RL concat
    #              may break this.
    # Pretty up the results
    for idx, ic in enumerate(ica_maps):
        if -ic.min() > ic.max():
            # Flip the map's sign for prettiness
            ica_maps[idx] = -ic
            if term_scores:
                ica_terms[idx] = -ica_terms[idx]

    # Create image from maps, save terms to the image directly
    ica_image = NiftiImageWithTerms.from_image(masker.inverse_transform(ica_maps))
    if term_scores:
        ica_image.terms = dict(zip(terms, ica_terms.T))

    # Write to disk
    if out_dir is not None:
        out_path = op.join(out_dir, "%s_ica_components.nii.gz" % hemi)
        if not op.exists(op.dirname(out_path)):
            os.makedirs(op.dirname(out_path))
        ica_image.to_filename(out_path)
    return ica_image
Beispiel #50
0
def test_load_mni152_template():
    # All subjects
    template_nii = datasets.load_mni152_template()
    assert_equal(template_nii.shape, (91, 109, 91))
    assert_equal(template_nii.get_header().get_zooms(), (2.0, 2.0, 2.0))
"""
Resample an image to a template
===============================

The goal of this example is to illustrate the use of the function
:func:`nilearn.image.resample_to_img` to resample an image to a template.
We use the MNI152 template as the reference for resampling a t-map image.
Function :func:`nilearn.image.resample_img` could also be used to achieve this.
"""

###############################################################################
# First we load the required datasets using the nilearn datasets module.
from nilearn.datasets import fetch_neurovault_motor_task
from nilearn.datasets import load_mni152_template

template = load_mni152_template()

motor_images = fetch_neurovault_motor_task()
stat_img = motor_images.images[0]

###############################################################################
# Now, the localizer t-map image can be resampled to the MNI template image.
from nilearn.image import resample_to_img

resampled_stat_img = resample_to_img(stat_img, template)

###############################################################################
# Let's check the shape and affine have been correctly updated.

# First load the original t-map in memory:
from nilearn.image import load_img