def main():
    # Import a numpy array as the adjacency matrix
    home = expanduser('~')
    directory_name = join(home, 'Documents', 'data_conn')
    data_file_name = join(directory_name, 'func_modeled.npy')
    struct_conn = np.load(data_file_name)

    # # Generate graph
    # G = nx.from_numpy_array(struct_conn)
    #
    # # Visualize graph - no meaning to position or colour
    # plt.figure('Graph')
    # n_node = G.number_of_nodes()  # number of nodes
    # nx.draw(G, node_size=50, node_color=np.arange(n_node),  width=0.1, cmap='Blues')
    # plt.show()

    # Visualise graph with positions specified by brain region coordinates
    # # Import node positions from file of (x,y,z) co-ordinates from brain region centers
    positions_file_name = join(directory_name, 'region_positions.npy')
    region_positions = np.load(positions_file_name)
    plotting.plot_connectome(struct_conn,
                             region_positions - region_positions.mean(0),
                             title="Structural Connectivity",
                             display_mode='x',
                             alpha=0,
                             node_color='k',
                             node_size=10,
                             edge_cmap='jet',
                             colorbar=True)
    plotting.show()
Example #2
0
def plot_consistent_edges(all_masks,
                          tail,
                          thresh=1.,
                          color='gray',
                          coords=None):
    edge_frac = (all_masks[tail].sum(axis=0)) / (all_masks[tail].shape[0])
    print("For the {} tail, {} edges were selected in at least {}% of folds".
          format(tail, (edge_frac >= thresh).sum(), thresh * 100))
    edge_frac_square = sp.spatial.distance.squareform(edge_frac)

    node_mask = np.amax(
        edge_frac_square, axis=0
    ) >= thresh  # find nodes that have at least one edge that passes the threshold
    node_size = edge_frac_square.sum(
        axis=0
    ) * node_mask * 20  # size nodes based on how many suprathreshold edges they have

    plotting.plot_connectome(adjacency_matrix=edge_frac_square,
                             edge_threshold=thresh,
                             node_color=color,
                             node_coords=coords,
                             node_size=node_size,
                             display_mode='lzry',
                             edge_kwargs={
                                 "linewidth": 1,
                                 'color': color
                             })
Example #3
0
def plot_brain_connections(mat,
                           power_coords,
                           mat_name='beta_mat',
                           thre='99.9%',
                           save_plot=False,
                           cache_prefix='r1s1_'):
    if mat_name == 'beta_mat':
        tit = 'Beta'
    elif mat_name == 'wcorr_mat':
        tit = 'Weighted Connectivity'
    else:
        tit = 'Unknown'

    # plot
    sns.set_style('white')
    fig = plt.figure(figsize=(10, 3))
    ax = fig.add_subplot(111)
    ax.axis("off")

    # plot connectome with 80% edge strength in the connectivity
    plotting.plot_connectome(
        mat,
        power_coords,
        figure=fig,
        edge_threshold=thre,
        #node_color=,
        colorbar=True,
        node_size=0,  # size 264
        #alpha=.8,
        #title='Group analysis: ' + tit,
        edge_kwargs={'lw': 8})
    if save_plot:
        plt.savefig('./bin/' + cache_prefix + mat_name + thre + '.png')
    plt.show()
    plt.close()
Example #4
0
def test_plot_connectome_non_symmetric(node_coords, non_symmetric_matrix):
    """Tests for plot_connectome with non symmetric adjacency matrices."""
    ax = plot_connectome(non_symmetric_matrix, node_coords,
                         display_mode='ortho')
    # No thresholding was performed, we should get
    # as many arrows as we have edges
    for direction in ['x', 'y', 'z']:
        assert(len([patch for patch in ax.axes[direction].ax.patches
                    if isinstance(patch, FancyArrow)])
               == np.prod(non_symmetric_matrix.shape))

    # Set a few elements of adjacency matrix to zero
    non_symmetric_matrix[1, 0] = 0.0
    non_symmetric_matrix[2, 3] = 0.0
    # Plot with different display mode
    ax = plot_connectome(non_symmetric_matrix,
                         node_coords,
                         display_mode='lzry')
    # No edge in direction 'l' because of node coords
    assert(len([patch for patch in ax.axes['l'].ax.patches
                if isinstance(patch, FancyArrow)]) == 0)
    for direction in ['z', 'r', 'y']:
        assert(len([patch for patch in ax.axes[direction].ax.patches
                    if isinstance(patch, FancyArrow)])
               == np.prod(non_symmetric_matrix.shape) - 2)
Example #5
0
def CCA_cm_brain_plot(cca, MNIcoords, mode=0, num_edge=200, title=None):
    cm = cca.x_weights_mat[:, :, mode]
    cm = cm + cm.T
    cm_degree = np.sum(abs(cm), axis=1)
    cm = matrix_threshold(cm, num_edge=num_edge)
    cm_degree_plot = (cm_degree / np.max(cm_degree)) * 75
    plotting.plot_connectome(cm,
                             MNIcoords,
                             node_size=cm_degree_plot,
                             node_color='black',
                             edge_cmap='vlag',
                             edge_vmin=-1,
                             edge_vmax=1,
                             display_mode='lzr',
                             edge_kwargs={
                                 'Alpha': 0.75,
                                 'lw': 1
                             },
                             node_kwargs={
                                 'Alpha': 0,
                                 'lw': 0
                             },
                             colorbar=True)
    if title is not None:
        plt.savefig(title, dpi=600)
    plotting.show()
Example #6
0
def lesion_dist_cm(cm, MNIcoords, title=None, vmin=-30, vmax=30):
    #binarize
    cm[cm > 0] = 1
    cm = np.sum(cm, axis=2)

    #symmetrize
    cm = cm + cm.T
    cm_degree = np.sum(abs(cm), axis=1)
    cm_degree_plot = (cm_degree / np.max(cm_degree)) * 100
    plotting.plot_connectome(
        cm,
        MNIcoords,
        node_size=cm_degree_plot,
        node_color='black',
        edge_cmap='viridis',
        edge_vmin=
        vmin,  # to get same colour echeme as the nifti plot set to opposite
        edge_vmax=vmax,
        colorbar=True,
        display_mode='lzr',
        edge_kwargs={
            'Alpha': 0.25,
            'lw': 1
        },
        node_kwargs={
            'Alpha': 0,
            'lw': 0
        })
    if title is not None:
        plt.savefig(title, dpi=600)
    plotting.show()
Example #7
0
def plot_connectome_edge_thresholding(node_coords, non_symmetric_matrix):
    """Tests for plot_connectome with edge thresholding."""
    # Case 1: Threshold is a number
    thresh = 1.1
    ax = plot_connectome(non_symmetric_matrix,
                         node_coords,
                         edge_threshold=thresh)
    for direction in ['x', 'y', 'z']:
        assert(len([patch for patch in ax.axes[direction].ax.patches
                    if isinstance(patch, FancyArrow)])
               == np.sum(np.abs(non_symmetric_matrix) >= thresh)
               )
    # Case 2: Threshold is a percentage
    thresh = 80
    ax = plot_connectome(non_symmetric_matrix,
                         node_coords,
                         edge_threshold="{}%".format(thresh))
    for direction in ['x', 'y', 'z']:
        assert(len([patch for patch in ax.axes[direction].ax.patches
                    if isinstance(patch, FancyArrow)])
               == np.sum(np.abs(non_symmetric_matrix)
                         >= np.percentile(np.abs(
                             non_symmetric_matrix.ravel()), thresh))
               )
    plt.close()
Example #8
0
def channel_position_plot(ax, coords, mask=[]):
    """Plot electrode position on brain with nilearn

    Plot all electrodes in white and selected electrode in blue.
    Output jpeg with several projections

    Parameters
    ----------
    ax : pyplot ax
        ax where to plot 
    coords : list 
        coords of channel to plot
    """

    colors = np.array([[0.7, 0.13, 0.13, 1.]] * len(coords))
    sizes = 10 * np.ones(len(colors))
    if len(mask) > 0 and np.sum(mask) > 0:
        sizes[mask] = 0.5 * np.ones(np.sum(mask))
        colors[mask] = np.array([[0., 0., 0., .5]] * np.sum(mask))

    # nilearn plot
    try:
        plotting.plot_connectome(np.zeros((len(coords), len(coords))),
                                 coords,
                                 node_color=colors.tolist(),
                                 display_mode='lyrz',
                                 axes=ax,
                                 node_size=sizes)
    except:
        pass
