Exemplo n.º 1
0
def surf_plot(stat,
              hemi='left',
              mesh='infl',
              platform='camh',
              fsaverage='fsaverage5',
              **kwargs):
    stat_fsavg, fsaverage = sch2fsavg(stat, mesh=fsaverage)
    fig = plotting.plot_surf(fsaverage[mesh + '_' + hemi],
                             stat_fsavg[0 if hemi == 'left' else 1],
                             hemi=hemi,
                             bg_map=fsaverage['sulc_' + hemi],
                             bg_on_data=True,
                             **kwargs)
    return fig
Exemplo n.º 2
0
#
# To load a surface mesh in a FreeSurfer directory, use `nb.freesurfer.read_geometry`:

# %%
fs_verts, fs_faces, fs_meta = nb.freesurfer.read_geometry(
    data_dir / 'ds005-preproc/freesurfer/sub-01/surf/lh.pial',
    read_metadata=True)
print(fs_verts[:2])
print(fs_faces[:2])
pprint(fs_meta)

# %% [markdown]
# NiBabel does not have any viewer for surfaces, but Nilearn has plotting utilities:

# %%
_ = nlp.plot_surf((fs_verts, fs_faces))

# %% [markdown] slideshow={"slide_type": "subslide"}
# Let's do the same thing with GIFTI. Here, the file-level metadata is minimal:

# %%
gii_pial = nb.load(
    data_dir /
    'ds005-preproc/fmriprep/sub-01/anat/sub-01_hemi-L_pial.surf.gii')
pprint(
    gii_pial.meta.metadata
)  # .meta maps onto the XML object, its .metadata property exposes a Python dict

# %% [markdown]
# The vertices and faces are stored as separate data arrays, each with their own metadata. These can be queried by NIfTI *intent code*:
Exemplo n.º 3
0
    def _generate_report(self):
        """Side effect function of ISurfMapRPT

        Generate a surface visualization

        Args:
            runtime: Nipype runtime object

        Returns:
            runtime: Resultant runtime object
        """

        from mpl_toolkits import mplot3d  # noqa: F401

        Hemispheres = namedtuple("Hemispheres", ["left", "right"])

        l_surf = nib.load(self._left_surf)
        r_surf = nib.load(self._right_surf)
        num_views = len(self._views)
        num_maps = 1
        vmin, vmax = None, None

        if self._cifti_map:
            cifti_map = nib.load(self._cifti_map)
            lv, lt, lm = niviz.surface.map_cifti_to_gifti(l_surf, cifti_map)
            rv, rt, rm = niviz.surface.map_cifti_to_gifti(r_surf, cifti_map)

            if lm.ndim == 1:
                lm = lm[None, :]
                rm = rm[None, :]

            if not self._visualize_all_maps:
                lm = lm[0, :]
                rm = rm[0, :]
            else:
                num_maps = lm.shape[0]

            map_hemi = Hemispheres(left=(lv, lt, lm), right=(rv, rt, rm))
            vmin, vmax = np.nanpercentile(cifti_map.get_fdata(), [2, 98])
        else:
            # Use vertices and triangles from Mesh
            lv, lt = niviz.surface.gifti_get_mesh(l_surf)
            rv, rt = niviz.surface.gifti_get_mesh(r_surf)
            map_hemi = Hemispheres(left=(lv, lt, None), right=(rv, rt, None))

        if self._bg_map:
            bg_map = nib.load(self._bg_map)
            _, _, l_bg = niviz.surface.map_cifti_to_gifti(l_surf, bg_map)
            _, _, r_bg = niviz.surface.map_cifti_to_gifti(r_surf, bg_map)
            bg_hemi = Hemispheres(left=l_bg, right=r_bg)
        else:
            bg_hemi = Hemispheres(left=None, right=None)

        # Construct figure
        w, h = plt.figaspect(num_maps / (num_views))
        fig, axs = plt.subplots(num_maps,
                                num_views,
                                subplot_kw={'projection': '3d'},
                                figsize=(w, h))
        fig.set_facecolor("black")
        fig.tight_layout()

        for i, a in enumerate(axs.flat):
            a.set_facecolor("black")

            view_ind = i % num_views
            map_ind = i // num_views

            view = self._views[view_ind]["view"]
            hemi = self._views[view_ind]["hemi"]

            display_map = getattr(map_hemi, hemi)
            display_bg = getattr(bg_hemi, hemi)

            v, t, m = display_map
            m = m[map_ind]
            if self._zero_nan:
                m[np.isnan(m)] = 0

            # Plot
            nplot.plot_surf([v, t],
                            surf_map=m,
                            bg_map=display_bg,
                            cmap=self._colormap,
                            axes=a,
                            hemi=hemi,
                            view=view,
                            bg_on_data=True,
                            darkness=self._darkness,
                            vmin=vmin,
                            vmax=vmax)

        plt.draw()
        plt.savefig(self._out_report)
