예제 #1
0
def plot_brain_visualization(parcels_bold):
    """Plot brain activity map
    :param parcels_bold: numpy array with one Bold activity signal for each parcel
    """
    fsaverage = datasets.fetch_surf_fsaverage()
    surf_parcels_bold = parcels_bold[atlas["labels_L"]]
    plotting.view_surf(fsaverage['infl_left'], surf_parcels_bold)
예제 #2
0
def plot_surface(data, mesh='infl', hemi='right', bg='sulc', space='fsaverage5', threshold=0):
    fs = datasets.fetch_surf_fsaverage(mesh=space, data_dir=None)
    return plotting.view_surf(
        surf_mesh=getattr(fs, f'{mesh}_{hemi}'),
        surf_map=data,
        bg_map=getattr(fs, f'{bg}_{hemi}'),
        threshold=threshold
    )
예제 #3
0
def plot_labelmap(label_map):

    cols = [
        "#FCF9F5",
        "#C06A45",  # CER
        "#5B5BFF",  # DMN
        "#D73E68",  # FP
        "#8D18AB",  # LIM
        "#0AFE47",  # MOT
        "#FF9C42",  # VAT_SAL_SUB
        "#FFFFAA"  # VIS
    ]

    from nilearn import surface
    from nilearn import plotting, datasets
    import numpy.linalg as npl
    import nibabel as nb

    fsaverage = datasets.fetch_surf_fsaverage()

    from PAINTeR import utils
    s = utils.load_surface_obj('/Users/tspisak/tmp/wm_gm_simp2.obj')

    s2 = surface.load_surf_mesh(fsaverage['pial_left'])

    from nibabel.affines import apply_affine

    img = nb.load(label_map)
    data = img.get_data()

    import pandas as pd
    from PAINTeR import global_vars
    l = pd.read_csv(global_vars._ATLAS_LABELS_, sep="\t")
    modules = l['modules'].values
    lut = pd.factorize(modules)[0] + 1
    lut = np.array([0] + lut.tolist())
    data = lut[np.array(data, dtype=int)]

    parcellation = np.repeat(0, len(s[0]))
    for i in range(len(s[0])):
        coord = np.round(apply_affine(npl.inv(img.affine),
                                      s[0][i])).astype(int)
        if coord[0] - 1 >= data.shape[0] or coord[1] - 1 >= data.shape[
                1] or coord[2] - 1 >= data.shape[2]:
            parcellation[i] = 0
        else:
            parcellation[i] = data[coord[0] - 1, coord[1] - 1, coord[2] - 1]

    import matplotlib.cm as cm
    view = plotting.view_surf(
        s,
        surf_map=parcellation,
        cmap=ListedColormap(sns.color_palette(
            cols)),  # ListedColormap(cm.get_cmap('tab20').colors)
        threshold=0,
        symmetric_cmap=False)
    view.open_in_browser()
예제 #4
0
def view_surf(file, hemi, space, fs_dir, threshold, idx):
    """ Utility command to quickly view interactive surface in your browser.

    file : str
        Path to numpy file (.npy) with vertex data
    hemi : str
        Hemifield; either L or R
    space : str
        Space of vertices (fsaverage[,5,6])
    fs_dir : str
        Directory with space template (mutually exclusive with `space` param)
    threshold : float
        Minimum value to display
    idx : int
        If data has multiple timepoints/observations, visualize the one corresponding to
        this index
    """

    if hemi is None:
        if 'hemi-' in file:
            hemi = file.split('hemi-')[1][0]
        else:
            raise ValueError("Could not determine hemisphere from filename; "
                             "set it explicitly using --hemi {L,R}")

    if space is None and fs_dir is None:
        # Try to determine space from filename
        if 'space-' in file:
            space = file.split('space-')[1].split('_')[0]
        else:
            raise ValueError("Could not determine space from filename; "
                             "set it explicitly using --space or --fs-dir")

    if fs_dir is not None:  # use data from specified Freesurfer dir
        mesh = op.join(fs_dir, 'surf', f"{hemi.lower()}h.inflated")
        bg = op.join(fs_dir, 'surf', f"{hemi.lower()}h.sulc")
    else:  # fetch template using Nilearn
        hemi = 'left' if hemi == 'L' else 'right'
        fs = fetch_surf_fsaverage(mesh=space)
        mesh = fs[f"infl_{hemi}"]
        bg = fs[f"sulc_{hemi}"]

    dat = np.load(file)
    if idx is not None:  # select volume
        dat = dat[idx, :]

    if dat.ndim > 1:
        raise ValueError("Data is 2D! Set --idx explicitly")

    # Finally, plot it
    display = plotting.view_surf(surf_mesh=mesh,
                                 surf_map=dat,
                                 bg_map=bg,
                                 threshold=threshold)
    display.open_in_browser()
