Пример #1
0
def _check_vol_to_surf_results(img, mesh):
    mni_mask = datasets.load_mni152_brain_mask()
    for kind, interpolation, mask_img in itertools.product(
        ['ball', 'line'], ['linear', 'nearest'], [mni_mask, None]):
        proj_1 = vol_to_surf(img,
                             mesh,
                             kind=kind,
                             interpolation=interpolation,
                             mask_img=mask_img)
        assert_true(proj_1.ndim == 1)
        img_rot = image.resample_img(img,
                                     target_affine=rotation(
                                         np.pi / 3., np.pi / 4.))
        proj_2 = vol_to_surf(img_rot,
                             mesh,
                             kind=kind,
                             interpolation=interpolation,
                             mask_img=mask_img)
        # The projection values for the rotated image should be close
        # to the projection for the original image
        diff = np.abs(proj_1 - proj_2) / np.abs(proj_1)
        assert_true(np.mean(diff[diff < np.inf]) < .03)
        img_4d = image.concat_imgs([img, img])
        proj_4d = vol_to_surf(img_4d,
                              mesh,
                              kind=kind,
                              interpolation=interpolation,
                              mask_img=mask_img)
        nodes, _ = surface.load_surf_mesh(mesh)
        assert_array_equal(proj_4d.shape, [nodes.shape[0], 2])
        assert_array_almost_equal(proj_4d[:, 0], proj_1, 3)
Пример #2
0
def save_imgs(bg_img, stats_img, seed_img, output_path):
    vmin, vmax = abs(args.vmin), abs(args.vmax)

    if args.mask:
        stats_img = image.math_img('img1 * img2',
                                   img1=stats_img,
                                   img2=datasets.load_mni152_brain_mask())

    slices = {'x': (-71, 72), 'y': (-107, 74), 'z': (-70, 82)}

    for key, value in slices.items():

        for i in range(value[0], value[1]):
            if args.verbose: print(f'slice: {key}={i}')
            img = plotting.plot_stat_map(bg_img=bg_img,
                                         stat_map_img=stats_img,
                                         threshold=vmin,
                                         vmax=vmax,
                                         display_mode=key,
                                         cut_coords=[i],
                                         colorbar=False,
                                         annotate=False,
                                         draw_cross=False)

            if args.seed: img.add_overlay(seed_img, cmap='cold_hot', alpha=.25)

            img.savefig(f'{output_path}_{key}={i}.png', dpi=600)
            img.close()
            del img
Пример #3
0
    def test_002(self):
        from roistats import collect
        from nilearn import plotting as nip
        from nilearn import image
        from nilearn import datasets
        from roistats import atlases, plotting
        import random
        import numpy as np
        import pandas as pd

        atlas = datasets.load_mni152_brain_mask()
        atlas_fp = datasets.fetch_atlas_harvard_oxford('cort-maxprob-thr50-2mm')['maps']
        try:
            labels = atlases.labels('HarvardOxford-Cortical.xml')
        except Exception:
            from nilearn import datasets

            name = 'cort-maxprob-thr50-2mm'
            labels = datasets.fetch_atlas_harvard_oxford(name)['labels']

            # Store them in a dict
            labels = dict(enumerate(labels))
        print(atlas_fp)

        images = []
        for i in range(0, 50):
            d = np.random.rand(*atlas.dataobj.shape) * atlas.dataobj
            im = image.new_img_like(atlas, d)
            im = image.smooth_img(im, 5)
            _, f = tempfile.mkstemp(suffix='.nii.gz')
            im.to_filename(f)
            images.append(f)

        for each in images[:3]:
            nip.plot_roi(atlas_fp, bg_img=each)

        df = collect.roistats_from_maps(images, atlas_fp, subjects=None)
        df = df.rename(columns=labels)

        df['group'] = df.index
        df['age'] = df.apply(lambda row: random.random()*5+50, axis=1)
        df['group'] = df.apply(lambda row: row['group'] < len(df)/2, axis=1)
        df['index'] = df.index

        plotting.boxplot('Temporal Pole', df, covariates=['age'], by='group')

        _ = plotting.lmplot('Temporal Pole', 'age', df, covariates=[],
                            hue='group', palette='default')

        cov = df[['age', 'group']]
        melt = pd.melt(df, id_vars='index', value_vars=labels.values(),
                       var_name='region').set_index('index')
        melt = melt.join(cov)
        plotting.hist(melt, by='group', region_colname='region',
                      covariates=['age'])

        print('Removing images')
        import os
        for e in images:
            os.unlink(e)
