Esempio n. 1
0
def view_connectome_with_nilearn(G,
                                 edge_attribute="weight",
                                 edge_cmap="Spectral_r",
                                 symmetric_cmap=True,
                                 edgewidth=6.0,
                                 node_size=3.0,
                                 node_colour_att=None,
                                 node_colour='black'):
    #   node_colour_list=None):
    """
    Plot a BrainNetwork using :func:`nilearn.plotting.view_connectome()` tool.

    Parameters
    ----------
    G : :class:`networkx.Graph`
        G should have nodal locations in MNI space indexed by nodal
        attribute "centroids"
    node_colour_att : str, optional
        index a nodal attribute to scale node colour by
    edge_attribute : str, optional
        index an edge attribute to scale edge colour by

    other parameters are passed to :func:`nilearn.plotting.view_connectome()`
    """
    adjacency_matrix, node_coords, colour_list, z = graph_to_nilearn_array(
        G, edge_attribute=edge_attribute, node_colour=node_colour_att)
    return plotting.view_connectome(adjacency_matrix,
                                    node_coords,
                                    threshold=None,
                                    cmap=edge_cmap,
                                    symmetric_cmap=symmetric_cmap,
                                    linewidth=edgewidth,
                                    marker_size=node_size)
Esempio n. 2
0
def plot_connectome(mat, label_map, threshold='95%', GS=True):

    if GS:
        mat = mat[1:, 1:]  #fisrt row and column is global signal
    coords = plotting.find_parcellation_cut_coords(label_map)
    view = plotting.view_connectome(mat, coords, threshold=threshold)
    view.open_in_browser()
def getConnectome(imgPath=None,
                  atlasPath=None,
                  viewInBrowser=False,
                  displayCovMatrix=False):
    """
    Gets the connectome of a functional MRI scan
    imgPath -> absolute or relative path to the .nii file
    atlasPath -> download path for the reference MSDL atlas
    viewInBrowser (optional, default=False) -> if True, opens up an interactive viewer in the browser
    displayCovMatrix (optional, default=False) -> display the inverse covariance matrix
    Returns a tuple of shape (estimator, atlas)
    """
    # Download the reference atlas
    atlas = datasets.fetch_atlas_msdl(data_dir=atlasPath)
    # Loading atlas image stored in 'maps'
    atlasFilename = atlas['maps']
    # Get the time series for the fMRI scan
    masker = NiftiMapsMasker(maps_img=atlasFilename,
                             standardize=True,
                             memory='nilearn_cache',
                             verbose=5)
    timeSeries = masker.fit_transform(imgPath)
    # Compute the connectome using sparse inverse covariance
    estimator = GraphicalLassoCV()
    estimator.fit(timeSeries)
    if (displayCovMatrix):
        labels = atlas['labels']
        plotting.plot_matrix(estimator.covariance_,
                             labels=labels,
                             figure=(9, 7),
                             vmax=1,
                             vmin=-1,
                             title='Covariance')
        plotting.plot_matrix(estimator.precision_,
                             labels=labels,
                             figure=(9, 7),
                             vmax=1,
                             vmin=-1,
                             title='Inverse covariance (Precision)')
        #covPlot.get_figure().savefig('Covariance.png')
        # precPlot.get_figure().savefig('Inverse Covariance.png')
    if (viewInBrowser):
        coords = atlas.region_coords
        view = plotting.view_connectome(-estimator.precision_, coords, '60.0%')
        #view.save_as_html(file_name='Connectome Test.html')
        view.open_in_browser()
    return (estimator, atlas)
Esempio n. 4
0
def plot_connectivity_matrix(matrix_data,matrix_name:str):
'''
The connectivity_matrix nilearn implementation allows the visualization of the matrices based on the atlas and matrix selected.

'''
    # Plot the tangent matrix
    # The labels of the MSDL Atlas that we are using 
    # Data from the atlas used (in the given example MSDL)
    atlas = datasets.fetch_atlas_msdl()
    # Loading atlas data stored in 'labels'
    labels = atlas['labels']
    # Loading atlas coordinates
    coords = atlas.region_coords
    
    font = {'family': 'serif',
            'color':  'black',
            'weight': 'bold',
            'size': 12}
    
    tt = plt.figure(1,figsize=(7,6))

 
    np.fill_diagonal(matrix_data, 0)
    plt.imshow(matrix_data, interpolation='None', cmap='RdYlBu_r', vmax=.000002, vmin=-.000002)
    plt.yticks(range(len(atlas.labels)),labels, fontsize=10, weight='bold');
    plt.xticks( range(len(atlas.labels)), labels, rotation=90, fontsize=10, weight='bold');
    plt.title(str(matrix_name)+'_msdl',fontdict=font)
    plt.colorbar(shrink=0.8)
    
    tt2 = plt.figure(2)   
    view=plotting.view_connectome(matrix_data,coords, node_size=5.0, edge_threshold='99.5%')    
    

    plt.show()    
   
    return view
