-
Notifications
You must be signed in to change notification settings - Fork 3
/
functions.py
2181 lines (1777 loc) · 70.5 KB
/
functions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Created on Tue May 24 10:53:22 2022
This file contains function used to load the required data, run the analyses
and plot the figures presented in 'Assortative mixing in micro-architecturally
annotated brain connectomes'.
@author: Vincent Bazinet
"""
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pickle
import seaborn as sns
from tqdm import trange, tqdm
from brainspace.null_models.moran import MoranRandomization
from matplotlib import cm
from matplotlib.ticker import MultipleLocator
from matplotlib.colors import is_color_like, ListedColormap, to_rgba
from palettable.colorbrewer.diverging import Spectral_11_r, RdBu_11_r
from palettable.colorbrewer.sequential import Reds_3, Blues_3, GnBu_9
from palettable.cartocolors.sequential import SunsetDark_7
from scipy.stats import pearsonr, zscore
from sklearn.linear_model import LinearRegression
from sklearn.decomposition import PCA
from statsmodels.stats.multitest import multipletests
from joblib import Parallel, delayed
from itertools import repeat, chain, combinations
from netneurotools.plotting import plot_fsaverage
'''
ASSORTATIVITY FUNCTIONS
'''
def weighted_assort(A, M, N=None, directed=True, normalize=True):
'''
Function to compute the weighted Pearson correlation between the attributes
of the nodes connected by edges in a network (i.e. weighted assortativity).
This function also works for binary networks.
Parameters
----------
A : (n,n) ndarray
Adjacency matrix of our network.
M : (n,) ndarray
Vector of nodal attributes.
N : (n,) ndarray
Second vector of nodal attributes (optional)
directed: bool
Whether the network is directed or not. When the network is not
directed, setting this parameter to False will increase the speed of
the computations.
normalize: bool
If False, the adjacency weights won't be normalized to make its weights
sum to 1. This should only be set to False if the matrix has been
normalized already. Otherwise, the result will not be the assortativity
coefficent. This is useful when we want to compute the assortativity
of thousands annotations in a row. In that case, not having to
normalize the adjacency matrix each time makes the function much
faster.
Returns
-------
ga : float
Weighted assortativity of our network, with respect to the vector
of attributes
'''
if (directed) and (N is None):
N = M
# Normalize the adjacency matrix to make weights sum to 1
if normalize:
A = A / A.sum(axis=None)
# zscores of in-annotations
k_in = A.sum(axis=0)
mean_in = np.sum(k_in * M)
sd_in = np.sqrt(np.sum(k_in * ((M-mean_in)**2)))
z_in = (M - mean_in) / sd_in
# zscores of out-annotations (if directed or N is not None)
if N is not None:
k_out = A.sum(axis=1)
mean_out = np.sum(k_out * N)
sd_out = np.sqrt(np.sum(k_out * ((N-mean_out)**2)))
z_out = (N - mean_out) / sd_out
else:
z_out = z_in
# Compute the weighted assortativity as a sum of z-scores
ga = (z_in[np.newaxis, :] * z_out[:, np.newaxis] * A).sum()
return ga
def wei_assort_batch(A, M_all, N_all=None, n_batch=100, directed=True):
'''
Function to compute the weighted assortativity of a "batch" of attributes
on a single network.
Parameters
----------
A : (n, n) ndarray
Adjacency matrix
M_all : (m, n) ndarray
Attributes
n_batch: int
Number of attribute in each batch.
directed: bool
Whether the network is directed or not. When the network is not
directed, setting this parameter to False will increase the speed of
the computations.
Returns
-------
'''
n_attributes, n_nodes = M_all.shape
ga = np.array([])
# Create batches of annotations
if N_all is not None:
M_batches = zip(np.array_split(M_all, n_batch),
np.array_split(N_all, n_batch))
elif directed:
N_all = True
M_batches = zip(np.array_split(M_all, n_batch),
np.array_split(M_all, n_batch))
else:
M_batches = np.array_split(M_all, n_batch)
# Normalize the adjacency matrix to make weights sum to 1
A = A / A.sum(axis=None)
# Compute in- and out- degree (if directed)
k_in = A.sum(axis=0)
if (directed) or (N_all is not None):
k_out = A.sum(axis=1)
for M in M_batches:
if N_all is not None:
M, N = M
# Z-score of in-annotations
n_att, _ = M.shape
mean_in = (k_in[np.newaxis, :] * M).sum(axis=1)
var_in = (k_in[np.newaxis, :] * ((M - mean_in[:, np.newaxis])**2)).sum(axis=1) # noqa
sd_in = np.sqrt(var_in)
z_in = (M - mean_in[:, np.newaxis]) / sd_in[:, np.newaxis]
# Z-score of out-annotations
if N_all is not None:
n_att, _ = N.shape
mean_out = (k_out[np.newaxis, :] * N).sum(axis=1)
var_out = (k_out[np.newaxis, :] * ((N - mean_out[:, np.newaxis])**2)).sum(axis=1) # noqa
sd_out = np.sqrt(var_out)
z_out = (N - mean_out[:, np.newaxis]) / sd_out[:, np.newaxis]
else:
z_out = z_in
# Compute assortativity
ga_batch = A[np.newaxis, :, :] * z_out[:, :, np.newaxis] * z_in[:, np.newaxis, :] # noqa
ga_batch = ga_batch.sum(axis=(1, 2))
# Add assortativity results to ga
ga = np.concatenate((ga, ga_batch), axis=0)
return ga
'''
UTILITY FUNCTIONS
'''
def load_data(path):
'''
Utility function to load pickled dictionary containing the data used in
these experiments.
Parameters
----------
path: str
File path to the pickle file to be loaded.
Returns
-------
data: dict
Dictionary containing the data used in these experiments
'''
with open(path, 'rb') as handle:
data = pickle.load(handle)
return data
def save_data(data, path):
'''
Utility function to save pickled dictionary containing the data used in
these experiments.
Parameters
----------
data: dict
Dictionary storing the data that we want to save.
path: str
path of the pickle file
'''
with open(path, 'wb') as handle:
pickle.dump(data, handle, protocol=pickle.HIGHEST_PROTOCOL)
def standardize_scores(surr, emp, axis=None, ignore_nan=False):
'''
Utility function to standardize a score relative to a null distribution.
Parameters
----------
perm: array-like
Null distribution of scores.
emp: float
Empirical score.
'''
if ignore_nan:
return (emp - np.nanmean(surr, axis=axis)) / np.nanstd(surr, axis=axis)
else:
return (emp - surr.mean(axis=axis)) / surr.std(axis=axis)
def get_p_value(perm, emp, axis=0):
'''
Utility function to compute the p-value (two-tailed) of a score, relative
to a null distribution.
Parameters
----------
perm: array-like
Null distribution of (permuted) scores.
emp: float or array-like
Empirical score.
axis: float
Axis of the `perm` array associated with the null scores.
'''
k = perm.shape[axis]
perm_moved = np.moveaxis(perm, axis, 0)
perm_mean = np.mean(perm_moved, axis=0)
# Compute p-value
num = (np.count_nonzero(abs(perm_moved-perm_mean) > abs(emp-perm_mean),
axis=0))
den = k
pval = num / den
return pval
def get_cmap(colorList):
'''
Function to get a colormap from a list of colors
'''
n = len(colorList)
c_all = np.zeros((256, 4))
m = int(256/(n-1))
for i in range(n):
if isinstance(colorList[i], str):
color = to_rgba(colorList[i])
else:
color = colorList[i]
if i == 0:
c_all[:int(m/2)] = color
elif i < n-1:
c_all[((i-1)*m)+(int(m/2)):(i*m)+(int(m/2))] = color
else:
c_all[((i-1)*m)+(int(m/2)):] = color
cmap = ListedColormap(c_all)
return cmap
def get_corr_spin_p(X, Y, spins):
'''
Function to compute the p-value of a correlation score compared to spun
distributions
Parameters
----------
X: (n,) ndarray
Independent variable.
Y: (n,) ndarray
Dependent variable
spins: (n, n_spin) ndarray
Permutations used to compute the p-value of the correlation.
Returns
-------
p_spin: float
p-value of the correlation.
'''
N_nodes, N_spins = spins.shape
emp_corr, _ = pearsonr(X, Y)
spin_corr = np.zeros((N_spins))
for i in range(N_spins):
spin_corr[i], _ = pearsonr(X[spins[:, i]], Y)
p_spin = get_p_value(spin_corr, emp_corr)
return p_spin
def fill_triu(A):
'''
Function to fill the triu indices of a matrix with the elements of the
tril matrix
'''
n = len(A)
A[np.triu_indices(n)] = A.T[np.triu_indices(n)]
return A
'''
VISUALIZATION FUNCTIONS
'''
def get_colormaps():
'''
Utility function that loads colormaps from the palettable module into a
dictionary
Returns
-------
cmaps: dict
Dictionary containing matplotlib colormaps
'''
cmaps = {}
# Colorbrewer | Diverging
cmaps['Spectral_11_r'] = Spectral_11_r.mpl_colormap
cmaps['RdBu_11_r'] = RdBu_11_r.mpl_colormap
# Colorbrewer | Sequential
cmaps['Reds_3'] = Reds_3.mpl_colormap
cmaps['Blues_3'] = Blues_3.mpl_colormap
cmaps['GnBu_9'] = GnBu_9.mpl_colormap
# Cartocolors | Sequential
cmaps['SunsetDark_7'] = SunsetDark_7.mpl_colormap
return cmaps
def plot_network(A, coords, edge_scores, node_scores, edge_cmap="Greys",
node_cmap="viridis", edge_alpha=0.25, node_alpha=1,
edge_vmin=None, edge_vmax=None, node_vmin=None,
node_vmax=None, nodes_color='black', edges_color='black',
linewidth=0.25, s=100, view_edge=True, figsize=None):
'''
Function to draw (plot) a network of nodes and edges.
Parameters
----------
A : (n, n) ndarray
Array storing the adjacency matrix of the network. 'n' is the
number of nodes in the network.
coords : (n, 3) ndarray
Coordinates of the network's nodes.
edge_scores: (n,n) ndarray
Array storing edge scores for individual edges in the network. These
scores are used to color the edges.
node_scores : (n) ndarray
Array storing node scores for individual nodes in the network. These
scores are used to color the nodes.
edge_cmap, node_cmap: str
Colormaps from matplotlib.
edge_alpha, node_alpha: float, optional
The alpha blending value, between 0 (transparent) and 1 (opaque)
edge_vmin, edge_vmax, node_vmin, node_vmax: float, optional
Minimal and maximal values of the node and edge colors. If None,
the min and max of edge_scores and node_scores respectively are used.
Default: `None`
nodes_color, edges_color: str
Color to be used to plot the network's nodes and edges if edge_scores
or node_scores are none.
linewidth: float
Width of the edges.
s: float or array-like
Size the nodes.
view_edge: bool
If true, network edges are shown.
figsize: (float, float)
Width and height of the figure, in inches.
Returns
-------
fig: matplotlib.figure.Figure instance
Figure instance of the drawn network.
ax: matplotlib.axes.Axes instance
Ax instance of the drawn network.
'''
if figsize is None:
figsize = (10, 10)
fig, ax = plt.subplots(1, 1, figsize=figsize)
# Plot the edges
if view_edge:
# Identify edges in the network
edges = np.where(A > 0)
# Get the color of the edges
if edge_scores is None:
edge_colors = np.full((len(edges[0])), edges_color, dtype="<U10")
else:
edge_colors = cm.get_cmap(edge_cmap)(
mpl.colors.Normalize(edge_vmin, edge_vmax)(edge_scores[edges]))
# Plot the edges
for edge_i, edge_j, c in zip(edges[0], edges[1], edge_colors):
x1, x2 = coords[edge_i, 0], coords[edge_j, 0]
y1, y2 = coords[edge_i, 1], coords[edge_j, 1]
ax.plot([x1, x2], [y1, y2], c=c, linewidth=linewidth,
alpha=edge_alpha, zorder=0)
# Get the color of the nodes
if node_scores is None:
node_scores = nodes_color
node_colors = node_scores
# plot the nodes
ax.scatter(
coords[:, 0], coords[:, 1], c=node_colors,
edgecolors='none', cmap=node_cmap, vmin=node_vmin,
vmax=node_vmax, alpha=node_alpha, s=s, zorder=1)
ax.set_aspect('equal')
ax.axis('off')
return fig, ax
def bilaterize_network(A, coords, symmetry_axis=0, between_hemi_dist=0):
'''
Function to bilaterize a single-hemisphere connectome (i.e. duplicate the
number of nodes and the connectivity of the network)
Parameters
----------
A: (n, n) ndarray
Adjacency matrix of the single-hemisphere connectome, where `n` is the
number of nodes in this single-hemispheric connectome
coords: (n, 3) ndarray
Coordinates of the nodes in the single-hemisphere connectome
symmetry_axis: int
Axis of symmetry along which the network is bilaterized
between_hemi_dist = float
Distance between the coordinates of the two hemisphere
Returns
-------
A_bil: (2*n, 2*n) ndarray
Bilaterized adjacency matrix
coords_bil: (2*n, 3) ndarray
Coordinate of the nodes in the bilaterized connectome. Coordinates are
mirrored along the symmetry axis.
'''
n_nodes = len(A)
A_bil = np.zeros((n_nodes * 2, n_nodes * 2))
A_bil[:n_nodes, :n_nodes] = A.copy()
A_bil[n_nodes:, n_nodes:] = A.copy()
coords_bil = np.zeros((n_nodes * 2, 3))
coords_bil[:n_nodes] = coords.copy()
coords_bil[n_nodes:] = coords.copy()
coords_bil[:n_nodes, 2] += between_hemi_dist
coords_bil[n_nodes:, symmetry_axis] = -coords_bil[:n_nodes, symmetry_axis]
return A_bil, coords_bil
def assortativity_boxplot(network_name, null_type, annotations, figsize=(3, 2),
face_color='white', edge_color='black'):
'''
Function to plot the boxplots showing the distribution of null
assortativity results, relative to each assortativity result obtained with
empirical annotations. This function relies on the results stored
in the `results/standardized_assortativity` folder.
Parameters
----------
network_name: str
Name of the network. This is used to load the necessary results in
stored in `results/standardized_assortativity/{network_name}.pickle`
null_type: str
Type of the null model used to compute the null distribution of
assortativity results.
annotations: list
List of annotation names that we want to include in the figure.
figsize: (float, float)
Width and height of the figure, in inches.
Returns
-------
fig: matplotlib.figure.Figure instance
Figure instance of the drawn network.
'''
path2results = f"results/standardized_assortativity/{network_name}.pickle"
results = load_data(path2results)
fig = plt.figure(figsize=figsize)
ax = plt.subplot(111)
for i, ann in enumerate(annotations):
ax.scatter(i+1,
results[ann]['assort'],
c=edge_color,
s=50)
bplot = ax.boxplot(results[ann][f'assort_{null_type}'],
positions=[i+1],
widths=0.5,
patch_artist=True,
medianprops=dict(color='black'),
flierprops=dict(marker='+',
markerfacecolor='lightgray',
markeredgecolor='lightgray'),
showcaps=False,
zorder=0)
for element in ['boxes', 'whiskers', 'means', 'medians', 'caps']:
plt.setp(bplot[element], color=edge_color)
for patch in bplot['boxes']:
patch.set_facecolor(face_color)
sns.despine()
ax.set_ylabel("assortativity")
ax.set_xlabel("annotation")
ax.set_xticklabels(annotations)
return fig
def assortativity_barplot(results, annotation_labels, non_sig_colors,
sig_colors, figsize=None, barwidth=0.5,
ylim=None, tight_layout=True):
'''
Function to plot the barplot showing the standardized assortativity
results of all the annotations, across all networks.This function relies
on the results stored in the `results/standardized_assortativity` folder.
Parameters
----------
results: list
List of assortativity results for each annotation.
annotation_labels: list
List of annotation labels for each annotation.
non_sig_colors: list of colors
List of colors used to color each barplot that are non-significant,
according to the network associated with it.
sig_color: list of colors
List of colors used to color each barplot that are significant,
according to the network associated with it.
figsize: tuple
Tuple specifying the width and height of the figure in dots-per-inch.
barwidth: float
Width of the bars.
ylim: float
Y-limit.
Returns
-------
fig: matplotlib.figure.Figure instance
Figure instance of the drawn network.
'''
n_annotations = len(results)
if figsize is None:
figsize = (n_annotations/2, 3)
fig = plt.figure(figsize=figsize)
ax = plt.subplot(111)
for i, ann in enumerate(results):
if ann['assort_p_fdr'] < 0.05:
color = sig_colors[i]
else:
color = non_sig_colors[i]
plt.bar(i, ann['assort_z'], width=barwidth, color=color,
edgecolor=color, zorder=1)
plt.plot([0, n_annotations], [0, 0], color='lightgray', linestyle='dashed',
zorder=0)
ax.set_ylabel("z-assortativity")
ax.set_xlabel("annotation")
ax.set_xticks(np.arange(len(results)), labels=annotation_labels,
rotation='vertical')
if ylim is not None:
margin = 0.05 * (ylim[1] - ylim[0])
ax.set_ylim(bottom=ylim[0]-margin, top=ylim[1]+margin)
if tight_layout:
plt.tight_layout()
sns.despine()
return fig
def plot_assortativity_thresholded(network_name, annotations, percent_kept,
sig_colors, non_sig_colors,
figsize=(3.9, 1.8)):
'''
Function to plot lineplots of the standardized assortativity of annotations
as a function of the percentile of short-range connections removed from the
network.
Parameters:
----------
network_name: str
Name of the network. This is used to load the necessary results in
stored in `results/assortativity_thresholded/{network_name}.pickle`.
annotations: list
List of annotation names that we want to include in the figure.
percent_kept: array-like
List of percentile values indicating the percentile of connections
that we want to keep when thresholding the network.
sig_colors: list
List of colors used to indicate significance, for each annotation
non_sig_colors: list
List of colors used to indicate non-significance, for each annotation.
Returns
-------
fig: matplotlib.figure.Figure instance
Figure instance of the drawn network.
'''
percent_removed = 100 - percent_kept
n_box = len(percent_kept)
results = load_data(
f"results/assortativity_thresholded/{network_name}.pickle")
fig = plt.figure(figsize=figsize)
for i, key in enumerate(annotations):
assort_p_fdr = results[key]['assort_all_p_fdr']
assort_z = results[key]['assort_all_z']
# Set color
color = np.zeros((n_box), dtype='object')
color[:] = non_sig_colors[i]
color[assort_p_fdr < 0.05] = sig_colors[i]
# Plot trajectory lines
plt.plot(percent_removed,
assort_z,
color=non_sig_colors[i],
zorder=0)
# Plot scatterplot markers
plt.scatter(percent_removed,
assort_z,
color=color,
s=10,
zorder=1,
label=key)
# Plot dashed line at 0
plt.plot(percent_removed,
np.zeros((n_box)),
linestyle='dashed',
color='lightgray')
plt.gca().xaxis.set_major_locator(MultipleLocator(10))
plt.gca().xaxis.set_minor_locator(MultipleLocator(5))
sns.despine()
plt.legend(bbox_to_anchor=(1.04, 1), loc='upper left')
return fig
def plot_regression(X, Y, x_label=None, y_label=None, s=5, figsize=(3, 3),
alpha=0.5, permutations=None):
'''
Function to plot a scatterplot showing the relationship between a variable
X and a variable Y as well as the regression line of this relationship.
Paramaters:
----------
X: (n,) ndarray
Independent variable.
Y: (n,) ndarray
Dependent variable
x_label: str
Label of the x-axis
y_label: str
Label of the y-axis.
s: float
Size of the markers in the scatterplot.
figsize: tuple of floats
Size of the matplotlib figure.
alpha: float
Transparancy of the markers in the scatterplot
permutations: (n, n_perm) ndarray
Permutations used to compute the significance of the relatiosnhip.
Returns:
-------
fig: matplotlib.figure.Figure instance
Figure instance of the drawn network.
'''
r_results = pearsonr(X, Y)
r, p_perm = r_results
CI = r_results.confidence_interval()
df = len(X) - 2
if permutations is not None:
p_spin = get_corr_spin_p(X, Y, permutations)
fig = plt.figure(figsize=(3, 3))
sns.regplot(
x=X, y=Y, color='black', truncate=False,
scatter_kws={'s': 5, 'rasterized': True,
'alpha': alpha, 'edgecolor': 'none'}
)
plt.gca().set_aspect(1 / plt.gca().get_data_ratio())
plt.xlabel(x_label)
plt.ylabel(y_label)
if permutations is not None:
p = p_spin
plt.title(f"r={r:.2f}; p_spin={p:.4f}")
else:
p = p_perm
if p < 0.00001:
plt.title(f"r={r:.2f}; p_perm={p:.5e}")
else:
plt.title(f"r={r:.2f}; p_perm={p:.5f}")
plt.tight_layout()
return fig, (r, p, df, CI)
def plot_heatmap(values, xlabels, ylabels, cbarlabel="values",
cmap="viridis", vmin=None, vmax=None, grid_width=3,
figsize=None, text_size=12, sigs=None, text=False,
tight_layout=True):
'''
Function to plot a heatmap
Parameters
----------
values: ndarray
Array storing the values displayed in the heatmaps
xlabels, ylabels: list
List of labels for each x-tick or y-tick
cbarlabel: str
Label of the colorbar
cmap: str
Colormap
vmin, vmax: float
Minimum and maximum values for colorbar.
grid_width: float
Width of the grid lines between each entry of the heatmap.
figsize: (float, float)
Width and height of the figure, in inches.
text_size: float
Size of the asterisks used to denote significance.
sigs: ndarray of bool
Matrix of boolean values indicating which scores in the `values` matrix
are significant. Significant scores will be denoted with an asterisk.
text: bool
Boolean indicating whether we want the values plotted as text on top
of the heatmap.
tight_layout: bool
Boolean indicating whether we want a tight layout for the figure
Returns
-------
fig: matplotlib.figure.Figure instance
Figure instance of the drawn network.
'''
fig, ax = plt.subplots(dpi=100, figsize=figsize)
if vmin is None:
vmin = np.nanmin(values)
if vmax is None:
vmax = np.nanmax(values)
# Plot the heatmap
im = ax.imshow(values, aspect='equal', vmin=vmin, vmax=vmax, cmap=cmap)
# Create colorbar
cbar = ax.figure.colorbar(im, ax=ax)
cbar.ax.set_ylabel(cbarlabel, rotation=-90, va="bottom")
cbar.set_ticks([vmin, vmax])
cbar.set_ticklabels([f"{vmin:.2f}", f"{vmax:.2f}"])
# show each ticks and label them with the respective list entries.
ax.set_xticks(np.arange(values.shape[1]))
ax.set_yticks(np.arange(values.shape[0]))
ax.set_xticklabels(xlabels)
ax.set_yticklabels(ylabels)
# Let the horizontal axes labeling appear on top.
ax.tick_params(top=True, bottom=False, labeltop=True, labelbottom=False)
# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=-30, ha="right",
rotation_mode="anchor")
# Turn spines off and create white grid.
for edge, spine in ax.spines.items():
spine.set_visible(False)
ax.set_xticks(np.arange(values.shape[1]+1)-.5, minor=True)
ax.set_yticks(np.arange(values.shape[0]+1)-.5, minor=True)
ax.grid(which="minor", color="w", linestyle='-', linewidth=grid_width)
ax.tick_params(which="minor", bottom=False, left=False)
# Add stars if significants
if sigs is not None:
for i in range(sigs.shape[0]):
for j in range(sigs.shape[1]):
if sigs[i, j]:
im.axes.text(j, i, '*', horizontalalignment='center',
verticalalignment='center', color="white",
fontsize=text_size)
# Add text
if text:
for i in range(values.shape[0]):
for j in range(values.shape[1]):
im.axes.text(j, i, "{:.2f}".format(values[i, j]),
horizontalalignment='center',
verticalalignment='center', color="black",
fontsize=text_size)
if tight_layout:
fig.tight_layout()
return fig
def plot_homophilic_ratios(ratios, ann, coords, lhannot, rhannot,
noplot, order, vmin, vmax, hemi='', n_nodes=None):
# If hemi is only left hemisphere, set the values on the right to the mean
if hemi == "L":
scores = np.zeros((n_nodes))+np.mean(ratios)
if order == 'RL':
scores[(n_nodes-len(ratios)):] = ratios
ratios = scores
elif order == 'LR':
scores[:len(ratios)] = ratios
else:
scores = ratios
# plot homophilic ratios on brain surface
surface_image = plot_fsaverage(
scores, lhannot=lhannot, rhannot=rhannot, noplot=noplot, order=order,
views=['lateral', 'm'], vmin=vmin, vmax=vmax,
colormap=GnBu_9.mpl_colormap,
data_kws={'representation': 'wireframe', 'line_width': 4.0})
# plot homophilic ratios on dotted brain
size_change = abs(zscore(ratios))
size_change[size_change > 5] = 5
size = 40 + (10 * size_change)
dot_image, _ = plot_network(
None, coords[:, :2], None, ratios, s=size,
view_edge=False, node_cmap=GnBu_9.mpl_colormap, node_vmin=vmin,
node_vmax=vmax)
return surface_image, dot_image
def plot_brain_surface(scores, lhannot, rhannot, noplot, order, colormap,
vmin=None, vmax=None):
'''wrapper function to call plot_fsaverage more efficiently'''
data_kws = {'representation': 'wireframe', 'line_width': 4.0}
if vmin is None:
vmin = scores.min()
if vmax is None:
vmax = scores.max()
return plot_fsaverage(scores, lhannot=lhannot, rhannot=rhannot,
noplot=noplot, order=order, colormap=colormap,
views=['lateral', 'm'], data_kws=data_kws,
vmin=vmin, vmax=vmax)
def plot_SC_FC_heterophilic_comparison(SC_receptors, FC_receptors, SC_layers,
FC_layers):
'''
Function to plot the scatterplot comparing heterophilic mixing in the
structural and functional connectomes. Data points that are significant
in FC are colored in red if they are positive, and in blue if they are
negative.
Parameters
----------
SC_receptors: dict
Dictionary storing the heterophilic mixing results for the receptor
data, for the structural connectome.
FC_receptors: dict
Dictionary storing the heterophilic mixing results for the receptor
data, for the functional connectome.
SC_layers: dict
Dictionary storing the heterophilic mixing results for the laminar
data, for the structural connectome.
FC_layers: dict
Dictionary storing the heterophilic mixing results for the laminar
data, for the functional connectome.
Returns
-------
fig: matplotlib.figure.Figure instance
Figure instance of the drawn network.
'''
def scatterplot_significance_colored(X, Y):
plt.scatter(
x=X['a_z'], y=Y['a_z'],
color='lightgray', s=8, rasterized=True)
pos_sig_FC = (Y['a_p_fdr'] < 0.05) & (Y['a_z'] > 0)
plt.scatter(x=X['a_z'][pos_sig_FC],
y=Y['a_z'][pos_sig_FC],
color='#67001F', s=8, rasterized=True)
neg_sig_FC = (Y['a_p_fdr'] < 0.05) & (Y['a_z'] < 0)
plt.scatter(x=X['a_z'][neg_sig_FC],
y=Y['a_z'][neg_sig_FC],
color='#053061', s=8, rasterized=True)
fig = plt.figure(figsize=(2.3, 2.3))
# Plot receptors results
scatterplot_significance_colored(SC_receptors, FC_receptors)
# Plot layer results
scatterplot_significance_colored(SC_layers, FC_layers)
plt.gca().set_aspect(1 / plt.gca().get_data_ratio())
plt.xlabel("z-assortativity (SC)")
plt.ylabel("z-assortativity (FC)")
# Compute correlation
SC_a_z_all = np.concatenate(
(SC_receptors['a_z'].flatten(),
SC_layers['a_z'].flatten()),
axis=0)
FC_a_z_all = np.concatenate(
(FC_receptors['a_z'].flatten(),
FC_layers['a_z'].flatten()),
axis=0)
r, _ = pearsonr(SC_a_z_all, FC_a_z_all)
plt.title(f"r={r:.2f}")
return fig
def plot_PC1_assortativity_correlations(PC1_r, PC1_r_prod, data, z_assort,
barplot_size=(5, 2), grid_width=0.25):
'''
Function to plot results exploring the relationship between assortativity
and correlations with PC1 (SUPPLEMENTARY FIGURE 6)
Parameters
----------
PC1_r: (m,) ndarray
Correlations between each brain map and the first component of the
network.
PC1_r_prod: (m, m) ndarray
Product of the correlations stored in PC1_r
data: dict
Dictionary storing either the laminar thickness or the receptor density
data.
z_assort: (m, m) ndarray
Z-assortativity (i.e. heterophilic mixing) of each pair of brain map.
barplot_size: tuple of floats
Size of the barplot figure.
grid_width: float
Width of the grid in the r-product heatmap figure.
Returns