Пример #4
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
Пример #5
0
def find_overlaps(atlas_names, dimension):
    """Estimate overlap (queries) provided atlas names

    Parameters
    ----------
    atlas_names : str or list of str
        Grab atlas from web given the name. Few are shipped with FSL
        and Nilearn.
        Valid options:  ['harvard_oxford', 'destrieux', 'diedrichsen',
                         'juelich', 'jhu', 'mist', 'yeo_networks7',
                         'yeo_networks17']

    dimension : int
        Dimension of the DiFuMo atlas (4D).

    Returns
    -------
    info : dict
        Contains meta-data assigned to each atlas name such as
        overlap proportion, etc
        Each atlas dict contains following attributes:
            'intersection' : sparse matrix
                dot product between DiFuMo regions and regions in target
                atlas (existing pre-defined)

            'target_size' : np.ndarray
                Size of each region estimated in target atlas

            'overlap_proportion' : list of pd.Series
                Each list contains the proportion of overlap estimated
                between this region and all region in target sizes.
                Sorted according to most strong hit in the overlap.

            'overlap_size' : list
                Each list contain overlap in estimated sizes for all
                regions in target atlas.

    save_labels : dict
        List of original labels specific to each atlas. Useful
        for matching the overlap for the visualization of
        records.
    """
    masker = input_data.NiftiMasker(datasets.load_mni152_brain_mask()).fit([])
    queries = transform_difumo_to_data(dimension=dimension, masker=masker)
    atlases = fetch_atlases(atlas_names)
    info = {}
    save_labels = {}
    for atlas in atlas_names:
        this_atlas = atlases[atlas]
        labels_img, labels = labels_img_to_binary(this_atlas.maps,
                                                  this_atlas.labels, masker)
        save_labels[atlas] = labels
        info[atlas] = overlaps(queries, labels_img)
    return info, save_labels
Пример #6
0
def coords_to_voxels(coords, ref_img=None):
    if ref_img is None:
        ref_img = load_mni152_brain_mask()
    affine = ref_img.affine
    coords = np.atleast_2d(coords)
    coords = np.hstack([coords, np.ones((len(coords), 1))])
    voxels = np.linalg.pinv(affine).dot(coords.T)[:-1].T
    voxels = voxels[(voxels >= 0).all(axis=1)]
    voxels = voxels[(voxels < ref_img.shape[:3]).all(axis=1)]
    voxels = np.floor(voxels).astype(int)
    return voxels
Пример #7
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
Пример #8
0
def test_kernel_peaks(testdata_cbma, tmp_path_factory, kern, res, param,
                      return_type, kwargs):
    """Peak/COMs of kernel maps should match the foci fed in (assuming focus isn't masked out).

    Notes
    -----
    Remember that dataframe --> dataset won't work.
    Only testing dataset --> dataset with ALEKernel because it takes a while.
    Test on multiple template resolutions.
    """
    tmpdir = tmp_path_factory.mktemp("test_kernel_peaks")
    testdata_cbma.update_path(tmpdir)

    id_ = "pain_03.nidm-1"

    # Ignoring resolution until we support 0.8.1
    # template = load_mni152_brain_mask(resolution=res)
    template = load_mni152_brain_mask()
    masker = get_masker(template)

    xyz = testdata_cbma.coordinates.loc[testdata_cbma.coordinates["id"] == id_,
                                        ["x", "y", "z"]]
    ijk = mm2vox(xyz, masker.mask_img.affine)
    ijk = np.squeeze(ijk.astype(int))

    if param == "dataframe":
        input_ = testdata_cbma.coordinates.copy()
    elif param == "dataset":
        input_ = testdata_cbma.copy()

    kern_instance = kern(**kwargs)
    output = kern_instance.transform(input_, masker, return_type=return_type)

    if return_type == "image":
        kern_data = output[0].get_fdata()
    elif return_type == "array":
        kern_data = np.squeeze(
            masker.inverse_transform(output[:1, :]).get_fdata())
    else:
        f = output.images.loc[output.images["id"] == id_,
                              kern_instance.image_type].values[0]
        kern_data = nib.load(f).get_fdata()

    if isinstance(kern_instance, kernel.ALEKernel):
        loc_idx = np.array(np.where(kern_data == np.max(kern_data))).T
    elif isinstance(kern_instance, (kernel.MKDAKernel, kernel.KDAKernel)):
        loc_idx = np.array(center_of_mass(kern_data)).astype(int).T
    else:
        raise Exception(f"A {type(kern_instance)}? Why?")

    loc_ijk = np.squeeze(loc_idx)

    assert np.array_equal(ijk, loc_ijk)
Пример #9
0
def coords_to_img(coords, fwhm=9.0):
    mask = load_mni152_brain_mask()
    masker = NiftiMasker(mask).fit()
    voxels = np.asarray(
        image.coord_transform(*coords.T, np.linalg.pinv(mask.affine)),
        dtype=int,
    ).T
    peaks = np.zeros(mask.shape)
    np.add.at(peaks, tuple(voxels.T), 1.0)
    peaks_img = image.new_img_like(mask, peaks)
    img = image.smooth_img(peaks_img, fwhm=fwhm)
    img = masker.inverse_transform(masker.transform(img).squeeze())
    return img