Esempio n. 5
0
"""weights: 168 recordings, 39 roi, but it transposed

Brain Synchrony: Connectome
"""

from nilearn.connectome import ConnectivityMeasure

correlation_measure = ConnectivityMeasure(kind='correlation')
correlation_matrix = correlation_measure.fit_transform([roi_time_series])[0]

np.fill_diagonal(correlation_matrix, 0)
plotting.plot_matrix(correlation_matrix, labels=msdl_atlas.labels,
                     vmax=0.8, vmin=-0.8, colorbar=True)

plotting.view_connectome(correlation_matrix, edge_threshold=0.2,
                         node_coords=msdl_atlas.region_coords)

"""###Noise sources"""

pd.read_table(development_dataset.confounds[0]).head()

corrected_roi_time_series = masker.transform(
    development_dataset.func[0], confounds=development_dataset.confounds[0])
corrected_correlation_matrix = correlation_measure.fit_transform(
    [corrected_roi_time_series])[0]
np.fill_diagonal(corrected_correlation_matrix, 0)
plotting.plot_matrix(corrected_correlation_matrix, labels=msdl_atlas.labels,
                     vmax=0.8, vmin=-0.8, colorbar=True)

plotting.view_connectome(corrected_correlation_matrix, edge_threshold=0.2,
                         node_coords=msdl_atlas.region_coords)
Esempio n. 6
0
def view_connectome_3d(G,
                       edge_threshold="98%",
                       edge_cmap="Spectral_r",
                       symmetric_cmap=False,
                       linewidth=6.,
                       node_size=3.):
    """
    Insert a 3d plot of a connectome into an HTML page.

    Plot a BrainNetwork using :func:`nilearn.plotting.view_connectome()` tool.

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

    edge_threshold : str, number or None, optional (default="2%")
        If None, no thresholding.
        If it is a number only connections of amplitude greater
        than threshold will be shown.
        If it is a string it must finish with a percent sign,
        e.g. "25.3%", and only connections of amplitude above the
        given percentile will be shown.

    edge_cmap : str or matplotlib colormap, optional
        Colormap for displaying edges.

    symmetric_cmap : bool, optional (default=False)
        Make colormap symmetric (ranging from -vmax to vmax).

    linewidth : float, optional (default=6.)
        Width of the lines that show connections.

    node_size : float, optional (default=3.)
        Size of the markers showing the seeds in pixels.

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

    """

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

    # plot connectome
    ConnectomeView = plotting.view_connectome(adjacency_matrix=adj_matrix,
                                              node_coords=node_coords,
                                              edge_threshold=edge_threshold,
                                              edge_cmap=edge_cmap,
                                              symmetric_cmap=symmetric_cmap,
                                              linewidth=linewidth,
                                              node_size=node_size)

    return ConnectomeView
Esempio n. 7
0
plt.figure(figsize=(10, 10))
# Mask out the major diagonal
numpy.fill_diagonal(correlation_matrix, 0)
plt.imshow(correlation_matrix,
           interpolation="nearest",
           cmap="RdBu_r",
           vmax=0.8,
           vmin=-0.8)
plt.colorbar()
# And display the labels
x_ticks = plt.xticks(range(len(labels)), labels, rotation=90)
y_ticks = plt.yticks(range(len(labels)), labels)

#coords = atlas.region_coords

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

plotting.show()

view = plotting.view_connectome(correlation_matrix,
                                atlas_coords_,
                                edge_threshold="80%")
view.save_as_html('t.html')
view.open_in_browser()
node = np.unique(node)

# 显示连接网络
weight_filter = weight[id_mat[0], id_mat[1]]
wei_node = np.hstack([node1, node2]).T
wei_node = np.vstack([wei_node, np.hstack([weight_filter, weight_filter])]).T