Example #9
0
def plot_ecog_electrodes_mni_from_file_and_labels(mni_coords_fullfile,chan_labels,num_grid_chans=64,colors=list()):
    'Plots ECoG electrodes from MNI coordinate file'
    #Example code to run it: 
         #import sys
         #sys.path.append('/home/stepeter/AJILE/stepeter_sandbox/ECoG_Preprocessing')
         #from plot_ecog_electrodes_mni import *

         #mni_coords_fullfile='/data2/users/stepeter/mni_coords/a0f66459/a0f66459_MNI_atlasRegions.xlsx'
         #plot_ecog_electrodes_mni_from_file_and_labels(mni_coords_fullfile,chan_num_min=-1,chan_num_max=-1,num_grid_chans=64)
        
    #NOTE: A warning may pop up the first time running it, leading to no output. Rerun this function, and the plots should appear.
    
    #Load in MNI file
    mni_file = pd.read_excel(mni_coords_fullfile, delimiter=",")
    
    
    #Create dataframe for electrode locations
    locs=mni_file.loc[mni_file['Electrode'].isin(chan_labels)][['X coor', 'Y coor', 'Z coor']]
    print(locs.shape)
    
    #Label strips/depths differently for easier visualization (or use defined color list)
    if len(colors)==0:
        for s in range(locs.shape[0]):
            if s>=num_grid_chans:
                colors.append('r')
            else:
                colors.append('b')
        
    #Plot the result
    ni_plt.plot_connectome(np.eye(locs.shape[0]), locs, output_file=None,
                           node_kwargs={'alpha': 0.5, 'edgecolors': None},
                           node_size=10, node_color=colors)
Example #10
0
def plot_ecog_electrodes_mni_direct(mni_coords,num_grid_chans=64,colors=list()):
    'Plots ECoG electrodes from MNI coordinate file'
    #Example code to run it: 
        # import sys
        # sys.path.append('/home/stepeter/AJILE/stepeter_sandbox/ECoG_Preprocessing')
        # from plot_ecog_electrodes_mni import *

        # colors=list()
        # cmap = matplotlib.cm.get_cmap('jet')
        # for i in range(virtualCoords_pos.shape[1]):
        # colors.append(np.asarray(cmap(frac_sbj_virtual_grid[0,i]))[0:3])
        # colors = np.asarray(colors)
        # colors = list(map(lambda x: x[0], np.array_split(colors, colors.shape[0], axis=0)))
        # plot_ecog_electrodes_mni_direct(virtualCoords_pos.T,num_grid_chans=64,colors=colors)
        
    #NOTE: If running in Jupyter, use '%matplotlib inline' instead of '%matplotlib notebook'
    
    #Create dataframe for electrode locations
    locs=pd.DataFrame(mni_file.loc[mni_file['Electrode'].isin(chan_labels)]['Coordinates'])
    #locs=pd.DataFrame({'x': mni_coords[:,0].T,
    #                  'y': mni_coords[:,1].T,
    #                  'z': mni_coords[:,2].T})
    
    #Label strips/depths differently for easier visualization (or use defined color list)
    if len(colors)==0:
        for s in range(locs.shape[0]):
            if s>=num_grid_chans:
                colors.append('r')
            else:
                colors.append('b')
   
    #Plot the result
    ni_plt.plot_connectome(np.eye(locs.shape[0]), locs, output_file=None,
                           node_kwargs={'alpha': 0.5, 'edgecolors': None},
                           node_size=10, node_color=colors)
def plot_connectivity_glassbrain(subject_id, group, pc, roi_coords,
                                 suffix, session='func1',
                                 preprocessing_folder='pipeline_1',
                                 save=True, msdl=False):
    """Plots connectome of pc
    """
    title = '-'.join([suffix, group, subject_id, session])
    
    output_folder = os.path.join(set_figure_base_dir('connectivity'), suffix)
    if not os.path.isdir(output_folder):
        os.makedirs(output_folder)
    
    output_file = os.path.join(output_folder,
                               '_'.join([suffix, 'connectome', group,
                                         session,
                                         preprocessing_folder, subject_id]))
                                         
    if msdl:
        title += '_msdl'
        output_file += '_msdl'
                                         
    plt.figure(figsize=(10, 20), dpi=90)
    if save:    
        plot_connectome(pc, roi_coords, edge_threshold='90%', title=title,
                        output_file=output_file)
    else:
        plot_connectome(pc, roi_coords, edge_threshold='90%', title=title)
Example #12
0
def plot_connectome(covs, tv=False):
    # g = np.zeros(shape=(160, 160))
    g = covs
    dos_coords = datasets.fetch_coords_dosenbach_2010()
    dos_coords = dos_coords.rois
    dos_coords_table = [[x, y, z] for (x, y, z) in dos_coords
                        ]  # Reformat the atlas coordinates

    f = plt.figure(figsize=(2.3, 3.5))  # 2.2,2.3
    if tv:
        plotting.plot_connectome(g,
                                 dos_coords_table,
                                 display_mode='z',
                                 output_file='figs/connectome_tv.pdf',
                                 edge_threshold="0.0005%",
                                 annotate=True,
                                 figure=f,
                                 node_size=18)

    else:
        plotting.plot_connectome(g,
                                 dos_coords_table,
                                 display_mode='z',
                                 output_file='figs/connectome.pdf',
                                 edge_threshold="0.0005%",
                                 annotate=True,
                                 figure=f,
                                 node_size=18)
def save_graphs_models(subj, subj_folder, mnicoor, thresholds):

    for i, r in enumerate(thresholds):
        correlation_matrix = subj[i]

        aux = int(round(thresholds[i] * 100))

        if aux < 10:
            aux = '0' + str(aux)
        else:
            aux = str(aux)

        print('r=' + aux + ',', end=' ')
        SAVEIMAGENAME = subj_folder + "\\" + subj_folder + '_r' + aux + '.png'

        plotting.plot_connectome(correlation_matrix,
                                 mnicoor,
                                 colorbar=False,
                                 node_color='black',
                                 edge_vmin=0,
                                 edge_vmax=1,
                                 node_size=10,
                                 display_mode="lzry",
                                 title='r=.' + aux,
                                 output_file=SAVEIMAGENAME)

    return None
Example #14
0
def test_plot_connectome_with_nans(adjacency, node_coords, base_params):
    """Smoke test for plot_connectome with nans in the adjacency matrix."""
    adjacency[0, 1] = np.nan
    adjacency[1, 0] = np.nan
    base_params["node_color"] = np.array(['green', 'blue', 'k', 'yellow'])
    plot_connectome(adjacency, node_coords, **base_params)
    plt.close()
Example #15
0
def plot_consistent_edges(all_masks,
                          tail,
                          thresh=1.,
                          color='gray',
                          coords=None,
                          **plot_kwargs):
    """Plots edges which are consistent in a defined percentage of folds"""
    edge_frac = (all_masks[tail].sum(axis=0)) / (all_masks[tail].shape[0])
    summary = "{} suprathreshold (>= {} %) edges in {} % of the subjects".format(
        (edge_frac >= thresh).sum(), thresh * 100, "TODO")
    print("For the {} tail, {} edges were selected in at least {}% of folds".
          format(tail, (edge_frac >= thresh).sum(), thresh * 100))
    edge_frac_square = sp.spatial.distance.squareform(edge_frac)

    node_mask = np.amax(
        edge_frac_square, axis=0
    ) >= thresh  # find nodes that have at least one edge that passes the threshold
    node_size = edge_frac_square.sum(
        axis=0
    ) * node_mask * 20  # size nodes based on how many suprathreshold edges they have

    plotting.plot_connectome(adjacency_matrix=edge_frac_square,
                             edge_threshold=thresh,
                             node_color=color,
                             node_coords=coords,
                             node_size=node_size,
                             display_mode='lzry',
                             edge_kwargs={
                                 "linewidth": 1,
                                 'color': color
                             },
                             **plot_kwargs)

    return (edge_frac_square >= thresh).astype(int), node_mask
Example #16
0
def test_plot_connectome_exceptions_non_symmetric_adjacency(matrix):
    """Tests that warning messages are given when the adjacency matrix ends
    up being non symmetric.
    """
    node_coords = np.arange(2 * 3).reshape((2, 3))
    with pytest.warns(UserWarning, match="A directed graph will be plotted."):
        plot_connectome(matrix, node_coords, display_mode='x')
    plt.close()
