Esempio n. 1
0
    def surf_stat_maps(self, data, data_type, map_index):
        data, title, threshold, output_folder = self.prepare_plots(
            data, data_type, map_index, "Surf_Stat_Maps")
        fsaverage = datasets.fetch_surf_fsaverage()

        texture = surface.vol_to_surf(data, fsaverage.pial_left)
        plotting.plot_surf_stat_map(
            fsaverage.infl_left,
            texture,
            hemi='left',
            view='lateral',
            title=title,
            colorbar=True,
            threshold=threshold,
            bg_map=fsaverage.sulc_left,
            bg_on_data=True,
            cmap='Spectral',
            output_file=(output_folder + 'feature_' + str(map_index) +
                         '-left-lateral-' + self.category + '_category.png'))
        plotting.plot_surf_stat_map(
            fsaverage.infl_left,
            texture,
            hemi='left',
            view='medial',
            title=title,
            colorbar=True,
            threshold=threshold,
            bg_map=fsaverage.sulc_left,
            bg_on_data=True,
            cmap='Spectral',
            output_file=(output_folder + 'feature_' + str(map_index) +
                         '-left-medial-' + self.category + '_category.png'))

        texture = surface.vol_to_surf(data, fsaverage.pial_right)
        plotting.plot_surf_stat_map(
            fsaverage.infl_right,
            texture,
            hemi='right',
            view='lateral',
            title=title,
            colorbar=True,
            threshold=threshold,
            bg_map=fsaverage.sulc_right,
            bg_on_data=True,
            cmap='Spectral',
            output_file=(output_folder + 'feature_' + str(map_index) +
                         '-right-lateral-' + self.category + '_category.png'))
        plotting.plot_surf_stat_map(
            fsaverage.infl_right,
            texture,
            hemi='right',
            view='medial',
            title=title,
            colorbar=True,
            threshold=threshold,
            bg_map=fsaverage.sulc_right,
            bg_on_data=True,
            cmap='Spectral',
            output_file=(output_folder + 'feature_' + str(map_index) +
                         '-right-medial-' + self.category + '_category.png'))
Esempio n. 2
0
def volumeToSurface(image, interpolation='linear'):
    fsaverageL = r"E:\brain\BNatlas\BN_Atlas_freesurfer\fsaverage\fsaverage_LR32k\fsaverage.L.inflated.32k_fs_LR.surf.gii"
    fsaverageR = r"E:\brain\BNatlas\BN_Atlas_freesurfer\fsaverage\fsaverage_LR32k\fsaverage.R.inflated.32k_fs_LR.surf.gii"
    textureL = surface.vol_to_surf(
        image,
        fsaverageL,
        inner_mesh=
        r"E:\brain\BNatlas\BN_Atlas_freesurfer\fsaverage\fsaverage_LR32k\fsaverage.L.white.32k_fs_LR.surf.gii"
    )
    textureR = surface.vol_to_surf(
        image,
        fsaverageR,
        inner_mesh=
        r"E:\brain\BNatlas\BN_Atlas_freesurfer\fsaverage\fsaverage_LR32k\fsaverage.R.white.32k_fs_LR.surf.gii"
    )

    #textureL = surface.vol_to_surf(image,fsaverageL,radius=4,interpolation=interpolation,kind='line',mask_img='Mask.nii')
    #textureR = surface.vol_to_surf(image,fsaverageR,radius=4,interpolation=interpolation,kind='line',mask_img='Mask.nii')

    newL = nib.GiftiImage(
        header=nib.load(r"E:\brain\GS\surface\NC_tmap.nii.L.func.gii").header)
    newR = nib.GiftiImage(
        header=nib.load(r"E:\brain\GS\surface\NC_tmap.nii.R.func.gii").header)

    dataArrayL = nib.gifti.gifti.GiftiDataArray(textureL.astype(np.float32))
    dataArrayR = nib.gifti.gifti.GiftiDataArray(textureR.astype(np.float32))

    newL.add_gifti_data_array(dataArrayL)
    newR.add_gifti_data_array(dataArrayR)

    return newL, newR
Esempio n. 3
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)
Esempio n. 4
0
def plot_data(data,affine,plot_title,thresh):
    minval = np.min(data)
    maxval = np.max(data)
    img = nib.Nifti1Image(data,affine)
    img.header["cal_min"] = minval
    img.header["cal_max"] = maxval
    fsaverage = datasets.fetch_surf_fsaverage()
    texture_right = surface.vol_to_surf(img, fsaverage.pial_right) 
    texture_left = surface.vol_to_surf(img, fsaverage.pial_left)
    plotting.plot_surf_stat_map(fsaverage.infl_right, texture_right, hemi='right', title=plot_title, colorbar=True, threshold=thresh, bg_map=fsaverage.sulc_right)    
    plotting.plot_surf_stat_map(fsaverage.infl_left, texture_left, hemi='left', title=plot_title, threshold=thresh, bg_map=fsaverage.sulc_left)
    plt.show() 
def plot_data(data, affine, thresh):
    minval = np.min(data)
    maxval = np.max(data)
    img = nib.Nifti1Image(data, affine)
    img.header["cal_min"] = minval
    img.header["cal_max"] = maxval

    fsaverage = datasets.fetch_surf_fsaverage()

    texture_right = surface.vol_to_surf(img, fsaverage.pial_right)
    texture_left = surface.vol_to_surf(img, fsaverage.pial_left)

    # plot right lateral
    plotting.plot_surf_stat_map(fsaverage.infl_right,
                                texture_right,
                                hemi='right',
                                view='lateral',
                                title="right lateral",
                                threshold=thresh,
                                bg_map=fsaverage.sulc_right)
    plt.tight_layout()

    # plot left lateral
    plotting.plot_surf_stat_map(fsaverage.infl_left,
                                texture_left,
                                hemi='left',
                                view='lateral',
                                title="left lateral",
                                threshold=thresh,
                                bg_map=fsaverage.sulc_left)
    plt.tight_layout()

    # plot right medial
    plotting.plot_surf_stat_map(fsaverage.infl_right,
                                texture_right,
                                hemi='right',
                                view='medial',
                                title="right medial",
                                threshold=thresh,
                                bg_map=fsaverage.sulc_right)
    plt.tight_layout()

    # plot left medial
    plotting.plot_surf_stat_map(fsaverage.infl_left,
                                texture_left,
                                hemi='left',
                                view='medial',
                                title="left medial",
                                threshold=thresh,
                                bg_map=fsaverage.sulc_left)
    plt.tight_layout()

    plt.show()