nodes = [{"name": nd, "symbolSize": np.sum(np.abs(np.float64(wei_node[:,1][np.in1d(wei_node[:,0], str(nd))])))*10} for nd in node]
links = [{"source": str(nd1), "target": str(nd2)} for (nd1, nd2) in zip(node1, node2)]
graph= (
        Graph()
        .add("", nodes,links, repulsion=1000)
        .set_global_opts(title_opts=opts.TitleOpts(title="前0.1%的权重"))
    )
graph.render()


# 只显示靠前的权重
plt.imshow(weight, cmap="RdBu_r")
plt.colorbar()

plotting.plot_connectome(weight, node_coords, annotate=True)

view = plotting.view_connectome(weight, node_coords)
view.open_in_browser()


from chord import Chord
names = [str(i) for i in range(246)]
chrod_fig = Chord(weight, names, colors="d3.schemeSet2").to_html("chrod_fig.html")
Esempio n. 9
0
##############################################################################
# 3D visualization in a web browser
# ---------------------------------
# An alternative to :func:`nilearn.plotting.plot_surf_roi` is to use
# :func:`nilearn.plotting.view_surf` for more interactive
# visualizations in a web browser. See :ref:`interactive-surface-plotting` for
# more details.

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

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

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

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

view = plotting.view_connectome(corr, coordinates, edge_threshold='90%')
# uncomment this to open the plot in a web browser:
# view.open_in_browser()
view
Esempio n. 10
0
def plotConnectome(matrix, coords, networks, out_folder, base_name, min_r):
    """Creates brain plot with connections according to minimum R value
	param matrix: two dimensional array. The correlation matrix
	param coords : list. Coordinates of the networks
	param networks: list. Networks names.
	param out_folder: string. Output folder for brain plot
	param base_name: string. Base name
	param min_r: float. The minimun R value for connection plotting.
	return: None
	"""
    colors = []
    patches_list = []
    index2network = {}
    last_index = 0
    for network in networks:
        network_color = [net_dic.labelToColorDic[network]] * len(
            list(net_dic.dic[network]))
        colors = colors + network_color
        for i in range(last_index,
                       last_index + len(list(net_dic.dic[network]))):
            index2network[i] = network
            last_index = i + 1
        network_patch = mpatches.Patch(color=net_dic.labelToColorDic[network],
                                       label=network)
        patches_list.append(network_patch)
    correlated_coords = {}
    for i in range(1, len(matrix)):
        for j in range(i):
            if (matrix[i][j] >= min_r):
                correlated_coords[matrix[i][j]] = ({
                    index2network[i]: coords[i]
                }, {
                    index2network[j]: coords[j]
                })
    plot_name = out_folder + "/" + base_name + "_brain_plot" + str(
        networks) + ".png"
    if (len(correlated_coords) > 0):
        fig = plt.figure()
        title = "Threshold : " + str(min_r)
        plotting.plot_connectome(adjacency_matrix=matrix,
                                 node_coords=coords,
                                 title=title,
                                 node_color=colors,
                                 colorbar=True,
                                 edge_threshold=min_r,
                                 node_size=5,
                                 edge_vmin=-1,
                                 edge_vmax=1,
                                 figure=fig,
                                 display_mode='lyrz')
        fig.legend(handles=patches_list, loc="upper center")
        fig.savefig(plot_name)
        plt.close()
    view = plotting.view_connectome(matrix,
                                    coords,
                                    edge_threshold=min_r,
                                    node_size=7,
                                    symmetric_cmap=True)
    html_name = out_folder + "/" + base_name + "_brain_plot" + str(
        networks) + ".html"
    view.save_as_html(html_name)
Esempio n. 11
0
significantconnectDiff = np.multiply(significantconnectDiff, pvaluesDiff)
plot_matrix(significantconnectDiff,
            labels=labels,
            colorbar=True,
            tri='full',
            reorder=False)

significantconnectOdorVsOff = 1 * (pvaluesOdorVsOff <= 0.05)
plot_matrix(significantconnectOdorVsOff,
            title='Significant Connect',
            labels=labels,
            colorbar=True,
            tri='full',
            reorder=False)

#---- Show plotted matrixes ------
show()

#------------------------------------------------------------------------------
# Read channel locations
#------------------------------------------------------------------------------
# coords = read_channLoc(channelLocationsPath)
coords = read_channLocMNI(channelLocationsPath)

