Exemple #1
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() 
Exemple #2
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
Exemple #3
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'))
Exemple #4
0
def plot_surfaces(grad_dict, index, outdir):
    grad_lh = grad_dict["grads_lh"][:, index]
    if np.max(grad_lh[grad_lh > 0]) > np.abs(np.min(grad_lh[grad_lh < 0])):
        grad_lh[grad_lh < 0] = grad_lh[grad_lh < 0] / np.abs(np.min(grad_lh[grad_lh < 0]))
        grad_lh[grad_lh < 0] = grad_lh[grad_lh < 0] * np.max(grad_lh[grad_lh > 0])
    else:
        grad_lh[grad_lh > 0] = grad_lh[grad_lh > 0] / np.max(grad_lh[grad_lh > 0])
        grad_lh[grad_lh > 0] = grad_lh[grad_lh > 0] * np.abs(np.min(grad_lh[grad_lh < 0]))
    plotting.plot_surf_stat_map(
        grad_dict["pial_left"],
        grad_lh,
        hemi="left",
        bg_map=grad_dict["sulc_left"],
        bg_on_data=True,
        colorbar=False,
        view="medial",
        cmap="jet",
        output_file=op.join(outdir, "gradient-{0}_left_medial.png".format(index)),
    )
    plotting.plot_surf_stat_map(
        grad_dict["pial_left"],
        grad_lh,
        hemi="left",
        bg_map=grad_dict["sulc_left"],
        bg_on_data=True,
        colorbar=False,
        view="lateral",
        cmap="jet",
        output_file=op.join(outdir, "gradient-{0}_left_lateral.png".format(index)),
    )
    grad_rh = grad_dict["grads_rh"][:, index]
    if np.max(grad_rh[grad_rh > 0]) > np.abs(np.min(grad_rh[grad_rh < 0])):
        grad_rh[grad_rh < 0] = grad_rh[grad_rh < 0] / np.abs(np.min(grad_rh[grad_rh < 0]))
        grad_rh[grad_rh < 0] = grad_rh[grad_rh < 0] * np.max(grad_rh[grad_rh > 0])
    else:
        grad_rh[grad_rh > 0] = grad_rh[grad_rh > 0] / np.max(grad_rh[grad_rh > 0])
        grad_rh[grad_rh > 0] = grad_rh[grad_rh > 0] * np.abs(np.min(grad_rh[grad_rh < 0]))
    plotting.plot_surf_stat_map(
        grad_dict["pial_right"],
        grad_rh,
        hemi="right",
        bg_map=grad_dict["sulc_right"],
        bg_on_data=True,
        colorbar=False,
        view="medial",
        cmap="jet",
        output_file=op.join(outdir, "gradient-{0}_right_medial.png".format(index)),
    )
    plotting.plot_surf_stat_map(
        grad_dict["pial_right"],
        grad_rh,
        hemi="right",
        bg_map=grad_dict["sulc_right"],
        bg_on_data=True,
        colorbar=True,
        view="lateral",
        cmap="jet",
        output_file=op.join(outdir, "gradient-{0}_right_lateral.png".format(index)),
    )
Exemple #5
0
def make_surf_plot(data, surf='inflated', version='fsaverage5', **kwargs):
    """
    Generates 2 x 2 surface plot of `data`

    Parameters
    ----------
    data : array_like
        Data to be plotted; should be left hemisphere first
    surf : {'orig', 'white', 'smoothwm', 'pial', 'inflated', 'sphere'}
        Which surface plot should be displaye don
    version : {'fsaverage', 'fsaverage5', 'fsaverage6'}
        Which fsaverage surface to use for plots. Dimensionality of `data`
        should match resolution of surface

    Returns
    -------
    fig : matplotlib.figure.Figure
        Figure object
    """

    # get plotting kwargs
    data = np.nan_to_num(data)
    opts = dict(colorbar=False, vmax=data.max())
    opts.update(kwargs)
    for key in ['hemi', 'view', 'axes']:
        if key in opts:
            del opts[key]

    data = np.split(data, 2)
    fs = fetch_fsaverage(version)[surf]

    fig, axes = plt.subplots(2, 2, subplot_kw={'projection': '3d'})
    for row, view in zip(axes, ['lateral', 'medial']):
        for n, (col, hemi) in enumerate(zip(row, ['lh', 'rh'])):
            fn = getattr(fs, hemi)
            hemi = 'left' if hemi == 'lh' else 'right'

            plot_surf_stat_map(fn,
                               data[n],
                               hemi=hemi,
                               view=view,
                               axes=col,
                               **opts)

    fig.tight_layout()

    return fig
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()
Exemple #7
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
def make_thumbnail_surface(func,
                           hemi,
                           threshold=3.0,
                           vmax=10.,
                           output_dir='/tmp'):
    if os.path.exists('/neurospin/ibc'):
        dir_ = '/neurospin/ibc/derivatives/sub-01/ses-00/anat/fsaverage/surf'
    else:
        dir_ = '/storage/store/data/ibc/derivatives/sub-01/ses-00/anat/' + \
               'fsaverage/surf'
    if hemi == 'right':
        mesh = os.path.join(dir_, 'rh.inflated')
        bg_map = os.path.join(dir_, 'rh.sulc')
    else:
        mesh = os.path.join(dir_, 'lh.inflated')
        bg_map = os.path.join(dir_, 'lh.sulc')

    medial = '/tmp/surf_medial_%s.png' % hemi
    lateral = '/tmp/surf_lateral_%s.png' % hemi
    # threshold = fdr_threshold(func, .05)
    plotting.plot_surf_stat_map(mesh,
                                func,
                                hemi=hemi,
                                vmax=vmax,
                                threshold=threshold,
                                bg_map=bg_map,
                                view='lateral',
                                output_file=lateral)
    plotting.plot_surf_stat_map(mesh,
                                func,
                                hemi=hemi,
                                vmax=vmax,
                                threshold=threshold,
                                bg_map=bg_map,
                                view='medial',
                                output_file=medial)
    return medial, lateral
