-
Notifications
You must be signed in to change notification settings - Fork 9
/
HCP_task_fmri_gcn_test8.py
executable file
·2207 lines (1943 loc) · 117 KB
/
HCP_task_fmri_gcn_test8.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/home/yuzhang/tensorflow-py3.6/bin/python3.6
# Author: Yu Zhang
# License: simplified BSD
# coding: utf-8
## ps | grep python; pkill python
from pathlib import Path
import glob
import itertools
import lmdb
import h5py
import os
import sys
import time
import datetime
import shutil
from operator import itemgetter
from collections import Counter
import ast
import math
import numpy as np
import pandas as pd
import nibabel as nib
from scipy import sparse
import argparse
os.environ['KMP_DUPLICATE_LIB_OK']='True'
from nilearn import connectome
from nilearn import signal,image,masking
from sklearn import preprocessing
from sklearn.model_selection import cross_val_score, train_test_split,ShuffleSplit
from keras.utils import np_utils
import pickle
import lmdb
import tensorflow as tf
from tensorpack import dataflow
from tensorpack.utils.serialize import dumps, loads
from tensorpack.utils import logger
from tensorpack.utils.gpu import get_num_gpu
from tensorpack.tfutils.common import get_tf_version_tuple
try:
# import cnn_graph
###sys.path.append('/path/to/application/app/folder')
from cnn_graph.lib_new import models, graph, coarsening, utils
except ImportError:
print('Could not find the package of graph-cnn ...')
print('Please check the location where cnn_graph is !\n')
#####global variable settings
'''
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"]="0,1"
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
'''
USE_GPU_CPU = 1
num_CPU = 6
num_GPU = 1 #get_num_gpu() # len(used_GPU_avail)
print('\nAvaliable GPUs for usage: %d \n' % num_GPU)
config_TF = tf.ConfigProto(intra_op_parallelism_threads=num_CPU,\
inter_op_parallelism_threads=num_CPU, allow_soft_placement=True,\
device_count = {'CPU' : num_CPU, 'GPU' : num_GPU})
session = tf.Session(config=config_TF)
tf.keras.backend.set_session(session)
global TR, dataarg, droprate
TR = 0.72
dataarg = 1
##AtlasName = 'MMP'
#adj_mat_type = 'SC' #'surface'
'''
pathdata = '/data/cisl/yuzhang/projects/HCP/'
###pathdata = '/home/yuzhang/scratch/HCP/'
pathout = pathdata + "temp_res_new2/"
#mmp_atlas = pathdata + "codes/HCP_S1200_GroupAvg_v1/"+"Q1-Q6_RelatedValidation210.CorticalAreas_dil_Final_Final_Areas_Group_Colors.32k_fs_LR.dlabel.nii"
#lmdb_filename = pathout+modality+"_MMP_ROI_act_1200R_test_Dec2018_ALL.lmdb"
#adj_mat_file = pathdata + 'codes/MMP_adjacency_mat_white.pconn.nii'
pathdata="/home/yuzhang/scratch/HCP/" ##aws_s3_HCP1200/FMRI/tfMRI_MOTOR_LR/
pathatlas=pathdata + "codes/HCP_S1200_GroupAvg_v1/"
pathout=pathdata+"temp_res_new2/"
#mmp_atlas = pathdata + "HCP_S1200_GroupAvg_v1/"+"Q1-Q6_RelatedValidation210.CorticalAreas_dil_Final_Final_Areas_Group_Colors.32k_fs_LR.dlabel.nii"
##lmdb_filename = pathout+modality+"_MMP_ROI_act_1200R_test_Dec2018_ALL.lmdb"
##adj_mat_file = pathout + 'MMP_adjacency_mat_white.pconn.nii'
'''
pathdata="/home/yu/PycharmProjects/HCP_data/" ##aws_s3_HCP1200/FMRI/tfMRI_MOTOR_LR/
pathatlas=pathdata + "HCP_S1200_GroupAvg_v1/"
pathout=pathdata+"temp_res_new2/"
##############################################
###################################################
def bulid_dict_task_modularity(modality):
###edited Jan 25th 2019: we need to use block design for fmri decoding when splitting trials into data samples
##build the dict for different subtypes of events under different modalities
motor_task_con = {"rf": "footR_mot",
"lf": "footL_mot",
"rh": "handR_mot",
"lh": "handL_mot",
"t": "tongue_mot"}
lang_task_ev = {"present_math": "pmath_lang",
#"question_math": "pmath_lang",
"response_math": "rmath_lang",
"present_story": "pstory_lang",
#"question_story": "pstory_lang" ,
"response_story": "rstory_lang"}
lang_task_con = {"math": "math_lang",
"story": "story_lang"}
emotion_task_con={"fear": "fear_emo",
"neut": "non_emo"}
gambl_task_ev = {"win_event": "win_gamb",
"loss_event": "loss_gamb",
"neut_event": "non_gamb"}
gambl_task_con = {"win": "win_gamb",
"loss": "loss_gamb"}
reson_task_con = {"match": "match_reson",
"relation": "relat_reson"}
social_task_con ={"mental": "mental_soc",
"rnd": "random_soc"}
wm_task_con = {"2bk_body": "body2b_wm",
"2bk_faces": "face2b_wm",
"2bk_places": "place2b_wm",
"2bk_tools": "tool2b_wm",
"0bk_body": "body0b_wm",
"0bk_faces": "face0b_wm",
"0bk_places": "place0b_wm",
"0bk_tools": "tool0b_wm"}
dicts = [motor_task_con, lang_task_con, emotion_task_con, reson_task_con, social_task_con, wm_task_con] ##gambl_task_con,
from collections import defaultdict
all_task_con = defaultdict(list) # uses set to avoid duplicates
for d in dicts:
for k, v in d.items():
#all_task_con[k].append(v) ## all_task_con[k]=v to remove the list []
all_task_con[k] = v
rwm_task_con = defaultdict(list)
for d in [wm_task_con, reson_task_con]:
for k, v in d.items():
rwm_task_con[k] = v
mod_chosen = modality[:3].lower().strip()
mod_choices = {'mot': 'MOTOR',
'lan': 'LANGUAGE',
'ela': 'LANGUAGE',
'emo': 'EMOTION',
'ega': 'GAMBLING',
'gam': 'GAMBLING',
'rel': 'RELATIONAL',
'soc': 'SOCIAL',
'wm': 'WM',
'rwm': 'RWM',
'all': 'ALLTasks'}
task_choices = {'mot': motor_task_con,
'lan': lang_task_con,
'ela': lang_task_ev,
'emo': emotion_task_con,
'gam': gambl_task_con,
'ega': gambl_task_ev,
'rel': reson_task_con,
'soc': social_task_con,
'wm': wm_task_con,
'rwm': rwm_task_con,
'all': all_task_con}
modality = mod_choices.get(mod_chosen, 'default')
task_contrasts = task_choices.get(mod_chosen, 'default')
return task_contrasts, modality
#####start collecting data for classification algorithm
def load_fmri_data(pathdata,modality=None,confound_name=None):
###fMRI decoding: using event signals instead of activation pattern from glm
##collect task-fMRI signals
if not modality:
modality = 'MOTOR' # 'MOTOR'
pathfmri = pathdata + 'aws_s3_HCP1200/FMRI/'
print("Loading fmri data from data folder:",pathfmri)
pathdata = Path(pathfmri)
subjects = []
fmri_files = []
confound_files = []
if modality == 'ALLTasks' or modality == 'RWM':
for fmri_file in sorted(pathdata.glob('tfMRI_*_??/*tfMRI_*_??_Atlas.dtseries.nii')):
subjects.append(Path(os.path.dirname(fmri_file)).parts[-3])
fmri_files.append(str(fmri_file))
for confound in sorted(pathdata.glob('tfMRI_*_??/*Movement_Regressors.txt')):
confound_files.append(str(confound))
else:
for fmri_file in sorted(pathdata.glob('tfMRI_'+modality+'_??/*tfMRI_'+modality+'_??_Atlas.dtseries.nii')):
subjects.append(Path(os.path.dirname(fmri_file)).parts[-3])
fmri_files.append(str(fmri_file))
for confound in sorted(pathdata.glob('tfMRI_'+modality+'_??/*Movement_Regressors.txt')):
confound_files.append(str(confound))
print('Included {} fmri data and {} confound files in the dataset!\n'.format(len(fmri_files),len(confound_files)))
return fmri_files, confound_files, subjects
def load_event_files(pathdata, modality, fmri_files, confound_files, ev_filename=None, flag_event=False):
###collect the event design files
confound = np.loadtxt(confound_files[0])
Subject_Num = len(confound_files)
Trial_Num = confound.shape[0]
pathfmri = pathdata + 'aws_s3_HCP1200/FMRI/'
pathdata = Path(pathfmri)
if modality == 'ALLTasks' or modality == 'RWM':
modality_str = '*'
else:
modality_str = modality
if flag_event:
modality_str2 = modality_str + '_event'
else:
modality_str2 = modality_str
EVS_files = []
subj = 0
'''
for ev, sub_count in zip(sorted(pathdata.glob('tfMRI_' + modality + '_??/*combined_events_spm_' + modality + '.csv')),range(Subject_Num)):
###remove fmri files if the event design is missing
while os.path.dirname(fmri_files[subj]) < os.path.dirname(str(ev)):
print("Event files and fmri data are miss-matching for subject: ")
print(Path(os.path.dirname(str(ev))).parts[-3::2], ':',
Path(os.path.dirname(fmri_files[subj])).parts[-3::2])
print("Due to missing event files for subject : %s" % os.path.dirname(fmri_files[subj]))
fmri_files[subj] = []
confound_files[subj] = []
subj += 1
if subj > Subject_Num:
break
if os.path.dirname(fmri_files[subj]) == os.path.dirname(str(ev)):
EVS_files.append(str(ev))
subj += 1
'''
###adjust the code after changing to the new folder
for ev in sorted(pathdata.glob('tfMRI_' + modality_str + '_??/*combined_events_spm_' + modality_str2 + '.csv')):
###remove fmri files if the event design is missing
##not including the event design, use block design instead
if not flag_event and 'event' in os.path.basename(str(ev)).split('_')[-1]: continue;
while os.path.basename(confound_files[subj]).split('_')[0] < os.path.basename(str(ev)).split('_')[0]:
print("Event files and fmri data are miss-matching for subject: ")
print(os.path.basename(str(ev)).split('_')[0], ':', os.path.basename(confound_files[subj]).split('_')[0])
print("Due to missing event files for subject : %s_%s" % (Path(os.path.dirname(confound_files[subj])).parts[-1], os.path.basename(confound_files[subj]).split('_')[0]))
##fmri_files[subj] = []
confound_files[subj] = []
subj += 1
if subj > Subject_Num:
break
if os.path.basename(confound_files[subj]).split('_')[0] == os.path.basename(str(ev)).split('_')[0]:
EVS_files.append(str(ev))
subj += 1
fmri_files = list(filter(None, fmri_files))
confound_files = list(filter(None, confound_files))
if len(EVS_files) != len(confound_files):
print('Miss-matching number of subjects between event:{} and fmri:{} files'.format(len(EVS_files), len(confound_files)))
print("Data samples including {} subjects with {} trials for event design. \n".format(len(EVS_files),Trial_Num))
################################
###loading all event designs
if not ev_filename:
ev_filename = "_event_labels_1200R_LR_RL_new2.txt"
if flag_event:
print("Using event design files for task: ", modality)
ev_filename = ev_filename.replace('.h5', '_event.h5')
events_all_subjects_file = pathout+modality+ev_filename
if os.path.isfile(events_all_subjects_file):
trial_infos = pd.read_csv(EVS_files[0],sep="\t",encoding="utf8",header = None,names=['onset','duration','rep','task'])
Duras = np.ceil((trial_infos.duration/TR)).astype(int) #(trial_infos.duration/TR).astype(int)
print('Collecting trial info from file:', events_all_subjects_file)
subjects_trial_labels = pd.read_csv(events_all_subjects_file,sep="\t",encoding="utf8")
print(subjects_trial_labels.keys())
try:
label_matrix = subjects_trial_labels['label_data'].values
# print(label_matrix[0],label_matrix[1])
# xx = label_matrix[0].split(",")
subjects_trial_label_matrix = []
for subi in range(len(label_matrix)):
xx = [x.replace("['", "").replace("']", "") for x in label_matrix[subi].split("', '")]
subjects_trial_label_matrix.append(xx)
subjects_trial_label_matrix = pd.DataFrame(data=(subjects_trial_label_matrix))
except:
print('only extracting {} trials from event design'.format(Trial_Num))
subjects_trial_label_matrix = subjects_trial_labels.loc[:, 'trial1':'trial' + str(Trial_Num)]
#subjects_trial_label_matrix = subjects_trial_labels.values.tolist()
trialID = subjects_trial_labels['trialID']
sub_name = subjects_trial_labels['subject'].tolist()
coding_direct = subjects_trial_labels['coding']
print(np.array(subjects_trial_label_matrix).shape,len(sub_name),len(np.unique(sub_name)),len(coding_direct))
else:
print('Loading trial info for each task-fmri file and save to csv file:', events_all_subjects_file)
subjects_trial_label_matrix = []
sub_name = []
coding_direct = []
modality_pre = ''
for subj in np.arange(len(EVS_files)):
pathsub = Path(os.path.dirname(EVS_files[subj]))
#Trial_Num = nib.load(fmri_files[subj]).shape[-1]
Trial_Num = np.loadtxt(confound_files[subj]).shape[0]
if os.path.basename(pathsub) != modality_pre:
print("Start analysizing event data for modality {} ".format(os.path.basename(pathsub)))
modality_pre = os.path.basename(pathsub)
#sub_name.append(pathsub.parts[-3])
###adjust the code after changing to the new folder
sub_name.append(str(os.path.basename(EVS_files[subj]).split('_')[0]))
coding_direct.append(pathsub.parts[-1].replace('tfMRI_',''))
##trial info in volume
trial_infos = pd.read_csv(EVS_files[subj],sep="\t",encoding="utf8",header = None,names=['onset','duration','rep','task'])
Onsets = np.array((trial_infos.onset/TR).astype(int)-1) #(trial_infos.onset/TR).astype(int)
Duras = np.array((trial_infos.duration/TR).astype(int)) #(trial_infos.duration/TR).astype(int)
Movetypes = list(trial_infos.task)
move_mask = pd.Series(Movetypes).isin(task_contrasts.keys())
Onsets = Onsets[move_mask]
Duras = Duras[move_mask]
Movetypes = [Movetypes[i] for i in range(len(move_mask)) if move_mask[i]]
event_len = Onsets[-1] + Duras[-1] + 1 ###start with 0
while event_len > Trial_Num:
'''
##del Onsets[-1]; del Duras[-1]; del Movetypes[-1]
print('Cutting {} event design due to incomplete scanning...short of {} volumes out of {}'.format(os.path.basename(pathsub),event_len-Trial_Num,Trial_Num))
try:
Duras[-1] -= (event_len-Trial_Num)
except:
print(Duras,event_len,Trial_Num)
event_len -= (event_len-Trial_Num)
if Duras[-1] <= 0:
'''
#print('Remove last trials due to incomplete scanning...short of {} volumes out of {}'.format(event_len - Trial_Num, Trial_Num))
Onsets=Onsets[:-1]; Duras=Duras[:-1]; del Movetypes[-1]
event_len = Onsets[-1] + Duras[-1] + 1
labels = ["rest"]*Trial_Num;
trialID = [0] * Trial_Num;
tid = 1
for start,dur,move in zip(Onsets,Duras,Movetypes):
for ti in range(start-1,start+dur):
try:
labels[ti]= task_contrasts[move]
trialID[ti] = tid
except:
print('Error loading for event file {}'.format(EVS_files[subj]))
print('Run in to #{} volume when having total {} volumes'.format(ti,Trial_Num))
print(Onsets, Duras, Movetypes, move)
tid += 1
subjects_trial_label_matrix.append(labels)
##subjects_trial_label_matrix = np.array(subjects_trial_label_matrix)
print(np.array(subjects_trial_label_matrix).shape)
sub_name = list(map("_".join, zip(sub_name,coding_direct)))
#print(np.array(subjects_trial_label_matrix[0]))
try:
subjects_trial_labels = pd.DataFrame(data=np.array(subjects_trial_label_matrix),columns=['label_data'])
except:
subjects_trial_labels = pd.DataFrame(data=np.array(subjects_trial_label_matrix), columns=['trial' + str(i + 1) for i in range(Trial_Num)])
subjects_trial_labels['trialID'] = tid-1
subjects_trial_labels['subject'] = sub_name
subjects_trial_labels['coding'] = coding_direct
subjects_trial_labels.keys()
#print(subjects_trial_labels['subject'],subjects_trial_labels['coding'])
##save the labels
subjects_trial_labels.to_csv(events_all_subjects_file,sep='\t', encoding='utf-8',index=False)
block_dura = np.unique(Duras)[0]
return subjects_trial_label_matrix, sub_name, block_dura
def load_fmri_data_from_lmdb(lmdb_filename):
##lmdb_filename = pathout + modality + "_MMP_ROI_act_1200R_test_Dec2018_ALL.lmdb"
## read lmdb matrix
print('loading data from file: %s' % lmdb_filename)
matrix_dict = []
fmri_sub_name = []
if not os.path.isfile(lmdb_filename) and modality == 'ALLTasks':
print("Loading fMRI data from all tasks and merge into one lmdb file:", lmdb_filename)
lmdb_env = lmdb.open(lmdb_filename, subdir=False,readonly=False, map_size=int(1e12) * 2, meminit=False, map_async=True)
write_frequency = 100
pathout = Path(os.path.dirname(lmdb_filename))
for lmdb_mod in sorted(pathout.glob(os.path.basename(lmdb_filename).replace(modality,'*'))):
mod_name = os.path.basename(lmdb_mod).split('_')[0]
if mod_name == 'ALLTasks': continue
print('Loading data for modality',mod_name)
lmdb_txn = lmdb_env.begin(write=True)
lmdb_mod_env = lmdb.open(str(lmdb_mod), subdir=False, readonly=True)
with lmdb_mod_env.begin() as lmdb_mod_txn:
mod_cursor = lmdb_mod_txn.cursor()
for idx,(key, value) in enumerate(mod_cursor):
lmdb_txn.put(key, value)
if (idx + 1) % write_frequency == 0:
lmdb_txn.commit()
lmdb_txn = lmdb_env.begin(write=True)
lmdb_txn.commit()
lmdb_mod_env.close()
lmdb_env.sync()
lmdb_env.close()
##########################################33
lmdb_env = lmdb.open(lmdb_filename, subdir=False)
try:
lmdb_txn = lmdb_env.begin()
listed_fmri_files = loads(lmdb_txn.get(b'__keys__'))
listed_fmri_files = [l.decode("utf-8") for l in listed_fmri_files]
print('Stored fmri data from files:')
print(len(listed_fmri_files))
except:
print('Search each key for every fmri file...')
with lmdb_env.begin() as lmdb_txn:
cursor = lmdb_txn.cursor()
for key, value in cursor:
# print(key)
if key == b'__keys__':
continue
pathsub = Path(os.path.dirname(key.decode("utf-8")))
##subname_info = os.path.basename(key.decode("utf-8")).split('_')
##fmri_sub_name.append('_'.join((subname_info[0], subname_info[2], subname_info[3])))
#############change due to directory switch to projects
subname_info = str(Path(os.path.dirname(key.decode("utf-8"))).parts[-3])
fmri_sub_name.append(Path(os.path.dirname(key.decode("utf-8"))).parts[-1].replace('tfMRI',subname_info))
data = loads(lmdb_txn.get(key)).astype('float32', casting='same_kind')
matrix_dict.append(np.array(data))
lmdb_env.close()
return matrix_dict, fmri_sub_name
def load_rsfmri_data_matrix(lmdb_filename,Trial_Num=1200):
import lmdb
from tensorpack.utils.serialize import dumps, loads
## read lmdb matrix
print('loading data from file: %s' % lmdb_filename)
matrix_dict = []
fmri_sub_name = []
lmdb_env = lmdb.open(lmdb_filename, subdir=False)
try:
lmdb_txn = lmdb_env.begin()
listed_fmri_files = loads(lmdb_txn.get(b'__keys__'))
listed_fmri_files = [l.decode("utf-8") for l in listed_fmri_files]
print('Stored fmri data from files:')
print(len(listed_fmri_files))
except:
print('Search each key for every fmri file...')
with lmdb_env.begin() as lmdb_txn:
cursor = lmdb_txn.cursor()
for key, value in cursor:
# print(key)
if key == b'__keys__':
continue
pathsub = Path(os.path.dirname(key.decode("utf-8")))
if any('REST' in string for string in lmdb_filename.split('_')):
fmri_sub_name.append(pathsub.parts[-3] + '_' + pathsub.parts[-1].split('_')[-2][-1] + '_' + pathsub.parts[-1].split('_')[-1])
else:
fmri_sub_name.append(pathsub.parts[-3] + '_' + pathsub.parts[-1].split('_')[-1])
data = loads(lmdb_txn.get(key))
if any('REST' in string for string in lmdb_filename.split('_')):
if data is None or data.shape[-1] != Trial_Num:
print('fmri data shape mis-matching between subjects...')
print('Check subject: %s with only %d Trials \n' % (fmri_sub_name[-1], data.shape[0]))
del fmri_sub_name[-1]
else:
#print(np.array(data).shape)
matrix_dict.append(np.array(data))
else:
print('wrong located')
matrix_dict.append(np.array(data))
lmdb_env.close()
print(np.array(matrix_dict).shape)
return matrix_dict, fmri_sub_name
def preclean_data_for_shape_match_new(subjects_tc_matrix,subjects_trial_label_matrix, fmri_sub_name, ev_sub_name):
print("Pre-clean the fmri and event data to make sure the matching shapes between two arrays!")
Subject_Num = np.array(subjects_tc_matrix).shape[0]
Trial_Num, Region_Num = subjects_tc_matrix[0].shape
#####################sort list of files
print('Sort both fmri and event files into the same order!')
fmrifile_index, fmri_sub_name_sorted = zip(*sorted(enumerate(fmri_sub_name), key=itemgetter(1)))
subjects_tc_matrix_sorted = [subjects_tc_matrix[ind] for ind in fmrifile_index]
ev_index, ev_sub_name_sorted = zip(*sorted(enumerate(ev_sub_name), key=itemgetter(1)))
subjects_trial_label_matrix_sorted = [list(filter(None, subjects_trial_label_matrix.iloc[ind])) for ind in ev_index]
fmri_sub_name_sorted = list(fmri_sub_name_sorted)
ev_sub_name_sorted = list(ev_sub_name_sorted)
####check matching of filenames
for ev, subcount in zip(ev_sub_name_sorted, range(len(ev_sub_name_sorted))):
evfile_mask = pd.Series(ev).isin(fmri_sub_name_sorted)
if not evfile_mask[0]:
print("Remove event file: {} from the list!!".format(ev))
del subjects_trial_label_matrix_sorted[subcount]
ev_sub_name_sorted.remove(ev)
for fmri_file, subcount in zip(fmri_sub_name_sorted, range(len(fmri_sub_name_sorted))):
fmrifile_mask = pd.Series(fmri_file).isin(ev_sub_name_sorted)
if not fmrifile_mask[0]:
print("Remove fmri file: {} from the list!!".format(fmri_file))
del subjects_tc_matrix_sorted[subcount]
fmri_sub_name_sorted.remove(fmri_file)
print('New shapes of fmri-data-matrix and trial-label-matrix after matching!')
print(np.array(subjects_tc_matrix_sorted).shape, np.array(subjects_trial_label_matrix_sorted).shape)
if len(fmri_sub_name_sorted) != len(ev_sub_name_sorted):
print('Warning: Mis-matching subjects list between fmri-data-matrix and trial-label-matrix')
print(np.array(subjects_tc_matrix_sorted).shape, np.array(subjects_trial_label_matrix_sorted).shape)
###########matching each evfile in fmri data
subjects_tc_matrix_new = []
fmri_sub_name_new = []
for ev in ev_sub_name_sorted:
###remove fmri files if the event design is missing
fmrifile_mask = pd.Series(fmri_sub_name_sorted).isin([ev])
if np.sum(fmrifile_mask):
subjects_tc_matrix_new.append(subjects_tc_matrix_sorted[np.where(fmrifile_mask)[0][0]])
fmri_sub_name_new.append(fmri_sub_name_sorted[np.where(fmrifile_mask)[0][0]])
fmri_sub_name = fmri_sub_name_new
subjects_tc_matrix = np.array(subjects_tc_matrix_new)
###########matching each fmri file in event data
subjects_trial_label_matrix_new = []
ev_sub_name_new = []
for fmri_file in fmri_sub_name_sorted:
###remove fmri files if the event design is missing
evfile_mask = pd.Series(ev_sub_name_sorted).isin([fmri_file])
if np.sum(evfile_mask):
subjects_trial_label_matrix_new.append(subjects_trial_label_matrix_sorted[np.where(evfile_mask)[0][0]])
ev_sub_name_new.append(ev_sub_name_sorted[np.where(evfile_mask)[0][0]])
ev_sub_name = ev_sub_name_new
subjects_trial_label_matrix = np.array(subjects_trial_label_matrix_new)
else:
ev_sub_name = ev_sub_name_sorted
subjects_trial_label_matrix = subjects_trial_label_matrix_sorted
fmri_sub_name = fmri_sub_name_sorted
subjects_tc_matrix = np.array(subjects_tc_matrix_sorted)
for subj in range(min(len(fmri_sub_name), len(ev_sub_name))):
try:
tsize, rsize = np.array(subjects_tc_matrix[subj]).shape
tsize2 = len(list(filter(None, subjects_trial_label_matrix[subj])))
except:
print(subj == Subject_Num - 1)
print('The end of SubjectList...\n')
if tsize != tsize2:
'''
if tsize2 > Trial_Num:
##print('Cut event data for subject %s from %d to fit event label matrix' % (fmri_sub_name[subj],tsize2))
subjects_trial_label_matrix[subj][tsize:] = []
'''
print('Remove fmri_subject: {} and event subject {} due to different trial num: {} / {}'.format(fmri_sub_name[subj],ev_sub_name[subj],tsize,tsize2))
del fmri_sub_name[subj]
del ev_sub_name[subj]
del subjects_tc_matrix[subj]
del subjects_trial_label_matrix[subj]
if rsize != Region_Num:
print('Remove fmri_subject: {} and event subject {} due to different region num: {}/{}'.format(fmri_sub_name[subj], ev_sub_name[subj],rsize,Region_Num))
del fmri_sub_name[subj]
del ev_sub_name[subj]
del subjects_tc_matrix[subj]
del subjects_trial_label_matrix[subj]
print('Done matching data shapes:', np.array(subjects_tc_matrix).shape, np.array(subjects_trial_label_matrix).shape)
return subjects_tc_matrix, subjects_trial_label_matrix, fmri_sub_name
def preclean_data_for_shape_match(subjects_tc_matrix,subjects_trial_label_matrix, fmri_sub_name, ev_sub_name):
print("Pre-clean the fmri and event data to make sure the matching shapes between two arrays!")
Subject_Num = np.array(subjects_tc_matrix).shape[0]
Trial_Num, Region_Num = subjects_tc_matrix[0].shape
if len(fmri_sub_name) != len(ev_sub_name):
print('Warning: Mis-matching subjects list between fmri-data-matrix and trial-label-matrix')
print(np.array(subjects_tc_matrix).shape, np.array(subjects_trial_label_matrix).shape)
subj = 0
if len(fmri_sub_name) > len(ev_sub_name):
for ev, subcount in zip(ev_sub_name, range(Subject_Num)):
###remove fmri files if the event design is missing
while fmri_sub_name[subj].split('_')[0] < str(ev).split('_')[0]:
print("Event files and fmri data are miss-matching for subject: ")
print(ev, ':', fmri_sub_name[subj])
print("Due to missing event files for subject : %s" % fmri_sub_name[subj])
del fmri_sub_name[subj]
del subjects_tc_matrix[subj]
subj += 1
else:
if subj > Subject_Num:
ev_sub_name.remove(ev)
del subjects_trial_label_matrix[subcount]
subj = subcount
if fmri_sub_name[subj] == str(ev): subj += 1
subjects_tc_matrix[subj:] = []
fmri_sub_name[subj:] = []
elif len(fmri_sub_name) < len(ev_sub_name):
for fmri_file, subcount in zip(fmri_sub_name, range(len(ev_sub_name))):
###remove fmri files if the event design is missing
while str(ev_sub_name[subj]).split('_')[0] < fmri_file.split('_')[0]:
print("Event files and fmri data are miss-matching for subject: ")
print(ev_sub_name[subj], ':', fmri_file)
print("Due to missing fmri data for subject : %s" % str(ev_sub_name[subj]))
del ev_sub_name[subj]
del subjects_trial_label_matrix[subj]
subj += 1
else:
if subj > len(ev_sub_name):
fmri_sub_name.remove(fmri_file)
del subjects_tc_matrix[subcount]
subj = subcount
if str(ev_sub_name[subj]) == fmri_file: subj += 1
subjects_trial_label_matrix[subj:] = []
ev_sub_name[subj:] = []
for subj in range(min(len(fmri_sub_name), len(ev_sub_name))):
try:
tsize, rsize = np.array(subjects_tc_matrix[subj]).shape
tsize2 = len(subjects_trial_label_matrix[subj])
except:
print(subj == Subject_Num - 1)
print('The end of SubjectList...\n')
if tsize != tsize2:
'''
if tsize2 > Trial_Num:
##print('Cut event data for subject %s from %d to fit event label matrix' % (fmri_sub_name[subj],tsize2))
subjects_trial_label_matrix[subj][tsize:] = []
'''
print('Remove fmri_subject: {} and event subject{} due to different trial num: {} / {}'.format(fmri_sub_name[subj],ev_sub_name[subj],tsize,tsize2))
del subjects_tc_matrix[subj]
del subjects_trial_label_matrix[subj]
if rsize != Region_Num:
print('Remove subject: %s due to different region num: %d in the fmri data' % (fmri_sub_name[subj], rsize))
del subjects_tc_matrix[subj]
del subjects_trial_label_matrix[subj]
print('Done matching data shapes:', np.array(subjects_tc_matrix).shape, np.array(subjects_trial_label_matrix).shape)
return subjects_tc_matrix, subjects_trial_label_matrix
#####################################
###standard scaler for nd array instead of 2d matrix
from sklearn.base import TransformerMixin
class NDStandardScaler(TransformerMixin):
def __init__(self, **kwargs):
self._scaler = preprocessing.StandardScaler(copy=True, **kwargs)
self._orig_shape = None
def fit(self, X, **kwargs):
X = np.array(X)
# Save the original shape to reshape the flattened X later
# back to its original shape
if len(X.shape) > 1:
self._orig_shape = X.shape[1:]
X = self._flatten(X)
self._scaler.fit(X, **kwargs)
return self
def transform(self, X, **kwargs):
X = np.array(X)
X = self._flatten(X)
X = self._scaler.transform(X, **kwargs)
X = self._reshape(X)
return X
def _flatten(self, X):
# Reshape X to <= 2 dimensions
if len(X.shape) > 2:
n_dims = np.prod(self._orig_shape)
X = X.reshape(-1, n_dims)
return X
def _reshape(self, X):
# Reshape X back to it's original shape
if len(X.shape) >= 2:
X = X.reshape(-1, *self._orig_shape)
return X
def edges(window):
"""Splits a window into start and end indices. Will default to have the
larger padding at the end in case of an odd window.
"""
start = window // 2
end = window - start
return (start, end)
def fast_pad_symmetric(values, window, dtype='f8'):
"""A fast version of numpy n-dimensional symmetric pad.
In contrast to np.pad, this algorithm only allocates memory once, regardless
of the number of axes padded. Performance for large data sets is vastly
improved.
Note: if the requested padding is 0 along all axes, then this algorithm
returns the original input ndarray.
Author: Stian Lode [email protected]
Args:
values: n-dimensional ndarray
window: an iterable of length n
return:
a numpy ndarray containing the values with each axis padded according
to the specified window. The padding is a reflection of the data in
the input values.
"""
assert len(values.shape) == len(window)
if (window <= 0).all():
return values
start, end = edges(window)
new = np.empty(values.shape + window, dtype=dtype)
slice_stack = []
for a, b in zip(start, end):
slice_stack.append(slice(a, None if b == 0 else -b))
new[tuple(slice_stack)] = values
slice_stack = []
for a, b in zip(start, end):
if a > 0:
s_to, s_from = slice(a - 1, None, -1), slice(a, 2 * a, None)
new[tuple(slice_stack + [s_to])] = new[tuple(slice_stack + [s_from])]
if b > 0:
e_to, e_from = slice(-1, -b - 1, -1), slice(-2 * b, -b)
new[tuple(slice_stack + [e_to])] = new[tuple(slice_stack + [e_from])]
slice_stack.append(slice(None))
return new
##############################
def subject_cross_validation_split_trials(tc_matrix, label_matrix,target_name, sub_num=None, block_dura=18, n_folds=10, testsize=0.2, valsize=0.1,randomseed=1234):
##randomseed=1234;testsize = 0.2;n_folds=10;valsize=0.1
from sklearn import preprocessing
from sklearn.model_selection import cross_val_score, train_test_split,ShuffleSplit
Subject_Num, Trial_Num, Region_Num = np.array(tc_matrix).shape
rs = np.random.RandomState(randomseed)
if not sub_num or sub_num>Subject_Num:
sub_num = Subject_Num
if not block_dura:
block_dura = 18 ###12s block for MOTOR task
fmri_data_matrix = []
label_data_matrix = []
for subi in range(Subject_Num):
label_trial_data = np.array(label_matrix[subi])
condition_mask = pd.Series(label_trial_data).isin(target_name)
##condition_mask = pd.Series(label_trial_data).str.split('_', expand=True)[0].isin(target_name)
fmri_data_matrix.append(tc_matrix[subi][condition_mask, :])
label_data_matrix.append(label_trial_data[condition_mask])
fmri_data_matrix = np.array(fmri_data_matrix).astype('float32', casting='same_kind')
label_data_matrix = np.array(label_data_matrix)
##cut the trials into blocks
chunks = int(np.floor(label_data_matrix.shape[-1] / block_dura))
fmri_data_block = np.array(np.array_split(fmri_data_matrix, chunks, axis=1)).mean(axis=2).astype('float32',casting='same_kind')
label_data_block = np.array(np.array_split(label_data_matrix, chunks, axis=1))[:, :, 0]
print(fmri_data_block.shape,label_data_block.shape)
train_sid_tmp, test_sid = train_test_split(range(sub_num), test_size=testsize, random_state=rs, shuffle=True)
fmri_data_train = np.array([fmri_data_block[:, i, :] for i in train_sid_tmp]).astype('float32', casting='same_kind')
fmri_data_test = np.array([fmri_data_block[:, i, :] for i in test_sid]).astype('float32', casting='same_kind')
# print(fmri_data_train.shape,fmri_data_test.shape)
label_data_train = np.array([label_data_block[:, i] for i in train_sid_tmp])
label_data_test = np.array([label_data_block[:, i] for i in test_sid])
# print(label_data_train.shape,label_data_test.shape)
###transform the data
scaler = preprocessing.StandardScaler().fit(np.vstack(fmri_data_train))
##fmri_data_train = scaler.transform(fmri_data_train)
X_test = scaler.transform(np.vstack(fmri_data_test))
nb_class = len(np.unique(label_data_block))
Y_test = label_data_test.ravel()
# print(X_test.shape,Y_test.shape)
from sklearn.model_selection import ShuffleSplit
valsplit = ShuffleSplit(n_splits=n_folds, test_size=valsize, random_state=rs)
X_train_scaled = []
X_val_scaled = []
Y_train_scaled = []
Y_val_scaled = []
for train_sid, val_sid in valsplit.split(train_sid_tmp):
##preprocess features and labels
X = np.array(np.vstack([fmri_data_train[i, :, :] for i in train_sid]))
Y = np.array([label_data_train[i, :] for i in train_sid]).ravel()
# print(X.shape, Y.shape)
X_train_scaled.append(scaler.transform(X))
Y_train_scaled.append(Y)
X = np.array(np.vstack([fmri_data_train[i, :, :] for i in val_sid]))
Y = np.array([label_data_train[i, :] for i in val_sid]).ravel()
# print(X.shape, Y.shape)
X_val_scaled.append(scaler.transform(X))
Y_val_scaled.append(Y)
print('Samples of Subjects for training: %d and testing %d and validating %d with %d classes' % (len(train_sid), len(test_sid), len(val_sid), nb_class))
return X_train_scaled, Y_train_scaled, X_val_scaled, Y_val_scaled, X_test, Y_test
def subject_cross_validation_split_trials_new(tc_matrix, label_matrix, target_name, sub_num=None, block_dura=18, flag_event=0,
n_folds=10, train_dataarg=2, testsize=0.2, valsize=0.1, randomseed=1234):
##randomseed=1234;testsize = 0.2;n_folds=10;valsize=0.1
from sklearn import preprocessing
from sklearn.model_selection import cross_val_score, train_test_split, ShuffleSplit
Subject_Num = np.array(tc_matrix).shape[0]
##Trial_Num, Region_Num = np.array(tc_matrix[0]).shape
rs = np.random.RandomState(randomseed)
if not sub_num or sub_num > Subject_Num:
sub_num = Subject_Num
if not block_dura:
block_dura = 18 ###12s block for MOTOR task
if not train_dataarg:
train_dataarg = 1
train_dataarg = min(train_dataarg, block_dura)
fmri_data_matrix = []
label_data_matrix = []
Trial_dura_pre = 0
for subi in range(Subject_Num):
label_trial_data = np.array(label_matrix[subi])
condition_mask = pd.Series(label_trial_data).isin(target_name)
##condition_mask = pd.Series(label_trial_data).str.split('_', expand=True)[0].isin(target_name)
tc_matrix_select = np.array(tc_matrix[subi][condition_mask, :])
label_data_select = np.array(label_trial_data[condition_mask])
##print(tc_matrix_select.shape,label_data_select.shape)
le = preprocessing.LabelEncoder()
le.fit(target_name)
label_data_int = le.transform(label_data_select)
##cut the trials
label_data_trial_block = np.array(np.split(label_data_select, np.where(np.diff(label_data_int))[0] + 1))
fmri_data_block = np.array_split(tc_matrix_select, np.where(np.diff(label_data_int))[0] + 1, axis=0)
trial_duras = [label_data_trial_block[ii].shape[0] for ii in range(label_data_trial_block.shape[0]-1)]
if len(np.unique(trial_duras))>1 and not flag_event: print("Warning: Using a event design for task ",modality)
if trial_duras[-1] < block_dura: trial_duras = trial_duras[:-1]
Trial_dura = min(trial_duras)
if Trial_dura < 5 and not flag_event:
print('Warning: Only extract {} TRs for each trial. You need to recheck the event design to make sure!'.format(Trial_dura))
else:
if Trial_dura != Trial_dura_pre:
#print('each trial contains %d volumes/TRs for task %s' % (Trial_dura, modality))
Trial_dura_pre = Trial_dura
chunks = int(np.floor(len(label_data_select) / Trial_dura))
if subi == 1:
ulabel = [np.unique(x) for x in label_data_trial_block]
print("After cutting: unique values for each block of trials %s with %d blocks" % (np.array(ulabel), len(ulabel)))
if label_data_trial_block.shape[0] != chunks:
try:
label_data_trial_block = np.array(np.split(label_data_select, chunks))
fmri_data_block = np.array_split(tc_matrix_select, chunks, axis=0)
except:
print("\nWrong cutting of event data...")
print("Should have %d block-trials but only found %d cuts" % (chunks, label_data_trial_block.shape[0]))
ulabel = [np.unique(x) for x in label_data_trial_block]
print("Adjust the cutting: unique values for each block of trials %s with %d blocks\n" % (np.array(ulabel), len(ulabel)))
chunks = len(trial_duras)
label_data_trial_block = np.array([label_data_trial_block[i][:Trial_dura] for i in range(chunks)])
fmri_data_block = np.array([fmri_data_block[i][:Trial_dura, :] for i in range(chunks)])
if subi == 1: print('first cut:', fmri_data_block.shape, label_data_trial_block.shape)
#######adjust to event design ??
##cut each trial to blocks
block_dura_used = min(Trial_dura, block_dura)
chunks = int(np.floor(Trial_dura / block_dura_used))
if Trial_dura % block_dura_used:
trial_num_used = Trial_dura // block_dura_used * block_dura_used
fmri_data_block = np.array(np.vstack(np.array_split(fmri_data_block[:,:trial_num_used,:], chunks, axis=1))).transpose(0,2,1).astype('float32', casting='same_kind')
label_data_trial_block = np.array(np.vstack(np.array_split(label_data_trial_block[:,:trial_num_used], chunks, axis=1)))[:,0]
else:
fmri_data_block = np.array(np.vstack(np.array_split(fmri_data_block, chunks, axis=1))).transpose(0,2,1).astype('float32', casting='same_kind')
label_data_trial_block = np.array(np.vstack(np.array_split(label_data_trial_block, chunks, axis=1)))[:, 0]
if subi == 1: print('second cut:', fmri_data_block.shape, label_data_trial_block.shape)
##label_data_test = le.transform(label_data_trial_block[:,0]).flatten()
if subi == 1: print('finalize: reshape data into size:', fmri_data_block.shape, label_data_trial_block.shape)
fmri_data_matrix.append(fmri_data_block)
label_data_matrix.append(label_data_trial_block)
fmri_data_matrix = np.array(fmri_data_matrix) ##.astype('float32', casting='same_kind')
label_data_matrix = np.array(label_data_matrix)
print(fmri_data_matrix.shape, label_data_matrix.shape)
########spliting into train,val and testing
train_sid_tmp, test_sid = train_test_split(range(sub_num), test_size=testsize, random_state=rs, shuffle=True)
if len(train_sid_tmp)<2 or len(test_sid)<2:
print("Only %d subjects avaliable. Use all subjects for training and testing" % (sub_num))
train_sid_tmp = range(sub_num)
test_sid = range(sub_num)
fmri_data_train = np.array([fmri_data_matrix[i] for i in train_sid_tmp]) ##.astype('float32', casting='same_kind')
fmri_data_test = np.array([fmri_data_matrix[i] for i in test_sid]) ##.astype('float32', casting='same_kind')
print('fmri data for train and test:', fmri_data_train.shape, fmri_data_test.shape)
label_data_train = np.array([label_data_matrix[i] for i in train_sid_tmp])
label_data_test = np.array(np.block([label_data_matrix[i] for i in test_sid]))
print('label data for train and test', label_data_train.shape, label_data_test.shape)
###transform the data
scaler = NDStandardScaler().fit(np.vstack(fmri_data_train))
##scaler = preprocessing.StandardScaler().fit(np.vstack(fmri_data_train))
##fmri_data_train = scaler.transform(fmri_data_train)
X_test = scaler.transform(np.vstack(fmri_data_test)) ###.astype('float32', casting='same_kind')
nb_class = len(target_name)
Y_test = le.transform(label_data_test) ##.astype('uint8')
##print(X_test.shape,Y_test.shape)
from sklearn.model_selection import ShuffleSplit
valsplit = ShuffleSplit(n_splits=n_folds, test_size=valsize, random_state=rs)
X_train_scaled = []
X_val_scaled = []
Y_train_scaled = []
Y_val_scaled = []
for train_sid, val_sid in valsplit.split(train_sid_tmp):
##preprocess features and labels
X = np.array(np.vstack([fmri_data_train[i] for i in train_sid])) ##using vstack or hstack
Y = np.array(np.block([label_data_train[i] for i in train_sid])) ##check whether data and label corresponding
if train_dataarg > 1 and block_dura_used > 1:
Y = np.repeat(Y, train_dataarg, axis=0).ravel()
X_new = []
time_window = np.empty(len(X.shape)).astype(int)
time_window[-1] = block_dura_used * 2
for xi in range(X.shape[0]):
xx = np.array(X[np.random.choice(range(X.shape[0]), size=train_dataarg, replace=True), :, :])
rand_timeslice = np.random.randint(block_dura_used) ##range(block_dura_used)
##xx_wrap = xx.take(range(rand_timeslice,rand_timeslice+block_dura_used), axis=-1, mode='wrap')
xx_wrap = fast_pad_symmetric(xx, time_window)[:,:,rand_timeslice+block_dura_used:rand_timeslice+2*block_dura_used]
X_new.append(xx_wrap)
X = X_new
X_new = []
# print('fmri and label data for training:',X.shape, Y.shape)
X_train_scaled.append(scaler.transform(X)) ##.astype('float32', casting='same_kind')
Y_train_scaled.append(le.transform(Y))
X = np.array(np.vstack([fmri_data_train[i] for i in val_sid]))
Y = np.array(np.block([label_data_train[i] for i in val_sid]))
# print('fmri and label data for validation:',X.shape, Y.shape)
X_val_scaled.append(scaler.transform(X))
Y_val_scaled.append(le.transform(Y))
print('Samples of Subjects for training: %d and testing %d and validating %d with %d classes' % (
len(train_sid), len(test_sid), len(val_sid), nb_class))
return X_train_scaled, Y_train_scaled, X_val_scaled, Y_val_scaled, X_test, Y_test
def subject_cross_validation_split_trials_eventcut(tc_matrix, label_matrix, target_name, sub_num=None, start_trial=0, hrf_delay=0,
block_dura=1, sampling=0,flag_event=0,TRstep=1,sub_name=None,
n_folds=10, train_dataarg=2, testsize=0.2, valsize=0.1, randomseed=123):
##randomseed=1234;testsize = 0.2;n_folds=10;valsize=0.1
from sklearn import preprocessing
from sklearn.model_selection import cross_val_score, train_test_split, ShuffleSplit
Subject_Num = np.array(tc_matrix).shape[0]
##Trial_Num, Region_Num = np.array(tc_matrix[0]).shape
rs = np.random.RandomState(randomseed)
if not sub_num or sub_num > Subject_Num:
sub_num = Subject_Num
if not block_dura:
block_dura = 1 ###12s block for MOTOR task
if not train_dataarg:
train_dataarg = 1
train_dataarg = min(train_dataarg, block_dura)
global Trial_dura
fmri_data_matrix = []
label_data_matrix = []
Trial_dura_pre = 0
for subi in range(Subject_Num):
label_trial_data = np.array(label_matrix[subi])
if hrf_delay > 0:
label_trial_data = np.roll(label_trial_data, -hrf_delay)
condition_mask = pd.Series(label_trial_data).isin(target_name)
if start_trial != 0 or hrf_delay > 0:
###set the start point of each trial to extract data
label_trial_data_shift = np.roll(label_trial_data, start_trial)
condition_mask_shift = pd.Series(label_trial_data_shift).isin(target_name)
if start_trial < 0: