-
Notifications
You must be signed in to change notification settings - Fork 0
/
visualization.py
1941 lines (1801 loc) · 93.3 KB
/
visualization.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 5 21:41:18 2021
@author: 99488
"""
import matplotlib.colors as mcolors
import os
import scipy.io as sio
import numpy as np
import pandas as pd
import sys
sys.path.append(r'F:\OPT\research\fMRI\utils_for_all')
from common_utils import get_function_connectivity, fig_pcd_distrub, outliner_detect, keep_triangle_half,\
vector_to_matrix, get_rois_label, get_net_net_connect, heatmap, setup_seed, t_test, get_fc, read_singal_fmri_ts
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.pyplot import MultipleLocator
import matplotlib
import copy
from collections import Counter
import math
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.model_selection import KFold, train_test_split
from scipy.stats import pearsonr
import seaborn as sns
from sklearn.cross_decomposition import CCA,PLSRegression
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error
# import phik
from scipy import stats
from sklearn.decomposition import PCA,TruncatedSVD,NMF, SparsePCA,FactorAnalysis, SparsePCA
from sklearn.manifold import MDS
from sklearn.metrics.pairwise import cosine_similarity
from scipy.stats import spearmanr, pearsonr, ttest_ind
from statsmodels.stats import multitest
from scipy.stats import boxcox, yeojohnson, normaltest
import seaborn as sns
from rpy2.robjects.packages import importr
import rpy2.robjects as robjects
from rpy2.robjects import pandas2ri, numpy2ri
# from statsmodels.stats.anova import anova_lm
from statsmodels.formula.api import ols
from scipy.stats import levene
from statsmodels.robust.scale import mad
# from skimage.metrics import structural_similarity as ssim
from statsmodels.stats.multicomp import pairwise_tukeyhsd
from statsmodels.stats.multitest import multipletests
from pathlib import Path
from bids.layout import parse_file_entities
np.random.seed(6)
font = {'family' : 'Tahoma', 'weight' : 'bold', 'size' : 15}
font2 = {'family' : 'Tahoma', 'weight' : 'bold', 'size' : 35}
# font2 = {'family' : 'Tahoma', 'weight' : 'bold', 'size' : 10}
font3 = {'family' : 'Tahoma', 'weight' : 'bold', 'size' : 18}
matplotlib.rc('font', **font2)
def MAD(data, percentile):
M2 = mad(data, axis=0)
thre = np.percentile(M2, percentile)
mask = M2>=thre
return mask
def get_npi(data, name_list, no_NC=False):
npi_list = []
for name in name_list:
if pd.api.types.is_float_dtype(data[name]):
npi_sub_scale = data[name].fillna(0)
if no_NC:
npi_list.append(npi_sub_scale[data['DX']!='CN'].values)
else:
npi_list.append(npi_sub_scale.values)
else:
variable_names = set(data[name])
t = 0
for variable_name in variable_names:
data[name][data[name] == variable_name] = t
t = t + 1
data[name] = data[name].astype('float')
if no_NC:
npi_list.append(data[name][data['DX']!='CN'].values)
else:
npi_list.append(data[name].values)
return np.array(npi_list).T
def regress_out_confunder(data, confounder):
beta = np.dot(np.dot(np.linalg.inv(np.dot(confounder.T, confounder)), confounder.T), data)
feature_regout = np.zeros((data.shape[0], data.shape[1]))
feature_regout = data - np.dot(confounder, beta)
return feature_regout
def CPM_reduce_dimension(feature, target):
r_p_array = np.zeros((feature.shape[-1], 3))
for i in range(feature.shape[-1]):
r, p = pearsonr(feature[:,i], target)
if p < 0.05:
r_p_array[i,0] = r
r_p_array[i,1] = p
r_p_array[i,2] = 1
return r_p_array
def pca(data, components, corr_matrix):
# features = X_scaled.T
cov_matrix = corr_matrix
# cov_matrix = np.corrcoef(features)
values, vectors = np.linalg.eig(cov_matrix)
explained_variances = []
for i in range(len(values)):
explained_variances.append(values[i] / np.sum(values))
projected = data.dot(vectors.T[:,:components])
return explained_variances, vectors, projected
def Ttest(group1, group2):
t_p_array = np.zeros((group1.shape[-1],2))
for i in range(group1.shape[-1]):
t, p = ttest_ind(group1[:,i], group2[:,i])
if p <= 0.05:
t_p_array[i,0] = t
t_p_array[i,1] = p
return t_p_array[:,1] != 0
def get_roi_net_connects(connections, net_info, net_nums = 7):
nets = list(net_info.keys())
new_conn = np.zeros((connections.shape[0], net_nums, connections.shape[-1]))
for i in range(len(nets)):
new_conn[:,i,:] = new_conn[:,i,:] + np.mean(connections[:,net_info[nets[i]][0][0]:net_info[nets[i]][0][1],:],1)
new_conn[:,i,:] = new_conn[:,i,:] + np.mean(connections[:,net_info[nets[i]][1][0]:net_info[nets[i]][1][1],:],1)
return new_conn
def concate(matrix):
if len(matrix.shape) == 2:
for i, array in enumerate(matrix):
if i == 0:
out = array[0]
else:
out = np.concatenate((out, array[0]))
return out
else:
out_ = []
for i, array in enumerate(matrix):
out = []
for j in range(matrix.shape[-1]):
out.extend(list(array[:,j]))
out_.append(out)
return np.array(out_).T
def get_variance_explained(model, data):
fa_loadings = model.components_.T # loadings
# variance explained
total_var = data.var(axis=0).sum() # total variance of original variables,
# equal to no. of vars if they are standardized
var_exp = np.sum(fa_loadings**2, axis=0)
prop_var_exp = var_exp/total_var
return var_exp, prop_var_exp
def signaltonoise(a, axis=0, ddof=0):
a = np.asanyarray(a)
m = a.mean(axis)
sd = a.std(axis=axis, ddof=ddof)
return np.where(sd == 0, 0, m/sd)
def PSNR(original, compressed):
mse = np.mean((original - compressed) ** 2)
if(mse == 0): # MSE is zero means no noise is present in the signal .
# Therefore PSNR have no importance.
return 100
max_pixel = 255.0
psnr = 20 * math.log10(max_pixel / math.sqrt(mse))
return psnr
oas_pcd_info = sio.loadmat(r'E:\PHD\learning\research\AD\data\OASIS3\fMRIdata_OASIS3_struct.mat')
tvar = oas_pcd_info['OASIS3_Phenotypic_struct']
PCD_data = []
pcd_keys = ['subjectID_Date', 'dx1', 'Age', 'apoe', 'NPIQINF', 'NPIQINFX', 'DEL',
'DELSEV', 'HALL', 'HALLSEV', 'AGIT', 'AGITSEV', 'DEPD', 'DEPDSEV', 'ANX',
'ANXSEV', 'ELAT', 'ELATSEV', 'APA', 'APASEV', 'DISN', 'DISNSEV', 'IRR',
'IRRSEV', 'MOT', 'MOTSEV', 'NITE', 'NITESEV', 'APP', 'APPSEV', 'mmse',
'cdr', 'commun','homehobb', 'judgment', 'memory', 'orient', 'perscare', 'sumbox',
'DIGIF', 'DIGIB', 'ANIMALS', 'VEG', 'TRAILA', 'TRAILALI', 'TRAILB',
'TRAILBLI', 'WAIS', 'LOGIMEM', 'MEMUNITS', 'MEMTIME', 'BOSTON']
for idx in range(len(tvar)):
sub_data = []
for name in pcd_keys:
value = tvar[idx][0][name]
for i in range(3):
if isinstance(value, np.ndarray):
try:
value = value[0]
except IndexError:
if name == 'DX':
value = 'nan'
else:
value = "error"
else:
if name == 'subjectID_Date' or name == 'dx1':
value = str(value)
sub_data.append(value)
break
PCD_data.append(sub_data)
PCD_data = np.array(PCD_data)
pcd_info= pd.Series(PCD_data[:,0]).str.split('d', expand = True)
pcd_day = pcd_info.iloc[:,1].str.split('d', expand = True).iloc[:,-1].astype(int).values
pcd_sub = pcd_info.iloc[:,0]
pcd_sub = np.array([info[:8] for info in pcd_sub])
info = sio.loadmat(r'E:\PHD\learning\research\AD\data\OASIS3\Updated_fc_240328.mat')
sess_unique = info['sess']
fc_unique = info['fc']
sub_unique_ = info['sub']
all_sess = info['all_sess']
all_day = np.array([day[0] for day in info['all_day'].squeeze()])
output = sio.loadmat(r'E:\PHD\learning\research\AD_two_modal\result\multi_run\baseline\roi_100\python\cca\12_domains_OAS_norm_True\subsample_zeroTrue_0.0\l10.6\test_method_norm_pca_npi7_method_none_fmri4950_CAcomp4_fold10\output.mat')
trans_x_te_ = output['trans_x_te'].T
trans_x_tr = output['trans_x_tr'].T
trans_y_te_ = output['trans_y_te'].T
trans_y_tr = output['trans_y_tr'].T
trans_x_te = np.zeros((177, 4))
trans_y_te = np.zeros((177, 4))
for i in range(output['idx_te'].shape[1]):
idx_tr = output['idx_tr'][:,i][0].squeeze()
idx_te = output['idx_te'][:,i][0].squeeze()
trans_x_te[idx_te,:] = trans_x_te_[i,:][0]
trans_y_te[idx_te,:] = trans_y_te_[i,:][0]
subjects_oas = pd.read_csv(r'E:\PHD\learning\research\AD\data\OASIS3\pcd_interest_multirun_Schaefer200_moreITEM.csv')['subjectID_Date']
subjects_oas_array = subjects_oas.values
sub_names = np.array([i.split('_')[0] for i in subjects_oas_array])
sub_names_uniq = np.array(list(set(list(sub_names))))
sub_names_uniq.sort()
_, sub_names_uniq_id, sub_names_id = np.intersect1d(sub_names_uniq, sub_names, return_indices=True)
mask = subjects_oas.str.contains('d000', regex=False)
fc_oas = sio.loadmat(r'E:\PHD\learning\research\AD\data\OASIS3\fc_NPI_roi_multirun_zscore.mat')['interest_subjects_fc']
npi_oas_raw = pd.read_csv(r'E:\PHD\learning\research\AD\data\OASIS3\pcd_interest_multirun_Schaefer200_moreITEM2.csv').iloc[:,[8,10,12,14,16,18,20,22,24,26,28,30]]
pup_oas = pd.read_csv(r'E:\PHD\learning\research\AD\data\OASIS3\PUP.csv')
pup_oas_subject = pup_oas['PUP_PUPTIMECOURSEDATA ID'].values
pup_oas_BP_SUVR = pup_oas[['Centil_fBP_TOT_CORTMEAN', 'Centil_fSUVR_TOT_CORTMEAN', 'Centil_fBP_rsf_TOT_CORTMEAN', 'Centil_fSUVR_rsf_TOT_CORTMEAN']].values
health_hist_oas = pd.read_csv(r'E:\PHD\learning\research\AD\data\OASIS3\UDS-A5-HealthHistory.csv')
health_hist_oas_subject = health_hist_oas['UDS_A5SUBHSTDATA ID'].values
health_hist_oas_info = health_hist_oas[['CVHATT', 'CVAFIB', 'CVANGIO', 'CVBYPASS', 'CVPACE', 'CVCHF', 'CVOTHR', 'CBSTROKE', 'CBTIA', 'CBOTHR',
'PD', 'PDOTHR', 'SEIZURES', 'TRAUMBRF', 'TRAUMEXT', 'TRAUMCHR', 'NCOTHR', 'HYPERTEN', 'HYPERCHO', 'DIABETES',
'B12DEF', 'THYROID', 'INCONTU', 'INCONTF', 'DEP2YRS', 'DEPOTHR', 'ALCOHOL', 'TOBAC30', 'TOBAC100', 'ABUSOTHR',
'PSYCDIS']].values #PACKSPER QUITSMOK ABUSOTHR ABUSX PSYCDIS
cvd_oas = pd.read_csv(r'E:\PHD\learning\research\AD\data\OASIS3\UDS-B2-HIS_CVD.csv')
cvd_oas_subject = cvd_oas['UDS_B2HACHDATA ID'].values
cvd_oas_info = cvd_oas[['ABRUPT', 'STEPWISE', 'SOMATIC', 'EMOT', 'HXHYPER', 'HXSTROKE', 'FOCLSYM', 'FOCLSIGN', 'HACHIN', 'CVDCOG', 'STROKCOG', 'CVDIMAG']].values
updrs_oas = pd.read_csv(r'E:\PHD\learning\research\AD\data\OASIS3\UDS-B3-UPDRS.csv')
updrs_oas_subject = updrs_oas['UDS_B3UPDRSDATA ID'].values
updrs_oas_info = updrs_oas[['PDNORMAL', 'SPEECH', 'FACEXP', 'TRESTFAC', 'TRESTRHD', 'TRESTLHD', 'TRESTRFT', 'TRESTLFT', 'TRACTRHD', 'TRACTLHD',
'RIGDNECK', 'RIGDUPRT', 'RIGDUPLF', 'RIGDLORT', 'RIGDLOLF', 'TAPSRT', 'TAPSLF', 'HANDMOVR', 'HANDMOVL', 'HANDALTR',
'HANDALTL', 'LEGRT', 'LEGLF', 'ARISING', 'POSTURE', 'GAIT', 'POSSTAB', 'BRADYKIN']].values
gds_oas = pd.read_csv(r'E:\PHD\learning\research\AD\data\OASIS3\UDS-B6-GDS.csv')
gds_oas_subject = gds_oas['UDS_B6BEVGDSDATA ID'].values
gds_oas_info = gds_oas[['GDS']].values
faq_oas = pd.read_csv(r'E:\PHD\learning\research\AD\data\OASIS3\UDS-B7-FAQ.csv')
faq_oas_subject = faq_oas['UDS_B7FAQDATA ID'].values
faq_oas_info = faq_oas[['BILLS', 'TAXES', 'SHOPPING', 'GAMES', 'STOVE', 'MEALPREP', 'EVENTS', 'PAYATTN', 'REMDATES', 'TRAVEL']].values
subjects_oas_bl = subjects_oas[mask]
npi_oas_raw = npi_oas_raw.fillna(0)
fc_oas_bl = fc_oas[mask]
npi_oas_bl = npi_oas_raw[mask]
fc_adni = sio.loadmat(r'E:\PHD\learning\research\AD\data\ADNI\fc.mat')['interest_subjects_fc']
npi_adni = pd.read_csv(r'E:\PHD\learning\research\AD\data\ADNI\pcd_interest.csv').iloc[:,[29,31,33,35,37,39,41,43,45,47]]
subjects_adni = pd.read_csv(r'E:\PHD\learning\research\AD\data\ADNI\pcd_interest.csv')['TimePoint']
mask2 = subjects_adni.str.contains('bl', regex=False)
subjects_adni = subjects_adni[mask2]
npi_adni = npi_adni.fillna(0)
fc_adni = fc_adni[mask2]
npi_adni = npi_adni[mask2]
fc = fc_oas_bl
npi = npi_oas_bl.values
# fc = np.r_[fc_oas, fc_adni]
# npi = np.r_[npi_oas_bl.values, npi_adni.values]
net_info_shf = {'VIS': ([0,9],[50,58]), 'SMN': ([9,15],[58,66]), 'DAN': ([15,23],[66,73]), 'VAN': ([23,30],[73,78]),
'LIM': ([30,33],[78,80]), 'FPC': ([33,37],[80,89]), 'DMN':([37,50],[89,100])}
continue_pcd = pd.read_csv(r'E:\PHD\learning\research\AD\data\OASIS3\pcd_interest_multirun_Schaefer200_moreITEM.csv')[['EDU','mmse', 'DIGIF', 'DIGIB',
'ANIMALS', 'VEG', 'TRAILA', 'TRAILB',
'WAIS', 'LOGIMEM', 'MEMUNITS', 'BOSTON', 'sumbox']]
decret_pcd = pd.read_csv(r'E:\PHD\learning\research\AD\data\OASIS3\pcd_interest_multirun_Schaefer200_moreITEM2.csv')[['cdr', 'SEX', 'Age',
'commun', 'homehobb',
'judgment', 'memory', 'orient', 'perscare', 'apoe']]
label = pd.read_csv(r'E:\PHD\learning\research\AD\data\OASIS3\pcd_interest_multirun_Schaefer200_moreITEM.csv')['dx1']
continue_pcd_bl = continue_pcd[mask]
decret_pcd_bl = decret_pcd[mask]
label_bl = label[mask]
decret_pcd_bl = decret_pcd_bl.values
# null_mask = np.ones((len(decret_pcd_bl)))==1#np.sum(np.isnan(decret_pcd_bl),-1)!=1
null_mask = np.sum(np.isnan(decret_pcd_bl[:,:2]),-1)!=1
fc = fc[null_mask,:,:]
npi = npi[null_mask,:,]
decret_pcd_bl = decret_pcd_bl[null_mask,:]
continue_pcd_bl = continue_pcd_bl.values[null_mask,:]
label_bl = label_bl.values[null_mask]
subjects_oas_bl = subjects_oas_bl[null_mask]
comp = 1
vis = 'fdr'
vari2 = 'brain'
roi_num = 100
name_ = 'cca_12_domains_OAS_norm_True_subsample_zeroTrue_l10.6_pca_npi7_method_none_fmri4950_CAcomp4_fold10'
te_save_path = r'E:\PHD\learning\research\AD_two_modal\result\revised'
# E:\PHD\learning\research\AD_two_modal\result\multi_run\baseline\roi_100\python\cca\12_domains_OAS_norm_True\subsample_zeroTrue_0.0\l10.6\test_method_norm_pca_npi7_method_none_fmri4950_CAcomp4_fold10
ca_components = 7
folds = 10
fc_components = 4950
npi_components = 7
npi_reduce_method = 'pca'
fc_reduce_method2 = 'none'
if fc_reduce_method2 == 'none':
decomp = False
else:
decomp = True
dimension_method = 'cca'
sparsity = True
subsample = True
subsample_ratio = 0/4
feature_norm = True
if sparsity:
if dimension_method == 'cca':
c_ = 0.6
elif dimension_method == 'pls':
c_ = 0.6
else:
if dimension_method == 'cca':
l1 = [0]
elif dimension_method == 'pls':
l1 = [0]
half_feature = keep_triangle_half(fc.shape[1] * (fc.shape[1]-1)//2, fc.shape[0], fc)
npi_raw = npi
npi_oas_raw = npi_oas_raw.values
continue_pcd = continue_pcd.values
decret_pcd = decret_pcd.values
label = label.values
subjects_oas = subjects_oas.values
half_feature_oas = keep_triangle_half(fc_unique.shape[1] * (fc_unique.shape[1]-1)//2, fc_unique.shape[0], fc_unique)
if subsample:
non_zero_id = np.where(np.sum(npi_raw,1)!=0)[0]
zero_id = np.where(np.sum(npi_raw,1)==0)[0]
idx = np.r_[zero_id[:int(len(non_zero_id)*subsample_ratio)], non_zero_id]
np.random.shuffle(idx)
npi = npi_raw[idx,:]
npi_raw2 = npi_raw[idx,:]
continue_pcd_bl = continue_pcd_bl[idx,:]
decret_pcd_bl = decret_pcd_bl[idx,:]
half_feature = half_feature[idx,:]
label_bl = label_bl[idx]
pcd = decret_pcd_bl
subjects_oas_bl = subjects_oas_bl.iloc[idx]
subjectsbl = [sub[:8] for sub in subjects_oas_bl]
sub_f, _, _ = np.intersect1d(subjectsbl, sub_unique_, return_indices=True)
sub_more = []
sess_more = []
days_more = []
fc_more = []
dx_more = []
for sub in sub_f:
mask = (sub_unique_ == sub) & (sess_unique != 'ses-M000')
sub_more.extend(list(sub_unique_[mask]))
sess_more.extend(list(sess_unique[mask]))
pcd_info= pd.Series(PCD_data[:,0]).str.split('d', expand = True)
pcd_day = pcd_info.iloc[:,1].str.split('d', expand = True).iloc[:,-1].astype(int).values
pcd_sub = pcd_info.iloc[:,0]
pcd_sub = np.array([info[:8] for info in pcd_sub])
for sess in sess_unique[mask]:
day = int(all_day[all_sess == sess][0][1:])
diff = abs(pcd_day - day)
days_more.append(day)
dx = PCD_data[(pcd_sub==sub)&(diff <= 600),1][0]
dx_more.append(dx)
fc_more.extend(list(half_feature_oas[mask]))
sub_more = np.array(sub_more)
sess_more = np.array(sess_more)
fc_more = np.array(fc_more)
days_more = np.array(days_more)
dx_more = np.array(dx_more)
else:
npi = npi_raw
npi_raw2 = npi_raw
continue_pcd_bl = continue_pcd_bl
decret_pcd_bl = decret_pcd_bl
half_feature = half_feature
label_bl = label_bl
pcd = decret_pcd_bl
pup_oas_BP_SUVR_list = np.zeros((len(subjects_oas_bl), 4))
heal_his_list = np.zeros((len(subjects_oas_bl), health_hist_oas_info.shape[-1]))
cvd_list = np.zeros((len(subjects_oas_bl), cvd_oas_info.shape[-1]))
updrs_list = np.zeros((len(subjects_oas_bl), updrs_oas_info.shape[-1]))
gds_list = np.zeros((len(subjects_oas_bl), gds_oas_info.shape[-1]))
faq_list = np.zeros((len(subjects_oas_bl), faq_oas_info.shape[-1]))
for j, subject in enumerate(subjects_oas_bl):
sub_fc, day_fc = subject.split('_')
for i, pup_sub in enumerate(pup_oas_subject):
pup_sub_info = pup_sub.split('_')
sub_pup, day_pup = pup_sub_info[0], int(pup_sub_info[-1].split('d')[-1])
if sub_pup == sub_fc:
if day_pup<100:
pup_oas_BP_SUVR_list[j,:] = pup_oas_BP_SUVR[i,:]
else:
pup_oas_BP_SUVR_list[j,:] = np.nan
break
else:
pup_oas_BP_SUVR_list[j,:] = np.nan
for i, his_sub in enumerate(health_hist_oas_subject):
his_sub_info = his_sub.split('_')
his_pup, day_his = his_sub_info[0], int(his_sub_info[-1].split('d')[-1])
if his_pup == sub_fc:
if day_his<100:
heal_his_list[j,:] = health_hist_oas_info[i,:]
else:
heal_his_list[j,:] = np.nan
break
else:
heal_his_list[j,:] = np.nan
for i, his_sub in enumerate(cvd_oas_subject):
his_sub_info = his_sub.split('_')
his_pup, day_his = his_sub_info[0], int(his_sub_info[-1].split('d')[-1])
if his_pup == sub_fc:
if day_his<100:
cvd_list[j,:] = cvd_oas_info[i,:]
else:
cvd_list[j,:] = np.nan
break
else:
cvd_list[j,:] = np.nan
for i, his_sub in enumerate(updrs_oas_subject):
his_sub_info = his_sub.split('_')
his_pup, day_his = his_sub_info[0], int(his_sub_info[-1].split('d')[-1])
if his_pup == sub_fc:
if day_his<100:
updrs_list[j,:] = updrs_oas_info[i,:]
else:
updrs_list[j,:] = np.nan
break
else:
updrs_list[j,:] = np.nan
for i, his_sub in enumerate(gds_oas_subject):
his_sub_info = his_sub.split('_')
his_pup, day_his = his_sub_info[0], int(his_sub_info[-1].split('d')[-1])
if his_pup == sub_fc:
if day_his<100:
gds_list[j,:] = gds_oas_info[i,:]
else:
gds_list[j,:] = np.nan
break
else:
gds_list[j,:] = np.nan
for i, his_sub in enumerate(faq_oas_subject):
his_sub_info = his_sub.split('_')
his_pup, day_his = his_sub_info[0], int(his_sub_info[-1].split('d')[-1])
if his_pup == sub_fc:
if day_his<100:
faq_list[j,:] = faq_oas_info[i,:]
else:
faq_list[j,:] = np.nan
break
else:
faq_list[j,:] = np.nan
heal_his_list[heal_his_list==9] = np.nan
cvd_list[cvd_list==8] = np.nan
updrs_list[updrs_list==8] = np.nan
faq_list[(faq_list==8) | (faq_list==9)] = np.nan
continue_pcd_bl = np.c_[decret_pcd_bl[:,2],continue_pcd_bl, pup_oas_BP_SUVR_list, gds_list]
decret_pcd_bl = np.c_[decret_pcd_bl, heal_his_list, cvd_list, updrs_list, faq_list]
if feature_norm:
scaler = StandardScaler()
half_feature = scaler.fit_transform(half_feature.T).T
half_feature_oas_more = scaler.fit_transform(fc_more.T).T
###################used for visualization
if fc_reduce_method2 == 'pca':
fmri_pca = PCA(n_components=fc_components)
X_train = fmri_pca.fit_transform(half_feature)
var = fmri_pca.explained_variance_ratio_
elif fc_reduce_method2 == 'fa':
fmri_pca = FactorAnalysis(n_components=fc_components)
X_train = fmri_pca.fit_transform(half_feature)
elif fc_reduce_method2 == 'mad':
percentile = fc_components
mask = MAD(half_feature, percentile)
X_train = half_feature[:,mask]
else:
X_train = half_feature
if npi_reduce_method == 'pca':
npi_reduce_model = PCA(n_components=npi_components)
npi = npi_reduce_model.fit_transform(npi)
# npi_more = npi_reduce_model.transform(npi_more)
elif npi_reduce_method == 'nmf':
npi_reduce_model = NMF(n_components=npi_components, random_state=42)
npi = npi_reduce_model.fit_transform(npi+1)
elif npi_reduce_method == 'fa':
npi_reduce_model = FactorAnalysis(n_components=npi_components)
npi = npi_reduce_model.fit_transform(npi)
elif npi_reduce_method == 'sparse_pca':
npi_reduce_model = SparsePCA(n_components=npi_components, alpha=0.5)
npi = npi_reduce_model.fit_transform(npi)
setup_seed(6)
if sparsity:
if dimension_method == 'cca':
importr('PMA')
r = robjects.r
numpy2ri.activate()
out_pls_r = r['CCA'](X_train, npi, K = ca_components, penaltyx = c_, penaltyz = 1, standardize = True)
value = list(out_pls_r)
name = list(out_pls_r.names)
w_x = value[0]
w_y = value[1]
X_train_ = np.dot(X_train, w_x)
y_train_ = np.dot(npi, w_y)
X_more = np.dot(half_feature_oas_more, w_x)
elif dimension_method == 'pls':
importr('mixOmics')
r = robjects.r
numpy2ri.activate()
c = c_*X_train.shape[-1]
c_list = r['c'](c, c, c)
out_pls_r = r['spls'](X_train, npi, ncomp = ca_components, keepX = c_list)
# out_pls_r = r['pls'](X_train, y_train, ncomp = ca_components)
value = list(out_pls_r)
name = list(out_pls_r.names)
del name[14] #手动索引去掉一个null对象。。
del value[14]
del name[0] #去掉没必要的为map省时间
del value[0]
del name[0]
del value[0]
# del name[10]
# del value[10]
del name[-1]
del value[-1]
del name[-1]
del value[-1]
value = list(map(list,value))
variate = list(map(list,value[5]))
X_train_ = np.reshape(np.array(variate[0]), (ca_components, X_train.shape[0])).T
y_train_ = np.reshape(np.array(variate[1]), (ca_components, X_train.shape[0])).T
loading = list(map(list,value[6]))
w_x = np.reshape(np.array(loading[0]), (ca_components, X_train.shape[1])).T
w_y = np.reshape(np.array(loading[1]), (ca_components, npi.shape[1])).T
x_load = np.dot(X_train_.T, X_train).T / np.diagonal(np.dot(X_train_.T, X_train_))
pctVar = sum(abs(x_load)*abs(x_load),1) / sum(sum(abs(X_train)*abs(X_train),1))
else:
if dimension_method == 'cca':
pls = CCA(n_components=ca_components)
X_train_, y_train_ = pls.fit_transform(X_train, npi)
# pls.fit(X_train, y_train, cu = 0, cv=0)
elif dimension_method == 'pls':
pls = PLSRegression(n_components=ca_components)
X_train_, y_train_ = pls.fit_transform(X_train, npi)
w_x = pls.x_weights_
w_y = pls.y_weights_
sio.savemat(r'E:\PHD\learning\research\AD_two_modal\result\revised\cca_feature.mat', {'brain_feature':X_train_, 'subject': subjects_oas_bl.values,
'brain_feature_more': X_more, 'subject_more':sub_more, 'label': label_bl,
'label_more': dx_more, 'sess_more': sess_more})
r_total_f = list(pearsonr(X_train_[:,i], y_train_[:,i]) for i in range(4))
print(r_total_f)
if not os.path.exists(te_save_path):
os.makedirs(te_save_path)
if X_train_.shape[0] != continue_pcd_bl.shape[0]:
X_train_ = X_train_[:continue_pcd_bl.shape[0]]
y_train_ = y_train_[:continue_pcd_bl.shape[0]]
npi_raw2 = npi_raw2[:continue_pcd_bl.shape[0]]
half_feature = half_feature[:continue_pcd_bl.shape[0]]
#############################################################################
##########Correlates_of_brain_canonical_variates_and_other_measures
def vis1(X_train_, num_cp=3, name = 'Correlates_of_brain_canonical_variates_and_other_measures', y_label_bl=['brain comps 1', 'brain comps 2', 'brain comps 3']):
id_null = ~np.isnan(continue_pcd_bl)
r_matrix = np.zeros((2, num_cp, continue_pcd_bl.shape[-1]))
for i in range(num_cp):
for j in range(continue_pcd_bl.shape[-1]):
subjects_oas_bl_ = subjects_oas_bl[id_null[:,j]]
subjects_uni, subjects_uni_idx, subjects_oas_bl_idx = np.unique(subjects_oas_bl_, return_index=True, return_inverse = True)
x = X_train_[id_null[:,j],i]
y = continue_pcd_bl[id_null[:,j],j]
x_list = []
y_list = []
for name_ in subjects_uni:
x_list.append(np.mean(x[subjects_oas_bl_==name_]))
y_list.append(np.mean(y[subjects_oas_bl_==name_]))
r_total_f = pearsonr(x_list, y_list)
r_matrix[0,i,j] = r_total_f[0]
r_matrix[1,i,j] = r_total_f[1]
fdr_correct = np.zeros((num_cp, continue_pcd_bl.shape[-1]))
for i in range(num_cp):
out = multitest.multipletests(r_matrix[1][i], method="fdr_bh")[1]
fdr_correct[i] = out
# # fdr_correct[0] = out[:len(out)//2]
# # fdr_correct[1] = out[len(out)//2:]
# out1 = multitest.multipletests(r_matrix[1][0], method="fdr_bh")[1]
# out2 = multitest.multipletests(r_matrix[1][1], method="fdr_bh")[1]
# out3 = multitest.multipletests(r_matrix[1][2], method="fdr_bh")[1]
# mask = np.zeros((r_matrix[1][0].shape))==0
# mask[4] = False
# # out1_ = multitest.multipletests(r_matrix[1][0][mask], method="fdr_bh")[1]
# # out2_ = multitest.multipletests(r_matrix[1][1][mask], method="fdr_bh")[1]
# fdr_correct[0] = out1
# fdr_correct[1] = out2
# fdr_correct[2] = out3
r_matrix_fdr = r_matrix[0]*(fdr_correct<=0.05*1)
plt.figure(figsize =(15,15))
ax = plt.gca()
try:
norm = mcolors.TwoSlopeNorm(vmin=r_matrix_fdr.min(), vmax = r_matrix_fdr.max(), vcenter=0)
im = plt.imshow(r_matrix_fdr, cmap = 'RdBu', norm=norm)
except ValueError:
im = plt.imshow(r_matrix_fdr, cmap = 'RdBu')
im_ratio = r_matrix_fdr.shape[0]/r_matrix_fdr.shape[1]
plt.colorbar(im,fraction=0.046*im_ratio, pad=0.04)
# name = 'Correlates_of_brain_canonical_variates_and_other_measures'
plt.title(name)
ax.spines['top'].set_color('none') # 设置上‘脊梁’为红色
ax.spines['right'].set_color('none') # 设置上‘脊梁’为无色
# ax.set_aspect(1.0/ax.get_data_ratio(), adjustable='box')
plt.setp(ax.get_xticklabel_bls(), rotation=90, ha="right",
rotation_mode="anchor")
# plt.xticks(np.arange(continue_pcd_bl.shape[-1]), ['mmse', 'DIGIF', 'DIGIB',
# 'ANIMALS', 'VEG', 'TRAILA', 'TRAILB',
# 'WAIS', 'LOGIMEM', 'MEMUNITS', 'MEMTIME', 'BOSTON', 'sumbox'])
plt.xticks(np.arange(continue_pcd_bl.shape[-1]), ['age', 'edu', 'mmse', 'DIGIF', 'DIGIB',
'ANIMALS', 'VEG', 'TRAILA', 'TRAILB',
'WAIS', 'LOGIMEM', 'MEMUNITS', 'BOSTON', 'sumbox',
'Centil_fBP_TOT_CORTMEAN', 'Centil_fSUVR_TOT_CORTMEAN',
'Centil_fBP_rsf_TOT_CORTMEAN', 'Centil_fSUVR_rsf_TOT_CORTMEAN', 'GDS'])
# plt.xticks(np.arange(continue_pcd_bl.shape[-1]), ['Age', 'apoe', 'mmse', 'DIGIF', 'DIGIB', 'EDU',
# 'ANIMALS', 'VEG', 'TRAILA', 'TRAILALI', 'TRAILB',
# 'TRAILBLI', 'WAIS', 'LOGIMEM', 'MEMUNITS', 'MEMTIME', 'BOSTON'])
# plt.yticks(np.arange(num_cp), y_label_bl)
ax.set_yticks(np.arange(num_cp))
for i in range(r_matrix_fdr.shape[0]):
for j in range(r_matrix_fdr.shape[1]):
ax.text(j,i,r_matrix[0][i,j].round(2),ha="center", va="center", color="black",fontsize=20,fontname='Times New Roman')
plt.savefig(os.path.join(te_save_path, '{}.svg'.format(name)))
return r_matrix
#############################################
############anova
def vis2(comp=0, variable='brain', p=False):
subjects_uni, subjects_uni_idx, subjects_oas_bl_idx = np.unique(subjects_oas_bl, return_index=True, return_inverse = True)
if variable == 'brain':
array = []
for name in subjects_uni:
array.append(np.mean(X_train_[subjects_oas_bl==name], 0))
# array = X_train_
# name = 'Brain canonical variate {}'.format(comp+1)
name = 'Brain_canonical_variate_{}'.format(comp+1)
name1 = 'Brain canonical variate {}'.format(comp+1)
elif variable == 'npi':
array = []
for name in subjects_uni:
array.append(np.mean(y_train_[subjects_oas_bl==name]), 0)
# array = y_train_
name = 'NPI_canonical_variate_{}'.format(comp+1)
name1 = 'NPI canonical variate {}'.format(comp+1)
decret_pcd_bl_ = []
for name_ in subjects_uni:
decret_pcd_bl_.append(np.mean(decret_pcd_bl[subjects_oas_bl==name_], 0))
array = np.array(array)
decret_pcd_bl__ = np.array(decret_pcd_bl_)
# items = ['cdr', 'SEX', 'commun', 'homehobb', 'judgment', 'memory', 'orient', 'perscare', 'apoe']
items = ['cdr', 'SEX', 'commun', 'homehobb', 'judgment', 'memory', 'orient', 'perscare', 'apoe', 'CVHATT', 'CVAFIB', 'CVANGIO',
'CVBYPASS', 'CVPACE', 'CVCHF', 'CVOTHR', 'CBSTROKE', 'CBTIA', 'CBOTHR', 'PD', 'PDOTHR', 'SEIZURES', 'TRAUMBRF', 'TRAUMEXT',
'TRAUMCHR', 'NCOTHR', 'HYPERTEN', 'HYPERCHO', 'DIABETES', 'B12DEF', 'THYROID', 'INCONTU', 'INCONTF', 'DEP2YRS', 'DEPOTHR',
'ALCOHOL', 'TOBAC30', 'TOBAC100', 'ABUSOTHR', 'PSYCDIS', 'ABRUPT', 'STEPWISE', 'SOMATIC', 'EMOT', 'HXHYPER', 'HXSTROKE',
'FOCLSYM', 'FOCLSIGN', 'HACHIN', 'CVDCOG', 'STROKCOG', 'CVDIMAG', 'PDNORMAL', 'SPEECH', 'FACEXP', 'TRESTFAC',
'TRESTRHD', 'TRESTLHD', 'TRESTRFT', 'TRESTLFT', 'TRACTRHD', 'TRACTLHD','RIGDNECK', 'RIGDUPRT', 'RIGDUPLF', 'RIGDLORT',
'RIGDLOLF', 'TAPSRT', 'TAPSLF', 'HANDMOVR', 'HANDMOVL', 'HANDALTR', 'HANDALTL', 'LEGRT', 'LEGLF', 'ARISING', 'POSTURE',
'GAIT', 'POSSTAB', 'BRADYKIN', 'BILLS', 'TAXES', 'SHOPPING', 'GAMES', 'STOVE', 'MEALPREP', 'EVENTS', 'PAYATTN', 'REMDATES', 'TRAVEL']
for k in range(len(items)):
if items[k] == 'SEX':
a = 0
if k > 1:
idx = k+1
else:
idx = k
value_cdr = []
groupID_cdr = []
for i, j in enumerate(list(set(decret_pcd_bl__[:,idx]))):
if sum(decret_pcd_bl__[:,idx] == j)<10 or math.isnan(j):
continue
value_cdr.extend(list(array[decret_pcd_bl__[:,idx] == j, comp]))
groupID_cdr.extend(list(np.ones(len(np.where(decret_pcd_bl__[:,idx] == j)[0])) * j))
# value_cdr = value_cdr[groupID_cdr!=2]
# groupID_cdr = groupID_cdr[groupID_cdr!=2]
df = {'cdr_id': groupID_cdr, name: value_cdr}
data = pd.DataFrame(df)
# df2 = data[data['cdr_id'] != 2]
mod = ols('{}~C(cdr_id)'.format(name),data=data).fit()
anova_reC= anova_lm(mod)
print(anova_reC)
# stat, p_ = levene(value_array[0], value_array[1], value_array[2], value_array[3])
stat, p_ = anova_reC['F'].iloc[0], anova_reC['PR(>F)'].iloc[0]
plt.figure(figsize =(13,13))
ax = plt.gca()
sns.violinplot(x="cdr_id", y=name, data=data, width = 0.4, color = 'grey', inner = 'box', alpha = 0.2, ax = ax)
plt.setp(ax.collections, alpha=.15)
sns.stripplot(x="cdr_id", y=name, data=data, size = 8, palette="Set1", ax = ax)
# sns.boxplot(x="cdr_id", y=name, data=data, width = 0.5, medianprops=dict(color='gray'), boxprops=dict(facecolor='gray', alpha = 0.2),
# capprops=dict(color='gray'), whiskerprops=dict(color='gray'), showfliers=False, ax = ax)
max_y = array[:,comp].max()
min_y = array[:,comp].min()
ax.set_yticks(np.arange(int(min_y), int(max_y+30), int((max_y-min_y)/3)))
ax.spines['top'].set_color('none') # 设置上‘脊梁’为红色
ax.spines['right'].set_color('none') # 设置上‘脊梁’为无色
name_ = '{}_{}_ANOVA'.format(name, items[k])
# plt.title(name_)
# plt.xticks(np.arange(4), ['No impair', 'Questionable impair', 'Mild impair', 'Moderate impair'])
# plt.xticks(np.arange(3), ['No impair', 'Questionable impair', 'Mild impair'])
ax.set_ylabel_bl(name1, fontproperties=font2)
ax.set_xlabel_bl(items[k], fontproperties=font2)
plt.savefig(os.path.join(te_save_path, '{}.svg'.format(name_)))
plt.figure(figsize =(10,10))
ax = plt.gca()
# if not p:
# p = anova_reC['PR(>F)'].iloc[0]
ax.spines['top'].set_color('none') # 设置上‘脊梁’为红色
ax.spines['right'].set_color('none') # 设置上‘脊梁’为无色
plt.text(0.1, 0.05, 'all P: {:.3}\n'.format(p_))
plt.text(0.1, 0.1, 'all F: {:.3}\n'.format(stat))
if len(set(groupID_cdr))>2:
tukey = pairwise_tukeyhsd(endog=df[name],
groups=df['cdr_id'],
alpha=0.05)
out = tukey.summary().data
import scikit_posthocs as sp
out2 = sp.posthoc_ttest(data, val_col=name, group_col='cdr_id', p_adjust=None, pool_sd=True)
out2 = np.expand_dims(out2.values,0)
out2_half = keep_triangle_half(out2.shape[1] * (out2.shape[1]-1)//2, out2.shape[0], out2).squeeze()
# t, p = ttest_ind(data[name][data['cdr_id']==0], data[name][data['cdr_id']==1])
for i in range(1,len(out)):
plt.text(0.1, 0.1*i+0.15, '{} vs {} P: {:.3} {}\n'.format(out[i][0], out[i][1], out[i][3], out2_half[i-1]))
plt.text(0.1, 0.1*i+0.2, '{} vs {} meandiff: {:.3}\n'.format(out[i][0], out[i][1], out[i][2]))
plt.savefig(os.path.join(te_save_path, '{}_stat.svg'.format(name_)))
return anova_reC['F'].iloc[0], anova_reC['PR(>F)'].iloc[0]
############pca_cca_yloadings and correlation
def vis3(comp=0, array = None, name2 = 'none'):
font2 = {'family' : 'Tahoma', 'weight' : 'bold', 'size' : 35}
matplotlib.rc('font', **font2)
# weight_fc = fmri_pca.components_.T
weight_npi= npi_reduce_model.components_.T
w_npi = np.dot(npi_reduce_model.components_.T,w_y)
# w_npi = w_y
plt.figure(figsize =(18,18))
ax = plt.gca()
try:
norm = mcolors.TwoSlopeNorm(vmin=w_npi.min(), vmax = w_npi.max(), vcenter=0)
im = plt.imshow(w_npi, cmap = 'RdBu_r', norm=norm)
except ValueError:
im = plt.imshow(w_npi, cmap = 'RdBu_r')
im_ratio = w_npi.shape[0]/w_npi.shape[1]
# plt.colorbar(im,fraction=0.046*im_ratio, pad=0.04)
plt.colorbar()
name = 'pca_cca_yloadings'
plt.title(name)
ax.spines['top'].set_color('none') # 设置上‘脊梁’为红色
ax.spines['right'].set_color('none') # 设置上‘脊梁’为无色
ax.spines['left'].set_color('none') # 设置上‘脊梁’为无色
ax.spines['bottom'].set_color('none') # 设置上‘脊梁’为无色
ax.set_aspect(1.0/ax.get_data_ratio(), adjustable='box')
plt.yticks(np.arange(12), ['Delusions', 'Hallucinations', 'Agitation', 'Depression', 'Anxiety', 'Euphoria',
'Apathy', 'Disinhibition', 'Irritability', 'Aberrant motor\nbehavior', 'Nighttime behavior\ndisturbances', 'Appetite abnormalities'])
plt.xticks(np.arange(4), ['Affective mode', 'Psychotic mode', 'other mode', 'other mode'])
# ax.axes.get_xaxis().set_visible(False)
for i in range(w_npi.shape[0]):
for j in range(w_npi.shape[1]):
text = ax.text(j,i,w_npi[i,j].round(2),ha="center", va="center", color="black",fontsize=20,fontname='Times New Roman')
# plt.savefig(os.path.join(te_save_path, '{}.svg'.format(name)), bbox_inches = 'tight')
###################################################################################
# if variable == 'brain':
# # array = X_train_
# # name = 'Brain canonical variate {}'.format(comp+1)
# name = 'Brain_component{}_NPI_correlation_spear'.format(comp+1)
# # name1 = 'Brain canonical variate {}'.format(comp+1)
# elif variable == 'npi':
# # array = y_train_
# name = 'NPI_component{}_NPI_correlation_spear'.format(comp+1)
# # name1 = 'NPI canonical variate {}'.format(comp+1)
name = name2
loading_r = np.zeros((array.shape[-1], npi_raw2.shape[-1]))
loading_p = np.zeros((array.shape[-1], npi_raw2.shape[-1]))
for i in range(array.shape[-1]):
for j in range(npi_raw2.shape[-1]):
# r_poly = r['polyserial'](array[:,j], npi[:,i])
# r_poly = pearsonr(npi_raw2[:,j], array[:,i])
r_poly = spearmanr(npi_raw2[:,j], array[:,i])
r_ = list(r_poly)[0]
loading_r[i,j] = r_
loading_p[i,j] = list(r_poly)[1]
plt.figure(figsize =(10,16))
ax = plt.gca()
data = pd.DataFrame({'x tick':np.arange(loading_r.shape[-1]), 'correlation':loading_r[comp]})
data['sign'] = data['correlation'] > 0
data['correlation'].plot(kind='barh', color=data.sign.map({True: (1.0, 0, 0, 0.7), False: '#87CEFA'}), ax=ax)
# data.plot(y = 'correlation', kind='bar', color=data.sign.map({True: (1.0, 0, 0, 0.7), False: '#87CEFA'}), ax=ax)
ax.axvline(0, color='black')
# ax.set_aspect(1.0/ax.get_data_ratio(), adjustable='box')
max_y = data['correlation'].max()
min_y = data['correlation'].min()
ax.set_xticks(np.around(np.arange(round(min_y,2), round(max_y, 2), 0.1), 2))
ax.set_xlabel_bl('R', fontproperties=font2)
plt.setp(ax.get_yticklabel_bls(), rotation=30, ha="right",
rotation_mode="anchor")
plt.yticks(np.arange(12), ['Delusions', 'Hallucinations', 'Agitation', 'Depression', 'Anxiety', 'Euphoria',
'Apathy', 'Disinhibition', 'Irritability', 'Aberrant motor behavior', 'Nighttime behavior disturbances', 'Appetite abnormalities'])
ax.spines['top'].set_color('none') # 设置上‘脊梁’为红色
ax.spines['right'].set_color('none') # 设置上‘脊梁’为无色
# plt.savefig(os.path.join(te_save_path, '{}.svg'.format(name)), bbox_inches = 'tight')
# plt.savefig(os.path.join(te_save_path, '{}.svg'.format(name)))
plt.close('all')
return loading_p
################t test sex
def vis4(comp=0, variable='brain'):
if variable == 'brain':
array = X_train_
name = 'Brain canonical variate {}'.format(comp+1)
elif variable == 'npi':
array = y_train_
name = 'NPI canonical variate {}'.format(comp+1)
value_array = []
id_null = ~np.isnan(decret_pcd_bl)
decret_pcd_bl_2 = decret_pcd_bl[id_null[:,1]]
X_train_2 = array[id_null[:,1]]
for i, j in enumerate(list(set(decret_pcd_bl_2[:,1]))):
if i == 0:
value_cdr = X_train_2[decret_pcd_bl_2[:,1] == j, comp]
groupID_cdr = np.ones(len(np.where(decret_pcd_bl_2[:,1] == j)[0])) * j
value_array.append(X_train_2[decret_pcd_bl_2[:,1] == j, comp])
else:
value_cdr = np.concatenate((value_cdr, X_train_2[decret_pcd_bl_2[:,1] == j, comp]))
groupID_cdr = np.concatenate((groupID_cdr, np.ones(len(np.where(decret_pcd_bl_2[:,1] == j)[0])) * j ))
value_array.append(X_train_2[decret_pcd_bl_2[:,1] == j, comp])
t, p = ttest_ind(value_array[0], value_array[1])
df = {'sex': groupID_cdr, name: value_cdr}
data = pd.DataFrame(df)
plt.figure(figsize =(15,15))
ax = plt.gca()
sns.stripplot(x="sex", y=name, data=data, size = 8, palette="Set2", ax = ax)
sns.boxplot(x="sex", y=name, data=data, width = 0.5, medianprops=dict(color='gray'), boxprops=dict(facecolor='gray', alpha = 0.2),
capprops=dict(color='gray'), whiskerprops=dict(color='gray'), showfliers=False, ax = ax)
ax.spines['top'].set_color('none') # 设置上‘脊梁’为红色
ax.spines['right'].set_color('none') # 设置上‘脊梁’为无色
plt.text(1, -2, 'P: {:.3}\n'.format(p))
name = '{}_sex_t-test'.format(name)
plt.title(name)
plt.savefig(os.path.join(te_save_path, '{}.svg'.format(name)))
return t, p
###################################################################################
##########npi score
def vis5():
plt.figure(figsize =(15,15))
ax = plt.gca()
norm = mcolors.TwoSlopeNorm(vmin=npi.min()-0.1, vmax = npi.max(), vcenter=0)
im = plt.imshow(npi, cmap = 'RdBu', norm=norm)
im_ratio = npi.shape[0]/npi.shape[1]
# plt.colorbar(im,fraction=0.046*im_ratio, pad=0.04)
plt.colorbar()
name = 'npi_after{}mapping'.format(npi_reduce_method)
ax.set_aspect(1.0/ax.get_data_ratio(), adjustable='box')
plt.title(name)
plt.savefig(os.path.join(te_save_path, '{}.svg'.format(name)))
plt.close('all')
############################################################
###############brain pca pls loading
def vis6(comp=0, variable = 'roi', vis = 'full', decomp = True, roi_num = 100, fc_reduce_method2 = 'pca'):
if vis == 'full':
name = 'brain_pca_pls_loading_comp{}_{}_full'.format(comp, variable)
else:
name = 'brain_pca_pls_loading_comp{}_{}_top100'.format(comp, variable)
if decomp:
if fc_reduce_method2 == 'mad':
fc_pca_pls_loading = np.zeros((roi_num*(roi_num-1)//2, ca_components))
fc_pca_pls_loading[mask] = w_x
else:
fc_pca_pls_loading = np.dot(fmri_pca.components_.T, w_x)
fc_pca_pls_loading_sys, _ = vector_to_matrix(fc_pca_pls_loading[:,comp], roi_num)
else:
fc_pca_pls_loading_sys, _ = vector_to_matrix(w_x[:,comp], roi_num)
if roi_num == 100:
atlas = 'shf_100'
else:
atlas = 'shf_200'
if variable == 'roi':
if vis != 'full':
if decomp:
fc_pca_pls_loading_sys[abs(fc_pca_pls_loading_sys)<np.sort(abs(fc_pca_pls_loading[:,comp]))[-100]] = 0
else:
fc_pca_pls_loading_sys[abs(fc_pca_pls_loading_sys)<np.sort(abs(w_x[:,comp]))[-100]] = 0
fig, ax = plt.subplots(figsize=(15, 15))
roi_idx = np.arange(0,roi_num,1)
im, cbar = heatmap(fc_pca_pls_loading_sys, roi_idx, ax=ax, cmap="RdBu_r",
cbarlabel="Weights",atlas = atlas, half_or_full='half')
# im, cbar = heatmap(fc_pca_pls_loading_sys, roi_idx, ax=ax, cmap="RdBu_r",
# cbarlabel_bl="Weights")
# plt.title(name)
plt.savefig(os.path.join(te_save_path, '{}.svg'.format(name)), bbox_inches = 'tight')
else:
net_pca_pls_loading_sys = get_net_net_connect(np.expand_dims(abs(fc_pca_pls_loading_sys), 0), 1)
net_pca_pls_loading_sys = net_pca_pls_loading_sys.squeeze()
vis_loading_sys =net_pca_pls_loading_sys
mask_id = abs(np.tri(vis_loading_sys.shape[0], k=0)-1)
vis_loading_sys = np.ma.array(vis_loading_sys, mask=mask_id) # mask out the lower triangle
fig, ax = plt.subplots(figsize=(15, 15))
net_idx = np.arange(0,7,1)
im, cbar = heatmap(vis_loading_sys, net_idx, ax=ax, cmap="Reds", connect_type='net',
cbarlabel="Weights", dash_line = 'no',atlas = atlas)
# im, cbar = heatmap(vis_loading_sys, net_idx, ax=ax, cmap="Reds", connect_type='net',
# cbarlabel_bl="Weights", dash_line = 'no')
# plt.title(name)
plt.savefig(os.path.join(te_save_path, '{}.svg'.format(name)), bbox_inches = 'tight')
return fc_pca_pls_loading_sys
###############################################################
##########npi and brain transformed score
def vis7(comp=0):
plt.figure(figsize =(15,15))
ax = plt.gca()
norm = mcolors.TwoSlopeNorm(vmin=X_train_.min(), vmax = X_train_.max(), vcenter=0)
im = plt.imshow(X_train_, cmap = 'RdBu_r', norm=norm)
im_ratio = npi.shape[0]/npi.shape[1]
plt.colorbar(im,fraction=0.046*im_ratio, pad=0.04)
# plt.colorbar()1
name = 'cca_X_train_transform'
plt.title(name)
ax.set_aspect(1.0/ax.get_data_ratio(), adjustable='box')
plt.savefig(os.path.join(te_save_path, '{}.svg'.format(name)), bbox_inches = 'tight')
plt.figure(figsize =(15,15))
ax = plt.gca()
norm = mcolors.TwoSlopeNorm(vmin=y_train_.min(), vmax = y_train_.max(), vcenter=0)
im = plt.imshow(y_train_, cmap = 'RdBu_r', norm=norm)
im_ratio = npi.shape[0]/npi.shape[1]
plt.colorbar(im,fraction=0.046*im_ratio, pad=0.04)
name = 'cca_y_train_transform'
plt.title(name)
ax.set_aspect(1.0/ax.get_data_ratio(), adjustable='box')
plt.savefig(os.path.join(te_save_path, '{}.svg'.format(name)), bbox_inches = 'tight')