def main(argv=None):

    args = get_parser().parse_args(argv)

    output_dir = op.join(args.dset, 'derivatives', args.deriv, args.sub,
                         args.ses)
    os.makedirs(output_dir, exist_ok=True)

    nii_files = glob(
        op.join(args.dset, 'derivatives',
                '3dTproject_denoise_acompcor_csfwm+12mo+0.35mm', args.sub,
                args.ses, '*.nii.gz'))

    for tmp_nii_file in nii_files:
        print(tmp_nii_file)
        imgs = nib.load(tmp_nii_file)

        fsaverage = fetch_surf_fsaverage(mesh='fsaverage5')

        mask = compute_background_mask(imgs)
        surf_lh = surface.vol_to_surf(imgs,
                                      fsaverage.pial_left,
                                      radius=24,
                                      interpolation='nearest',
                                      kind='ball',
                                      n_samples=None,
                                      mask_img=mask)
        surf_rh = surface.vol_to_surf(imgs,
                                      fsaverage.pial_right,
                                      radius=24,
                                      interpolation='nearest',
                                      kind='ball',
                                      n_samples=None,
                                      mask_img=mask)

        time_series = np.transpose(np.vstack((surf_lh, surf_rh)))
        correlation = ConnectivityMeasure(kind='correlation')
        time_series = correlation.fit_transform([time_series])[0]
        plotting.plot_matrix(time_series, figure=(10, 8))
        plt.savefig(
            op.join(
                output_dir, '{0}-correlation_matrix.png'.format(
                    op.basename(tmp_nii_file).split('.')[0])))
        plt.close()
        with open(
                op.join(
                    output_dir, '{0}-correlation_matrix.pkl'.format(
                        op.basename(tmp_nii_file).split('.')[0])), 'wb') as fo:
            pickle.dump(time_series, fo)
def membership_to_rois(template, mesh, memb, **kwargs):
    '''
    Input:
        template: a nibabel.nifti1.Nifti1Image object
        mesh: a string of a mesh, or a list of two np.array with vert and faces
        memb: a np.array of integers of the parcel membership

    '''
    from copy import copy
    template2 = copy(template)
    radius = kwargs.get('radius', 0.01)
    # Put the specific node module index inside the atlas nifti, thus changing
    # the volume content
    indices = []
    all_parcels = np.unique(template2.get_fdata().flatten()).astype(np.int32)
    # find the indices of the voxels of a given parcel
    # since it's sorted we will exclude the 0 parcel
    for parcel in all_parcels[1:]:  # avoid parcel 0 which is empty space
        i, j, k = np.where(template2.get_fdata(caching='fill') == parcel)
        indices.append((i, j, k))

    # # Put the membership as from memb in those voxels
    for parcel in all_parcels[1:]:
        # set the value to the voxesl as the parcel membership
        i, j, k = indices[parcel - 1][0], indices[parcel -
                                                  1][1], indices[parcel - 1][2]
        template2.get_data(caching='fill')[i, j, k] = memb[parcel - 1]

    from nilearn.surface import vol_to_surf
    memb_rois = surface.vol_to_surf(template2,
                                    mesh,
                                    interpolation='nearest',
                                    radius=radius)
    return memb_rois
Esempio n. 8
0
def full_brain_info(stat_map,
                    mesh=None,
                    threshold=None,
                    cmap=plotting.cm.cold_hot):
    info = {}
    if mesh is None:
        mesh = datasets.fetch_surf_fsaverage5()
        # mesh = load_fsaverage()
    surf_maps = [
        surface.vol_to_surf(stat_map, mesh['pial_{}'.format(h)])
        for h in ['left', 'right']
    ]
    colors, cmax, cmap, norm, at = colorscale(cmap,
                                              np.asarray(surf_maps).ravel(),
                                              threshold)

    for hemi, surf_map in zip(['left', 'right'], surf_maps):
        pial = mesh['pial_{}'.format(hemi)]
        sulc_depth_map = surface.load_surf_data(mesh['sulc_{}'.format(hemi)])
        sulc_depth_map -= sulc_depth_map.min()
        sulc_depth_map /= sulc_depth_map.max()
        info['pial_{}'.format(hemi)] = to_plotly(pial)
        info['inflated_{}'.format(hemi)] = to_plotly(
            mesh['infl_{}'.format(hemi)])
        vertexcolor = cmap(norm(surf_map).data)
        if threshold is not None:
            anat_color = cm.get_cmap('Greys')(sulc_depth_map)
            vertexcolor[np.abs(surf_map) < at] = anat_color[
                np.abs(surf_map) < at]
        vertexcolor = np.asarray(vertexcolor * 255, dtype='uint8')
        info['vertexcolor_{}'.format(hemi)] = [
            '#{:02x}{:02x}{:02x}'.format(*row) for row in vertexcolor
        ]
    info["cmin"], info["cmax"] = -cmax, cmax
    return info, colors
