-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCPM_emp_LPE.py
More file actions
2680 lines (1906 loc) · 106 KB
/
Copy pathCPM_emp_LPE.py
File metadata and controls
2680 lines (1906 loc) · 106 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
###############################################################################
# #
# Connectome-based predictive modeling of empathy in adolescents #
# with and without the low-prosocial emotion specifier #
# #
# By: Drew E. Winters, PhD. #
# #
###############################################################################
# python version 3.95
# Sys.setenv(RETICULATE_PYTHON = "C:\\Program Files\\Python39")
# Packages
# data manipulation
import pandas as pd
import numpy as np
import glob, os
import re
# machine learning
from nilearn import connectome # for connectivity measure
from sklearn.model_selection import permutation_test_score
from sklearn.dummy import DummyRegressor
from sklearn.feature_selection import SelectPercentile, f_regression
from sklearn.linear_model import ElasticNet
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import cross_val_score, KFold, cross_validate
from sklearn.model_selection import GridSearchCV
## Stats
from scipy.stats import ttest_ind
rng = np.random.default_rng()
## plotting
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.pyplot import figure, show, savefig
## system
from joblib import parallel_backend ## for parallel processing
import warnings
warnings.simplefilter("ignore")
### IMAGING DATA ####
# FILE NAMES LIST
import glob
csv_list = glob.glob(r"C:\Users\wintersd\OneDrive - The University of Colorado Denver\1 Publications\conn_pred_emp_ML\Subj_timeseries_denoised\ROI_*")
# printing to ensure they are the right files
for i in range(0,len(csv_list)):
print(os.path.basename(os.path.normpath(csv_list[i])))
# test to make sure it is the right #
len(csv_list) == 86 # true
# 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 that were used in preprocessing
## extracting time series of 164 nodes
time_s=[]
from joblib import parallel_backend
with parallel_backend('threading', n_jobs=12):
for i in range(0,len(csv_list)):
time_s.append(pd.read_csv(csv_list[i],
header= None).iloc[:,3:167].to_numpy())
## running test to make sure we have the right number of participants
len(time_s) == 86 # True
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})
# LABELS FOR ROIs
## here we extract whole brain ROI labels
# and we reformat them to be more user friendly
# Extracting labels
labels = pd.read_csv(r"C:\Users\wintersd\OneDrive - The University of Colorado Denver\1 Publications\conn_pred_emp_ML\ROInames.csv", header=None).iloc[:,3:167]
labels = np.array(labels)[0]
# modifying labels to shorter labels
new_namess = []
for i in labels:
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=np.array(dls4).astype('O')
# test to ensrue we have the right number of labels
len(new_names) == 164 # True
# COORDINATES FOR ROIs
coords = pd.read_csv(r"C:\Users\wintersd\OneDrive - The University of Colorado Denver\1 Publications\conn_pred_emp_ML\CONN_coordinates NO LABELS.csv", header=None)
coords.columns = ["x", "y", "z"]
# test for correct number of nodes
len(coords) == 164 # True
##### BEHAVIORAL DATA AND DESCRIPTIVES ####
# READING IMAGING DATA
dda = pd.read_csv(r"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")
dda.shape
# test to ensrue we dont have repeat IDs
np.where(dda.ID.value_counts()>1) ## none >1
# READING INDIVIDUAL ITEM CU TRAIT DATA
ICUY=pd.read_csv(r"D:\IU Box Sync\2 Dissertation & Qualifying exam\Rockland Data\Data_Rockland_SEM\Assessments_rklnd_SEM\8100_ICUY_20180929.csv",header=1)
# testing for duplicates
ICUY[['ID','VISIT']].value_counts()[np.where(ICUY[['ID','VISIT']].value_counts() >1)[0]] # participant A00065978 is duplicated
dup = ICUY[['ID','VISIT']].value_counts()[np.where(ICUY[['ID','VISIT']].value_counts() >1)[0]].index[0][0]
ICUY = ICUY.drop(np.where(ICUY['ID'] == dup)[0][-1]) # droping the duplicate
# formatting the visit labels to match
ICUY['VISIT'] = ICUY['VISIT'].replace(['V1'],'V2')
# formating the column name
ICUY=ICUY.rename(columns={"VISIT": "visit"})
# MERGIG BRAIN AN CU DATA
df = dda.merge(ICUY, on=(['ID','visit']))
# test to see if there are any duplicates
df.ID.value_counts()[np.where(df.ID.value_counts() >1)[0]] ## No duplicates
# test to make sure we have the right number
len(df) == 86 ## True
# info on dataframe
df.info()
# CALCULATING LPE SPECIFIER'S'
## reverse scoring
df['DICUY_01']=(3-df['DICUY_01'])
df['DICUY_03']=(3-df['DICUY_03'])
df['DICUY_05']=(3-df['DICUY_05'])
df['DICUY_08']=(3-df['DICUY_08'])
df['DICUY_13']=(3-df['DICUY_13'])
df['DICUY_14']=(3-df['DICUY_14'])
df['DICUY_15']=(3-df['DICUY_15'])
df['DICUY_16']=(3-df['DICUY_16'])
df['DICUY_17']=(3-df['DICUY_17'])
df['DICUY_19']=(3-df['DICUY_19'])
df['DICUY_23']=(3-df['DICUY_23'])
df['DICUY_24']=(3-df['DICUY_24'])
# dichotomizing for CU severity
df['DICUY_01_RC1'] = np.where(df['DICUY_01']>1,1,0)
df['DICUY_03_RC1'] = np.where(df['DICUY_03']>1,1,0)
df['DICUY_05_RC1'] = np.where(df['DICUY_05']>1,1,0)
df['DICUY_06_RC1'] = np.where(df['DICUY_06']>1,1,0)
df['DICUY_08_RC1'] = np.where(df['DICUY_08']>1,1,0)
df['DICUY_13_RC1'] = np.where(df['DICUY_13']>1,1,0)
df['DICUY_15_RC1'] = np.where(df['DICUY_15']>1,1,0)
df['DICUY_16_RC1'] = np.where(df['DICUY_16']>1,1,0)
df['DICUY_17_RC1'] = np.where(df['DICUY_17']>1,1,0)
df['DICUY_24_RC1'] = np.where(df['DICUY_24']>1,1,0)
## 4 Item method
df['sum_hi_cu4']=df[['DICUY_03_RC1','DICUY_05_RC1','DICUY_06_RC1','DICUY_08_RC1']].sum(axis=1)
df['hi_s_cu4'] = np.where(df['sum_hi_cu4']>=2,1,0)
df['hi_ex_cu4'] = np.where(df['sum_hi_cu4']>=3,1,0)
## 9 Item method
df['unconP_cu9_sum']= df[['DICUY_03_RC1','DICUY_15_RC1']].sum(axis=1)
df['lguilt_cu9_sum']= df[['DICUY_05_RC1','DICUY_13_RC1','DICUY_16_RC1']].sum(axis=1)
df['lemp_cu9_sum']= df[['DICUY_08_RC1','DICUY_17_RC1','DICUY_24_RC1']].sum(axis=1)
df['saff_s_cu9']= np.where(df['DICUY_01_RC1']>=2,1,0)
df['unconP_s_cu9']= np.where(df['unconP_cu9_sum']>=2,1,0)
df['lguilt_s_cu9']= np.where(df['lguilt_cu9_sum']>=2,1,0)
df['lemp_s_cu9']= np.where(df['lemp_cu9_sum']>=2,1,0)
df['sum_hi_s_cu9']=df[['saff_s_cu9','unconP_s_cu9','lguilt_s_cu9','lemp_s_cu9']].sum(axis=1)
df['hi_s_cu9'] = np.where(df['sum_hi_s_cu9']>=2,1,0)
df['saff_ex_cu9']= np.where(df['DICUY_01_RC1']>=3,1,0)
df['unconP_ex_cu9']= np.where(df['unconP_cu9_sum']>=3,1,0)
df['lguilt_ex_cu9']= np.where(df['lguilt_cu9_sum']>=3,1,0)
df['lemp_ex_cu9']= np.where(df['lemp_cu9_sum']>=3,1,0)
df['sum_hi_ex_cu9']=df[['saff_ex_cu9','unconP_ex_cu9','lguilt_ex_cu9','lemp_ex_cu9']].sum(axis=1)
df['hi_ex_cu9'] = np.where(df['sum_hi_ex_cu9']>=2,1,0)
# EXAMINING DESCRIPTIVES BY LPE SPECIFIER
# 4-item
## split
np.sum(df.hi_s_cu4) #27
np.sum(df.hi_s_cu4)/len(df.hi_s_cu4) #31%
## extreme
np.sum(df.hi_ex_cu4) #12
np.sum(df.hi_ex_cu4)/len(df.hi_s_cu4) #13.9%
# 9-item
## split
np.sum(df.hi_s_cu9) #24
np.sum(df.hi_s_cu9)/len(df.hi_s_cu9) #27.9%
## extreme
np.sum(df.hi_ex_cu9) #8
np.sum(df.hi_ex_cu9)/len(df.hi_s_cu9) #9.3%
# what I will do is create two groups to compare
#> Those who qualify for any LPE = LPE
#> THose who do not qualify for any LPE = normative
# summing all and seeing how many times each qualify
df["hi_all"] = (df.hi_ex_cu4 + df.hi_s_cu4 + df.hi_s_cu9 + df.hi_ex_cu9)
df["hi_all"].value_counts()
#> those that qualify for LPE
#> once = 10
#> twice = 10
#> thrice = 5
#> all four times = 4
# extreme and times qualifying
df["extreme"] =(df.hi_ex_cu4 + df.hi_ex_cu9)
df["extreme"].value_counts()
#> once = 12
#> twice = 4
# split and times qualifying
df["split"] =(df.hi_s_cu4 + df.hi_s_cu9)
df["split"].value_counts()
#> once = 22
#> twice = 7
df["four"] =(df.hi_s_cu4 + df.hi_ex_cu4)
df["four"].value_counts()
df["nine"] =(df.hi_s_cu9 + df.hi_ex_cu9)
df["nine"].value_counts()
# looking at tables of the different coding methods
df[["nine", "four"]].value_counts().unstack(fill_value=0)
df[["extreme", "split"]].value_counts().unstack(fill_value=0)
# examining numbers by each LPE
df[["hi_ex_cu9", "hi_s_cu9", "hi_ex_cu4", "hi_s_cu4"]].value_counts().unstack(fill_value=0)
# CREATING ONE COLUMN EITHER LPE (1) OR NO LPE (0)
df["hi_all_rc"] = df["hi_all"].apply(lambda x: 1 if x >= 1 else 0)
df["hi_all_rc"].value_counts()
#> 57 "normative"
#> 29 LPE
## test to ensure correct # of participants
len(df["hi_all_rc"]) == 86 # True
pd.set_option('display.max_rows', None)
# pd.Series(df.iloc[:,0:30].columns)
# pd.Series(df.columns)
# agregating summary stats by
pd.set_option('display.max_columns', None)
df[["hi_all_rc","PERSPECTIVE_TAKING", "EMPATHIC_CONCERN", "ICUY_TOTAL", "YSR_EXTERNALIZING_RAW"]].groupby("hi_all_rc").describe().loc[:,(slice(None),['mean','std'])].T
# group by table by sex
df.groupby(["hi_all_rc","sex"]).size().unstack(fill_value=0)
# TESTING FOR GROUP DIFFERENCES
# X2 tests
from scipy.stats import chisquare
# sex
pd.DataFrame(chisquare(df.groupby(["hi_all_rc","sex"]).size().unstack(fill_value=0), axis= 1), columns = ["sex: non-LPE","sex: LPE"], index= ["x2","p-val"]).T
# race
pd.DataFrame(chisquare(df.groupby(["hi_all_rc","race"]).size().unstack(fill_value=0), axis= 1), columns = ["race: non-LPE","race: LPE"], index= ["x2","p-val"]).T
# T-tests
from scipy.stats import ttest_ind
rng = np.random.default_rng()
ttest_ind(df[df['hi_all_rc'] ==0].age,
df[df['hi_all_rc'] ==1].age,
permutations=10000,
random_state=rng
)
ttest_ind(df[df['hi_all_rc'] ==0].tanner,
df[df['hi_all_rc'] ==1].tanner,
permutations=10000,
random_state=rng
)
ttest_ind(df[df['hi_all_rc'] ==0].PERSPECTIVE_TAKING,
df[df['hi_all_rc'] ==1].PERSPECTIVE_TAKING,
permutations=10000,
random_state=rng
)
ttest_ind(df[df['hi_all_rc'] ==0].EMPATHIC_CONCERN,
df[df['hi_all_rc'] ==1].EMPATHIC_CONCERN,
permutations=10000,
random_state=rng
)
ttest_ind(df[df['hi_all_rc'] ==0].ICUY_TOTAL,
df[df['hi_all_rc'] ==1].ICUY_TOTAL,
permutations=10000,
random_state=rng
)
ttest_ind(df[df['hi_all_rc'] ==0].YSR_EXTERNALIZING_RAW,
df[df['hi_all_rc'] ==1].YSR_EXTERNALIZING_RAW,
permutations=10000,
random_state=rng
)
#### DEMOGRAPHICS ####
# CONTINUOUS VARS
pd.DataFrame(df[["age",
"tanner",
"PERSPECTIVE_TAKING",
"EMPATHIC_CONCERN",
"ICUY_TOTAL",
"YSR_EXTERNALIZING_RAW"]].describe()).iloc[[1,2,3,7],:]
# SEX = MALE
pd.concat([pd.DataFrame({"male":df.sex.value_counts()}), pd.DataFrame({"%": df.sex.value_counts()/86})], axis = 1)
# RACE = WHITE
pd.concat([pd.DataFrame({"White": df.race.value_counts()}), pd.DataFrame({"%": df.race.value_counts()/86})], axis = 1)
# correlations
pd.DataFrame(df[["sex",
"race",
"age",
"tanner",
"PERSPECTIVE_TAKING",
"EMPATHIC_CONCERN",
"ICUY_TOTAL",
"YSR_EXTERNALIZING_RAW"]]).corr()
# p values
def calculate_pvalues(df):
from scipy.stats import pearsonr
import pandas as pd
df = df.dropna()._get_numeric_data()
dfcols = pd.DataFrame(columns=df.columns)
pvalues = dfcols.transpose().join(dfcols, how='outer')
for r in df.columns:
for c in df.columns:
pvalues[r][c] = round(pearsonr(df[r], df[c])[1], 4)
return pvalues
calculate_pvalues(pd.DataFrame(df[["sex",
"race",
"age",
"tanner",
"PERSPECTIVE_TAKING",
"EMPATHIC_CONCERN",
"ICUY_TOTAL",
"YSR_EXTERNALIZING_RAW"]]))
## By LPE demographics
# agregating summary stats by
pd.set_option('display.max_columns', None)
df[["hi_all_rc",
"age",
"tanner",
"PERSPECTIVE_TAKING",
"EMPATHIC_CONCERN",
"ICUY_TOTAL",
"YSR_EXTERNALIZING_RAW"]].groupby("hi_all_rc").describe().loc[:,(slice(None),['mean','std'])].T
# group by table by sex
df.groupby(["hi_all_rc","sex"]).size().unstack(fill_value=0)
df.groupby(["hi_all_rc","sex"]).size().unstack(fill_value=0)/86
# group table by race
df.groupby(["hi_all_rc","race"]).size().unstack(fill_value=0)
df.groupby(["hi_all_rc","race"]).size().unstack(fill_value=0)/86
#### EXTRACTING EMPATHY BY LPE ####
# SUBSETTING DATAFRAMES BY LPE
# high
df_hi = df[df['hi_all_rc'] ==1]
# df_hi.shape
# testing
len(df_hi) == len(np.where(df["hi_all_rc"] == 1)[0]) # True
# low or normative
df_lo = df[df['hi_all_rc'] ==0]
# df_lo.shape
# testing
len(df_lo) == len(np.where(df["hi_all_rc"] == 0)[0]) # True
# extracting empathy by LPE
## LPE
c_emp_hi = df_hi["PERSPECTIVE_TAKING"]
a_emp_hi = df_hi["EMPATHIC_CONCERN"]
# emp_hi = (c_emp_hi + a_emp_hi)
# c_emp_hi.shape
## No LPE (normative)
c_emp_lo = df_lo["PERSPECTIVE_TAKING"]
a_emp_lo = df_lo["EMPATHIC_CONCERN"]
# emp_lo = (c_emp_lo + a_emp_lo)
# c_emp_lo.shape
#### CONNECTIVITY MATRIX ####
# CALCULATING CONNECTOME
from nilearn import connectome
connectivity = connectome.ConnectivityMeasure(kind="correlation", vectorize=True, discard_diagonal=True)
fc_mat = connectivity.fit_transform(time_s)
# testing
len(fc_mat) == 86 # True
# creating an indicies matrix to help IDing edges later
tri = np.zeros((164, 164))
tri[np.triu_indices(164, 1)] = list(range(0,fc_mat[0].shape[0]))
tri_df = pd.DataFrame(tri)
tri_df.columns = new_names
tri_df.index = new_names
# tri_df.to_csv(r"C:\Users\wintersd\OneDrive - The University of Colorado Denver\1 Publications\conn_pred_emp_ML\upper_index.csv")
#### IDENTIFYING POSITIVE AND NEGATIVE NODES ####
## FUNCTION USED TO ID POSITIVE AND NEGATIVE REGIONS
def train_cpm(ipmat, pheno):
"""
Accepts input matrices and pheno data
Returns model
@author: David O'Connor
@documentation: Javid Dadashkarimi
cpm: in cpm we select the most significant edges for subjects. so each subject
have a pair set of edges with positive and negative correlation with behavioral subjects.
It's important to keep both set in final regression task.
posedges: positive edges are a set of edges have positive
correlatin with behavioral measures
negedges: negative edges are a set of edges have negative
correlation with behavioral measures
"""
from scipy import stats
import numpy as np
cc=[stats.pearsonr(pheno,im) for im in ipmat]
rmat=np.array([c[0] for c in cc])
pmat=np.array([c[1] for c in cc])
posedges=(rmat > 0) & (pmat < 0.005)
posedges=posedges.astype(int)
negedges=(rmat < 0) & (pmat < 0.005)
negedges=negedges.astype(int)
pe=ipmat[posedges.flatten().astype(bool),:]
ne=ipmat[negedges.flatten().astype(bool),:]
pe=pe.sum(axis=0)/2
ne=ne.sum(axis=0)/2
if np.sum(pe) != 0:
fit_pos=np.polyfit(pe,pheno,1)
else:
fit_pos=[]
if np.sum(ne) != 0:
fit_neg=np.polyfit(ne,pheno,1)
else:
fit_neg=[]
return fit_pos,fit_neg,posedges,negedges
### NOTE we tried multiple thresholds and found that 0.005 was the best fit (hyper parameter tuning)
# EXTRACTING LPE - COGNITIVE
fit_pos,fit_neg,posedges,negedges = train_cpm(fc_mat[df['hi_all_rc'] == 1].T, c_emp_hi)
## now I have positive and negative indicies to pull from for my selection
np.sum(posedges)
np.sum(negedges)
# creating matrix IDing identified regions to be use for later
tri = np.zeros((164, 164))
tri[np.triu_indices(164, 1)] = posedges
tri_df = pd.DataFrame(tri)
tri_df.columns = new_names
tri_df.index = new_names
# tri_df.to_csv(r"C:\Users\wintersd\OneDrive - The University of Colorado Denver\1 Publications\conn_pred_emp_ML\c_emp_hi_pos.csv")
# finding edge indicies
c_hi_pos_indicies = np.where(tri_df == 1)
# listing indicies
# pd.DataFrame(c_hi_pos_indicies).T
# using indicies to identify edge names
c_hi_pos_edge_names = new_names[c_hi_pos_indicies[0]] + "__" + new_names[c_hi_pos_indicies[1]]
# pd.Series(c_hi_pos_edge_names)
tri = np.zeros((164, 164))
tri[np.triu_indices(164, 1)] = negedges
tri_df = pd.DataFrame(tri)
tri_df.columns = new_names
tri_df.index = new_names
# tri_df.to_csv(r"C:\Users\wintersd\OneDrive - The University of Colorado Denver\1 Publications\conn_pred_emp_ML\c_emp_hi_neg.csv")
# finding edge indicies
c_hi_neg_indicies = np.where(tri_df == 1)
# listing indicies
# pd.DataFrame(c_hi_neg_indicies).T
# using indicies to identify edge names
c_hi_neg_edge_names = new_names[c_hi_neg_indicies[0]] + "__" + new_names[c_hi_neg_indicies[1]]
# pd.Series(c_hi_neg_edge_names)
# EXTRACTING POSITIVE AND NEGATIVE EDGES
c_hi_pos_edge = []
for i in range(0, fc_mat[df['hi_all_rc'] ==1].shape[0]):
c_hi_pos_edge.append(fc_mat[df['hi_all_rc'] ==1][i][posedges==1])
c_hi_pos_edge = np.array(c_hi_pos_edge)
c_hi_neg_edge = []
for i in range(0, fc_mat[df['hi_all_rc'] ==1].shape[0]):
c_hi_neg_edge.append(fc_mat[df['hi_all_rc'] ==1][i][negedges==1])
c_hi_neg_edge = np.array(c_hi_neg_edge)
# EXTRACT HIGH - AFFECTIVE
fit_pos,fit_neg,posedges,negedges = train_cpm(fc_mat[df['hi_all_rc'] == 1].T, a_emp_hi)
## now I have positive and negative coeffs to pull from for my selection
np.sum(posedges)
np.sum(negedges)
# creating matrix IDing identified regions to be use for later
tri = np.zeros((164, 164))
tri[np.triu_indices(164, 1)] = posedges
tri_df = pd.DataFrame(tri)
tri_df.columns = new_names
tri_df.index = new_names
# tri_df.to_csv(r"C:\Users\wintersd\OneDrive - The University of Colorado Denver\1 Publications\conn_pred_emp_ML\a_emp_hi_pos.csv")
# finding edge indicies
a_hi_pos_indicies = np.where(tri_df == 1)
# listing indicies
# pd.DataFrame(a_hi_pos_indicies).T
# using indicies to identify edge names
a_hi_pos_edge_names = new_names[a_hi_pos_indicies[0]] + "__" + new_names[a_hi_pos_indicies[1]]
# pd.Series(a_hi_pos_edge_names)
tri = np.zeros((164, 164))
tri[np.triu_indices(164, 1)] = negedges
tri_df = pd.DataFrame(tri)
tri_df.columns = new_names
tri_df.index = new_names
# tri_df.to_csv(r"C:\Users\wintersd\OneDrive - The University of Colorado Denver\1 Publications\conn_pred_emp_ML\a_emp_hi_neg.csv")
# finding edge indicies
a_hi_neg_indicies = np.where(tri_df == 1)
# listing indicies
# pd.DataFrame(a_hi_neg_indicies).T
# using indicies to identify edge names
a_hi_neg_edge_names = new_names[a_hi_neg_indicies[0]] + "__" + new_names[a_hi_neg_indicies[1]]
# pd.Series(a_hi_neg_edge_names)
# EXTRACTING POSITIVE AND NEGATIVE EDGES
a_hi_pos_edge = []
for i in range(0, fc_mat[df['hi_all_rc'] ==1].shape[0]):
a_hi_pos_edge.append(fc_mat[df['hi_all_rc'] ==1][i][posedges==1])
a_hi_pos_edge = np.array(a_hi_pos_edge)
a_hi_neg_edge = []
for i in range(0, fc_mat[df['hi_all_rc'] ==1].shape[0]):
a_hi_neg_edge.append(fc_mat[df['hi_all_rc'] ==1][i][negedges==1])
a_hi_neg_edge = np.array(a_hi_neg_edge)
# EXTRACTING NO LPE - COGNITIVE
fit_pos,fit_neg,posedges,negedges = train_cpm(fc_mat[df['hi_all_rc'] == 0].T, c_emp_lo)
## now I have positive and negative coeffs to pull from for my selection
np.sum(posedges)
np.sum(negedges)
# creating matrix IDing identified regions to be use for later
tri = np.zeros((164, 164))
tri[np.triu_indices(164, 1)] = posedges
tri_df = pd.DataFrame(tri)
tri_df.columns = new_names
tri_df.index = new_names
# tri_df.to_csv(r"C:\Users\wintersd\OneDrive - The University of Colorado Denver\1 Publications\conn_pred_emp_ML\c_emp_lo_pos.csv")
# finding edge indicies
c_lo_pos_indicies = np.where(tri_df == 1)
# listing indicies
# pd.DataFrame(c_lo_pos_indicies).T
# using indicies to identify edge names
c_lo_pos_edge_names = new_names[c_lo_pos_indicies[0]] + "__" + new_names[c_lo_pos_indicies[1]]
# pd.Series(c_lo_pos_edge_names)
tri = np.zeros((164, 164))
tri[np.triu_indices(164, 1)] = negedges
tri_df = pd.DataFrame(tri)
tri_df.columns = new_names
tri_df.index = new_names
# tri_df.to_csv(r"C:\Users\wintersd\OneDrive - The University of Colorado Denver\1 Publications\conn_pred_emp_ML\c_emp_lo_neg.csv")
# finding edge indicies
c_lo_neg_indicies = np.where(tri_df == 1)
# listing indicies
# pd.DataFrame(c_lo_neg_indicies).T
# using indicies to identify edge names
c_lo_neg_edge_names = new_names[c_lo_neg_indicies[0]] + "__" + new_names[c_lo_neg_indicies[1]]
# pd.Series(c_lo_neg_edge_names)
# EXTRACTING POSITIVE AND NEGATIVE EDGES
c_lo_pos_edge = []
for i in range(0, fc_mat[df['hi_all_rc'] == 0].shape[0]):
c_lo_pos_edge.append(fc_mat[df['hi_all_rc'] == 0][i][posedges == 1])
c_lo_pos_edge = np.array(c_lo_pos_edge)
c_lo_neg_edge = []
for i in range(0, fc_mat[df['hi_all_rc'] == 0].shape[0]):
c_lo_neg_edge.append(fc_mat[df['hi_all_rc'] == 0][i][negedges == 1])
c_lo_neg_edge = np.array(c_lo_neg_edge)
#### ML models ####
# ML MODEL
# packages
from sklearn.feature_selection import SelectPercentile, f_regression
from sklearn.linear_model import ElasticNet
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import cross_val_score, KFold, cross_validate
from sklearn.model_selection import GridSearchCV
# setting up ML model
#> logic
#> we are creating a model with elastic net in order to reduce over fitting
#> we are hyperparameter tuning for both alpha and L1
#> We are doing a nested cross validation
#> hyperparemeter tuning iwht 3 folds
#> CV with 5 folds
model = make_pipeline(ElasticNet(random_state=42)) # StandardScaler()
# 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)
#### ML MODEL: AFF EMP - HIGH CU ####
## AFFECTIVE HIGH POSITIVE MODEL__________________
# adding controls ## pd.DataFrame(a_hi_pos_edge).mean(axis=1)
a_hi_pos_edge_c = pd.concat([pd.DataFrame(a_hi_pos_edge),pd.concat([df_hi[["sex", "tanner", "race", "CBCL_EXTERNALIZING_RAW"]], head_m_ave.loc[df['hi_all_rc'] ==1]], axis=1).set_index(pd.DataFrame(a_hi_neg_edge).index)],axis=1)
# ML model
from joblib import parallel_backend
with parallel_backend('threading', n_jobs=12):
aff_hi_pos_res = cross_validate(model_s, a_hi_pos_edge_c, a_emp_hi, 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"{-aff_hi_pos_res['train_neg_mean_squared_error'].mean():.3f} +/- {aff_hi_pos_res['train_neg_mean_squared_error'].std():.3f}",
"\n",
f"The mean train R2 using nested cross-validation is: "
f"{aff_hi_pos_res['train_r2'].mean():.3f} +/- {aff_hi_pos_res['train_r2'].std():.3f}",
"\n",
f"The mean train absolute mean error using nested cross-validation is: "
f"{-aff_hi_pos_res['train_neg_mean_absolute_error'].mean():.3f} +/- {aff_hi_pos_res['train_neg_mean_absolute_error'].std():.3f}")
# Test data score
print(f"The mean test MSE using nested cross-validation is: "
f"{-aff_hi_pos_res['test_neg_mean_squared_error'].mean():.3f} +/- {aff_hi_pos_res['test_neg_mean_squared_error'].std():.3f}",
"\n",
f"The mean test R2 using nested cross-validation is: "
f"{aff_hi_pos_res['test_r2'].mean():.3f} +/- {aff_hi_pos_res['test_r2'].std():.3f}",
"\n",
f"The mean test absolute mean error using nested cross-validation is: "
f"{-aff_hi_pos_res['test_neg_mean_absolute_error'].mean():.3f} +/- {aff_hi_pos_res['test_neg_mean_absolute_error'].std():.3f}")
# Comparing CV results to a dummy model
errors_ridge_regressor = pd.Series(abs(aff_hi_pos_res['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, a_hi_pos_edge_c, a_emp_hi, cv=outer_cv, scoring="neg_mean_squared_error")
errors_dummy_regressor = pd.Series(
-result_dummy["test_score"], name="Dummy regressor"
)
aff_hi_pos_errors = pd.concat(
[errors_ridge_regressor, errors_dummy_regressor],
axis=1,
)
aff_hi_pos_errors
## DECISION - LPE POSITIVE AFFECTIVE MODEL
#> generalizes adn better than null model - good
## PERMUTATION TESTING
## setting up model
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(a_hi_pos_edge_c, a_emp_hi)
mm = make_pipeline(ElasticNet(alpha=tuning.alpha_, l1_ratio = tuning.l1_ratio_))
## permutation test with model
from sklearn.model_selection import permutation_test_score
from joblib import parallel_backend
with parallel_backend('threading', n_jobs=12):
score_dat, perm_scores, perm_pvalue = permutation_test_score(
mm,
a_hi_pos_edge_c,
a_emp_hi,
scoring="r2",
cv=outer_cv,
n_permutations=2000
)
# True R2
print("permuted R2 =", score_dat)
# permuted p-value
print("permuted p value =",perm_pvalue, "\n",
"rounded permuted p = " ,round(perm_pvalue,3))
# PLOTTING PERMUTED R2 ADN MODEL PREDICTION
# Permuted R2 distribition
perm_scores_df=pd.DataFrame({"perm_scores":perm_scores})
perm_scores_df.describe().iloc[1:8,]
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.pyplot import figure, show, savefig
fig, ax = plt.subplots()
# ax.set_axis_bgcolor('white')
sns.histplot(perm_scores_df,bins=200, x= "perm_scores", color="blue")
sns.despine()
plt.xlabel("Permutation $R^2$")
plt.ylabel("Outcome Number")
plt.xlim(-4,1.25)
ax.annotate("",
xy=(score_dat, 4), xycoords='data',
xytext=(score_dat, 15), textcoords='data',
arrowprops=dict(arrowstyle="->",
connectionstyle="arc3",
color = "black"),
)
plt.text(score_dat,16,"$P_{perm}$ < 0.001", horizontalalignment='left', size='large', color='black', weight='semibold')
# plt.savefig(r"C:\Users\wintersd\OneDrive - The University of Colorado Denver\1 Publications\conn_pred_emp_ML\figures\perm_hist_aff_pos_LPE.tiff", dpi=700)
plt.tight_layout(), plt.show(), plt.close()
# Fitting model predictions with true R2
from sklearn.model_selection import train_test_split
train_x, test_x, train_y, test_y = train_test_split(a_hi_pos_edge_c, a_emp_hi,test_size= .50, random_state=25)
target_predicted = mm.fit(train_x,train_y).predict(test_x)
predicted_actual = pd.DataFrame({"True Affective Empathy": test_y, "Predicted Affective Empathy": target_predicted})
sns.regplot(data=predicted_actual,
x="True Affective Empathy", y="Predicted Affective Empathy",
color="blue",
scatter_kws={'alpha':0.5},
x_jitter = .3,
y_jitter = .1).set(title='Positive Connectivity in Low Prosocial Emotion Specifier')
plt.text(18,8,"".join(['R$^2$= ', str(round(score_dat,3)),"$^{***}$"]), horizontalalignment='left', size='large', color='black', weight='semibold')
sns.despine()
# plt.savefig(r"C:\Users\wintersd\OneDrive - The University of Colorado Denver\1 Publications\conn_pred_emp_ML\figures\perm_regplot_aff_pos_LPE.tiff", dpi=700)
plt.tight_layout(),plt.show(), plt.close()
## AFFECTIVE HIGH NEGATIVE MODEL_________________________
# adding controls
a_hi_neg_edge_c = pd.concat([pd.DataFrame(a_hi_neg_edge),pd.concat([df_hi[["sex", "tanner", "race", "CBCL_EXTERNALIZING_RAW"]], head_m_ave.loc[df['hi_all_rc'] ==1]], axis=1).set_index(pd.DataFrame(a_hi_neg_edge).index)],axis=1)
# ML model
from joblib import parallel_backend
with parallel_backend('threading', n_jobs=12):
aff_hi_neg_res = cross_validate(model_s, a_hi_neg_edge_c, a_emp_hi, 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"{-aff_hi_neg_res['train_neg_mean_squared_error'].mean():.3f} +/- {aff_hi_neg_res['train_neg_mean_squared_error'].std():.3f}",
"\n",
f"The mean train R2 using nested cross-validation is: "
f"{aff_hi_neg_res['train_r2'].mean():.3f} +/- {aff_hi_neg_res['train_r2'].std():.3f}",
"\n",
f"The mean train absolute mean error using nested cross-validation is: "
f"{-aff_hi_neg_res['train_neg_mean_absolute_error'].mean():.3f} +/- {aff_hi_neg_res['train_neg_mean_absolute_error'].std():.3f}")
# Test data score
print(f"The mean test MSE using nested cross-validation is: "
f"{-aff_hi_neg_res['test_neg_mean_squared_error'].mean():.3f} +/- {aff_hi_neg_res['test_neg_mean_squared_error'].std():.3f}",
"\n",
f"The mean test R2 using nested cross-validation is: "
f"{aff_hi_neg_res['test_r2'].mean():.3f} +/- {aff_hi_neg_res['test_r2'].std():.3f}",
"\n",
f"The mean test absolute mean error using nested cross-validation is: "
f"{-aff_hi_neg_res['test_neg_mean_absolute_error'].mean():.3f} +/- {aff_hi_neg_res['test_neg_mean_absolute_error'].std():.3f}")
# Comparing CV results to a dummy model
errors_ridge_regressor = pd.Series(abs(aff_hi_neg_res['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, a_hi_neg_edge_c, a_emp_hi, cv=outer_cv, scoring="neg_mean_squared_error")
errors_dummy_regressor = pd.Series(
-result_dummy["test_score"], name="Dummy regressor"
)
aff_hi_neg_errors = pd.concat(
[errors_ridge_regressor, errors_dummy_regressor],
axis=1,
)
aff_hi_neg_errors
## PERMUTATION TESTING