예제 #1
0
    def plot_cluster_freqs_on_brain(self, cluster_name, xyz, colormap='viridis', vmin=None, vmax=None, do_3d=False):
        """
        Plot the frequencies of single electrode cluster on either a 2d or interactive 2d brain.

        Parameters
        ----------
        cluster_name: str
            Name of column in self.res['clusters']
        xyz: np.ndarray
            3 x n array of electrode locations. Should be in MNI space.
        colormap: str
            matplotlib colormap name
        vmin: float
            lower limit of colormap values. If not given, lowest value in frequency column will be used
        vmax: float
            upper limit of colormap values. If not given, highest value in frequency column will be used
        do_3d:
            Whether to plot an interactive 3d brain, or a 2d brain

        Returns
        -------
        If 2d, returns the matplotlib figure. If 3d, returns the html used to render the brain.
        """

        # get frequecies for this cluster
        freqs = self.res['clusters'][cluster_name].values

        # get color for each frequency. Start with all black
        colors = np.stack([[0., 0., 0., 0.]] * len(freqs))

        # fill in colors of electrodes with defined frequencies
        cm = plt.get_cmap(colormap)
        cNorm = clrs.Normalize(vmin=np.nanmin(freqs) if vmin is None else vmin,
                               vmax=np.nanmax(freqs) if vmax is None else vmax)
        colors[~np.isnan(freqs)] = cmx.ScalarMappable(norm=cNorm, cmap=cm).to_rgba(freqs[~np.isnan(freqs)])

        # if plotting 2d, use the nilearn glass brain
        if not do_3d:
            fig, ax = plt.subplots()
            ni_plot.plot_connectome(np.eye(xyz.shape[0]), xyz,
                                    node_kwargs={'alpha': 0.7, 'edgecolors': None},
                                    node_size=60, node_color=colors, display_mode='lzr',
                                    axes=ax)
            divider = make_axes_locatable(ax)
            cax = divider.append_axes('bottom', size='4%', pad=0)
            cb1 = mpl.colorbar.ColorbarBase(cax, cmap=colormap,
                                            norm=cNorm,
                                            orientation='horizontal')
            cb1.set_label('Frequency', fontsize=20)
            cb1.ax.tick_params(labelsize=14)
            fig.set_size_inches(15, 10)
            return fig

        # if plotting 3d use the nilearn 3d brain. Unfortunately this doesn't add a colorbar.
        else:
            # you need to return the html. If in jupyter, it will automatically render
            return ni_plot.view_markers(xyz, colors=colors, marker_size=6)
    def plot_cluster_freqs_on_brain(self, cluster_name, xyz, colormap='viridis', vmin=None, vmax=None, do_3d=False):
        """
        Plot the frequencies of single electrode cluster on either a 2d or interactive 2d brain.

        Parameters
        ----------
        cluster_name: str
            Name of column in self.res['clusters']
        xyz: np.ndarray
            3 x n array of electrode locations. Should be in MNI space.
        colormap: str
            matplotlib colormap name
        vmin: float
            lower limit of colormap values. If not given, lowest value in frequency column will be used
        vmax: float
            upper limit of colormap values. If not given, highest value in frequency column will be used
        do_3d:
            Whether to plot an interactive 3d brain, or a 2d brain

        Returns
        -------
        If 2d, returns the matplotlib figure. If 3d, returns the html used to render the brain.
        """

        # get frequecies for this cluster
        freqs = self.res['clusters'][cluster_name].values

        # get color for each frequency. Start with all black
        colors = np.stack([[0., 0., 0., 0.]] * len(freqs))

        # fill in colors of electrodes with defined frequencies
        cm = plt.get_cmap(colormap)
        cNorm = clrs.Normalize(vmin=np.nanmin(freqs) if vmin is None else vmin,
                               vmax=np.nanmax(freqs) if vmax is None else vmax)
        colors[~np.isnan(freqs)] = cmx.ScalarMappable(norm=cNorm, cmap=cm).to_rgba(freqs[~np.isnan(freqs)])

        # if plotting 2d, use the nilearn glass brain
        if not do_3d:
            fig, ax = plt.subplots()
            ni_plot.plot_connectome(np.eye(xyz.shape[0]), xyz,
                                    node_kwargs={'alpha': 0.7, 'edgecolors': None},
                                    node_size=60, node_color=colors, display_mode='lzr',
                                    axes=ax)
            divider = make_axes_locatable(ax)
            cax = divider.append_axes('bottom', size='4%', pad=0)
            cb1 = mpl.colorbar.ColorbarBase(cax, cmap=colormap,
                                            norm=cNorm,
                                            orientation='horizontal')
            cb1.set_label('Frequency', fontsize=20)
            cb1.ax.tick_params(labelsize=14)
            fig.set_size_inches(15, 10)
            return fig

        # if plotting 3d use the nilearn 3d brain. Unfortunately this doesn't add a colorbar.
        else:
            # you need to return the html. If in jupyter, it will automatically render
            return ni_plot.view_markers(xyz, colors=colors, marker_size=6)