Esempio n. 9
0
def plot_roi_img_surf(surf_img, saving_path, plot_name, mask=None, labels=None, inflated=False, compute_surf=True, colorbar=True, **kwargs):
    fsaverage = datasets.fetch_surf_fsaverage()
    if compute_surf:
        surf_img = vol_to_surf(surf_img, fsaverage[kwargs['surf_mesh']], interpolation='nearest', mask_img=mask)
        surf_img[np.isnan(surf_img)] = -2
    if labels is not None:
        surf_img = np.round(surf_img)
        
    surf_img += 2
    if saving_path:
        plt.close('all')
        plt.hist(surf_img, bins=50)
        plt.title(plot_name)
        plt.savefig(saving_path + "hist_{}.png".format(plot_name))
    plt.close('all')
    if inflated:
        kwargs['surf_mesh'] = 'infl_left' if 'left' in kwargs['surf_mesh_type'] else 'infl_right' 
    disp = plotting.plot_surf_roi(
        surf_mesh=fsaverage[kwargs['surf_mesh']], 
        roi_map=surf_img,
        hemi=kwargs['hemi'],
        view=kwargs['view'],
        bg_map=fsaverage[kwargs['bg_map']], 
        bg_on_data=kwargs['bg_on_data'],
        darkness=kwargs['darkness'],
        colorbar=colorbar)
    if saving_path:
        disp.savefig(saving_path + plot_name + '_{}_{}_{}.png'.format(kwargs['surf_mesh_type'], kwargs['hemi'], kwargs['view']))
    plotting.show()
Esempio n. 10
0
 def vol_2surf(self, radius=.3):
     for param, img in self.voxel_regressions.items():
         for hemisphere in ['L', 'R']:
             pial = join(
                 self.epi_dir, 'completed_preprocessed', self.subject,
                 'fmriprep', self.subject, 'anat',
                 '{0}_T1w_pial.{1}.surf.gii'.format(self.subject,
                                                    hemisphere))
             surface = vol_to_surf(img, pial, radius=radius, kind='line')
             self.surface_textures.append(surface)
             slu.mkdir_p(join(self.out_dir, 'surface_textures'))
             pd.DataFrame(surface, columns=['coef_', 'intercept_', 'r2_score', 'mean_squared_error']).\
                 to_csv(join(self.out_dir, 'surface_textures', '{0}_{1}_{2}_{3}.csv'.format(self.subject, self.session, param, hemisphere)))
Esempio n. 11
0
    def surface_plots(self, perf_img):
        print("Creating surface plots")

        figure, axes = plt.subplots(2,
                                    2,
                                    subplot_kw={"projection": "3d"},
                                    figsize=(12, 12))
        axes = axes.ravel()
        big_fsaverage = datasets.fetch_surf_fsaverage("fsaverage")

        cnt = 0
        for hemi, infl, sulc, pial in [
            (
                "left",
                big_fsaverage.infl_left,
                big_fsaverage.sulc_left,
                big_fsaverage.pial_left,
            ),
            (
                "right",
                big_fsaverage.infl_right,
                big_fsaverage.sulc_right,
                big_fsaverage.pial_right,
            ),
        ]:
            print("Hemi {}".format(hemi))

            big_texture = surface.vol_to_surf(perf_img,
                                              pial,
                                              interpolation="nearest")

            for view in ["lateral", "medial"]:
                print("   View {}".format(view))
                if cnt == 3:
                    output_file = os.path.join(
                        self.folder, "importance_scores_surface.png")
                else:
                    output_file = None
                plotting.plot_surf_stat_map(
                    infl,
                    big_texture,
                    hemi=hemi,
                    colorbar=True,
                    title="{} hemisphere {} view".format(hemi, view),
                    threshold=0.0001,
                    bg_map=sulc,
                    view=view,
                    output_file=output_file,
                    axes=axes[cnt],
                )
                cnt += 1
Esempio n. 12
0
 def vol_2surf(self, radius=.3):
     for param, img in self.voxel_regressions.items():
         for hemisphere in ['L', 'R']:
             pial = join(
                 self.flex_dir, 'fmri', 'completed_preprocessed',
                 self.subject, 'fmriprep', self.subject, 'anat',
                 '{0}_T1w_pial.{1}.surf.gii'.format(self.subject,
                                                    hemisphere))
             surface = vol_to_surf(img, pial, radius=radius, kind='line')
             self.surface_textures[param][hemisphere] = pd.DataFrame(
                 surface,
                 columns=[
                     'coef_', 'intercept_', 'r2_score', 'mean_squared_error'
                 ])
Esempio n. 13
0
def full_brain_info(volume_img,
                    mesh='fsaverage5',
                    threshold=None,
                    cmap=cm.cold_hot,
                    black_bg=False,
                    symmetric_cmap=True,
                    vmax=None,
                    vmin=None,
                    vol_to_surf_kwargs={}):
    """
    Project 3D map on cortex; prepare info to plot both hemispheres.


    This computes the dictionary that gets inserted in the web page,
    which contains encoded meshes, colors, min and max values, and
    background color.

    """
    info = {}
    mesh = surface.surface._check_mesh(mesh)
    surface_maps = {
        h: surface.vol_to_surf(volume_img,
                               mesh['pial_{}'.format(h)],
                               inner_mesh=mesh.get('white_{}'.format(h), None),
                               **vol_to_surf_kwargs)
        for h in ['left', 'right']
    }
    colors = colorscale(cmap,
                        np.asarray(list(surface_maps.values())).ravel(),
                        threshold,
                        symmetric_cmap=symmetric_cmap,
                        vmax=vmax,
                        vmin=vmin)

    for hemi, surf_map in surface_maps.items():
        bg_map = surface.load_surf_data(mesh['sulc_{}'.format(hemi)])
        info['pial_{}'.format(hemi)] = mesh_to_plotly(
            mesh['pial_{}'.format(hemi)])
        info['inflated_{}'.format(hemi)] = mesh_to_plotly(
            mesh['infl_{}'.format(hemi)])

        info['vertexcolor_{}'.format(hemi)] = _get_vertexcolor(
            surf_map, colors['cmap'], colors['norm'], colors['abs_threshold'],
            bg_map)
    info["cmin"], info["cmax"] = float(colors['vmin']), float(colors['vmax'])
    info['black_bg'] = black_bg
    info['full_brain_mesh'] = True
    info['colorscale'] = colors['colors']
    return info
