-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSim_les_git_code.py
More file actions
2157 lines (1442 loc) · 73.2 KB
/
Copy pathSim_les_git_code.py
File metadata and controls
2157 lines (1442 loc) · 73.2 KB
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
################################################################################
# Code for: Computatoinal Lesionoing of Heterogenous Functional Connectomes #
# Explains Variance in Callous-Unemotional Traits #
# #
# Code by: Drew E. Winters. PhD. #
################################################################################
# Packages
# for file paths
import os, glob, pathlib
# for plotting
import matplotlib.pyplot as plt
import seaborn as sns
from pycebox.ice import ice, ice_plot ## for ICE plots
from nilearn import plotting
# for data manupulation
import pandas as pd #
import numpy as np #
import re # for data manipulation to remove prefix/suffix using regex
# for network analysis
import networkx as nx # for network analysis
import bct # brain connectivity toolbox
# system
import warnings # what to do with warnings
warnings.filterwarnings('ignore')
from joblib import parallel_backend ## parallel processing
# machine learning
from sklearn.covariance import GraphicalLassoCV # used to get the precision matrix
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge, RidgeCV, Lasso, ElasticNet
from nilearn import connectome
from sklearn.compose import make_column_selector as selector
from sklearn.preprocessing import StandardScaler
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import cross_val_score, KFold, cross_validate
from scipy.stats import loguniform
from sklearn.model_selection import RandomizedSearchCV
from sklearn.model_selection import StratifiedKFold
from sklearn.linear_model import ElasticNet
from sklearn.model_selection import permutation_test_score # for permutation testing
# stats
import scipy
import statsmodels.formula.api as smf ## for MLM
import statsmodels.api as sm
from scipy import stats
import random
from sklearn.metrics import rand_score, adjusted_rand_score # similarity between community detection iterations.
# centered residual interaction terms
from resmod.single import residual_center
# brain data tools
import nltools ## to create the mask
import nibabel as nib ## manipulate nii.gz files
# Data
# Parcelization Labels and coordinates
# - note for labels and coordinates
# * names from the Harvard Oxford atlas in CONN reflects two atlases
# + 1) Harvard Oxford atlas - cortical and sub-cortical areas
# + 2) automated anatomical labeling (AAL) atlas - cerebellar areas
# - link describing labels = <https://www.nitrc.org/frs/shownotes.php?release_id=2823>
# - link describing coordinates = <https://www.nitrc.org/forum/forum.php?thread_id=11220&forum_id=1144>
# LABELS
labels = pd.read_csv(r"C:\Users\wintersd\OneDrive - The University of Colorado Denver\1 Publications\CU traits and ANTS cog funct\Subj_timeseries_denoised\ROInames.csv", header=None).iloc[:,3:167]
labels = np.array(labels)[0]
# COORDINATES
coords = pd.read_csv(r"C:\Users\wintersd\OneDrive - The University of Colorado Denver\1 Publications\Simulated lesions and network analyses\CONN_coordinates NO LABELS.csv", header=None)
coords.columns = ["x", "y", "z"] ## If I want to add this - not sure
# FILE NAMES LIST
# creaing a list of the file names
import glob
csv_list = glob.glob(r"C:\Users\wintersd\OneDrive - The University of Colorado Denver\1 Publications\CU traits and ANTS cog funct\Subj_timeseries_denoised\ROI*")[2:88]
for i in range(0,len(csv_list)):
print(os.path.basename(os.path.normpath(csv_list[i])))
# EXTRACTING TIMESERIES
# assigning each timeseries csv to a single list
# we are only keeping the columns that are related to the nodes form the parcelization
# the others have confounds.
time_s=[]
for i in range(0,len(csv_list)):
time_s.append(pd.read_csv(csv_list[i], header= None).iloc[:,3:167])
#time_s
print("Total number of participants = ",len(time_s))
## checking the dimension of vars downloaded
for i in range(0,len(time_s)):
print("Dimensions for participant #",i,"=",time_s[i].shape)
# EXTRACTIG HEAD MOTION
## here we extract the headmotiong variable to use as a covariate
head_m=[]
from joblib import parallel_backend
with parallel_backend('threading', n_jobs=12):
for i in range(0,len(csv_list)):
head_m.append(pd.read_csv(csv_list[i], header= None).iloc[:,169].to_numpy())
## test to ensure we have the right number
len(head_m) == 86 # True
# averaging headmotion for each participant
## will use this as a covariate later
head_m_ave = []
from joblib import parallel_backend
with parallel_backend('threading', n_jobs=12):
for i in head_m:
head_m_ave.append(np.average(i))
## test to ensure right #
len(head_m_ave) == 86 # True
## Assigning to dataframe
head_m_ave = pd.DataFrame({"h_move":head_m_ave})
### CONSTRUCTING PRECISION MATRICIES USING GRAPHICAL LASSO
# > here we are using a precision matrix because:
# - We use the precision matrix becuase it allows us to only examine direct connection between ROIs
# * As shown in [Smith 2011], [Varoquaux 2010], it is more interesting to
# * use the inverse covariance matrix, ie the precision matrix. It gives
# * only direct connections between regions, as it contains partial covariances,
# * which are covariances between two regions conditioned on all the others.
# - Instead of using an arbitrary thresholded matrix representing characteritics of the data
# * the graphical lasso is a principled way to arive at a sparse matrix
# * that is more reproducable
from sklearn.covariance import GraphicalLassoCV
from sklearn.preprocessing import StandardScaler
estimator = GraphicalLassoCV()
scaler = StandardScaler()
# estimating the precision matricies
prec_mat =[] # initializing the list to append to
from joblib import parallel_backend
with parallel_backend('threading', n_jobs=12): ## running parallel processes for the following function
for i in range(0,len(time_s)):
#print(i)
scaler.fit(time_s[i])
prec = estimator.fit(scaler.transform(time_s[i])).precision_ ## creating a precision matrix object
np.fill_diagonal(prec, 0) ## filling diagonal of matrix to 0
prec_mat.append(prec) ## appending precision matrix to list
# SIMULATED LESIONS
# Loop: functional node removal
# - removing each node and then calculating
# * 1) overall efficiency for the network
# * 2) overall change in modularity
# - this function is simulating lesions across the entire brain
# * by making a 0 across each column and row in the matrix
# * then retesting each time what happens to the efficiency using charpath
# - what the value represents is the entire matrix
# * efficiency after removing the node
# * modularity after removing the node
eff_lesion = []
delta_eff = []
from joblib import parallel_backend
with parallel_backend('threading', n_jobs=12):
for i in range(0,len(prec_mat)):
eff_lesion = []
eff = bct.charpath(bct.distance_bin(np.array(prec_mat[i])))[1]
num_nodes = len(prec_mat[i])
for j in range(0,num_nodes):
CIJ_lesion = np.matrix(prec_mat[i])
CIJ_lesion[j,:]= np.zeros(num_nodes)
CIJ_lesion[:,j]= np.zeros([num_nodes,1]) # note I use ,1 here to denote a column vector
d = bct.distance_bin(np.array(CIJ_lesion)) ## not sure this is necessary but I could add .astype(int)
eff_lesion.append(bct.charpath(d)[1]) # note I am indicating [1] becaues that is the efficiency.
delta_eff.append(eff_lesion-eff) # delta efficiency array
# Delta dataframes -- EFFICIENCY DELTA
node_eff_delta = pd.DataFrame(np.vstack([delta_eff[0]]),c
olumns=['node_eff_' + sub for sub in labels])
for i in range(1,len(delta_eff)):
#print(i)
node_eff_delta = pd.DataFrame(np.vstack([node_eff_delta,delta_eff[i]]),
columns=['node_eff_' + sub for sub in labels])
# COMMUNITY DETECTION AND VALIDATION
# - Here we take multipe stept to retain reliable louvain community detection netwokrs
# * estimate 5 netwrks for each individual to ID optimal gamma value
# * estimate 5 netwroks usign the optimal gamma for each individual
# * then calculate similarity and consensus communities across all 5 new iterations
# Setting up gamma values to tune
num_nodes = np.size(prec_mat[1],1);
num_participants = len(prec_mat)
num_reps = 5;
# gamma a range list
def range_inc(start, stop, step, inc):
i = start
while i < stop:
yield i
i += step
step += inc
gamma_range = list(range_inc(0.5, 4.25, 0.25, 0))
## the reason I have the stop at 4.25 is becaues I Want to include 4 at the end
num_gamma = len(gamma_range);
# Hyperparameter tuning Gamma
from sklearn.metrics import rand_score
cia = []
da = []
from joblib import parallel_backend
with parallel_backend('threading', n_jobs=12):
for z in range(0,num_participants):
# preallocate some arrays to store communities and similarity scores
ci = np.zeros([num_nodes,num_reps,num_gamma]);
d = np.empty([num_reps,num_gamma])
d[:] = np.NaN
for i in range(0,num_gamma):
gamma = gamma_range[i]
for ii in range(0,num_reps):
# print(ii)
ci[:,ii,i] = bct.community_louvain((prec_mat[z]),gamma = gamma, B='negative_asym')[0]
d[ii,i] = rand_score(ci[:,ii,i],np.array(labels))**2## thsi is the zrand score
cia.append(ci)
da.append(d)
# estimating peak for each individual
b= []
a=np.zeros([len(da),len(da[0])])
for i in range(0, len(da)):
for ii in range(0,len(da[i])):
a[i][ii]=(max(da[i][ii]))
b.append(max(a[i]))
# np.where(da[i]== max(b[i]))
# identify the gamma at which similarity has peaked for each participant
ind_gamma = []
for i in range(0, len(da)):
if int(np.where(np.matrix.flatten(da[i]) == b[i])[0][0]) >= 15:
ind_gamma.append(gamma_range[int(round(int(np.where(np.matrix.flatten(da[i]) == b[i])[0][0])%15))])
else:
ind_gamma.append(gamma_range[int(np.where(np.matrix.flatten(da[i]) == b[i])[0][0])])
# Reruning Community detection with optimal gamma
num_reps = len(prec_mat[0])
ddu = []
from joblib import parallel_backend
with parallel_backend('threading', n_jobs=12):
for i in range(0,num_participants):
aa = []
for ii in range(0, num_reps):
aa.append(bct.community_louvain(prec_mat[i], gamma = ind_gamma[i], B='negative_asym')[0])
ddu.append(aa)
# calculating agreement across Louvain iterations for each individual
thr = 0.5
# ammount of agreement between iterations of community detection
d = []
from joblib import parallel_backend
with parallel_backend('threading', n_jobs=12):
for i in range(0,len(ddu)):
d.append(bct.agreement(ddu[i])/num_reps)
# calculating consensus communities across Louvain iterations for each individual
# community detection for each node
# the community a node belongs to
comm = []
from joblib import parallel_backend
with parallel_backend('threading', n_jobs=12):
for i in range(0,len(d)):
comm.append(bct.consensus_und(d[i],thr,num_reps))
# LOOP: NETWORK PROPERTIES
# - Participation coefficient, within-module density z-score, modularity, density
# * here we extract modularity for each individual from Louvain results
# * then we calculate a participation coefficient for each individual node
mod=[]# modularity
# networks with high modularity have dense connections within modules and sparser connections between modules
# in other words - high modularity means that there are more clicks *aka they form more modules* where as low modularity pertains to less modularity meaning greater connections between networks.
part=[] # participation coefficient
# used to measure global hub -- aka: hubs that are connected across multiple modules
# Participation coefficients measure the distribution of a node's edges among the communities of a graph
# If a node's edges are entirely restricted to its community, its participation coefficient is 0.
# If the node's edges are evenly distributed among all communities, the participation coefficient is a maximal value that approaches 1
# nodes with low participation scores are local hubs
# nodes with high participation coefficient are more global hubs
mod_deg=[] # within-module degree z-score
# used to assess for local hub -- aka: hubs that are connected mainly within one module
#it's the z-score of a node's within-module degree; z-scores greater than 2.5 denote hub status
dense = []# this is just the overall density of the network
for i in range(0,len(prec_mat)):
mod.append(bct.modularity_louvain_dir(prec_mat[i],
gamma=ind_gamma[i],
seed=123)[1])
part.append(bct.participation_coef(prec_mat[i],
bct.modularity_louvain_dir(prec_mat[i],
gamma=ind_gamma[i],
seed=123)[0]))
mod_deg.append(bct.module_degree_zscore(prec_mat[i],
bct.modularity_louvain_dir(prec_mat[i],
gamma=ind_gamma[i],
seed=123)[0]))
dense.append(bct.density_und(prec_mat[i])[0])
# CALCULATING HUBS:
# Global hubs
def NormalizeData(data):
return (data - np.min(data)) / (np.max(data) - np.min(data))
scale= StandardScaler()
part_norm = []
for i in range(0,len(part)):
part_norm.append(NormalizeData(scale.fit_transform(part).astype('float')[i]))
# Identifying global hubs
import scipy
global_hub = []
for i in range(0,len(part_norm)):
ee = []
for j in range(0,(len(part_norm[0]))):
#print(i,j)
ee.append(int(np.where(part_norm[i][j] >= (np.median(part_norm[i]) + scipy.stats.median_absolute_deviation(part_norm[i])), 1, 0)))
global_hub.append(ee)
# Global hub dataframe
global_hub_df = pd.DataFrame(np.vstack([global_hub[0]]),
columns=['global_h_' + sub for sub in labels])
for i in range(1,len(global_hub)):
#print(i)
global_hub_df = pd.DataFrame(np.vstack([global_hub_df,global_hub[i]]),
columns=['global_h_' + sub for sub in labels])
# Number of global hubs
global_sum=[]
for i in range(0,len(global_hub)):
print("Global hubs for participant",i,"=",sum(global_hub[i]),
"\n", "% of hubs =", round((sum(global_hub[i])/len(global_hub[i]))*100,1) ,"%")
global_sum.append(sum(global_hub[i]))
# Local hubs
mod_deg_norm = []
for i in range(0,len(mod_deg)):
mod_deg_norm.append(NormalizeData(scale.fit_transform(mod_deg).astype('float')[i]))
# Identifying local hubs
local_hub = []
for i in range(0,len(mod_deg_norm)):
ee = []
for j in range(0,(len(mod_deg_norm[0]))):
#print(i,j)
ee.append(int(np.where(mod_deg_norm[i][j] >= (np.median(mod_deg_norm[i])+scipy.stats.median_absolute_deviation(mod_deg_norm[i])), 1, 0)))
local_hub.append(ee)
# Number of local hubs
local_sum = []
for i in range(0,len(local_hub)):
print("local hubs for participant",i,"=",
sum(local_hub[i]), "\n", "% of hubs =",
round((sum(local_hub[i])/len(local_hub[i]))*100,1) ,"%")
local_sum.append(sum(local_hub[i]))
# Local hub dataframe
local_hub_df = pd.DataFrame(np.vstack([local_hub[0]]),
columns=['local_h_' + sub for sub in labels])
for i in range(1,len(local_hub)):
#print(i)
local_hub_df = pd.DataFrame(np.vstack([local_hub_df,
local_hub[i]]),
columns=['local_h_' + sub for sub in labels])
# NON-HUB IDENTIFICATION
# connectors
import scipy
connector_non_hub = []
for i in range(0,len(part_norm)):
ee = []
for j in range(0,(len(part_norm[0]))):
#print(i,j)
ee.append(int(np.where((part_norm[i][j] > (np.median(part_norm[i]))) & (part_norm[i][j] <
(np.median(part_norm[i])+scipy.stats.median_absolute_deviation(part_norm[i]))),1,0)))
connector_non_hub.append(ee)
connector_sum = []
for i in range(0,len(connector_non_hub)):
print("connector non-hub for participant",i,"=",
sum(connector_non_hub[i]), "\n", "% of hubs =",
round((sum(connector_non_hub[i])/len(connector_non_hub[i]))*100,1) ,"%")
connector_sum.append(sum(connector_non_hub[i]))
# Periphery
import scipy
periphery_non_hub = []
for i in range(0,len(mod_deg_norm)):
ee = []
for j in range(0,(len(mod_deg_norm[0]))):
#print(i,j)
ee.append(int(np.where((mod_deg_norm[i][j] > (np.median(mod_deg_norm[i]))) & (mod_deg_norm[i][j] <
(np.median(mod_deg_norm[i])+scipy.stats.median_absolute_deviation(mod_deg_norm[i]))),1,0)))
periphery_non_hub.append(ee)
periphery_sum = []
for i in range(0,len(periphery_non_hub)):
print("periphery non-hub for participant",i,"=",
sum(periphery_non_hub[i]), "\n", "% of hubs =",
round((sum(periphery_non_hub[i])/len(periphery_non_hub[i]))*100,1) ,"%")
periphery_sum.append(sum(periphery_non_hub[i]))
# TARGETED LESIONS
# > here we calculate changes in modularity and efficiency after removing global and local nodes for each individual participant
# > We then averaged the change in the overall network for removing each global node to get a sense for overall impact of global nodes
#
# > these will be used later to examine differnces targetd node attacks.
# Targeting Global nodes
eff_global_les = []
delta_global_eff = []
from joblib import parallel_backend
with parallel_backend('threading', n_jobs=12):
for i in range(0,len(prec_mat)):
#print(i)
eff_global_les = []
effs = bct.charpath(bct.distance_bin(np.array(prec_mat[i])))[1]
CIJ_lesion = np.matrix(prec_mat[i])
for j in np.where(np.array(global_hub[i])==1)[0]:
CIJ_lesion[j,:] = np.zeros(len(prec_mat[0]))
CIJ_lesion[:,j] = np.zeros([len(prec_mat[0]),1])
d = bct.distance_bin(np.array(CIJ_lesion))
eff_global_les.append(bct.charpath(d)[1])
delta_global_eff.append(eff_global_les-effs)
delta_global_eff_mean = []
for i in delta_global_eff:
delta_global_eff_mean.append(np.mean(i))
# Targeting Local nodes
eff_local_les = []
delta_local_eff = []
from joblib import parallel_backend
with parallel_backend('threading', n_jobs=12):
for i in range(0,len(prec_mat)):
#print(i)
eff_local_les = []
effs = bct.charpath(bct.distance_bin(np.array(prec_mat[i])))[1]
CIJ_lesion = np.matrix(prec_mat[i])
for j in np.where(np.array(local_hub[i])==1)[0]:
CIJ_lesion[j,:] = np.zeros(len(prec_mat[0]))
CIJ_lesion[:,j] = np.zeros([len(prec_mat[0]),1])
d = bct.distance_bin(np.array(CIJ_lesion))
eff_local_les.append(bct.charpath(d)[1])
delta_local_eff.append(eff_local_les-effs)
delta_local_eff_mean = []
for i in delta_local_eff:
delta_local_eff_mean.append(np.mean(i))
# Targeting connector non-hubs
eff_connector_les = []
delta_connector_eff = []
from joblib import parallel_backend
with parallel_backend('threading', n_jobs=12):
for i in range(0,len(prec_mat)):
#print(i)
eff_connector_les = []
effs = bct.charpath(bct.distance_bin(np.array(prec_mat[i])))[1]
CIJ_lesion = np.matrix(prec_mat[i])
for j in np.where(np.array(connector_non_hub[i])==1)[0]:
CIJ_lesion[j,:] = np.zeros(len(prec_mat[0]))
CIJ_lesion[:,j] = np.zeros([len(prec_mat[0]),1])
d = bct.distance_bin(np.array(CIJ_lesion))
eff_connector_les.append(bct.charpath(d)[1])
delta_connector_eff.append(eff_connector_les-effs)
delta_connector_eff_mean = []
for i in delta_connector_eff:
delta_connector_eff_mean.append(np.mean(i))
# Targeting periphery non-hubs
eff_periphery_les = []
delta_periphery_eff = []
from joblib import parallel_backend
with parallel_backend('threading', n_jobs=12):
for i in range(0,len(prec_mat)):
#print(i)
eff_periphery_les = []
effs = bct.charpath(bct.distance_bin(np.array(prec_mat[i])))[1]
CIJ_lesion = np.matrix(prec_mat[i])
for j in np.where(np.array(periphery_non_hub[i])==1)[0]:
CIJ_lesion[j,:] = np.zeros(len(prec_mat[0]))
CIJ_lesion[:,j] = np.zeros([len(prec_mat[0]),1])
d = bct.distance_bin(np.array(CIJ_lesion))
eff_periphery_les.append(bct.charpath(d)[1])
delta_periphery_eff.append(eff_periphery_les-effs)
delta_periphery_eff_mean = []
for i in delta_periphery_eff:
delta_periphery_eff_mean.append(np.mean(i))
# CONSTRUCTING DATAFRAME
# Calculating base efficiency
eff=[]
for i in range(0,len(prec_mat)):
d = bct.distance_bin(prec_mat[i]);
eff.append(bct.charpath(d)[1])
# Column vectors for total network metrics
node_eff_delta["modularity"]=np.array(mod)
node_eff_delta["density"]=np.array(dense)
node_eff_delta["eff_base"]=np.array(eff)
node_eff_delta["global_hub"]=np.array(global_sum)
node_eff_delta["local_hub"]=np.array(local_sum)
# arrays for node metrics
#len(part)
part_df = pd.DataFrame(np.vstack([part_norm[0]]),
columns=['part_' + sub for sub in labels])
for i in range(1,len(part)):
#print(i)
part_df = pd.DataFrame(np.vstack([part_df,part_norm[i]]),
columns=['part_' + sub for sub in labels])
# community structure for each node
#len(comm)
comm_df = pd.DataFrame(np.vstack([comm[0]]),
columns=['comm_' + sub for sub in labels])
for i in range(1,len(comm)):
#print(i)
comm_df = pd.DataFrame(np.vstack([comm_df,comm[i]]),
columns=['comm_' + sub for sub in labels])
# modularity degree
mod_deg_df = pd.DataFrame(np.vstack([mod_deg_norm[0]]),
columns=['mod_deg_' + sub for sub in labels])
for i in range(1,len(mod_deg)):
#print(i)
mod_deg_df = pd.DataFrame(np.vstack([mod_deg_df,mod_deg_norm[i]]),
columns=['mod_deg_' + sub for sub in labels])
# Concatenating dataframe
# concatenating the participation and community detection nodes data
a = pd.concat([part_df,
comm_df,
mod_deg_df,
node_eff_delta], axis=1)
# reading rockland data
dda = pd.read_csv("D:\\IU Box Sync\\2 Dissertation & Qualifying exam\\Rockland Data\\Data_Rockland_SEM\\2_4_19 newest data r code\\2019_6_6_imaging_cases_86_FINAL.csv")
# concatenating rockland data with calculated brain data.
data = pd.concat([dda, a], axis=1)
data.info()
# ELASTIC NET MODEL
# Targets and predicting features
pred1 = pd.concat([pd.DataFrame([data.age,
data.sex,
data.tanner,
data.modularity,
head_m_ave]).T,
node_eff_delta.iloc[:,0:164]],axis=1)
pred1.sex = pred1.sex.astype('object')
target = data.ICUY_TOTAL
# Efficiency Changes
# setting up the estimation model
# - model
# * we use an elastic net to impose both l1 and l2 penalties on our data to ensure we do not over fit or spurious results
# * we will tune hyper parameters of both alpha and l1 ratio to optimize model fitting
# - Split
# * inner cv - used for hyperparameter tuning - we use only 3 folds for this
# * outter cv - used for corss validation of the tuned model - we use 5 fold cross validation for this
# setting up the model with a preprocessing step
model = make_pipeline(StandardScaler(),ElasticNet(random_state=42))
# parameters for hyperparamter tuning
param_grid = {"elasticnet__alpha": np.logspace(-2, 0, num=20),
'elasticnet__l1_ratio': np.logspace(-1.5, 0, num=20)}
# setting up nested cross validation
from sklearn.model_selection import StratifiedKFold
inner_cv = StratifiedKFold(n_splits=3,
shuffle=True,
random_state=0)
outer_cv = StratifiedKFold(n_splits=5,
shuffle=True,
random_state=0)
# nested CV model
model_s = GridSearchCV(
estimator=model,
param_grid=param_grid,
cv=inner_cv)
# Feature selection
# - We use data driven approach to select features to identify the nodes that predict CU traits
# - This is done using by optimizing the regress parameter f
# - we tried tuned for number of features to select and found k=25 to be the optimal number of features to improve prediction
# - note
# * we added sex becaue we felt sex was important independent of the fact that feature selection did not select it
from sklearn.feature_selection import SelectKBest, f_regression
pred1_reduced = SelectKBest(f_regression, k=25).fit_transform(pred1, target)
pred1_reduced_sex=pd.concat([data.sex, pd.DataFrame(pred1_reduced)],axis=1)
# Cross Validation
# - we score using 3 metrics: mean squared error, R2, and mean absolute error
# * Mean Squared Error - can interpret this as the amount of variation around the predicted line
# * R2 - can interpret as the amount of variance accounted for by predicted the linear line
# * mean absolute error - can interpret our model predicts on average the mean absolute error away from the true CU score.
from joblib import parallel_backend
with parallel_backend('threading', n_jobs=12):
cv_results = cross_validate(model_s,
pred1_reduced_sex,
target,
cv=outer_cv,
scoring={'neg_mean_squared_error',
'r2',
'neg_mean_absolute_error'},
return_train_score=True)
# Training data score
print(f"The mean train MSE using nested cross-validation is: "
f"{-cv_results['train_neg_mean_squared_error'].mean():.3f} +/- {cv_results['train_neg_mean_squared_error'].std():.3f}",
"\n",
f"The mean train R2 using nested cross-validation is: "
f"{cv_results['train_r2'].mean():.3f} +/- {cv_results['train_r2'].std():.3f}",
"\n",
f"The mean train absolute mean error using nested cross-validation is: "
f"{-cv_results['train_neg_mean_absolute_error'].mean():.3f} +/- {cv_results['train_neg_mean_absolute_error'].std():.3f}")
# Test data score
print(f"The mean test MSE using nested cross-validation is: "
f"{-cv_results['test_neg_mean_squared_error'].mean():.3f} +/- {cv_results['test_neg_mean_squared_error'].std():.3f}",
"\n",
f"The mean test R2 using nested cross-validation is: "
f"{cv_results['test_r2'].mean():.3f} +/- {cv_results['test_r2'].std():.3f}",
"\n",
f"The mean test absolute mean error using nested cross-validation is: "
f"{-cv_results['test_neg_mean_absolute_error'].mean():.3f} +/- {cv_results['test_neg_mean_absolute_error'].std():.3f}")
# Comparing CV results to a dummy model
errors_ridge_regressor = pd.Series(abs(cv_results['test_neg_mean_squared_error']), name="Regressor")
from sklearn.dummy import DummyRegressor
dummy_model = make_pipeline( StandardScaler(),DummyRegressor(strategy="mean"))
result_dummy = cross_validate(
dummy_model, pred1_reduced_sex, target, cv=outer_cv, scoring="neg_mean_squared_error")
errors_dummy_regressor = pd.Series(
-result_dummy["test_score"], name="Dummy regressor"
)
all_errors = pd.concat(
[errors_ridge_regressor, errors_dummy_regressor],
axis=1,
)
all_errors
# Names of features selected
# Identifying features selected
a=list(pred1.iloc[0,:][pred1.iloc[0,:].isin(pred1_reduced[0])].index)
aa= list(pred1.iloc[1,:][pred1.iloc[1,:].isin(pred1_reduced[1])].index)
features_selected=list(set.intersection(set(a),set(aa)))
# Removing prefix from node name
new_names = []
for i in features_selected:
new_names.append(i.removeprefix('node_eff_'))
new_namess = []
for i in new_names:
new_namess.append(i.removeprefix('atlas.'))
new_namesss = []
for i in new_namess:
new_namesss.append(i.removeprefix('networks.'))
new_names = new_namesss
# Removing Suffix
import re
dll = []
for i in new_names:
#print(i)
dll.append(re.sub(r'\([L]\)','L', str(i)))
dlr = []
for i in dll:
#print(i)
dlr.append(re.sub(r'\([R]\)','R', str(i)))
dl = []
for i in dlr:
#print(i)
dl.append(re.sub(r'\([^()]*\)','', str(i)))
dls = []
for i in dl:
#print(i)
dls.append(re.sub(r' $','', str(i)))
dls2 = []
for i in dls:
#print(i)
dls2.append(re.sub(r' $','', str(i)))
dls3 = []
for i in dls2:
dls3.append(re.sub(r' l',' L', str(i)))
dls4 = []
for i in dls3:
dls4.append(re.sub(r' r',' R', str(i)))
new_names=dls4
# ORDERING VALUES
# ordering is off so I will find the proper order
order=[]
for i in features_selected:
order.append(a.index(i))
new_names = new_names[order]
pd.Series(new_names)
# DESCRIPTIVES FOR SELECTED PARAMETERS
pred1_reduced_sex.columns = new_names
reduced_dataframe= pred1_reduced_sex.astype(float)
## setting pandas options to see all of dataframe
pd.set_option('max_rows', None)
pd.set_option('max_columns', None)
pd.DataFrame(reduced_dataframe.describe(percentiles=[]).T).iloc[:,[3,5,1,2]]
print("number of males =",np.sum(data.sex), "\n" , "% that are male =", round((np.sum(data.sex)/len(data.sex))*100,1) , "%")
# FITTING MODEL
# Hyperparameter tuning
from sklearn.linear_model import ElasticNetCV
tuning = ElasticNetCV(alphas=np.logspace(-2, 0, num=20),
l1_ratio= np.logspace(-1.5, 0, num=20),
cv=inner_cv).fit(pred1_reduced, target)
# Cross validation
mm = make_pipeline(StandardScaler(),ElasticNet(alpha=tuning.alpha_,
l1_ratio = tuning.l1_ratio_))
CV_results = cross_validate(mm, reduced_dataframe, target,
cv=outer_cv,
scoring="neg_mean_squared_error",
return_train_score=True,
return_estimator=True)
## getting the coefficients from the CV
coefs = [est[-1].coef_ for est in CV_results["estimator"]]
feature_names = features_selected
weights_elasticnet = pd.DataFrame(coefs,columns=new_names)
## viewing the coefficients
pd.set_option('max_rows', None) # so it prints all rows
#pd.set_option('max_columns', None) # can set max columns too
weights_elasticnet.T
# PLOTTING COEFFFICIENTY
import matplotlib.pyplot as plt
color = {"whiskers": "black", "medians": "black", "caps": "black"}
weights_elasticnet.plot.box(color=color,
vert=False,
figsize=(10, 6))
_ = plt.title("Cross Validation Weights")
plt.vlines(0,1,26, color='red') ## adding a vertical line
plt.tight_layout()
# plt.savefig(r"C:\Users\wintersd\OneDrive - The University of Colorado Denver\1 Publications\Simulated lesions and network analyses\Figures\efficiency_CV_Weights_additional.tiff", dpi=700)
plt.show(), plt.close()
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
sns.set(rc={'figure.figsize':(7.25,2.8)})
sns.set_style("ticks")
sns.boxplot(x="value", y= "variable",
data= pd.melt(weights_elasticnet),