예제 #3
0
def view_markers_with_nilearn(G, node_size=5., node_colouring='black'):
    """
    Plot nodes of a BrainNetwork using
    :func:`nilearn.plotting.view_connectome()` tool.

    Parameters
    ----------
    G : :class:`networkx.Graph`
        G should have nodal locations in MNI space indexed by nodal
        attribute "centroids"
    node_colouring : str or list of str, default 'black'
        node_colouring will determine the colour given to each node.
        If a single string is given, this string will be interpreted as a
        a colour, and all nodes will be rendered in this colour.
        If a list of colours is given,
    """
    a, node_coords, colour_list, z = graph_to_nilearn_array(G, )
    if isinstance(node_colouring, str):
        colours = [node_colouring for i in range(len(node_coords))]
    elif colour_list is not None:
        colours = np.array([node_colouring(x) for x in colour_list])
    return plotting.view_markers(node_coords,
                                 colors=colours,
                                 marker_size=node_size)
예제 #4
0
    scans = reduce_mean(scans)
    voxel_ids = select_most_varied_voxels(scans)[0:1000]


    varied_voxels = [mni_mapping[v] for v in voxel_ids]
    regions =  [roi_mapping[v] for v in voxel_ids]
    all_varied_voxels.extend(varied_voxels)
    color = colors[subject-1]
    color_data.extend([color for _ in range(len(varied_voxels))])
print(len(all_varied_voxels), len(color_data))
    # Open plot in browser
count_map = {}
for i in regions:
    count_map[str(i)] = count_map.get(str(i), 0) + 1
print(count_map)
view = plotting.view_markers(all_varied_voxels, color_data, marker_size=3)
view.open_in_browser()





# ---- KAPLAN DATA -----
# This dataset is described in Dehghani et al. 2017: https://onlinelibrary.wiley.com/doi/epdf/10.1002/hbm.23814
# I received it from Jonas Kaplan, but I am not allowed to share it.

# print("\n\n Stories Data")
# kaplan_reader = StoryDataReader(data_dir=data_dir + "Kaplan_data/")
# kaplan_data = kaplan_reader.read_all_events(subject_ids=[29],language="english")
# sum = 0
#
예제 #5
0
from networkToIndexDicGordon import dic
import pandas as pd
import argparse
from nilearn import plotting
import numpy as np

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--dic_excel',
                        required=True,
                        type=str,
                        help='path to dictionary excel file')
    args = parser.parse_args()
    fd = pd.read_excel(args.dic_excel)
    for net, indexes in dic.items():
        #Checks for every network if all the parcels exists
        fd_net = fd[fd["Community"] == net]
        parcels = list(fd_net["ParcelID"])
        parcels = list(np.array(parcels) - np.array([1] * len(parcels)))
        if (indexes != parcels):
            print("Parcelation error in ", net)
        #Plots all the coordinates - you can compare later with the output from the code
        coords = fd_net["Centroid (MNI)"]
        coords_new = []
        for coord_str in coords:
            coords_new.append([float(x) for x in coord_str.split()])
        view = plotting.view_markers(coords_new, marker_size=10)
        html_name = "test_out/network_plot" + str(net) + ".html"
        view.save_as_html(html_name)