Example #17
0
def test_plot_connectome_display_mode(display_mode, node_coords,
                                      adjacency, base_params):
    """Smoke test for plot_connectome with different values
    for display_mode.
    """
    plot_connectome(adjacency, node_coords, display_mode=display_mode,
                    **base_params)
    plt.close()
Example #18
0
def test_plot_connectome_tuple_node_coords(adjacency, node_coords, base_params,
                                           tmpdir):
    """Smoke test for plot_connectome where node_coords is not provided
    as an array but as a list of tuples.
    """
    plot_connectome(adjacency, [tuple(each) for each in node_coords],
                    display_mode='x',
                    **base_params)
    plt.close()
    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(connectome, title, axes):
     plotting.plot_connectome(connectome,
                              DesikanAtlas.coordinates(),
                              title=title,
                              edge_threshold='90%',
                              node_size=20,
                              colorbar=True,
                              axes=axes,
                              annotate=True)
Example #21
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)
Example #22
0
def test_plot_connectome_exception_wrong_edge_threshold(adjacency, node_coords):  # noqa
    """Tests that a TypeError is raised in plot_connectome when edge
    threshold is neither a number nor a string.
    """
    with pytest.raises(TypeError,
                       match='should be either a number or a string'):
        plot_connectome(
            adjacency, node_coords, edge_threshold=object(), display_mode='x'
        )
Example #23
0
def test_plot_connectome_node_colors(node_color, display_mode, node_coords,
                                     adjacency, base_params, tmpdir):
    """Smoke test for plot_connectome with different values for node_color."""
    plot_connectome(adjacency,
                    node_coords,
                    node_color=node_color,
                    display_mode=display_mode,
                    **base_params)
    plt.close()
Example #24
0
def test_plot_connectome_node_and_edge_kwargs(adjacency, node_coords):
    """Smoke test for plot_connectome with node_kwargs, edge_kwargs,
    and edge_cmap arguments.
    """
    plot_connectome(adjacency, node_coords, edge_threshold='70%',
                    node_size=[10, 20, 30, 40], node_color=np.zeros((4, 3)),
                    edge_cmap='RdBu', colorbar=True,
                    node_kwargs={'marker': 'v'},
                    edge_kwargs={'linewidth': 4})
    plt.close()
Example #25
0
def test_plot_connectome_exceptions_providing_node_info_with_kwargs(
        node_kwargs, adjacency, node_coords, expected_error_node_kwargs):
    """Tests that an error is raised when specifying node parameters
    via node_kwargs in plot_connectome.
    """
    with pytest.raises(ValueError,
                       match=expected_error_node_kwargs):
        plot_connectome(
            adjacency, node_coords, node_kwargs=node_kwargs, display_mode='x'
        )
Example #26
0
def test_plot_connectome_masked_array_sparse_matrix(node_coords, adjacency,
                                                    base_params):
    """Smoke tests for plot_connectome with masked arrays and sparse
    matrices as inputs.
    """
    masked_adjacency_matrix = np.ma.masked_array(adjacency,
                                                 np.abs(adjacency) < 0.5)
    plot_connectome(masked_adjacency_matrix, node_coords, **base_params)
    sparse_adjacency_matrix = sparse.coo_matrix(adjacency)
    plot_connectome(sparse_adjacency_matrix, node_coords, **base_params)
    plt.close()
Example #27
0
def test_plot_connectome_exceptions_wrong_number_node_colors(node_color,
                                                             adjacency,
                                                             node_coords):
    """Tests that a wrong number of node colors raises a
    ValueError in plot_connectome.
    """
    with pytest.raises(ValueError,
                       match='Mismatch between the number of nodes'):
        plot_connectome(
            adjacency, node_coords, node_color=node_color, display_mode='x'
        )
Example #28
0
def test_plot_connectome_exception_wrong_edge_threshold_format(
        threshold, adjacency, node_coords):
    """Tests that a ValueError is raised when edge_threshold is an incorrectly
    formatted string.
    """
    with pytest.raises(ValueError,
                       match=("should be a number followed "
                              "by the percent sign")):
        plot_connectome(
            adjacency, node_coords, edge_threshold=threshold, display_mode='x'
        )
def run_mini_pipeline():
    atlas = datasets.fetch_atlas_msdl()
    atlas_img = atlas['maps']
    labels = pd.read_csv(atlas['labels'])['name']

    masker = NiftiMapsMasker(maps_img=atlas_img, standardize=True,
                               memory='/tmp/nilearn', verbose=0)

    data = datasets.fetch_adhd(number_subjects)

    figures_folder = '../figures/'
    count=0
    for func_file, confound_file in zip(data.func, data.confounds):
        
        # fit the data to the atlas mask, regress out confounds
        time_series = masker.fit_transform(func_file, confounds=confound_file)

        correlation = np.corrcoef(time_series.T)

        #plotting starts here
        plt.figure(figsize=(10, 10))
        plt.imshow(correlation, interpolation="nearest")
        x_ticks = plt.xticks(range(len(labels)), labels, rotation=90)
        y_ticks = plt.yticks(range(len(labels)), labels)
        corr_file = figures_folder+'subject_number_' + str(count) + '_correlation.pdf'
        plt.savefig(corr_file)

        atlas_region_coords = [plotting.find_xyz_cut_coords(img) for img in image.iter_img(atlas_img)]
        threshold = 0.6
        plotting.plot_connectome(correlation, atlas_region_coords, edge_threshold=threshold)
        connectome_file = figures_folder+'subject_number_' + str(count) + '_connectome.pdf'
        plt.savefig(connectome_file)


        #graph setup

        #binarize correlation matrix
        correlation[correlation<threshold] = 0
        correlation[correlation != 0] = 1

        graph = nx.from_numpy_matrix(correlation)

        partition=louvain.best_partition(graph)

        values = [partition.get(node) for node in graph.nodes()]

        plt.figure()
        nx.draw_spring(graph, cmap = plt.get_cmap('jet'), node_color = values, node_size=30, with_labels=True)
        graph_file = figures_folder+'subject_number_' + str(count) + '_community.pdf'
        plt.savefig(graph_file)

        count += 1

        plt.close('all')
Example #30
0
File: MHA.py Project: piomonti/MHA
	def plot( self, ROIcoord, clusterID, title):
		"""
		INPUT:
			- ROIcoord: MNNI coordinates
			- clusterID: which cluster should we plot

		"""
		ii = np.where( self.W[:, clusterID] !=0 )[0]
		RandomMat = np.cov( np.random.random(( 10, len(ii))).T ) # this is just a place holder, we will not plot any of it!

		# we just plot the result
		plotting.plot_connectome(RandomMat, ROIcoord[ii,:], node_color='black', annotate=False, display_mode='ortho', edge_kwargs = {'alpha':0}, node_size=50, title=title)
Example #31
0
def plot_brains(coords, colors, fname):
    plt.clf()
    adjMat = np.zeros(shape=(len(colors), len(colors)))

    bf = plt.figure(figsize=[24, 20])
    plot_connectome(adjMat,
                    coords,
                    colors,
                    display_mode='lr',
                    node_size=900,
                    figure=bf,
                    output_file=fname)
Example #32
0
def plot_ecog_electrodes_mni_from_file(mni_coords_fullfile,
                                       chan_num_min=-1,
                                       chan_num_max=-1,
                                       num_grid_chans=64,
                                       colors=list()):
    'Plots ECoG electrodes from MNI coordinate file'
    #Example code to run it:
    #import sys
    #sys.path.append('/home/stepeter/AJILE/stepeter_sandbox/ECoG_Preprocessing')
    #from plot_ecog_electrodes_mni import *

    #mni_coords_fullfile='/data2/users/stepeter/mni_coords/a0f66459/294e1c_Trodes_MNIcoords.txt'
    #plot_ecog_electrodes_mni(mni_coords_fullfile,chan_num_min=-1,chan_num_max=-1,num_grid_chans=64)

    #NOTE: A warning may pop up the first time running it, leading to no output. Rerun this function, and the plots should appear.

    #Load in MNI file
    mni_file = np.loadtxt(mni_coords_fullfile, delimiter=",")

    #Specify which channels to plot (from min to max number)
    if chan_num_min == -1:
        chan_num_min = 0
    if chan_num_max == -1:
        chan_num_max = mni_file.shape[0] - 1
    slice_inds = slice(chan_num_min, chan_num_max + 1)

    #Create dataframe for electrode locations
    locs = pd.DataFrame({
        'x': mni_file[slice_inds, 0].T,
        'y': mni_file[slice_inds, 1].T,
        'z': mni_file[slice_inds, 2].T
    })

    #Label strips/depths differently for easier visualization (or use defined color list)
    if len(colors) == 0:
        for s in range(locs.shape[0]):
            if s >= num_grid_chans:
                colors.append('r')
            else:
                colors.append('b')

    #Plot the result
    ni_plt.plot_connectome(np.eye(locs.shape[0]),
                           locs,
                           output_file=None,
                           node_kwargs={
                               'alpha': 0.5,
                               'edgecolors': None
                           },
                           node_size=10,
                           node_color=colors)