def plot_dscalar(
    img,
    colorbar=True,
    plot_abs=False,
    vmax=None,
    threshold=None,
    cmap='cold_hot',
    output_file=None,
):
    import matplotlib as mpl
    from matplotlib import pyplot as plt

    subcort, ltexture, rtexture = decompose_dscalar(img)
    fig = plt.figure(figsize=(11, 9))
    ax1 = plt.subplot2grid((3, 2), (0, 0), projection='3d')
    ax2 = plt.subplot2grid((3, 2), (0, 1), projection='3d')
    ax3 = plt.subplot2grid((3, 2), (1, 0), projection='3d')
    ax4 = plt.subplot2grid((3, 2), (1, 1), projection='3d')
    ax5 = plt.subplot2grid((3, 2), (2, 0), colspan=2)
    surf_fmt = 'data/conte69/tpl-conte69_hemi-{hemi}_space-fsLR_den-32k_inflated.surf.gii'.format
    lsurf = nb.load(resource_filename('fitlins',
                                      surf_fmt(hemi='L'))).agg_data()
    rsurf = nb.load(resource_filename('fitlins',
                                      surf_fmt(hemi='R'))).agg_data()
    kwargs = {
        'threshold': None if threshold == 'auto' else threshold,
        'colorbar': False,
        'plot_abs': plot_abs,
        'cmap': cmap,
        'vmax': vmax,
    }
    nlp.plot_surf_stat_map(lsurf, ltexture, view='lateral', axes=ax1, **kwargs)
    nlp.plot_surf_stat_map(rsurf, rtexture, view='medial', axes=ax2, **kwargs)
    nlp.plot_surf_stat_map(lsurf, ltexture, view='medial', axes=ax3, **kwargs)
    nlp.plot_surf_stat_map(rsurf, rtexture, view='lateral', axes=ax4, **kwargs)
    nlp.plot_glass_brain(subcort, display_mode='lyrz', axes=ax5, **kwargs)
    if colorbar:
        data = img.get_fdata(dtype=np.float32)
        if vmax is None:
            vmax = max(-data.min(), data.max())
        norm = mpl.colors.Normalize(vmin=-vmax if data.min() < 0 else 0,
                                    vmax=vmax)
        sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
        fig.colorbar(sm, ax=fig.axes, location='right', aspect=50)
    if output_file:
        fig.savefig(output_file)
        plt.close(fig)
ax.set_yticklabels(nice_contrasts[half_contrasts:])
ax.plot([0.017, 0.017], [0, len(contrasts)], 'g', linewidth=2)
#
#plt.subplots_adjust(left=.4, right=.99, bottom=.03, top=.99)
plt.savefig(os.path.join(write_dir, 'score_per_contrast.png'))
plt.show(block=False)

print(n_dim, n_parcellations, np.mean(con_scores))

fsaverage = fetch_surf_fsaverage()
texture = vol_to_surf(mean_vox_scores_img, fsaverage.pial_right)
output_file = os.path.join(write_dir, 'score_rh.png')
plot_surf_stat_map(fsaverage.infl_right,
                   texture,
                   hemi='right',
                   colorbar=False,
                   output_file=output_file,
                   threshold=0.,
                   bg_map=fsaverage.sulc_right,
                   vmax=.25)
texture = vol_to_surf(mean_vox_scores_img, fsaverage.pial_left)
output_file = os.path.join(write_dir, 'score_lh.png')
plot_surf_stat_map(fsaverage.infl_left,
                   texture,
                   hemi='left',
                   colorbar=False,
                   output_file=output_file,
                   threshold=0.,
                   bg_map=fsaverage.sulc_left,
                   vmax=.25)

###############################################################################
##############################################################################
# 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
# ----------------------------

plotting.plot_glass_brain(stat_img, display_mode='r', plot_abs=False,
                          title='Glass brain', threshold=2.)

plotting.plot_stat_map(stat_img, display_mode='x', threshold=1.,
                       cut_coords=range(0, 51, 10), title='Slices')


##############################################################################
# Plot with higher-resolution mesh
if hemi == 'left':
    coords_x, faces_x, beta_mesh_x, sulc_x =\
        coords_l, faces_l, beta_mesh_l, sulc_l
elif hemi == 'right':
    coords_x, faces_x, beta_mesh_x, sulc_x =\
        coords_r, faces_r, beta_mesh_r, sulc_r

vmax_beta = np.max(np.abs(beta)) / 10
vmax_beta = np.max(np.abs(beta_mesh_x) * 1000) / 10

plotting.plot_surf_stat_map(
    [coords_x, faces_x],
    stat_map=1000 * beta_mesh_x,
    hemi=hemi,
    view=view,
    bg_map=sulc_x,  #bg_on_data=True,
    #vmax = vmax_beta,#stat[2] / 10,#vmax=vmax_beta,
    darkness=.5,
    cmap=plt.cm.seismic,
    #symmetric_cbar=True,
    #output_file=output_filename
)