Esempio n. 14
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)
Esempio n. 15
0
def add_surf_map(niimg, sides=['left', 'right'], selected=False,
                 threshold=None, **kwargs):
    """ Project a volumetric data and plot it on the corresponding
        fsaverage surface.

        The kwargs are passed to mlab.triangular_mesh
    """
    actors = dict()
    for side in sides:
        data = surface.vol_to_surf(niimg, fsaverage['pial_%s' % side])
        this_actor = plot_on_surf(data, selected=selected,
                                  sides=[side, ], threshold=threshold,
                                  **kwargs)
        actors[side] = this_actor[side]
    return actors
Esempio n. 16
0
    def extract_correlation_hemi(self,
                                 nifti_image,
                                 output_file,
                                 mesh,
                                 hemi='map_left'):
        """
        Input params:
            - hemi (hemisphere) = 'map_left' or 'map_right'
            - mesh : 'fsaverage.infl_left'
                    'fsaverage.infl_right'
                    'fsaverage.pial_left'
                    'fsaverage.pial_right'
                    'fsaverage.sulc_left'
                    'fsaverage.sulc_right'
        Output param:
            - correlation matrix and its zFisher values
            - Save the correlation matrix to csv file
        """
        # extract surface data from nifti image ###################
        surface_data = surface.vol_to_surf(nifti_image, surf_mesh=mesh)
        timeseries = surface.load_surf_data(surface_data)
        # fill Nan value with 0 and infinity with large finite numbers
        timeseries = np.nan_to_num(timeseries)
        # get destrieux atlas ######################################
        destrieux_atlas = datasets.fetch_atlas_surf_destrieux()
        labels = destrieux_atlas['labels']  # get labels
        parcellation = destrieux_atlas[hemi]  # get parcellation

        # convert timeseries surface to 2D matrix where each column is a ROI
        rois = []
        for i in range(len(labels)):
            pcc_labels = np.where(parcellation == i)[0]
            # each parcellation to 1D matrix
            seed_timeseries = np.mean(timeseries[pcc_labels], axis=0)
            rois.append(np.array(seed_timeseries))
        rois = np.array(rois).T
        rois = np.nan_to_num(rois)

        # extract correlation matrix
        correlation_measure = ConnectivityMeasure(kind='correlation')
        corr_rois = correlation_measure.fit_transform([rois])[0]
        corr_rois_z = np.arctanh(corr_rois)  # normalize to z-fisher

        # save the correlation to csv
        df = pd.DataFrame(corr_rois_z)
        df.to_csv(output_file, index=False, header=None)

        return corr_rois, corr_rois_z
Esempio n. 17
0
def plot_brain_saliences(custom_roi,
                         minval=0,
                         maxval=None,
                         figpath=None,
                         cbar=False,
                         cmap=None):
    mpl.rcParams.update(mpl.rcParamsDefault)
    if cmap is None:
        cmap = 'coolwarm'

    fsaverage = datasets.fetch_surf_fsaverage()

    orders = [('medial', 'left'), ('medial', 'right'), ('lateral', 'left'),
              ('lateral', 'right')]

    fig, ax = plt.subplots(nrows=2,
                           ncols=2,
                           figsize=(8.0, 6.0),
                           dpi=300,
                           frameon=False,
                           sharex=True,
                           sharey=True,
                           subplot_kw={'projection': '3d'})

    fig.subplots_adjust(hspace=0., wspace=0.00005)
    axes_list = fig.axes

    for index, order in enumerate(orders):
        view = order[0]
        hemi = order[1]

        texture = surface.vol_to_surf(custom_roi, fsaverage['pial_%s' % hemi])
        plotting.plot_surf_roi(fsaverage['infl_%s' % hemi],
                               texture,
                               cmap=cmap,
                               hemi=hemi,
                               view=view,
                               bg_on_data=True,
                               axes=axes_list[index],
                               bg_map=fsaverage['sulc_%s' % hemi],
                               vmin=minval,
                               vmax=maxval,
                               output_file=figpath,
                               symmetric_cbar=False,
                               figure=fig,
                               darkness=.5,
                               colorbar=cbar)
    plt.clf()
Esempio n. 18
0
 def mni_to_fsaverage(self):
     '''
     Extract surface data (fsaverage) from MNI152-nifti
     Uses nilearn.vol_to_surf: https://nilearn.github.io/modules/generated/nilearn.surface.vol_to_surf.html
     '''
     fs_average = datasets.fetch_surf_fsaverage(mesh='fsaverage')
     for param, img in self.voxel_regressions.items():
         for hemisphere, hemi in {'L': 'left', 'R': 'right'}.items():
             surface = vol_to_surf(img,
                                   fs_average['pial_{}'.format(hemi)],
                                   radius=.3,
                                   kind='line')
             self.surface_textures[param][hemisphere] = pd.DataFrame(
                 surface,
                 columns=[
                     'coef_', 'intercept_', 'r2_score', 'mean_squared_error'
                 ])
Esempio n. 19
0
 def vol_2surf(self):
     '''
     Extract surface data (subject surface) from subject-specific T1w-nifti
     Uses nilearn.vol_to_surf: https://nilearn.github.io/modules/generated/nilearn.surface.vol_to_surf.html
     '''
     for param, img in self.voxel_regressions.items():
         for hemisphere in ['L', 'R']:
             pial = join(
                 self.flex_dir, 'fmri', 'completed_preprocessed',
                 self.subject, 'fmriprep', self.subject, 'anat',
                 '{0}_T1w_pial.{1}.surf.gii'.format(self.subject,
                                                    hemisphere))
             surface = vol_to_surf(img, pial, radius=.3, kind='line')
             self.surface_textures[param][hemisphere] = pd.DataFrame(
                 surface,
                 columns=[
                     'coef_', 'intercept_', 'r2_score', 'mean_squared_error'
                 ])