def plot_freesurfer_surface(path: Path) -> str:
    suffix = path.suffix
    if suffix in FREESURFER_MESHES:
        return view_surf(str(path)).get_iframe(**DEFAULT_NIFTI_SIZE)
    default_title = suffix[1:].title()
    info = tuple(path.suffixes[:-1])
    hemisphere = "Left" if path.name.startswith("l") else "Right"
    description = FREESURFER_SURFACE_TITLES.get(suffix, default_title)
    if isinstance(description, dict):
        description = description.get(info, "".join(info))
    title = f"{hemisphere} Hemisphere {description}"
    mesh_key = ".orig" if suffix not in (".curv", ".sulc") else ".inflated"
    mesh = (str(path).replace("".join(path.suffixes),
                              mesh_key).replace("label", "surf"))
    # if suffix == ".label":
    #     return view_img_on_surf(inflated, str(path), hemi=hemisphere.lower())

    symmetric_cmap = suffix not in (".thickness", ".curv")
    cmap = "YlOrRd" if suffix in (".thickness", ".curv") else cm.cold_hot
    return view_surf(mesh,
                     str(path),
                     title=title,
                     symmetric_cmap=symmetric_cmap,
                     cmap=cmap).get_iframe(**DEFAULT_NIFTI_SIZE)
예제 #6
0
def view_parcellation(meshLR, parcellation):
    """
    View the given parcellation on an a whole brain surface mesh.
    """
    # for some parcellations the numerical ids need not be consecutive
    cortex_map = cortex_data(parcellation.map_all)
    ids = np.unique(cortex_map)
    normalized_cortex_map = np.zeros_like(cortex_map)
    rgba = np.zeros((len(ids), 4))
    for i in range(len(ids)):
        ind = cortex_map == ids[i]
        normalized_cortex_map[ind] = i
        rgba[i, :] = parcellation.rgba[ids[i]]

    cmap = matplotlib.colors.ListedColormap(rgba)
    return plotting.view_surf(meshLR,
                              normalized_cortex_map,
                              symmetric_cmap=False,
                              cmap=cmap)
예제 #7
0
    def visualize(self, statmap, space='fsnative', threshold=0, hemi='R', mask=None, **plot_args):
        """ Visualizes a statmap on an image/surface background. """
        if 'fs' in space and isinstance(statmap, nib.Nifti1Image):
            raise ValueError("Statmap is an image, but space is fs* something ...")
        
        bg = 'surface' if 'fs' in space else 'volume'
        self.logger.info(f"Visualizing statmap on {bg} ...")
        if 'fs' in space:
            fs_base = op.dirname(self.fs_dir)
            if space == 'fsnative':
                fs_id = f'sub-{self.sub}'
            else:
                fs_id = space
                    
            return plotting.view_surf(
                surf_mesh=op.join(fs_base, fs_id, 'surf', f'{hemi.lower()}h.inflated'),
                surf_map=statmap,
                bg_map=op.join(fs_base, fs_id, 'surf', f'{hemi.lower()}h.sulc'),
                threshold=threshold,
                **plot_args
            )
        else:
            
            if mask is not None:
                statmap = masking.unmask(statmap, mask)

            if space == 'T1w':
                bg = op.join(self.fp_dir, 'anat', f'sub-{self.sub}_desc-preproc_T1w.nii.gz')
            else:
                bg = 'MNI152'

                
            return plotting.view_img(
                stat_map_img=statmap,
                bg_img=bg,
                threshold=threshold,
                **plot_args
            )
예제 #8
0
plotting.plot_connectome(corr,
                         coordinates,
                         edge_threshold="90%",
                         title='fsaverage Destrieux atlas')
plotting.show()

##############################################################################
# 3D visualization in a web browser
# ---------------------------------
# An alternative to :func:`nilearn.plotting.plot_surf_roi` is to use
# :func:`nilearn.plotting.view_surf` for more interactive
# visualizations in a web browser. See :ref:`interactive-surface-plotting` for
# more details.

view = plotting.view_surf(fsaverage.infl_left,
                          parcellation,
                          cmap='gist_ncar',
                          symmetric_cmap=False)
# In a Jupyter notebook, if ``view`` is the output of a cell, it will
# be displayed below the cell

view
##############################################################################

# uncomment this to open the plot in a web browser:
# view.open_in_browser()

##############################################################################
# you can also use :func:`nilearn.plotting.view_connectome` to open an
# interactive view of the connectome.

view = plotting.view_connectome(corr, coordinates, edge_threshold='90%')
def plot_gii(path: Path) -> str:
    html_doc = view_surf(str(path), symmetric_cmap=False)
    return html_doc.get_iframe(**DEFAULT_NIFTI_SIZE)
예제 #10
0
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%',
                          bg_map=big_fsaverage.sulc_left)

예제 #11
0
                          hemispheres=['left', 'right'],
                          colorbar=True)
plotting.show()

##############################################################################
# 3D visualization in a web browser
# ---------------------------------
#
# An alternative to :func:`nilearn.plotting.plot_surf_stat_map` is to use
# :func:`nilearn.plotting.view_surf` or
# :func:`nilearn.plotting.view_img_on_surf` that give more interactive
# visualizations in a web browser. See :ref:`interactive-surface-plotting` for
# more details.

view = plotting.view_surf(fsaverage.infl_right,
                          texture,
                          threshold='90%',
                          bg_map=fsaverage.sulc_right)

# In a Jupyter notebook, if ``view`` is the output of a cell, it will
# be displayed below the cell
view

##############################################################################

# uncomment this to open the plot in a web browser:
# view.open_in_browser()

##############################################################################
# We don't need to do the projection ourselves, we can use
# :func:`~nilearn.plotting.view_img_on_surf`:
예제 #12
0
                       bg_map=fsaverage['sulc_left'], bg_on_data=True,
                       darkness=.5)

###############################################################################
# Display Destrieux parcellation with different views: ventral
plotting.plot_surf_roi(fsaverage['infl_left'], roi_map=parcellation,
                       hemi='left', view='ventral',
                       bg_map=fsaverage['sulc_left'], bg_on_data=True,
                       darkness=.5)
plotting.show()


##############################################################################
# 3D visualization in a web browser
# ---------------------------------
# An alternative to :func:`nilearn.plotting.plot_surf_roi` is to use
# :func:`nilearn.plotting.view_surf` for more interactive
# visualizations in a web browser. See :ref:`interactive-surface-plotting` for
# more details.

view = plotting.view_surf(fsaverage.infl_left, parcellation,
                          cmap='gist_ncar', symmetric_cmap=False)
# uncomment this to open the plot in a web browser:
# view.open_in_browser()

##############################################################################
# In a Jupyter notebook, if ``view`` is the output of a cell, it will
# be displayed below the cell

view
from nilearn.plotting import plot_surf, view_surf, show
from nilearn import datasets
import os
import nibabel as nib
import glob

fsaverage = datasets.fetch_surf_fsaverage('fsaverage5')

dir_ = '/neurospin/ibc/derivatives/sub-*/ses-*/anat/analysis/'
if 0:
    wc = os.path.join(dir_, 't1_t2_ratio_lh.gii')
    textures = glob.glob(wc)
    for texture in textures:
        tex = nib.load(texture).darrays[0].data
        view_surf(
            fsaverage['infl_left'], surf_map=tex, bg_map=None, vmin=1, vmax=2
        ).open_in_browser()

    wc = os.path.join(dir_, 't1_t2_ratio_rh.gii')
    textures = glob.glob(wc)
    for texture in textures:
        tex = nib.load(texture).darrays[0].data
        view_surf(
            fsaverage['infl_right'], surf_map=tex, bg_map=None, vmin=1, vmax=2
        ).open_in_browser()

if 1:
    wc = os.path.join(dir_, 't1_t2_ratio_lh.gii')
    textures = glob.glob(wc)
    tex = nib.load(textures[0]).darrays[0].data
    plot_surf(
예제 #14
0
# %%
# We can tell volumetric from surface spaces using their `is_surface` attribute.
for space in jubrain.spaces:
    if space.is_surface:
        print(space)

# %%
# The surface map is accessed in just the same way as volumetric maps, using the `get map` method.
# Note that we call the method here on the parcellation object, while previous examples usually
# called it on an atlas object.
# For surfaces however, the `fetch()` method accepts an additional parameter 'variant' to select
# between 'white matter', 'pial' and 'inflated' surface.
surfmap = jubrain.get_map('fsaverage6').fetch(variant="inflated")

# %%
# The returned structure is a dictionary of three numpy arrays representing the vertices, faces, and labels respectively.
# Each vertex defines a 3D surface point, while the faces are triplets of indices into the list of vertices, defining surface triangles.
# The labels provide the label index associated with each vertex.
print(surfmap.keys())

# %%
# For plotting meshes, most python libraries can be employes.
# We recommend again the plotting module of `nilearn <https://nilearn.github.io>`_.
# We use Julich-Brain's native colormap for plotting.
from nilearn import plotting
jubrain_cmap = jubrain.get_colormap()
plotting.view_surf(surf_mesh=[surfmap['verts'], surfmap['faces']],
                   surf_map=surfmap['labels'],
                   cmap=jubrain_cmap,
                   symmetric_cmap=False,
                   colorbar=False)
plotting.view_img(destrieux['maps'],
                  resampling_interpolation='nearest',
                  cmap='gist_ncar', symmetric_cmap=False, colorbar=False)
plotting.plot_roi(destrieux['maps'])


######################################################################
# Harvard-Oxford probabilistic (4D) atlas
harvard_oxford = datasets.fetch_atlas_harvard_oxford('cort-prob-2mm')
plotting.plot_prob_atlas(harvard_oxford['maps'])


######################################################################
surf_destrieux = datasets.fetch_atlas_surf_destrieux()
fsaverage = datasets.fetch_surf_fsaverage()
plotting.view_surf(fsaverage['pial_left'], surf_destrieux['map_left'],
                   cmap='gist_ncar', colorbar=False)


######################################################################

# not needed with master
from nilearn import surface
fsaverage['sulc_left'] = surface.load_surf_data(fsaverage['sulc_left'])


######################################################################
plotting.view_surf(fsaverage['pial_left'], fsaverage['sulc_left'],
                   cmap='Greys', threshold=None, symmetric_cmap=False,
                   colorbar=False)

######################################################################
예제 #16
0
def plot_destrieux_surface(
    stats: Union[pd.Series, pd.DataFrame],
    hemisphere: str = "Left",
    measurement: str = None,
    average: bool = False,
    std: bool = False,
    standardize: bool = False,
    title: str = None,
    symmetric_cmap: bool = False,
    cmap: str = None,
    vmin: float = None,
    vmax: float = None,
    factor: int = 1,
) -> plt.Figure:
    if title is None and measurement is None:
        title = f"{hemisphere} Hemisphere Values"
    elif title is None:
        title = f"{measurement} ({hemisphere})"
    if (
        isinstance(stats, pd.DataFrame) or stats.index.nlevels > 2
    ) and measurement is None:
        measurement = "Surface Area"
    destrieux_atlas = datasets.fetch_atlas_surf_destrieux()
    destrieux_labels = [
        parse_destrieux_label(label) for label in destrieux_atlas["labels"][1:]
    ]
    fsaverage = datasets.fetch_surf_fsaverage()
    if isinstance(stats, pd.DataFrame):
        data = stats.xs("Destrieux", level="Atlas").copy()
    else:
        data = stats.copy()
    if average:
        data = data.mean(level=["Hemisphere", "Region Name"])
        title = f"Average {title}"
    if std:
        data = data.std(level=["Hemisphere", "Region Name"])
        title = f"{measurement} Standard Deviation ({hemisphere})"
        vmin = 0
    if standardize:
        if isinstance(data, pd.DataFrame):
            data.loc[:, :] = StandardScaler().fit_transform(data)
        else:
            data.loc[:] = StandardScaler().fit_transform(data)
        title = f"Standardized {title}"
        symmetric_cmap = True
        cmap = cmap if cmap is not None else "coolwarm"
    cmap = cmap if cmap is not None else "Reds"
    hemi_stats = data.xs(hemisphere, level="Hemisphere")
    destrieux_projection = destrieux_atlas[f"map_{hemisphere.lower()}"].copy()
    region_ids = sorted(set(destrieux_projection))
    for i, region_id in enumerate(region_ids):
        label = destrieux_labels[i]
        if label == MEDIAL_WALL:
            value = 0
        else:
            if isinstance(data, pd.DataFrame):
                value = hemi_stats.loc[label, measurement]
            else:
                if hemi_stats.index.nlevels == 2:
                    value = hemi_stats.loc[(measurement, label)]
                else:
                    value = hemi_stats.loc[label]
        region_mask = destrieux_projection == region_id
        destrieux_projection[region_mask] = value * factor
    surface = plotting.view_surf(
        fsaverage[f"infl_{hemisphere.lower()}"],
        destrieux_projection,
        bg_map=fsaverage[f"sulc_{hemisphere.lower()}"],
        cmap=cmap,
        title=title,
        symmetric_cmap=symmetric_cmap,
        vmin=vmin,
        vmax=vmax,
    )
    surface.resize(900, 600)
    return surface
                            threshold=1., bg_map=big_fsaverage.sulc_right)


plotting.show()


##############################################################################
# 3D visualization in a web browser
# ---------------------------------
# An alternative to :func:`nilearn.plotting.plot_surf_stat_map` is to use
# :func:`nilearn.plotting.view_surf` or
# :func:`nilearn.plotting.view_img_on_surf` that give more interactive
# visualizations in a web browser. See :ref:`interactive-surface-plotting` for
# more details.

view = plotting.view_surf(fsaverage.infl_right, texture, threshold='90%',
                          bg_map=fsaverage.sulc_right)
# uncomment this to open the plot in a web browser:
# view.open_in_browser()

##############################################################################
# In a Jupyter notebook, if ``view`` is the output of a cell, it will
# be displayed below the cell

view

##############################################################################
# We don't need to do the projection ourselves, we can use view_img_on_surf:

view = plotting.view_img_on_surf(stat_img, threshold='90%')
# view.open_in_browser()