print(pd.Series((beta_mesh_l[beta_mesh_l != 0]).ravel()).describe())
print(pd.Series((beta_mesh_r[beta_mesh_r != 0]).ravel()).describe())

mesh_processing.save_texture(os.path.join(WD_CLUST, "beta_lh.gii"),
                             beta_mesh_l)

mesh_processing.save_texture(os.path.join(WD_CLUST, "beta_rh.gii"),
                             beta_mesh_r)
Exemple #13
0
def plot_full_surf_stat_map(stat,
                            title=None,
                            ts=None,
                            mask=None,
                            inflate=False,
                            outfile=None,
                            add_colorbar=True,
                            vmax=None,
                            **kwargs):
    """Use nilearn's plot_surf_stat_map to plot volume data in the surface.
    Plots a collage of both hemispheres and both medial and lateral views of
    the brain. The surface mesh used for plotting is freesurfer's fsaverage.

    :param stat: A 3D statistical map (Nilearn's niimg object)
    :param title: A title for the image
    :param ts: Optional timeseries to be plotted in the background.
    :param mask: Optional mask passed to nilearn's vol_to_surf.
    :param inflate: If True, plot on inflated, if False, on pial.
    :param outfile: Optional output filename to save figure.
    :param vmax: Colormap vmax limit

    Other kwargs are passed to Nilearn's plot_surf_stat_map.
    """

    fig, axes = plt.subplots(dpi=100,
                             nrows=2,
                             ncols=2,
                             subplot_kw={'projection': '3d'})
    ((ax_ll, ax_rl), (ax_lm, ax_rm)) = axes

    # Compute the surface textures from the statistical map.
    texture_r = surface.vol_to_surf(stat, FSAVERAGE.pial_right, mask_img=mask)
    texture_l = surface.vol_to_surf(stat, FSAVERAGE.pial_left, mask_img=mask)

    # Vmax scaled for optimal dynamic range.
    if vmax is None:
        vmax = fast_abs_percentile(stat.dataobj, 99.8)

    # Plot on inflated brain or on pial surface?
    if inflate:
        leftsurf = FSAVERAGE.infl_left
        rightsurf = FSAVERAGE.infl_right
    else:
        leftsurf = FSAVERAGE.pial_left
        rightsurf = FSAVERAGE.pial_right

    plotting.plot_surf_stat_map(rightsurf,
                                texture_r,
                                colorbar=False,
                                hemi='right',
                                axes=ax_rl,
                                bg_map=FSAVERAGE.sulc_right,
                                vmax=vmax,
                                **kwargs)
    plotting.plot_surf_stat_map(rightsurf,
                                texture_r,
                                colorbar=False,
                                hemi='right',
                                view='medial',
                                axes=ax_rm,
                                bg_map=FSAVERAGE.sulc_right,
                                vmax=vmax,
                                **kwargs)

    plotting.plot_surf_stat_map(leftsurf,
                                texture_l,
                                colorbar=False,
                                hemi='left',
                                axes=ax_ll,
                                bg_map=FSAVERAGE.sulc_left,
                                vmax=vmax,
                                **kwargs)
    plotting.plot_surf_stat_map(leftsurf,
                                texture_l,
                                colorbar=False,
                                hemi='left',
                                view='medial',
                                axes=ax_lm,
                                bg_map=FSAVERAGE.sulc_left,
                                vmax=vmax,
                                **kwargs)

    # The default camera distance in the 3D plot makes the surfaces look small.
    # The fix is simple, bring the camera closer to the object.
    for ax in axes.flatten():
        ax.dist = 6
        # Alpha set to 0 so that the timeseries is visible.
        ax.patch.set_alpha(0.)
    # Remove whitespace between subplots.
    fig.subplots_adjust(wspace=-0.02, hspace=0.0)

    if ts is not None:
        # x0, y0, width, height = 0.34, 0.465, 0.38, 0.06
        # x0 left -> right, y0 top -> down.
        x0, y0 = 0.15, 0.445
        width, height = (1.05 - 2 * x0), 0.12
        ax5 = fig.add_axes([x0, y0, width, height], zorder=-1)
        ax5.plot(ts[::2], 'dimgray', linewidth=0.8)
        ax5.axis('off')
        # Only necessary if ax5 is on top. (zorder larger than other axes)
        # ax5.patch.set_alpha(0.)

    # Add colorbar
    if add_colorbar:
        if 'threshold' in kwargs:
            if kwargs['threshold'] is not None:
                threshold = kwargs['threshold']
            else:
                threshold = 0

        vmin = -vmax  # when also displaying negative values, change to -vmax
        if 'cmap' in kwargs:
            cmap = nilearn_cmaps[kwargs['cmap']]
        else:
            cmap = nilearn_cmaps['cold_hot']

        norm = Normalize(vmin=vmin, vmax=vmax)
        cmaplist = [cmap(i) for i in range(cmap.N)]
        # set colors to grey for absolute values < threshold
        istart = int(norm(-threshold, clip=True) * (cmap.N - 1))
        istop = int(norm(threshold, clip=True) * (cmap.N - 1))
        for i in range(istart, istop):
            cmaplist[i] = (0.5, 0.5, 0.5, 1.)
        our_cmap = LinearSegmentedColormap.from_list('Custom cmap', cmaplist,
                                                     cmap.N)
        sm = plt.cm.ScalarMappable(cmap=our_cmap,
                                   norm=plt.Normalize(vmin=vmin, vmax=vmax))
        # fake up the array of the scalar mappable.
        sm._A = []
        # fig.subplots_adjust(bottom=0.05)
        cbar_ax = fig.add_subplot(32, 1,
                                  32)  # fig.add_axes([0.3, 0.9, 0.4, 0.03])
        fig.colorbar(sm, cax=cbar_ax, orientation='horizontal')

    if title is not None:
        # y defaults to 0.98. The value of 0.93 lowers it a bit.
        fig.suptitle(title, fontsize=12, y=0.93)

    if outfile is not None:
        plt.savefig(outfile, dpi=100, bbox_inches='tight')
