Beispiel #1
0
# visualize which regions are more central in this analysis.

from sklearn.metrics import pairwise_distances
from nltools.data import Adjacency
from nltools.mask import roi_to_brain
import pandas as pd
import numpy as np

sub_list = data.X['SubjectID'].unique()

# perform matrix multiplication to compute linear contrast for each subject
lin_contrast = []
for sub in sub_list:
    lin_contrast.append(data[data.X['SubjectID'] == sub] * np.array([1, -1,  0])) 

# concatenate list of Brain_Data instances into a single instance
lin_contrast = Brain_Data(lin_contrast) 

# Compute correlation distance between each ROI
dist = Adjacency(pairwise_distances(lin_contrast.extract_roi(mask), metric='correlation'), matrix_type='distance')

# Threshold functional connectivity and convert to Adjacency Matrix. Plot as heatmap
dist.threshold(upper=.4, binarize=True).plot()

# Convert Adjacency matrix to networkX instance
g = dist.threshold(upper=.4, binarize=True).to_graph()

# Compute degree centrality and convert back into Brain_Data instance.
degree_centrality = roi_to_brain(pd.Series(dict(g.degree())), mask_x)

degree_centrality.plot()
Beispiel #2
0
def test_adjacency(tmpdir):
    n = 10
    sim = np.random.multivariate_normal([0,0,0,0],[[1, 0.8, 0.1, 0.4],
                                         [0.8, 1, 0.6, 0.1],
                                         [0.1, 0.6, 1, 0.3],
                                         [0.4, 0.1, 0.3, 1]], 100)
    data = pairwise_distances(sim.T, metric='correlation')
    dat_all = []
    for t in range(n):
        tmp = data
        dat_all.append(tmp)
    sim_directed = np.array([[1, 0.5, 0.3, 0.4],
              [0.8, 1, 0.2, 0.1],
              [0.7, 0.6, 1, 0.5],
              [0.85, 0.4, 0.3, 1]])
    labels = ['v_%s' % (x+1) for x in range(sim.shape[1])]
    dat_single = Adjacency(dat_all[0], labels=labels)
    dat_multiple = Adjacency(dat_all, labels=labels)
    dat_directed = Adjacency(sim_directed, matrix_type='directed',
                             labels=labels)

    # Test automatic distance/similarity detection
    assert dat_single.matrix_type is 'distance'
    dat_single2 = Adjacency(1-data)
    assert dat_single2.matrix_type is 'similarity'
    assert not dat_directed.issymmetric
    assert dat_single.issymmetric

    # Test length
    assert len(dat_multiple) == dat_multiple.data.shape[0]
    assert len(dat_multiple[0]) == 1

    # Test Indexing
    assert len(dat_multiple[0]) == 1
    assert len(dat_multiple[0:4]) == 4
    assert len(dat_multiple[0, 2, 3]) == 3

    # Test basic arithmetic
    assert(dat_directed+5).data[0] == dat_directed.data[0]+5
    assert(dat_directed-.5).data[0] == dat_directed.data[0]-.5
    assert(dat_directed*5).data[0] == dat_directed.data[0]*5
    assert np.all(np.isclose((dat_directed+dat_directed).data,
                (dat_directed*2).data))
    assert np.all(np.isclose((dat_directed*2-dat_directed).data,
                dat_directed.data))

    # Test copy
    assert np.all(dat_multiple.data == dat_multiple.copy().data)

    # Test squareform & iterable
    assert len(dat_multiple.squareform()) == len(dat_multiple)
    assert dat_single.squareform().shape == data.shape
    assert dat_directed.squareform().shape == sim_directed.shape

    # Test write
    dat_multiple.write(os.path.join(str(tmpdir.join('Test.csv'))),
                        method='long')
    dat_multiple2 = Adjacency(os.path.join(str(tmpdir.join('Test.csv'))),
                        matrix_type='distance_flat')
    dat_directed.write(os.path.join(str(tmpdir.join('Test.csv'))),
                        method='long')
    dat_directed2 = Adjacency(os.path.join(str(tmpdir.join('Test.csv'))),
                        matrix_type='directed_flat')
    assert np.all(np.isclose(dat_multiple.data, dat_multiple2.data))
    assert np.all(np.isclose(dat_directed.data, dat_directed2.data))

    # Test mean
    assert isinstance(dat_multiple.mean(axis=0), Adjacency)
    assert len(dat_multiple.mean(axis=0)) == 1
    assert len(dat_multiple.mean(axis=1)) == len(np.mean(dat_multiple.data,
                axis=1))

    # Test std
    assert isinstance(dat_multiple.std(axis=0), Adjacency)
    assert len(dat_multiple.std(axis=0)) == 1
    assert len(dat_multiple.std(axis=1)) == len(np.std(dat_multiple.data,
                axis=1))

    # Test similarity
    assert len(dat_multiple.similarity(
                dat_single.squareform())) == len(dat_multiple)
    assert len(dat_multiple.similarity(dat_single.squareform(),
                metric='pearson')) == len(dat_multiple)
    assert len(dat_multiple.similarity(dat_single.squareform(),
                metric='kendall')) == len(dat_multiple)

    # Test distance
    assert isinstance(dat_multiple.distance(), Adjacency)
    assert dat_multiple.distance().square_shape()[0] == len(dat_multiple)

    # Test ttest
    mn, p = dat_multiple.ttest()
    assert len(mn) == 1
    assert len(p) == 1
    assert mn.shape()[0] == dat_multiple.shape()[1]
    assert p.shape()[0] == dat_multiple.shape()[1]

    # Test Threshold
    assert np.sum(dat_directed.threshold(upper=.8).data == 0) == 10
    assert dat_directed.threshold(upper=.8, binarize=True).data[0]
    assert np.sum(dat_directed.threshold(upper='70%', binarize=True).data) == 5
    assert np.sum(dat_directed.threshold(lower=.4, binarize=True).data) == 6

    # Test to_graph()
    assert isinstance(dat_directed.to_graph(), nx.DiGraph)
    assert isinstance(dat_single.to_graph(), nx.Graph)

    # Test Append
    a = Adjacency()
    a = a.append(dat_single)
    assert a.shape() == dat_single.shape()
    a = a.append(a)
    assert a.shape() == (2, 6)

    n_samples = 3
    b = dat_multiple.bootstrap('mean', n_samples=n_samples)
    assert isinstance(b['Z'], Adjacency)
    b = dat_multiple.bootstrap('std', n_samples=n_samples)
    assert isinstance(b['Z'], Adjacency)

    # Test plot
    f = dat_single.plot()
    assert isinstance(f, plt.Figure)
    f = dat_multiple.plot()
    assert isinstance(f, plt.Figure)

    # Test plot_mds
    f = dat_single.plot_mds()
    assert isinstance(f, plt.Figure)