Пример #10
0
def fishers_workflow(img_list=None, prefix=None, output_dir=None):

    from nimare.meta.esma import fishers
    from nilearn.datasets import load_mni152_brain_mask
    import nibabel as nib
    import numpy as np
    import os.path as op
    import statsmodels.stats.multitest as mc

    mask_img = load_mni152_brain_mask()
    mask_ind = np.nonzero(mask_img.get_data())

    img_stack = []
    for i, img_fn in enumerate(img_list):

        tmp_img = nib.load(img_fn)

        if i == 0:
            img_stack = tmp_img.get_data()[mask_ind]
        else:
            img_stack = np.vstack([img_stack, tmp_img.get_data()[mask_ind]])

    results = fishers(img_stack, two_sided=False)

    for tmp_key in results.keys():

        img_data = np.zeros(mask_img.shape)

        img_data[mask_ind] = results[tmp_key]
        img = nib.Nifti1Image(img_data, mask_img.affine)

        nib.save(
            img,
            op.join(
                output_dir, '{prefix}_{suffix}.nii.gz'.format(prefix=prefix,
                                                              suffix=tmp_key)))

    _, p_corr = mc.fdrcorrection(results['p'],
                                 alpha=0.05,
                                 method='indep',
                                 is_sorted=False)

    img_data = np.zeros(mask_img.shape)

    img_data[mask_ind] = p_corr
    img = nib.Nifti1Image(img_data, mask_img.affine)

    nib.save(
        img,
        op.join(output_dir,
                '{prefix}_p_corr-fdr05.nii.gz'.format(prefix=prefix)))
Пример #11
0
def generate_mni_space_img(n_scans=1, res=30, random_state=0, mask_dilation=2):
    rng = check_random_state(random_state)
    mni = datasets.load_mni152_brain_mask()
    target_affine = np.eye(3) * res
    mask_img = image.resample_img(
        mni, target_affine=target_affine, interpolation="nearest")
    masker = input_data.NiftiMasker(mask_img).fit()
    n_voxels = image.get_data(mask_img).sum()
    data = rng.randn(n_scans, n_voxels)
    if mask_dilation is not None and mask_dilation > 0:
        mask_img = image.new_img_like(
            mask_img, ndimage.binary_dilation(
                image.get_data(mask_img), iterations=mask_dilation))
    return masker.inverse_transform(data), mask_img
Пример #12
0
def __create_precomputed(data_dir: Optional[Union[str, Path]] = None) -> None:
    """Create nearest neighbor interpolation niftis for MATLAB."""
    # Embed import to prevent circular dependency.
    from brainstat.datasets import fetch_template_surface

    data_dir = Path(
        data_dir) if data_dir else data_directories["BRAINSTAT_DATA_DIR"]
    mni152 = load_mni152_brain_mask()
    for template in ("fsaverage5", "fsaverage", "civet41k", "civet164k"):
        output_file = data_dir / f"nn_interp_{template}.nii.gz"
        if output_file.exists():
            continue
        top_surf = "pial" if template[:9] == "fsaverage" else "mid"
        pial = fetch_template_surface(template, layer=top_surf, join=False)
        white = fetch_template_surface(template, layer="white", join=False)
        labels = (
            np.arange(1,
                      get_points(pial[0]).shape[0] + 1),
            np.arange(
                get_points(pial[0]).shape[0] + 1,
                get_points(pial[0]).shape[0] * 2 + 1),
        )
        multi_surface_to_volume(
            pial=pial,
            white=white,
            volume_template=mni152,
            labels=labels,
            output_file=str(output_file),
            interpolation="nearest",
        )

    if not (data_dir / "nn_interp_hcp.nii.gz").exists():
        import hcp_utils as hcp
        from brainspace.mesh.mesh_creation import build_polydata

        pial_fslr32k = (build_polydata(hcp.mesh.pial[0], hcp.mesh.pial[1]), )
        white_fslr32k = (build_polydata(hcp.mesh.white[0],
                                        hcp.mesh.white[1]), )
        labels_fslr32k = (np.arange(1,
                                    get_points(pial_fslr32k[0]).shape[0] +
                                    1), )
        multi_surface_to_volume(
            pial=pial_fslr32k,
            white=white_fslr32k,
            volume_template=mni152,
            labels=labels_fslr32k,
            output_file=str(data_dir / "nn_interp_fslr32k.nii.gz"),
            interpolation="nearest",
        )
Пример #13
0
def get_masker(mask_img=None, target_affine=None):
    if isinstance(mask_img, input_data.NiftiMasker):
        return mask_img
    if mask_img is None:
        mask_img = load_mni152_brain_mask()
    if target_affine is not None:
        if np.ndim(target_affine) == 0:
            target_affine = np.eye(3) * target_affine
        elif np.ndim(target_affine) == 1:
            target_affine = np.diag(target_affine)
        mask_img = image.resample_img(mask_img,
                                      target_affine=target_affine,
                                      interpolation="nearest")
    masker = input_data.NiftiMasker(mask_img=mask_img).fit()
    return masker