##############################################################################
# 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
# ----------------------------

plotting.plot_glass_brain(localizer_tmap, display_mode='r', plot_abs=False,
                          title='Glass brain', threshold=2.)

plotting.plot_stat_map(localizer_tmap, display_mode='x', threshold=1.,
                       cut_coords=range(0, 51, 10), title='Slices')

plotting.show()
Exemple #15
0
plotting.plot_surf_roi(fsaverage['pial_left'],
                       roi_map=pcc_map,
                       hemi='left',
                       view='medial',
                       bg_map=fsaverage['sulc_left'],
                       bg_on_data=True,
                       title='PCC Seed')

###############################################################################
# Display unthresholded stat map  with dimmed background
plotting.plot_surf_stat_map(fsaverage['pial_left'],
                            stat_map=stat_map,
                            hemi='left',
                            view='medial',
                            colorbar=True,
                            bg_map=fsaverage['sulc_left'],
                            bg_on_data=True,
                            darkness=.5,
                            title='Correlation map')

###############################################################################
# Display unthresholded stat map without background map, transparency is
# automatically set to .5, but can also be controlled with the alpha parameter
plotting.plot_surf_stat_map(fsaverage['pial_left'],
                            stat_map=stat_map,
                            hemi='left',
                            view='medial',
                            colorbar=True,
                            title='Plotting without background')
# -----------
#
# Prepare figure for concurrent plot of individual maps
# compute population-level maps for left and right hemisphere
# we directetly do that on the values arrays 
from scipy.stats import ttest_1samp, norm
t_left, pval_left = ttest_1samp(np.array(z_scores_left), 0)
t_right, pval_right = ttest_1samp(np.array(z_scores_right), 0)

############################################################################
# What we have so far are p-values: we convert them to z-values for plotting
z_val_left = norm.isf(pval_left)
z_val_right = norm.isf(pval_right)

############################################################################
# Plot the resulting maps.
# Left hemipshere
from nilearn import plotting
plotting.plot_surf_stat_map(
    fsaverage.infl_left, z_val_left, hemi='left',
    title="language-string, left hemisphere", colorbar=True,
    threshold=3., bg_map=fsaverage.sulc_left)
############################################################################
# Right hemisphere
plotting.plot_surf_stat_map(
    fsaverage.infl_right, z_val_left, hemi='right',
    title="language-string, right hemisphere", colorbar=True,
    threshold=3., bg_map=fsaverage.sulc_right)

plotting.show()
Exemple #17
0
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',
                                  colorbar=True,
                                  threshold=1.,
                                  bg_map=fsaverage.sulc_right)
fig.show()

##############################################################################
# Interactive plotting with Plotly
# --------------------------------
#
# If you have a recent version of Nilearn (>=0.8.2), and if you have
# ``plotly`` installed, you can easily configure
# :func:`~nilearn.plotting.plot_surf_stat_map` to use ``plotly`` instead
# of ``matplotlib``:

engine = 'plotly'
# 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
plotting.plot_glass_brain(rho_map_pos,
                          display_mode='lyrz',
                          plot_abs=False,
                          title='Glass brain',
                          threshold=0.005)

#%%
## Plot Group
p_val = 0.05
# 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(z_map, fsaverage.pial_left)

#%%
p_val = 0.05
p_unc = norm.isf(p_val)

#%%
# plot surface
# note: the bg_map and hemi should be the same hemisphere as fsaverage.
plotting.plot_surf_stat_map(fsaverage.infl_left,
                            img_to_plot,
                            hemi='left',
                            bg_map=fsaverage.sulc_left,
                            view='lateral',
                            title=f"{model1}-{model2}, p<{p_val}",
                            colorbar=True,
                            threshold=p_unc)

#%%
# Plot glass brain of the z_map
display = plotting.plot_glass_brain(
    z_map,
    threshold=p_unc,
    colorbar=True,
    display_mode='lyr',
    plot_abs=False,
    title=f"group {model1}-{model2} (unc p<{p_val})")
#display.savefig(os.path.join(rootdir, "brain_plots", f"group_{model1}_{model2}.png"))
#########################################################################
# iterate over contrasts
for index, (contrast_id, contrast_val) in enumerate(contrasts.items()):
    print('  Contrast % i out of %i: %s, right hemisphere' %
          (index + 1, len(contrasts), contrast_id))
    # compute contrast-related statistics
    contrast = compute_contrast(labels, estimates, contrast_val,
                                contrast_type='t')
    # we present the Z-transform of the t map
    z_score = contrast.z_score()
    # we plot it on the surface, on the inflated fsaverage mesh,
    # together with a suitable background to give an impression
    # of the cortex folding.
    plotting.plot_surf_stat_map(
        fsaverage.infl_right, z_score, hemi='right',
        title=contrast_id, colorbar=True,
        threshold=3., bg_map=fsaverage.sulc_right)