Esempio n. 20
0
    def surface_plots(self, perf_img):
        print('Creating surface plots')

        figure, axes = plt.subplots(2,
                                    2,
                                    subplot_kw={'projection': '3d'},
                                    figsize=(12, 12))
        axes = axes.ravel()
        big_fsaverage = datasets.fetch_surf_fsaverage('fsaverage')

        cnt = 0
        for hemi, infl, sulc, pial in [
            ('left', big_fsaverage.infl_left, big_fsaverage.sulc_left,
             big_fsaverage.pial_left),
            ('right', big_fsaverage.infl_right, big_fsaverage.sulc_right,
             big_fsaverage.pial_right)
        ]:
            print('Hemi {}'.format(hemi))

            big_texture = surface.vol_to_surf(perf_img,
                                              pial,
                                              interpolation='nearest')

            for view in ['lateral', 'medial']:
                print('   View {}'.format(view))
                if cnt == 3:
                    output_file = os.path.join(
                        self.folder, 'importance_scores_surface.png')
                else:
                    output_file = None
                plotting.plot_surf_stat_map(
                    infl,
                    big_texture,
                    hemi=hemi,
                    colorbar=True,
                    title='{} hemisphere {} view'.format(hemi, view),
                    threshold=0.0001,
                    bg_map=sulc,
                    view=view,
                    output_file=output_file,
                    axes=axes[cnt])
                cnt += 1
Esempio n. 21
0
def to_three(mesh, stat_map, sample_mesh=None):
    if sample_mesh is None:
        sample_mesh = mesh
    mesh = surface.load_surf_mesh(mesh)
    coords = mesh[0][mesh[1].ravel()]
    surf_stat_map = surface.vol_to_surf(stat_map, sample_mesh)
    surf_stat_map -= surf_stat_map.min()
    surf_stat_map /= surf_stat_map.max()
    colors = cm.cold_hot(surf_stat_map[mesh[1].ravel()])[:, :3]
    center = list(map(float, mesh[0].mean(axis=0)))
    center = {'x': center[0], 'y': center[1], 'z': center[2]}
    vertices = np.asarray(coords.ravel(), dtype='<f4')
    # vertices = list(map(float, coords.ravel()))
    col = list(map(float, colors.ravel()))
    return {
        'INSERT_VERTICES_HERE':
        base64.b64encode(
            vertices.tobytes()).decode('utf-8'),  #json.dumps(vertices),
        'INSERT_COLORS_HERE':
        json.dumps(col),
        'INSERT_CENTER_POSITION_HERE':
        json.dumps(center)
    }
Esempio n. 22
0
stat_img2 = my_images

template_brain = 'B3'

b_obj_proj_ll = BrainObj(template_brain, hemisphere='left', translucent=False)
b_obj_proj_lr = BrainObj(template_brain, hemisphere='left', translucent=False)
b_obj_proj_rr = BrainObj(template_brain, hemisphere='right', translucent=False)
b_obj_proj_rl = BrainObj(template_brain, hemisphere='right', translucent=False)

meshll = [b_obj_proj_ll.vertices, b_obj_proj_ll.faces]
meshlr = [b_obj_proj_lr.vertices, b_obj_proj_lr.faces]

meshrr = [b_obj_proj_rr.vertices, b_obj_proj_rr.faces]
meshrl = [b_obj_proj_rl.vertices, b_obj_proj_rl.faces]

texturell = surface.vol_to_surf(stat_img2, meshll)
texturelr = surface.vol_to_surf(stat_img2, meshlr)
texturerr = surface.vol_to_surf(stat_img2, meshrr)
texturerl = surface.vol_to_surf(stat_img2, meshrl)

texturell = texturell.ravel()
texturelr = texturelr.ravel()
texturerr = texturerr.ravel()
texturerl = texturerl.ravel()

b_obj_proj_ll.add_activation(texturell,
                             hemisphere='left',
                             cmap='hot_r',
                             vmin=0,
                             vmax=1,
                             clim=(0, 1))
stat_img = motor_images.images[0]


##############################################################################
# Get a cortical mesh
# -------------------

fsaverage = datasets.fetch_surf_fsaverage()

##############################################################################
# Sample the 3D data around each node of the mesh
# -----------------------------------------------

from nilearn import surface

texture = surface.vol_to_surf(stat_img, fsaverage.pial_right)

##############################################################################
# Plot the result
# ---------------

from nilearn import plotting

plotting.plot_surf_stat_map(fsaverage.infl_right, texture, hemi='right',
                            title='Surface right hemisphere', colorbar=True,
                            threshold=1., bg_map=fsaverage.sulc_right)