#------------------------------------------------------------------------------
# Show visualization in browser
#------------------------------------------------------------------------------
view = view_connectome(significantconnectDiff, coords, edge_threshold='95%')
#view = view_connectome(significantconnectOdorVsOff, coords, edge_threshold='90%')
view.open_in_browser()
x = input("Done...press to exit")
Esempio n. 12
0
]
masked_data = np.asarray(masked_data)
print('masked data shape:', masked_data[0].shape)

###############################################################################
# Compute and plot connectivity matrix

from nilearn.connectome import ConnectivityMeasure

correlation_measure = ConnectivityMeasure(kind='correlation').fit(masked_data)

plotting.plot_matrix(correlation_measure.mean_, tri='lower')

###############################################################################
plotting.view_connectome(correlation_measure.mean_,
                         msdl.region_coords,
                         threshold='90%',
                         cmap='cold_hot')

###############################################################################
# Age group classification with scikit-learn
# ------------------------------------------
# `ConnectivityMeasure` can be used to extract features for supervised learning
from sklearn.svm import LinearSVC
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import cross_val_score

kinds = ['correlation', 'partial correlation', 'tangent']
groups = [pheno['Child_Adult'] for pheno in rest_data.phenotypic]
classes = LabelEncoder().fit_transform(groups)
                     figure=(9, 7), vmax=1, vmin=-1,
                     title='Sparse inverse covariance')

##############################################################################
# And now display the corresponding graph
# ----------------------------------------
plotting.plot_connectome(-estimator.precision_, coords,
                         title='Sparse inverse covariance')

plotting.show()

##############################################################################
# 3D visualization in a web browser
# ---------------------------------
# An alternative to :func:`nilearn.plotting.plot_connectome` is to use
# :func:`nilearn.plotting.view_connectome` that gives more interactive
# visualizations in a web browser. See :ref:`interactive-connectome-plotting`
# for more details.


view = plotting.view_connectome(-estimator.precision_, coords)

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

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

view
Esempio n. 14
0
    os.makedirs(common_mat_folder)

#Plot the common matrices
fig = plt.figure()
plotting.plot_matrix(common_cov_mat,
                     colorbar=True,
                     labels=labels,
                     figure=fig,
                     title='Common covariance matrix')
fig.savefig(common_mat_folder + "/common_cov_matrix_" + str(argList) + ".png")
fig2 = plt.figure()
plotting.plot_matrix(common_cor_mat,
                     colorbar=True,
                     labels=labels,
                     vmin=-1.,
                     vmax=1.,
                     figure=fig2,
                     title='Common correlation matrix')
fig2.savefig(common_mat_folder + "/common_cor_matrix_" + str(argList) + ".png")
fig3 = plt.figure()
plotting.plot_connectome(adjacency_matrix=common_cor_mat,
                         node_coords=coords,
                         edge_threshold="80%",
                         colorbar=True,
                         edge_vmin=-1,
                         edge_vmax=1,
                         figure=fig3,
                         title=str(argList))
fig3.savefig(common_mat_folder + "/brain_plot_" + str(argList) + ".png")
view = plotting.view_connectome(common_cor_mat, coords, threshold="80%")
view.open_in_browser()
                         title="Connectivity projected on hemispheres",
                         display_mode='lyrz')

plotting.show()


##############################################################################
# 3D visualization in a web browser
# ---------------------------------
# An alternative to :func:`nilearn.plotting.plot_connectome` is to use
# :func:`nilearn.plotting.view_connectome`, which gives more interactive
# visualizations in a web browser. See :ref:`interactive-connectome-plotting`
# for more details.


view = plotting.view_connectome(partial_correlation_matrix, dmn_coords)

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


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

view


##########################################################################
# Extract signals on spheres from an atlas
# ----------------------------------------
                     vmin=-1,
                     title='Sparse inverse covariance')

##############################################################################
# And now display the corresponding graph
# ----------------------------------------
plotting.plot_connectome(-estimator.precision_,
                         coords,
                         title='Sparse inverse covariance')

plotting.show()

##############################################################################
# 3D visualization in a web browser
# ---------------------------------
# An alternative to :func:`nilearn.plotting.plot_connectome` is to use
# :func:`nilearn.plotting.view_connectome` that gives more interactive
# visualizations in a web browser. See :ref:`interactive-connectome-plotting`
# for more details.

view = plotting.view_connectome(-estimator.precision_, coords)

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

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