#########################################################################
# Analysing the left hemisphere
# -----------------------------
#
# Note that it requires little additional code!

#########################################################################
# Project the fMRI data to the mesh
texture = surface.vol_to_surf(fmri_img, fsaverage.pial_left)

#########################################################################
# Estimate the General Linear Model
labels, estimates = run_glm(texture.T, design_matrix.values)
Exemple #21
0
# load and smooth, when convert to nifti object
file = glob.glob(os.path.join(rootdir, 'subj01_diff_test_rho.nii.gz'))
rho_map = masker.transform(file)
rho_map = masker.inverse_transform(rho_map)

# 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, 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='medial',
                            title='Surface plot',
                            colorbar=True,
                            threshold=0.005)

# plot glass brain
plotting.plot_glass_brain(rho_map,
                          display_mode='lyrz',
                          plot_abs=False,
                          title='Glass brain',
                          threshold=0.005)
Exemple #22
0
 save_obj(d_parcel_fsaverage,
          os.path.join(path_to_masks, 'ROIS_in_fsaverge.pkl'))
 do_plotting = False
 if do_plotting:
     fsaverage = datasets.fetch_surf_fsaverage(mesh='fsaverage')
     for ROI_file in os.listdir(
             os.path.join(path_to_masks,
                          'language_separFiles_in_fsaverage')):
         if ROI_file.__contains__('_LH_'):
             lh_surf = nib.load(
                 os.path.join(path_to_masks,
                              'language_separFiles_in_fsaverage', ROI_file))
             figure = plotting.plot_surf_stat_map(
                 fsaverage.infl_left,
                 lh_surf.agg_data(),
                 hemi='left',
                 title='Surface left hemisphere',
                 colorbar=True,
                 threshold=1.,
                 bg_map=fsaverage.sulc_left)
             plotting.plot_surf_contours(
                 fsaverage.infl_left,
                 lh_surf.agg_data(),
                 levels=[
                     1,
                 ],
                 figure=figure,
                 legend=False,
                 colors=[
                     'g',
                 ],
                 output_file=os.path.join(
Exemple #23
0
    def __update_views__(self, new_vertex):

        if new_vertex is None or new_vertex == self._current_vertex:
            return

        axes = [
            (self._ax[0], self.__lateral_cut__),
            # (self._ax[1], self.__medial_cut__),
            # (self._ax[2], self.__dorsal_cut__),
            # (self._ax[3], self.__ventral_cut__),
            # (self._ax[4], self.__anterior_cut__),
            # (self._ax[5], self.__posterior_cut__)
        ]

        for i in range(len(axes)):
            ax, cut = axes[i]
            ax.clear()

            stat_map, view = cut()

            plotting.plot_surf_stat_map(self._template,
                                        stat_map=stat_map,
                                        hemi=self._hemisphere,
                                        view=view,
                                        colorbar=True,
                                        bg_map=self._bg_image,
                                        bg_on_data=True,
                                        cmap=self._rgba_cmap,
                                        threshold=.5,
                                        title='Threshold and colormap',
                                        axes=ax)

            ax.tick_params(direction='in')
            for item in ax.get_xticklabels():
                item.set_fontsize(8)
            for item in ax.get_yticklabels():
                item.set_fontsize(8)

        self._ax[-1].clear()

        x = new_vertex

        colors = ['r', 'c', 'g', 'm', 'y', 'k']

        if self._correction_processor is not None:
            correction_processor, correction_parameters = self._correction_processor
            cdata = correction_processor.corrected_values(
                correction_parameters, x1=x, x2=x + 1)
            self._ax[1].plot(correction_processor.predictors[:, 0],
                             cdata[:, 0], 'bo')

        for processor, prediction_parameters, correction_parameters, label in self._processors:

            cdata = processor.corrected_values(correction_parameters,
                                               x1=x,
                                               x2=x + 1)
            self._ax[1].plot(processor.predictors[:, 0],
                             cdata[:, 0],
                             'bo',
                             color=colors[0])

            axis, curve = processor.curve(prediction_parameters,
                                          x1=x,
                                          x2=x + 1,
                                          tpoints=self._num_points)
            self._ax[1].plot(axis.T,
                             curve[:, 0],
                             label=label,
                             color=colors[0],
                             marker='d')

            colors.append(colors[0])
            del colors[0]

        if len(self._processors) > 0 or hasattr(self, '_correction_processor'):
            self._ax[1].legend()

        # Compute mm coordinates with affine
        # c_vertex = [new_vertex, 1]
        # c_vertex = np.array(c_vertex, dtype=np.float32)
        # mm_coords = self._affine.dot(c_vertex)[:-1]
        # self._figure.canvas.set_window_title('Coordinates {}, {}, {}'.format(*mm_coords))

        self._figure.canvas.draw()

        self._current_vertex = new_vertex
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])
plotting.plot_surf_stat_map(surf_mesh=fsaverage.infl_left,
                            stat_map=texturestate1_l,
                            bg_map=fsaverage.sulc_left,
                            hemi='left',
                            view='lateral',
                            threshold=.084,
                            colorbar=False,
                            axes=axs[1])
plotting.plot_surf_stat_map(surf_mesh=fsaverage.infl_left,
                            stat_map=texturestate1_l,
                            bg_map=fsaverage.sulc_left,
                            hemi='left',
Exemple #25
0
                            '%s.sl_distinct%.1f.func.gii' % (hemi, radius))
