-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhcp_perf2.py
2933 lines (2724 loc) · 143 KB
/
hcp_perf2.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
#!/home/despoB/mb3152/anaconda2/bin/python
import brain_graphs
import pandas as pd
import matlab
import matlab.engine
import os
import sys
import time
import numpy as np
import subprocess
import pickle
import h5py
import random
import time
import scipy
from scipy.io import loadmat
import scipy.io as sio
from scipy.stats.stats import pearsonr
import nibabel as nib
from sklearn.metrics.cluster import normalized_mutual_info_score
from sklearn.neural_network import MLPRegressor
from itertools import combinations, permutations
from igraph import Graph, ADJ_UNDIRECTED, VertexClustering
import glob
import math
import matplotlib.patches as patches
from collections import Counter
import matplotlib.pylab as plt
import matplotlib as mpl
from matplotlib import patches
plt.rcParams['pdf.fonttype'] = 42
path = '/home/despoB/mb3152/anaconda2/lib/python2.7/site-packages/matplotlib/mpl-data/fonts/ttf/Helvetica.ttf'
prop = mpl.font_manager.FontProperties(fname=path)
mpl.rcParams['font.family'] = prop.get_name()
import seaborn as sns
import powerlaw
from richclub import preserve_strength, RC
from multiprocessing import Pool
sys.path.append('/home/despoB/mb3152/dynamic_mod/')
from sklearn import linear_model, metrics
import random
global hcp_subjects
hcp_subjects = os.listdir('/home/despoB/connectome-data/')
hcp_subjects.sort()
# global pc_vals
# global fit_matrices
# global task_perf
import statsmodels.api as sm
from statsmodels.stats.mediation import Mediation
from scipy import stats, linalg
global homedir
# homedir = '/Users/Maxwell/HWNI/'
homedir = '/home/despoB/mb3152/'
import multiprocessing
from sklearn.decomposition import PCA,FastICA,FactorAnalysis
from sklearn.cross_decomposition import CCA
import copy
from quantities import millimeter
def mm_2_inches(mm):
mm = mm * millimeter
mm.units = 'inches'
return mm.item()
def alg_compare_multi(matrix):
alg1mods = []
alg2mods = []
alg3mods = []
for cost in np.array(range(5,16))*0.01:
temp_matrix = matrix.copy()
graph = brain_graphs.matrix_to_igraph(temp_matrix,cost,binary=False,check_tri=True,interpolation='midpoint',normalize=True,mst=True)
assert np.diff([cost,graph.density()])[0] < .01
alg1mods.append(graph.community_infomap(edge_weights='weight').modularity)
alg2mods.append(graph.community_multilevel(weights='weight').modularity)
alg3mods.append(graph.community_fastgreedy(weights='weight').as_clustering().modularity)
alg1mods = np.nanmean(alg1mods)
alg2mods = np.nanmean(alg2mods)
alg3mods = np.nanmean(alg3mods)
return [alg1mods,alg2mods,alg3mods]
def alg_compare(subjects,homedir=homedir):
task = 'REST'
atlas = 'power'
project='hcp'
matrices = []
for subject in subjects:
s_matrix = []
files = glob.glob('%sdynamic_mod/%s_matrices/%s_%s_*%s*_matrix.npy'%(homedir,atlas,subject,atlas,task))
for f in files:
f = np.load(f)
np.fill_diagonal(f,0.0)
f[np.isnan(f)] = 0.0
f = np.arctanh(f)
s_matrix.append(f.copy())
if len(s_matrix) == 0:
continue
s_matrix = np.nanmean(s_matrix,axis=0)
matrices.append(s_matrix.copy())
pool = Pool(40)
results = pool.map(alg_compare_multi,matrices)
np.save('%sdynamic_mod/results/alg_compare.npy'%(homedir),results)
def alg_plot():
sns.set_style("white")
sns.set_style("ticks")
d = np.load('%sdynamic_mod/results/alg_compare.npy'%(homedir))
df = pd.DataFrame(columns=['Q','Community Algorithm'])
for i,s in enumerate(d):
df = df.append({"Q":s[0],'Community Algorithm':'InfoMap','subject':i},ignore_index=True)
df = df.append({"Q":s[1],'Community Algorithm':'Louvain','subject':i},ignore_index=True)
df = df.append({"Q":s[2],'Community Algorithm':'Fast Greedy','subject':i},ignore_index=True)
ax1 = plt.subplot2grid((3,3), (0,0), colspan=3)
ax2 = plt.subplot2grid((3,3), (1, 0))
ax3 = plt.subplot2grid((3,3), (1, 1))
ax4 = plt.subplot2grid((3,3), (1, 2))
sns.set_style("white")
sns.set_style("ticks")
sns.set(context="paper",font='Helvetica',font_scale=1.2)
sns.violinplot(data=df,inner='quartile',y='Q',x='Community Algorithm',palette=sns.color_palette("cubehelix", 8)[-3:],ax=ax1)
sns.plt.legend(bbox_to_anchor=[1,1.05],columnspacing=10)
ax1.set_title('Q Values Across Different Algorithms')
axes = [ax1,ax2,ax3]
for x,ax in zip(combinations(np.unique(df['Community Algorithm']),2),[ax2,ax3,ax4]):
print x[0],x[1]
print pearsonr(df.Q[df['Community Algorithm']==x[0]],df.Q[df['Community Algorithm']==x[1]])
print scipy.stats.ttest_ind(df.Q[df['Community Algorithm']==x[0]],df.Q[df['Community Algorithm']==x[1]])
sns.regplot(df.Q[df['Community Algorithm']==x[0]],df.Q[df['Community Algorithm']==x[1]],ax=ax,color=sns.dark_palette("muted purple", input="xkcd")[-1])
ax.set_xlabel(x[0] + ' Q')
ax.set_ylabel(x[1] + ' Q')
sns.plt.show()
plt.savefig('/home/despoB/mb3152/dynamic_mod/figures/alg_compare.pdf',dpi=3600)
plt.close()
def nan_pearsonr(x,y):
x = np.array(x)
y = np.array(y)
isnan = np.sum([x,y],axis=0)
isnan = np.isnan(isnan) == False
return pearsonr(x[isnan],y[isnan])
def remove_missing_subjects(subjects,task,atlas):
"""
remove missing subjects, original array is being edited
"""
subjects = list(subjects)
for subject in subjects:
files = glob.glob('/home/despoB/mb3152/dynamic_mod/%s_matrices/%s_%s_*%s*_matrix.npy'%(atlas,subject,atlas,task))
if len(files) < 2:
subjects.remove(subject)
return subjects
def check_motion(subjects):
for subject in subjects:
e = np.load('/home/despoB/mb3152/dynamic_mod/component_activation/%s_12_False_engagement.npy' %(subject))
m = np.loadtxt('/home/despoB/mb3152/data/nki_data/preprocessed/pipeline_comp_cor_and_standard/%s_session_1/frame_wise_displacement/_scan_RfMRI_mx_645_rest/FD.1D'%(subject))
print pearsonr(m,np.std(e.reshape(900,12),axis=1))
def plot_corr_matrix(matrix,membership,colors,out_file=None,reorder=True,line=False,rectangle=False,draw_legend=False,colorbar=False):
"""
matrix: square, whatever you like
membership: the community (or whatever you like of each node in the matrix)
colors: the colors of each node in the matrix (same order as membership)
out_file: save the file here, will supress plotting, do None if you want to plot it.
line: draw those little lines to divide up communities
rectangle: draw colored rectangles around each community
draw legend: draw legend...
colorbar: colorbar...
"""
if reorder == True:
swap_dict = {}
index = 0
corr_mat = np.zeros((matrix.shape))
names = []
x_ticks = []
y_ticks = []
reordered_colors = []
for i in np.unique(membership):
for node in np.where(membership==i)[0]:
swap_dict[node] = index
index = index + 1
names.append(membership[node])
reordered_colors.append(colors[node])
for i in range(len(swap_dict)):
for j in range(len(swap_dict)):
corr_mat[swap_dict[i],swap_dict[j]] = matrix[i,j]
corr_mat[swap_dict[j],swap_dict[i]] = matrix[j,i]
colors = reordered_colors
membership = np.array(names)
else:
corr_mat = matrix
sns.set(style='dark',context="paper",font='Helvetica',font_scale=1.2)
std = np.nanstd(corr_mat)
mean = np.nanmean(corr_mat)
fig = sns.clustermap(corr_mat,yticklabels=[''],xticklabels=[''],cmap=sns.diverging_palette(260,10,sep=10, n=20,as_cmap=True),rasterized=True,col_colors=colors,row_colors=colors,row_cluster=False,col_cluster=False,**{'vmin':mean - (std*2),'vmax':mean + (std*2),'figsize':(15.567,15)})
ax = fig.fig.axes[4]
# Use matplotlib directly to emphasize known networks
if line == True or rectangle == True:
if len(colors) != len(membership):
colors = np.arange(len(membership))
for i,network,color, in zip(np.arange(len(membership)),membership,colors):
if network != membership[i - 1]:
if len(colors) != len(membership):
color = 'white'
if rectangle == True:
ax.add_patch(patches.Rectangle((i+len(membership[membership==network]),264-i),len(membership[membership==network]),len(membership[membership==network]),facecolor="none",edgecolor=color,linewidth="2",angle=180))
if line == True:
ax.axhline(len(membership) - i, c=color,linewidth=.5,label=network)
ax.axhline(len(membership) - i, c='black',linewidth=.5)
ax.axvline(i, c='black',linewidth=.5)
fig.ax_col_colors.add_patch(patches.Rectangle((0,0),264,1,facecolor="None",edgecolor='black',lw=2))
fig.ax_row_colors.add_patch(patches.Rectangle((0,0),1,264,facecolor="None",edgecolor='black',lw=2))
col = fig.ax_col_colors.get_position()
fig.ax_col_colors.set_position([col.x0, col.y0, col.width*1, col.height*.35])
col = fig.ax_row_colors.get_position()
fig.ax_row_colors.set_position([col.x0+col.width*(1-.35), col.y0, col.width*.35, col.height*1])
fig.ax_col_dendrogram.set_visible(False)
fig.ax_row_dendrogram.set_visible(False)
if draw_legend == True:
leg = fig.ax_heatmap.legend(bbox_to_anchor=[.98,1.1],ncol=5)
for legobj in leg.legendHandles:
legobj.set_linewidth(2.5)
if colorbar == False:
fig.cax.set_visible(False)
if out_file != None:
plt.savefig(out_file,dpi=600)
plt.close()
if out_file == None:
plt.show()
return fig
def plot_corr_matrix2(matrix,membership,reorder=True):
"""
matrix: square, whatever you like
membership: the community (or whatever you like of each node in the matrix)
colors: the colors of each node in the matrix (same order as membership)
out_file: save the file here, will supress plotting, do None if you want to plot it.
line: draw those little lines to divide up communities
rectangle: draw colored rectangles around each community
draw legend: draw legend...
colorbar: colorbar...
"""
if reorder == True:
swap_dict = {}
index = 0
corr_mat = np.zeros((matrix.shape))
names = []
x_ticks = []
y_ticks = []
for i in np.unique(membership):
for node in np.where(membership==i)[0]:
swap_dict[node] = index
index = index + 1
names.append(membership[node])
for i in range(len(swap_dict)):
for j in range(len(swap_dict)):
corr_mat[swap_dict[i],swap_dict[j]] = matrix[i,j]
corr_mat[swap_dict[j],swap_dict[i]] = matrix[j,i]
membership = np.array(names)
sns.set(style='dark',context="paper",font='Helvetica',font_scale=1.2)
std = np.nanstd(matrix)
mean = np.nanmean(matrix)
np.fill_diagonal(matrix,0.0)
fig = sns.heatmap(matrix,yticklabels=[''],xticklabels=[''],cmap=sns.diverging_palette(260,10,sep=10, n=20,as_cmap=True),rasterized=True,**{'vmin':mean - (std*2),'vmax':mean + (std*2)})
# Use matplotlib directly to emphasize known networks
for i,network in zip(np.arange(len(membership)),membership):
if network != membership[i - 1]:
fig.figure.axes[0].add_patch(patches.Rectangle((i+len(membership[membership==network]),len(membership)-i),len(membership[membership==network]),len(membership[membership==network]),facecolor="none",edgecolor='black',linewidth="2",angle=180))
sns.plt.show()
def make_static_matrix(subject,task,project,atlas,scrub=False):
hcp_subject_dir = '/home/despoB/connectome-data/SUBJECT/*TASK*/*reg*'
parcel_path = '/home/despoB/mb3152/dynamic_mod/atlases/%s_template.nii' %(atlas)
MP = None
# try:
# MP = np.load('/home/despoB/mb3152/dynamic_mod/motion_files/%s_%s.npy' %(subject,task))
# except:
# run_fd(subject,task)
# MP = np.load('/home/despoB/mb3152/dynamic_mod/motion_files/%s_%s.npy' %(subject,task))
subject_path = hcp_subject_dir.replace('SUBJECT',subject).replace('TASK',task)
if scrub == True:
subject_time_series = brain_graphs.load_subject_time_series(subject_path,dis_file=MP,scrub_mm=0.2)
brain_graphs.time_series_to_matrix(subject_time_series,parcel_path,voxel=False,fisher=False,out_file='/home/despoB/mb3152/dynamic_mod/%s_matrices/%s_%s_%s_matrix_scrubbed_0.2.npy' %(atlas,subject,atlas,task))
if scrub == False:
subject_time_series = brain_graphs.load_subject_time_series(subject_path,dis_file=None,scrub_mm=False)
brain_graphs.time_series_to_matrix(subject_time_series,parcel_path,voxel=False,fisher=False,out_file='/home/despoB/mb3152/dynamic_mod/%s_matrices/%s_%s_%s_matrix.npy' %(atlas,subject,atlas,task))
# parcel = nib.load(parcel_path).get_data().astype(int)
# g = np.zeros((np.max(parcel),subject_time_series.shape[-1]))
# for i in range(np.max(parcel)):
# g[i,:] = np.nanmean(subject_time_series[parcel==i+1],axis = 0)
def proc_figure():
hcp_subject_dir = '/home/despoB/connectome-data/SUBJECT/*TASK*/*reg*'
parcel_path = '/home/despoB/mb3152/dynamic_mod/atlases/%s_template.nii' %(atlas)
dis_file = np.load('/home/despoB/mb3152/dynamic_mod/motion_files/100307_rfMRI_REST1_LR.npy')
subject_path = hcp_subject_dir.replace('SUBJECT','100307').replace('TASK','REST1_LR')
subject_time_series = brain_graphs.load_subject_time_series(subject_path,dis_file=None,scrub_mm=False)
parcel = nib.load(parcel_path).get_data().astype(int)
# g = np.zeros((np.max(parcel),subject_time_series.shape[-1]))
# for i in range(np.max(parcel)):
# g[i,:] = np.nanmean(subject_time_series[parcel==i+1],axis = 0)
# np.save('100307_REST1LR_ts.npy',g)
# g = np.corrcoef(g)
ts = np.load('100307_REST1LR_ts.npy')
sns.set_style("white")
p = sns.color_palette("cubehelix", 8)
sns.tsplot(ts[43]-125,color=p[5])
sns.tsplot(ts[41],color=p[6])
sns.tsplot(ts[215]+180,color=p[7])
sns.plt.yticks([],[])
sns.plt.xticks([],[])
sns.despine()
sns.plt.savefig('ts_example.pdf')
plt.show()
m = []
for f in glob.glob('%s/dynamic_mod/power_matrices/*100307*REST*'%(homedir)):
if 'scrubbed' in f: continue
f = np.load(f)
np.fill_diagonal(f,0.0)
f[np.isnan(f)] = 0.0
f = np.arctanh(f)
m.append(f.copy())
m = np.nanmean(m,axis=0)
membership,network_names,num_nodes,name_int_dict = network_labels('power')
# m = np.load('/home/despoB/mb3152/diverse_club/graphs/REST.npy')
m = np.triu(m,1) + np.triu(m,1).transpose()
graph = brain_graphs.matrix_to_igraph(m.copy(),0.05,binary=False,check_tri=True,interpolation='midpoint',normalize=False,mst=True)
thresh_m = brain_graphs.threshold(m.copy(), .05, binary=False, check_tri=True, interpolation='midpoint', mst=True, test_matrix=True)
graph = graph.community_infomap(edge_weights='weight')
graph = brain_graphs.brain_graph(graph)
graph = brain_graphs.matrix_to_igraph(m,0.05,binary=False,check_tri=True,interpolation='midpoint',normalize=True)
graph = graph.community_infomap(edge_weights='weight')
graph = brain_graphs.brain_graph(graph)
pc.append(np.array(graph.pc))
wmd.append(np.array(graph.wmd))
mod.append(graph.community.modularity)
g = graph.community.graph
g.vs['community'] = graph.community.membership
p = pd.read_csv('%smodularity/Consensus264.csv'%(homedir),header=None)
x,y,z = p[6],p[7],p[8]
pc = graph.pc
pc[np.isnan(pc)] = 0.0
pc = pc * 1000
pc = pc.astype(int)
wcd= graph.wmd
wcd[np.isnan(wcd)] = 0.0
wcd = wcd * 1000
wcd = wcd.astype(int)
g.vs['latitude'] = np.array(y.values)
g.vs['longitude'] = np.array(z.values)
g.vs['pc'] = np.array(pc.astype('float16'))
g.vs['wcd'] = np.array(wcd.astype('float16'))
g.write_gml('100307_viz.gml')
network_order = ['Auditory','Sensory/somatomotor Hand','Sensory/somatomotor Mouth','Visual','Dorsal attention','Ventral attention',
'Cingulo-opercular Task Control','Salience','Fronto-parietal Task Control','Default mode','Cerebellar','Subcortical','Memory retrieval?','Uncertain']
colors = np.array(pd.read_csv('%smodularity/Consensus264.csv'%(homedir),header=None)[34].values)
colors[colors=='Pale blue'] = '#ADD8E6'
colors[colors=='Teal'] = '#008080'
swap_indices = []
for nn in network_order:
original_idx = np.where(network_names == nn)
for i in range(len(original_idx[0])):
swap_indices.append(original_idx[0][i])
membership = graph.community.membership
swap_dict = {}
index = 0
corr_mat = np.zeros((m.shape))
u = np.unique(membership)
np.random.shuffle(u)
for i in u:
for node in np.where(membership==i)[0]:
swap_dict[node] = index
index = index + 1
for i in range(len(swap_dict)):
for j in range(len(swap_dict)):
corr_mat[swap_dict[i],swap_dict[j]] = m[i,j]
corr_mat[swap_dict[j],swap_dict[i]] = m[j,i]
plt_m = np.tril(m) + np.triu(thresh_m)
sns.heatmap(m[swap_indices,:][:,swap_indices],cmap="coolwarm",vmin=-1,vmax=1)
plt.xticks([], [])
plt.yticks([], [])
plt.savefig('examplematrix.pdf')
plt.show()
def null_graph_individual_graph_analyes(matrix):
cost = 0.05
temp_matrix = matrix.copy()
graph = brain_graphs.matrix_to_igraph(temp_matrix,cost,binary=False,check_tri=True,interpolation='midpoint',normalize=True)
vc = graph.community_infomap(edge_weights='weight')
temp_matrix = matrix.copy()
random_matrix = temp_matrix.copy()
random_matrix = random_matrix[np.tril_indices(264,-1)]
np.random.shuffle(random_matrix)
temp_matrix[np.tril_indices(264,-1)] = random_matrix
temp_matrix[np.triu_indices(264)] = 0.0
temp_matrix = np.nansum([temp_matrix,temp_matrix.transpose()],axis=0)
graph = brain_graphs.matrix_to_igraph(temp_matrix,cost,binary=False,check_tri=True,interpolation='midpoint',normalize=True)
graph = brain_graphs.brain_graph(VertexClustering(graph,vc.membership))
return (graph.community.modularity,np.array(graph.pc),np.array(graph.wmd))
def null_community_individual_graph_analyes(matrix):
cost = 0.05
temp_matrix = matrix.copy()
graph = brain_graphs.matrix_to_igraph(temp_matrix,cost,binary=False,check_tri=True,interpolation='midpoint',normalize=True)
graph = graph.community_infomap(edge_weights='weight')
membership = graph.membership
np.random.shuffle(membership)
graph = brain_graphs.brain_graph(VertexClustering(graph.graph,membership))
return (graph.community.modularity,np.array(graph.pc),np.array(graph.wmd))
def null_all_individual_graph_analyes(matrix):
cost = 0.01
temp_matrix = matrix.copy()
random_matrix = temp_matrix.copy()
random_matrix = random_matrix[np.tril_indices(264,-1)]
np.random.shuffle(random_matrix)
temp_matrix[np.tril_indices(264,-1)] = random_matrix
temp_matrix[np.triu_indices(264)] = 0.0
temp_matrix = np.nansum([temp_matrix,temp_matrix.transpose()],axis=0)
graph = brain_graphs.matrix_to_igraph(temp_matrix,cost,binary=False,check_tri=True,interpolation='midpoint',normalize=True)
graph = graph.community_infomap(edge_weights='weight')
graph = brain_graphs.brain_graph(graph)
return (graph.community.modularity,np.array(graph.pc),np.array(graph.wmd))
def individual_graph_analyes_wc(variables):
subject = variables[0]
print subject
atlas = variables[1]
task = variables[2]
s_matrix = variables[3]
pc = []
mod = []
wmd = []
memlen = []
for cost in np.array(range(5,16))*0.01:
temp_matrix = s_matrix.copy()
graph = brain_graphs.matrix_to_igraph(temp_matrix,cost,binary=False,check_tri=True,interpolation='midpoint',normalize=True,mst=True)
assert np.diff([cost,graph.density()])[0] < .01
del temp_matrix
graph = graph.community_infomap(edge_weights='weight')
graph = brain_graphs.brain_graph(graph)
pc.append(np.array(graph.pc))
wmd.append(np.array(graph.wmd))
mod.append(graph.community.modularity)
memlen.append(len(graph.community.sizes()))
del graph
return (mod,np.nanmean(pc,axis=0),np.nanmean(wmd,axis=0),np.nanmean(memlen),subject)
def individual_graph_analyes(variables):
subject = variables[0]
print subject
atlas = variables[1]
task = variables[2]
s_matrix = variables[3]
pc = []
mod = []
wmd = []
for cost in np.array(range(5,16))*0.01:
temp_matrix = s_matrix.copy()
graph = brain_graphs.matrix_to_igraph(temp_matrix,cost,binary=False,check_tri=True,interpolation='midpoint',normalize=True)
del temp_matrix
graph = graph.community_infomap(edge_weights='weight')
graph = brain_graphs.brain_graph(graph)
pc.append(np.array(graph.pc))
wmd.append(np.array(graph.wmd))
mod.append(graph.community.modularity)
del graph
return (mod,np.nanmean(pc,axis=0),np.nanmean(wmd,axis=0),subject)
def check_num_nodes(subjects,task,atlas='power'):
mods = []
num_nodes = []
for subject in subjects:
smods = []
snum_nodes = []
print subject
s_matrix = []
files = glob.glob('/home/despoB/mb3152/dynamic_mod/%s_matrices/%s_%s_*%s*_matrix.npy'%(atlas,subject,atlas,task))
for f in files:
f = np.load(f)
np.fill_diagonal(f,0.0)
f[np.isnan(f)] = 0.0
f = np.arctanh(f)
s_matrix.append(f.copy())
if len(s_matrix) == 0:
continue
s_matrix = np.nanmean(s_matrix,axis=0)
for cost in np.array(range(5,16))*0.01:
temp_matrix = s_matrix.copy()
graph = brain_graphs.matrix_to_igraph(temp_matrix,cost,binary=False,check_tri=True,interpolation='midpoint',normalize=True)
del temp_matrix
graph = graph.community_infomap(edge_weights='weight')
smods.append(graph.modularity)
snum_nodes.append(len(np.array(graph.graph.degree())[np.array(graph.graph.degree())>0.0]))
mods.append(np.mean(smods))
num_nodes.append(np.mean(snum_nodes))
print pearsonr(mods,num_nodes)
def participation_coef(W, ci, degree='undirected'):
'''
Participation coefficient is a measure of diversity of intermodular
connections of individual nodes.
Parameters
----------
W : NxN np.ndarray
binary/weighted directed/undirected connection matrix
ci : Nx1 np.ndarray
community affiliation vector
degree : str
Flag to describe nature of graph 'undirected': For undirected graphs
'in': Uses the in-degree
'out': Uses the out-degree
Returns
-------
P : Nx1 np.ndarray
participation coefficient
'''
if degree == 'in':
W = W.T
_, ci = np.unique(ci, return_inverse=True)
ci += 1
n = len(W) # number of vertices
Ko = np.sum(W, axis=1) # (out) degree
Gc = np.dot((W != 0), np.diag(ci)) # neighbor community affiliation
Kc2 = np.zeros((n,)) # community-specific neighbors
for i in range(1, int(np.max(ci)) + 1):
Kc2 += np.square(np.sum(W * (Gc == i), axis=1))
P = np.ones((n,)) - Kc2 / np.square(Ko)
# P=0 if for nodes with no (out) neighbors
P[np.where(np.logical_not(Ko))] = 0
return P
def check_sym():
known_membership,network_names,num_nodes,name_int_dict = network_labels('power')
tasks = ['WM','GAMBLING','RELATIONAL','MOTOR','LANGUAGE','SOCIAL','REST']
for task in tasks:
print task
subjects = np.load('/home/despoB/mb3152/dynamic_mod/results/%s_%s_%s_subs_%s.npy' %('hcp',task,'power','fz'))
for subject in subjects:
print task,subject
s_matrix = []
files = glob.glob('/home/despoB/mb3152/dynamic_mod/%s_matrices/%s_%s_*%s*_matrix.npy'%('power',subject,'power',task))
for f in files:
f = np.load(f)
np.fill_diagonal(f,0.0)
f[np.isnan(f)] = 0.0
f = np.arctanh(f)
s_matrix.append(f.copy())
s_matrix = np.nanmean(s_matrix,axis=0)
assert (np.tril(s_matrix,-1) == np.triu(s_matrix,1).transpose()).all()
graph = brain_graphs.matrix_to_igraph(s_matrix,0.15,binary=False,check_tri=False,interpolation='midpoint',normalize=True,mst=True)
graph = brain_graphs.brain_graph(VertexClustering(graph,known_membership))
graph.pc[np.isnan(graph.pc)] = 0.0
assert np.max(graph.pc) < 1.0
assert np.isclose(graph.pc,participation_coef(np.array(graph.matrix),np.array(graph.community.membership))).all() == True
assert np.nansum(np.abs(graph.pc-participation_coef(np.array(graph.matrix),np.array(graph.community.membership)))) < 1e-10
def check_mst(subjects,task,atlas='power'):
for task in tasks:
subjects = np.load('/home/despoB/mb3152/dynamic_mod/results/%s_%s_%s_subs_%s.npy' %('hcp',task,atlas,'fz'))
for subject in subjects:
print subject
s_matrix = []
files = glob.glob('/home/despoB/mb3152/dynamic_mod/%s_matrices/%s_%s_*%s*_matrix.npy'%(atlas,subject,atlas,task))
for f in files:
f = np.load(f)
np.fill_diagonal(f,0.0)
f[np.isnan(f)] = 0.0
f = np.arctanh(f)
s_matrix.append(f.copy())
s_matrix = np.nanmean(s_matrix,axis=0)
assert s_matrix.shape == (264,264)
for cost in np.array(range(5,16))*0.01:
temp_matrix = s_matrix.copy()
graph = brain_graphs.matrix_to_igraph(temp_matrix,cost,binary=False,check_tri=False,interpolation='midpoint',normalize=False,mst=True)
# assert np.diff([cost,graph.density()])[0] < .005
# assert graph.is_connected() == True
def check_scrubbed_normalize(subjects,task,atlas='power'):
for subject in subjects:
print subject
s_matrix = []
files = glob.glob('/home/despoB/mb3152/dynamic_mod/%s_matrices/%s_%s_*%s*_matrix_scrubbed_0.2.npy'%(atlas,subject,atlas,task))
for f in files:
dis_file = run_fd(subject,'_'.join(f.split('/')[-1].split('_')[2:5]))
remove_array = np.zeros(len(dis_file))
for i,fdf in enumerate(dis_file):
if fdf > .2:
remove_array[i] = 1
if i == 0:
remove_array[i+1] = 1
continue
if i == len(dis_file)-1:
remove_array[i-1] = 1
continue
remove_array[i-1] = 1
remove_array[i+1] = 1
if len(remove_array[remove_array==1])/float(len(remove_array)) > .75:
continue
f = np.load(f)
np.fill_diagonal(f,0.0)
f[np.isnan(f)] = 0.0
f = np.arctanh(f)
s_matrix.append(f.copy())
s_matrix = np.nanmean(s_matrix,axis=0)
assert s_matrix.shape == (264,264)
for cost in np.array(range(5,16))*0.01:
temp_matrix = s_matrix.copy()
graph = brain_graphs.matrix_to_igraph(temp_matrix,cost,binary=False,check_tri=True,interpolation='midpoint',normalize=True)
assert np.diff([cost,graph.density()])[0] < .005
def graph_metrics(subjects,task,atlas,run_version,project='hcp',run=False,scrubbed=False,homedir=homedir):
"""
run graph metrics or load them
"""
if run == False:
# done_subjects = np.load('/home/despoB/mb3152/dynamic_mod/results/%s_%s_%s_subs_%s.npy' %(project,task,atlas,run_version))
# assert (done_subjects == subjects).all() #make sure you are getting subjects / subjects order you wanted and ran last time.
subject_pcs = np.load('%sdynamic_mod/results/%s_%s_%s_pcs_%s.npy' %(homedir,project,task,atlas,run_version))
subject_wmds = np.load('%sdynamic_mod/results/%s_%s_%s_wmds_%s.npy' %(homedir,project,task,atlas,run_version))
subject_mods = np.load('%sdynamic_mod/results/%s_%s_%s_mods_%s.npy' %(homedir,project,task,atlas,run_version))
try:
subject_communities = np.load('%sdynamic_mod/results/%s_%s_%s_coms_%s.npy' %(homedir,project,task,atlas,run_version))
except:
subject_communities = np.load('%sdynamic_mod/results/%s_%s_%s_coms_fz_wc.npy' %(homedir,project,task,atlas))
matrices = np.load('%sdynamic_mod/results/%s_%s_%s_matrices_%s.npy' %(homedir,project,task,atlas,run_version))
thresh_matrices = np.load('%sdynamic_mod/results/%s_%s_%s_z_matrices_%s.npy' %(homedir,project,task,atlas,run_version))
finished_subjects = np.load('%sdynamic_mod/results/%s_%s_%s_subs_%s.npy' %(homedir,project,task,atlas,run_version))
elif run == True:
finished_subjects = []
variables = []
matrices = []
thresh_matrices = []
for subject in subjects:
s_matrix = []
if scrubbed == True:
files = glob.glob('%sdynamic_mod/%s_matrices/%s_%s_*%s*_matrix_scrubbed_0.2.npy'%(homedir,atlas,subject,atlas,task)) # FOR SCRUBBING ONLY
if scrubbed == False:
files = glob.glob('%sdynamic_mod/%s_matrices/%s_%s_*%s*_matrix.npy'%(homedir,atlas,subject,atlas,task))
for f in files:
if scrubbed == True:
# FOR SCRUBBING ONLY
dis_file = run_fd(subject,'_'.join(f.split('/')[-1].split('_')[2:5]))
remove_array = np.zeros(len(dis_file))
for i,fdf in enumerate(dis_file):
if fdf > .2:
remove_array[i] = 1
if i == 0:
remove_array[i+1] = 1
continue
if i == len(dis_file)-1:
remove_array[i-1] = 1
continue
remove_array[i-1] = 1
remove_array[i+1] = 1
if len(remove_array[remove_array==1])/float(len(remove_array)) > .75:
continue
f = np.load(f)
1/0
np.fill_diagonal(f,0.0)
f[np.isnan(f)] = 0.0
f = np.arctanh(f)
s_matrix.append(f.copy())
if len(s_matrix) == 0:
continue
s_matrix = np.nanmean(s_matrix,axis=0)
variables.append([subject,atlas,task,s_matrix.copy()])
num_nodes = s_matrix.shape[0]
thresh_matrix = s_matrix.copy()
thresh_matrix = scipy.stats.zscore(thresh_matrix.reshape(-1)).reshape((num_nodes,num_nodes))
thresh_matrices.append(thresh_matrix.copy())
matrices.append(s_matrix.copy())
finished_subjects.append(subject)
subject_mods = [] #individual subject modularity values
subject_pcs = [] #subjects PCs
subject_wmds = []
subject_communities = []
assert len(variables) == len(finished_subjects)
print 'Running Graph Theory Analyses'
from multiprocessing import Pool
pool = Pool(18)
results = pool.map(individual_graph_analyes_wc,variables)
for r,s in zip(results,finished_subjects):
subject_mods.append(np.nanmean(r[0]))
subject_pcs.append(r[1])
subject_wmds.append(r[2])
subject_communities.append(r[3])
assert r[4] == s #make sure it returned the order of subjects/results correctly
np.save('%sdynamic_mod/results/%s_%s_%s_pcs_%s.npy' %(homedir,project,task,atlas,run_version),np.array(subject_pcs))
np.save('%sdynamic_mod/results/%s_%s_%s_wmds_%s.npy' %(homedir,project,task,atlas,run_version),np.array(subject_wmds))
np.save('%sdynamic_mod/results/%s_%s_%s_mods_%s.npy' %(homedir,project,task,atlas,run_version),np.array(subject_mods))
np.save('%sdynamic_mod/results/%s_%s_%s_subs_%s.npy' %(homedir,project,task,atlas,run_version),np.array(finished_subjects))
np.save('%sdynamic_mod/results/%s_%s_%s_matrices_%s.npy'%(homedir,project,task,atlas,run_version),np.array(matrices))
np.save('%sdynamic_mod/results/%s_%s_%s_coms_%s.npy' %(homedir,project,task,atlas,run_version),np.array(subject_communities))
np.save('%sdynamic_mod/results/%s_%s_%s_z_matrices_%s.npy'%(homedir,project,task,atlas,run_version),np.array(thresh_matrices))
subject_mods = np.array(subject_mods)
subject_pcs = np.array(subject_pcs)
subject_wmds = np.array(subject_wmds)
subject_communities = np.array(subject_communities)
matrices = np.array(matrices)
thresh_matrices = np.array(thresh_matrices)
results = {}
results['subject_pcs'] = subject_pcs
results['subject_mods'] = subject_mods
results['subject_wmds'] = subject_wmds
results['subject_communities'] = subject_communities
results['matrices'] = matrices
del matrices
results['z_scored_matrices'] = thresh_matrices
results['subjects'] = finished_subjects
del thresh_matrices
return results
def pc_edge_correlation(subject_pcs,matrices,path):
try:
pc_edge_corr = np.load(path)
except:
pc_edge_corr = np.zeros((subject_pcs.shape[1],subject_pcs.shape[1],subject_pcs.shape[1]))
subject_pcs[np.isnan(subject_pcs)] = 0.0
for i in range(subject_pcs.shape[1]):
for n1,n2 in combinations(range(subject_pcs.shape[1]),2):
val = pearsonr(subject_pcs[:,i],matrices[:,n1,n2])[0]
pc_edge_corr[i,n1,n2] = val
pc_edge_corr[i,n2,n1] = val
np.save(path,pc_edge_corr)
return pc_edge_corr
def pc_edge_q_figure(tasks = ['REST','WM','GAMBLING','RELATIONAL','MOTOR','LANGUAGE','SOCIAL']):
"""
edge weight mediation of pearsonr(PC,Q) =
(regression coefficient of edge weight by PC) How much variance in the edge is explained by PC
(regression coefficient of Q by edge weight, controlling for PC) How much variance in Q is explained by the edge weight, controlling for PC.
"""
driver = 'PC'
project='hcp'
tasks = ['REST','WM','GAMBLING','RELATIONAL','MOTOR','LANGUAGE','SOCIAL']
atlas = 'power'
run_version = 'fz'
known_membership,network_names,num_nodes,name_int_dict = network_labels(atlas)
q_corr_matrix = []
pc_corr_matrix = []
#order by primary versus secondary networks.
network_order = ['Auditory','Sensory/somatomotor Hand','Sensory/somatomotor Mouth','Visual','Dorsal attention','Ventral attention',
'Cingulo-opercular Task Control','Salience','Fronto-parietal Task Control','Default mode','Cerebellar','Subcortical','Memory retrieval?','Uncertain']
colors = np.array(pd.read_csv('%smodularity/Consensus264.csv'%(homedir),header=None)[34].values)
colors[colors=='Pale blue'] = '#ADD8E6'
colors[colors=='Teal'] = '#008080'
swap_indices = []
for nn in network_order:
original_idx = np.where(network_names == nn)
for i in range(len(original_idx[0])):
swap_indices.append(original_idx[0][i])
locality_df = pd.DataFrame()
stats = []
for task in tasks:
print task
subjects = np.load('%sdynamic_mod/results/%s_%s_%s_subs_%s.npy' %(homedir,project,task,atlas,run_version))
static_results = graph_metrics(subjects,task,atlas,run_version)
subject_pcs = static_results['subject_pcs']
subject_mods = static_results['subject_mods']
subject_wmds = static_results['subject_wmds']
matrices = static_results['matrices']
assert subject_pcs.shape[0] == len(subjects)
mean_pc = np.nanmean(subject_pcs,axis=0)
mean_wmd = np.nanmean(subject_wmds,axis=0)
mod_pc_corr = np.zeros(subject_pcs.shape[1])
for i in range(subject_pcs.shape[1]):
mod_pc_corr[i] = nan_pearsonr(subject_mods,subject_pcs[:,i])[0]
mod_wmd_corr = np.zeros(subject_wmds.shape[1])
for i in range(subject_wmds.shape[1]):
mod_wmd_corr[i] = nan_pearsonr(subject_mods,subject_wmds[:,i])[0]
if driver == 'PC': m = np.load('%s/dynamic_mod/results/full_med_matrix_new_%s.npy'%(homedir,task))
else: m = np.load('%s/dynamic_mod/results/full_med_matrix_new_%s_wmds.npy'%(homedir,task))
mean_conn = np.nanmean(matrices,axis=0)
e_tresh = np.percentile(mean_conn,85)
for i in range(264):
real_t = scipy.stats.ttest_ind(np.abs(m)[i][np.argwhere(mean_conn[i]>=e_tresh)][:,:,np.arange(264)!=i].reshape(-1),np.abs(m)[i][np.argwhere(mean_conn[i]<e_tresh)][:,:,np.arange(264)!=i].reshape(-1))[0]
# real_t = scipy.stats.ttest_ind(m[i][np.argwhere(mean_conn[i]>=e_tresh)][:,:,np.arange(264)!=i].reshape(-1),m[i][np.argwhere(mean_conn[i]<e_tresh)][:,:,np.arange(264)!=i].reshape(-1))[0]
if mod_pc_corr[i] > 0.0:
locality_df = locality_df.append({"Node Type":'Connector Hub','t':real_t,'Task':task.capitalize()},ignore_index=True)
else:
locality_df = locality_df.append({"Node Type":'Local Node','t':real_t,'Task':task.capitalize()},ignore_index=True)
locality_df.dropna(inplace=True)
if driver == 'PC':
predict_nodes = np.where(mod_pc_corr>0.0)[0]
local_predict_nodes = np.where(mod_pc_corr<0.0)[0]
pc_edge_corr = np.arctanh(pc_edge_correlation(subject_pcs,matrices,path='%s/dynamic_mod/results/%s_%s_%s_pc_edge_corr_z.npy' %(homedir,project,task,atlas)))
if driver == 'WMD':
predict_nodes = np.where(mod_wmd_corr>0.0)[0]
local_predict_nodes = np.where(mod_wmd_corr<0.0)[0]
pc_edge_corr = np.arctanh(pc_edge_correlation(subject_wmds,matrices,path='%s/dynamic_mod/results/%s_%s_%s_wmd_edge_corr_z.npy' %(homedir,project,task,atlas)))
n_nodes = pc_edge_corr.shape[0]
q_edge_corr = np.zeros((n_nodes,n_nodes))
perf_edge_corr = np.zeros((n_nodes,n_nodes))
for i,j in combinations(range(n_nodes),2):
ijqcorr = nan_pearsonr(matrices[:,i,j],subject_mods)[0]
q_edge_corr[i,j] = ijqcorr
q_edge_corr[j,i] = ijqcorr
# continue
# if task not in ['WM','RELATIONAL','SOCIAL','LANGUAGE']:
# continue
# ijqcorr = nan_pearsonr(matrices[:,i,j],task_perf)[0]
# perf_edge_corr[i,j] = ijqcorr
# perf_edge_corr[j,i] = ijqcorr
pc_corr_matrix.append(np.nanmean(pc_edge_corr[predict_nodes,:,:],axis=0))
q_corr_matrix.append(q_edge_corr)
# if task in ['WM','RELATIONAL','SOCIAL','LANGUAGE']:
# print nan_pearsonr(perf_edge_corr.reshape(-1),np.nanmean(pc_edge_corr[predict_nodes,:,:],axis=0).reshape(-1))
# plot_corr_matrix(perf_edge_corr[:,swap_indices][swap_indices],network_names[swap_indices].copy(),out_file='%s/dynamic_mod/figures/%s_%s_edge_perf_corr_matrix.pdf'%(homedir,task,run_version),reorder=False,colors=colors[swap_indices],line=True,draw_legend=True,rectangle=False)
# plot_corr_matrix(np.nanmean(m[predict_nodes,:,:],axis=0)[:,swap_indices][swap_indices],network_names[swap_indices].copy(),out_file='%s/dynamic_mod/figures/%s_%s_%s_mediation_matrix.pdf'%(homedir,task,driver,run_version),reorder=False,colors=colors[swap_indices],line=True,draw_legend=True,rectangle=False)
# plot_corr_matrix(np.nanmean(pc_edge_corr[predict_nodes],axis=0)[:,swap_indices][swap_indices],network_names[swap_indices].copy(),out_file='%s/dynamic_mod/figures/%s_%s_pcedge__corr_matrix.pdf'%(homedir,task,run_version),reorder=False,colors=colors[swap_indices],line=True,draw_legend=True,rectangle=False)
# plot_corr_matrix(q_edge_corr[:,swap_indices][swap_indices],network_names[swap_indices].copy(),out_file='%s/dynamic_mod/figures/%s_%s_%s_qedgecorr_matrix.pdf'%(homedir,task,driver,run_version),reorder=False,colors=colors[swap_indices],line=True,draw_legend=True,rectangle=False)
plot_corr_matrix(np.nanmean(q_corr_matrix,axis=0)[:,swap_indices][swap_indices],network_names[swap_indices].copy(),out_file='%s/dynamic_mod/figures/%s_mean_q_corr_matrix.pdf'%(homedir,run_version),reorder=False,colors=colors[swap_indices],line=True,draw_legend=True,rectangle=False)
plot_corr_matrix(np.nanmean(pc_corr_matrix,axis=0)[:,swap_indices][swap_indices],network_names[swap_indices].copy(),out_file='%s/dynamic_mod/figures/%s_mean_pc_corr_matrix.pdf'%(homedir,run_version),reorder=False,colors=colors[swap_indices],line=True,draw_legend=True,rectangle=False)
plot_corr_matrix(np.nanmean(m[predict_nodes,:,:],axis=0)[:,swap_indices][swap_indices],network_names[swap_indices].copy(),out_file='%s/dynamic_mod/figures/%s_%s_mean_mediation_matrix_withbar.pdf'%(homedir,driver,run_version),reorder=False,colors=colors[swap_indices],line=True,draw_legend=True,rectangle=False)
# plot_corr_matrix(np.nanmean(pc_corr_matrix,axis=0)[:,swap_indices][swap_indices],network_names[swap_indices].copy(),out_file=None,reorder=False,colors=colors[swap_indices],line=True,draw_legend=True,rectangle=False)
f = sns.plt.figure(figsize=(18,6))
sns.set_style("white")
sns.set_style("ticks")
sns.set(context="paper",font='Helvetica',font_scale=1.2)
sns.violinplot(data=locality_df[locality_df['Node Type']=='Connector Hub'],x='Task',y='t',hue='Task',inner='quartile',palette=sns.palettes.color_palette('Paired',7))
sns.plt.ylabel("T Test Values, mediation values of node's nieghbors \n versus mediation of node's non-neighbors")
sns.plt.legend(bbox_to_anchor=[1,1.05],ncol=7,columnspacing=10)
sns.plt.savefig('%s/dynamic_mod/figures/%s_mediation_t_test.pdf'%(homedir,run_version))
sns.plt.show()
# plot_corr_matrix(mean_conn[:,swap_indices][swap_indices],network_names[swap_indices].copy(),out_file=None,reorder=False,colors=colors[swap_indices],line=True,draw_legend=True,rectangle=False)
def network_labels(atlas):
if atlas == 'gordon':
name_dict = {}
df = pd.read_excel('%sdynamic_mod/Parcels.xlsx'%(homedir))
df.Community[df.Community=='None'] = 'Uncertain'
for i,com in enumerate(np.unique(df.Community.values)):
name_dict[com] = i
known_membership = np.zeros((333))
for i in range(333):
known_membership[i] = name_dict[df.Community[i]]
network_names = np.array(df.Community.values).astype(str)
if atlas == 'power':
known_membership = np.array(pd.read_csv('%smodularity/Consensus264.csv'%(homedir),header=None)[31].values)
known_membership[known_membership==-1] = 0
network_names = np.array(pd.read_csv('%smodularity/Consensus264.csv'%(homedir),header=None)[36].values)
name_int_dict = {}
for name,int_value in zip(network_names,known_membership):
name_int_dict[int_value] = name
return known_membership,network_names,len(known_membership),name_int_dict
def split_connectivity_across_tasks(n_iters=10000):
global hcp_subjects
try:
df = pd.read_csv('/home/despoB/mb3152/dynamic_mod/results/split_corrs.csv')
except:
split = True
tasks = ['WM','GAMBLING','RELATIONAL','MOTOR','LANGUAGE','SOCIAL','REST']
project='hcp'
atlas = 'power'
known_membership,network_names,num_nodes,name_int_dict = network_labels(atlas)
df_columns=['Task','Pearson R, PC, PC & Q','Pearson R, WCD, WCD & Q']
df = pd.DataFrame(columns = df_columns)
for task in tasks:
print task
subjects = np.array(hcp_subjects).copy()
subjects = list(subjects)
subjects = remove_missing_subjects(subjects,task,atlas)
assert (subjects == np.load('/home/despoB/mb3152/dynamic_mod/results/hcp_%s_%s_subs_fz.npy'%(task,atlas))).all()
static_results = graph_metrics(subjects,task,atlas)
subject_pcs = static_results['subject_pcs']
subject_mods = static_results['subject_mods']
subject_wmds = static_results['subject_wmds']
matrices = static_results['matrices']
task_perf = task_performance(subjects,task)
assert subject_pcs.shape[0] == len(subjects)
wmd_rs = []
pc_rs = []
from sklearn.cross_validation import ShuffleSplit
for pc_subs,pc_mod_subjects in ShuffleSplit(n=len(subjects),n_iter=n_iters,train_size=.5,test_size=.5):
mod_pc_corr = np.zeros(subject_pcs.shape[1])
mod_wmd_corr = np.zeros(subject_pcs.shape[1])
mean_pc = np.nanmean(subject_pcs[pc_subs,],axis=0)
mean_wmd = np.nanmean(subject_wmds[pc_subs,],axis=0)
for i in range(subject_pcs.shape[1]):
mod_pc_corr[i] = nan_pearsonr(subject_mods[pc_mod_subjects],subject_pcs[pc_mod_subjects,i])[0]
mod_wmd_corr[i] = nan_pearsonr(subject_mods[pc_mod_subjects],subject_wmds[pc_mod_subjects,i])[0]
df = df.append({'Task':task,'Pearson R, PC, PC & Q':nan_pearsonr(mod_pc_corr,mean_pc)[0],'Pearson R, WCD, WCD & Q':nan_pearsonr(mod_wmd_corr,mean_wmd)[0]},ignore_index=True)
print np.mean(df['Pearson R, PC, PC & Q'][df.Task==task])
print np.mean(df['Pearson R, WCD, WCD & Q'][df.Task==task])
df.to_csv('/home/despoB/mb3152/dynamic_mod/results/split_corrs.csv')
sns.plt.figure(figsize=(20,10))
sns.violinplot(data=df,y='Pearson R, PC, PC & Q',x='Task',inner='quartile')
sns.plt.savefig('/home/despoB/mb3152/dynamic_mod/figures/split_pc.pdf',dpi=3600)
sns.plt.close()
sns.violinplot(data=df,y='Pearson R, WCD, WCD & Q',x='Task',inner='quartile')
sns.plt.savefig('/home/despoB/mb3152/dynamic_mod/figures/split_wcd.pdf',dpi=3600)
sns.plt.close()
def run_fd(subject,task):
try:
MP = np.load('/home/despoB/mb3152/dynamic_mod/motion_files/%s_%s.npy' %(subject,task))
except:
outfile = '/home/despoB/mb3152/dynamic_mod/motion_files/%s_%s.npy' %(subject,task)
MP = np.loadtxt('/home/despoB/connectome-raw/%s/MNINonLinear/Results/%s/Movement_Regressors.txt'%(subject,task))
FD = brain_graphs.compute_FD(MP[:,:6])
FD = np.append(0,FD)
np.save(outfile,FD)
MP = np.load('/home/despoB/mb3152/dynamic_mod/motion_files/%s_%s.npy' %(subject,task))
return MP
def get_sub_motion(subject,task):
motion_files = glob.glob('/home/despoB/mb3152/dynamic_mod/motion_files/%s_*%s*' %(subject,task))
if len(motion_files) == 0:
smo = np.nan
if len(motion_files) > 0:
smo = []
for m in motion_files:
smo.append(np.nanmean(np.load(m)))
smo = np.nanmean(smo)
return smo
def hcp_motion(subject,task):
motion_files = glob.glob('/home/despoB/connectome-raw/%s/MNINonLinear/Results/*%s*/Movement_RelativeRMS_mean.txt'%(subject,task))
smo = []
for m in motion_files:
smo.append(np.nanmean(np.loadtxt(m)))
smo = np.nanmean(smo)
return smo
def compare_motion_params(subjects,task):
my_ver = []
hcp_ver = []
for s in hcp_subjects:
my_ver.append(get_sub_motion(s,''))
hcp_ver.append(hcp_motion(s,''))
def all_motion(tasks,atlas='power'):
everything = ['tfMRI_WM_RL','tfMRI_WM_LR','rfMRI_REST1_LR','rfMRI_REST2_LR','rfMRI_REST1_RL','rfMRI_REST2_RL','tfMRI_RELATIONAL_LR','tfMRI_RELATIONAL_RL','tfMRI_SOCIAL_RL','tfMRI_SOCIAL_LR','tfMRI_LANGUAGE_LR','tfMRI_LANGUAGE_RL','tfMRI_GAMBLING_RL','tfMRI_MOTOR_RL','tfMRI_GAMBLING_LR','tfMRI_MOTOR_LR']
for task in everything:
print task
if 'REST' in task:
subjects = np.load('/home/despoB/mb3152/dynamic_mod/results/%s_%s_%s_subs_fz.npy' %('hcp',task.split('_')[1][:4],atlas))
else:
subjects = np.load('/home/despoB/mb3152/dynamic_mod/results/%s_%s_%s_subs_fz.npy' %('hcp',task.split('_')[1],atlas))
for subject in subjects:
try:
run_fd(subject,task)
except:
print subject,task
def individual_differnce_networks(task,atlas='power',run_version='fz'):
known_membership,network_names,num_nodes,name_int_dict = network_labels(atlas)
network_order = ['Auditory','Sensory/somatomotor Hand','Sensory/somatomotor Mouth','Visual','Dorsal attention','Ventral attention',
'Cingulo-opercular Task Control','Salience','Fronto-parietal Task Control','Default mode','Cerebellar','Subcortical','Memory retrieval?','Uncertain']
colors = np.array(pd.read_csv('%smodularity/Consensus264.csv'%(homedir),header=None)[34].values)
colors[colors=='Pale blue'] = '#ADD8E6'
colors[colors=='Teal'] = '#008080'
swap_indices = []
for nn in network_order:
original_idx = np.where(network_names == nn)
for i in range(len(original_idx[0])):
swap_indices.append(original_idx[0][i])
subjects = np.load('/home/despoB/mb3152/dynamic_mod/results/%s_%s_%s_subs_%s.npy' %('hcp',task,atlas,run_version))
static_results = graph_metrics(subjects,task,atlas,run_version=run_version)
matrices = static_results['matrices']
diff_matrix = np.zeros((264,264))
for i,j in combinations(range(264),2):
r = np.nanmean(np.diagonal(generate_correlation_map(matrices[:,i,:].swapaxes(0,1), matrices[:,j,:].swapaxes(0,1))))
diff_matrix[i,j] = r
diff_matrix[j,i] = r
plot_corr_matrix(matrix=diff_matrix[:,swap_indices][swap_indices],membership=network_names[swap_indices].copy(),out_file=None,reorder=False,colors=colors[swap_indices],line=True,draw_legend=True,rectangle=False)
plot_corr_matrix(matrix=np.nanmean(matrices,axis=0)[:,swap_indices][swap_indices],membership=network_names[swap_indices].copy(),out_file=None,reorder=False,colors=colors[swap_indices],line=True,draw_legend=True,rectangle=False)
plot_corr_matrix(matrix=diff_matrix-np.nanmean(matrices,axis=0)[:,swap_indices][swap_indices],membership=network_names[swap_indices].copy(),out_file=None,reorder=False,colors=colors[swap_indices],line=True,draw_legend=True,rectangle=False)
for network in np.unique(network_names):
print network, np.mean((diff_matrix-np.nanmean(matrices,axis=0))[network_names==network][:,network_names!=network])
for network in np.unique(network_names):
print network, scipy.stats.ttest_ind((diff_matrix-np.nanmean(matrices,axis=0))[network_names==network][:,network_names!=network].reshape(-1),(diff_matrix-np.nanmean(matrices,axis=0))[network_names==network][:,network_names==network].reshape(-1))
def make_mean_matrix():
atlas = 'power'
for task in ['WM','GAMBLING','RELATIONAL','MOTOR','LANGUAGE','SOCIAL','REST']:
print task
matrix = []