Example #33
0
def plotBrains(coords, colors, fname=None):
    #Simplified from projUtils version
    mpl.rcParams.update(mpl.rcParamsDefault)

    numc = len(colors)
    adjMat = np.zeros(shape=(numc, numc))
    fig = plt.figure(figsize=[24, 12])
    plot_connectome(adjMat,
                    coords,
                    colors,
                    display_mode='lr',
                    node_size=900,
                    figure=fig,
                    output_file=fname,
                    black_bg=False)
Example #34
0
def plot_connectome(matrix, 
                    coords, 
                    colors, 
                    size, 
                    threshold, 
                    fname,                    
                    cmap=plt.cm.hot, 
                    title='', 
                    max_=None, 
                    min_=None, 
                    display_='ortho'):
    
    """
    Wrapper of the plot_connectome function in nilearn with some fixed
    values
    """
    
    from nilearn import plotting
    
    plotting.plot_connectome(adjacency_matrix=matrix, 
                             node_coords=coords, 
                             node_color=colors.tolist(), 
                             node_size=1.5*size, 
                             edge_cmap=cmap, 
                             edge_vmin=min_, 
                             edge_vmax=max_, 
                             edge_threshold=threshold, 
                             output_file=fname, 
                             display_mode=display_, 
                             figure=plt.figure(figsize=(16*1.2,9*1.2)),# facecolor='k', edgecolor='k'), 
                             #axes, 
                             title=title, 
                             #annotate, 
                             black_bg=True, 
                             #alpha, 
                             edge_kwargs={
                                          'alpha':0.8,
                                          'linewidth':9,
                                          }, 
                             node_kwargs={
                                          'edgecolors':'k',
                                          }, 
                             #colorbar=True
                             )
###############################################################################
# Plot matrix and graph
# ---------------------
#
# We use `matplotlib` plotting functions to visualize our correlation matrix
# and display the graph of connections with `nilearn.plotting.plot_connectome`.
import matplotlib.pyplot as plt
from nilearn import plotting

plt.imshow(matrix, vmin=-1.0, vmax=1.0, cmap="RdBu_r", interpolation="nearest")
plt.colorbar()
plt.title("Power correlation matrix")

# Tweak edge_threshold to keep only the strongest connections.
plotting.plot_connectome(
    matrix, coords, title="Power correlation graph", edge_threshold="99.8%", node_size=20, colorbar=True
)

###############################################################################
# Note the 1. on the matrix diagonal: These are the signals variances, set to
# 1. by the `spheres_masker`. Hence the covariance of the signal is a
# correlation matrix

###############################################################################
# Connectome extracted from Dosenbach's atlas
# -------------------------------------------
#
# We repeat the same steps for Dosenbach's atlas.
dosenbach = datasets.fetch_coords_dosenbach_2010()

coords = np.vstack((dosenbach.rois["x"], dosenbach.rois["y"], dosenbach.rois["z"])).T
from nilearn.group_sparse_covariance import GroupSparseCovarianceCV
gsc = GroupSparseCovarianceCV(verbose=2)
gsc.fit(subject_time_series)

print("-- Computing graph-lasso precision matrices ...")
from sklearn import covariance
gl = covariance.GraphLassoCV(verbose=2)
gl.fit(np.concatenate(subject_time_series))

# Displaying results ##########################################################
atlas_imgs = image.iter_img(msdl_atlas_dataset.maps)
atlas_region_coords = [plotting.find_xyz_cut_coords(img) for img in atlas_imgs]

title = "GraphLasso"
plotting.plot_connectome(-gl.precision_, atlas_region_coords,
                         edge_threshold='90%',
                         title="Sparse inverse covariance (GraphLasso)")
plotting.plot_connectome(gl.covariance_,
                         atlas_region_coords, edge_threshold='90%',
                         title="Covariance")
plot_matrices(gl.covariance_, gl.precision_, title)

title = "GroupSparseCovariance"
plotting.plot_connectome(-gsc.precisions_[..., 0],
                         atlas_region_coords, edge_threshold='90%',
                         title=title)
plot_matrices(gsc.covariances_[..., 0],
              gsc.precisions_[..., 0], title)

plt.show()
# The covariance can be found at estimator.covariance_
plt.imshow(estimator.covariance_, interpolation="nearest",
           vmax=1, vmin=-1, cmap=plt.cm.RdBu_r)
# And display the labels
x_ticks = plt.xticks(range(len(labels)), labels, rotation=90)
y_ticks = plt.yticks(range(len(labels)), labels)
plt.title('Covariance')

##############################################################################
# And now display the corresponding graph
# ----------------------------------------
from nilearn import plotting
coords = atlas.region_coords

plotting.plot_connectome(estimator.covariance_, coords,
                         title='Covariance')


##############################################################################
# Display the sparse inverse covariance
# --------------------------------------
# we negate it to get partial correlations
plt.figure(figsize=(10, 10))
plt.imshow(-estimator.precision_, interpolation="nearest",
           vmax=1, vmin=-1, cmap=plt.cm.RdBu_r)
# And display the labels
x_ticks = plt.xticks(range(len(labels)), labels, rotation=90)
y_ticks = plt.yticks(range(len(labels)), labels)
plt.title('Sparse inverse covariance')

##############################################################################
# All individual coefficients are stacked in a unique 2D matrix.
print('Correlations of ADHD patients are stacked in an array of shape {0}'
      .format(correlation_matrices.shape))

###############################################################################
# as well as the average correlation across all fitted subjects.
mean_correlation_matrix = correlation_measure.mean_
print('Mean correlation has shape {0}.'.format(mean_correlation_matrix.shape))

###############################################################################
# We display the connectomes of the first 3 ADHD subjects and the mean
# correlation matrix over all ADHD patients.
from nilearn import plotting

plot_matrices(correlation_matrices[:4], 'correlation')
plotting.plot_connectome(mean_correlation_matrix, msdl_coords,
                         title='mean correlation over 13 ADHD subjects')

###############################################################################
# Look at blocks structure, reflecting functional networks.

###############################################################################
# Examine partial correlations
# ----------------------------
# We can also study **direct connections**, revealed by partial correlation
# coefficients. We just change the `ConnectivityMeasure` kind
partial_correlation_measure = ConnectivityMeasure(kind='partial correlation')

###############################################################################
# and repeat the previous operation.
partial_correlation_matrices = partial_correlation_measure.fit_transform(
    adhd_subjects)
Example #39
0
        if "Unknown" not in str(label):  # Omit the Unknown label.
            # Compute mean location of vertices in label of index k
            coordinates.append(np.mean(rr[vert == k], axis=0))

coordinates = np.array(coordinates)  # 3D coordinates of parcels

# We now make a synthetic connectivity matrix that connects labels
# between left and right hemispheres.
n_parcels = len(coordinates)
corr = np.zeros((n_parcels, n_parcels))
n_parcels_hemi = n_parcels // 2
corr[np.arange(n_parcels_hemi), np.arange(n_parcels_hemi) + n_parcels_hemi] = 1
corr = corr + corr.T

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)
# uncomment this to open the plot in a web browser:
# view.open_in_browser()
from nilearn.connectome import ConnectivityMeasure
connectivity_measure = ConnectivityMeasure(kind='partial correlation')
partial_correlation_matrix = connectivity_measure.fit_transform(
    [time_series])[0]


##########################################################################
# Display connectome
# -------------------
#
# We display the graph of connections with `:func: nilearn.plotting.plot_connectome`.

from nilearn import plotting

plotting.plot_connectome(partial_correlation_matrix, dmn_coords,
                         title="Default Mode Network Connectivity")