Exemplo n.º 4
0
def main():

    parser = argparse.ArgumentParser()

    parser.add_argument('dscalar', type=str, help="CIFTI dscalar file to view")
    parser.add_argument("l_surf",
                        type=str,
                        help="Left surface to visualize over")
    parser.add_argument("r_surf",
                        type=str,
                        help="Right surface to visualize over")
    parser.add_argument("output_base",
                        type=str,
                        help="Output basename, will add _view-VIEW to end")
    parser.add_argument("--bg_surf",
                        type=str,
                        help="Optional background surface to modulate "
                        "levels of dscalar map")

    args = parser.parse_args()

    dscalar = args.dscalar
    f_l_surf = args.l_surf
    f_r_surf = args.r_surf
    f_bg = args.bg_surf
    outbase = args.output_base

    # Use background image if available
    if f_bg:
        logging.info(f"Using BG map {f_bg}")
        bg = -construct_map_from_cifti(nib.load(f_bg))
        bg_exists = True
    else:
        logging.info(f"No BG map supplied!")
        bg = None
        bg_exists = False

    l_surf = nib.load(f_l_surf)
    r_surf = nib.load(f_r_surf)

    logging.info("Joining together surface mesh")
    coord, trigs = construct_cifti_surf_mesh(l_surf, r_surf)

    logging.info("Constructing map from dscalar CIFTI")
    vertices = construct_map_from_cifti(nib.load(dscalar))

    plot_args = {
        "darkness": 0.99,
        "bg_on_data": True if bg_exists else False,
        "threshold": 0.1,
        "cmap": "magma"
    }

    # Construct mapping from left/right
    logging.info("Generating anterior view...")
    plot.plot_surf(surf_mesh=[coord, trigs],
                   surf_map=vertices,
                   bg_map=bg,
                   view='anterior',
                   output_file=f"{outbase}_view-anterior.png",
                   **plot_args)

    logging.info("Generating dorsal view...")
    plot.plot_surf(surf_mesh=[coord, trigs],
                   surf_map=vertices,
                   bg_map=bg,
                   view='dorsal',
                   output_file=f"{outbase}_view-dorsal.png",
                   **plot_args)

    # Hemispheric views
    ind2h = {0: 'left', 1: 'right'}
    prev_vert = 0
    for i, h in enumerate([l_surf, r_surf]):

        # Slice up to length of underlying mesh
        inds = slice(prev_vert, prev_vert + h.darrays[0].data.shape[0])
        h_verts = vertices[inds]
        hemi = ind2h[i]
        h_bg = bg[inds] if bg_exists else None

        logging.info(f"Generating lateral view of {hemi} hemisphere")
        plot.plot_surf(surf_mesh=[h.darrays[0].data, h.darrays[1].data],
                       surf_map=h_verts,
                       bg_map=h_bg,
                       view='lateral',
                       hemi=hemi,
                       output_file=f"{outbase}_view-lateral_hemi-{hemi}.png",
                       **plot_args)

        logging.info(f"Generating medial view of {hemi} hemisphere")
        plot.plot_surf(surf_mesh=[h.darrays[0].data, h.darrays[1].data],
                       surf_map=h_verts,
                       bg_map=h_bg,
                       view='medial',
                       hemi=hemi,
                       output_file=f"{outbase}_view-medial_hemi-{hemi}.png",
                       **plot_args)

        prev_vert += h.darrays[0].data.shape[0]
