def test_plot_connectivity_circle():
    """Test plotting connectivity circle
    """
    node_order = ['frontalpole-lh', 'parsorbitalis-lh', 'lateralorbitofrontal-lh', 'rostralmiddlefrontal-lh', 'medialorbitofrontal-lh', 'parstriangularis-lh', 'rostralanteriorcingulate-lh', 'temporalpole-lh', 'parsopercularis-lh', 'caudalanteriorcingulate-lh', 'entorhinal-lh', 'superiorfrontal-lh', 'insula-lh', 'caudalmiddlefrontal-lh', 'superiortemporal-lh', 'parahippocampal-lh', 'middletemporal-lh', 'inferiortemporal-lh', 'precentral-lh', 'transversetemporal-lh', 'posteriorcingulate-lh', 'fusiform-lh', 'postcentral-lh', 'bankssts-lh', 'supramarginal-lh', 'isthmuscingulate-lh', 'paracentral-lh', 'lingual-lh', 'precuneus-lh', 'inferiorparietal-lh', 'superiorparietal-lh', 'pericalcarine-lh', 'lateraloccipital-lh', 'cuneus-lh', 'cuneus-rh', 'lateraloccipital-rh', 'pericalcarine-rh', 'superiorparietal-rh', 'inferiorparietal-rh', 'precuneus-rh', 'lingual-rh', 'paracentral-rh', 'isthmuscingulate-rh', 'supramarginal-rh', 'bankssts-rh', 'postcentral-rh', 'fusiform-rh', 'posteriorcingulate-rh', 'transversetemporal-rh', 'precentral-rh', 'inferiortemporal-rh', 'middletemporal-rh', 'parahippocampal-rh', 'superiortemporal-rh', 'caudalmiddlefrontal-rh', 'insula-rh', 'superiorfrontal-rh', 'entorhinal-rh', 'caudalanteriorcingulate-rh', 'parsopercularis-rh', 'temporalpole-rh', 'rostralanteriorcingulate-rh', 'parstriangularis-rh', 'medialorbitofrontal-rh', 'rostralmiddlefrontal-rh', 'lateralorbitofrontal-rh', 'parsorbitalis-rh', 'frontalpole-rh']
    label_names = ['bankssts-lh', 'bankssts-rh', 'caudalanteriorcingulate-lh', 'caudalanteriorcingulate-rh', 'caudalmiddlefrontal-lh', 'caudalmiddlefrontal-rh', 'cuneus-lh', 'cuneus-rh', 'entorhinal-lh', 'entorhinal-rh', 'frontalpole-lh', 'frontalpole-rh', 'fusiform-lh', 'fusiform-rh', 'inferiorparietal-lh', 'inferiorparietal-rh', 'inferiortemporal-lh', 'inferiortemporal-rh', 'insula-lh', 'insula-rh', 'isthmuscingulate-lh', 'isthmuscingulate-rh', 'lateraloccipital-lh', 'lateraloccipital-rh', 'lateralorbitofrontal-lh', 'lateralorbitofrontal-rh', 'lingual-lh', 'lingual-rh', 'medialorbitofrontal-lh', 'medialorbitofrontal-rh', 'middletemporal-lh', 'middletemporal-rh', 'paracentral-lh', 'paracentral-rh', 'parahippocampal-lh', 'parahippocampal-rh', 'parsopercularis-lh', 'parsopercularis-rh', 'parsorbitalis-lh', 'parsorbitalis-rh', 'parstriangularis-lh', 'parstriangularis-rh', 'pericalcarine-lh', 'pericalcarine-rh', 'postcentral-lh', 'postcentral-rh', 'posteriorcingulate-lh', 'posteriorcingulate-rh', 'precentral-lh', 'precentral-rh', 'precuneus-lh', 'precuneus-rh', 'rostralanteriorcingulate-lh', 'rostralanteriorcingulate-rh', 'rostralmiddlefrontal-lh', 'rostralmiddlefrontal-rh', 'superiorfrontal-lh', 'superiorfrontal-rh', 'superiorparietal-lh', 'superiorparietal-rh', 'superiortemporal-lh', 'superiortemporal-rh', 'supramarginal-lh', 'supramarginal-rh', 'temporalpole-lh', 'temporalpole-rh', 'transversetemporal-lh', 'transversetemporal-rh']
    node_angles = circular_layout(label_names, node_order, start_pos=90)
    con = np.random.randn(68, 68)
    plot_connectivity_circle(con, label_names, n_lines=300,
                             node_angles=node_angles, title='test')
Beispiel #2
0
def test_plot_connectivity_circle():
    """Test plotting connectivity circle
    """
    node_order = [
        'frontalpole-lh', 'parsorbitalis-lh', 'lateralorbitofrontal-lh',
        'rostralmiddlefrontal-lh', 'medialorbitofrontal-lh',
        'parstriangularis-lh', 'rostralanteriorcingulate-lh',
        'temporalpole-lh', 'parsopercularis-lh', 'caudalanteriorcingulate-lh',
        'entorhinal-lh', 'superiorfrontal-lh', 'insula-lh',
        'caudalmiddlefrontal-lh', 'superiortemporal-lh', 'parahippocampal-lh',
        'middletemporal-lh', 'inferiortemporal-lh', 'precentral-lh',
        'transversetemporal-lh', 'posteriorcingulate-lh', 'fusiform-lh',
        'postcentral-lh', 'bankssts-lh', 'supramarginal-lh',
        'isthmuscingulate-lh', 'paracentral-lh', 'lingual-lh', 'precuneus-lh',
        'inferiorparietal-lh', 'superiorparietal-lh', 'pericalcarine-lh',
        'lateraloccipital-lh', 'cuneus-lh', 'cuneus-rh', 'lateraloccipital-rh',
        'pericalcarine-rh', 'superiorparietal-rh', 'inferiorparietal-rh',
        'precuneus-rh', 'lingual-rh', 'paracentral-rh', 'isthmuscingulate-rh',
        'supramarginal-rh', 'bankssts-rh', 'postcentral-rh', 'fusiform-rh',
        'posteriorcingulate-rh', 'transversetemporal-rh', 'precentral-rh',
        'inferiortemporal-rh', 'middletemporal-rh', 'parahippocampal-rh',
        'superiortemporal-rh', 'caudalmiddlefrontal-rh', 'insula-rh',
        'superiorfrontal-rh', 'entorhinal-rh', 'caudalanteriorcingulate-rh',
        'parsopercularis-rh', 'temporalpole-rh', 'rostralanteriorcingulate-rh',
        'parstriangularis-rh', 'medialorbitofrontal-rh',
        'rostralmiddlefrontal-rh', 'lateralorbitofrontal-rh',
        'parsorbitalis-rh', 'frontalpole-rh'
    ]
    label_names = [
        'bankssts-lh', 'bankssts-rh', 'caudalanteriorcingulate-lh',
        'caudalanteriorcingulate-rh', 'caudalmiddlefrontal-lh',
        'caudalmiddlefrontal-rh', 'cuneus-lh', 'cuneus-rh', 'entorhinal-lh',
        'entorhinal-rh', 'frontalpole-lh', 'frontalpole-rh', 'fusiform-lh',
        'fusiform-rh', 'inferiorparietal-lh', 'inferiorparietal-rh',
        'inferiortemporal-lh', 'inferiortemporal-rh', 'insula-lh', 'insula-rh',
        'isthmuscingulate-lh', 'isthmuscingulate-rh', 'lateraloccipital-lh',
        'lateraloccipital-rh', 'lateralorbitofrontal-lh',
        'lateralorbitofrontal-rh', 'lingual-lh', 'lingual-rh',
        'medialorbitofrontal-lh', 'medialorbitofrontal-rh',
        'middletemporal-lh', 'middletemporal-rh', 'paracentral-lh',
        'paracentral-rh', 'parahippocampal-lh', 'parahippocampal-rh',
        'parsopercularis-lh', 'parsopercularis-rh', 'parsorbitalis-lh',
        'parsorbitalis-rh', 'parstriangularis-lh', 'parstriangularis-rh',
        'pericalcarine-lh', 'pericalcarine-rh', 'postcentral-lh',
        'postcentral-rh', 'posteriorcingulate-lh', 'posteriorcingulate-rh',
        'precentral-lh', 'precentral-rh', 'precuneus-lh', 'precuneus-rh',
        'rostralanteriorcingulate-lh', 'rostralanteriorcingulate-rh',
        'rostralmiddlefrontal-lh', 'rostralmiddlefrontal-rh',
        'superiorfrontal-lh', 'superiorfrontal-rh', 'superiorparietal-lh',
        'superiorparietal-rh', 'superiortemporal-lh', 'superiortemporal-rh',
        'supramarginal-lh', 'supramarginal-rh', 'temporalpole-lh',
        'temporalpole-rh', 'transversetemporal-lh', 'transversetemporal-rh'
    ]
    node_angles = circular_layout(label_names, node_order, start_pos=90)
    con = np.random.randn(68, 68)
    plot_connectivity_circle(con,
                             label_names,
                             n_lines=300,
                             node_angles=node_angles,
                             title='test')
Beispiel #3
0
    def _run_interface(self, runtime):
        from nilearn.input_data import NiftiLabelsMasker
        from nilearn.connectome import ConnectivityMeasure
        from sklearn.covariance import EmpiricalCovariance
        import numpy as np
        import pandas as pd
        import os
        import matplotlib.pyplot as plt
        from mne.viz import plot_connectivity_circle
        import re

        plt.switch_backend('Agg')

        # extract timeseries from every label
        masker = NiftiLabelsMasker(labels_img=self.inputs.atlas_file,
                                   standardize=True, verbose=1)
        timeseries = masker.fit_transform(self.inputs.timeseries_file)
        # create correlation matrix
        correlation_measure = ConnectivityMeasure(cov_estimator=EmpiricalCovariance(),
                                                  kind="correlation")
        correlation_matrix = correlation_measure.fit_transform([timeseries])[0]
        np.fill_diagonal(correlation_matrix, np.NaN)

        # add the atlas labels to the matrix
        atlas_lut_df = pd.read_csv(self.inputs.atlas_lut, sep='\t')
        regions = atlas_lut_df['regions'].values
        correlation_matrix_df = pd.DataFrame(correlation_matrix, index=regions, columns=regions)

        # do a fisher's r -> z transform
        fisher_z_matrix_df = correlation_matrix_df.apply(lambda x: (np.log(1 + x) - np.log(1 - x)) * 0.5)

        # write out the file.
        out_file = os.path.join(runtime.cwd, 'fisher_z_correlation.tsv')
        fisher_z_matrix_df.to_csv(out_file, sep='\t', na_rep='n/a')

        # save the filename in the outputs
        self._results['correlation_matrix'] = out_file

        # visualizations with mne
        connmat = fisher_z_matrix_df.values
        labels = list(fisher_z_matrix_df.index)

        # define title and outfile names:
        trial_regex = re.compile(r'.*trialtype-(?P<trial>[A-Za-z0-9]+)')
        title = re.search(trial_regex, self.inputs.timeseries_file).groupdict()['trial']
        outfile = os.path.join(runtime.cwd, ".".join([title, "svg"]))

        n_lines = int(np.sum(connmat > 0) / 2)
        fig = plt.figure(figsize=(5, 5))

        plot_connectivity_circle(connmat, labels, n_lines=n_lines, fig=fig, title=title, fontsize_title=10,
                                 facecolor='white', textcolor='black', colormap='jet', colorbar=1,
                                 node_colors=['black'], node_edgecolor=['white'], show=False, interactive=False)

        fig.savefig(outfile, dpi=300)
        self._results['correlation_fig'] = outfile

        return runtime
Beispiel #4
0
def plot_circular_connectivity(conmat, label_names, node_colors, node_order, vmin = 0.3, vmax = 1.0, nb_lines = 200, fname = "_def"):
    import os
    import numpy as np
    from mne.viz import circular_layout, plot_connectivity_circle
    import matplotlib.pyplot as plt

    # Angles
    node_angles = circular_layout(label_names, node_order, start_pos=90,
                                group_boundaries=[0, len(label_names) / 2])

    # Plot the graph using node colors from the FreeSurfer parcellation. We only
    # show the 300 strongest connections.
    fig,_ = plot_connectivity_circle(conmat, 
                                     label_names, 
                                     n_lines=nb_lines,  
                                     node_angles=node_angles, 
                                     node_colors = node_colors,
                                     fontsize_names = 12, 
                                     title='All-to-All Connectivity' , 
                                     show = False, 
                                     vmin = vmin, 
                                     vmax = vmax)
    
    
    #plot_conmat_file = os.path.abspath('circle.png')
    plot_conmat_file = os.path.abspath('circle_' + fname + '.eps')
    fig.savefig(plot_conmat_file, facecolor='black')
    
    
    plt.close(fig)
    #fig1.close()
    del fig
    
    return plot_conmat_file