##########################################################################
# Display connectome with hemispheric projections.
# Notice (0, -52, 18) is included in both hemispheres since x == 0.
plotting.plot_connectome(partial_correlation_matrix, dmn_coords,
                         title="Connectivity projected on hemispheres",
                         display_mode='lyrz')

plotting.show()


##############################################################################
# 3D visualization in a web browser
# ---------------------------------
gsc.fit(subject_time_series)

from sklearn import covariance
gl = covariance.GraphLassoCV(verbose=2)
gl.fit(np.concatenate(subject_time_series))


##############################################################################
# Displaying results
# -------------------
atlas_imgs = image.iter_img(msdl_atlas_dataset.maps)
atlas_region_coords = [plotting.find_xyz_cut_coords(img) for img in atlas_imgs]
labels = msdl_atlas_dataset.labels

plotting.plot_connectome(gl.covariance_,
                         atlas_region_coords, edge_threshold='90%',
                         title="Covariance",
                         display_mode="lzr")
plotting.plot_connectome(-gl.precision_, atlas_region_coords,
                         edge_threshold='90%',
                         title="Sparse inverse covariance (GraphLasso)",
                         display_mode="lzr",
                         edge_vmax=.5, edge_vmin=-.5)
plot_matrices(gl.covariance_, gl.precision_, "GraphLasso", labels)

title = "GroupSparseCovariance"
plotting.plot_connectome(-gsc.precisions_[..., 0],
                         atlas_region_coords, edge_threshold='90%',
                         title=title,
                         display_mode="lzr",
                         edge_vmax=.5, edge_vmin=-.5)