view
Esempio n. 17
0
def plot_all(matrix,
             title,
             time_series,
             coords_file,
             labels_file,
             output_dir,
             clean=True,
             vmin=None,
             vmax=None,
             nan_matrix=False,
             pconn_dummy=False,
             pconn_fname='correlation_measure-mean_.pconn.nii'):
    # Before anything else, save matrix (i.e. corelation_measure.mean) as binary npy
    # file (e.g. to manually create pconn CIFTIs)
    create_dir_if_not_exist(output_dir)
    matrix_fname = os.path.join(output_dir, 'correlation_measure-mean_.npy')
    np.save(matrix_fname, matrix)
    # Build pconn file
    if pconn_dummy:
        pconn_fname = os.path.join(output_dir, pconn_fname)
        print("Saving pconn file to {}...".format(pconn_fname))
        save_pconn(matrix, pconn_dummy, pconn_fname)

    plot_title = title + ", n = {}".format(len(time_series))
    plot_title_orig = plot_title  # We might modify plot_title later on
    coordinates = np.loadtxt(coords_file)
    labels = load_list_from_file(labels_file)

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    if nan_matrix is False:
        nan_matrix = matrix
    timer("tic")
    np.fill_diagonal(matrix, 0)
    # plotting.plot_matrix(nan_matrix, colorbar=True, figure=(40, 40), labels=labels, auto_fit=True, vmin=vmin, vmax=vmax)
    # plt.title(plot_title, fontsize=50)
    # fig_fname = "{}/correlation_matrix.svg".format(output_dir)
    # plt.savefig(fig_fname)
    # plt.clf()

    # We need to introduce this as clean_matrix does something unexpected with np.nan values
    # and plot_connectome specifically cannot deal with this
    if clean:
        print("Cleaning matrix ...")
        mean_roi_matrix = clean_matrix(matrix)
        plot_title = plot_title + " (clean)"
        fname_clean = "clean"
    else:
        mean_roi_matrix = matrix
        fname_clean = "nonclean"

    fig_fname = os.path.join(output_dir,
                             "correlation_matrix_{}".format(fname_clean))
    print("Plotting matrix...")
    plotting.plot_matrix(mean_roi_matrix,
                         colorbar=True,
                         figure=(40, 40),
                         labels=labels,
                         auto_fit=True,
                         vmin=vmin,
                         vmax=vmax)
    plt.title(plot_title, fontsize=50)
    print("Saving plot to {}.svg...".format(fig_fname))
    plt.savefig("{}.svg".format(fig_fname))
    #plt.savefig("{}.png".format(fig_fname), dpi=1080) # PNG export does not seem to work in this case. Who knows..
    timer("toc", name="plotting and saving matrices")
    plt.clf()
    print("Plotting connectome ...")
    timer("tic")
    # Manually create new figure because for some reason plotting.plot_connectome() won't
    # accept figure size like plotting.plot_matrix()
    connectome_figure = plt.figure(figsize=(10, 5))
    # plot_connectome does not process np.nan values, we still have to pass np.nan_to_num(matrix) to plot_all function
    plotting.plot_connectome(np.nan_to_num(mean_roi_matrix),
                             coordinates,
                             figure=connectome_figure,
                             colorbar=True,
                             node_size=30,
                             title=plot_title,
                             edge_vmin=vmin,
                             edge_vmax=vmax)
    fig_fname = os.path.join(output_dir,
                             "roi_connectome_{}".format(fname_clean))
    plt.savefig("{}.svg".format(fig_fname))
    plt.savefig("{}.png".format(fig_fname), dpi=1080)
    timer("toc", name="plotting and saving connectome")
    plt.clf()

    html_fname = os.path.join(output_dir,
                              "roi_connectome_90_{}.html".format(fname_clean))
    print("Constructing interactive HTML connectome...")
    timer("tic")
    web_connectome = plotting.view_connectome(mean_roi_matrix,
                                              coordinates,
                                              edge_threshold="99%",
                                              node_size=6,
                                              symmetric_cmap=False)
    html_fname = os.path.join(output_dir,
                              "roi_connectome_{}.html".format(fname_clean))
    web_connectome.save_as_html(html_fname)
    timer("toc", name="plotting and saving HTML connectome")
# ----------------------------------------
from nilearn import plotting
coords = atlas.region_coords

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

plotting.show()