##############################################################################
# Plot 3D image for comparison
# ----------------------------
Esempio n. 24
0
def plot_img_on_surf(stat_map,
                     surf_mesh='fsaverage5',
                     mask_img=None,
                     hemispheres=['left', 'right'],
                     inflate=False,
                     views=['lateral', 'medial'],
                     output_file=None,
                     title=None,
                     colorbar=True,
                     vmax=None,
                     threshold=None,
                     cmap='cold_hot',
                     aspect_ratio=1.4,
                     **kwargs):
    """Convenience function to plot multiple views of plot_surf_stat_map
    in a single figure. It projects stat_map into meshes and plots views of
    left and right hemispheres. The *views* argument defines the views
    that are shown. This function returns the fig, axes elements from
    matplotlib unless kwargs sets and output_file, in which case nothing
    is returned.

    Parameters
    ----------
    stat_map : str or 3D Niimg-like object
        See http://nilearn.github.io/manipulating_images/input_output.html

    surf_mesh : str, dict, or None, optional
        If str, either one of the two:
        'fsaverage5': the low-resolution fsaverage5 mesh (10242 nodes)
        'fsaverage': the high-resolution fsaverage mesh (163842 nodes)
        If dict, a dictionary with keys: ['infl_left', 'infl_right',
        'pial_left', 'pial_right', 'sulc_left', 'sulc_right'], where
        values are surface mesh geometries as accepted by plot_surf_stat_map.
        Default='fsaverage5'.

    mask_img : Niimg-like object or None, optional
        The mask is passed to vol_to_surf.
        Samples falling out of this mask or out of the image are ignored
        during projection of the volume to the surface.
        If ``None``, don't apply any mask.

    inflate : bool, optional
        If True, display images in inflated brain.
        If False, display images in pial surface.
        Default=False.

    views : list of strings, optional
        A list containing all views to display.
        The montage will contain as many rows as views specified by
        display mode. Order is preserved, and left and right hemispheres
        are shown on the left and right sides of the figure.
        Default=['lateral', 'medial'].

    hemispheres : list of strings, optional
        Hemispheres to display. Default=['left', 'right'].

    output_file : str, optional
        The name of an image file to export plot to. Valid extensions
        are: *.png*, *.pdf*, *.svg*. If output_file is not None,
        the plot is saved to a file, and the display is closed. Return
        value is None.

    title : str, optional
        Place a title on the upper center of the figure.

    colorbar : bool, optional
        If *True*, a symmetric colorbar of the statistical map is displayed.
        Default=True.

    vmax : float, optional
        Upper bound for plotting of stat_map values.

    threshold : float, optional
        If None is given, the image is not thresholded.
        If a number is given, it is used to threshold the image,
        values below the threshold (in absolute value) are plotted
        as transparent.

    cmap : str, optional
        The name of a matplotlib or nilearn colormap. Default='cold_hot'.

    kwargs : dict, optional
        keyword arguments passed to plot_surf_stat_map.

    See Also
    --------
    nilearn.datasets.fetch_surf_fsaverage : For surface data object to be
        used as the default background map for this plotting function.

    nilearn.surface.vol_to_surf : For info on the generation of surfaces.

    nilearn.plotting.plot_surf_stat_map : For info on kwargs options
        accepted by plot_img_on_surf.

    """
    for arg in ('figure', 'axes'):
        if arg in kwargs:
            raise ValueError(('plot_img_on_surf does not'
                              ' accept %s as an argument' % arg))

    stat_map = check_niimg_3d(stat_map, dtype='auto')
    modes = _check_views(views)
    hemis = _check_hemispheres(hemispheres)
    surf_mesh = _check_mesh(surf_mesh)

    mesh_prefix = "infl" if inflate else "pial"
    surf = {
        'left': surf_mesh[mesh_prefix + '_left'],
        'right': surf_mesh[mesh_prefix + '_right'],
    }

    texture = {
        'left': vol_to_surf(stat_map,
                            surf_mesh['pial_left'],
                            mask_img=mask_img),
        'right': vol_to_surf(stat_map,
                             surf_mesh['pial_right'],
                             mask_img=mask_img)
    }

    figsize = plt.figaspect(len(modes) / (aspect_ratio * len(hemispheres)))
    fig, axes = plt.subplots(nrows=len(modes),
                             ncols=len(hemis),
                             figsize=figsize,
                             subplot_kw={'projection': '3d'})

    axes = np.atleast_2d(axes)

    if len(hemis) == 1:
        axes = axes.T

    for index_mode, mode in enumerate(modes):
        for index_hemi, hemi in enumerate(hemis):
            bg_map = surf_mesh['sulc_%s' % hemi]
            plot_surf_stat_map(
                surf[hemi],
                texture[hemi],
                view=mode,
                hemi=hemi,
                bg_map=bg_map,
                axes=axes[index_mode, index_hemi],
                colorbar=False,  # Colorbar created externally.
                vmax=vmax,
                threshold=threshold,
                cmap=cmap,
                **kwargs)

    for ax in axes.flatten():
        # We increase this value to better position the camera of the
        # 3D projection plot. The default value makes meshes look too small.
        ax.dist = 6

    if colorbar:
        sm = _colorbar_from_array(image.get_data(stat_map),
                                  vmax,
                                  threshold,
                                  kwargs,
                                  cmap=get_cmap(cmap))

        cbar_ax = fig.add_subplot(32, 1, 32)
        fig.colorbar(sm, cax=cbar_ax, orientation='horizontal')

    fig.subplots_adjust(wspace=-0.02, hspace=0.0)

    if title is not None:
        fig.suptitle(title)

    if output_file is not None:
        fig.savefig(output_file)
        plt.close(fig)
    else:
        return fig, axes
# Project the fMRI image to the surface
# -------------------------------------
#
# For this we need to get a mesh representing the geometry of the
# surface.  We could use an individual mesh, but we first resort to a
# standard mesh, the so-called fsaverage5 template from the FreeSurfer
# software.

import nilearn
fsaverage = nilearn.datasets.fetch_surf_fsaverage()

#########################################################################
# The projection function simply takes the fMRI data and the mesh.
# Note that those correspond spatially, are they are both in MNI space.
from nilearn import surface
texture = surface.vol_to_surf(fmri_img, fsaverage.pial_right)

#########################################################################
# Perform first level analysis
# ----------------------------
#
# This involves computing the design matrix and fitting the model.
# We start by specifying the timing of fMRI frames.

import numpy as np
n_scans = texture.shape[1]
frame_times = t_r * (np.arange(n_scans) + .5)

#########################################################################
# Create the design matrix.
#
#########################################################################
# The projection function simply takes the fMRI data and the mesh.
# Note that those correspond spatially, are they are bothin MNI space.
import numpy as np
from nilearn import surface
from nistats.design_matrix import make_first_level_design_matrix
from nistats.first_level_model import run_glm
from nistats.contrasts import compute_contrast

#########################################################################
# Empty lists in which we are going to store activation values.
z_scores_right = []
z_scores_left = []
for (fmri_img, confound, events) in zip(
        models_run_imgs, models_confounds, models_events):
    texture = surface.vol_to_surf(fmri_img[0], fsaverage.pial_right)
    n_scans = texture.shape[1]
    frame_times = t_r * (np.arange(n_scans) + .5)

    # Create the design matrix
    #
    # We specify an hrf model containing Glover model and its time derivative
    # the drift model is implicitly a cosine basis with period cutoff 128s.
    design_matrix = make_first_level_design_matrix(
        frame_times, events=events[0], hrf_model='glover + derivative',
        add_regs=confound[0])

    # contrast_specification
    contrast_values = (design_matrix.columns == 'language') * 1.0 -\
                      (design_matrix.columns == 'string')