plot_matrices(gsc.covariances_[..., 0],
Example #42
0
__author__ = '2d Lt Kyle Palko'

import numpy as np
from nilearn import plotting as plt

# import Pitt 0050013, a young autistic subject
ts = np.genfromtxt('/media/kap/8e22f6f8-c4df-4d97-a388-0adcae3ec1fb/Python/Thesis/C200/ABIDE_pcp/cpac/filt_noglobal/'
                   'Pitt_0050013_rois_cc200.1D', skip_header=1)
cor = np.corrcoef(ts.T)

# create matrix
x = np.zeros((200, 200))
for i in range(0, np.size(x, axis=0)):
    x[i][i] = 1

a = np.genfromtxt('cc200_roi.csv', delimiter=',')
row = np.array([c[0] for c in a])
col = np.array([c[1] for c in a])
del a

for i in range(0, 10):
    r = row[i]
    c = col[i]
    x[r, c] = cor[r, c]
    x[c, r] = cor[c, r]

node_coords = np.genfromtxt('cc200_lab_coord.csv', delimiter=',')
plt.plot_connectome(x, node_coords, output_file='corrtest_1.png', node_size=1)
###############################################################################
# Extract and plot correlation matrix

for atlas in ['Power', 'Dosenbach']:

    if atlas == 'Power':
        timeseries = power_timeseries
        coords = power_coords
    else:
        timeseries = dosenbach_timeseries
        coords = dosenbach_coords

    connectivity = connectome.ConnectivityMeasure(kind='correlation')
    corr_matrix = connectivity.fit_transform([timeseries])[0]
    np.fill_diagonal(corr_matrix, 0)

    plt.figure()
    vmax = np.max(np.abs(corr_matrix))
    plt.imshow(corr_matrix, vmin=-vmax, vmax=vmax, cmap='RdBu_r',
               interpolation='nearest')
    plt.colorbar()
    plt.title(atlas + 'correlation matrix')

    # Plot the connectome
    plotting.plot_connectome(corr_matrix, coords,
                             edge_threshold='99.8%', node_size=20,
                             title=atlas + 'correlation connectome')

plotting.show()
    if kind == 'tangent':
        mean_connectivity_matrix[kind] = conn_measure.mean_
    else:
        mean_connectivity_matrix[kind] = \
            individual_connectivity_matrices[kind].mean(axis=0)


######################################################################
# Plot the mean connectome with hemispheric saggital cuts
import numpy as np
from nilearn import plotting
labels = atlas.labels
region_coords = atlas.region_coords
for kind in kinds:
    plotting.plot_connectome(mean_connectivity_matrix[kind],
                             region_coords, edge_threshold='98%',
                             title=kind, display_mode='lzry')


######################################################################
# Use the connectivity coefficients to classify ADHD vs controls
from sklearn.svm import LinearSVC
from sklearn.cross_validation import StratifiedKFold, cross_val_score
classes = ['{0}{1}'.format(site, adhd) for site, adhd in zip(sites, adhds)]
print('Classification accuracy:')
mean_scores = []
cv = StratifiedKFold(classes, n_folds=3)
for kind in kinds:
    svc = LinearSVC()
    # Transform the connectivity matrices to 1D arrays
    coonectivity_coefs = connectome.sym_to_vec(
###############################################################################
# as well as the average correlation across all fitted subjects.
mean_correlation_matrix = correlation_measure.mean_
print('Mean correlation has shape {0}.'.format(mean_correlation_matrix.shape))

###############################################################################
# We display the connectome matrices of the first 4 children
from nilearn import plotting

plot_matrices(correlation_matrices[:4], 'correlation')
###############################################################################
# The blocks structure that reflect functional networks are visible.

###############################################################################
# Now we display as a connectome the mean correlation matrix over all children.
plotting.plot_connectome(mean_correlation_matrix, msdl_coords,
                         title='mean correlation over all children')

###############################################################################
# Studying partial correlations
# -----------------------------
# We can also study **direct connections**, revealed by partial correlation
# coefficients. We just change the `ConnectivityMeasure` kind
partial_correlation_measure = ConnectivityMeasure(kind='partial correlation')

###############################################################################
# and repeat the previous operation.
partial_correlation_matrices = partial_correlation_measure.fit_transform(
    children)

###############################################################################
# Most of direct connections are weaker than full connections,
###############################################################################
# Plot resulting connectomes
# ----------------------------

title = 'Correlation between %d regions' % n_regions_extracted

# First plot the matrix
display = plotting.plot_matrix(mean_correlations, vmax=1, vmin=-1,
                               colorbar=True, title=title)

# Then find the center of the regions and plot a connectome
regions_img = regions_extracted_img
coords_connectome = plotting.find_probabilistic_atlas_cut_coords(regions_img)

plotting.plot_connectome(mean_correlations, coords_connectome,
                         edge_threshold='90%', title=title)

################################################################################
# Plot regions extracted for only one specific network
# ----------------------------------------------------

# First, we plot a network of index=4 without region extraction (left plot)
from nilearn import image

img = image.index_img(components_img, 4)
coords = plotting.find_xyz_cut_coords(img)
display = plotting.plot_stat_map(img, cut_coords=coords, colorbar=False,
                                 title='Showing one specific network')

################################################################################
# Now, we plot (right side) same network after region extraction to show that
for time_serie, label in zip(time_series.T, labels):
    plt.plot(time_serie, label=label)

plt.title("Default Mode Network Time Series")
plt.xlabel("Scan number")
plt.ylabel("Normalized signal")
plt.legend()
plt.tight_layout()


##########################################################################
# Compute precision matrices
from sklearn.covariance import LedoitWolf

cve = LedoitWolf()
cve.fit(time_series)


##########################################################################
# Display connectome
from nilearn import plotting

plotting.plot_connectome(cve.precision_, dmn_coords, title="Default Mode Network Connectivity")

# Display connectome with hemispheric projections.
# Notice (0, -52, 18) is included in both hemispheres since x == 0.
title = "Connectivity projected on hemispheres"
plotting.plot_connectome(cve.precision_, dmn_coords, title=title, display_mode="lyrz")

plotting.show()
             w,a = pairwise_classification(Xp, yp, title=output)
             print groups[i], groups[j], a
             t = np.zeros((len(roi_names), len(roi_names)))
             t[ind] = np.abs(w)
             t = (t + t.T) / 2.
             if msdl:
                 msdl_str = 'msdl'
             else:
                 msdl_str = 'rois'
             output_folder = os.path.join(set_figure_base_dir('classification'),
                                          metric, session, msdl_str)
             if not os.path.isdir(output_folder):
                 os.makedirs(output_folder)
             output_file = os.path.join(output_folder, 'connectome_' + output)
             plot_connectome(t, roi_coords, title=output,
                             output_file=output_file,
                             annotate=True,
                             edge_threshold='0%')
             
 
     # 1 vs rest
     for i in range(3):
         gr_i = dataset.group_indices[groups[i]]
         yr = np.zeros(X.shape[0])
         yr[gr_i] = 1
         output = '_'.join([groups[i] + '_rest', metric, session, msdl_str,
                            preprocessing_folder])
         plt.figure()
         w, a = pairwise_classification(X, yr, title=output)
 
         print groups[i] + '_rest', a
         if np.sum(w) == 0:
###############################################################################
# Extract and plot correlation matrix

# calculate connectivity and plot Power-264 correlation matrix
connectivity = connectome.ConnectivityMeasure(kind='correlation')
corr_matrix = connectivity.fit_transform([timeseries])[0]
np.fill_diagonal(corr_matrix, 0)
plt.imshow(corr_matrix, vmin=-1., vmax=1., cmap='RdBu_r')
plt.colorbar()
plt.title('Power 264 Connectivity')

# Plot the connectome

plotting.plot_connectome(corr_matrix,
                         power_coords,
                         edge_threshold='99.8%',
                         node_size=20)


###############################################################################
# Extract and plot covariance and sparse covariance

# Compute the sparse inverse covariance
from sklearn.covariance import GraphLassoCV

estimator = GraphLassoCV()
estimator.fit(timeseries)

# Display the covariance
plt.figure(figsize=(5, 5))
plt.imshow(estimator.covariance_, interpolation="nearest",
Example #50
0
plt.tight_layout()


##########################################################################
# Compute partial correlation matrix
# -----------------------------------
# Using object :class:`nilearn.connectome.ConnectivityMeasure`: Its
# default covariance estimator is Ledoit-Wolf, allowing to obtain accurate
# partial correlations.
from nilearn.connectome import ConnectivityMeasure
connectivity_measure = ConnectivityMeasure(kind='partial correlation')
partial_correlation_matrix = connectivity_measure.fit_transform(
    [time_series])[0]

##########################################################################
# Display connectome
# -------------------
from nilearn import plotting

plotting.plot_connectome(partial_correlation_matrix, dmn_coords,
                         title="Default Mode Network Connectivity")

##########################################################################
# Display connectome with hemispheric projections.
# Notice (0, -52, 18) is included in both hemispheres since x == 0.
plotting.plot_connectome(partial_correlation_matrix, dmn_coords,
                         title="Connectivity projected on hemispheres",
                         display_mode='lyrz')

plotting.show()
Example #51
0
for func, confounds in zip(data.func, data.confounds):
    time_series.append(masker.fit_transform(func, confounds=confounds))

# calculate correlation matrices across subjects and display
correlation_matrices = connectome_measure.fit_transform(time_series)

# Mean correlation matrix across 10 subjects can be grabbed like this,
# using connectome measure object
mean_correlation_matrix = connectome_measure.mean_

# grab center coordinates for atlas labels
coordinates = plotting.find_parcellation_cut_coords(labels_img=yeo['thick_17'])

# plot connectome with 80% edge strength in the connectivity
plotting.plot_connectome(mean_correlation_matrix, coordinates,
                         edge_threshold="80%",
                         title='Yeo Atlas 17 thick (func)')

##########################################################################
# Load probabilistic atlases - extracting coordinates on brain maps
# -----------------------------------------------------------------

msdl = datasets.fetch_atlas_msdl()

##########################################################################
# Iterate over fetched atlases to extract coordinates - probabilistic
# -------------------------------------------------------------------
from nilearn.input_data import NiftiMapsMasker

# create masker to extract functional data within atlas parcels
masker = NiftiMapsMasker(maps_img=msdl['maps'], standardize=True,
    def plot_cluster_stats(self, cluster_name):
        """
        Multi panel plot showing:

        1. brain map of electrodes in the cluster, color-coded by phase
        2. brain map of electrodes in the cluster, color-coded by subsequent memory effect
        3. timecourse of resultant vector length of wave direction, averaged across trials
        4. timecourse of r^2, averaged across trials
        5. polor plot of left-frontal and hippocampal electrode phases
        6/7. same as 5, but for recalled and not recalled items only

        Data are taken from the timepoint with the highest r-square value.

        Figure creation code is so ugly sorry.
        """

        ############################
        # GET TIME TIME FOR X-AXIS #
        ############################
        time_axis = self.res['traveling_waves'][cluster_name]['time']

        #####################
        # SET UP THE FIGURE #
        #####################
        gs = gridspec.GridSpec(6, 3)
        ax1 = plt.subplot(gs[0, :])
        ax2 = plt.subplot(gs[2, :])
        ax3 = plt.subplot(gs[3, :])
        ax4 = plt.subplot(gs[4, 0], projection='polar')
        ax6 = plt.subplot(gs[4, 1], projection='polar')
        ax7 = plt.subplot(gs[4, 2], projection='polar')
        ax8 = plt.subplot(gs[5, 0], projection='polar')
        ax9 = plt.subplot(gs[5, 1], projection='polar')
        ax10 = plt.subplot(gs[5, 2], projection='polar')
        ax5 = plt.subplot(gs[1, :])

        # some figure parameters
        fig = plt.gcf()
        fig.set_size_inches(15, 30)
        mpl.rcParams['xtick.labelsize'] = 18
        mpl.rcParams['ytick.labelsize'] = 18

        #############################################
        # INFO ABOUT THE ELECTRODES IN THIS CLUSTER #
        #############################################
        cluster_rows = self.res['clusters'][cluster_name].notna()
        regions_all = self.get_electrode_roi_by_hemi()
        regions = regions_all[cluster_rows]['merged_col'].unique()
        regions_str = ', '.join(regions)
        xyz = self.res['clusters'][cluster_rows][['x', 'y', 'z']].values

        ###############################
        # ROW 1: electrodes and phase #
        ###############################
        mean_r2 = np.nanmean(self.res['traveling_waves'][cluster_name]['cluster_r2_adj'], axis=1)
        argmax_r2 = np.argmax(mean_r2)
        print(argmax_r2)
        phases = self.res['traveling_waves'][cluster_name]['phase_data'][:, argmax_r2]
        #     phases = (phases + np.pi) % (2 * np.pi) - np.pi
        #     phases[phases<0] += np.pi*2
        #     phases *= 180. / np.pi
        #     phases -= phases.min() - 1
        colors = np.stack([[0., 0., 0., 0.]] * len(phases))
        cm = clrs.LinearSegmentedColormap.from_list('cm', cc.cyclic_mrybm_35_75_c68_s25)
        cNorm = clrs.Normalize(vmin=0, vmax=np.pi * 2)
        colors[~np.isnan(phases)] = cmx.ScalarMappable(norm=cNorm, cmap=cm).to_rgba(phases[~np.isnan(phases)])
        ni_plot.plot_connectome(np.eye(xyz.shape[0]), xyz,
                                node_kwargs={'alpha': 0.7, 'edgecolors': None},
                                node_size=45, node_color=colors, display_mode='lzr',
                                axes=ax1)
        mean_freq = self.res['traveling_waves'][cluster_name]['mean_freq']
        plt.suptitle('{0} ({1:.2f} Hz): {2}'.format(self.subject, mean_freq, regions_str), y=.9)
        divider = make_axes_locatable(ax1)
        cax = divider.append_axes('right', size='6%', pad=15)
        cb1 = mpl.colorbar.ColorbarBase(cax, cmap=cm,
                                        norm=cNorm,
                                        orientation='vertical', ticks=[0, np.pi / 2, np.pi, np.pi * 3 / 2, np.pi * 2])
        cb1.ax.yaxis.set_ticklabels(['0°', '90°', '180°', '270°', '360°'])
        cb1.ax.tick_params(labelsize=14)
        for label in cb1.ax.yaxis.get_majorticklabels():
            label.set_transform(label.get_transform() + mpl.transforms.ScaledTranslation(0.15, 0, fig.dpi_scale_trans))

        ##################################################
        # ROW 2: electrodes and subsequent memory effect #
        ##################################################
        sme = self.res['traveling_waves'][cluster_name]['sme_t'][:, argmax_r2]
        colors = np.stack([[0., 0., 0., 0.]] * len(sme))
        cm = plt.get_cmap('RdBu_r')
        clim = np.max(np.abs(sme))
        cNorm = clrs.Normalize(vmin=-clim, vmax=clim)
        colors[~np.isnan(sme)] = cmx.ScalarMappable(norm=cNorm, cmap=cm).to_rgba(sme[~np.isnan(sme)])
        ni_plot.plot_connectome(np.eye(xyz.shape[0]), xyz,
                                node_kwargs={'alpha': 0.7, 'edgecolors': None},
                                node_size=45, node_color=colors, display_mode='lzr',
                                axes=ax5)
        divider = make_axes_locatable(ax5)
        cax = divider.append_axes('right', size='6%', pad=15)
        cb2 = mpl.colorbar.ColorbarBase(cax, cmap='RdBu_r',
                                        norm=cNorm,
                                        orientation='vertical')
        cb2.ax.tick_params(labelsize=14)
        for label in cb2.ax.yaxis.get_majorticklabels():
            label.set_transform(label.get_transform() + mpl.transforms.ScaledTranslation(0.15, 0, fig.dpi_scale_trans))

        ############################
        # ROW 3: timecourse of RVL #
        ############################
        rvl = pycircstat.resultant_vector_length(self.res['traveling_waves'][cluster_name]['cluster_wave_ang'], axis=1)
        ax2.plot(time_axis, rvl, lw=2)
        ax2.set_ylabel('RVL', fontsize=20)

        ##################################
        # ROW 4: timecourse of r-squared #
        ##################################
        ax3.plot(time_axis, np.nanmean(self.res['traveling_waves'][cluster_name]['cluster_r2_adj'], axis=1), lw=2)
        ax3.set_xlabel('Time (ms)', fontsize=20)
        ax3.set_ylabel('mean($R^{2}$)', fontsize=20)

        ############################
        # ROW 5a: phase polar plots #
        ############################
        #     phases = np.deg2rad(phases)
        cluster_regions = regions_all[cluster_rows]['merged_col']
        phases_left_front = phases[cluster_regions == 'left-Frontal']
        phases_hipp = phases[(cluster_regions == 'left-Hipp') | (cluster_regions == 'right-Hipp')]
        phases_other = phases[~cluster_regions.isin(['left-Frontal', 'left-Hipp', 'right-Hipp'])]

        for this_phase in phases_left_front:
            ax4.plot([this_phase, this_phase], [0, 1], lw=3, c='#67a9cf', alpha=.5)
        for this_phase in phases_hipp:
            ax4.plot([this_phase, this_phase], [0, 1], lw=3, c='#ef8a62', alpha=.5)
        for this_phase in phases_other:
            ax4.plot([this_phase, this_phase], [0, .7], lw=2, c='k', alpha=.4, zorder=-1)
        ax4.grid()
        for r in np.linspace(0, 2 * np.pi, 5)[:-1]:
            ax4.plot([r, r], [0, 1.3], lw=1, c=[.7, .7, .7], zorder=-2)
        ax4.spines['polar'].set_visible(False)
        ax4.set_ylim(0, 1.3)
        ax4.set_yticklabels([])
        ax4.set_aspect('equal', 'box')
        red_patch = mpatches.Patch(color='#67a9cf', label='L. Frontal')
        blue_patch = mpatches.Patch(color='#ef8a62', label='Hipp')
        _ = ax4.legend(handles=[red_patch, blue_patch], loc='lower left', bbox_to_anchor=(0.9, 0.9),
                       frameon=False, fontsize=16)

        ################################################
        # ROW 5b: phase polar plots for recalled items #
        ################################################
        phases = self.res['traveling_waves'][cluster_name]['phase_data_recalled'][:, argmax_r2]
        #     phases = (phases + np.pi) % (2 * np.pi) - np.pi
        #     phases *= 180. / np.pi
        #     phases -= phases.min() - 1
        #     phases = np.deg2rad(phases)
        phases_left_front = phases[cluster_regions == 'left-Frontal']
        phases_hipp = phases[(cluster_regions == 'left-Hipp') | (cluster_regions == 'right-Hipp')]
        phases_other = phases[~cluster_regions.isin(['left-Frontal', 'left-Hipp', 'right-Hipp'])]

        for this_phase in phases_left_front:
            ax6.plot([this_phase, this_phase], [0, 1], lw=3, c='#67a9cf', alpha=.5)
        for this_phase in phases_hipp:
            ax6.plot([this_phase, this_phase], [0, 1], lw=3, c='#ef8a62', alpha=.5)
        for this_phase in phases_other:
            ax6.plot([this_phase, this_phase], [0, .7], lw=2, c='k', alpha=.4, zorder=-1)
        ax6.grid()
        for r in np.linspace(0, 2 * np.pi, 5)[:-1]:
            ax6.plot([r, r], [0, 1.3], lw=1, c=[.7, .7, .7], zorder=-2)
        ax6.spines['polar'].set_visible(False)
        ax6.set_ylim(0, 1.3)
        ax6.set_yticklabels([])
        ax6.set_aspect('equal', 'box')
        ax6.set_title('Recalled items', y=1.12)

        ####################################################
        # ROW 5c: phase polar plots for not recalled items #
        ####################################################
        phases = self.res['traveling_waves'][cluster_name]['phase_data_not_recalled'][:, argmax_r2]
        #     phases = (phases + np.pi) % (2 * np.pi) - np.pi
        #     phases *= 180. / np.pi
        #     phases -= phases.min() - 1
        #     phases = np.deg2rad(phases)
        phases_left_front = phases[cluster_regions == 'left-Frontal']
        phases_hipp = phases[(cluster_regions == 'left-Hipp') | (cluster_regions == 'right-Hipp')]
        phases_other = phases[~cluster_regions.isin(['left-Frontal', 'left-Hipp', 'right-Hipp'])]

        for this_phase in phases_left_front:
            ax7.plot([this_phase, this_phase], [0, 1], lw=3, c='#67a9cf', alpha=.5)
        for this_phase in phases_hipp:
            ax7.plot([this_phase, this_phase], [0, 1], lw=3, c='#ef8a62', alpha=.5)
        for this_phase in phases_other:
            ax7.plot([this_phase, this_phase], [0, .7], lw=2, c='k', alpha=.4, zorder=-1)
        ax7.grid()
        for r in np.linspace(0, 2 * np.pi, 5)[:-1]:
            ax7.plot([r, r], [0, 1.3], lw=1, c=[.7, .7, .7], zorder=-2)
        ax7.spines['polar'].set_visible(False)
        ax7.set_ylim(0, 1.3)
        ax7.set_yticklabels([])
        ax7.set_aspect('equal', 'box')
        ax7.set_title('Not recalled items', y=1.12)

        ####################################################
        # ROW 6:
        ####################################################
        recalled = self.res['traveling_waves']['cluster1']['recalled']
        if ('left-Frontal' in self.res['traveling_waves'][cluster_name]['phase_by_roi']) & \
                ('both-Hipp' in self.res['traveling_waves'][cluster_name]['phase_by_roi']):

            phase_by_roi = self.res['traveling_waves'][cluster_name]['phase_by_roi']

            phase_left_front_roi = phase_by_roi['left-Frontal'][:, argmax_r2]
            #         phase_left_front_roi = (phase_left_front_roi + np.pi) % (2 * np.pi)
            phase_hipp_roi = phase_by_roi['both-Hipp'][:, argmax_r2]
            #         phase_hipp_roi = (phase_hipp_roi + np.pi) % (2 * np.pi)
            #         phase_left_front_roi = (phase_left_front_roi + np.pi) % (2 * np.pi) - np.pi
            #         phase_left_front_roi *= 180. / np.pi
            #         phase_left_front_roi -= phase_left_front_roi.min() - 1
            #         phase_left_front_roi = np.deg2rad(phase_left_front_roi)
            #         phase_hipp_roi = (phase_hipp_roi + np.pi) % (2 * np.pi) - np.pi
            #         phase_hipp_roi *= 180. / np.pi
            #         phase_hipp_roi -= phase_hipp_roi.min() - 1
            #         phase_hipp_roi = np.deg2rad(phase_hipp_roi)

            # LEFT
            ax8 = self.rose_plot(phase_left_front_roi, n_bins=30, ax=ax8)
            ax8 = self.rose_plot(phase_hipp_roi, n_bins=30, ax=ax8)
            ax8.spines['polar'].set_visible(False)
            ax8.set_yticks([ax8.get_ylim()[1]])
            ax8.set_aspect('equal', 'box')
            ax8.tick_params(axis='y', colors=[.7, .7, .7])
            for r in np.linspace(0, 2 * np.pi, 5)[:-1]:
                ax8.plot([r, r], [0, ax8.get_ylim()[1]], lw=1, c=[.7, .7, .7], zorder=-2)
            ax8.grid()

            # MIDDLE
            ax9 = self.rose_plot(phase_left_front_roi[recalled], n_bins=30, ax=ax9)
            ax9 = self.rose_plot(phase_hipp_roi[recalled], n_bins=30, ax=ax9)
            ax9.spines['polar'].set_visible(False)
            ax9.set_yticks([ax9.get_ylim()[1]])
            ax9.set_aspect('equal', 'box')
            ax9.tick_params(axis='y', colors=[.7, .7, .7])
            for r in np.linspace(0, 2 * np.pi, 5)[:-1]:
                ax9.plot([r, r], [0, ax9.get_ylim()[1]], lw=1, c=[.7, .7, .7], zorder=-2)
            ax9.grid()

            # RIGHT
            ax10 = self.rose_plot(phase_left_front_roi[~recalled], n_bins=30, ax=ax10)
            ax10 = self.rose_plot(phase_hipp_roi[~recalled], n_bins=30, ax=ax10)
            ax10.spines['polar'].set_visible(False)
            ax10.set_yticks([ax10.get_ylim()[1]])
            ax10.set_aspect('equal', 'box')
            ax10.tick_params(axis='y', colors=[.7, .7, .7])
            for r in np.linspace(0, 2 * np.pi, 5)[:-1]:
                ax10.plot([r, r], [0, ax10.get_ylim()[1]], lw=1, c=[.7, .7, .7], zorder=-2)
            ax10.grid()

        plt.subplots_adjust(hspace=.5)
        return fig
Example #53
0
func_filename = adhd_dataset.func[0]
confound_filename = adhd_dataset.confounds[0]

time_series = masker.fit_transform(func_filename,
                                   confounds=[confound_filename])


# Computing precision matrices ################################################
from sklearn.covariance import LedoitWolf
cve = LedoitWolf()
cve.fit(time_series)

# Displaying results ##########################################################
import matplotlib.pyplot as plt
from nilearn import plotting

# Display time series
for time_serie, label in zip(time_series.T, labels):
    plt.plot(time_serie, label=label)

plt.title('Default Mode Network Time Series')
plt.xlabel('Scan number')
plt.ylabel('Normalized signal')
plt.legend()
plt.tight_layout()

# Display connectome
title = "Default Mode Network Connectivity"
plotting.plot_connectome(cve.precision_, dmn_coords, title=title)
plotting.show()
############################################################################
# Build and display a correlation matrix
from nilearn.connectome import ConnectivityMeasure
correlation_measure = ConnectivityMeasure(kind='correlation')
correlation_matrix = correlation_measure.fit_transform([time_series])[0]

# Display the correlation matrix
import numpy as np
from matplotlib import pyplot as plt
plt.figure(figsize=(10, 10))
# Mask out the major diagonal
np.fill_diagonal(correlation_matrix, 0)
plt.imshow(correlation_matrix, interpolation="nearest", cmap="RdBu_r",
           vmax=0.8, vmin=-0.8)
plt.colorbar()
# And display the labels
x_ticks = plt.xticks(range(len(labels)), labels, rotation=90)
y_ticks = plt.yticks(range(len(labels)), labels)

############################################################################
# And now display the corresponding graph
from nilearn import plotting
coords = atlas.region_coords

# We threshold to keep only the 20% of edges with the highest value
# because the graph is very dense
plotting.plot_connectome(correlation_matrix, coords,
                         edge_threshold="80%", colorbar=True)

plotting.show()
comp_list=partperm(func_type_list)
     
with backend_pdf.PdfPages(save_report) as pdf:
    for g_index in range(len(func_type_list)+1):    
        pdf.savefig(at_check[g_index])
        plt.close()
    #tstats for comparison of metrics  accross groups
    for kind in kinds:
        print('saving report: '+kind)
        for func_type in func_type_list :
            #average across all subjects            
            Mean_mat = mean_connectivity_matrix[func_type][kind]
            Mean_tot = np.mean(Mean_mat)            
            #plot connectomes                    
            plotting.plot_connectome(Mean_mat, coords,title= func_type +' '+ kind+' connectome',edge_threshold='90%')                                
            pdf.savefig()    
            plt.close()            
            if kind in ['correlation','partial correlation']:
                span = [-1,1]
            else:
                m_span = np.max(np.abs(Mean_mat))                
                span = [-m_span,m_span]
            plot_matrices(Mean_mat,span ,rois, 'Average '+func_type + ' ' + kind+ ' across subjects\nTotal average for '+kind+' = '+str(Mean_tot) ,colmap ="bwr",labelsize=l)                   
            pdf.savefig()
            plt.close()
            
        for comp in comps :
            paired = Paired
            if kind in ['correlation', 'partial correlation']:
                # Z-Fisher transform
time_series = masker.fit_transform(func_filename,
                                   confounds=[confound_filename])

##########################################################################
# Display time series
import matplotlib.pyplot as plt
for time_serie, label in zip(time_series.T, labels):
    plt.plot(time_serie, label=label)

plt.title('Default Mode Network Time Series')
plt.xlabel('Scan number')
plt.ylabel('Normalized signal')
plt.legend()
plt.tight_layout()


##########################################################################
# Compute precision matrices
from sklearn.covariance import LedoitWolf
cve = LedoitWolf()
cve.fit(time_series)


##########################################################################
# Display connectome
from nilearn import plotting

plotting.plot_connectome(cve.precision_, dmn_coords,
                         title="Default Mode Network Connectivity")
plotting.show()
masker = NiftiMapsMasker(maps_img=atlas_filename, standardize=True,
                           memory='nilearn_cache', verbose=5)

data = datasets.fetch_adhd(n_subjects=1)

time_series = masker.fit_transform(data.func[0],
                                   confounds=data.confounds)

correlation_matrix = np.corrcoef(time_series.T)

# Display the correlation matrix
from matplotlib import pyplot as plt
plt.figure(figsize=(10, 10))
plt.imshow(correlation_matrix, interpolation="nearest")
# And display the labels
x_ticks = plt.xticks(range(len(names)), names, rotation=90)
y_ticks = plt.yticks(range(len(names)), names)

# And now display the corresponding graph
from nilearn import plotting
coords = np.vstack((labels['x'], labels['y'], labels['z']))

# We threshold to keep only the 20% of edges with the highest value
# because the graph is very dense
plotting.plot_connectome(correlation_matrix, coords.T,
                         edge_threshold="80%")

plt.show()


confound_filename = adhd_dataset.confounds[0]

# Computing some confounds
hv_confounds = mem.cache(nilearn.image.high_variance_confounds)(
    fmri_filename)

time_series = masker.transform(fmri_filename,
                                confounds=[hv_confounds, confound_filename])


print("-- Computing graph-lasso inverse matrix ...")
from sklearn import covariance
gl = covariance.GraphLassoCV(verbose=2)
gl.fit(time_series)

# Displaying results ##########################################################
atlas_imgs = image.iter_img(msdl_atlas_dataset.maps)
atlas_region_coords = [plotting.find_xyz_cut_coords(img) for img in atlas_imgs]

title = "GraphLasso"
plotting.plot_connectome(-gl.precision_, atlas_region_coords,
                         edge_threshold='90%',
                         title="Sparse inverse covariance")
plotting.plot_connectome(gl.covariance_,
                         atlas_region_coords, edge_threshold='90%',
                         title="Covariance")
plot_matrices(gl.covariance_, gl.precision_, title)


plt.show()
roi_names, roi_coords = load_msdl_names_and_coords()
stat_av = read_test('pc', 'av', 'avg')
stat_v = read_test('pc', 'v', 'avg')
stat2 = read_test2('pc', ['av', 'v'], 'avg')


i, j = np.unravel_index(stat2.argmax(), stat2.shape)
print 'av 1sample pval :', stat_av[i, j]
print 'v 1sample pval :', stat_v[i, j]
print roi_names[i], roi_names[j]
print i, j

m = np.eye(2)
m[1,0] = stat2[i, j]
m[0,1] = m[1,0] 
plot_connectome(m, [roi_coords[i], roi_coords[j]])


conn = []
behav = []
for i in range(len(dataset.subjects)):
    c = load_dynacomp_fc(dataset.subjects[i], session='func1', metric='pc', msdl=True)
    conn.append(c[i, j])
    b = behav_data[i]['postRT'] - behav_data[i]['preRT']
    behav.append(b)

sns.jointplot(np.array(conn), np.array(behav), kind='kde')
sns.axlabel('Connectivity', 'Behavior')