##############################################################################
# 3D visualization in a web browser
# ---------------------------------
# An alternative to :func:`nilearn.plotting.plot_connectome` is to use
# :func:`nilearn.plotting.view_connectome` that gives more interactive
# visualizations in a web browser. See :ref:`interactive-connectome-plotting`
# for more details.


view = plotting.view_connectome(correlation_matrix, coords, threshold='80%')

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

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

view
Esempio n. 19
0
def plot_palm_new(palm_results,
                  title,
                  coords,
                  labels,
                  alpha=1.3,
                  scale=False,
                  n_best_values=5,
                  lower_is_better=False,
                  output_dir=None,
                  pconn_dummy=False,
                  pconn_fname='connectome.pconn.nii'):
    """
    Take PALM results (file or NumPy array) and plot its suprathreshold values (default 
    threshold value: alpha=1.3) in a correlation matrix and as a connectome visualisation.
    
    Use lower_is_better=True if you use standard p values and not log p or 1-p
    """
    if isinstance(palm_results, str):
        # We assume the argument is a filename if it's a string
        data = get_nimg_data(palm_results)
        info = [
            "PALM results: {}".format(palm_results)
        ]  # This list holds all the informational messages we may later write into info.txt
    else:
        data = palm_results
        info = [
            "PALM results:"
        ]  # This list holds all the informational messages we may later write into info.txt
    # Get rid of superfluous dimensions
    adjmatrix = data[:, :, 0, 0]
    # Plot all p values
    fig_matrix = plotting.plot_matrix(adjmatrix,
                                      colorbar=True,
                                      figure=(40, 40),
                                      labels=labels,
                                      auto_fit=True).figure
    fig_connectome = plotting.plot_connectome(symmetrize(adjmatrix,
                                                         mirror_lower=True),
                                              coords,
                                              colorbar=True,
                                              node_size=15,
                                              title=title)
    web_connectome = plotting.view_connectome(adjmatrix,
                                              coords,
                                              node_size=6,
                                              symmetric_cmap=False)

    # Get highest/lowest indices and check if there are any suprathreshold values
    if lower_is_better:
        best_indices = get_extreme_indices(abs(adjmatrix),
                                           n_best_values,
                                           get_smallest=True)
        adjmatrix[adjmatrix ==
                  0] = np.nan  # See get_extreme_indices() for rationale
        nsupthr = len(adjmatrix[abs(adjmatrix) <= alpha])
    else:
        best_indices = get_extreme_indices(abs(adjmatrix), n_best_values)
        nsupthr = len(adjmatrix[abs(adjmatrix) >= alpha])
    msg = "{} best values: {}".format(n_best_values, adjmatrix[best_indices])
    info.append(msg)
    print(msg)
    if nsupthr == 0:
        msg = "\nNo values survive the threshold of {}.".format(alpha)
        info.append(msg)
        print(msg)
        fig_matrix_clean, fig_connectome_clean, web_connectome_clean = None, None, None
        labels_clean = ""
        coords_clean = ""
    else:
        msg = "Number of values to survive the threshold of {}: {}".format(
            alpha, nsupthr)
        info.append(msg)
        print(msg)
        # Purge matrix, coordinates and labels of subthreshold values
        adjmatrix_clean = adjmatrix.copy()
        if lower_is_better:
            adjmatrix_clean[abs(adjmatrix) > alpha] = np.nan
        else:
            adjmatrix_clean[abs(adjmatrix_clean) < alpha] = np.nan
        supthr_indices = np.argwhere(~np.isnan(adjmatrix_clean))
        labels_clean = [
            "" if i not in supthr_indices else x for i, x in enumerate(labels)
        ]
        coords_clean = [
            [np.nan, np.nan, np.nan] if i not in supthr_indices else x
            for i, x in enumerate(coords)
        ]

        fig_matrix_clean = plotting.plot_matrix(adjmatrix_clean,
                                                colorbar=True,
                                                figure=(40, 40),
                                                labels=labels_clean,
                                                auto_fit=True).figure
        fig_connectome_clean = plotting.plot_connectome(
            symmetrize(np.nan_to_num(adjmatrix_clean), mirror_lower=True),
            coords_clean,
            figure=plt.figure(figsize=(10, 5)),
            colorbar=True,
            node_size=30,
            title=title)
        web_connectome_clean = plotting.view_connectome(adjmatrix_clean,
                                                        coords_clean,
                                                        node_size=6,
                                                        symmetric_cmap=False)

    if output_dir:
        create_dir_if_not_exist(output_dir)
        print("Saving plots to {}...".format(output_dir))
        fig_matrix.savefig(os.path.join(output_dir, "matrix.svg"))
        if fig_matrix_clean:
            fig_matrix_clean.savefig(
                os.path.join(output_dir, "matrix_clean.svg"))
        fig_connectome.savefig(os.path.join(output_dir, "connectome.svg"))
        if fig_connectome_clean:
            fig_connectome_clean.savefig(
                os.path.join(output_dir, "connectome_clean.svg"))
        web_connectome.save_as_html(
            os.path.join(output_dir, "web_connectome.html"))
        if web_connectome_clean:
            web_connectome_clean.save_as_html(
                os.path.join(output_dir, "web_connectome_clean.html"))

        info.append("")
        info.append("Top 5 connections according to p value:")
        info.append("Node A (label) <-> Node B (label): p value")
        for i in range(5):
            x = best_indices[0][i]
            y = best_indices[1][i]
            msg = "{} ({}) <-> {} ({}): {}".format(x + 1, labels[x], y + 1,
                                                   labels[y], adjmatrix[x, y])
            info.append(msg)
        save_list_to_file(info, os.path.join(output_dir, "info.txt"))

        if labels_clean:
            save_list_to_file(labels_clean,
                              os.path.join(output_dir, "labels_clean"))
            np.savetxt(os.path.join(output_dir, "coords_clean"), coords_clean)

        if pconn_dummy:
            save_pconn(adjmatrix, pconn_dummy,
                       os.path.join(output_dir, pconn_fname))

    for entry in info:
        print(entry)
    return fig_matrix, fig_matrix_clean, fig_connectome, fig_connectome_clean, web_connectome, web_connectome_clean, labels_clean, coords_clean