예제 #6
0
def view_nodes_3d(G,
                  node_size=5.,
                  node_color='black',
                  measure=None,
                  cmap_name=None,
                  sns_palette=None,
                  continuous=False,
                  vmin=None,
                  vmax=None):
    """
    Plot nodes of a BrainNetwork using
    :func:`nilearn.plotting.view_markers()` tool.

    Insert a 3d plot of markers in a brain into an HTML page.

    Parameters
    ----------
    G : :class:`networkx.Graph`
        G should have nodal locations in MNI space indexed by nodal
        attribute "centroids"

    node_size : float or array-like, optional (default=5.)
        Size of the nodes showing the seeds in pixels.

    node_color : str or list of str (default 'black')
        node_colour determines the colour given to each node.
        If a single string is given, this string will be interpreted as a
        a colour, and all nodes will be rendered in this colour.
        If a list of colours is given, it must be the same length as the length
        of nodes coordinates.

    measure: str, (optional, default=None)
        The name of a nodal measure.

    cmap_name : Matplotlib colormap
       Colormap for mapping intensities of nodes (default=None).

    sns_palette: seaborn palette, (optional, default=None)
        Discrete color palette only for discrete data. List of colors defining
        a color palette (list of RGB tuples from seaborn color palettes).

    continuous: bool, (optional, default=False)
        Indicate whether the data values are discrete (False) or
        continuous (True).

    vmin : scalar or None, optional
        The minimum value used in colormapping *data*. If *None* the minimum
        value in *data* is used.

    vmax : scalar or None, optional
        The maximum value used in colormapping *data*. If *None* the maximum
        value in *data* is used.

    Returns
    -------
    ConnectomeView : plot of the nodes.
        It can be saved as an html page or rendered (transparently) by the
        Jupyter notebook. Useful methods are :
        - 'resize' to resize the plot displayed in a Jupyter notebook
        - 'save_as_html' to save the plot to a file
        - 'open_in_browser' to save the plot and open it in a web browser.
    """

    # get the nodes coordinates
    adj_matrix, node_coords = graph_to_nilearn_array(G)

    # apply color to all nodes in Graph if node_color is string
    if isinstance(node_color, str):
        node_color = [node_color for _ in range(len(node_coords))]

    # report the attributes of each node in BrainNetwork Graph
    nodal_measures = G.report_nodal_measures()

    # get the color for each node based on the nodal measure
    if measure:
        if measure in nodal_measures.columns:
            node_color = setup_color_list(df=nodal_measures,
                                          measure=measure,
                                          cmap_name=cmap_name,
                                          sns_palette=sns_palette,
                                          continuous=continuous,
                                          vmin=vmin,
                                          vmax=vmax)
        else:
            warnings.warn(
                "Measure \"{}\" does not exist in nodal attributes of graph. "
                "The default color will be used for all nodes.".format(
                    measure))
            node_color = [node_color for _ in range(len(node_coords))]

    # plot nodes
    ConnectomeView = plotting.view_markers(node_coords,
                                           marker_color=node_color,
                                           marker_size=node_size)

    return ConnectomeView
#%%

from nilearn import plotting  
ofc_electrodes = [(-3.17,37.28,7.56),(8.67,38.04,-15.47),(-4.26,38.19,-12.07),(7.67,38.07,-15.91),(-1.98,40.24,-15.36),(7.08,32.13,-14.81),(-8.06,36.04,-6.05),(10.87,35.06,-5.09),(-1.03,36.31,-10.91),(13.66,37.28,-17.09),(-7.02,36.94,-13.11),(4.18,38.13,-12.05),(-0.97,35.20,-10.35),(10.56,31.60,-5.53),(-8.95,43.22,-13.4),(10.63,39.65,-13.44),(-8.97,34.15,-12.16),(27.02,31.69,-5.48),(-8.64,36.74,-6.98),(6.32,35.04,-11.7),(-3.53,36.85,-16.95),(3.94,31.75,-14.51),(0.87,42.45,-1.65),(15.93,33.66,-0.4)]
view = plotting.view_markers(ofc_electrodes, marker_size=10) 
view.save_as_html('ueli_ofc_electrodes.html') 