Пример #14
0
def make_sphere(x, y, z, output_dir):

    mask = load_mni152_brain_mask()
    mask_img = mask.get_data()
    xyz_img = np.dot(np.linalg.inv(mask.affine), [x, y, z, 1]).astype(int)

    tmp_mask_img = mask_img * 0
    tmp_mask_img[xyz_img[0], xyz_img[1], xyz_img[2]] = 1
    tmp_roi_img = nib.Nifti1Image(tmp_mask_img, mask.affine, mask.header)

    tmp_roi_fn = op.join(output_dir, '{x}_{y}_{z}.nii.gz'.format(x=x, y=y,
                                                                 z=z))
    nib.save(tmp_roi_img, tmp_roi_fn)

    di = fsl.maths.DilateImage(in_file=tmp_roi_fn,
                               operation="mean",
                               kernel_shape="sphere",
                               kernel_size=4,
                               out_file=tmp_roi_fn)
Пример #15
0
def find_overlaps(dimension):
    """Estimate overlap (queries) within and across components

    Parameters
    ----------
    dimension : int
        Dimension of the DiFuMo atlas (4D).

    Returns
    -------
    info : dict
        Contains meta-data assigned to each atlas name such as
        overlap proportion, etc
        Each atlas dict contains following attributes:
            'intersection' : sparse matrix
                dot product between DiFuMo regions and regions in target
                atlas (existing pre-defined)

            'target_size' : np.ndarray
                Size of each region estimated in target atlas

            'overlap_proportion' : list of pd.Series
                Each list contains the proportion of overlap estimated
                between this region and all region in target sizes.
                Sorted according to most strong hit in the overlap.

            'overlap_size' : list
                Each list contain overlap in estimated sizes for all
                regions in target atlas.
    """
    masker = input_data.NiftiMasker(datasets.load_mni152_brain_mask()).fit([])
    queries = transform_difumo_to_data(dimension=dimension, masker=masker)
    info = {}
    for n in [64, 128, 256, 512, 1024]:
        targets = transform_difumo_to_data(dimension=n, masker=masker)
        info[n] = overlaps(queries, targets)
    return info
Пример #16
0
def _check_vol_to_surf_results(img, mesh):
    mni_mask = datasets.load_mni152_brain_mask()
    for kind, interpolation, mask_img in itertools.product(
            ['ball', 'line'], ['linear', 'nearest'], [mni_mask, None]):
        proj_1 = vol_to_surf(
            img, mesh, kind=kind, interpolation=interpolation,
            mask_img=mask_img)
        assert_true(proj_1.ndim == 1)
        img_rot = image.resample_img(
            img, target_affine=rotation(np.pi / 3., np.pi / 4.))
        proj_2 = vol_to_surf(
            img_rot, mesh, kind=kind, interpolation=interpolation,
            mask_img=mask_img)
        # The projection values for the rotated image should be close
        # to the projection for the original image
        diff = np.abs(proj_1 - proj_2) / np.abs(proj_1)
        assert_true(np.mean(diff[diff < np.inf]) < .03)
        img_4d = image.concat_imgs([img, img])
        proj_4d = vol_to_surf(
            img_4d, mesh, kind=kind, interpolation=interpolation,
            mask_img=mask_img)
        nodes, _ = surface.load_surf_mesh(mesh)
        assert_array_equal(proj_4d.shape, [nodes.shape[0], 2])
        assert_array_almost_equal(proj_4d[:, 0], proj_1, 3)
Пример #17
0
def get_masker(mask_img=None):
    if mask_img is None:
        mask_img = load_mni152_brain_mask()
    masker = input_data.NiftiMasker(mask_img=mask_img).fit()
    return masker