cons_path_fn = os.path.join(surfpath,
                            '%s.sl_consist%.1f.func.gii' % (hemi, radius))
spread_path_fn = os.path.join(
    surfpath, '%s.sl_spread_correlation_%.1f.func.gii' % (hemi, radius))

# plot the surface data
hemi_text = 'right' if hemi == 'rh' else 'left'
for view in ['medial', 'lateral']:
    plotting.plot_surf_stat_map(
        surf_mesh=os.path.join(surfpath, '%s.inflated' % (hemi)),
        stat_map=load_surf_data(dist_path_fn)[:, 1],
        bg_map=os.path.join(surfpath, '%s.sulc' % (hemi)),
        hemi=hemi_text,
        title='Distinctiveness %s hemisphere' % (hemi_text),
        view=view,
        output_file=os.path.join(datapath, 'results',
                                 '%s.distinct.%s.png' % (hemi, view)),
        alpha=0.7,
        bg_on_data=True,
        colorbar=True,
        threshold=0.2,
        cmap='cold_hot')
    plotting.plot_surf_stat_map(
        surf_mesh=os.path.join(surfpath, '%s.inflated' % (hemi)),
        stat_map=load_surf_data(cons_path_fn)[:, 1],
        bg_map=os.path.join(surfpath, '%s.sulc' % (hemi)),
        hemi=hemi_text,
        title='Consistency %s hemisphere' % (hemi_text),
        view=view,
        output_file=os.path.join(datapath, 'results',
                                 '%s.consist.%s.png' % (hemi, view)),
Exemple #26
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()
# -----------
#
# Prepare figure for concurrent plot of individual maps
# compute population-level maps for left and right hemisphere
# we directetly do that on the values arrays 
from scipy.stats import ttest_1samp, norm
t_left, pval_left = ttest_1samp(np.array(z_scores_left), 0)
t_right, pval_right = ttest_1samp(np.array(z_scores_right), 0)

############################################################################
# What we have so far are p-values: we convert them to z-values for plotting
z_val_left = norm.isf(pval_left)
z_val_right = norm.isf(pval_right)

############################################################################
# Plot the resulting maps.
# Left hemipshere
from nilearn import plotting
plotting.plot_surf_stat_map(
    fsaverage.infl_left, z_val_left, hemi='left',
    title="language-string, left hemisphere", colorbar=True,
    threshold=3., bg_map=fsaverage.sulc_left)
############################################################################
# Right hemisphere
plotting.plot_surf_stat_map(
    fsaverage.infl_right, z_val_left, hemi='right',
    title="language-string, right hemisphere", colorbar=True,
    threshold=3., bg_map=fsaverage.sulc_right)

plotting.show()
Exemple #28
0
    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, 
                            bg_map=big_fsaverage.sulc_right)