# %%
#load transform from subj to template
sub2template= np.loadtxt(snakemake.input.xfm_ras)

#plot electrodes transformed (affine) to MNI space, with MNI glass brain
from nilearn import plotting

coords = df[['x','y','z']].to_numpy()
#print(coords.shape)

#to plot in mni space, need to transform coords
tcoords = np.zeros(coords.shape)
for i in range(len(coords)):

    vec = np.hstack([coords[i,:],1])
    tvec = np.linalg.inv(sub2template) @ vec.T
    tcoords[i,:] = tvec[:3]


html_view = plotting.view_markers(tcoords)
html_view.save_as_html(snakemake.output.html)

#plot subject native space electrodes with glass brain
adjacency_matrix = np.zeros([len(coords),len(coords)])


display = plotting.plot_connectome(adjacency_matrix, tcoords)
display.savefig(snakemake.output.png)
display.close()

예제 #9
0
        scans.extend([event.scan for event in block.scan_events])
    scans = reduce_mean(scans)
    voxel_ids = select_most_varied_voxels(scans)[0:1000]

    varied_voxels = [mni_mapping[v] for v in voxel_ids]
    regions = [roi_mapping[v] for v in voxel_ids]
    all_varied_voxels.extend(varied_voxels)
    color = colors[subject - 1]
    color_data.extend([color for _ in range(len(varied_voxels))])
print(len(all_varied_voxels), len(color_data))
# Open plot in browser
count_map = {}
for i in regions:
    count_map[str(i)] = count_map.get(str(i), 0) + 1
print(count_map)
view = plotting.view_markers(all_varied_voxels, color_data, marker_size=3)
view.open_in_browser()

# ---- KAPLAN DATA -----
# This dataset is described in Dehghani et al. 2017: https://onlinelibrary.wiley.com/doi/epdf/10.1002/hbm.23814
# I received it from Jonas Kaplan, but I am not allowed to share it.

# print("\n\n Stories Data")
# kaplan_reader = StoryDataReader(data_dir=data_dir + "Kaplan_data/")
# kaplan_data = kaplan_reader.read_all_events(subject_ids=[29],language="english")
# sum = 0
#
# for subject_id in kaplan_data.keys():
#     all_scans = []
#     for block in kaplan_data[subject_id]:
#         # These are all already sorted, so I think you don't even need timesteps.
예제 #10
0
from nilearn import plotting
import pandas as pd
import scipy.io as sio
import numpy as np

# Load subjVar as pandas dataframe
fname = '/Users/pinheirochagas/Desktop/elinfo.csv'
mni = np.loadtxt(fname, delimiter=',')
fname = '/Users/pinheirochagas/Desktop/colors.csv'
colors = np.loadtxt(fname, delimiter=',')

view = plotting.view_markers(mni, colors, marker_size=5)
view.open_in_browser()
view.save_as_html("/Users/pinheirochagas/Desktop/elinfo.html")

img = datasets.fetch_localizer_button_task()
view = plotting.view_img_on_surf(img, threshold='90%', surf_mesh='fsaverage')

fname = '/Users/pinheirochagas/Downloads/arithmetic_association-test_z_FDR_0.01.nii'

plotting.plot_glass_brain(fname, display_mode='lyrz', threshold=3)
plt.savefig('/Users/pinheirochagas/Desktop/arith_neurosynth.png')

plotting.plot_glass_brain(stat_img, threshold=3)

from nilearn import plotting, datasets, surface
dmn_coords = [(0, -52, 18), (-46, -68, 32), (46, -68, 32), (1, 50, -5)]

img = datasets.fetch_localizer_button_task()['tmap']
view = plotting.view_img_on_surf(fname, threshold='90%', surf_mesh='fsaverage')