-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcichy_data.py
More file actions
1968 lines (1531 loc) · 67.7 KB
/
cichy_data.py
File metadata and controls
1968 lines (1531 loc) · 67.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import torch
import random
import pickle
import mne
import dill
import math
import traceback
import numpy as np
import faiss
from sklearn.cluster import KMeans
from scipy.ndimage import gaussian_filter1d
from scipy.io import loadmat, savemat
from sklearn.preprocessing import StandardScaler, RobustScaler, MaxAbsScaler
from sklearn.decomposition import PCA
from mrc_data import MRCData
def mulaw_inv(x, mu=255):
'''
Inverse mu-law companding.
'''
shape = x.shape
x = x.reshape(-1)
x = (x - 0.5) / mu * 2 - 1
x = torch.sign(x)*((1+mu)**torch.abs(x)-1)/mu
x = x.reshape(shape)
return x
class CichyData(MRCData):
'''
Class for loading the trials from the Cichy dataset.
'''
def set_subjects(self, split):
inds = np.in1d(self.sub_id[split], self.args.subjects_data)
self.sub_id[split] = self.sub_id[split][:, inds]
if split == 'train':
self.x_train_t = self.x_train_t[inds]
elif split == 'val':
self.x_val_t = self.x_val_t[inds]
elif split == 'test':
self.x_test_t = self.x_test_t[inds]
def load_mat_data(self, args):
'''
Loads ready-to-train splits from mat files.
'''
chn = args.num_channels
x_train_ts = []
x_val_ts = []
x_test_ts = []
# load data for each channel
for index, i in enumerate(chn):
data = loadmat(args.load_data + 'ch' + str(i) + '.mat')
x_train_ts.append(np.array(data['x_train_t']))
x_val_ts.append(np.array(data['x_val_t']))
try:
x_test_ts.append(np.array(data['x_test_t']))
except:
pass
if index == 0:
self.sub_id['train'] = np.array(data['sub_id_train'])
self.sub_id['val'] = np.array(data['sub_id_val'])
try:
self.sub_id['test'] = np.array(data['sub_id_test'])
except:
pass
self.x_train_t = np.concatenate(tuple(x_train_ts), axis=1)
self.x_val_t = np.concatenate(tuple(x_val_ts), axis=1)
if len(x_test_ts) == 0:
self.x_test_t = self.x_val_t
self.sub_id['test'] = self.sub_id['val']
else:
self.x_test_t = np.concatenate(tuple(x_test_ts), axis=1)
def trial_subset(self, data, args):
'''
Selects a subset of trials from the data.
'''
num_ch = len(args.num_channels) - 1
# select a subset of training trials
num_trials = np.sum(data[:, num_ch, 0] == 0.0)
max_trials = int(args.max_trials * num_trials)
trials = [0] * args.num_classes
inds = []
for i in range(data.shape[0]):
cond = int(data[i, num_ch, 0])
if trials[cond] < max_trials:
trials[cond] += 1
inds.append(i)
return inds
def set_common(self, args):
if not isinstance(args.num_channels, list):
args.num_channels = list(range(args.num_channels+1))
num_ch = len(args.num_channels) - 1
# select wanted subjects
if args.subjects_data:
self.set_subjects('train')
self.set_subjects('val')
self.set_subjects('test')
# crop data
tmin = args.sample_rate[0]
tmax = args.sample_rate[1]
self.x_train_t = self.x_train_t[:, :, tmin:tmax]
self.x_val_t = self.x_val_t[:, :, tmin:tmax]
self.x_test_t = self.x_test_t[:, :, tmin:tmax]
args.sample_rate = tmax - tmin
inds = self.trial_subset(self.x_train_t, args)
self.x_train_t = self.x_train_t[inds, :, :]
if args.val_max_trials:
inds = self.trial_subset(self.x_val_t, args)
self.x_val_t = self.x_val_t[inds, :, :]
self.x_test_t = self.x_test_t[inds, :, :]
# whiten data if needed
if args.group_whiten:
# reshape for PCA
x_train = self.x_train_t[:, :num_ch, :].transpose(0, 2, 1)
x_val = self.x_val_t[:, :num_ch, :].transpose(0, 2, 1)
x_test = self.x_test_t[:, :num_ch, :].transpose(0, 2, 1)
x_train = x_train.reshape(-1, num_ch)
x_val = x_val.reshape(-1, num_ch)
x_test = x_test.reshape(-1, num_ch)
# change dim red temporarily
dim_red = args.dim_red
args.dim_red = num_ch
x_train, x_val, x_test = self.whiten(x_train, x_val, x_test)
args.dim_red = dim_red
# reshape back to trials
x_train = x_train.reshape(-1, args.sample_rate, num_ch)
x_val = x_val.reshape(-1, args.sample_rate, num_ch)
x_test = x_test.reshape(-1, args.sample_rate, num_ch)
x_train = x_train.transpose(0, 2, 1)
x_val = x_val.transpose(0, 2, 1)
x_test = x_test.transpose(0, 2, 1)
self.x_train_t[:, :num_ch, :] = x_train
self.x_val_t[:, :num_ch, :] = x_val
self.x_test_t[:, :num_ch, :] = x_test
args.num_channels = args.num_channels[:-1]
super(CichyData, self).set_common()
def save_data(self):
'''
Save final data to disk for easier loading next time.
'''
if self.args.save_data:
for i in range(self.x_train_t.shape[1]):
dump = {'x_train_t': self.x_train_t[:, i:i+1:, :],
'x_val_t': self.x_val_t[:, i:i+1, :],
'x_test_t': self.x_test_t[:, i:i+1, :],
'sub_id_train': self.sub_id['train'],
'sub_id_val': self.sub_id['val'],
'sub_id_test': self.sub_id['test']}
savemat(self.args.dump_data + 'ch' + str(i) + '.mat', dump)
# save standardscaler
path = os.path.join('/'.join(self.args.dump_data.split('/')[:-1]),
'standardscaler')
with open(path, 'wb') as file:
pickle.dump(self.norm, file)
def splitting(self, dataset, args):
split_l = int(args.split[0] * dataset.shape[1])
split_h = int(args.split[1] * dataset.shape[1])
x_val = dataset[:, split_l:split_h, :, :]
x_train = dataset[:, :split_l, :, :]
x_train = np.concatenate((x_train, dataset[:, split_h:, :, :]),
axis=1)
return x_train, x_val, x_val
def load_data(self, args):
'''
Load trials for each condition from multiple subjects.
'''
# whether we are working with one subject or a directory of them
if isinstance(args.data_path, list):
paths = args.data_path
elif 'sub' in args.data_path:
paths = [args.data_path]
else:
paths = os.listdir(args.data_path)
paths = [os.path.join(args.data_path, p) for p in paths]
paths = [p for p in paths if os.path.isdir(p)]
paths = [p for p in paths if 'opt' not in p]
paths = [p for p in paths if 'sub' in p]
channels = len(args.num_channels)
x_trains = []
x_vals = []
x_tests = []
for path in paths:
print('Loading ', path, flush=True)
min_trials = 1000000
dataset = []
# loop over conditions
for c in range(args.num_classes):
cond_path = os.path.join(path, 'cond' + str(c))
files = os.listdir(cond_path)
files = [f for f in files if 'npy' in f]
if len(files) < min_trials:
min_trials = len(files)
for c in range(args.num_classes):
cond_path = os.path.join(path, 'cond' + str(c))
trials = []
# loop over trials within a condition
for i in range(min_trials):
trial = np.load(os.path.join(cond_path, f'trial{i}.npy'))
trials.append(trial)
dataset.append(np.array(trials))
# condition with lowest number of trials
print('Minimum trials: ', min_trials, flush=True)
# dataset shape: conditions x trials x timesteps x channels
dataset = np.array([t[:min_trials, :, :] for t in dataset])
if args.whiten > 1000:
args.num_channels = list(range(dataset.shape[-1]))
args.whiten = dataset.shape[-1]
channels = dataset.shape[-1]
# choose first 306 channels
dataset = dataset.transpose(0, 1, 3, 2)
if hasattr(args, 'flip_axes'):
if args.flip_axes:
dataset = dataset.transpose(0, 1, 3, 2)
dataset = dataset[:, :, args.num_channels, :]
self.timesteps = dataset.shape[3]
# create training and validation splits with equal class numbers
x_train, x_val, x_test = self.splitting(dataset, args)
# crop training trials
max_trials = round(args.max_trials * x_train.shape[1])
x_train = x_train[:, :max_trials, :, :]
print(x_train.shape)
x_train = x_train.transpose(0, 1, 3, 2).reshape(-1, channels)
x_val = x_val.transpose(0, 1, 3, 2).reshape(-1, channels)
x_test = x_test.transpose(0, 1, 3, 2).reshape(-1, channels)
# standardize dataset along channels
x_train, x_val, x_test = self.normalize(x_train, x_val, x_test)
x_trains.append(x_train)
x_vals.append(x_val)
x_tests.append(x_test)
# this is just needed to work together with other dataset classes
disconts = [[0] for path in paths]
args.num_channels = len(args.num_channels)
return x_trains, x_vals, x_tests, disconts
def normalize_ex(self, data):
'''
data = data.transpose(0, 1, 3, 2)
scaler = StandardScaler()
for i in range(data.shape[0]):
for j in range(data.shape[1]):
data[i, j, :, :] = scaler.fit_transform(data[i, j, :, :])
return data.transpose(0, 1, 3, 2)
'''
trials = data.shape[1]
data = data.reshape(-1, data.shape[2], data.shape[3])
data = data.astype(np.float64)
data = mne.filter.notch_filter(
data, 1000, np.array([50, 100, 150]), phase='minimum')
data = mne.filter.filter_data(
data, 1000, 0.1, 124.9, phase='minimum')
return data.reshape(-1, trials, data.shape[1], data.shape[2])
def create_examples(self, x, disconts):
'''
Create examples with labels.
'''
# expand shape to trials
x = x.transpose(1, 0)
x = x.reshape(self.args.num_classes, -1, self.timesteps, x.shape[1])
x = x.transpose(0, 1, 3, 2)
# downsample data if needed
resample = int(self.args.original_sr/self.args.sr_data)
x = x[:, :, :, ::resample]
timesteps = x.shape[3]
trials = x.shape[1]
# create labels, and put them in the last channel of the data
array = []
labels = np.ones((trials, 1, timesteps))
for c in range(x.shape[0]):
array.append(np.concatenate((x[c, :, :, :], labels * c), axis=1))
x = np.array(array).reshape(-1, x.shape[2] + 1, timesteps)
return x
class CichyDataDISP(CichyData):
def splitting(self, dataset, args):
split_l = int(args.split[0] * dataset.shape[1])
split_h = int(args.split[1] * dataset.shape[1])
x_val = dataset[:, split_l:split_h, :, :]
x_train_lower, x_train_upper = None, None
if split_l > 1:
x_train_lower = dataset[:, :split_l-1, :, :]
if split_h < dataset.shape[1] - 1:
x_train_upper = dataset[:, split_h+1:, :, :]
if x_train_lower is not None and x_train_upper is not None:
x_train = np.concatenate((x_train_lower, x_train_upper),
axis=1)
elif x_train_lower is not None:
x_train = x_train_lower
elif x_train_upper is not None:
x_train = x_train_upper
return x_train, x_val, x_val
class CichyDataTrialNorm(CichyData):
def normalize(self, x_train, x_val, x_test):
'''
Standardize and whiten data if needed.
'''
# standardize dataset along channels
self.norm = StandardScaler()
resample = int(self.args.original_sr/self.args.sr_data)
# expand shape to trials x timesteps x channels
x_train = x_train.reshape(-1, self.timesteps, x_train.shape[1])
x_val = x_val.reshape(-1, self.timesteps, x_val.shape[1])
x_test = x_test.reshape(-1, self.timesteps, x_test.shape[1])
x_train = x_train[:, ::resample, :]
x_val = x_val[:, ::resample, :]
x_test = x_test[:, ::resample, :]
self.timesteps = x_train.shape[1]
# squeeze to trials x (timesteps x channels)
x_train = x_train.reshape(x_train.shape[0], -1)
x_val = x_val.reshape(x_val.shape[0], -1)
x_test = x_test.reshape(x_test.shape[0], -1)
self.norm.fit(x_train)
print(x_train.shape)
#x_train = self.norm.transform(x_train)
#x_val = self.norm.transform(x_val)
#x_test = self.norm.transform(x_test)
var = 1e-6
var = np.std(x_train)
print('Global variance: ', var)
mean = np.mean(x_train, axis=0)
x_train = (x_train - mean)/var
x_val = (x_val - mean)/var
x_test = (x_test - mean)/var
# expand shape to trials x timesteps x channels
x_train = x_train.reshape(x_train.shape[0], self.timesteps, -1)
x_val = x_val.reshape(x_val.shape[0], self.timesteps, -1)
x_test = x_test.reshape(x_test.shape[0], self.timesteps, -1)
# squeeze to (trials x timesteps) x channels
x_train = x_train.reshape(-1, x_train.shape[2])
x_val = x_val.reshape(-1, x_val.shape[2])
x_test = x_test.reshape(-1, x_test.shape[2])
return x_train.T, x_val.T, x_test.T
def create_examples(self, x, disconts):
'''
Create examples with labels.
'''
# expand shape to trials
x = x.transpose(1, 0)
x = x.reshape(self.args.num_classes, -1, self.timesteps, x.shape[1])
x = x.transpose(0, 1, 3, 2)
# downsample data if needed
timesteps = x.shape[3]
trials = x.shape[1]
# create labels, and put them in the last channel of the data
array = []
labels = np.ones((trials, 1, timesteps))
for c in range(x.shape[0]):
array.append(np.concatenate((x[c, :, :, :], labels * c), axis=1))
x = np.array(array).reshape(-1, x.shape[2] + 1, timesteps)
return x
class CichyDataDISPTrialNorm(CichyDataDISP, CichyDataTrialNorm):
pass
class CichyDataCHN(CichyData):
'''
Same as CichyData, but channel numbers are not pre-specified.
'''
def load_mat_data(self, args):
'''
Loads ready-to-train splits from mat files.
Number of channels is inferred from number of files.
'''
# get number of channels by counting files in args.load_data
chn = []
for f in os.listdir(args.data_path):
if 'ch' in f:
chn.append(int(f.split('.')[0].split('ch')[-1]))
args.num_channels = sorted(chn)
super().load_mat_data(args)
class CichyDataRandsample(CichyData):
'''
Class for randomizing the batch retrieval for the Cichy dataset.
'''
def get_train_batch(self, i):
if i == 0:
self.inds['train'] = list(range(self.x_train_t.shape[0]))
# sample random indices
inds = random.sample(self.inds['train'], self.bs['train'])
self.inds['train'] = [v for v in self.inds['train'] if v not in inds]
return self.x_train_t[inds, :, :], self.sub_id['train'][inds]
class CichyDataRobust(CichyData):
def product_quantize(self, x_train, x_val, x_test):
# convert to contiguous array
x_train = np.ascontiguousarray(x_train, dtype=np.float32)
x_val = np.ascontiguousarray(x_val, dtype=np.float32)
x_test = np.ascontiguousarray(x_test, dtype=np.float32)
'''
self.res_quantizer = faiss.ResidualQuantizer(x_train.shape[1], 2, 8)
self.res_quantizer.train(x_train)
# encode
codes = self.res_quantizer.compute_codes(x_train)
x_train = self.res_quantizer.decode(codes)
codes = self.res_quantizer.compute_codes(x_val)
x_val = self.res_quantizer.decode(codes)
codes = self.res_quantizer.compute_codes(x_test)
x_test = self.res_quantizer.decode(codes)
'''
# put the 306 channels into 6 buckets based on covariance
# in each bucket the channels should have similar covariances
num_buckets = 40
# Compute the covariance matrix of the features
cov_matrix = np.cov(x_train, rowvar=False)
# Apply K-means clustering on the covariance matrix
kmeans = KMeans(n_clusters=num_buckets, random_state=0).fit(cov_matrix)
# Create a dictionary to store the features in each bucket
buckets = {i: [] for i in range(num_buckets)}
# Assign features to the corresponding buckets
for feature_idx, bucket in enumerate(kmeans.labels_):
buckets[bucket].append(feature_idx)
num_subspaces = 2 # Number of subspaces
num_clusters_per_subspace = 6 # Total quantization bins = num_clusters_per_subspace ** num_subspaces = 100k
# create a residual quantizer for each bucket of features
for bucket, features in buckets.items():
res_quant = faiss.ResidualQuantizer(len(features), num_subspaces, num_clusters_per_subspace)
res_quant.train(np.ascontiguousarray(x_train[:, features]))
xt = np.ascontiguousarray(x_train[:, features], dtype=np.float32)
codes = res_quant.compute_codes(xt)
x_train[:, features] = res_quant.decode(codes)
xv = np.ascontiguousarray(x_val[:, features], dtype=np.float32)
codes = res_quant.compute_codes(xv)
x_val[:, features] = res_quant.decode(codes)
xt = np.ascontiguousarray(x_test[:, features], dtype=np.float32)
codes = res_quant.compute_codes(xt)
x_test[:, features] = res_quant.decode(codes)
self.norm2 = RobustScaler()
self.norm2.fit(x_train)
x_train = self.norm2.transform(x_train)
x_val = self.norm2.transform(x_val)
x_test = self.norm2.transform(x_test)
return x_train, x_val, x_test
def save_data(self):
super().save_data()
'''
# check if self.res_quantizer and self.norm2 exist
if hasattr(self, 'res_quantizer') and hasattr(self, 'norm2'):
# save res_quantizer and norm2
path = os.path.join('/'.join(self.args.dump_data.split('/')[:-1]),
'quantizer')
with open(path, 'wb') as file:
pickle.dump(self.res_quantizer, file)
path = os.path.join('/'.join(self.args.dump_data.split('/')[:-1]),
'norm2')
with open(path, 'wb') as file:
pickle.dump(self.norm2, file)
'''
def normalize(self, x_train, x_val, x_test):
'''
Standardize and whiten data if needed.
'''
# standardize dataset along channels
self.norm = RobustScaler()
self.norm.fit(x_train)
print(x_train.shape)
x_train = self.norm.transform(x_train)
x_val = self.norm.transform(x_val)
x_test = self.norm.transform(x_test)
# if needed, remove covariance with PCA
if self.args.whiten:
x_train, x_val, x_test = self.whiten(x_train, x_val, x_test)
# check if args has product_quant attribute
if hasattr(self.args, 'product_quant'):
if self.args.product_quant:
x_train, x_val, x_test = self.product_quantize(
x_train, x_val, x_test)
return x_train.T, x_val.T, x_test.T
class CichyDataCrossval(CichyDataRobust):
def splitting(self, dataset, args):
split = args.split[1] - args.split[0]
split = int(split*dataset.shape[1])
if args.shuffle:
for i in range(dataset.shape[0]):
perm = np.random.permutation(dataset.shape[1])
dataset[i, :, :, :] = dataset[i, perm, :, :]
# create separate val and test splits
x_val = dataset[:, :split, :, :]
x_train = dataset[:, split:, :, :]
x_test = x_train[:, :split:, :, :]
x_train = x_train[:, split:, :, :]
return x_train, x_val, x_test
class CichyDataNoNorm(CichyData):
def normalize(self, x_train, x_val, x_test):
self.norm = RobustScaler()
return x_train.T, x_val.T, x_test.T
class CichyDataCrossvalRobust(CichyDataCrossval, CichyDataRobust):
pass
class CichyDataCrossvalNoNorm(CichyDataCrossval):
def normalize(self, x_train, x_val, x_test):
self.norm = StandardScaler()
return x_train.T, x_val.T, x_test.T
class CichyContData(MRCData):
'''
Implements the continuous classification problem on the Cichy dataset.
Under construction.
'''
def load_data(self, args):
'''
Load raw data from multiple subjects.
'''
# whether we are working with one subject or a directory of them
if isinstance(args.data_path, list):
paths = args.data_path
else:
paths = os.listdir(args.data_path)
paths = [p for p in paths if 'sub' in p]
paths = [os.path.join(args.data_path, p) for p in paths]
paths = [p for p in paths if not os.path.isdir(p)]
print('Number of subjects: ', len(paths))
resample = int(1000/args.sr_data)
epoch_len = int(0.5*args.sr_data)
# split ratio
split = args.split[1] - args.split[0]
split_trials = int(30 * split)
x_trains = []
x_vals = []
disconts = []
for path in paths:
print(path)
# will have to be changed to handle concatenated subjects
# load event timings for continuous data
ev_path = os.path.join(args.data_path, 'event_times.npy')
event_times = np.load(ev_path)
event_times = [(int(ev[0]/resample), ev[2]) for ev in event_times]
dataset = np.load(path).T
# choose first 306 channels and downsample
dataset = dataset[args.num_channels, ::resample]
labels = [118] * dataset.shape[1]
val_counter = [0] * args.num_classes
val_events = []
test_events = []
train_events = []
'''
elif val_counter[ev[1]-1] < split_trials * 2:
val_counter[ev[1]-1] += 1
test_events.append(ev[0])
'''
# set labels
for ev in event_times:
if ev[1] < 119:
labels[ev[0]:ev[0]+epoch_len] = [ev[1]-1] * epoch_len
if val_counter[ev[1]-1] < 6:
val_counter[ev[1]-1] += 1
val_events.append(ev[0])
else:
train_events.append(ev[0])
labels = np.array(labels)
print('Last val sample: ', max(val_events))
print('First train sample: ', min(train_events))
split = int((max(val_events) + min(train_events))/2)
labels = {'val': labels[:split].reshape(1, -1),
'train': labels[split:].reshape(1, -1)}
# create training and validation splits
x_val = dataset[:, :split]
x_test = dataset[:, :split]
x_train = dataset[:, split:]
x_train, x_val, x_test = self.normalize(x_train.T,
x_val.T,
x_test.T)
# add labels to data
x_val = np.concatenate((x_val, labels['val']), axis=0)
x_train = np.concatenate((x_train, labels['train']), axis=0)
x_trains.append(x_train)
x_vals.append(x_val)
# this is just needed to work together with other dataset classes
disconts = [[0] for path in paths]
return x_trains, x_vals, x_vals, disconts
def create_examples(self, x, disconts):
'''
Create examples with labels.
'''
return x.reshape(1, x.shape[0], x.shape[1])
def set_common(self, args=None):
# set common parameters
super(CichyContData, self).set_common()
sr = self.args.sample_rate
bs = self.args.batch_size
self.bs = {'train': bs, 'val': bs, 'test': bs}
print('Train batch size: ', self.bs['train'])
print('Validation batch size: ', self.bs['val'])
self.train_batches = int(
(self.x_train_t.shape[2] - sr - 1) / self.bs['train'])
self.val_batches = int(
(self.x_val_t.shape[2] - sr - 1) / self.bs['val'])
self.test_batches = int(
(self.x_test_t.shape[2] - sr - 1) / self.bs['test'])
args.num_channels -= 1
def get_batch(self, i, data, split):
sr = self.args.sample_rate
if i == 0:
self.inds[split] = np.arange(data.shape[2] - sr)
np.random.shuffle(self.inds[split])
# sample random indices
inds = self.inds[split][:self.bs[split]]
data = torch.stack([data[0, :, ind:ind+sr] for ind in inds])
self.inds[split] = self.inds[split][self.bs[split]:]
return data, self.sub_id[split]
def create_labels(self, data):
sr = self.args.sample_rate[1] - self.args.sample_rate[0]
inds = list(range(data.shape[2] - sr))
peak_times = [-1] * data.shape[2]
# how many timesteps needed to detect image
im_len = int(0.5*self.args.sr_data)
tresh = int(self.args.decode_front*self.args.sr_data)
halftresh = int(self.args.decode_front*self.args.sr_data/2)
back_tresh = int(self.args.decode_back*self.args.sr_data)
peak = int(self.args.decode_peak*self.args.sr_data)
im_presence = data[0, -1, :].copy()
im_presence = (im_presence < 118).astype(int)
# loop over examples in batch
for i in inds:
targets = data[0, -1, i:i+sr].copy()
# if last timestep is one of the 118 images and enough time
# has elapsed since image presentation
if targets[-1] < 118 and np.all(targets[-tresh:] == targets[-1]):
data[0, -1, i] = targets[-1]
# set image peak time (150ms)
tinds = np.nonzero(targets - targets[-1])[0]
peak_times[i] = tinds[-1] + peak
if tinds[-1] < sr - im_len - 1 or peak_times[i] > sr-1:
print('Error1')
print(targets)
# else predict last image presented
elif (targets[0] < 118 and
np.all(targets[:back_tresh] == targets[0])):
data[0, -1, i] = targets[0]
# set image peak time (150ms)
tinds = np.nonzero(targets - targets[0])[0]
peak_times[i] = tinds[0] - im_len + peak + 1
if tinds[0] > im_len + 1 or peak_times[i] < 0:
print('Error2')
print(peak_times[i])
print(targets)
# else predict image in middle of window
elif targets[im_len-1] < 118 or targets[-im_len+1] < 118:
data[0, -1, i] = targets[-im_len+1]
if targets[im_len-1] < 118:
data[0, -1, i] = targets[im_len-1]
# set image start
tinds = np.nonzero(targets - 118)[0]
tinds2 = np.nonzero(targets - targets[0])[0]
image_start = tinds[tinds > tinds2[0]][0]
peak_times[i] = image_start + peak
if image_start < 0 or image_start + im_len > sr:
print('Error3')
print(targets)
else:
data[0, -1, i] = 118
if peak_times[i] < -1 or peak_times[i] > sr - 1:
print(targets)
#print(data[0, -1, i])
#print(targets)
# scale non-epoch class
nonepoch_trials = sum(data[0, -1, :] == 118)
epoch_trials = sum(data[0, -1, :] == 0)
self.args.epoch_ratio = epoch_trials / nonepoch_trials
print('Non-epoch trials: ', sum(data[0, -1, :] == 118))
print('Class 0 trials: ', sum(data[0, -1, :] == 0))
print('Class 1 trials: ', sum(data[0, -1, :] == 1))
print('Total trials: ', data.shape[2])
peak_times = np.array(peak_times).reshape(1, 1, -1)
im_presence = np.array(im_presence).reshape(1, 1, -1)
return peak_times, im_presence
def load_mat_data(self, args):
super(CichyContData, self).load_mat_data(args)
ev_times, im_presence = self.create_labels(self.x_train_t)
self.x_train_t = np.concatenate((self.x_train_t[:, :-1, :],
im_presence,
ev_times,
self.x_train_t[:, -1:, :]),
axis=1)
ev_times, im_presence = self.create_labels(self.x_val_t)
self.x_val_t = np.concatenate((self.x_val_t[:, :-1, :],
im_presence,
ev_times,
self.x_val_t[:, -1:, :]),
axis=1)
self.x_test_t = self.x_val_t
class CichySimpleContData(CichyContData):
def create_labels(self, data):
sr = self.args.sample_rate[1] - self.args.sample_rate[0]
inds = list(range(data.shape[2] - sr))
peak_times = [-1] * data.shape[2]
im_presence = data[0, -1, :].copy()
im_presence = (im_presence < 118).astype(int)
im_presence = np.array(im_presence).reshape(1, 1, -1)
# how many timesteps needed to detect image
peak = int(self.args.decode_peak*self.args.sr_data)
# loop over examples in batch
for i in inds:
targets = data[0, -1, i:i+sr].copy()
end_loop = False
starts = list(range(20, 40))
for ind in starts:
if targets[ind] < 118 and np.all(targets[ind:ind+125] == targets[ind]):
data[0, -1, i] = targets[ind]
peak_times[i] = ind + peak
end_loop = True
if end_loop:
break
if not end_loop:
data[0, -1, i] = 118
# scale non-epoch class
nonepoch_trials = sum(data[0, -1, :] == 118)
epoch_trials = sum(data[0, -1, :] == 0)
self.args.epoch_ratio = epoch_trials / nonepoch_trials
print('Non-epoch trials: ', sum(data[0, -1, :] == 118))
print('Class 0 trials: ', sum(data[0, -1, :] == 0))
print('Class 1 trials: ', sum(data[0, -1, :] == 1))
print('Total trials: ', data.shape[2])
peak_times = np.array(peak_times).reshape(1, 1, -1)
return peak_times, im_presence
class CichyQuantized(MRCData):
def __init__(self, args):
'''
Load data and apply pca, then create batches.
'''
self.args = args
self.inds = {'train': [], 'val': [], 'test': []}
self.sub_id = {'train': [0], 'val': [0], 'test': [0]}
self.chn_weights_sample = {}
self.chn_ids = {}
# load pickled data directly, no further processing required
if args.load_data:
self.load_mat_data(args)
self.set_common(args)
return
# load the raw subject data
x_trains, x_vals, x_tests = self.load_data(args)
# this is the continuous data for AR models
self.x_train = np.concatenate(tuple(x_trains), axis=1)
self.x_val = np.concatenate(tuple(x_vals), axis=1)
self.x_test = np.concatenate(tuple(x_tests), axis=1)
if not args.bypass:
self.encode()
os.makedirs(args.dump_data, exist_ok=True)
self.save_data()
self.set_common(args)
else:
args.num_channels = len(args.num_channels)
def load_data(self, args):
'''
Load raw data from multiple subjects.
'''
# whether we are working with one subject or a directory of them
if isinstance(args.data_path, list):
paths = args.data_path
else:
paths = os.listdir(args.data_path)
paths = [p for p in paths if 'sub' in p]
paths = [os.path.join(args.data_path, p) for p in paths]
paths = [p for p in paths if not os.path.isdir(p)]
print('Number of subjects: ', len(paths))
resample = int(1000/args.sr_data)
epoch_len = int(0.5*args.sr_data)
x_trains = []
x_vals = []
x_tests = []
for sid, path in enumerate(paths):
print(path)
# will have to be changed to handle concatenated subjects
# load event timings for continuous data
ev_path = os.path.join(os.path.dirname(path), 'event_times.npy')
event_times = np.load(ev_path)
event_times = [(int(ev[0]/resample), ev[2]) for ev in event_times]
dataset = np.load(path)
# filter if needed
if args.filter:
iir_params = dict(order=5, ftype='butter')
dataset = mne.filter.filter_data(dataset,
1000,
args.filter[0],
args.filter[1],
method='iir',
iir_params=iir_params)
# choose first 306 channels and downsample
dataset = dataset[args.num_channels, ::resample]
labels = [0] * dataset.shape[1]
val_counter = [0] * args.num_classes
test_counter = [0] * args.num_classes
val_events = []
test_events = []
train_events = []
# set labels
for ev in event_times:
if ev[1] < 119:
cond = ev[1]-1
labels[ev[0]:ev[0]+epoch_len] = [cond+1] * epoch_len
if val_counter[cond] < 4:
val_counter[cond] += 1
val_events.append(ev[0])
elif test_counter[cond] < 4:
test_counter[cond] += 1
test_events.append(ev[0])
else:
train_events.append(ev[0])
labels = np.array(labels)
print('Last val sample: ', max(val_events))
print('First test sample: ', min(test_events))
print('Last test sample: ', max(test_events))
print('First train sample: ', min(train_events))