Beispiel #3
0
roi_corr = 1 - pairwise_distances(rois, metric='correlation')

sns.heatmap(roi_corr, square=True, vmin=-1, vmax=1, cmap='RdBu_r')

# Now we need to convert this correlation matrix into a graph and calculate a centrality measure. We will use the `Adjacency` class from nltools as it has many functions that are useful for working with this type of data, including casting these type of matrices into networkx graph objects.
#
# We will be using the [networkx](https://networkx.github.io/documentation/stable/) python toolbox to work with graphs and compute different metrics of the graph.
#
# Let's calculate degree centrality, which is the total number of nodes each node is connected with. Unfortunately, many graph theory metrics require working with adjacency matrices, which are binary matrices indicating the presence of an edge or not. To create this, we will simply apply an arbitrary threshold to our correlation matrix.

# In[38]:

a = Adjacency(roi_corr,
              matrix_type='similarity',
              labels=[x for x in range(50)])
a_thresholded = a.threshold(upper=.6, binarize=True)

a_thresholded.plot()

# Okay, now that we have a thresholded binary matrix, let's cast our data into a networkx object and calculate the degree centrality of each ROI and make a quick plot of the graph.

# In[41]:

plt.figure(figsize=(20, 15))
G = a_thresholded.to_graph()
pos = nx.kamada_kawai_layout(G)
node_and_degree = G.degree()
nx.draw_networkx_edges(G, pos, width=3, alpha=.2)
nx.draw_networkx_labels(G, pos, font_size=14, font_color='darkslategray')

nx.draw_networkx_nodes(G,