Пример #18
0
def surface_decoder(
    pial: Union[str, BSPolyData, Sequence[Union[str, BSPolyData]]],
    white: Union[str, BSPolyData, Sequence[Union[str, BSPolyData]]],
    stat_labels: Union[str, np.ndarray, Sequence[Union[str, np.ndarray]]],
    *,
    interpolation: str = "linear",
    data_dir: Optional[Union[str, Path]] = None,
    database: str = "neurosynth",
) -> pd.DataFrame:
    """Meta-analytic decoding of surface maps using NeuroSynth or NeuroQuery.

    Parameters
    ----------
    pial : str, BSPolyData, sequence of str or BSPolyData
        Path of a pial surface file, BSPolyData of a pial surface or a list
        containing multiple of the aforementioned.
    white : str, BSPolyData, sequence of str or BSPolyData
        Path of a white matter surface file, BSPolyData of a pial surface or a
        list containing multiple of the aforementioned.
    stat_labels : str, numpy.ndarray, sequence of str or numpy.ndarray
        Path to a label file for the surfaces, numpy array containing the
        labels, or a list containing multiple of the aforementioned.
    interpolation : str, optional
        Either 'nearest' for nearest neighbor interpolation, or 'linear'
        for trilinear interpolation, by default 'linear'.
    data_dir : str, optional
        The directory of the dataset. If none exists, a new dataset will
        be downloaded and saved to this path. If None, the directory defaults to
        your home directory, by default None.


    Returns
    -------
    pandas.DataFrame
        Table with correlation values for each feature.
    """
    from nilearn.datasets import load_mni152_brain_mask

    data_dir = Path(
        data_dir) if data_dir else data_directories["NEUROSYNTH_DATA_DIR"]
    data_dir.mkdir(exist_ok=True, parents=True)

    logger.info(
        "Fetching Neurosynth feature files. This may take several minutes if you haven't downloaded them yet."
    )
    feature_files = tuple(_fetch_precomputed(data_dir, database=database))

    mni152 = load_mni152_brain_mask()

    with NamedTemporaryFile(suffix=".nii.gz", delete=False) as f:
        name = f.name
    try:
        multi_surface_to_volume(
            pial=pial,
            white=white,
            volume_template=mni152,
            output_file=name,
            labels=stat_labels,
            interpolation=interpolation,
        )

        stat_volume = nib.load(name)

        mask = (stat_volume.get_fdata() != 0) & (mni152.get_fdata() != 0)
        stat_vector = stat_volume.get_fdata()[mask]
    finally:
        Path(name).unlink()

    feature_names = []
    correlations = np.zeros(len(feature_files))

    logger.info("Running correlations with all Neurosynth features.")
    for i in range(len(feature_files)):
        feature_names.append(
            re.search("__[A-Za-z0-9 ]+",
                      feature_files[i].stem)[0][2:])  # type: ignore
        feature_data = nib.load(feature_files[i]).get_fdata()[mask]
        keep = np.logical_not(
            np.isnan(feature_data)
            | np.isinf(feature_data)
            | np.isnan(stat_vector)
            | np.isinf(stat_vector))
        correlations[i], _ = pearsonr(stat_vector[keep], feature_data[keep])

    df = pd.DataFrame(correlations,
                      index=feature_names,
                      columns=["Pearson's r"])
    return df.sort_values(by="Pearson's r", ascending=False)
Пример #19
0

def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):
    new_cmap = colors.LinearSegmentedColormap.from_list(
        "trunc({n},{a:.2f},{b:.2f})".format(n=cmap.name, a=minval, b=maxval),
        cmap(np.linspace(minval, maxval, n)),
    )
    return new_cmap


from nilearn import image, datasets

mean_img = image.load_img("../data/statistical_map.nii")

masker = input_data.NiftiMasker(mask_img=image.resample_to_img(
    datasets.load_mni152_brain_mask(), mean_img, interpolation="nearest"))

# plot the image
masked_img = masker.fit_transform(mean_img)
unmasked_img = masker.inverse_transform(masked_img)
display = plotting.plot_glass_brain(
    unmasked_img,
    threshold=0,
    cmap=plt.cm.viridis,
    colorbar=False,
    display_mode="xz",
    axes=ax_glass_brain,
)
# ax_glass_brain.text(1, 1, '(a)', fontweight='bold')
ax1 = fig.add_axes([0.05, 0.12, 0.4, 0.03])
cmap = truncate_colormap(plt.cm.viridis, minval=0.5)
Пример #20
0
suj=89
meas=20

# Load Conditions file
eventname='F:/sim/event_sim.csv'
label=np.array(np.recfromcsv(eventname,names='s'))['s']
# Create session file
rest_mask = label == b'Rest'


# Prepare masker & Correct affine
template = load_mni152_template()
basc = datasets.fetch_atlas_basc_multiscale_2015(version='sym')['scale444']
orig_filename='F:/sim/template/restbaseline.nii.gz'
orig_img= image.load_img(orig_filename)
brainmask = load_mni152_brain_mask()
mem = Memory('nilearn_cache')
masker = NiftiLabelsMasker(labels_img = basc, mask_img = brainmask, 
                           memory=mem, memory_level=1, verbose=0,
                           detrend=False, standardize=False,  
                           high_pass=0.01,t_r=2,
                           resampling_target='labels')
masker.fit()

# Prep Classification
   
for s in np.arange(84,89):#range(suj):#
    for n in range(meas):
        sim_filename='F:/sim/sim_'+str(s+1)+'_'+ str(n+1)+ '.nii.gz'
        if os.path.exists(sim_filename): 
            sim_img = image.load_img(sim_filename)