y, session = y[condition_mask], session[condition_mask]

#########################################################################
# Surface bold response
# ----------------------
from nilearn import datasets, surface
from sklearn import neighbors

# Fetch a coarse surface of the left hemisphere only for speed
fsaverage = datasets.fetch_surf_fsaverage(mesh='fsaverage5')
hemi = 'left'

# Average voxels 5 mm close to the 3d pial surface
radius = 5.
pial_mesh = fsaverage['pial_' + hemi]
X = surface.vol_to_surf(fmri_img, pial_mesh, radius=radius).T

# To define the BOLD responses to be included within each searchlight "sphere"
# we define an adjacency matrix based on the inflated surface vertices such
# that nearby surfaces are concatenated within the same searchlight.

infl_mesh = fsaverage['infl_' + hemi]
coords, _ = surface.load_surf_mesh(infl_mesh)
radius = 3.
nn = neighbors.NearestNeighbors(radius=radius)
adjacency = nn.fit(coords).radius_neighbors_graph(coords).tolil()

#########################################################################
# Searchlight computation
# -----------------------
from sklearn.model_selection import KFold
localizer_dataset = datasets.fetch_localizer_button_task()
localizer_tmap = localizer_dataset.tmaps[0]

##############################################################################
# Get a cortical mesh
# -------------------

fsaverage = datasets.fetch_surf_fsaverage5()

##############################################################################
# Sample the 3D data around each node of the mesh
# -----------------------------------------------

from nilearn import surface

texture = surface.vol_to_surf(localizer_tmap, fsaverage.pial_right)

##############################################################################
# Plot the result
# ---------------

from nilearn import plotting

plotting.plot_surf_stat_map(fsaverage.infl_right, texture, hemi='right',
                            title='Surface right hemisphere',
                            threshold=1., bg_map=fsaverage.sulc_right)

##############################################################################
# Plot 3D image for comparison
# ----------------------------
Esempio n. 29
0
%matplotlib qt
nilearn.plotting.plot_stat_map(nilearn.image.smooth_img('/media/Data/work/KPE_SPM/Sink_ses-2/2ndLevel/_contrast_id_con_0001/spmT_0001.nii', 3), display_mode='x',
                                      threshold=5.5, bg_img=anatimg, dim=1)#%% Stat maps
for con_image in conImages:
    nilearn.plotting.plot_stat_map(con_image, display_mode='ortho',
                              threshold=2.3)#, cut_coords=(20,55)) #, 10, 15), dim=1) 
#%% Surface display
import nibabel as nib

from nilearn.plotting import plot_stat_map
from nilearn import datasets, surface, plotting
from nilearn import datasets
fsaverage = datasets.fetch_surf_fsaverage()
from nilearn import surface

texture = surface.vol_to_surf('/media/Data/work/KPE_SPM/Sink_ses-2/2ndLevel/_contrast_id_con_0001/spmT_0001_thr.nii', fsaverage.pial_right)
from nilearn import plotting
a = '/media/Data/KPE_fmriPrep_preproc/kpeOutput/derivatives/fmriprep/sub-1263/ses-1/func/sub-1263_ses-1_task-Memory_space-fsaverage5_hemi-R.func.gii'
plotting.plot_surf_stat_map(fsaverage.infl_right, texture, hemi='right',
                            title='Surface right hemisphere', colorbar=True,
                            threshold=0., bg_map=a)#fsaverage.sulc_right)
big_fsaverage = datasets.fetch_surf_fsaverage('fsaverage')
fmri_img = nib.load('/media/Data/work/KPE_SPM/Sink_ses-2/2ndLevel/_contrast_id_con_0001/spmT_0001_thr.nii')
big_texture_right = surface.vol_to_surf(fmri_img, big_fsaverage.pial_right)
%matplotlib inline