plotting.show()
%matplotlib qt
plotting.view_surf(big_fsaverage.infl_left, big_texture_right, threshold='95%',
Exemple #29
0
def plot_surf_stat(lh_surf,
                   lh_stat_map,
                   lh_bg_map,
                   rh_surf,
                   rh_stat_map,
                   rh_bg_map,
                   out_fname,
                   cmap='coolwarm',
                   symmetric_cbar='auto',
                   upper_lim=None,
                   threshold=None):
    '''Use Nilearn to plot statistical surface map for L lat, med, R lat, med view.
    '''
    import os.path as op
    import numpy as np
    import matplotlib.pyplot as plt
    import nibabel.freesurfer.io as fsio
    import nibabel.freesurfer.mghformat as fsmgh
    from nilearn import plotting

    # Get max and min value across stat maps from the two hemi
    lh_stat_dat = fsmgh.load(lh_stat_map).get_data()
    rh_stat_dat = fsmgh.load(rh_stat_map).get_data()
    flat_dat = np.hstack((lh_stat_dat.flatten(), rh_stat_dat.flatten()))
    max_val = np.maximum(np.abs(np.nanmax(flat_dat)),
                         np.abs(np.nanmin(flat_dat)))
    if upper_lim is not None:
        vmax = upper_lim if max_val > upper_lim else max_val
    else:
        vmax = max_val

    fig, axs = plt.subplots(2,
                            2,
                            figsize=(8, 6),
                            subplot_kw={'projection': '3d'})

    # Get threshold if txt is specified
    if isinstance(threshold, str):
        if op.exists(threshold):
            thresh_arr = np.loadtxt(threshold)
            thresh = thresh_arr if thresh_arr.shape == (
            ) and thresh_arr != np.inf else None
        else:
            thresh = None

    elif isinstance(threshold, int) or isinstance(threshold, float):
        thresh = threshold

    else:
        thresh = None

    # Add threshold to title if not None
    if thresh is not None:
        if float(thresh) >= 1e-2 and float(thresh) < 1e2:
            title_txt = 'Threshold = {:.2f}'.format(float(thresh))
        else:
            title_txt = 'Threshold = {:.2e}'.format(float(thresh))
    else:
        title_txt = ''

    for i, ax in enumerate(fig.axes):
        if i <= 1:
            hemi = 'left'
            surf = lh_surf
            stat_map = lh_stat_dat
            bg = lh_bg_map

        else:
            hemi = 'right'
            surf = rh_surf
            stat_map = rh_stat_dat
            bg = rh_bg_map

        view = 'lateral' if i % 2 == 0 else 'medial'
        colorbar = True if i == 3 else False
        title = title_txt if i == 0 else ''

        plotting.plot_surf_stat_map(surf,
                                    stat_map,
                                    hemi=hemi,
                                    bg_map=bg,
                                    view=view,
                                    vmax=vmax,
                                    threshold=thresh,
                                    title=title,
                                    cmap=cmap,
                                    symmetric_cbar=symmetric_cbar,
                                    colorbar=colorbar,
                                    axes=ax,
                                    figure=fig)

    fig.savefig(out_fname, dpi=200, bbox_inches='tight')

    return op.abspath(out_fname)
# Searchlight computation
# -----------------------
from sklearn.model_selection import KFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import RidgeClassifier
from nilearn.decoding.searchlight import search_light

# Simple linear estimator preceeded by a normalization step
estimator = make_pipeline(StandardScaler(), RidgeClassifier(alpha=10.))

# Define cross-validation scheme
cv = KFold(n_splits=3, shuffle=False)

# Cross-validated search light
scores = search_light(X, y, estimator, adjacency, cv=cv, n_jobs=1)

#########################################################################
# Visualization
# -------------
from nilearn import plotting
chance = .5
plotting.plot_surf_stat_map(infl_mesh,
                            scores - chance,
                            view='medial',
                            colorbar=True,
                            threshold=0.1,
                            bg_map=fsaverage['sulc_' + hemi],
                            title='Accuracy map, left hemisphere')
plotting.show()
Exemple #31
0
def ViewSurface(image, threshold=1.94):
    fsaverageL = r"E:\brain\atlas\fsaverage\pial_left.gii"
    fsaverageR = r"E:\brain\atlas\fsaverage\pial_right.gii"
    textureL = surface.vol_to_surf(image,
                                   fsaverage.pial_left,
                                   inner_mesh=fsaverage.white_left)
    textureR = surface.vol_to_surf(image,
                                   fsaverage.pial_right,
                                   inner_mesh=fsaverage.white_right)

    fig, axes = plt.subplots(1,
                             2,
                             figsize=[10, 6],
                             subplot_kw={'projection': '3d'})
    vmax = np.max([np.abs(textureL), np.abs(textureR)])

    plotting.plot_surf_stat_map(
        fsaverage.pial_left,
        textureL,
        hemi='left',
        threshold=threshold,
        bg_map=fsaverage.sulc_right,
        cmap=sns.color_palette('cold_hot', as_cmap=True),
        darkness=0.5,
        colorbar=False,
        #symmetric_cbar=True,
        bg_on_data=True,
        axes=axes[0],
        vmax=vmax,
        figure=fig)

    plotting.plot_surf_stat_map(
        fsaverage.pial_right,
        textureR,
        hemi='right',
        threshold=threshold,
        bg_map=fsaverage.sulc_right,
        cmap=sns.color_palette('cold_hot', as_cmap=True),
        darkness=0.5,
        colorbar=False,
        #symmetric_cbar=True,
        bg_on_data=True,
        axes=axes[1],
        vmax=vmax,
        figure=fig)
    plt.show()
    fig2, axes2 = plt.subplots(1,
                               2,
                               figsize=[10, 6],
                               subplot_kw={'projection': '3d'})
    plotting.plot_surf_stat_map(
        fsaverage.pial_left,
        textureL,
        hemi='right',
        threshold=threshold,
        bg_map=fsaverage.sulc_right,
        cmap=sns.color_palette('cold_hot', as_cmap=True),
        darkness=0.5,
        colorbar=False,
        #symmetric_cbar=True,
        bg_on_data=True,
        axes=axes2[0],
        vmax=vmax,
        figure=fig2)
    plotting.plot_surf_stat_map(
        fsaverage.pial_right,
        textureR,
        hemi='left',
        threshold=threshold,
        bg_map=fsaverage.sulc_right,
        cmap=sns.color_palette('cold_hot', as_cmap=True),
        darkness=0.5,
        colorbar=True,
        #symmetric_cbar=True,
        bg_on_data=True,
        axes=axes2[1],
        vmax=vmax,
        figure=fig2)
    plt.show()
    print('  Contrast % i out of %i: %s, right hemisphere' %
          (index + 1, len(contrasts), contrast_id))
    # compute contrast-related statistics
    contrast = compute_contrast(labels,
                                estimates,
                                contrast_val,
                                contrast_type='t')
    # we present the Z-transform of the t map
    z_score = contrast.z_score()
    # we plot it on the surface, on the inflated fsaverage mesh,
    # together with a suitable background to give an impression
    # of the cortex folding.
    plotting.plot_surf_stat_map(fsaverage.infl_right,
                                z_score,
                                hemi='right',
                                title=contrast_id,
                                colorbar=True,
                                threshold=3.,
                                bg_map=fsaverage.sulc_right)

#########################################################################
# Analysing the left hemisphere
# -----------------------------
#
# Note that re-creating the above analysis for the left hemisphere requires little additional code!

#########################################################################
# We project the fMRI data to the mesh.
texture = surface.vol_to_surf(fmri_img, fsaverage.pial_left)

#########################################################################
Exemple #33
0
def plot_surfaces(grad_dict,
                  index,
                  outdir,
                  prefix,
                  normalize=False,
                  cmap="jet"):
    grad_lh = grad_dict["grads_lh"][:, index]
    grad_rh = grad_dict["grads_rh"][:, index]
    if normalize:
        if np.max(grad_lh[grad_lh > 0]) > np.abs(np.min(grad_lh[grad_lh < 0])):
            grad_lh[grad_lh < 0] = grad_lh[grad_lh < 0] / np.abs(
                np.min(grad_lh[grad_lh < 0]))
            grad_lh[grad_lh < 0] = grad_lh[grad_lh < 0] * np.max(
                grad_lh[grad_lh > 0])
        else:
            grad_lh[grad_lh > 0] = grad_lh[grad_lh > 0] / np.max(
                grad_lh[grad_lh > 0])
            grad_lh[grad_lh > 0] = grad_lh[grad_lh > 0] * np.abs(
                np.min(grad_lh[grad_lh < 0]))
        if np.max(grad_rh[grad_rh > 0]) > np.abs(np.min(grad_rh[grad_rh < 0])):
            grad_rh[grad_rh < 0] = grad_rh[grad_rh < 0] / np.abs(
                np.min(grad_rh[grad_rh < 0]))
            grad_rh[grad_rh < 0] = grad_rh[grad_rh < 0] * np.max(
                grad_rh[grad_rh > 0])
        else:
            grad_rh[grad_rh > 0] = grad_rh[grad_rh > 0] / np.max(
                grad_rh[grad_rh > 0])
            grad_rh[grad_rh > 0] = grad_rh[grad_rh > 0] * np.abs(
                np.min(grad_rh[grad_rh < 0]))

    plotting.plot_surf_stat_map(
        grad_dict["pial_left"],
        grad_lh,
        hemi="left",
        bg_map=grad_dict["sulc_left"],
        bg_on_data=True,
        threshold=np.finfo(np.float32).eps,
        colorbar=False,
        view="medial",
        cmap=cmap,
        output_file=op.join(outdir,
                            "{0}-{1}_left_medial.png".format(prefix, index)),
    )
    plotting.plot_surf_stat_map(
        grad_dict["pial_left"],
        grad_lh,
        hemi="left",
        bg_map=grad_dict["sulc_left"],
        bg_on_data=True,
        threshold=np.finfo(np.float32).eps,
        colorbar=False,
        view="lateral",
        cmap=cmap,
        output_file=op.join(outdir,
                            "{0}-{1}_left_lateral.png".format(prefix, index)),
    )

    plotting.plot_surf_stat_map(
        grad_dict["pial_right"],
        grad_rh,
        hemi="right",
        bg_map=grad_dict["sulc_right"],
        bg_on_data=True,
        threshold=np.finfo(np.float32).eps,
        colorbar=False,
        view="medial",
        cmap=cmap,
        output_file=op.join(outdir,
                            "{0}-{1}_right_medial.png".format(prefix, index)),
    )
    plotting.plot_surf_stat_map(
        grad_dict["pial_right"],
        grad_rh,
        hemi="right",
        bg_map=grad_dict["sulc_right"],
        bg_on_data=True,
        threshold=np.finfo(np.float32).eps,
        colorbar=True,
        view="lateral",
        cmap=cmap,
        output_file=op.join(outdir,
                            "{0}-{1}_right_lateral.png".format(prefix, index)),
    )
Exemple #34
0
# Transform ROI indices in ROI map
pcc_map = np.zeros(parcellation.shape[0], dtype=int)
pcc_map[pcc_labels] = 1

from nilearn import plotting

plotting.plot_surf_roi(fsaverage['pial_left'], roi_map=pcc_map,
                       hemi='left', view='medial',
                       bg_map=fsaverage['sulc_left'], bg_on_data=True,
                       title='PCC Seed')

###############################################################################
# Display unthresholded stat map with a slightly dimmed background
plotting.plot_surf_stat_map(fsaverage['pial_left'], stat_map=stat_map,
                            hemi='left', view='medial', colorbar=True,
                            bg_map=fsaverage['sulc_left'], bg_on_data=True,
                            darkness=.3, title='Correlation map')

###############################################################################
# Many different options are available for plotting, for example thresholding,
# or using custom colormaps
plotting.plot_surf_stat_map(fsaverage['pial_left'], stat_map=stat_map,
                            hemi='left', view='medial', colorbar=True,
                            bg_map=fsaverage['sulc_left'], bg_on_data=True,
                            cmap='Spectral', threshold=.5,
                            title='Threshold and colormap')

###############################################################################
# Here the surface is plotted in a lateral view without a background map.
# To capture 3D structure without depth information, the default is to plot a
# half transparent surface.
Exemple #35
0
    avg /= n_images
    return avg


def get_collection_counts(img_fnames):
    counts = dict()
    for ii, image in enumerate(img_fnames):
        collection, name = image.split('/')[-2:]
        counts[collection] = counts.get(collection, 0) + 1
    return counts


# counts = get_collection_counts(images)

target_img = nib.load(images[0])
desc = 'Average maps for %s' % search_term
avg_effect = average_maps(images_effect, target_img, desc)
desc = 'Average other maps'
avg_other = average_maps(images_other, target_img, desc)

contrast_img = nib.Nifti1Image(avg_effect - avg_other, target_img.affine)
avg_img = nib.Nifti1Image(avg_effect, target_img.affine)
fig = plot_glass_brain(contrast_img, plot_abs=False)
fig.savefig('figures/encoder_%s.png' % search_term)

# surface
fsaverage = datasets.fetch_surf_fsaverage5()
texture = surface.vol_to_surf(contrast_img, fsaverage.pial_right)
plot_surf_stat_map(fsaverage.infl_right, texture, symmetric_cbar=True)
plt.show()