def parcellation(
    sub_name, input_dir, out_dir, spatial_regularisation=10, n_clusters=200
):
    """
    Will load a functional image, and parcellate the brain into different zones that tend to activate together

    Parameters
    ----------
    sub_name : string
        name of the subject, used to access and save his data.

    input_dir : string
        path to where functional images can be loaded from

    out_dir : string
        path where files will be saved once computed

    spatial_regularisation : float, default 10
        once normalised, the spatial parameters a

    n_clusters : int, default 200
        The number of clusters to divide the image into

    Notes
    ------
    the "SUBJECTNAME_func_minimal.nii.gz" rsfMRI file is expected to be found in the input_dir,
    in a folder named after the subject 

    no output, but saves three files in the out_dir, in the corresponding subject file 
    skward_regXX_parcellation.nii.gz : the ward parcellated file
    ward_connectivity.npz : a sparse spatial adjacency matrix, voxel to voxel
    ward_labels.npy


    """
    raw_img = load_img(
        os.path.join(input_dir, "{0}/{0}_func_minimal.nii.gz".format(sub_name)), 1
    )
    flat_img = (raw_img.get_fdata()).reshape(-1, raw_img.shape[3])

    mask_img = load_mni152_brain_mask()
    nifti_masker = NiftiMasker(
        mask_img=mask_img, memory="nilearn_cache", memory_level=1
    )
    nifti_masker = nifti_masker.fit()
    flat_img = nifti_masker.transform(raw_img)
    plotting.plot_roi(mask_img, title="mask", display_mode="xz", cmap="prism")
    mask = nifti_masker.mask_img_.get_fdata().astype(np.bool)
    shape = mask.shape
    connectivity = grid_to_graph(n_x=shape[0], n_y=shape[1], n_z=shape[2], mask=mask)

    # weigh by coords
    x_ = np.arange(61)
    y_ = np.arange(73)
    z_ = np.arange(61)

    coords = np.array(np.meshgrid(x_, y_, z_, indexing="ij"))

    assert np.all(coords[0, :, 0, 0] == x_)
    assert np.all(coords[1, 0, :, 0] == y_)
    assert np.all(coords[2, 0, 0, :] == z_)

    coods_ni = new_img_like(raw_img, np.array(coords).T)
    flat_coords = nifti_masker.transform(coods_ni)
    # normalize
    flat_img = (flat_img - flat_img.min()) / (flat_img.max() - flat_img.min())
    flat_coords = (flat_coords - flat_coords.min()) / (
        flat_coords.max() - flat_coords.min()
    )
    # add coords to data
    input_data = np.vstack((flat_img, spatial_regularisation * flat_coords))

    # Compute clustering
    ward = AgglomerativeClustering(
        n_clusters=n_clusters, linkage="ward", connectivity=connectivity
    )
    ward.fit(input_data.T)
    labels = nifti_masker.inverse_transform(ward.labels_)

    labels.to_filename(
        os.path.join(
            out_dir,
            sub_name,
            "skward_reg{}_parcellation.nii.gz".format(spatial_regularisation),
        )
    )

    save_npz(
        os.path.join(out_dir, sub_name, "ward_connectivity.npz",),
        ward.connectivity.tocsr(),
    )

    np.save(os.path.join(out_dir, sub_name, "ward_labels.npy",), ward.labels_)
    
# CROSS MODAL CLASSIFICATION (cross-validated)
#n_p=0
#result_cv_tr_foot,permutation_scores_tr_foot, p_foot=permutation_score(pipeline,roi_foot_all,roi_hand_all,y_foot_all,groups,logo,n_p) 
#print('Train FOOT - IMAG VS STIM',np.array(result_cv_tr_foot).mean(),p_foot)
#result_cv_tr_hand,permutation_scores_tr_hand, p_hand=permutation_score(pipeline,roi_hand_all,roi_foot_all,y_hand_all,groups,logo,n_p)
#print('Train HAND - IMAG VS STIM',np.array(result_cv_tr_hand).mean(),p_hand)
#result_cv_tr_imag,permutation_scores_tr_imag, p_imag=permutation_score(pipeline,roi_imag_all,roi_stim_all,y_imag_all,groups,logo,n_p)   
#print('Train IMAG - HAND VS FOOT',np.array(result_cv_tr_imag).mean(),p_imag)
#result_cv_tr_stim,permutation_scores_tr_stim, p_stim=permutation_score(pipeline,roi_stim_all,roi_imag_all,y_stim_all,groups,logo,n_p)
#print('Train STIM - HAND VS FOOT',np.array(result_cv_tr_stim).mean(),p_stim)


# Prepare ploting
basc = datasets.fetch_atlas_basc_multiscale_2015(version='asym')['scale444']
brainmask = load_mni152_brain_mask()
masker = NiftiLabelsMasker(labels_img = basc, mask_img = brainmask, 
                           memory_level=1, verbose=0,
                           detrend=True, standardize=False,  
                           high_pass=0.01,t_r=2.28,
                           resampling_target='labels'
                           )
masker.fit()

pipeline.fit(roi_foot_all,y_foot_all)
coef_foot = pipeline.named_steps['svm'].coef_
weight_f = masker.inverse_transform(coef_foot)
plot_stat_map(weight_f, title='Train Imp',display_mode='z',cmap='bwr',threshold=0.4)


pipeline.fit(roi_hand_all,y_hand_all)
Пример #23
0
print("\nTop 10 neurosynth terms from downloaded images:\n")

for term_idx in np.argsort(total_scores)[-10:][::-1]:
    print(vocabulary[term_idx])

######################################################################
# Reshape and mask images
# -----------------------

print("\nReshaping and masking images.\n")