plotting.plot_surf_stat_map(big_fsaverage.infl_right,
                            big_texture_right, 
                            hemi='right', colorbar=True,
                            title='',
                            threshold=3, 
Esempio n. 30
0
motor_images = datasets.fetch_neurovault_motor_task()
stat_img = motor_images.images[0]

##############################################################################
# Get a cortical mesh
# -------------------

fsaverage = datasets.fetch_surf_fsaverage()

##############################################################################
# Sample the 3D data around each node of the mesh
# -----------------------------------------------

from nilearn import surface

texture = surface.vol_to_surf(stat_img, fsaverage.pial_right)

##############################################################################
# Plot the result
# ---------------
#
# You can visualize the texture on the surface using the function
# :func:`~nilearn.plotting.plot_surf_stat_map` which uses ``matplotlib``
# as the default plotting engine:

from nilearn import plotting

fig = plotting.plot_surf_stat_map(fsaverage.infl_right,
                                  texture,
                                  hemi='right',
                                  title='Surface right hemisphere',
Esempio n. 31
0
def plot_brainrsa_surface(img, threshold=None, type='r'):

    """
    Plot the RSA-result into a brain surface

    Parameters
    ----------
    img : string
        The file path of the .nii file of the RSA results.
    threshold : None or int. Default is None.
        The threshold of the number of voxels used in correction.
        If threshold=n, only the similarity clusters consisting more than threshold voxels will be visible. If it is
        None, the threshold-correction will not work.
    type : string 'r' or 't'
        The type of result (r-values or t-values).
    """

    imgarray = nib.load(img).get_data()

    if (imgarray == np.nan).all() == True:

        print("No Valid Results")

    else:

        if threshold != None:

            imgarray = nib.load(img).get_data()
            affine = get_affine(img)
            imgarray = correct_by_threshold(imgarray, threshold)
            img = nib.Nifti1Image(imgarray, affine)

        fsaverage = datasets.fetch_surf_fsaverage(mesh='fsaverage')
        texture_left = surface.vol_to_surf(img, fsaverage.pial_left)
        texture_right = surface.vol_to_surf(img, fsaverage.pial_right)

        # type='r'
        if type == 'r':
            plotting.plot_surf_stat_map(fsaverage.pial_left, texture_left, hemi='left', threshold=0.1,
                                        bg_map=fsaverage.sulc_right, colorbar=False, vmax=0.8, darkness=0.7)

            plotting.plot_surf_stat_map(fsaverage.pial_right, texture_right, hemi='right', threshold=0.1,
                                        bg_map=fsaverage.sulc_right, colorbar=True, vmax=0.8, darkness=0.7)

            plotting.plot_surf_stat_map(fsaverage.pial_right, texture_left, hemi='left', threshold=0.1,
                                        bg_map=fsaverage.sulc_right, colorbar=False, vmax=0.8, darkness=0.7)

            plotting.plot_surf_stat_map(fsaverage.pial_left, texture_right, hemi='right', threshold=0.1,
                                        bg_map=fsaverage.sulc_right, colorbar=True, vmax=0.8, darkness=0.7)

            plt.show()

        # type='t'
        if type == 't':
            plotting.plot_surf_stat_map(fsaverage.pial_left, texture_left, hemi='left', threshold=0.8,
                                        bg_map=fsaverage.sulc_right, colorbar=False, darkness=0.7)

            plotting.plot_surf_stat_map(fsaverage.pial_right, texture_right, hemi='right', threshold=0.8,
                                        bg_map=fsaverage.sulc_right, colorbar=True, darkness=0.7)

            plotting.plot_surf_stat_map(fsaverage.pial_right, texture_left, hemi='left', threshold=0.8,
                                        bg_map=fsaverage.sulc_right, colorbar=False, darkness=0.7)

            plotting.plot_surf_stat_map(fsaverage.pial_left, texture_right, hemi='right', threshold=0.8,
                                        bg_map=fsaverage.sulc_right, colorbar=True, darkness=0.7)

            plt.show()
                 f'subj01_{model1}-{model2}_test_rho.nii.gz'))
rho_map = masker.transform(file)
rho_map_pos = [val if val > 0 else 0 for val in rho_map[0]]

rho_map = masker.inverse_transform(rho_map)
rho_map_pos = masker.inverse_transform(rho_map_pos)

#%%
# get surface mesh (fsaverage)
fsaverage = datasets.fetch_surf_fsaverage()

#%%
# project volume onto surface
# Caution: the projection is done for one hemisphere only, make sure to plot
# (below) for the same hemisphere
img_to_plot = surface.vol_to_surf(rho_map_pos, fsaverage.pial_right)

#%%
# plot surface
# note: the bg_map and hemi should be the same hemisphere as fsaverage.???
plotting.plot_surf_stat_map(fsaverage.infl_right,
                            img_to_plot,
                            hemi='right',
                            bg_map=fsaverage.sulc_right,
                            view='lateral',
                            title='Surface plot',
                            colorbar=True,
                            threshold=0.01)

#%%
# plot glass brain
for x in list(range(0, len(temp0state4))):
    LOstate4[LOstate4 == temp0state4.label[x]] = temp0state4.value[x]
atlas_0state4 = nib.Nifti1Image(LOstate4, atlas_filename.affine,
                                atlas_filename.header)

LOstate5 = data.astype(float)
temp0state5 = pd.DataFrame({'label': labellist, 'value': state5x_norm})
for x in list(range(0, len(temp0state5))):
    LOstate5[LOstate5 == temp0state5.label[x]] = temp0state5.value[x]
atlas_0state5 = nib.Nifti1Image(LOstate5, atlas_filename.affine,
                                atlas_filename.header)

fsaverage = datasets.fetch_surf_fsaverage('fsaverage')

####### Plot state 1
texturestate1_l = surface.vol_to_surf(atlas_0state1, fsaverage.pial_left)
texturestate1_r = surface.vol_to_surf(atlas_0state1, fsaverage.pial_right)

fig, axs = plt.subplots(ncols=4,
                        nrows=1,
                        subplot_kw={'projection': '3d'},
                        figsize=(22, 5))
fig.tight_layout()
plotting.plot_surf_stat_map(surf_mesh=fsaverage.infl_right,
                            stat_map=texturestate1_r,
                            bg_map=fsaverage.sulc_right,
                            hemi='right',
                            view='lateral',
                            threshold=.084,
                            colorbar=False,
                            axes=axs[0])
Esempio n. 34
0
    fname = os.path.splitext(os.path.basename(n))[0]

    b_obj_proj_ll = BrainObj(template_brain, hemisphere='left', translucent=False)
    b_obj_proj_lr = BrainObj(template_brain, hemisphere='left', translucent=False)
    b_obj_proj_rr = BrainObj(template_brain, hemisphere='right', translucent=False)
    b_obj_proj_rl = BrainObj(template_brain, hemisphere='right', translucent=False)


    meshll  = [b_obj_proj_ll.vertices, b_obj_proj_ll.faces]
    meshlr  = [b_obj_proj_lr.vertices, b_obj_proj_lr.faces]

    meshrr  = [b_obj_proj_rr.vertices, b_obj_proj_rr.faces]
    meshrl  = [b_obj_proj_rl.vertices, b_obj_proj_rl.faces]

    texturell = surface.vol_to_surf(nii, meshll)
    texturelr = surface.vol_to_surf(nii, meshlr)
    texturerr = surface.vol_to_surf(nii, meshrr)
    texturerl = surface.vol_to_surf(nii, meshrl)

    texturell = texturell.ravel()
    texturelr = texturelr.ravel()
    texturerr = texturerr.ravel()
    texturerl = texturerl.ravel()


    b_obj_proj_ll.add_activation(texturell, hemisphere='left',
                         cmap='hot_r',
                         vmin=0,
                         vmax=1,
                         clim=(0, 1))