Esempio n. 20
0
                         title="Default Mode Network Connectivity")

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

plotting.show()

##############################################################################
# 3D visualization in a web browser
# ---------------------------------
# An alternative to :func:`nilearn.plotting.plot_connectome` is to use
# :func:`nilearn.plotting.view_connectome` that gives more interactive
# visualizations in a web browser. See :ref:`interactive-connectome-plotting`
# for more details.

view = plotting.view_connectome(partial_correlation_matrix, dmn_coords)

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

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

view
Esempio n. 21
0
                         title='fsaverage Destrieux atlas')
plotting.show()

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

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

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

view

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

view = plotting.view_connectome(corr, coordinates, edge_threshold='90%')
# uncomment this to open the plot in a web browser:
# view.open_in_browser()
view
from nilearn import plotting
coords = atlas.region_coords

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

plotting.show()

##############################################################################
# 3D visualization in a web browser
# ---------------------------------
# An alternative to :func:`nilearn.plotting.plot_connectome` is to use
# :func:`nilearn.plotting.view_connectome` that gives more interactive
# visualizations in a web browser. See :ref:`interactive-connectome-plotting`
# for more details.

view = plotting.view_connectome(correlation_matrix, coords, threshold='80%')

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

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

view
Esempio n. 23
0
#%% plotting stuff
# take colors
colors = pd.read_csv('/home/or/Downloads/shenPar/shen_268_parcellation_networklabels_colors.csv')
color_node = list(colors["color"])
# plot in specific region as seed
# create 268 x 268 array
empty = np.zeros((268,268))
# take only left amygdala connections
empty[227,:] = trauma_1st_thr[227,:]
empty[:,227] = trauma_1st_thr[:,227]
# plot
plotting.plot_connectome(empty, coords, edge_threshold='95%', colorbar=True, black_bg = False, annotate = True, node_color = color_node)

# plot in browser
view = plotting.view_connectome(empty, coords, threshold='90%') 
view.open_in_browser() 
view_color.open_in_browser()


#%% Run Network Based Analysis
# first reshape the matrix dimensions (right now its [subs,x,y]) to [x,y,subs]
trt1Reshape = np.moveaxis(np.array(trauma_1st_ses),0,-1)
trt2Reshape = np.moveaxis(np.array(trauma_2_1st_ses),0,-1)

from bct import nbs
# we compare ket1 and ket3
pval, adj, _ = nbs.nbs_bct(trt1Reshape, trt2Reshape, thresh=2.5, tail='both',k=500, paired=True, verbose = True)
# one network is different

#%% compare sad to trauma 1