with warnings.catch_warnings():
    warnings.simplefilter('ignore', UserWarning)
    warnings.simplefilter('ignore', DeprecationWarning)

    mask_img = load_mni152_brain_mask()
    masker = NiftiMasker(mask_img=mask_img,
                         memory='nilearn_cache',
                         memory_level=1)
    masker = masker.fit()

    # Images may fail to be transformed, and are of different shapes,
    # so we need to transform one-by-one and keep track of failures.
    X = []
    is_usable = np.ones((len(images), ), dtype=bool)

    for index, image_path in enumerate(images):
        # load image and remove nan and inf values.
        # applying smooth_img to an image with fwhm=None simply cleans up
        # non-finite values but otherwise doesn't modify the image.
        image = smooth_img(image_path, fwhm=None)
Пример #24
0
    # Elaborate the ERP time windows
    ERPs = {
        'N1': [[1232, 1301], [0.101, 0.1348]],
        'P2': [[1353, 1499], [0.160, 0.2314]],
        'N2': [[1517, 1721], [0.2402, 0.3394]],
        'P3': [[1722, 1927], [0.3403, 0.4404]],
        'eLPP': [[1928, 2356], [0.4409, 0.6499]],
        'lLPP': [[2357, 2868], [0.6504, 0.8999]]
    }

    # Import the eeg data
    pos, time, fun = import_data(fname)

    # Import the mni template
    bm = load_mni152_brain_mask()
    bm_data = bm.get_fdata()
    Lx, Ly, Lz = bm_data.shape

    # Apply shift and scaling to the data and reorder the axis in pos
    shift = np.array([0, 40, 40])
    scale = np.array([1, 1, 1])
    ix, iy, iz = [1, 0, 2]
    pos_ref = np.array([pos[:, ix], pos[:, iy], pos[:, iz]]).T
    transformed_pos = pos_ref * scale[None, :] - shift[None, :]

    # Plot a 2d crosscut overview to check that the scaling makes sense
    plot_2D_crosscuts(bm_data, transformed_pos, fdir)

    # Send the position to volume space
    pos_volume = coord_transform(transformed_pos[:, 0], transformed_pos[:, 1],
Пример #25
0
def plot_4d_image_surface(components, colors, output_dir):
    # Indices of the maps to outline
    indices = []
    mlab.options.offscreen = True

    fig = mlab.figure(bgcolor=(1, 1, 1))

    # Disable rendering to speed things up
    fig.scene.disable_render = True

    rng = np.random.RandomState(42)

    mask = datasets.load_mni152_brain_mask().get_data() > 0

    n_components = components.shape[-1]
    threshold = np.percentile(np.abs(components.get_data()[mask]),
                              100. * (1 - 1. / n_components))

    # To speed up when prototyping
    # components = image.index_img(components, slice(0, 5))
    actors = dict(left=[], right=[])
    delayed = []
    for i, (component, color) in enumerate(zip(
            image.iter_img(components),
            colors)):
        if i in indices:
            delayed.append((i, (component, color)))
        else:
            print('Component %i' % i)
            component = image.math_img('np.abs(img)', img=component)
            this_actors = add_surf_map(component, threshold=threshold,
                                       color=tuple(color[:3]),
                                       sides=['left', 'right'],
                                       selected=i in indices,
                                       inflate=1.001)
            actors['left'].extend(this_actors['left'])
            actors['right'].extend(this_actors['right'])
    for i, (component, color) in delayed:
        print('Component %i' % i)
        component = image.math_img('np.abs(img)', img=component)
        this_actors = add_surf_map(component, threshold=threshold,
                                   color=tuple(color[:3]),
                                   sides=['left', 'right'],
                                   selected=i in indices,
                                   inflate=1.001)
        actors['left'].extend(this_actors['left'])
        actors['right'].extend(this_actors['right'])

    # Plot the background
    for side in ['left', 'right']:
        depth = surface.load_surf_data(fsaverage['sulc_%s' % side])
        this_actors = plot_on_surf(-depth, sides=[side, ],
                                   colormap='gray', inflate=.995)
        actors[side].extend(this_actors[side])

    # Enable rendering
    fig.scene.disable_render = False

    save_views(fig, 'components_3d', actors,
               left_actors=actors['left'],
               right_actors=actors['right'], output_dir=output_dir)
Пример #26
0
def surface_decode_nimare(
    pial,
    white,
    stat_labels,
    mask_labels,
    interpolation="linear",
    data_dir=None,
    feature_group=None,
    features=None,
):
    """Meta-analytic decoding of surface maps using NeuroSynth or Brainmap.

    Parameters
    ----------
    pial : str, BSPolyData, list
        Path of a pial surface file, BSPolyData of a pial surface or a list
        containing multiple of the aforementioned.
    white : str, BSPolyData, list
        Path of a white matter surface file, BSPolyData of a pial surface or a
        list containing multiple of the aforementioned.
    stat_labels : str, numpy.ndarray, list
        Path to a label file for the surfaces, numpy array containing the
        labels, or a list containing multiple of the aforementioned.
    mask_labels : str, numpy.ndarray, list
        Path to a mask file for the surfaces, numpy array containing the
        mask, or a list containing multiple of the aforementioned. If None
        all vertices are included in the mask. Defaults to None.
    interpolation : str, optional
        Either 'nearest' for nearest neighbor interpolation, or 'linear'
        for trilinear interpolation, by default 'linear'.
    data_dir : str, optional
        The directory of the nimare dataset. If none exists, a new dataset will
        be downloaded and saved to this path. If None, the directory defaults to
        your home directory, by default None.
    correction : str, optional
        Multiple comparison correction. Valid options are None and 'fdr_bh',
        by default 'fdr_bh'.

    Returns
    -------
    pandas.DataFrame
        Table with each label and the following values associated with each
        label: ‘pForward’, ‘zForward’, ‘likelihoodForward’,‘pReverse’,
        ‘zReverse’, and ‘probReverse’.
    """

    if data_dir is None:
        data_dir = os.path.join(str(Path.home()), "nimare_data")

    mni152 = load_mni152_brain_mask()

    stat_image = tempfile.NamedTemporaryFile(suffix=".nii.gz")
    mask_image = tempfile.NamedTemporaryFile(suffix=".nii.gz")

    multi_surface_to_volume(
        pial,
        white,
        mni152,
        stat_labels,
        stat_image.name,
        interpolation=interpolation,
    )
    multi_surface_to_volume(
        pial,
        white,
        mni152,
        mask_labels,
        mask_image.name,
        interpolation="nearest",
    )

    dataset = fetch_nimare_dataset(data_dir, mask=mask_image.name, keep_neurosynth=True)

    logging.info(
        "If you use BrainStat's surface decoder, "
        + "please cite NiMARE (https://zenodo.org/record/4408504#.YBBPAZNKjzU))."
    )

    decoder = nimare.decode.continuous.CorrelationDecoder(
        feature_group=feature_group, features=features
    )
    decoder.fit(dataset)
    return decoder.transform(stat_image.name)
Пример #27
0
for term_idx in np.argsort(total_scores)[-10:][::-1]:
    print(vocabulary[term_idx])


######################################################################
# Reshape and mask images
# -----------------------

print("\nReshaping and masking images.\n")

with warnings.catch_warnings():
    warnings.simplefilter('ignore', UserWarning)
    warnings.simplefilter('ignore', DeprecationWarning)

    mask_img = load_mni152_brain_mask()
    masker = NiftiMasker(
        mask_img=mask_img, memory='nilearn_cache', memory_level=1)
    masker = masker.fit()

    # Images may fail to be transformed, and are of different shapes,
    # so we need to transform one-by-one and keep track of failures.
    X = []
    is_usable = np.ones((len(images),), dtype=bool)

    for index, image_path in enumerate(images):
        # load image and remove nan and inf values.
        # applying smooth_img to an image with fwhm=None simply cleans up
        # non-finite values but otherwise doesn't modify the image.
        image = smooth_img(image_path, fwhm=None)
        try:
Пример #28
0
import os.path as op

import numpy as np
import nibabel as nib
from nilearn import datasets, input_data
from nilearn.image import resample_to_img

from brainconn import utils

mask_img = datasets.load_mni152_brain_mask()
subjects = datasets.fetch_adhd(n_subjects=1)
power = datasets.fetch_coords_power_2011()

conf = subjects.confounds[0]
func_img = nib.load(subjects.func[0])
func_img = resample_to_img(func_img, mask_img)

coords = np.vstack((power.rois['x'], power.rois['y'], power.rois['z'])).T
spheres_masker = input_data.NiftiSpheresMasker(
    seeds=coords, smoothing_fwhm=4, radius=5.,
    detrend=True, standardize=True, low_pass=0.1, high_pass=0.01,
    t_r=func_img.header.get_zooms()[-1])

timeseries = spheres_masker.fit_transform(func_img,
                                          confounds=conf)
corr = np.corrcoef(timeseries.T)
np.savetxt(op.join(utils.get_resource_path(), 'example_corr.txt'), corr)
Пример #29
0
####################################################################
# First we load the ADHD200 data
from nilearn import datasets
import scipy as sp
from fmri_methods_sipi import rot_sub_data, hotelling_t2
import matplotlib.pyplot as plt
from nilearn import input_data
from nilearn.plotting import plot_roi, show, plot_stat_map
from nilearn.image.image import mean_img
from nilearn.image import index_img
from sklearn.decomposition import PCA
from scipy.stats import levene
from statsmodels.sandbox.stats.multicomp import multipletests
from nilearn.image import resample_to_img

std_msk = datasets.load_mni152_brain_mask()
gm_msk = datasets.fetch_icbm152_brain_gm_mask(threshold=0.3)
gm_msk.set_data_dtype(sp.float32)
affine_tar = 1.0 * sp.eye(4)
affine_tar[3, 3] = .3

adhd_dataset = datasets.fetch_adhd()

func_filenames = adhd_dataset.func  # list of 4D nifti files for each subject

mean_func_img = mean_img(func_filenames[0])

gm_msk = resample_to_img(source_img=gm_msk,
                         target_img=mean_func_img,
                         interpolation='nearest')
#affine_tar,