forked from weikanggong/BWAS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BWAS_cpu.py
1291 lines (955 loc) · 49.2 KB
/
BWAS_cpu.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
# Script name: BWAS_cpu.py
#
# Description: Functions to run BWAS analysis using CPU
#
# Author: Weikang Gong
#
# Reference: Gong, W., Wan, L., Lu, W., Ma, L., Cheng, F., Cheng, W., Gruenewald, S. and Feng, J., 2018. Statistical testing and power analysis for brain-wide association study. Medical image analysis, 47, pp.15-30.
#
# Weikang Gong
# DPhil Student, WIN, FMRIB
# Nuffield Department of Clinical Neurosciences
# University of Oxford
# Oxford OX3 9DU, UK
# Email: [email protected] or [email protected]
#
# Copyright 2018 University of Oxford
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import time
import os
from copy import deepcopy
import glob
import sys
import numpy as np
from scipy.spatial.distance import cdist
from scipy import sparse
from scipy.stats import norm
import scipy
import scipy.io as sio
import scipy.signal
from scipy import misc
import matplotlib as mpl
mpl.use('Agg')
from nilearn import plotting
import nibabel as nib
from joblib import Parallel, delayed
import multiprocessing
from PyPDF2 import PdfFileMerger
def BWAS_correlation(fMRI_2D_1,fMRI_2D_2):
# fMRI_2D_1 and fMRI_2D_2 are both time * voxel (t * p1 and t * p2) matrices
# This function return the fisher z transformed correlation matrix (p1 * p2)
fMRI_2D_1 = (fMRI_2D_1 - fMRI_2D_1.mean(axis=0)) / fMRI_2D_1.std(axis=0)
fMRI_2D_2 = (fMRI_2D_2 - fMRI_2D_2.mean(axis=0)) / fMRI_2D_2.std(axis=0)
r=np.dot(np.transpose(fMRI_2D_1),fMRI_2D_2) / fMRI_2D_1.shape[0]
return r
def BWAS_fisher_z(r):
r=0.5 * np.log(np.divide(1+r,1-r))
return r
def BWAS_regression_online1(X,Y,st,en,Betas0):
ss=np.linalg.pinv(np.dot(X.T,X))
Betas1=Betas0+np.dot(np.dot(ss,X[st:en,:].T),Y)
return Betas1
def BWAS_regression_online2(X,Y,st,en,Beta_glm,Sigma0):
#caculate current residual
Res=Y-np.dot(X[st:en,:],Beta_glm)
#update sigma
Sigma_glm=Sigma0+np.sum(np.square(Res),axis=0)
return Sigma_glm
def BWAS_regression_online3(X,Beta_glm,Sigma_glm):
#contrast
contrast=np.hstack((np.ones((1,1),dtype='float32'),np.zeros((1,X.shape[1]-1),dtype='float32'))).T
ss=np.linalg.pinv(np.dot(X.T,X))
#df
df=X.shape[0]-X.shape[1]
#tstat
Tstat=np.divide(np.dot(Beta_glm.T,contrast),np.dot(np.sqrt(Sigma_glm/df).T,np.sqrt(np.dot(np.dot(contrast.T,ss),contrast))))
return Tstat
def BWAS_est_fwhm(fMRI):
#4d fmri + 3d mask
#output fwhm of each time point
#mask=nib.load('/Users/wgong/Documents/MATLAB/hcp_bwas/hcp_bwas_mask_final_4mm.nii.gz').get_data()
#fMRI=nib.load('/Users/wgong/Documents/MATLAB/hcp_bwas/100206_rest1.nii.gz').get_data()
fMRI=scipy.signal.detrend(fMRI,3)
if len(fMRI.shape)==3:
[n1,n2,n3]=fMRI.shape
n4=1
else:
[n1,n2,n3,n4]=fMRI.shape
fMRI=fMRI*fMRI/fMRI
dx = np.diff(fMRI,1,0);
varX=np.nanvar(np.reshape(dx,[(n1-1)*n2*n3,n4]),axis=0)
dy = np.diff(fMRI,1,1);
varY=np.nanvar(np.reshape(dy,[n1*(n2-1)*n3,n4]),axis=0)
dz = np.diff(fMRI,1,2);
varZ=np.nanvar(np.reshape(dz,[n1*n2*(n3-1),n4]),axis=0)
varXYZ=(varX*varY*varZ)**(1/3.0);
varImg=np.zeros((n4,))
for i in range(0,n4):
tmp=fMRI[:,:,:,i]
varImg[i]=np.nanvar(tmp)
fwhm=np.real(np.sqrt(-2*np.log(2)/np.log(1-varXYZ/2/varImg)))
return fwhm
def BWAS_prepare(imgs_abs_dir,mask,nargout):
# BWAS_prepare(imgs_abs_dir,mask,name)
#Input imgs_abs_dir: list, one cell one absolute path of preprocessed fmri image
# mask: 3D matrix, non-zero elements are the voxel you want to use
# in the analysis.
#Output images: the data can be used in subsequent analysis.
tmp1= '.nii.gz' in imgs_abs_dir[0][0]
#tmp2= '.dtseries.nii' in imgs_abs_dir[0][0]
nrun=len(imgs_abs_dir[0])
nsub=len(imgs_abs_dir)
mask1=np.reshape(mask,[mask.shape[0]* mask.shape[1]* mask.shape[2]])
list_of_arrays=[np.array(a) for a in range (0,nsub)]
images = deepcopy(list_of_arrays)
fwhm=np.zeros((nsub,nrun))
if tmp1:
for i in range(0,nsub):
image1=None
for j in range(0,nrun):
print('Reading image '+imgs_abs_dir[i][j]+'...')
#load data
img = nib.load(imgs_abs_dir[i][j])
data = np.float32(img.get_data())
#estimate fwhm
if nargout==2:
print('Estimating Smoothness...')
fwhm[i,j]=np.mean(BWAS_est_fwhm(data))
print('FWHM = '+str(fwhm[i,j])+' voxels')
#to 2d matrix
img2d=np.reshape(data,[data.shape[0]* data.shape[1]* data.shape[2],data.shape[3]])
img2d=np.transpose(img2d[mask1!=0,:])
#connect by time
if j==0:
image1=(img2d - img2d.mean(axis=0)) / img2d.std(axis=0)
else:
image1=np.vstack((image1,(img2d - img2d.mean(axis=0)) / img2d.std(axis=0)))
print('Done...')
images[i]=image1
if nargout==2:
fwhm=np.mean(fwhm)
return image1,fwhm
if nargout==1:
return image1
def BWAS_prepare_parallel(imgs_abs_dir,mask,ncore,nargout):
# BWAS_prepare(imgs_abs_dir,mask,name)
#Input imgs_abs_dir: list, one cell one absolute path of preprocessed fmri image
# mask: 3D matrix, non-zero elements are the voxel you want to use
# in the analysis.
#Output images: the data can be used in subsequent analysis.
def readImage(img_name,mask,nrun,nargout):
fwhm=np.zeros((nrun,))
for j in range(0,nrun):
print('Reading image '+img_name[j]+'...')
#load data
img = nib.load(img_name[j])
data = np.float32(img.get_data())
#estimate fwhm
if nargout==2:
print('Estimating Smoothness...')
fwhm[j]=np.mean(BWAS_est_fwhm(data))
print('FWHM = '+str(fwhm[j])+' voxels')
#to 2d matrix
img2d=np.reshape(data,[data.shape[0]* data.shape[1]* data.shape[2],data.shape[3]])
img2d=np.transpose(img2d[mask1!=0,:])
#connect by time
if j==0:
image1=(img2d - img2d.mean(axis=0)) / img2d.std(axis=0)
else:
image1=np.vstack((image1,(img2d - img2d.mean(axis=0)) / img2d.std(axis=0)))
print('Done...')
if nargout==2:
fwhm=np.mean(fwhm)
return image1,fwhm
if nargout==1:
return image1
num_cores = multiprocessing.cpu_count()
print('Number of cores = '+str(num_cores))
nrun=len(imgs_abs_dir[0])
nsub=len(imgs_abs_dir)
mask1=np.reshape(mask,[mask.shape[0]* mask.shape[1]* mask.shape[2]])
list_of_arrays=[np.array(a) for a in range (0,nsub)]
images = deepcopy(list_of_arrays)
fwhms=np.zeros((nsub,))
results=Parallel(n_jobs=min(num_cores-2,ncore))(delayed(readImage)(img_name,mask,nrun,nargout) for img_name in imgs_abs_dir)
if nargout==2:
for i in range(0,nsub):
images[i]=results[i][0]
fwhms[i]=results[i][1]
return images,fwhms
if nargout==1:
for i in range(0,nsub):
images[i]=results[i]
return images
def BWAS_glm_online(image_names,targets,covariates,mask,options):
# BWAS_glm_online(image_names,targets,covariates,mask,options)
# Inputs: images_names: N*P cells, N subjects, P fMRI runs to connect together
# (within run mean and variance normalization);
# support nii.gz or cifti format.
# Targets: N*Q matrix, N subjects, Q target variables,
# results will be stored in separate directories.
# covariates: The covariates to regress out
# mask: the image masks
# (for nii.gz, it is a 3D one, and for cifti, it is a 1D vector )
# A list of options from previous scripts
#where to save your results
result_dir = options['result_dir']
print('Results will be saved to '+result_dir)
#subject dimension batch size
sub_batchsize=options['sub_batchsize']
#voxel dimension batch size
vol_batchsize=options['vol_batchsize']
#number of voxels
nvol=options['nvol']
print('Number of voxels = '+str(nvol))
#number of runs (e.g. HCP)
#nrun=size(image_names,2);
#number of behavior of interests
nsub,ntargets=targets.shape
print('Number of Subjects = '+str(nsub))
print('Number of Variable of Interests = '+str(ntargets))
#mkdir of results
for i in range(0,targets.shape[1]):
if not os.path.exists(result_dir+'glm_results'+('%03d' % i)):
os.mkdir(result_dir+'glm_results'+('%03d' % i))
#get design matrix demensions
design=np.hstack((np.reshape(targets[:,0],(nsub,1)),covariates,np.ones((nsub,1))));
ncov=design.shape[1]
print('Number of Covariates = '+str(ncov))
#total number of subject batchs
ind_end1=int(nsub/sub_batchsize-1e-4)+1;
#total number of voxel batchs
ind_end2=int(nvol/vol_batchsize-1e-4)+1;
####estimating Betas======================================================
fname=os.path.join(result_dir,'glm_results'+ ('%03d' % (ntargets-1))+'/stat_map' + ('%04d' % (ind_end2-1)) + '_iter' + ('%03d' % (ind_end1-1)) + '_Betas.npy')
if os.path.exists(fname):
print('We have got the results of all Betas ...')
print('Omit the steps of estimating Betas...')
else:
FWHMs=np.zeros((nsub,1))
for i in range(0,ind_end1):
st11=int(i*sub_batchsize)
en11=min(int((i+1)*sub_batchsize),nsub)
#sub_ids=subj_list(st11:en11);
#load images of this subject batch
print('Loading rsfMRI data of subject batch... '+
str(i+1)+'/'+str(ind_end1)+'...')
print('Total number of subjects in this batch = '+ str(en11-st11)+'...')
#read data, estimate smoothness
images,fwhms=BWAS_prepare(image_names[st11:en11],mask,2)
#print(len(images))
FWHMs[st11:en11,0]=fwhms
#get network of each voxel batch
for j in range(0,ind_end2):
start = time.time()
#get voxel index to analysis
st1=int(j*vol_batchsize)
en1=min(int(j+1)*vol_batchsize,nvol)
nn=int(nvol*(en1-st1))
#correlation matrix
print('Calculating the correlation matrix across all subjects... '+
str(j+1)+'/'+str(ind_end2)+'...')
r1=np.zeros((en11-st11,nvol,en1-st1),dtype='float32')
for jjj in range(0,en11-st11):
img_tmp=images[jjj]
tmp=BWAS_correlation(img_tmp,img_tmp[:,st1:en1])
tmp[tmp>0.9999]=0
r1[jjj,:,:]=tmp
r1=BWAS_fisher_z(r1)
r1=np.reshape(r1,(en11-st11,nn))
r1[np.isnan(r1)]=0
nfc_tmp=r1.shape[1]
print('Calculating the Statistical Parametirc Maps... '+
str(j+1)+'/'+str(ind_end2)+'...')
#GLM across different behavior variables
for ii in range(0,ntargets):
#get design matrix
design1=np.float32(np.hstack((np.reshape(targets[:,ii],(nsub,1)),covariates)))
if i==0:
#if this is not the last iter
if (ind_end1-1)>0:
#This is the first batch, initialize Betas0
Betas0=np.zeros((ncov,nfc_tmp),dtype='float32')
#Do GLM update
Betas_glm=BWAS_regression_online1(design1,r1,st11,en11,Betas0)
fname1=os.path.join(result_dir,'glm_results'+ ('%03d' % ii)+'/stat_map' + ('%04d' % j) + '_iter' + ('%03d' % i) + '_Betas.npy')
np.save(fname1,Betas_glm)
else:
#load results of lastest iteration
fname1=os.path.join(result_dir,'glm_results'+ ('%03d' % ii)+'/stat_map' + ('%04d' % j) + '_iter' + ('%03d' % (i-1)) + '_Betas.npy')
Betas0=np.load(fname1)
#update beta
Betas_glm=BWAS_regression_online1(design1,r1,st11,en11,Betas0)
#remove previous beta
os.remove(fname1)
#save results
fname1=os.path.join(result_dir,'glm_results'+ ('%03d' % ii)+'/stat_map' + ('%04d' % j) + '_iter' + ('%03d' % i) + '_Betas.npy')
np.save(fname1,Betas_glm)
end = time.time()
print('Total run time for Beta = ' + str(round(end - start,2))+ ' seconds...')
np.save(os.path.join(result_dir,'FWHMs.npy'),FWHMs)
####estimating Residual variances======================================================
fname=os.path.join(result_dir,'glm_results'+ ('%03d' % (ntargets-1))+'/stat_map' + ('%04d' % (ind_end2-1)) + '_iter' + ('%03d' % (ind_end1-1)) + '_Sigma.npy')
if os.path.exists(fname):
print('We have got the results of all Residual Variances ...')
print('Omit the steps of estimating Residual Variances...')
else:
for i in range(0,ind_end1):
st11=int(i*sub_batchsize)
en11=min(int((i+1)*sub_batchsize),nsub)
#sub_ids=subj_list(st11:en11);
#load images of this subject batch
print('Loading rsfMRI data of subject batch... '+
str(i+1)+'/'+str(ind_end1)+'...')
print('Total number of subjects in this batch = '+ str(en11-st11)+'...')
#read data, estimate smoothness
images=BWAS_prepare(image_names[st11:en11],mask,1)
#get network of each voxel batch
for j in range(0,ind_end2):
start = time.time()
#get voxel index to analysis
st1=int(j*vol_batchsize)
en1=min(int(j+1)*vol_batchsize,nvol)
nn=int(nvol*(en1-st1))
#correlation matrix
print('Calculating the correlation matrix across all subjects... '+
str(j+1)+'/'+str(ind_end2)+'...')
r1=np.zeros((en11-st11,nvol,en1-st1),dtype='float32')
for jjj in range(0,en11-st11):
img_tmp=images[jjj]
tmp=BWAS_correlation(img_tmp,img_tmp[:,st1:en1])
tmp[tmp>0.9999]=0
r1[jjj,:,:]=tmp
r1=BWAS_fisher_z(r1)
r1=np.reshape(r1,(en11-st11,nn))
r1[np.isnan(r1)]=0
nfc_tmp=r1.shape[1]
print('Calculating the Statistical Parametirc Maps... '+
str(j+1)+'/'+str(ind_end2)+'...')
#GLM across different behavior variables
for ii in range(0,ntargets):
#get design matrix
design1=np.float32(np.hstack((np.reshape(targets[:,ii],(nsub,1)),covariates)))
fname1=os.path.join(result_dir,'glm_results'+ ('%03d' % ii)+'/stat_map' + ('%04d' % j) + '_iter' + ('%03d' % (ind_end1-1)) + '_Betas.npy')
Betas_glm=np.load(fname1)
if i==0:
#if this is not the last iter
if (ind_end1-1)>0:
#This is the first batch, initialize Sigma0
Sigma0=np.zeros((1,nfc_tmp),dtype='float32')
#Do GLM update
Sigma_glm=BWAS_regression_online2(design1,r1,st11,en11,Betas_glm,Sigma0)
fname1=os.path.join(result_dir,'glm_results'+ ('%03d' % ii)+'/stat_map' + ('%04d' % j) + '_iter' + ('%03d' % i) + '_Sigma.npy')
np.save(fname1,Sigma_glm)
else:
#load results of lastest iteration
fname1=os.path.join(result_dir,'glm_results'+ ('%03d' % ii)+'/stat_map' + ('%04d' % j) + '_iter' + ('%03d' % (i-1)) + '_Sigma.npy')
Sigma0=np.load(fname1)
#update beta
Sigma_glm=BWAS_regression_online2(design1,r1,st11,en11,Betas_glm,Sigma0)
#remove previous beta
os.remove(fname1)
#save results
fname1=os.path.join(result_dir,'glm_results'+ ('%03d' % ii)+'/stat_map' + ('%04d' % j) + '_iter' + ('%03d' % i) + '_Sigma.npy')
np.save(fname1,Sigma_glm)
end = time.time()
print('Total run time for Residual variance = ' + str(round(end - start,2))+ ' seconds...')
#estimate z-stat
for j in range(0,ind_end2):
start = time.time()
#get voxel index to analysis
st1=int(j*vol_batchsize)
en1=min(int(j+1)*vol_batchsize,nvol)
print('Calculating the Statistical Parametirc Maps... '+
str(j+1)+'/'+str(ind_end2)+'...')
#GLM across different behavior variables
for ii in range(0,ntargets):
#get design matrix
design1=np.float32(np.hstack((np.reshape(targets[:,ii],(nsub,1)),covariates)))
fname1=os.path.join(result_dir,'glm_results'+ ('%03d' % ii)+'/stat_map' + ('%04d' % j) + '_iter' + ('%03d' % (ind_end1-1)) + '_Betas.npy')
Betas_glm=np.load(fname1)
fname2=os.path.join(result_dir,'glm_results'+ ('%03d' % ii)+'/stat_map' + ('%04d' % j) + '_iter' + ('%03d' % (ind_end1-1)) + '_Sigma.npy')
Sigma_glm=np.load(fname2)
os.remove(fname1)
os.remove(fname2)
stat_map=BWAS_regression_online3(design1,Betas_glm,Sigma_glm)
#do reshape
stat_map=np.reshape(stat_map,(nvol,(en1-st1)))
#convert t to z
stat_map=norm.ppf(scipy.stats.t.cdf(stat_map,nsub-ncov-1))
#save results
fname=os.path.join(result_dir,'glm_results'+ ('%03d' % ii)+'/stat_map' + ('%04d' % j) + '_iter' + ('%03d' % i) + '.npy')
np.save(fname,stat_map)
end = time.time()
print('Total run time for z-stat = ' + str(round(end - start,2))+ ' seconds...')
return
##This is for parallel in CPU################################################################################################
################################################################################################################################################
def BWAS_net_parallel(img,st1,en1,nn):
r=BWAS_correlation(img,img[:,st1:en1])
r[r>0.9999]=0
r=BWAS_fisher_z(r)
r[np.isnan(r)]=0
r=np.reshape(r,(nn,))
return r
def BWAS_parallel_beta(j,i,result_dir,images,targets,covariates,vol_batchsize,st11,en11,nvol,nsub,ncov,ntargets,ind_end1,ind_end2):
start = time.time()
#get voxel index to analysis
st1=int(j*vol_batchsize)
en1=min(int(j+1)*vol_batchsize,nvol)
nn=int(nvol*(en1-st1))
#correlation matrix
print('Calculating the correlation matrix across all subjects... '+
str(j+1)+'/'+str(ind_end2)+'...')
r1=np.zeros((en11-st11,nvol,en1-st1),dtype='float32')
for jjj in range(0,en11-st11):
img_tmp=images[jjj]
tmp=BWAS_correlation(img_tmp,img_tmp[:,st1:en1])
tmp[tmp>0.9999]=0
r1[jjj,:,:]=tmp
r1=BWAS_fisher_z(r1)
r1=np.reshape(r1,(en11-st11,nn))
r1[np.isnan(r1)]=0
nfc_tmp=r1.shape[1]
print('Calculating the Statistical Parametirc Maps... '+
str(j+1)+'/'+str(ind_end2)+'...')
#GLM across different behavior variables
for ii in range(0,ntargets):
#get design matrix
design1=np.float32(np.hstack((np.reshape(targets[:,ii],(nsub,1)),covariates)))
if i==0:
#if this is not the last iter
if (ind_end1-1)>0:
#This is the first batch, initialize Betas0
Betas0=np.zeros((ncov,nfc_tmp),dtype='float32')
#Do GLM update
Betas_glm=BWAS_regression_online1(design1,r1,st11,en11,Betas0)
fname1=os.path.join(result_dir,'glm_results'+ ('%03d' % ii)+'/stat_map' + ('%04d' % j) + '_iter' + ('%03d' % i) + '_Betas.npy')
np.save(fname1,Betas_glm)
else:
#load results of lastest iteration
fname1=os.path.join(result_dir,'glm_results'+ ('%03d' % ii)+'/stat_map' + ('%04d' % j) + '_iter' + ('%03d' % (i-1)) + '_Betas.npy')
Betas0=np.load(fname1)
#update beta
Betas_glm=BWAS_regression_online1(design1,r1,st11,en11,Betas0)
#remove previous beta
os.remove(fname1)
#save results
fname1=os.path.join(result_dir,'glm_results'+ ('%03d' % ii)+'/stat_map' + ('%04d' % j) + '_iter' + ('%03d' % i) + '_Betas.npy')
np.save(fname1,Betas_glm)
end = time.time()
print('Total run time for Beta = ' + str(round(end - start,2))+ ' seconds...')
def BWAS_parallel_Sigma(j,i,result_dir,images,targets,covariates,vol_batchsize,st11,en11,nvol,nsub,ncov,ntargets,ind_end1,ind_end2):
start = time.time()
#get voxel index to analysis
st1=int(j*vol_batchsize)
en1=min(int(j+1)*vol_batchsize,nvol)
nn=int(nvol*(en1-st1))
#correlation matrix
print('Calculating the correlation matrix across all subjects... '+
str(j+1)+'/'+str(ind_end2)+'...')
r1=np.zeros((en11-st11,nvol,en1-st1),dtype='float32')
for jjj in range(0,en11-st11):
img_tmp=images[jjj]
tmp=BWAS_correlation(img_tmp,img_tmp[:,st1:en1])
tmp[tmp>0.9999]=0
r1[jjj,:,:]=tmp
r1=BWAS_fisher_z(r1)
r1=np.reshape(r1,(en11-st11,nn))
r1[np.isnan(r1)]=0
nfc_tmp=r1.shape[1]
print('Calculating the Statistical Parametirc Maps... '+
str(j+1)+'/'+str(ind_end2)+'...')
#GLM across different behavior variables
for ii in range(0,ntargets):
#get design matrix
design1=np.float32(np.hstack((np.reshape(targets[:,ii],(nsub,1)),covariates)))
fname1=os.path.join(result_dir,'glm_results'+ ('%03d' % ii)+'/stat_map' + ('%04d' % j) + '_iter' + ('%03d' % (ind_end1-1)) + '_Betas.npy')
Betas_glm=np.load(fname1)
if i==0:
#if this is not the last iter
if (ind_end1-1)>0:
#This is the first batch, initialize Sigma0
Sigma0=np.zeros((1,nfc_tmp),dtype='float32')
#Do GLM update
Sigma_glm=BWAS_regression_online2(design1,r1,st11,en11,Betas_glm,Sigma0)
fname1=os.path.join(result_dir,'glm_results'+ ('%03d' % ii)+'/stat_map' + ('%04d' % j) + '_iter' + ('%03d' % i) + '_Sigma.npy')
np.save(fname1,Sigma_glm)
else:
#load results of lastest iteration
fname1=os.path.join(result_dir,'glm_results'+ ('%03d' % ii)+'/stat_map' + ('%04d' % j) + '_iter' + ('%03d' % (i-1)) + '_Sigma.npy')
Sigma0=np.load(fname1)
#update beta
Sigma_glm=BWAS_regression_online2(design1,r1,st11,en11,Betas_glm,Sigma0)
#remove previous beta
os.remove(fname1)
#save results
fname1=os.path.join(result_dir,'glm_results'+ ('%03d' % ii)+'/stat_map' + ('%04d' % j) + '_iter' + ('%03d' % i) + '_Sigma.npy')
np.save(fname1,Sigma_glm)
end = time.time()
print('Total run time for Residual variance = ' + str(round(end - start,2))+ ' seconds...')
def BWAS_parallel_zstat(j,i,result_dir,targets,covariates,vol_batchsize,st11,en11,nvol,nsub,ncov,ntargets,ind_end1,ind_end2):
start = time.time()
#get voxel index to analysis
st1=int(j*vol_batchsize)
en1=min(int(j+1)*vol_batchsize,nvol)
print('Calculating the Statistical Parametirc Maps... '+
str(j+1)+'/'+str(ind_end2)+'...')
#GLM across different behavior variables
for ii in range(0,ntargets):
#get design matrix
design1=np.float32(np.hstack((np.reshape(targets[:,ii],(nsub,1)),covariates)))
fname1=os.path.join(result_dir,'glm_results'+ ('%03d' % ii)+'/stat_map' + ('%04d' % j) + '_iter' + ('%03d' % (ind_end1-1)) + '_Betas.npy')
Betas_glm=np.load(fname1)
fname2=os.path.join(result_dir,'glm_results'+ ('%03d' % ii)+'/stat_map' + ('%04d' % j) + '_iter' + ('%03d' % (ind_end1-1)) + '_Sigma.npy')
Sigma_glm=np.load(fname2)
os.remove(fname1)
os.remove(fname2)
stat_map=BWAS_regression_online3(design1,Betas_glm,Sigma_glm)
#do reshape
stat_map=np.reshape(stat_map,(nvol,(en1-st1)))
#convert t to z
stat_map=norm.ppf(scipy.stats.t.cdf(stat_map,nsub-ncov-1))
#save results
fname=os.path.join(result_dir,'glm_results'+ ('%03d' % ii)+'/stat_map' + ('%04d' % j) + '_iter' + ('%03d' % i) + '.npy')
np.save(fname,stat_map)
end = time.time()
print('Total run time for z-stat = ' + str(round(end - start,2))+ ' seconds...')
return
def BWAS_glm_online_parallel(image_names,targets,covariates,mask,options):
# BWAS_glm_online(image_names,targets,covariates,mask,options)
# Inputs: images_names: N*P cells, N subjects, P fMRI runs to connect together
# (within run mean and variance normalization);
# support nii.gz or cifti format.
# Targets: N*Q matrix, N subjects, Q target variables,
# results will be stored in separate directories.
# covariates: The covariates to regress out
# mask: the image masks
# (for nii.gz, it is a 3D one, and for cifti, it is a 1D vector )
# A list of options from previous scripts
#where to save your results
result_dir = options['result_dir']
print('Results will be saved to '+result_dir)
#subject dimension batch size
sub_batchsize=options['sub_batchsize']
#voxel dimension batch size
vol_batchsize=options['vol_batchsize']
#number of voxels
nvol=options['nvol']
print('Number of voxels = '+str(nvol))
#number of runs (e.g. HCP)
#nrun=size(image_names,2);
#number of behavior of interests
nsub,ntargets=targets.shape
print('Number of Subjects = '+str(nsub))
print('Number of Variable of Interests = '+str(ntargets))
#mkdir of results
for i in range(0,targets.shape[1]):
if not os.path.exists(result_dir+'glm_results'+('%03d' % i)):
os.mkdir(result_dir+'glm_results'+('%03d' % i))
#get design matrix demensions
design=np.hstack((np.reshape(targets[:,0],(nsub,1)),covariates));
ncov=design.shape[1]
print('Number of Covariates (including a column of ones) = '+str(ncov))
#total number of subject batchs
ind_end1=int(nsub/sub_batchsize-1e-4)+1;
#total number of voxel batchs
ind_end2=int(nvol/vol_batchsize-1e-4)+1;
####estimating Betas======================================================
fname=os.path.join(result_dir,'glm_results'+ ('%03d' % (ntargets-1))+'/stat_map' + ('%04d' % (ind_end2-1)) + '_iter' + ('%03d' % (ind_end1-1)) + '_Betas.npy')
if os.path.exists(fname):
print('We have got the results of all Betas ...')
print('Omit the steps of estimating Betas...')
else:
FWHMs=np.zeros((nsub,1))
for i in range(0,ind_end1):
st11=int(i*sub_batchsize)
en11=min(int((i+1)*sub_batchsize),nsub)
#sub_ids=subj_list(st11:en11);
#load images of this subject batch
print('Loading rsfMRI data of subject batch... '+
str(i+1)+'/'+str(ind_end1)+'...')
print('Total number of subjects in this batch = '+ str(en11-st11)+'...')
#read data, estimate smoothness
images,fwhms=BWAS_prepare_parallel(image_names[st11:en11],mask,options['ncore'],2)
#print(len(images))
FWHMs[st11:en11,0]=fwhms
#get network of each voxel batch
#for j in range(0,ind_end2):
num_cores = multiprocessing.cpu_count()
Parallel(n_jobs=min(num_cores-2,options['ncore']))(delayed(
BWAS_parallel_beta)(j,i,result_dir,images,targets,covariates,vol_batchsize,st11,en11,nvol,nsub,ncov,ntargets,ind_end1,ind_end2) for j in range(0,ind_end2))
np.save(os.path.join(result_dir,'FWHMs.npy'),FWHMs)
####estimating Residual variances======================================================
fname=os.path.join(result_dir,'glm_results'+ ('%03d' % (ntargets-1))+'/stat_map' + ('%04d' % (ind_end2-1)) + '_iter' + ('%03d' % (ind_end1-1)) + '_Sigma.npy')
if os.path.exists(fname):
print('We have got the results of all Residual Variances ...')
print('Omit the steps of estimating Residual Variances...')
else:
for i in range(0,ind_end1):
st11=int(i*sub_batchsize)
en11=min(int((i+1)*sub_batchsize),nsub)
#sub_ids=subj_list(st11:en11);
#load images of this subject batch
print('Loading rsfMRI data of subject batch... '+
str(i+1)+'/'+str(ind_end1)+'...')
print('Total number of subjects in this batch = '+ str(en11-st11)+'...')
#read data, estimate smoothness
images=BWAS_prepare_parallel(image_names[st11:en11],mask,options['ncore'],1)
#get network of each voxel batch
#for j in range(0,ind_end2):
num_cores = multiprocessing.cpu_count()
Parallel(n_jobs=min(num_cores-2,options['ncore']))(delayed(
BWAS_parallel_Sigma)(j,i,result_dir,images,targets,covariates,vol_batchsize,st11,en11,nvol,nsub,ncov,ntargets,ind_end1,ind_end2) for j in range(0,ind_end2))
#estimate z-stat
num_cores = multiprocessing.cpu_count()
Parallel(n_jobs=min(num_cores-2,options['ncore']))(delayed(
BWAS_parallel_zstat)(j,i,result_dir,targets,covariates,vol_batchsize,st11,en11,nvol,nsub,ncov,ntargets,ind_end1,ind_end2) for j in range(0,ind_end2))
##This is the end for parallel in CPU 1################################################
def BWAS_GRF_6D_density(t):
#This is EC density of 6D Gaussian Random Field
EC=np.zeros((7,1))
a = 4.0 * np.log(2.0)
a1= 2.0 * np.pi
b = np.exp(-np.square(t)/2.0)
EC[0] = 1.0- norm.cdf(t)
EC[1] = a ** (1.0/2.0) / a1 * b
EC[2] = a/(a1 ** (3.0/2.0)) * b * t
EC[3] = a ** (3.0/2.0)/(a1**2.0) * b * (np.power(t,2) - 1)
EC[4] = a ** 2.0/(a1 ** (5.0/2.0)) * b * ( np.power(t,3) - 3 * t )
EC[5] = a ** (5.0/2.0)/(a1 ** 3.0) * b * ( np.power(t,4) - 6 * np.power(t,2) + 3 )
EC[6] = a ** 3.0/(a1 ** (7.0/2.0)) * b * ( np.power(t,5) - 10 * np.power(t,3) + 15*t)
return EC
def BWAS_whole_brain_cluster_p(nvoxel1,nvoxel2,cdt_z,cl_size,fwhm):
fwhm=np.array(fwhm,dtype='float64')
cdt_z=np.array(cdt_z,dtype='float64')
cl_size=np.array(cl_size,dtype='float64')
r1=(nvoxel1/(4.0/3.0*np.pi))**(1/3.0)
R1=[1,
4*(r1**3/np.prod(fwhm))**(1/3.0),
2*np.pi*(r1**3/np.prod(fwhm))**(2/3.0),
nvoxel1/np.prod(fwhm)]
r2=(nvoxel2/(4.0/3.0*np.pi))**(1/3.0)
R2=[1,
4*(r2**3/np.prod(fwhm))**(1/3.0),
2*np.pi*(r2**3/np.prod(fwhm))**(2/3.0),
nvoxel2/np.prod(fwhm)]
V=nvoxel1*nvoxel2
EC=BWAS_GRF_6D_density(cdt_z);
EN=V*(norm.cdf(-np.abs(cdt_z)))
EL1=0
for i in range(0,4):
for j in range(0,4):
EL1=EL1+R1[i]*R2[j]*EC[i+j];
if EL1<0:
p_uncorrected=1
p_corrected=1
else:
phi=(scipy.special.gamma(6.0/2.0+1)*EL1/EN)**(2.0/6.0);
p_uncorrected=np.exp(-phi*cl_size**(2.0/6.0));
p_corrected=1-np.exp(-EL1*p_uncorrected)
return p_corrected,p_uncorrected
def BWAS_get_sparse_dismat(dims):
#dims n*p
#output n*n
nvol=dims.shape[0]
nstep=10000
for i in range(0,nvol,nstep):
s=i
s1=min(i+nstep,nvol)
tmptmp=cdist(dims[s:s1,:],dims,'euclidean')
#tmp=np.where((tmptmp<1.5) & (tmptmp>0))
tmp=np.where(tmptmp<1.5)
if i==0:
coo1=tmp[0]
coo2=tmp[1]
else:
coo1=np.append(coo1,tmp[0]+i)
coo2=np.append(coo2,tmp[1])
#print(i)
adj=sparse.csc_matrix((np.ones((len(coo1))), (coo1, coo2)), shape=(nvol, nvol))
return adj
def BWAS_analysis_result(result_dir,mask_file,CDT,fwhm,options):
#result_dir='/Users/wgong/Documents/MATLAB/hcp_bwas/glm_results004/'
#iter_number=2
#mask_file='/Users/wgong/Documents/MATLAB/hcp_bwas/aal2_4mm.nii.gz'
#CDT=4.5
#fwhm=[2,2,2]
info=nib.load(mask_file)
mask=np.float64(info.get_data()!=0)
affine=info.affine
#mask=np.float32((mask>0) & (mask<9000))
#img = nib.Nifti1Image(mask, affine)
#nib.save(img, result_dir+'hcp_bwas_mask_final_4mm.nii.gz')
dim=np.array(np.where(mask!=0)).T
print('Number of voxels = '+str(dim.shape[0]))
mni=np.dot(np.hstack((dim,np.ones((dim.shape[0],1)))),affine.T[:,0:3])
nfile=len(glob.glob(result_dir+'stat_map*.npy'))
files_to_read=sorted(glob.glob(result_dir+'stat_map*.npy'))
print('Number of parts = '+str(nfile))
#load all fc z-value
print('Reading stat maps...')
ind_sig=np.zeros((dim.shape[0],dim.shape[0]),dtype='uint8')
nvol=dim.shape[0]
vol_batchsize=options['vol_batchsize']
for i in range(0,nfile):
st1=int(i*vol_batchsize)
en1=min(int((i+1)*vol_batchsize),int(nvol))
stat_map=np.load(files_to_read[i])
stat_map[np.isnan(stat_map)]=0
#significant
tmp=np.abs(stat_map)>CDT
ind_sig[:,st1:en1]=tmp
coo_tmp=np.array(np.where(tmp==1)).T
coo_tmp[:,1]=coo_tmp[:,1]+st1
zval_tmp=np.array(stat_map[tmp],ndmin=2).T
data_tmp=np.hstack((coo_tmp,zval_tmp))
if i==0:
data=data_tmp
else:
data=np.vstack((data,data_tmp))
print('Loading and preprocessing '+files_to_read[i])
print('Done...')
stat_map=sparse.csc_matrix((data[:,2], (data[:,0], data[:,1])), shape=(nvol, nvol))
#index of fcs with |z|>cdt
ind_sig=np.triu(ind_sig,0)
#matrix index
ind_sig_mat=np.array(np.where(ind_sig==1)).T
ind_sig=None
print('Number of FCs with |z|>'+str(CDT)+' = '+str(ind_sig_mat.shape[0]))
if ind_sig_mat.shape[0]==0:
print('No significant FCs...')
else:
#get 6d coordiantes
FC_6d_coordiantes=np.hstack((dim[ind_sig_mat[:,0],:],dim[ind_sig_mat[:,1],:]))
FC_6d_MNI=np.hstack((mni[ind_sig_mat[:,0],:],mni[ind_sig_mat[:,1],:]))
#calculate (sparse) distance matrix of mask
adj=BWAS_get_sparse_dismat(dim)
#coo=np.where(cdist(dim,dim,'euclidean')<1.5)
#coo=np.array(coo).T
#adj=sparse.csc_matrix((np.ones((len(coo))), (coo[:,0], coo[:,1])), shape=(nvol, nvol))
#first 3 dims' adj matrix