Exemplo n.º 5
0
def plot_surf_map(lh_surf,
                  lh_surf_map,
                  lh_bg_map,
                  rh_surf,
                  rh_surf_map,
                  rh_bg_map,
                  out_fname,
                  cmap='jet',
                  vmin=None,
                  vmax=None):
    '''Use Nilearn to plot non-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_surf_dat = fsmgh.load(lh_surf_map).get_data()
    rh_surf_dat = fsmgh.load(rh_surf_map).get_data()
    if vmin is None or vmax is None:
        flat_dat = np.hstack((lh_surf_dat.flatten(), rh_surf_dat.flatten()))
    if vmin is None:
        vmin = np.nanmin(flat_dat)
    if vmax is None:
        vmax = np.nanmax(flat_dat)

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

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

        else:
            hemi = 'right'
            surf = rh_surf
            surf_map = rh_surf_dat
            bg = rh_bg_map

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

        plotting.plot_surf(surf,
                           surf_map,
                           hemi=hemi,
                           bg_map=bg,
                           view=view,
                           vmin=vmin,
                           vmax=vmax,
                           cmap=cmap,
                           colorbar=colorbar,
                           axes=ax,
                           figure=fig)

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

    return op.abspath(out_fname)
Exemplo n.º 6
0
from nilearn import plotting
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

import matplotlib
matplotlib.use('Agg')

# 3D surface
# requires `snakemake.input.surf`
fig = plotting.plot_surf(snakemake.input.surf, view='dorsal')
fig.savefig(snakemake.output.png)
Exemplo n.º 7
0
    def __update_views__(self, new_vertex):
        if new_vertex is None or new_vertex == self._current_vertex:
            return

        axes = (self._ax[0], self.__image_cut__,
                cm.get_cmap(self._template_cmap))
        # xydata = self.__compute_xydata__(new_vertex)

        for i in range(len(self._images)):
            ax, bg_cut, bg_cmap = axes
            fg_cut, fg_cmap = self._images[i]
            ax.clear()

            plotting.plot_surf(bg_cut(new_vertex),
                               surf_map=fg_cut,
                               cmap=fg_cmap,
                               axes=ax)
            #
            # (xdata,), (width, height) = xydata
            # ax.add_line(mplline(xdata=[0, width], ydata=[ydata, ydata], linewidth=1, color='green'))
            # ax.add_line(mplline(xdata=[xdata, xdata], ydata=[0, height], linewidth=1, color='green'))

        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
    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(
        fsaverage['infl_left'],
        surf_map=tex, bg_map=None, hemi='left', view='lateral',
        vmin=1, vmax=2, engine='matplotlib')
    plot_surf(
        fsaverage['infl_left'],
        surf_map=tex, bg_map=None, hemi='left', view='medial',
        vmin=1, vmax=2, engine='matplotlib')
    show()



Exemplo n.º 9
0
for measure in ["thickness", "area", "volume"]:
    for hemi in ["lh", "rh"]:
        for quantity in ["ICC", "pd", "ttest"]:
            file = "/data/pt_nro186_lifeupdate/Results/GMV_project_evelyn_frauke/FS_Group_Analysis/ICC_analysis/ICC_pairedt_results/%s.%s_sm10_%s.mgz" % (
                hemi, measure, quantity)
            surf = surface.load_surf_data(file)
            #set Nan values to 0
            surf[np.isnan(surf)] = 0
            print("plotting %s for %s on %s" % (quantity, measure, hemi))
            if hemi == "lh":
                plotting.plot_surf(
                    fsaverage['pial_left'],
                    surf_map=surf,
                    hemi='left',
                    view='medial',
                    colorbar=True,
                    bg_map=fsaverage['sulc_left'],
                    bg_on_data=True,
                    title='',
                    output_file=
                    "/data/pt_nro186_lifeupdate/Results/GMV_project_evelyn_frauke/FS_Group_Analysis/ICC_analysis/ICC_pairedt_results/%s.%s_sm10_%s_medial.png"
                    % (hemi, measure, quantity))
                plotting.plot_surf(
                    fsaverage['pial_left'],
                    surf_map=surf,
                    hemi='left',
                    view='lateral',
                    colorbar=True,
                    bg_map=fsaverage['sulc_left'],
                    bg_on_data=True,
                    title='',
                    output_file=