Beispiel #5
0
def _plot_circular_connectivity(conmat,
                                label_names,
                                node_colors=None,
                                node_order=[],
                                vmin=0.3,
                                vmax=1.0,
                                nb_lines=200,
                                fname="_def",
                                save_dir=None):
    """Plot circular connectivity."""
    import matplotlib.pyplot as plt

    assert len(conmat.shape) == 2, "Error, conmat should be 2D matrix"
    assert conmat.shape[0] == conmat.shape[1], "Error, conmat should squared"
    assert conmat.shape[0] == len(label_names), "Error, conmat and labels\
        should have same length {} != {}".format(conmat.shape[0],
                                                 len(label_names))

    # if not defined, use label_names
    if len(node_order) == 0:
        node_order = label_names

    # Angles
    node_angles = circular_layout(label_names,
                                  node_order,
                                  start_pos=90,
                                  group_boundaries=[0, len(label_names) / 2])

    # necessary to have symetric matrix
    conmat = conmat + np.transpose(conmat)

    # Plot the graph
    fig, _ = plot_connectivity_circle(conmat,
                                      label_names,
                                      n_lines=nb_lines,
                                      node_angles=node_angles.astype(int),
                                      node_colors=None,
                                      fontsize_names=12,
                                      title='All-to-All Connectivity',
                                      show=False,
                                      vmin=vmin,
                                      vmax=vmax)

    # saving circle file
    if save_dir is not None:
        assert os.path.exists(save_dir), ("Error, do not use save_dir if it \
            does not exists before")
        plot_conmat_file = os.path.join(save_dir, 'circle_' + fname + '.png')
    else:
        plot_conmat_file = os.path.abspath('circle_' + fname + '.png')

    fig.savefig(plot_conmat_file, facecolor='black')
    plt.close(fig)
    return plot_conmat_file
Beispiel #6
0
def plot_circular_connectivity(conmat,
                               label_names,
                               node_colors,
                               node_order,
                               vmin=0.3,
                               vmax=1.0,
                               nb_lines=200,
                               fname="_def"):
    """Plot circular connectivity"""

    import os
    import numpy as np
    from mne.viz import circular_layout, plot_connectivity_circle
    import matplotlib.pyplot as plt

    # Angles
    node_angles = circular_layout(label_names,
                                  node_order,
                                  start_pos=90,
                                  group_boundaries=[0, len(label_names) / 2])
    print(conmat)
    print((node_angles.astype(int)))

    conmat = conmat + np.transpose(conmat)

    # Plot the graph using node colors from the FreeSurfer parcellation.
    # We only show the 300 strongest connections.
    fig, _ = plot_connectivity_circle(conmat,
                                      label_names,
                                      n_lines=nb_lines,
                                      node_angles=node_angles.astype(int),
                                      node_colors=None,
                                      fontsize_names=12,
                                      title='All-to-All Connectivity',
                                      show=False,
                                      vmin=vmin,
                                      vmax=vmax)

    # plt.show()
    # print fig
    # plot_conmat_file = os.path.abspath('circle.png')
    plot_conmat_file = os.path.abspath('circle_' + fname + '.eps')
    fig.savefig(plot_conmat_file, facecolor='black')
    # fig.savefig(plot_conmat_file)

    plt.close(fig)
    # fig1.close()
    del fig

    return plot_conmat_file
Beispiel #7
0
def test_plot_connectivity_circle():
    """Test plotting connectivity circle."""
    node_order = ['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff']

    label_names = ['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff']

    group_boundaries = [0, 2, 4]
    node_angles = circular_layout(label_names,
                                  node_order,
                                  start_pos=90,
                                  group_boundaries=group_boundaries)
    con = np.random.RandomState(0).randn(6, 6)
    con[con < 0.7] = 0

    fig, ax = plot_connectivity_circle(con,
                                       label_names,
                                       n_lines=60,
                                       node_angles=node_angles,
                                       title='test',
                                       colormap='RdBu_r',
                                       vmin=0,
                                       vmax=2,
                                       linewidth=.5,
                                       facecolor='k')
    plt.show()

    pytest.raises(ValueError,
                  circular_layout,
                  label_names,
                  node_order,
                  group_boundaries=[-1])
    pytest.raises(ValueError,
                  circular_layout,
                  label_names,
                  node_order,
                  group_boundaries=[20, 0])
Beispiel #8
0
# Save the plot order and create a circular layout
label_names=channel_names
node_order = list()
node_order=label_names
node_angles = circular_layout(label_names, node_order, start_pos=90,
                              group_boundaries=[0, len(label_names) / 2])

con_res=con_res.reshape(20,20)
if condition<3:
	con_res1=con_res1.reshape(20,20)
	dif=con_res1-con_res
	dif1=con_res-con_res1 #checking for difference between the two

#Plotting connectivity
plot_connectivity_circle(con_res, label_names, n_lines=300,
                         node_angles=node_angles, node_colors=label_colors,vmin=0.4,
                         title='Connectivity, Condition: PLI '+Event+' '+ frequency+'P')

if condition<3:
	plot_connectivity_circle(con_res1, label_names, n_lines=300,
                         node_angles=node_angles, node_colors=label_colors,vmin=0.4,
                         title='Connectivity, Condition: PLI '+Event+' '+ frequency+'NP')

if condition<3:
	#Plotting connections that have difference
	plot_connectivity_circle(dif, label_names, n_lines=300,
                         node_angles=node_angles, node_colors=label_colors, vmin=0.05,
                         title='Connectivity, Condition: PLI '+Event+' '+ frequency+'+')

	plot_connectivity_circle(dif, label_names, n_lines=300,
                         node_angles=node_angles, node_colors=label_colors, vmin=0.05,
Beispiel #9
0
# For the right hemi
rh_labels = [label[:-2] + 'rh' for label in lh_labels]

# Save the plot order and create a circular layout
node_order = list()
node_order.extend(lh_labels[::-1])  # reverse the order
node_order.extend(rh_labels)

node_angles = circular_layout(label_names, node_order, start_pos=90,
                              group_boundaries=[0, len(label_names) / 2])

# Plot the graph using node colors from the FreeSurfer parcellation. We only
# show the 300 strongest connections.
fig,ax = plot_connectivity_circle(con_res['wpli2_debiased'], label_names, n_lines=300,
                         node_angles=node_angles, node_colors=label_colors,
                         title='All-to-All Connectivity Gamma Gratings '
                               'Condition (w-PLI)')
plt.savefig('circle.png', facecolor='black')

# Plot connectivity for both methods in the same plot
fig = plt.figure(num=None, figsize=(8, 4), facecolor='black')
no_names = [''] * len(label_names)
for ii, method in enumerate(con_methods):
    plot_connectivity_circle(con_res[method], no_names, n_lines=300,
                             node_angles=node_angles, node_colors=label_colors,
                             title=method, padding=0, fontsize_colorbar=6,
                             fig=fig, subplot=(1, 2, ii + 1))

plt.show(block=True)

Beispiel #10
0
    def make_circle(authors_df, label_names):
        ## Prep all labels, colors, etc 
        # Create node colors
        types_colors = [ncol[0]] * len(type_labels)
        mm_colors = [ncol[1]] * len(authors_df.loc[authors_df['GendCat'] == 'MM', 'CitationKey'])
        mw_colors = [ncol[2]] * len(authors_df.loc[authors_df['GendCat'] == 'MW', 'CitationKey'])
        wm_colors = [ncol[3]] * len(authors_df.loc[authors_df['GendCat'] == 'WM', 'CitationKey'])
        ww_colors = [ncol[4]] * len(authors_df.loc[authors_df['GendCat'] == 'WW', 'CitationKey'])
        u_colors = [ncol[5]] * len(authors_df.loc[authors_df['GendCat'].str.contains(r'U'), 'CitationKey'])

        # LABEL COLORS GO IN THE ORIGINAL/MATRIX ORDER , not the reordered order!
        label_colors = types_colors + mm_colors + mw_colors + wm_colors + ww_colors + u_colors

        # MAKE NODE ORDER TO MAKE THE CIRCLE LOOK NICER - Node order is ONLY on the circle, not the matrix order. 
        pre_labels = ['Man - Man','Man - Woman','Spacer1']
        post_labels = ['Spacer2','Woman - Man','Woman - Woman','Unknown']

        # This node order is for the graph only! (ordered from starting point counter clockwise)
        node_order = pre_labels + papers_label_list + post_labels
        # now clean node order remove spacer labels only for graphing (angles needs all to be unique and match matrix)
        cleaned_label_names = [' ' if 'Spacer' in i else i for i in label_names]

        # Optional(?) clean paper titles for better looking graph
        cleaned_titles = []
        for paper in cleaned_label_names:
            x = re.split('(\d+)',paper)
            if len(x) == 3:
                cleaned_titles.append(f'{x[0]} ({x[1]})')
            else:
                cleaned_titles.append(paper)
         
        logger.debug(f'\n-Cleaned titles list: {cleaned_titles}\n')

        ## PREP FIGURE ##
        fig = plt.figure(figsize=(30, 30), facecolor='black')

        ## MAKE NODES ANGLES ##
        sp = 90
        node_angles = circular_layout(label_names, node_order, start_pos=sp)

        ## Make custom colormap (if used)
        cmap = colors.ListedColormap(['black',
                                      ccol[0],ccol[1],
                                      ccol[2],ccol[3],
                                      ccol[4]])
        boundaries = [0, 1, 2, 3, 4, 5]
        norm = colors.BoundaryNorm(boundaries, cmap.N, clip=True)

        # Make Custom/Manual Legend
        MM_patch = mpatches.Patch(facecolor=ncol[1], label='Man / Man', linewidth = 1, edgecolor = 'black')
        MW_patch = mpatches.Patch(facecolor=ncol[2], label='Man / Woman', linewidth = 1, edgecolor = 'black')
        WM_patch = mpatches.Patch(facecolor=ncol[3], label='Woman / Man', linewidth = 1, edgecolor = 'black')
        WW_patch = mpatches.Patch(facecolor=ncol[4], label='Woman / Woman', linewidth = 1, edgecolor = 'black')
        U_patch = mpatches.Patch(facecolor=ncol[5], label='Unknown', linewidth = 1, edgecolor = 'black')
        legend = plt.gcf().legend(handles=[MM_patch,MW_patch,WM_patch,WW_patch,U_patch],
                         loc=1, facecolor=args.lcol, framealpha=.98, prop={'size':35},
                         fancybox=True, title='Citation Type',title_fontsize=40)

        # change legen color text?
        # plt.setp(legend.get_texts(), color='g')

        ## Create Circle Graph
        plot_connectivity_circle(cite_mat, cleaned_titles,
                                 node_angles=node_angles,
                                 node_colors=label_colors,
                                 title=title, padding=4, fontsize_title=48,
                                 textcolor='white', facecolor='black',
                                 colormap=cmap, colorbar=False, fig=fig,
                                 linewidth=4, fontsize_names=25,
                                 subplot=111,
                                 interactive=False, show=False
                                )

        ## SAVE FIGURE ##
        out_fig = os.path.abspath(os.path.join(args.out_dir,png_name))

        # have to re-set the facecolor before saving #
        fig.savefig(out_fig, facecolor='black')
Beispiel #11
0
def plot_grouped_connectivity_circle(yaml_fname, con, orig_labels,
                                     node_order_size=68,
                                     out_fname='circle.png', title=None,
                                     subplot=111, include_legend=False,
                                     n_lines=None, fig=None, show=True,
                                     vmin=None, vmax=None,
                                     colorbar=False):
    '''
    Plot the connectivity circle grouped and ordered according to
    groups in the yaml input file provided.
    orig_labels : list of str
        Label names in the order as appears in con.
    '''
    # read the yaml file with grouping
    if op.isfile(yaml_fname):
        with open(yaml_fname, 'r') as f:
            labels = yaml.load(f)
    else:
        print '%s - File not found.' % yaml_fname
        sys.exit()

    cortex_colors = ['m', 'b', 'y', 'c', 'r', 'g',
                     'g', 'r', 'c', 'y', 'b', 'm']

    # make list of label_names (without individual cortex locations)
    label_names = list()
    for lab in labels:
        label_names.extend(labels[lab])

    lh_labels = [name + '-lh' for name in label_names]
    rh_labels = [name + '-rh' for name in label_names]

    # Save the plot order and create a circular layout
    node_order = list()
    node_order.extend(lh_labels[::-1])  # reverse the order
    node_order.extend(rh_labels)

    assert len(node_order) == node_order_size, 'Node order length is correct.'

    # the respective no. of regions in each cortex
    group_bound = [len(labels[key]) for key in labels.keys()]
    group_bound = [0] + group_bound[::-1] + group_bound
    group_boundaries = [sum(group_bound[:i+1]) for i in range(len(group_bound))]

    # remove the first element of group_bound
    # make label colours such that each cortex is of one colour
    group_bound.pop(0)
    label_colors = []
    for ind, rep in enumerate(group_bound):
        label_colors += [cortex_colors[ind]] * rep
    assert len(label_colors) == len(node_order), 'Number of colours do not match'

    # remove the last total sum of the list
    group_boundaries.pop()

    from mne.viz.circle import circular_layout
    node_angles = circular_layout(orig_labels, node_order, start_pos=90,
                                  group_boundaries=group_boundaries)

    # the order of the node_colors must match that of orig_labels
    # therefore below reordering is necessary
    reordered_colors = [label_colors[node_order.index(orig)]
                        for orig in orig_labels]

    # Plot the graph using node_order and colours
    # orig_labels is the order on nodes in the con matrix (important)
    from mne.viz import plot_connectivity_circle
    plot_connectivity_circle(con, orig_labels, n_lines=n_lines,
                             facecolor='white', textcolor='black',
                             node_angles=node_angles,
                             node_colors=reordered_colors,
                             node_edgecolor='white', fig=fig,
                             fontsize_names=6, vmax=vmax, vmin=vmin,
                             colorbar_size=0.2, colorbar_pos=(-0.3, 0.1),
                             colorbar=colorbar, show=show, subplot=subplot,
                             title=title)

    if include_legend:
        import matplotlib.patches as mpatches
        legend_patches = [mpatches.Patch(color=col, label=key)
                          for col, key in zip(['g', 'r', 'c', 'y', 'b', 'm'],
                                              labels.keys())]
        pl.legend(handles=legend_patches, loc=(0.02, 0.02), ncol=1,
                  mode=None, fontsize='small')
    if out_fname:
        pl.savefig(out_fname, facecolor='white', dpi=300)
Beispiel #12
0
# Compute connectivity for band containing the evoked response.
# We exclude the baseline period
# Delta 0 - 4
# Theta 4 - 7
# Alfa 7 - 14
# Beta 14 -21
# Gamma >30

# fmin, fmax = 3., 9.
fmin, fmax = 4., 7.
sfreq = raw.info['sfreq']  # the sampling frequency
tmin = 0.0  # exclude the baseline period
method = 'pli'
# method = 'pli'
con, freqs, times, n_epochs, n_tapers = spectral_connectivity(
    epochs, method=method, mode='multitaper', sfreq=sfreq, fmin=fmin, fmax=fmax,
    faverage=True, tmin=tmin, mt_adaptive=False, n_jobs=1)



# ******** PLOT ******** #
label_names = ['C3', 'C4', 'F3', 'F4', 'P3', 'P4'] # Orden original
node_order = ['F3', 'C3', 'P3', 'P4', 'C4', 'F4']
node_angles = circular_layout(label_names, node_order, start_pos=90,
    group_sep=20,group_boundaries=[0, len(label_names) / 2])

plot_connectivity_circle(con[:, :, 0],label_names,node_angles=node_angles,
    title=f'All-to-All Connectivity ({method})')

# %%
Beispiel #13
0
rh_labels = [label[:-2] + 'rh' for label in lh_labels]

    

# Save the plot order and create a circular layout
node_order = list()
node_order.extend(lh_labels[::-1])  #reverse the order
node_order.extend(rh_labels)

node_angles = circular_layout(label_names, node_order, start_pos=90,
                              group_boundaries=[0, len(label_names) / 2])

# Plot the graph using node colors from the FreeSurfer parcellation. We only
# show the 300 strongest connections.
plot_connectivity_circle(grand_con, label_names, n_lines=300,
                         node_angles=node_angles, node_colors=label_colors,vmin = 0.50, vmax = 1.00,
                         title='All-to-All Connectivity(PLV)- Grand Average - ' + freq)
import matplotlib.pyplot as plt
plt.savefig(conAll_plot_fname, facecolor='black')
plt.show()
## Plot connectivity for both methods in the same plot
#fig = plt.figure(num=None, figsize=(8, 4), facecolor='black')
#no_names = [''] * len(label_names)
#for ii, method in enumerate(con_methods):
#    plot_connectivity_circle(con_res[method], no_names, n_lines=300,
#                             node_angles=node_angles, node_colors=label_colors,
#                             title=method, padding=0, fontsize_colorbar=6,
#                             fig=fig, subplot=(1, 2, ii + 1))
#plt.savefig('/home/custine/MEG/data/epi_conn/' + subj + '/coh/' + subj + '_circle_coh_imcoh_' + freq + '.png', facecolor='black')
##plt.show()
    
# Save the plot order and create a circular layout
node_order = list()
node_order.extend(lh_labels[::-1])  # reverse the order
node_order.extend(rh_labels)

node_angles = circular_layout(label_names, node_order, start_pos=90,
                              group_boundaries=[0, len(label_names) / 2])

# <codecell>

# Plot the graph using node colors from the FreeSurfer parcellation. We only
# show the 300 strongest connections.
fig1 = plt.figure(figsize=(20,20))
plot_connectivity_circle(con_res['pli'], label_names, n_lines=300, fontsize_names= 16, colormap='PiYG',
                         node_angles=node_angles2, node_colors=label_colors, fig = fig1,
                         title='All-to-All Connectivity left-Auditory '
                               'Condition (PLI)')
plt.show()

# <codecell>

plt.imshow(con_res['pli'][0::6,0::6])
con_res['pli'][0::6,0::6].shape

# <codecell>

import pandas as pd
df = pd.read_csv(r'C:\Users\lenovo\Documents//middle_east_data2.csv', header=0,index_col=0)

# <codecell>
Beispiel #15
0
# Get the y-location of the label
label_ypos_lh = list()
for name in lh_labels:
    idx = label_names.index(name)
    ypos = np.mean(labels_parc[idx].pos[:, 1])
    label_ypos_lh.append(ypos)

# Reorder the labels based on their location
lh_labels = [label for (yp, label) in sorted(zip(label_ypos_lh, lh_labels))]

# For the right hemi
rh_labels = [label[:-2] + 'rh' for label in lh_labels]

# Save the plot order
node_order = lh_labels[::-1] + rh_labels

node_angles = circular_layout(label_names,
                              node_order,
                              start_pos=90,
                              group_boundaries=[0, len(label_names) // 2])

conmat = con[:, :, 0]
fig = plt.figure(num=None, figsize=(8, 8), facecolor='black')
plot_connectivity_circle(conmat,
                         label_names,
                         n_lines=300,
                         node_angles=node_angles,
                         node_colors=node_colors,
                         title='All-to-All Connectivity 300 Condition (PLI)',
                         fig=fig)
Beispiel #16
0
label_colors = [labels for label in labels]

labels[1][0]

node_angles = circular_layout(labels, labels, group_boundaries = boundaries)

fig = plt.figure(figsize=(20,20))


plot_connectivity_circle(corr_chans, labels,
                         node_angles=node_angles,
                         node_colors=[(.5,.5,.5, 1)],
                         facecolor = [0.1,0.1,0.1],
                         node_edgecolor=[0.1,0.1,0.1],
                         textcolor=[1,1,1],
                         fontsize_names = 10,
                         colormap='viridis',
                         vmin=np.min(corr_chans),
                         vmax = np.max(corr_chans),
                         linewidth = 1.5, fig=fig)
, fig=fig
vmax = np.max(corr_chans[corr_chans < 1]),

plot_connectivity_circle(corr_chans, labels,
                         node_angles=node_angles,
                         node_colors = [(.5, .5, .5, 1)],
                         facecolor = [0.1, 0.1, 0.1],
                         node_edgecolor = [0.1, 0.1, 0.1],
                         linewidth = 1.5)
Beispiel #17
0
print 'Jane Here' 
print 

print node_order
print len(node_order)

node_angles = circular_layout(label_names, node_order, start_pos=90,
                              group_boundaries=[0, len(label_names) / 2])
                              
#############################################################################################
#########Plot the difference 
##############3
# Plot the graph using node colors from the FreeSurfer parcellation. We only
# show the 300 strongest connections.
plot_connectivity_circle(con_diff_temp, label_names, n_lines=300,
                         node_angles=node_angles, node_colors=label_colors,colormap = 'RdBu', vmin = -1, vmax = 1,
                         title='Coherence - Difference ('+ gp1 + '-' +gp2 +') - '+ freq)
import matplotlib.pyplot as plt
plt.savefig(conAll_diff_plot_fname, facecolor='black')
plt.show()
###########################################################################################
###########Plot the connectivity T stats - 2 sample
## Plot the graph using node colors from the FreeSurfer parcellation. We only
## show the 300 strongest connections.
#plot_connectivity_circle(con_t_temp, label_names, n_lines=200,
#                         node_angles=node_angles, node_colors=label_colors,colormap = 'Blues', vmin = 1, vmax = 5.0,
#                         title='Coherence - T stats - Positive ('+ gp1 + '-' +gp2 +') - '+ freq)
#import matplotlib.pyplot as plt
#plt.savefig(conAll_Tpos_plot_fname, facecolor='black')
#plot_connectivity_circle(con_t_temp, label_names, n_lines=200,
#                         node_angles=node_angles, node_colors=label_colors,colormap = 'Reds', vmin = -5, vmax = -1,
node_angles = circular_layout(label_names,
                              node_order,
                              start_pos=90,
                              group_boundaries=[0, len(label_names) / 2])

# Plot the graph using node colors from the FreeSurfer parcellation. We only
# show the 200 strongest connections.
plt.ion()

fig = plt.figure(num=None, figsize=(8, 4), facecolor='black')

plot_connectivity_circle(leakage_mne,
                         label_names,
                         n_lines=200,
                         node_angles=node_angles,
                         node_colors=label_colors,
                         title='MNE Leakage',
                         fig=fig,
                         subplot=(1, 2, 1))

no_names = [''] * len(label_names)

plot_connectivity_circle(leakage_lor,
                         no_names,
                         n_lines=200,
                         node_angles=node_angles,
                         node_colors=label_colors,
                         title='sLORETA Leakage',
                         padding=0,
                         fontsize_colorbar=6,
                         fig=fig,
Beispiel #19
0
    (0.39215686274509803, 0.39803921568627451, 0.0, 1.0),
    (0.00215686274509803, 0.39803921568627451, 0.0, 1.0),
    (0.0, 0.39803921568627451, 0.4, 1.0), (0.0, 0.39803921568627451, 0.4, 1.0),
    (0.4, 0.0, 0.4, 1.0), (0.4, 0.2, 0.4, 1.0), (0.4, 0.4, 0.0, 1.0),
    (0.4, 0.2, 0.0, 1.0), (0.2, 0.0, 0.4, 1.0), (0.2, 0.2, 0.4, 1.0),
    (0.2, 0.4, 0.0, 1.0), (0.4, 0.0, 0.0, 1.0), (0.8, 0.2, 0.0, 1.0),
    (0.8, 0.0, 0.4, 1.0), (0.2, 0.8, 0.4, 1.0), (0.2, 0.8, 0.0, 1.0),
    (0.4, 0.0, 0.8, 1.0)
]
fig = plt.figure(num=None, figsize=(9, 9), facecolor='black')
plot_connectivity_circle(data_PLV1,
                         label_name,
                         n_lines=12,
                         facecolor='black',
                         textcolor='white',
                         vmin=np.min(data_PLV1),
                         vmax=np.max(data_PLV1),
                         node_angles=node_angles,
                         linewidth=3,
                         node_colors=label_colors,
                         fig=fig,
                         padding=6,
                         fontsize_colorbar=15,
                         colorbar_size=0.7,
                         colorbar_pos=(-0.3, 0.5),
                         colormap='hot',
                         fontsize_title=12,
                         fontsize_names=15)
plt.show()
fig.savefig('adj_diff_third_4.png', dpi=1800, facecolor='black')
# Reorder the labels based on their location
lh_labels = [label for (ypos, label) in sorted(zip(label_ypos, lh_labels))]
print lh_labels
# For the right hemi
rh_labels = [label[:-2] + 'rh' for label in lh_labels]
print rh_labels

# Save the plot order and create a circular layout
node_order = list()
node_order.extend(lh_labels[::-1])  #reverse the order
node_order.extend(rh_labels)

node_angles = circular_layout(label_names, node_order, start_pos=90,
                              group_boundaries=[0, len(label_names) / 2])

# Plot the graph using node colors from the FreeSurfer parcellation. We only
# show the 300 strongest connections.
plot_connectivity_circle(con_res['plv'], label_names, n_lines=300, ##con_res['coh'] or con_res1 if reading directly from text file - see commented section above 
                         node_angles=node_angles, node_colors=label_colors,
                         title='All-to-All Connectivity(PLV)-'+ freq, vmin = 0.40, vmax = 1.00)
import matplotlib.pyplot as plt
plt.savefig('/home/custine/MEG/data/epi_conn/' + subj + '/coh/' + subj + '_circle_PLV_' + freq + '.png', facecolor='black')

# Plot the graph using node colors from the FreeSurfer parcellation. We only
# show the 300 strongest connections.
plot_connectivity_circle(con_res['plv'], label_names, n_lines=300, ##con_res['coh'] or con_res1 if reading directly from text file - see commented section above 
                         node_angles=node_angles, node_colors=label_colors,
                         title='All-to-All Connectivity(PLI)-'+ freq, vmin = 0.0, vmax = 1.00)
import matplotlib.pyplot as plt
plt.savefig('/home/custine/MEG/data/epi_conn/' + subj + '/coh/' + subj + '_circle_PLI_' + freq + '.png', facecolor='black')
Beispiel #21
0
def test_plot_connectivity_circle():
    """Test plotting connectivity circle."""
    node_order = ['frontalpole-lh', 'parsorbitalis-lh',
                  'lateralorbitofrontal-lh', 'rostralmiddlefrontal-lh',
                  'medialorbitofrontal-lh', 'parstriangularis-lh',
                  'rostralanteriorcingulate-lh', 'temporalpole-lh',
                  'parsopercularis-lh', 'caudalanteriorcingulate-lh',
                  'entorhinal-lh', 'superiorfrontal-lh', 'insula-lh',
                  'caudalmiddlefrontal-lh', 'superiortemporal-lh',
                  'parahippocampal-lh', 'middletemporal-lh',
                  'inferiortemporal-lh', 'precentral-lh',
                  'transversetemporal-lh', 'posteriorcingulate-lh',
                  'fusiform-lh', 'postcentral-lh', 'bankssts-lh',
                  'supramarginal-lh', 'isthmuscingulate-lh', 'paracentral-lh',
                  'lingual-lh', 'precuneus-lh', 'inferiorparietal-lh',
                  'superiorparietal-lh', 'pericalcarine-lh',
                  'lateraloccipital-lh', 'cuneus-lh', 'cuneus-rh',
                  'lateraloccipital-rh', 'pericalcarine-rh',
                  'superiorparietal-rh', 'inferiorparietal-rh', 'precuneus-rh',
                  'lingual-rh', 'paracentral-rh', 'isthmuscingulate-rh',
                  'supramarginal-rh', 'bankssts-rh', 'postcentral-rh',
                  'fusiform-rh', 'posteriorcingulate-rh',
                  'transversetemporal-rh', 'precentral-rh',
                  'inferiortemporal-rh', 'middletemporal-rh',
                  'parahippocampal-rh', 'superiortemporal-rh',
                  'caudalmiddlefrontal-rh', 'insula-rh', 'superiorfrontal-rh',
                  'entorhinal-rh', 'caudalanteriorcingulate-rh',
                  'parsopercularis-rh', 'temporalpole-rh',
                  'rostralanteriorcingulate-rh', 'parstriangularis-rh',
                  'medialorbitofrontal-rh', 'rostralmiddlefrontal-rh',
                  'lateralorbitofrontal-rh', 'parsorbitalis-rh',
                  'frontalpole-rh']
    label_names = ['bankssts-lh', 'bankssts-rh', 'caudalanteriorcingulate-lh',
                   'caudalanteriorcingulate-rh', 'caudalmiddlefrontal-lh',
                   'caudalmiddlefrontal-rh', 'cuneus-lh', 'cuneus-rh',
                   'entorhinal-lh', 'entorhinal-rh', 'frontalpole-lh',
                   'frontalpole-rh', 'fusiform-lh', 'fusiform-rh',
                   'inferiorparietal-lh', 'inferiorparietal-rh',
                   'inferiortemporal-lh', 'inferiortemporal-rh', 'insula-lh',
                   'insula-rh', 'isthmuscingulate-lh', 'isthmuscingulate-rh',
                   'lateraloccipital-lh', 'lateraloccipital-rh',
                   'lateralorbitofrontal-lh', 'lateralorbitofrontal-rh',
                   'lingual-lh', 'lingual-rh', 'medialorbitofrontal-lh',
                   'medialorbitofrontal-rh', 'middletemporal-lh',
                   'middletemporal-rh', 'paracentral-lh', 'paracentral-rh',
                   'parahippocampal-lh', 'parahippocampal-rh',
                   'parsopercularis-lh', 'parsopercularis-rh',
                   'parsorbitalis-lh', 'parsorbitalis-rh',
                   'parstriangularis-lh', 'parstriangularis-rh',
                   'pericalcarine-lh', 'pericalcarine-rh', 'postcentral-lh',
                   'postcentral-rh', 'posteriorcingulate-lh',
                   'posteriorcingulate-rh', 'precentral-lh', 'precentral-rh',
                   'precuneus-lh', 'precuneus-rh',
                   'rostralanteriorcingulate-lh',
                   'rostralanteriorcingulate-rh', 'rostralmiddlefrontal-lh',
                   'rostralmiddlefrontal-rh', 'superiorfrontal-lh',
                   'superiorfrontal-rh', 'superiorparietal-lh',
                   'superiorparietal-rh', 'superiortemporal-lh',
                   'superiortemporal-rh', 'supramarginal-lh',
                   'supramarginal-rh', 'temporalpole-lh', 'temporalpole-rh',
                   'transversetemporal-lh', 'transversetemporal-rh']

    group_boundaries = [0, len(label_names) / 2]
    node_angles = circular_layout(label_names, node_order, start_pos=90,
                                  group_boundaries=group_boundaries)
    con = np.random.RandomState(0).randn(68, 68)
    plot_connectivity_circle(con, label_names, n_lines=300,
                             node_angles=node_angles, title='test',
                             )

    pytest.raises(ValueError, circular_layout, label_names, node_order,
                  group_boundaries=[-1])
    pytest.raises(ValueError, circular_layout, label_names, node_order,
                  group_boundaries=[20, 0])
    plt.close('all')
Beispiel #22
0
plt.show()
# %%
# ******** PLOT ******** #
label_names = ['C3', 'C4', 'F3', 'F4', 'P3', 'P4']  # Orden original
node_order = ['F3', 'C3', 'P3', 'P4', 'C4', 'F4']
node_angles = circular_layout(label_names,
                              node_order,
                              start_pos=90,
                              group_sep=20,
                              group_boundaries=[0, len(label_names) / 2])

fig = plt.figure(num=None, figsize=(12, 7), facecolor='black')
plot_connectivity_circle(exp2_CR[2, :, :],
                         label_names,
                         node_angles=node_angles,
                         interactive=True,
                         fig=fig,
                         subplot=(1, 3, 1),
                         title='All-to-All Connectivity (CR)')

plot_connectivity_circle(exp2_IR[0, :, :],
                         label_names,
                         node_angles=node_angles,
                         interactive=True,
                         fig=fig,
                         subplot=(1, 3, 2),
                         title='All-to-All Connectivity (IR)')

plot_connectivity_circle(exp2_NR[0, :, :],
                         label_names,
                         node_angles=node_angles,
# For the right hemi
rh_labels = [label[:-2] + 'rh' for label in lh_labels]

# Save the plot order and create a circular layout
node_order = list()
node_order.extend(lh_labels[::-1])  # reverse the order
node_order.extend(rh_labels)

node_angles = circular_layout(label_names, node_order, start_pos=90,
                              group_boundaries=[0, len(label_names) / 2])

# Plot the graph using node colors from the FreeSurfer parcellation. We only
# show the 300 strongest connections.
plot_connectivity_circle(con_res['pli'], label_names, n_lines=300,
                         node_angles=node_angles, node_colors=label_colors,
                         title='All-to-All Connectivity left-Auditory '
                               'Condition (PLI)')

###############################################################################
# Make two connectivity plots in the same figure
# ----------------------------------------------
#
# We can also assign these connectivity plots to axes in a figure. Below we'll
# show the connectivity plot using two different connectivity methods.

fig = plt.figure(num=None, figsize=(8, 4), facecolor='black')
no_names = [''] * len(label_names)
for ii, method in enumerate(con_methods):
    plot_connectivity_circle(con_res[method], no_names, n_lines=300,
                             node_angles=node_angles, node_colors=label_colors,
                             title=method, padding=0, fontsize_colorbar=6,
Beispiel #24
0
def plot_connectivity(fc: Union[np.ndarray, pd.DataFrame], threshold: Optional[float] = None, plot_style: str = 'heatmap',
                      bg_style: str = 'whitegrid', node_order: Optional[list] = None, auto_cluster: bool = False,
                      **kwargs) -> plt.Axes:
    """Plot functional connectivity between nodes in backend.

    Parameters
    ----------
    fc
        Pandas dataframe containing or numpy array containing the functional connectivities.
    threshold
        Connectivtiy threshold to be applied (only connectivities larger than the threshold will be shown).
    plot_style
        Can either be `heatmap` for plotting with seaborn.heatmap or `circular_graph` for plotting with
         mne.viz.plot_connectivity_circle. Check out the respective function docstrings for information on
         their arguments (can be passed to kwargs).
    bg_style
        Only relevant if plot_style == heatmap. Then this will define the style of the background of the plot.
    node_order
        Order in which the nodes should appear in the plot.
    auto_cluster
        If true, automatic cluster detection will be used to arange the nodes
    kwargs
        Additional arguments for the fc calculation or fc plotting that can be passed.

    Returns
    -------
    plt.Axes
        Handle of the axis the plot was created in.

    """

    import seaborn as sb

    # turn fc into dataframe if necessary
    if type(fc) is np.ndarray:
        rows = kwargs.pop('yticklabels') if 'yticklabels' in kwargs.keys() else [str(i) for i in range(fc.shape[0])]
        cols = kwargs.pop('xticklabels') if 'xticklabels' in kwargs.keys() else [str(i) for i in range(fc.shape[1])]
        fc = pd.DataFrame(fc, index=[str(r) for r in rows], columns=[str(c) for c in cols])

    # apply threshold
    if threshold:
        fc[fc < threshold] = 0.

    # cluster the columns
    #####################

    if auto_cluster:

        idx_r = [i for i in range(fc.shape[0])]
        idx_c = [i for i in range(fc.shape[1])]

        # Create a categorical color palette for node groups
        col_pal_args = ['h', 's', 'l']
        kwargs_tmp = {}
        for key in kwargs.keys():
            if key in col_pal_args:
                kwargs_tmp[key] = kwargs.pop(key)
        node_pal = sb.husl_palette(len(idx_c), **kwargs_tmp)
        nodes = fc.columns.values
        node_lut = dict(zip(map(str, nodes), node_pal))

        # Convert the palette to vectors that will be drawn on the side of the fc plot
        node_colors = pd.Series(nodes, index=fc.columns).map(node_lut)

    elif node_order:

        idx_c = [node_order.index(n) for n in fc.columns.values]
        idx_r = [i for i in range(fc.shape[0])]

    else:

        idx_r = [i for i in range(fc.shape[0])]
        idx_c = [i for i in range(fc.shape[1])]

    fc = fc.iloc[idx_r, idx_c]

    # plot the functional connectivities
    ####################################

    # choose plot style
    if plot_style == 'heatmap':

        # seaborn plot
        if 'xticklabels' not in kwargs:
            kwargs['xticklabels'] = fc.columns.values[idx_c]
        if 'yticklabels' not in kwargs:
            kwargs['yticklabels'] = fc.index[idx_r]

        sb.set_style(bg_style)

        if auto_cluster:
            ax = sb.clustermap(data=fc, row_colors=node_colors, col_colors=node_colors, **kwargs)
        else:
            ax = sb.heatmap(fc, **kwargs)
            # ax.invert_yaxis()

    elif plot_style == 'circular_graph':

        # mne python plot
        from mne.viz import circular_layout, plot_connectivity_circle

        # get node order for node layout
        node_names = fc.columns.values
        if auto_cluster:
            cluster_args = ['method', 'metric', 'z_score', 'standard_scale']
            kwargs_tmp = {}
            for key in kwargs.keys():
                if key in cluster_args:
                    kwargs_tmp[key] = kwargs.pop(key)
            clust_map = sb.clustermap(data=fc, row_colors=node_colors, col_colors=node_colors, **kwargs_tmp)
            node_order = [node_names[idx] for idx in clust_map.dendrogram_row.reordered_ind]
        elif not node_order:
            node_order = list(node_names)

        # create circular node layout
        kwargs_tmp = {}
        layout_args = ['start_pos', 'start_between', 'group_boundaries', 'group_sep']
        for key in kwargs.keys():
            if key in layout_args:
                kwargs_tmp[key] = kwargs.pop(key)
        node_angles = circular_layout(node_names, node_order, **kwargs_tmp)

        # plot the circular graph
        ax = plot_connectivity_circle(fc.values, node_names, node_angles=node_angles, **kwargs)

    else:

        raise ValueError(f'Plot style is not supported by this function: {plot_style}. Check the documentation of the '
                         f'argument `plot_style` for valid options.')

    return ax
Beispiel #25
0
# Leakage matrix for MNE, get first principal component per label
for [i, s] in enumerate(stcs_psf_mne):
    psfs_mat[i, :] = s.data[:, 0]
# Compute label-to-label leakage as Pearson correlation of PSFs
# Sign of correlation is arbitrary, so take absolute values
leakage_mne = np.abs(np.corrcoef(psfs_mat))

# Save the plot order and create a circular layout
node_order = lh_labels[::-1] + rh_labels  # mirror label order across hemis
node_angles = circular_layout(label_names, node_order, start_pos=90,
                              group_boundaries=[0, len(label_names) / 2])
# Plot the graph using node colors from the FreeSurfer parcellation. We only
# show the 200 strongest connections.
fig = plt.figure(num=None, figsize=(8, 8), facecolor='black')
plot_connectivity_circle(leakage_mne, label_names, n_lines=200,
                         node_angles=node_angles, node_colors=label_colors,
                         title='MNE Leakage', fig=fig)

# %%
# Most leakage occurs for neighbouring regions, but also for deeper regions
# across hemispheres.
#
# Save the figure (optional)
# --------------------------
#
# Matplotlib controls figure facecolor separately for interactive display
# versus for saved figures. Thus when saving you must specify ``facecolor``,
# else your labels, title, etc will not be visible::
#
#     >>> fname_fig = data_path + '/MEG/sample/plot_label_leakage.png'
#     >>> fig.savefig(fname_fig, facecolor='black')
Beispiel #26
0
def circular_brain_plot(forward,
                        solution_support,
                        stcs,
                        obj_fun,
                        label_name=False,
                        plot_circular=True,
                        plot_labels=True,
                        n_burnin=0,
                        vmin=0.,
                        vmax=10.,
                        plot_hist=False,
                        subplot=111,
                        title='',
                        fig=None,
                        colorbar=True):

    indices = list()
    vertices_lh = list()
    vertices_rh = list()

    support = np.unique(np.where(solution_support)[1])
    indices.append(support)
    for stc in stcs:
        vertices_lh.append(stc.vertices[0])
        vertices_rh.append(stc.vertices[1])

    indices = np.unique(np.concatenate(np.array(indices)))
    vertices_lh = np.unique(np.concatenate(np.array(vertices_lh)))
    vertices_rh = np.unique(np.concatenate(np.array(vertices_rh)))

    n_sources = solution_support.shape[1]
    # Get n_used of the left hemi
    n_used = forward['src'][0]['nuse']
    n_rh = forward['src'][1]['nuse']
    #
    indices_lh = indices[np.where(indices < n_used)[0]]
    indices_rh = indices[np.where(indices >= n_used)[0]]

    indices_sym = np.sort(
        np.concatenate(
            np.array([indices, indices_lh + n_used, indices_rh - n_rh])))

    #
    n_support = len(indices_sym)
    iindices = [list(indices_sym).index(ii) for ii in indices]

    # Remove burnin
    solution_support = solution_support[n_burnin:, :]
    stcs = stcs[n_burnin:]

    # Plot histogram of the different objective function values
    # obtained with the MCMC init after burnin.
    if plot_hist:
        out = plt.hist(obj_fun)
        ymin, ymax = 0, out[0].max()
        plt.vlines(obj_fun[0], ymin=ymin, ymax=ymax)
        plt.ylim([ymin, ymax])
        plt.yticks(fontsize=16)
        plt.xticks(fontsize=16)
        plt.xlabel('Objective function values', fontsize=16)
        plt.legend(['MM solution', 'MCMC initializations'], fontsize=16)
        plt.show()

    # ####
    ind = np.unique(np.where(solution_support)[1])
    # ####

    # Take the results for all indices
    data_support_res = solution_support[:, indices]

    # Construct cooeccurrence matrix
    cooecc = np.zeros((n_sources, n_sources))
    ixgrid = np.ix_(indices, indices)
    cooecc[ixgrid] = np.dot(data_support_res.T, data_support_res)

    ixgrid = np.ix_(indices_sym, indices_sym)
    cooecc = cooecc[ixgrid]

    # Read labels
    # data_path = sample.data_path()
    subjects_dir = sample.data_path() + '/subjects'
    labels = mne.read_labels_from_annot('sample',
                                        parc='aparc.split-125',
                                        subjects_dir=subjects_dir)

    # First, we reorder the labels based on their location in the left hemi
    label_names = [label.name for label in labels]

    lh_labels = [name for name in label_names if name.endswith('lh')]

    # Get the y-location of the label
    label_ypos = list()
    for name in lh_labels:
        idx = label_names.index(name)
        ypos = np.mean(labels[idx].pos[:, 1])
        label_ypos.append(ypos)

    # Reorder the labels based on their location
    lh_labels = [label for (yp, label) in sorted(zip(label_ypos, lh_labels))]

    # Find the corresponding label name to the vertices
    lh_names = list()
    length = 0
    for vertex in vertices_lh:
        for label in labels[::2]:
            if vertex in label.vertices:
                lh_names.append(label.name)
        if len(lh_names) != length + 1:
            lh_names.append(labels[56].name)
        length += 1

    rh_names = list()
    length = 0
    for vertex in vertices_rh:
        for label in labels[1::2]:
            if vertex in label.vertices:
                rh_names.append(label.name)

        if len(rh_names) != length + 1:
            rh_names.append(labels[57].name)
        length += 1

    names = lh_names + rh_names
    names_sym = np.array([''] * n_support, dtype='U30')
    names_sym[iindices] = names
    for ii in np.where(names_sym == '')[0]:
        if indices_sym[ii] < n_used:
            ind = np.where(indices == indices_sym[ii] + n_rh)[0]
            if ind.shape[0] == 0:
                ind = np.where(indices == indices_sym[ii] - 2 + n_rh)[0]
            name = np.array(names)[ind][0][:-3] + '-lh'
        else:
            ind = np.where(indices == indices_sym[ii] - n_used)[0]
            if ind.shape[0] == 0:
                ind = np.where(indices == indices_sym[ii] - 2 - n_used)[0]
            name = np.array(names)[ind][0][:-3] + '-rh'
        names_sym[ii] = name

    names = names_sym
    dipole_colors = list()
    names_lh = list()
    # For each found label find its color
    for label in names:
        if label[:-3] != 'n':
            idx = label_names.index(label)
            if labels[idx].color == (0., 0., 0., 1.):
                labels[idx].color = (0.5, 0.5, 0.5, 1.)
            dipole_colors.append(labels[idx].color)
            names_lh.append(label[:-3])
        else:
            dipole_colors.append((0., 0., 0., 1.))
            names_lh.append('none')
    names_lh = names_lh[:n_support // 2]

    seen_labels = list()
    node_order = list()
    # Find the good order for names and cooecc
    for label in lh_labels:
        if label not in seen_labels and label[:-3] in names_lh:
            node_order.append(np.where(np.array(names_lh) == label[:-3])[0])
            seen_labels.append(label)

    lh_order = list(np.concatenate(np.array(node_order)))

    node_order = lh_order[::-1]

    # colors = list(np.array(dipole_colors)[node_order])
    node_order.extend(list(np.array(lh_order) + len(lh_order)))

    node_width = 2 * 180. / n_support

    label_indices = range(n_support)
    node_angles = circular_layout(label_indices,
                                  node_order,
                                  start_pos=90,
                                  group_boundaries=[0,
                                                    len(label_indices) / 2])

    dipole_colors = dipole_colors[:n_support // 2]
    colors = np.concatenate(np.array([dipole_colors, dipole_colors]))

    if not label_name:
        names = np.array([''] * len(indices_sym), dtype=np.dtype((str, 35)))

    if plot_circular:
        fig, ax = plot_connectivity_circle(cooecc,
                                           names,
                                           n_lines=None,
                                           node_angles=node_angles,
                                           node_colors=colors,
                                           node_width=node_width,
                                           vmin=vmin,
                                           vmax=vmax,
                                           fig=fig,
                                           subplot=subplot,
                                           title=title,
                                           padding=4,
                                           textcolor='black',
                                           facecolor='white',
                                           colormap='viridis',
                                           node_edgecolor=None,
                                           colorbar=colorbar)

        plot_bars_circular(n_support, node_angles, cooecc.diagonal(), ax)
    if plot_labels:
        brain_labels(labels, names_sym, subjects_dir)
Beispiel #27
0
def connectivity_circle(r, measure='coh',
                        pairs='all',
                        times=list(range(0, 501, 125)),
                        figure_by={'POP': ['C']},
                        row_by={'condition': 'all'},
                        lims='absmax', cmap_override=None,
                        savedir=None):
    ''' plot coherence as generic circle of nodes connected by colored arcs '''
    ptype = 'arctopo'
    final_dim = 'pair'

    if measure in ['coh', 'coh_Z']:
        data, d_dims, d_dimlvls = get_data(r, measure)
        units, lims, cmap = get_plotparams(r, measure, lims, cmap_override)
    else:
        print('data not recognized')
        return

    f_dim, f_vals, f_lbls = handle_by(r, figure_by, d_dims, d_dimlvls)
    r_dim, r_vals, r_lbls = handle_by(r, row_by, d_dims, d_dimlvls)
    time_by = {'timepoint': times}
    t_dim, t_vals, t_lbls = handle_by(r, time_by, d_dims, d_dimlvls)

    pair_inds = handle_pairs(r, pairs)
    pair_chaninds = [r.cohpair_inds[pi] for pi in pair_inds]

    uniq_chaninds = np.unique(np.array(pair_chaninds).ravel())
    uniq_chanlabels = [r.montage.ch_names[ci] for ci in uniq_chaninds]
    uniq_chanlabels.sort(key=lambda x: ordered_chans.index(x))

    cohpair_array = []
    for chan_pair in np.array(r.cohpair_inds):
        cohpair_array.append(
            [uniq_chanlabels.index(r.montage.ch_names[int(chan_pair[0])]),
             uniq_chanlabels.index(r.montage.ch_names[int(chan_pair[1])])])
    cohpair_array = np.array(cohpair_array)
    indices = (cohpair_array[:, 0], cohpair_array[:, 1])

    pair_dim = d_dims.index('pair')
    data = basic_slice(data, [(pair_dim, pair_inds)])

    sp_dims = (len(r_vals), len(times))
    figsize = figsize_heuristic(sp_dims)
    for fi, fval in enumerate(f_vals):
        f, axarr = plt.subplots(sp_dims[0], sp_dims[1],
                                sharex=True, sharey=True, figsize=figsize)
        f.suptitle(f_lbls[fi], fontsize=titlefont_sz, fontweight=titlefont_wt)
        try:
            axarr = axarr.ravel()
        except:
            axarr = [axarr]
        ax_dum = -1
        for ri, rval in enumerate(r_vals):
            for ti, tval in enumerate(t_vals):
                vals = [fval, rval, tval]
                dims = [f_dim[fi], r_dim[ri], t_dim[ti]]
                # try:
                dimval_tups = [(d, v) for d, v in zip(dims, vals)]
                try:
                    arcs = basic_slice(data, dimval_tups)
                    print('slice')
                except:
                    arcs = compound_take(data, dimval_tups)
                    print('compound take')
                mean_dims = np.where([d != final_dim for d in d_dims])
                arcs = arcs.mean(axis=tuple(mean_dims[0]))
                print(arcs.shape)
                ax_dum += 1

                # column = (ax_dum + 1) % sp_dims[1]
                # row = floor(ax_dum / sp_dims[1])
                # plot here
                plot_connectivity_circle(arcs, uniq_chanlabels, indices,
                                         # node_angles=node_angles,
                                         facecolor='white',
                                         textcolor='black',
                                         colormap=plt.cm.hot_r,
                                         title='title',
                                         colorbar_size=0.4,
                                         colorbar_pos=(-0.5, 0.5),
                                         fig=f,
                                         subplot=(sp_dims[0], sp_dims[1], ax_dum + 1))

                axarr[ax_dum].text(-.5, .5, t_lbls[ti])  # time label
                if ti == 0:
                    axarr[ax_dum].text(-1.5, 0, r_lbls[ri])  # row label

        if savedir:
            save_fig(r, savedir, ptype, measure, f_lbls[fi])
Beispiel #28
0
# Save the plot order and create a circular layout
node_order = list()
node_order.extend(lh_labels[::-1])  # reverse the order
node_order.extend(rh_labels)

node_angles = circular_layout(label_names,
                              node_order,
                              start_pos=90,
                              group_boundaries=[0, len(label_names) / 2])

# Plot the graph using node colors from the FreeSurfer parcellation. We only
# show the 300 strongest connections.
plot_connectivity_circle(con_res['pli'],
                         label_names,
                         n_lines=300,
                         node_angles=node_angles,
                         node_colors=label_colors,
                         title='All-to-All Connectivity left-Auditory '
                         'Condition (PLI)')
plt.savefig('circle.png', facecolor='black')

# Plot connectivity for both methods in the same plot
fig = plt.figure(num=None, figsize=(8, 4), facecolor='black')
no_names = [''] * len(label_names)
for ii, method in enumerate(con_methods):
    plot_connectivity_circle(con_res[method],
                             no_names,
                             n_lines=300,
                             node_angles=node_angles,
                             node_colors=label_colors,
                             title=method,
    def make_circle(threshmat, outpath, label_names, thr):
        ## GET VMIN AND MAX FROM MATRIX
        # maxval = threshmat.max()
        # minval = np.min(threshmat[np.nonzero(threshmat)]) - 1
        maxval = None
        minval = None

        ## CHECK CIRCLE GRAPH COLOR TYPE ##
        if color_type == 'DARK':
            fc = 'black'
        elif color_type == 'LIGHT':
            fc = 'white'

        ## PREP FIGURE
        fig = plt.figure(num=None, figsize=(30, 30), facecolor=fc)

        ## MAKE NODES ANGLES ##
        node_angles = circular_layout(label_names,
                                      node_order,
                                      start_pos=sp,
                                      group_boundaries=split)

        ## REMOVE NAMES IF TRUE ##
        remove_names = True
        if remove_names == True:
            label_names = [''] * len(label_names)

        ## WRITE GRAPH TO FIG ##
        if color_type == 'DARK':
            plot_connectivity_circle(
                threshmat,
                label_names,
                node_angles=node_angles,
                node_colors=label_colors,
                title=title,
                fontsize_title=48,
                textcolor='white',
                facecolor='black',
                node_edgecolor='black',
                node_linewidth=.5,
                linewidth=1.5,
                fontsize_names=8,
                colormap='hot',
                vmin=minval,
                vmax=maxval,

                ### make vmin and max the values from the min/max of matrix
                colorbar_size=0.2,
                colorbar_pos=(-1, .5),
                fontsize_colorbar=28,
                colorbar=True,
                padding=6.0,
                fig=fig,
                subplot=111,
                interactive=False,
                show=False)

            # ADD Left/Right Labels
            plt.gcf().text(.22, .5, 'L', color='white', fontsize=48)
            plt.gcf().text(.633, .5, 'R', color='white', fontsize=48)

        elif color_type == 'LIGHT':
            plot_connectivity_circle(
                threshmat,
                label_names,
                node_angles=node_angles,
                node_colors=label_colors,
                title=title,
                fontsize_title=48,
                textcolor='black',
                facecolor='white',
                node_edgecolor='black',
                node_linewidth=.5,
                linewidth=1.5,
                fontsize_names=8,
                colormap='hot_r',
                vmin=minval,
                vmax=maxval,  # colormap='YlGnBu'

                ### make vmin and max the values from the min/max of matrix
                colorbar_size=0.2,
                colorbar_pos=(-1, .5),
                fontsize_colorbar=28,
                colorbar=True,
                padding=6.0,
                fig=fig,
                subplot=111,
                interactive=False,
                show=False)

            # ADD Left/Right Labels
            plt.gcf().text(.22, .5, 'L', color='black', fontsize=48)
            plt.gcf().text(.633, .5, 'R', color='black', fontsize=48)

        ## SAVE FIGURE ##
        out_fig = os.path.abspath(
            os.path.join(out_path, file_name + '_THR' + str(thr)))

        # have to re-set the facecolor before saving #
        fig.savefig(out_fig, facecolor=fc)
Beispiel #30
0
# For the right hemi
rh_labels = [
    label[:-2] + 'rh' for label in lh_labels
    if label != 'Brain-Stem' and label[:-2] + 'rh' in rh_labels
]

# Save the plot order
node_order = list()
node_order = lh_labels[::-1] + rh_labels

node_angles = circular_layout(label_names,
                              node_order,
                              start_pos=90,
                              group_boundaries=[0, len(label_names) // 2])

# Plot the graph using node colors from the FreeSurfer parcellation. We only
# show the 300 strongest connections.
conmat = con[:, :, 0]
plot_connectivity_circle(conmat,
                         label_names,
                         n_lines=300,
                         node_angles=node_angles,
                         node_colors=node_colors,
                         title='All-to-All Connectivity left-Auditory '
                         'Condition (PLI)')

# Uncomment the following line to save the figure
'''
import matplotlib.pyplot as plt
plt.savefig('circle.png', facecolor='black')
'''
Beispiel #31
0
def test_plot_connectivity_circle():
    """Test plotting connectivity circle."""
    node_order = ['frontalpole-lh', 'parsorbitalis-lh',
                  'lateralorbitofrontal-lh', 'rostralmiddlefrontal-lh',
                  'medialorbitofrontal-lh', 'parstriangularis-lh',
                  'rostralanteriorcingulate-lh', 'temporalpole-lh',
                  'parsopercularis-lh', 'caudalanteriorcingulate-lh',
                  'entorhinal-lh', 'superiorfrontal-lh', 'insula-lh',
                  'caudalmiddlefrontal-lh', 'superiortemporal-lh',
                  'parahippocampal-lh', 'middletemporal-lh',
                  'inferiortemporal-lh', 'precentral-lh',
                  'transversetemporal-lh', 'posteriorcingulate-lh',
                  'fusiform-lh', 'postcentral-lh', 'bankssts-lh',
                  'supramarginal-lh', 'isthmuscingulate-lh', 'paracentral-lh',
                  'lingual-lh', 'precuneus-lh', 'inferiorparietal-lh',
                  'superiorparietal-lh', 'pericalcarine-lh',
                  'lateraloccipital-lh', 'cuneus-lh', 'cuneus-rh',
                  'lateraloccipital-rh', 'pericalcarine-rh',
                  'superiorparietal-rh', 'inferiorparietal-rh', 'precuneus-rh',
                  'lingual-rh', 'paracentral-rh', 'isthmuscingulate-rh',
                  'supramarginal-rh', 'bankssts-rh', 'postcentral-rh',
                  'fusiform-rh', 'posteriorcingulate-rh',
                  'transversetemporal-rh', 'precentral-rh',
                  'inferiortemporal-rh', 'middletemporal-rh',
                  'parahippocampal-rh', 'superiortemporal-rh',
                  'caudalmiddlefrontal-rh', 'insula-rh', 'superiorfrontal-rh',
                  'entorhinal-rh', 'caudalanteriorcingulate-rh',
                  'parsopercularis-rh', 'temporalpole-rh',
                  'rostralanteriorcingulate-rh', 'parstriangularis-rh',
                  'medialorbitofrontal-rh', 'rostralmiddlefrontal-rh',
                  'lateralorbitofrontal-rh', 'parsorbitalis-rh',
                  'frontalpole-rh']
    label_names = ['bankssts-lh', 'bankssts-rh', 'caudalanteriorcingulate-lh',
                   'caudalanteriorcingulate-rh', 'caudalmiddlefrontal-lh',
                   'caudalmiddlefrontal-rh', 'cuneus-lh', 'cuneus-rh',
                   'entorhinal-lh', 'entorhinal-rh', 'frontalpole-lh',
                   'frontalpole-rh', 'fusiform-lh', 'fusiform-rh',
                   'inferiorparietal-lh', 'inferiorparietal-rh',
                   'inferiortemporal-lh', 'inferiortemporal-rh', 'insula-lh',
                   'insula-rh', 'isthmuscingulate-lh', 'isthmuscingulate-rh',
                   'lateraloccipital-lh', 'lateraloccipital-rh',
                   'lateralorbitofrontal-lh', 'lateralorbitofrontal-rh',
                   'lingual-lh', 'lingual-rh', 'medialorbitofrontal-lh',
                   'medialorbitofrontal-rh', 'middletemporal-lh',
                   'middletemporal-rh', 'paracentral-lh', 'paracentral-rh',
                   'parahippocampal-lh', 'parahippocampal-rh',
                   'parsopercularis-lh', 'parsopercularis-rh',
                   'parsorbitalis-lh', 'parsorbitalis-rh',
                   'parstriangularis-lh', 'parstriangularis-rh',
                   'pericalcarine-lh', 'pericalcarine-rh', 'postcentral-lh',
                   'postcentral-rh', 'posteriorcingulate-lh',
                   'posteriorcingulate-rh', 'precentral-lh', 'precentral-rh',
                   'precuneus-lh', 'precuneus-rh',
                   'rostralanteriorcingulate-lh',
                   'rostralanteriorcingulate-rh', 'rostralmiddlefrontal-lh',
                   'rostralmiddlefrontal-rh', 'superiorfrontal-lh',
                   'superiorfrontal-rh', 'superiorparietal-lh',
                   'superiorparietal-rh', 'superiortemporal-lh',
                   'superiortemporal-rh', 'supramarginal-lh',
                   'supramarginal-rh', 'temporalpole-lh', 'temporalpole-rh',
                   'transversetemporal-lh', 'transversetemporal-rh']

    group_boundaries = [0, len(label_names) / 2]
    node_angles = circular_layout(label_names, node_order, start_pos=90,
                                  group_boundaries=group_boundaries)
    con = np.random.RandomState(0).randn(68, 68)
    plot_connectivity_circle(con, label_names, n_lines=300,
                             node_angles=node_angles, title='test',
                             )

    pytest.raises(ValueError, circular_layout, label_names, node_order,
                  group_boundaries=[-1])
    pytest.raises(ValueError, circular_layout, label_names, node_order,
                  group_boundaries=[20, 0])
    plt.close('all')
Beispiel #32
0
def test_plot_connectivity_circle():
    """Test plotting connectivity circle
    """
    node_order = [
        "frontalpole-lh",
        "parsorbitalis-lh",
        "lateralorbitofrontal-lh",
        "rostralmiddlefrontal-lh",
        "medialorbitofrontal-lh",
        "parstriangularis-lh",
        "rostralanteriorcingulate-lh",
        "temporalpole-lh",
        "parsopercularis-lh",
        "caudalanteriorcingulate-lh",
        "entorhinal-lh",
        "superiorfrontal-lh",
        "insula-lh",
        "caudalmiddlefrontal-lh",
        "superiortemporal-lh",
        "parahippocampal-lh",
        "middletemporal-lh",
        "inferiortemporal-lh",
        "precentral-lh",
        "transversetemporal-lh",
        "posteriorcingulate-lh",
        "fusiform-lh",
        "postcentral-lh",
        "bankssts-lh",
        "supramarginal-lh",
        "isthmuscingulate-lh",
        "paracentral-lh",
        "lingual-lh",
        "precuneus-lh",
        "inferiorparietal-lh",
        "superiorparietal-lh",
        "pericalcarine-lh",
        "lateraloccipital-lh",
        "cuneus-lh",
        "cuneus-rh",
        "lateraloccipital-rh",
        "pericalcarine-rh",
        "superiorparietal-rh",
        "inferiorparietal-rh",
        "precuneus-rh",
        "lingual-rh",
        "paracentral-rh",
        "isthmuscingulate-rh",
        "supramarginal-rh",
        "bankssts-rh",
        "postcentral-rh",
        "fusiform-rh",
        "posteriorcingulate-rh",
        "transversetemporal-rh",
        "precentral-rh",
        "inferiortemporal-rh",
        "middletemporal-rh",
        "parahippocampal-rh",
        "superiortemporal-rh",
        "caudalmiddlefrontal-rh",
        "insula-rh",
        "superiorfrontal-rh",
        "entorhinal-rh",
        "caudalanteriorcingulate-rh",
        "parsopercularis-rh",
        "temporalpole-rh",
        "rostralanteriorcingulate-rh",
        "parstriangularis-rh",
        "medialorbitofrontal-rh",
        "rostralmiddlefrontal-rh",
        "lateralorbitofrontal-rh",
        "parsorbitalis-rh",
        "frontalpole-rh",
    ]
    label_names = [
        "bankssts-lh",
        "bankssts-rh",
        "caudalanteriorcingulate-lh",
        "caudalanteriorcingulate-rh",
        "caudalmiddlefrontal-lh",
        "caudalmiddlefrontal-rh",
        "cuneus-lh",
        "cuneus-rh",
        "entorhinal-lh",
        "entorhinal-rh",
        "frontalpole-lh",
        "frontalpole-rh",
        "fusiform-lh",
        "fusiform-rh",
        "inferiorparietal-lh",
        "inferiorparietal-rh",
        "inferiortemporal-lh",
        "inferiortemporal-rh",
        "insula-lh",
        "insula-rh",
        "isthmuscingulate-lh",
        "isthmuscingulate-rh",
        "lateraloccipital-lh",
        "lateraloccipital-rh",
        "lateralorbitofrontal-lh",
        "lateralorbitofrontal-rh",
        "lingual-lh",
        "lingual-rh",
        "medialorbitofrontal-lh",
        "medialorbitofrontal-rh",
        "middletemporal-lh",
        "middletemporal-rh",
        "paracentral-lh",
        "paracentral-rh",
        "parahippocampal-lh",
        "parahippocampal-rh",
        "parsopercularis-lh",
        "parsopercularis-rh",
        "parsorbitalis-lh",
        "parsorbitalis-rh",
        "parstriangularis-lh",
        "parstriangularis-rh",
        "pericalcarine-lh",
        "pericalcarine-rh",
        "postcentral-lh",
        "postcentral-rh",
        "posteriorcingulate-lh",
        "posteriorcingulate-rh",
        "precentral-lh",
        "precentral-rh",
        "precuneus-lh",
        "precuneus-rh",
        "rostralanteriorcingulate-lh",
        "rostralanteriorcingulate-rh",
        "rostralmiddlefrontal-lh",
        "rostralmiddlefrontal-rh",
        "superiorfrontal-lh",
        "superiorfrontal-rh",
        "superiorparietal-lh",
        "superiorparietal-rh",
        "superiortemporal-lh",
        "superiortemporal-rh",
        "supramarginal-lh",
        "supramarginal-rh",
        "temporalpole-lh",
        "temporalpole-rh",
        "transversetemporal-lh",
        "transversetemporal-rh",
    ]

    group_boundaries = [0, len(label_names) / 2]
    node_angles = circular_layout(label_names, node_order, start_pos=90, group_boundaries=group_boundaries)
    con = np.random.randn(68, 68)
    plot_connectivity_circle(con, label_names, n_lines=300, node_angles=node_angles, title="test")

    plt.close("all")
    assert_raises(ValueError, circular_layout, label_names, node_order, group_boundaries=[-1])
    assert_raises(ValueError, circular_layout, label_names, node_order, group_boundaries=[20, 0])
rh_labels = [label[:-2] + 'rh' for label in lh_labels
             if label != 'Brain-Stem' and label[:-2] + 'rh' in rh_labels]

# Save the plot order
node_order = list()
node_order = lh_labels[::-1] + rh_labels

node_angles = circular_layout(label_names, node_order, start_pos=90,
                              group_boundaries=[0, len(label_names) // 2])


# Plot the graph using node colors from the FreeSurfer parcellation. We only
# show the 300 strongest connections.
conmat = con[:, :, 0]
fig = plt.figure(num=None, figsize=(8, 8), facecolor='black')
plot_connectivity_circle(conmat, label_names, n_lines=300,
                         node_angles=node_angles, node_colors=node_colors,
                         title='All-to-All Connectivity left-Auditory '
                         'Condition (PLI)', fig=fig, interactive=False)

###############################################################################
# Save the figure (optional)
# --------------------------
#
# By default matplotlib does not save using the facecolor, even though this was
# set when the figure was generated. If not set via savefig, the labels, title,
# and legend will be cut off from the output png file.

# fname_fig = data_path + '/MEG/sample/plot_mixed_connect.png'
# plt.savefig(fname_fig, facecolor='black')
            node_colors.append(next(colors))
        node_colors.extend(node_colors)

        node_angles = circular_layout(
            label_names,
            node_order,
            start_pos=90,
            group_boundaries=[0, len(label_names) / 2])

        # Difference map
        if idx2 == 'diff' or idx2 == 'diff3':
            [fig1, _] = plot_connectivity_circle(con_res,
                                                 label_names,
                                                 n_lines=None,
                                                 node_angles=node_angles,
                                                 node_colors=node_colors,
                                                 colormap='BlueRed1',
                                                 vmin=-99,
                                                 vmax=99,
                                                 title=names[num][num2])

        # Heatmaps
        else:

            [fig1, _] = plot_connectivity_circle(con_res,
                                                 label_names,
                                                 n_lines=None,
                                                 node_angles=node_angles,
                                                 node_colors=node_colors,
                                                 colormap='afmhot',
                                                 vmin=0,
Beispiel #35
0
print("E2E prediction results:")
test_metrics_0 = regression_metrics(y_pred_0, y_true_0)
print("class 0: {0}".format(test_metrics_0))
test_metrics_1 = regression_metrics(y_pred_1, y_true_1)
print("class 1: {0}".format(test_metrics_1))

# Saliency map is the gradient of the maximum score value with respect to
# the input image.
model.model.eval()
X = torch.from_numpy(x_test)
X.requires_grad_()
scores = model.model(X)
scores.backward(torch.ones(scores.shape, dtype=torch.float32))
saliency, _ = torch.max(X.grad.data.abs(), dim=1)
saliency = np.mean(saliency.numpy(), axis=0)

hemi_size = len(labels) // 2
node_order = labels[:hemi_size]
node_order.extend(labels[hemi_size:][::-1])
node_angles = circular_layout(labels,
                              node_order,
                              start_pos=90,
                              group_boundaries=[0, hemi_size])
plot_connectivity_circle(saliency,
                         labels,
                         n_lines=300,
                         node_angles=node_angles,
                         title="Partial derivatives mapped on a circle plot")

plt.show()
Beispiel #36
0
def plot_conn_stats(AB_con,
                    fig,
                    flatten=True,
                    errdist_perms=0,
                    pctl=5,
                    min_corr_diff=0,
                    pcorrs=False,
                    neg_norm=True,
                    fdr_alpha=0.2,
                    exclude_conns=True,
                    savefig=None,
                    ccstatsmat=None,
                    inds_cc=None,
                    vvstatsmat=None,
                    refresh=False,
                    nofig=False,
                    rel=True):
    """ generates correlation and ASC stats for a pair of states. """

    # generate basic correlation and variance stats
    if ccstatsmat is None:
        inds_cc = find(
            mne.stats.fdr_correction(fa(
                AB_con.get_corr_stats(pcorrs=pcorrs, rel=rel)[1]),
                                     alpha=fdr_alpha)[0])
        ccstatsmat = -fa(AB_con.get_corr_stats(pcorrs=pcorrs, rel=rel)[0])
        vvstatsmat = -AB_con.get_std_stats(pcorrs=pcorrs, rel=rel)

    # generate ASC limits
    lims = AB_con.get_ASC_lims(pcorrs=pcorrs,
                               errdist_perms=errdist_perms,
                               refresh=refresh,
                               pctl=pctl)

    # gen correlation matrices for plotting
    Acorrs_mat = np.mean(AB_con.A.get_corrs(pcorrs=pcorrs), 0, keepdims=True)
    Acorrs = fa(Acorrs_mat)  # flattening
    Bcorrs_mat = np.mean(AB_con.B.get_corrs(pcorrs=pcorrs), 0, keepdims=True)
    Bcorrs = fa(Bcorrs_mat)  # flattening

    # min_corr_diff is the minimum change in correlation considered interesting (significant but tiny effects may not be interesting)
    if min_corr_diff != 0:
        inds_corr_diff = find(abs(Acorrs - Bcorrs) > min_corr_diff)
        inds_cc = np.intersect1d(inds_corr_diff, inds_cc)

    ##################################
    # set plot colours and other specs

    plot_colors = [(0.2, 0.6, 1), (0.62, 0.82, 0.98), (0.40, 0.95, 0.46),
                   (0.6, 0.95, 0.6), (0.15, 0.87, 0.87), (0.8, 0.8, 0.8)]

    cdict1 = {
        'red': ((0.0, 0.0, 0.0), (0.75, 0.5, 0.5), (1.0, 1.0, 1.0)),
        'green': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)),
        'blue': ((0.0, 0.0, 1.0), (0.25, 0.5, 0.5), (1.0, 0, 0))
    }

    cdict2 = {
        'red': ((0.0, 0.0, 0.0), (0.5, 0.0, 0.1), (1.0, 1.0, 1.0)),
        'green': ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0)),
        'blue': ((0.0, 0.0, 1.0), (0.5, 0.1, 0.0), (1.0, 0.0, 0.0))
    }

    blue_red1 = LinearSegmentedColormap('BlueRed1', cdict1)
    plt.register_cmap(cmap=blue_red1)
    cmap2 = matplotlib.colors.ListedColormap(name='Test', colors=plot_colors)
    plt.register_cmap(cmap=cmap2)

    fontsize = 9

    current_palette = [
        (0.2980392156862745, 0.4470588235294118, 0.6901960784313725),
        (0.3333333333333333, 0.6588235294117647, 0.40784313725490196),
        (0.7686274509803922, 0.3058823529411765, 0.3215686274509804),
        (0.5058823529411764, 0.4470588235294118, 0.6980392156862745),
        (0.8, 0.7254901960784313, 0.4549019607843137),
        (0.39215686274509803, 0.7098039215686275, 0.803921568627451)
    ]
    sb_cols = current_palette + current_palette + current_palette

    # colours for variance stats

    vcols = []
    # scaling stats for plotting colours for variance change
    vv_norm = vvstatsmat / 6
    vv_norm[np.isnan(vv_norm)] = 0
    n_nodes = AB_con.A.get_covs().shape[1]

    for a in np.arange(n_nodes):
        vcols.append(blue_red1((vv_norm[a] + 1) / 2))

    vmax = 3
    vmin = -3

    # node info
    node_angles = np.linspace(0, 2 * np.pi, n_nodes, endpoint=False)
    height = np.ones(n_nodes) * 4
    dist_mat = node_angles[None, :] - node_angles[:, None]
    dist_mat[np.diag_indices(n_nodes)] = 1e9
    node_width = np.min(np.abs(dist_mat))
    node_edgecolor = 'black'
    group_cols = []

    # colours for ROIs
    ROI_info = AB_con.A.ROI_info
    for a in ROI_info['ROI_RSNs']:
        val = 1 - 0.35 * a / max(ROI_info['ROI_RSNs'])
        group_cols.append((val * 0.8, val * 0.9, val))

    plots = ['uncorrelated', 'common', 'additive', 'other']
    titles = {
        'uncorrelated': "Addition of uncorrelated signal",
        'common': "Addition of common signal",
        'additive': "Mixed additive signals",
        'other': "Changes not explained \n by additive signal changes"
    }

    #################################
    # plot data

    indices = np.triu_indices(n_nodes, 1)
    notin = inds_cc.copy()
    inds_plots = {}

    for plot in plots[:3]:
        if errdist_perms > 0:
            inds_plots[plot] = np.intersect1d(inds_cc,
                                              find(fa(lims[plot]['pctls'])))
            notin = np.setdiff1d(notin, find(fa(lims[plot]['pctls'])))
            minstr = 'min_pctls'
            maxstr = 'max_pctls'
        else:
            inds_plots[plot] = np.intersect1d(
                inds_cc, find(fa(lims[plot]['pctls_noerr'])))
            notin = np.setdiff1d(notin, find(fa(lims[plot]['pctls_noerr'])))
            minstr = 'min'
            maxstr = 'max'

    inds_plots['other'] = notin
    if exclude_conns:
        inds_plots['common'] = np.setdiff1d(inds_plots['common'],
                                            inds_plots['uncorrelated'])
        inds_plots['additive'] = np.setdiff1d(inds_plots['additive'],
                                              inds_plots['common'])
        inds_plots['additive'] = np.setdiff1d(inds_plots['additive'],
                                              inds_plots['uncorrelated'])

    plotccstats = ccstatsmat.astype(float)

    # flip color of changes to negative corrs (neg_norm option)
    if neg_norm == True:
        plotccstats = plotccstats * np.sign(Acorrs)

    cnt = -1

    #################################
    # produce the four plots for the four ASC classes

    if fig != None:
        fig.clf()

        for plot in plots:

            cnt += 1

            ################################################
            # mne plot function
            # TODO: test for mne / nofig

            pp = plot_connectivity_circle(
                plotccstats.flatten()[inds_plots[plot]],
                ROI_info['ROI_names'][0:n_nodes],
                (indices[0][inds_plots[plot]], indices[1][inds_plots[plot]]),
                fig=fig,
                colormap='BlueRed1',
                vmin=vmin,
                vmax=vmax,
                node_colors=vcols,
                subplot=241 + cnt,
                title=titles[plot],
                interactive=True,
                fontsize_names=fontsize,
                facecolor='w',
                colorbar=False,
                node_edgecolor=node_edgecolor,
                textcolor='black',
                padding=3,
                node_linewidth=0.5)

            # titles
            ax = plt.gca()
            ax.set_title(titles[plot], color='black')

            #  color node faces
            bars = pp[1].bar(node_angles, height*2.2, width=node_width, bottom=10.4, \
                            edgecolor='0.9', lw=2, facecolor='.9', \
                            align='center',linewidth=1)

            for bar, color in zip(bars, group_cols):
                bar.set_facecolor(color)
                bar.set_edgecolor(color)

            # plot correlation info below circle plots
            if plot == 'other':
                plotrange = 'additive'
            else:
                plotrange = plot

            #  sorting plotting only those indices requested
            sort_array = np.zeros((len(inds_plots[plot]), ), dtype=('f4,f4'))
            sort_array['f0'] = fa(lims[plotrange][minstr])[0,
                                                           inds_plots[plot]]  #
            sort_array['f1'] = fa(lims[plotrange][maxstr])[0,
                                                           inds_plots[plot]]  #
            ii = np.argsort(sort_array, order=['f0', 'f1'])

            # plot conn info
            if len(ii) > 0:
                # width of nodes
                width = np.max((20, len(ii) + 10))
                # ii_ext
                ii_ext = np.r_[ii[0], ii, ii[-1]]

                # fbwx: midpoints for under plots
                fbwx = np.arange(len(ii_ext)) + (width - len(ii_ext)) / 2.
                fbwx[
                    0] = fbwx[0] + 0.5  #=np.r_[fbwx[0]-0.5, fbwx,fbwx[-1]+0.5]
                fbwx[-1] = fbwx[-1] - 0.5

                #  axis settings
                ax = plt.subplot(245 + cnt, axisbg='white')
                ax.set_ylim([-1., 1])
                ax.set_yticks([-1, 0, 1])
                ax.set_yticks([-0.75, -.25, 0, 0.25, .5, .75, 1], minor=True)
                ax.yaxis.grid(color=[0.7, .95, .95],
                              linestyle='-',
                              linewidth=.5,
                              which='minor')
                ax.yaxis.grid(color=[0.65, .85, .85],
                              linestyle='-',
                              linewidth=2,
                              which='major')

                # first plot bands for ASC / uncorr / common  (fill between)
                if len(fbwx) == 1:
                    # if only one element
                    plt.fill_between(np.r_[fbwx - 0.5, fbwx + 0.5],
                                     np.r_[fa(lims['additive'][minstr])[
                                         0, inds_plots[plot]][ii_ext],
                                           fa(lims['additive'][minstr])[
                                               0, inds_plots[plot]][ii_ext]],
                                     np.r_[fa(lims['additive'][maxstr])[
                                         0, inds_plots[plot]][ii_ext],
                                           fa(lims['additive'][maxstr])[
                                               0, inds_plots[plot]][ii_ext]],
                                     color='Grey',
                                     alpha=0.4)
                    plt.fill_between(np.r_[fbwx - 0.5, fbwx + 0.5],
                                     np.r_[fa(lims['common'][minstr])[
                                         0, inds_plots[plot]][ii_ext],
                                           fa(lims['common'][minstr])[
                                               0, inds_plots[plot]][ii_ext]],
                                     np.r_[fa(lims['common'][maxstr])[
                                         0, inds_plots[plot]][ii_ext],
                                           fa(lims['common'][maxstr])[
                                               0, inds_plots[plot]][ii_ext]],
                                     color='Blue',
                                     alpha=0.4)

                    plt.fill_between(np.r_[fbwx - 0.5, fbwx + 0.5],
                                     np.r_[fa(lims['uncorrelated'][minstr])[
                                         0, inds_plots[plot]][ii_ext],
                                           fa(lims['uncorrelated'][minstr])[
                                               0, inds_plots[plot]][ii_ext]],
                                     np.r_[fa(lims['uncorrelated'][maxstr])[
                                         0, inds_plots[plot]][ii_ext],
                                           fa(lims['uncorrelated'][maxstr])[
                                               0, inds_plots[plot]][ii_ext]],
                                     color='Green',
                                     alpha=0.6)
                else:
                    # if multple elements
                    plt.fill_between(
                        fbwx,
                        fa(lims['additive'][minstr])[0,
                                                     inds_plots[plot]][ii_ext],
                        fa(lims['additive'][maxstr])[0,
                                                     inds_plots[plot]][ii_ext],
                        color=[0.67, 0.76, 0.85])
                    plt.fill_between(
                        fbwx,
                        fa(lims['common'][minstr])[0,
                                                   inds_plots[plot]][ii_ext],
                        fa(lims['common'][maxstr])[0,
                                                   inds_plots[plot]][ii_ext],
                        color='Blue',
                        alpha=0.4)
                    plt.fill_between(fbwx,
                                     fa(lims['uncorrelated'][minstr])[
                                         0, inds_plots[plot]][ii_ext],
                                     fa(lims['uncorrelated'][maxstr])[
                                         0, inds_plots[plot]][ii_ext],
                                     color='Green',
                                     alpha=0.6)

                if neg_norm == True:
                    iipospos = np.in1d(
                        ii,
                        find(
                            abs(Acorrs[0, inds_plots[plot]]) > abs(Bcorrs[
                                0, inds_plots[plot]])))
                    iinegpos = np.in1d(
                        ii,
                        find(
                            abs(Acorrs[0, inds_plots[plot]]) < abs(Bcorrs[
                                0, inds_plots[plot]])))
                else:
                    iipospos = np.in1d(
                        ii,
                        find(Acorrs[0, inds_plots[plot]] > Bcorrs[
                            0, inds_plots[plot]]))
                    iinegpos = np.in1d(
                        ii,
                        find(Acorrs[0, inds_plots[plot]] < Bcorrs[
                            0, inds_plots[plot]]))

                iipos = ii[iipospos]
                iineg = ii[iinegpos]

                xes = np.arange(len(ii)) + (width - len(ii)) / 2.

                # now plot correlation in A and B conditions
                plt.plot(np.array([xes, xes])[:, find(iipospos)], [
                    Acorrs[0, inds_plots[plot][iipos]],
                    Bcorrs[0, inds_plots[plot][iipos]]
                ],
                         color=[0, 0, 1],
                         alpha=1,
                         linewidth=1.5,
                         zorder=1)
                plt.plot(np.array([xes, xes])[:, find(iinegpos)], [
                    Acorrs[0, inds_plots[plot][iineg]],
                    Bcorrs[0, inds_plots[plot][iineg]]
                ],
                         color=[1, 0, 0],
                         alpha=1,
                         linewidth=1.5,
                         zorder=1)

                plt.fill_between(
                    fbwx,
                    fa(lims['uncorrelated'][minstr])[0,
                                                     inds_plots[plot]][ii_ext],
                    fa(lims['uncorrelated'][maxstr])[0,
                                                     inds_plots[plot]][ii_ext],
                    color='Green',
                    alpha=0.6)
                line3 = plt.Rectangle((0, 0), 0, 0, color=current_palette[0])
                ax.add_patch(line3)
                ax.set_xticks([])

                # plot points
                line2 = plt.scatter((xes)[find(iipospos)],
                                    Bcorrs[0, inds_plots[plot][iipos]].T,
                                    color='blue',
                                    zorder=2)
                line2 = plt.scatter((xes)[find(iinegpos)],
                                    Bcorrs[0, inds_plots[plot][iineg]].T,
                                    color='red',
                                    zorder=2)
                line2 = plt.scatter((xes)[find(iipospos)],
                                    Acorrs[0, inds_plots[plot][iipos]].T,
                                    color='white',
                                    zorder=2)
                line2 = plt.scatter((xes)[find(iinegpos)],
                                    Acorrs[0, inds_plots[plot][iineg]].T,
                                    color='white',
                                    zorder=2)

                # plot line between, colouring line two according to pos or neg change
                cmap = ListedColormap([(0.2980392156862745, 0.4470588235294118,
                                        0.6901960784313725),
                                       (0.3333333333333333, 0.6588235294117647,
                                        0.40784313725490196),
                                       (0.7686274509803922, 0.3058823529411765,
                                        0.3215686274509804)])
                norm = BoundaryNorm([-2, 0, 1, 2], cmap.N)
                z = np.zeros(xes.shape[0] + 1, )

                # plot network membership above
                colorline(fbwx[:-1],
                          z + 1.05,
                          ROI_info['ROI_RSNs'][indices[0][np.r_[
                              inds_plots[plot], inds_plots[plot][-1]]]] - 1.5,
                          cmap=cmap,
                          norm=norm,
                          linewidth=5)
                colorline(fbwx[:-1],
                          z + 1.1,
                          ROI_info['ROI_RSNs'][indices[1][np.r_[
                              inds_plots[plot], inds_plots[plot][-1]]]] - 1.5,
                          cmap=cmap,
                          norm=norm,
                          linewidth=5)
                plt.show()

        if savefig != None:
            if nofig == 23:
                pp = PdfPages(fname)
                fig.tight_layout(h_pad=1, pad=4)
                pp.savefig(fig=fig)
                pp.close()
            else:
                fig.savefig(savefig)

    # add stats to AB_con struct
    AB_con.lims['covs']['inds_plots'] = inds_plots
    AB_con.lims['covs']['cc_stats'] = ccstatsmat
    AB_con.lims['covs']['vv_stats'] = vvstatsmat

    return (AB_con, inds_plots)
Beispiel #37
0
def plot_tab_circular_connectivity(list_list_conmat,
                                   all_elec_labels,
                                   plot_filename,
                                   coh_low_thresh=0.0,
                                   coh_high_thresh=1.0,
                                   color_bar='gist_rainbow',
                                   column_labels=[],
                                   row_labels=[]):
    """Plot tab circular conectivity."""
    nb_lines = len(list_list_conmat)
    print(nb_lines)

    print(len(list_list_conmat[0]))

    if len(list_list_conmat) != 1:
        for i, j in combinations(list(range(nb_lines)), 2):
            assert len(list_list_conmat[i]) == len(
                list_list_conmat[j]), ("Error, not all the same length {} != "
                                       "{}".format(len(list_list_conmat[i]),
                                                   len(list_list_conmat[j])))

    nb_cols = len(list_list_conmat[0])

    # for i in
    # print list_list_conmat[0][0].shape

    # Angles
    bounds = [0, len(all_elec_labels) / 2]
    all_node_angles = circular_layout(all_elec_labels,
                                      node_order=all_elec_labels,
                                      start_pos=90,
                                      group_boundaries=bounds)

    # print all_node_angles

    fig, axes = plt.subplots(nrows=nb_lines,
                             ncols=nb_cols,
                             figsize=(4 * nb_cols, 4 * nb_lines),
                             facecolor='black')
    # fig = plt.figure(num=None, figsize=(4*nb_cols, 4*nb_lines),
    # facecolor='black')

    if len(column_labels) == 0:
        column_labels = ['Column {}'.format(col) for col in range(nb_cols)]

    if len(row_labels) == 0:
        row_labels = ['Line {}'.format(row) for row in range(nb_lines)]

    assert len(column_labels) == nb_cols, (
        "Error, specifying invalid number of column labels")
    assert len(row_labels) == nb_lines, (
        "Error, specifying invalid number of line labels")

    for index_sess, list_conmat in enumerate(list_list_conmat):

        print(len(list_conmat))

        for index_win, np_all_mean_con_mats in enumerate(list_conmat):

            print(np_all_mean_con_mats.shape)

            kw = dict(textcolor="black",
                      facecolor="white",
                      n_lines=None,
                      node_angles=all_node_angles,
                      fontsize_names=15,
                      show=False,
                      colormap=color_bar,
                      vmin=coh_low_thresh,
                      vmax=coh_high_thresh,
                      fig=fig,
                      subplot=(nb_lines, nb_cols,
                               1 + index_win + nb_cols * index_sess))
            if index_win == len(list_conmat) - 1:
                fig, ax = plot_connectivity_circle(np_all_mean_con_mats,
                                                   all_elec_labels,
                                                   colorbar_size=0.5,
                                                   **kw)
                # (nb_lines,nb_cols,1+index_win+nb_cols*index_sess))

            else:
                fig, ax = plot_connectivity_circle(np_all_mean_con_mats,
                                                   all_elec_labels,
                                                   colorbar=False,
                                                   **kw)

            if index_win == 0:
                ax.set_ylabel(row_labels[index_sess],
                              rotation=0,
                              size='large',
                              fontsize=25)

            if index_sess == 0:
                ax.set_title(column_labels[index_win],
                             fontdict={'fontsize': 25})

    # saving
    print(plot_filename)

    fig.savefig(plot_filename, facecolor='white')

    plt.close(fig)
    # fig1.close()
    del fig
with open(yaml_fname, 'r') as f:
    xlabels = yaml.safe_load(f)

# the yaml file has been hand curated to follow the same order as label_names
# if not the node order has to be changed appropriately
node_order = list()
node_order.extend(label_names)

group_bound = [len(list(key.values())[0]) for key in xlabels]
group_bound = [0] + group_bound
group_boundaries = [sum(group_bound[:i+1]) for i in range(len(group_bound))]
group_boundaries.pop()

rsn_colors = ['m', 'b', 'y', 'c', 'r', 'g', 'w']

group_bound.pop(0)
label_colors = []
for ind, rep in enumerate(group_bound):
    label_colors += [rsn_colors[ind]] * rep
assert len(label_colors) == len(node_order), 'Number of colours do not match'

from mne.viz.circle import circular_layout
node_angles = circular_layout(label_names, label_names, start_pos=90,
                              group_boundaries=group_boundaries)

# Plot the graph using node colors from the FreeSurfer parcellation.
plot_connectivity_circle(con_res['wpli'], label_names, n_lines=300,
                         node_angles=node_angles, node_colors=label_colors,
                         title='Connectivity between standard RSNs')
# plt.savefig('circle.png', facecolor='black')
Beispiel #39
0
def main():
    parser = buildArgsParser()
    args = parser.parse_args()

    if not os.path.exists(args.matrix):
        parser.error("{0} is not a valid file path.".format(args.matrix))

    if not os.path.splitext(args.matrix)[1] == ".npy":
        parser.error("Connectivity matrix must be given in .npy format.")

    if not os.path.exists(args.row_map):
        parser.error("{0} is not a valid file path.".format(args.row_map))

    if os.path.splitext(args.row_map)[1] != ".pkl":
        parser.error("Name mapping must be given in a .pkl file.")

    if args.save and os.path.exists(args.save) and not args.force:
        parser.error("Output image: {0} already exists.\n".format(args.save) +
                     "Use -f to force overwriting.")

    con_mat = np.load(args.matrix)

    with open(args.row_map) as f:
        row_name_map = pickle.load(f)

    lh_tags = ['_lh_', 'Left']
    rh_tags = ['_rh_', 'Right']

    if args.clean_lbl:
        label_names = [row_name_map[k]['lut_name'] for k in sorted(row_name_map)]
        lh_tags = ['LH']
        rh_tags = ['RH']
    else:
        label_names = [row_name_map[k]['free_name'] for k in sorted(row_name_map)]
        lh_tags.append('-lh-')
        rh_tags.append('-rh-')

    lh_labels = [name for name in label_names if any(tag in name for tag in lh_tags)]
    rh_labels = [name for name in label_names if any(tag in name for tag in rh_tags)]

    # Validate if all labels were found
    uncut_labels = set(label_names) - set(lh_labels) - set(rh_labels)
    if len(uncut_labels) > 0:
        raise ValueError("Some labels were not filtered as Left or Right.")

    if args.sort_y:
        # TODO choose color
        # label_colors = [label.color for label in labels]
        label_ypos = []
        for name in lh_labels:
            label_ypos.append(find_mean_y_pos(row_name_map, name))
        lh_labels = [label for (ypos, label) in sorted(zip(label_ypos, lh_labels))]
        rh_labels = [label for (ypos, label) in sorted(zip(label_ypos, rh_labels))]

    node_order = list()
    node_order.extend(lh_labels[::-1])  # reverse the order
    node_order.extend(rh_labels)
    node_angles = circular_layout(label_names, node_order, start_pos=90,
                                  group_boundaries=[0, len(label_names) / 2])

    fig, axes = plot_connectivity_circle(con_mat, label_names, linewidth=1.5,
                                   interactive=True, vmin=0, vmax=1,
                                   node_angles=node_angles,
                                   title='All-to-all Connectivity')
    # plot_connectivity_circle(
    #                          node_colors=label_colors,
    #                          fontsize_colorbar=6,

    plt.show(block=True)
    if args.save:
        fig.savefig(args.save, facecolor='black')
Beispiel #40
0
            delta2 = range2[1] - range2[0]
            return (delta2 * (x - range1[0]) / delta1) + range2[0]

        # title
        tlt = 'Phase-Coherence Connectivity among DMN regions and V1 \n for \n State %d (%s)' % (
            k, freq)

        fig = plt.figure(num=None, figsize=(8, 8))
        plot_connectivity_circle(con,
                                 node_names,
                                 indices=indices,
                                 node_angles=node_angles,
                                 facecolor='white',
                                 textcolor='black',
                                 node_colors=node_colors,
                                 linewidth=3,
                                 node_edgecolor='black',
                                 colormap='RdBu_r',
                                 fontsize_names=12,
                                 fontsize_colorbar=12,
                                 vmin=vmin,
                                 vmax=vmax,
                                 colorbar_pos=(-0.7, 0.25),
                                 title=tlt,
                                 fig=fig)

        # save plot
        fig.savefig('fig/CirclePlt_' + fn_keys + '_Tvalue.png',
                    dpi=300,
                    transparent=True)
# Get the y-location of the label
label_ypos = list()
for name in lh_labels:
    idx = label_names.index(name)
    ypos = np.mean(labels[idx].pos[:, 1])
    label_ypos.append(ypos)

# Reorder the labels based on their location
lh_labels = [label for (ypos, label) in sorted(zip(label_ypos, lh_labels))]

# For the right hemi
rh_labels = [label[:-2] + 'rh' for label in lh_labels]

# Save the plot order and create a circular layout
node_order = list()
node_order.extend(lh_labels[::-1])  # reverse the order
node_order.extend(rh_labels)

node_angles = circular_layout(label_names, node_order, start_pos=90)

# Plot the graph using node colors from the FreeSurfer parcellation. We only
# show the 300 strongest connections.
plot_connectivity_circle(con, label_names, n_lines=300, node_angles=node_angles,
                         node_colors=label_colors,
                         title='All-to-All Connectivity left-Auditory '
                               'Condition')
import matplotlib.pyplot as plt
plt.savefig('circle.png', facecolor='black')
plt.show()
Beispiel #42
0
@author: bejar
"""

from mne.io import read_raw_bti
from mne.viz import circular_layout, plot_connectivity_circle
import numpy as np
import matplotlib.pyplot as plt

        
def plotOneSignal(signal):
    fig = plt.figure()
    minaxis=min(signal)
    maxaxis=max(signal)
    num=len(signal)    
    sp1=fig.add_subplot(111)
#    sp1.axis([0,num,minaxis,maxaxis])
    t = arange(0.0, num, 1)   
    sp1.plot(t,signal)
    plt.show() 
         

a=read_raw_bti('/home/bejar/MEG/ESQ21com10/ESQ21com10/MEG@-EKG/05@-25@-12@_10:00/1/c,rfhp1.0Hz')
cnames= a.info['ch_names'][0:148]

con=np.array([0.2,0.3,0.4,0.8,0.9])
lind=(np.array([12,79,123,104,97,61]),np.array([88,36,74,27,32,54]))

plot_connectivity_circle(con, cnames, indices=lind,title='Connections',n_lines=6,
                         linewidth=3,colormap='hot',vmin=0,vmax=1)
plt.savefig('circle.png', facecolor='black')
plt.show()