/
transforms.py
1072 lines (919 loc) · 37.1 KB
/
transforms.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
# Authors: Cédric Rommel <cedric.rommel@inria.fr>
# Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)
import warnings
from numbers import Real
from typing import Callable
import numpy as np
import torch
from mne.channels import make_standard_montage
from .base import Transform
from .functional import bandstop_filter
from .functional import channels_dropout
from .functional import channels_permute
from .functional import channels_shuffle
from .functional import frequency_shift
from .functional import ft_surrogate
from .functional import gaussian_noise
from .functional import mixup
from .functional import sensors_rotation
from .functional import sign_flip
from .functional import smooth_time_mask
from .functional import time_reverse
class TimeReverse(Transform):
"""Flip the time axis of each input with a given probability.
Parameters
----------
probability : float
Float setting the probability of applying the operation.
random_state: int | numpy.random.Generator, optional
Seed to be used to instantiate numpy random number generator instance.
Used to decide whether or not to transform given the probability
argument. Defaults to None.
"""
operation = staticmethod(time_reverse) # type: ignore[assignment]
def __init__(
self,
probability,
random_state=None,
):
super().__init__(
probability=probability,
random_state=random_state,
)
class SignFlip(Transform):
"""Flip the sign axis of each input with a given probability.
Parameters
----------
probability : float
Float setting the probability of applying the operation.
random_state: int | numpy.random.Generator, optional
Seed to be used to instantiate numpy random number generator instance.
Used to decide whether or not to transform given the probability
argument. Defaults to None.
"""
operation = staticmethod(sign_flip) # type: ignore[assignment]
def __init__(self, probability, random_state=None):
super().__init__(probability=probability, random_state=random_state)
class FTSurrogate(Transform):
"""FT surrogate augmentation of a single EEG channel, as proposed in [1]_.
Parameters
----------
probability: float
Float setting the probability of applying the operation.
phase_noise_magnitude : float | torch.Tensor, optional
Float between 0 and 1 setting the range over which the phase
perturbation is uniformly sampled:
``[0, phase_noise_magnitude * 2 * pi]``. Defaults to 1.
channel_indep : bool, optional
Whether to sample phase perturbations independently for each channel or
not. It is advised to set it to False when spatial information is
important for the task, like in BCI. Default False.
random_state: int | numpy.random.Generator, optional
Seed to be used to instantiate numpy random number generator instance.
Used to decide whether or not to transform given the probability
argument. Defaults to None.
References
----------
.. [1] Schwabedal, J. T., Snyder, J. C., Cakmak, A., Nemati, S., &
Clifford, G. D. (2018). Addressing Class Imbalance in Classification
Problems of Noisy Signals by using Fourier Transform Surrogates. arXiv
preprint arXiv:1806.08675.
"""
operation = staticmethod(ft_surrogate) # type: ignore[assignment]
def __init__(
self,
probability,
phase_noise_magnitude=1,
channel_indep=False,
random_state=None,
):
super().__init__(probability=probability, random_state=random_state)
assert isinstance(
phase_noise_magnitude, (float, int, torch.Tensor)
), "phase_noise_magnitude should be a float."
assert (
0 <= phase_noise_magnitude <= 1
), "phase_noise_magnitude should be between 0 and 1."
assert isinstance(
channel_indep, bool
), "channel_indep is expected to be a boolean"
self.phase_noise_magnitude = phase_noise_magnitude
self.channel_indep = channel_indep
def get_augmentation_params(self, *batch):
"""Return transform parameters.
Parameters
----------
X : tensor.Tensor
The data.
y : tensor.Tensor
The labels.
Returns
-------
params : dict
Contains:
* phase_noise_magnitude : float
The magnitude of the transformation.
* random_state : numpy.random.Generator
The generator to use.
"""
return {
"phase_noise_magnitude": self.phase_noise_magnitude,
"channel_indep": self.channel_indep,
"random_state": self.rng,
}
class ChannelsDropout(Transform):
"""Randomly set channels to flat signal.
Part of the CMSAugment policy proposed in [1]_
Parameters
----------
probability: float
Float setting the probability of applying the operation.
proba_drop: float | None, optional
Float between 0 and 1 setting the probability of dropping each channel.
Defaults to 0.2.
random_state: int | numpy.random.Generator, optional
Seed to be used to instantiate numpy random number generator instance.
Used to decide whether or not to transform given the probability
argument and to sample channels to erase. Defaults to None.
References
----------
.. [1] Saeed, A., Grangier, D., Pietquin, O., & Zeghidour, N. (2020).
Learning from Heterogeneous EEG Signals with Differentiable Channel
Reordering. arXiv preprint arXiv:2010.13694.
"""
operation = staticmethod(channels_dropout) # type: ignore[assignment]
def __init__(self, probability, p_drop=0.2, random_state=None):
super().__init__(probability=probability, random_state=random_state)
self.p_drop = p_drop
def get_augmentation_params(self, *batch):
"""Return transform parameters.
Parameters
----------
X : tensor.Tensor
The data.
y : tensor.Tensor
The labels.
Returns
-------
params : dict
Contains
* p_drop : float
Float between 0 and 1 setting the probability of dropping each
channel.
* random_state : numpy.random.Generator
The generator to use.
"""
return {
"p_drop": self.p_drop,
"random_state": self.rng,
}
class ChannelsShuffle(Transform):
"""Randomly shuffle channels in EEG data matrix.
Part of the CMSAugment policy proposed in [1]_
Parameters
----------
probability: float
Float setting the probability of applying the operation.
p_shuffle: float | None, optional
Float between 0 and 1 setting the probability of including the channel
in the set of permuted channels. Defaults to 0.2.
random_state: int | numpy.random.Generator, optional
Seed to be used to instantiate numpy random number generator instance.
Used to decide whether or not to transform given the probability
argument, to sample which channels to shuffle and to carry the shuffle.
Defaults to None.
References
----------
.. [1] Saeed, A., Grangier, D., Pietquin, O., & Zeghidour, N. (2020).
Learning from Heterogeneous EEG Signals with Differentiable Channel
Reordering. arXiv preprint arXiv:2010.13694.
"""
operation = staticmethod(channels_shuffle) # type: ignore[assignment]
def __init__(self, probability, p_shuffle=0.2, random_state=None):
super().__init__(probability=probability, random_state=random_state)
self.p_shuffle = p_shuffle
def get_augmentation_params(self, *batch):
"""Return transform parameters.
Parameters
----------
X : tensor.Tensor
The data.
y : tensor.Tensor
The labels.
Returns
-------
params : dict
Contains
* p_shuffle : float
Float between 0 and 1 setting the probability of including the
channel in the set of permuted channels.
* random_state : numpy.random.Generator
The generator to use.
"""
return {
"p_shuffle": self.p_shuffle,
"random_state": self.rng,
}
class GaussianNoise(Transform):
"""Randomly add white noise to all channels.
Suggested e.g. in [1]_, [2]_ and [3]_
Parameters
----------
probability : float
Float setting the probability of applying the operation.
std : float, optional
Standard deviation to use for the additive noise. Defaults to 0.1.
random_state: int | numpy.random.Generator, optional
Seed to be used to instantiate numpy random number generator instance.
Defaults to None.
References
----------
.. [1] Wang, F., Zhong, S. H., Peng, J., Jiang, J., & Liu, Y. (2018). Data
augmentation for eeg-based emotion recognition with deep convolutional
neural networks. In International Conference on Multimedia Modeling
(pp. 82-93).
.. [2] Cheng, J. Y., Goh, H., Dogrusoz, K., Tuzel, O., & Azemi, E. (2020).
Subject-aware contrastive learning for biosignals. arXiv preprint
arXiv:2007.04871.
.. [3] Mohsenvand, M. N., Izadi, M. R., & Maes, P. (2020). Contrastive
Representation Learning for Electroencephalogram Classification. In
Machine Learning for Health (pp. 238-253). PMLR.
"""
operation = staticmethod(gaussian_noise) # type: ignore[assignment]
def __init__(self, probability, std=0.1, random_state=None):
super().__init__(
probability=probability,
random_state=random_state,
)
self.std = std
def get_augmentation_params(self, *batch):
"""Return transform parameters.
Parameters
----------
X : tensor.Tensor
The data.
y : tensor.Tensor
The labels.
Returns
-------
params : dict
Contains
* std : float
Standard deviation to use for the additive noise.
* random_state : numpy.random.Generator
The generator to use.
"""
return {
"std": self.std,
"random_state": self.rng,
}
class ChannelsSymmetry(Transform):
"""Permute EEG channels inverting left and right-side sensors.
Suggested e.g. in [1]_
Parameters
----------
probability : float
Float setting the probability of applying the operation.
ordered_ch_names : list
Ordered list of strings containing the names (in 10-20
nomenclature) of the EEG channels that will be transformed. The
first name should correspond the data in the first row of X, the
second name in the second row and so on.
random_state: int | numpy.random.Generator, optional
Seed to be used to instantiate numpy random number generator instance.
Used to decide whether or not to transform given the probability
argument. Defaults to None.
References
----------
.. [1] Deiss, O., Biswal, S., Jin, J., Sun, H., Westover, M. B., & Sun, J.
(2018). HAMLET: interpretable human and machine co-learning technique.
arXiv preprint arXiv:1803.09702.
"""
operation = staticmethod(channels_permute) # type: ignore[assignment]
def __init__(self, probability, ordered_ch_names, random_state=None):
super().__init__(
probability=probability,
random_state=random_state,
)
assert isinstance(ordered_ch_names, list) and all(
isinstance(ch, str) for ch in ordered_ch_names
), "ordered_ch_names should be a list of str."
permutation = list()
for idx, ch_name in enumerate(ordered_ch_names):
new_position = idx
# Find digits in channel name (assuming 10-20 system)
d = "".join(list(filter(str.isdigit, ch_name)))
if len(d) > 0:
d = int(d)
if d % 2 == 0: # pair/right electrodes
sym = d - 1
else: # odd/left electrodes
sym = d + 1
new_channel = ch_name.replace(str(d), str(sym))
if new_channel in ordered_ch_names:
new_position = ordered_ch_names.index(new_channel)
permutation.append(new_position)
self.permutation = permutation
def get_augmentation_params(self, *batch):
"""Return transform parameters.
Parameters
----------
X : tensor.Tensor
The data.
y : tensor.Tensor
The labels.
Returns
-------
params : dict
Contains
* permutation : float
List of integers defining the new channels order.
"""
return {"permutation": self.permutation}
class SmoothTimeMask(Transform):
"""Smoothly replace a randomly chosen contiguous part of all channels by
zeros.
Suggested e.g. in [1]_ and [2]_
Parameters
----------
probability : float
Float setting the probability of applying the operation.
mask_len_samples : int | torch.Tensor, optional
Number of consecutive samples to zero out. Will be ignored if
magnitude is not set to None. Defaults to 100.
random_state: int | numpy.random.Generator, optional
Seed to be used to instantiate numpy random number generator instance.
Defaults to None.
References
----------
.. [1] Cheng, J. Y., Goh, H., Dogrusoz, K., Tuzel, O., & Azemi, E. (2020).
Subject-aware contrastive learning for biosignals. arXiv preprint
arXiv:2007.04871.
.. [2] Mohsenvand, M. N., Izadi, M. R., & Maes, P. (2020). Contrastive
Representation Learning for Electroencephalogram Classification. In
Machine Learning for Health (pp. 238-253). PMLR.
"""
operation = staticmethod(smooth_time_mask) # type: ignore[assignment]
def __init__(self, probability, mask_len_samples=100, random_state=None):
super().__init__(
probability=probability,
random_state=random_state,
)
assert (
isinstance(mask_len_samples, (int, torch.Tensor)) and mask_len_samples > 0
), "mask_len_samples has to be a positive integer"
self.mask_len_samples = mask_len_samples
def get_augmentation_params(self, *batch):
"""Return transform parameters.
Parameters
----------
X : tensor.Tensor
The data.
y : tensor.Tensor
The labels.
Returns
-------
params : dict
Contains two elements:
* mask_start_per_sample : torch.tensor
Tensor of integers containing the position (in last dimension)
where to start masking the signal. Should have the same size as
the first dimension of X (i.e. one start position per example
in the batch).
* mask_len_samples : int
Number of consecutive samples to zero out.
"""
if len(batch) == 0:
return super().get_augmentation_params(*batch)
X = batch[0]
seq_length = torch.as_tensor(X.shape[-1], device=X.device)
mask_len_samples = self.mask_len_samples
if isinstance(mask_len_samples, torch.Tensor):
mask_len_samples = mask_len_samples.to(X.device)
mask_start = torch.as_tensor(
self.rng.uniform(
low=0,
high=1,
size=X.shape[0],
),
device=X.device,
) * (seq_length - mask_len_samples)
return {
"mask_start_per_sample": mask_start,
"mask_len_samples": mask_len_samples,
}
class BandstopFilter(Transform):
"""Apply a band-stop filter with desired bandwidth at a randomly selected
frequency position between 0 and ``max_freq``.
Suggested e.g. in [1]_ and [2]_
Parameters
----------
probability : float
Float setting the probability of applying the operation.
bandwidth : float
Bandwidth of the filter, i.e. distance between the low and high cut
frequencies.
sfreq : float, optional
Sampling frequency of the signals to be filtered. Defaults to 100 Hz.
max_freq : float | None, optional
Maximal admissible frequency. The low cut frequency will be sampled so
that the corresponding high cut frequency + transition (=1Hz) are below
``max_freq``. If omitted or `None`, will default to the Nyquist
frequency (``sfreq / 2``).
random_state: int | numpy.random.Generator, optional
Seed to be used to instantiate numpy random number generator instance.
Defaults to None.
References
----------
.. [1] Cheng, J. Y., Goh, H., Dogrusoz, K., Tuzel, O., & Azemi, E. (2020).
Subject-aware contrastive learning for biosignals. arXiv preprint
arXiv:2007.04871.
.. [2] Mohsenvand, M. N., Izadi, M. R., & Maes, P. (2020). Contrastive
Representation Learning for Electroencephalogram Classification. In
Machine Learning for Health (pp. 238-253). PMLR.
"""
operation = staticmethod(bandstop_filter) # type: ignore[assignment]
def __init__(
self, probability, sfreq, bandwidth=1, max_freq=None, random_state=None
):
super().__init__(
probability=probability,
random_state=random_state,
)
assert (
isinstance(bandwidth, Real) and bandwidth >= 0
), "bandwidth should be a non-negative float."
assert (
isinstance(sfreq, Real) and sfreq > 0
), "sfreq should be a positive float."
if max_freq is not None:
assert (
isinstance(max_freq, Real) and max_freq > 0
), "max_freq should be a positive float."
nyq = sfreq / 2
if max_freq is None or max_freq > nyq:
max_freq = nyq
warnings.warn(
"You either passed None or a frequency greater than the"
f" Nyquist frequency ({nyq} Hz)."
f" Falling back to max_freq = {nyq}."
)
assert (
bandwidth < max_freq
), f"`bandwidth` needs to be smaller than max_freq={max_freq}"
# override bandwidth value when a magnitude is passed
self.sfreq = sfreq
self.max_freq = max_freq
self.bandwidth = bandwidth
def get_augmentation_params(self, *batch):
"""Return transform parameters.
Parameters
----------
X : tensor.Tensor
The data.
y : tensor.Tensor
The labels.
Returns
-------
params : dict
Contains
* sfreq : float
Sampling frequency of the signals to be filtered.
* bandwidth : float
Bandwidth of the filter, i.e. distance between the low and high
cut frequencies.
* freqs_to_notch : array-like | None
Array of floats of size ``(batch_size,)`` containing the center
of the frequency band to filter out for each sample in the
batch. Frequencies should be greater than
``bandwidth/2 + transition`` and lower than
``sfreq/2 - bandwidth/2 - transition`` (where
``transition = 1 Hz``).
"""
if len(batch) == 0:
return super().get_augmentation_params(*batch)
X = batch[0]
# Prevents transitions from going below 0 and above max_freq
notched_freqs = self.rng.uniform(
low=1 + 2 * self.bandwidth,
high=self.max_freq - 1 - 2 * self.bandwidth,
size=X.shape[0],
)
return {
"sfreq": self.sfreq,
"bandwidth": self.bandwidth,
"freqs_to_notch": notched_freqs,
}
class FrequencyShift(Transform):
"""Add a random shift in the frequency domain to all channels.
Note that here, the shift is the same for all channels of a single example.
Parameters
----------
probability : float
Float setting the probability of applying the operation.
sfreq : float
Sampling frequency of the signals to be transformed.
max_delta_freq : float | torch.Tensor, optional
Maximum shift in Hz that can be sampled (in absolute value).
Defaults to 2 (shift sampled between -2 and 2 Hz).
random_state: int | numpy.random.Generator, optional
Seed to be used to instantiate numpy random number generator instance.
Defaults to None.
"""
operation = staticmethod(frequency_shift) # type: ignore[assignment]
def __init__(self, probability, sfreq, max_delta_freq=2, random_state=None):
super().__init__(
probability=probability,
random_state=random_state,
)
assert (
isinstance(sfreq, Real) and sfreq > 0
), "sfreq should be a positive float."
self.sfreq = sfreq
self.max_delta_freq = max_delta_freq
def get_augmentation_params(self, *batch):
"""Return transform parameters.
Parameters
----------
X : tensor.Tensor
The data.
y : tensor.Tensor
The labels.
Returns
-------
params : dict
Contains
* delta_freq : float
The amplitude of the frequency shift (in Hz).
* sfreq : float
Sampling frequency of the signals to be transformed.
"""
if len(batch) == 0:
return super().get_augmentation_params(*batch)
X = batch[0]
u = torch.as_tensor(self.rng.uniform(size=X.shape[0]), device=X.device)
max_delta_freq = self.max_delta_freq
if isinstance(max_delta_freq, torch.Tensor):
max_delta_freq = max_delta_freq.to(X.device)
delta_freq = u * 2 * max_delta_freq - max_delta_freq
return {
"delta_freq": delta_freq,
"sfreq": self.sfreq,
}
def _get_standard_10_20_positions(raw_or_epoch=None, ordered_ch_names=None):
"""Returns standard 10-20 sensors position matrix (for instantiating
SensorsRotation for example).
Parameters
----------
raw_or_epoch : mne.io.Raw | mne.Epoch, optional
Example of raw or epoch to retrieve ordered channels list from. Need to
be named as in 10-20. By default None.
ordered_ch_names : list, optional
List of strings representing the channels of the montage considered.
The order has to be consistent with the order of channels in the input
matrices that will be fed to `SensorsRotation` transform. By
default None.
"""
assert (
raw_or_epoch is not None or ordered_ch_names is not None
), "At least one of raw_or_epoch and ordered_ch_names is needed."
if ordered_ch_names is None:
ordered_ch_names = raw_or_epoch.info["ch_names"]
ten_twenty_montage = make_standard_montage("standard_1020")
positions_dict = ten_twenty_montage.get_positions()["ch_pos"]
positions_subdict = {
k: positions_dict[k] for k in ordered_ch_names if k in positions_dict
}
return np.stack(list(positions_subdict.values())).T
class SensorsRotation(Transform):
"""Interpolates EEG signals over sensors rotated around the desired axis
with an angle sampled uniformly between ``-max_degree`` and ``max_degree``.
Suggested in [1]_
Parameters
----------
probability : float
Float setting the probability of applying the operation.
sensors_positions_matrix : numpy.ndarray
Matrix giving the positions of each sensor in a 3D cartesian coordinate
system. Should have shape (3, n_channels), where n_channels is the
number of channels. Standard 10-20 positions can be obtained from
`mne` through::
>>> ten_twenty_montage = mne.channels.make_standard_montage(
... 'standard_1020'
... ).get_positions()['ch_pos']
axis : 'x' | 'y' | 'z', optional
Axis around which to rotate. Defaults to 'z'.
max_degree : float, optional
Maximum rotation. Rotation angles will be sampled between
``-max_degree`` and ``max_degree``. Defaults to 15 degrees.
spherical_splines : bool, optional
Whether to use spherical splines for the interpolation or not. When
``False``, standard scipy.interpolate.Rbf (with quadratic kernel) will
be used (as in the original paper). Defaults to True.
random_state: int | numpy.random.Generator, optional
Seed to be used to instantiate numpy random number generator instance.
Defaults to None.
References
----------
.. [1] Krell, M. M., & Kim, S. K. (2017). Rotational data augmentation for
electroencephalographic data. In 2017 39th Annual International
Conference of the IEEE Engineering in Medicine and Biology Society
(EMBC) (pp. 471-474).
"""
operation = staticmethod(sensors_rotation) # type: ignore[assignment]
def __init__(
self,
probability,
sensors_positions_matrix,
axis="z",
max_degrees=15,
spherical_splines=True,
random_state=None,
):
super().__init__(probability=probability, random_state=random_state)
if isinstance(sensors_positions_matrix, (np.ndarray, list)):
sensors_positions_matrix = torch.as_tensor(sensors_positions_matrix)
assert isinstance(
sensors_positions_matrix, torch.Tensor
), "sensors_positions should be an Tensor"
assert (
isinstance(max_degrees, (Real, torch.Tensor)) and max_degrees >= 0
), "max_degrees should be non-negative float."
assert isinstance(axis, str) and axis in [
"x",
"y",
"z",
], "axis can be either x, y or z."
assert (
sensors_positions_matrix.shape[0] == 3
), "sensors_positions_matrix shape should be 3 x n_channels."
assert isinstance(
spherical_splines, bool
), "spherical_splines should be a boolean"
self.sensors_positions_matrix = sensors_positions_matrix
self.axis = axis
self.spherical_splines = spherical_splines
self.max_degrees = max_degrees
def get_augmentation_params(self, *batch):
"""Return transform parameters.
Parameters
----------
X : tensor.Tensor
The data.
y : tensor.Tensor
The labels.
Returns
-------
params : dict
Contains four elements:
* sensors_positions_matrix : numpy.ndarray
Matrix giving the positions of each sensor in a 3D cartesian
coordinate system. Should have shape (3, n_channels), where
n_channels is the number of channels.
* axis : 'x' | 'y' | 'z'
Axis around which to rotate.
* angles : array-like
Array of float of shape ``(batch_size,)`` containing the
rotation angles (in degrees) for each element of the input
batch, sampled uniformly between ``-max_degrees``and
``max_degrees``.
* spherical_splines : bool
Whether to use spherical splines for the interpolation or not.
When ``False``, standard scipy.interpolate.Rbf (with quadratic
kernel) will be used (as in the original paper).
"""
if len(batch) == 0:
return super().get_augmentation_params(*batch)
X = batch[0]
u = self.rng.uniform(low=0, high=1, size=X.shape[0])
max_degrees = self.max_degrees
if isinstance(max_degrees, torch.Tensor):
max_degrees = max_degrees.to(X.device)
random_angles = (
torch.as_tensor(u, device=X.device) * 2 * max_degrees - max_degrees
)
return {
"sensors_positions_matrix": self.sensors_positions_matrix,
"axis": self.axis,
"angles": random_angles,
"spherical_splines": self.spherical_splines,
}
class SensorsZRotation(SensorsRotation):
"""Interpolates EEG signals over sensors rotated around the Z axis
with an angle sampled uniformly between ``-max_degree`` and ``max_degree``.
Suggested in [1]_
Parameters
----------
probability : float
Float setting the probability of applying the operation.
ordered_ch_names : list
List of strings representing the channels of the montage considered.
Has to be in standard 10-20 style. The order has to be consistent with
the order of channels in the input matrices that will be fed to the
transform. This channel will be used to compute approximate sensors
positions from a standard 10-20 montage.
max_degree : float, optional
Maximum rotation. Rotation angles will be sampled between
``-max_degree`` and ``max_degree``. Defaults to 15 degrees.
spherical_splines : bool, optional
Whether to use spherical splines for the interpolation or not. When
``False``, standard scipy.interpolate.Rbf (with quadratic kernel) will
be used (as in the original paper). Defaults to True.
random_state: int | numpy.random.Generator, optional
Seed to be used to instantiate numpy random number generator instance.
Defaults to None.
References
----------
.. [1] Krell, M. M., & Kim, S. K. (2017). Rotational data augmentation for
electroencephalographic data. In 2017 39th Annual International
Conference of the IEEE Engineering in Medicine and Biology Society
(EMBC) (pp. 471-474).
"""
def __init__(
self,
probability,
ordered_ch_names,
max_degrees=15,
spherical_splines=True,
random_state=None,
):
sensors_positions_matrix = torch.as_tensor(
_get_standard_10_20_positions(ordered_ch_names=ordered_ch_names)
)
super().__init__(
probability=probability,
sensors_positions_matrix=sensors_positions_matrix,
axis="z",
max_degrees=max_degrees,
spherical_splines=spherical_splines,
random_state=random_state,
)
class SensorsYRotation(SensorsRotation):
"""Interpolates EEG signals over sensors rotated around the Y axis
with an angle sampled uniformly between ``-max_degree`` and ``max_degree``.
Suggested in [1]_
Parameters
----------
probability : float
Float setting the probability of applying the operation.
ordered_ch_names : list
List of strings representing the channels of the montage considered.
Has to be in standard 10-20 style. The order has to be consistent with
the order of channels in the input matrices that will be fed to the
transform. This channel will be used to compute approximate sensors
positions from a standard 10-20 montage.
max_degree : float, optional
Maximum rotation. Rotation angles will be sampled between
``-max_degree`` and ``max_degree``. Defaults to 15 degrees.
spherical_splines : bool, optional
Whether to use spherical splines for the interpolation or not. When
``False``, standard scipy.interpolate.Rbf (with quadratic kernel) will
be used (as in the original paper). Defaults to True.
random_state: int | numpy.random.Generator, optional
Seed to be used to instantiate numpy random number generator instance.
Defaults to None.
References
----------
.. [1] Krell, M. M., & Kim, S. K. (2017). Rotational data augmentation for
electroencephalographic data. In 2017 39th Annual International
Conference of the IEEE Engineering in Medicine and Biology Society
(EMBC) (pp. 471-474).
"""
def __init__(
self,
probability,
ordered_ch_names,
max_degrees=15,
spherical_splines=True,
random_state=None,
):
sensors_positions_matrix = torch.as_tensor(
_get_standard_10_20_positions(ordered_ch_names=ordered_ch_names)
)
super().__init__(
probability=probability,
sensors_positions_matrix=sensors_positions_matrix,
axis="y",
max_degrees=max_degrees,
spherical_splines=spherical_splines,
random_state=random_state,
)
class SensorsXRotation(SensorsRotation):
"""Interpolates EEG signals over sensors rotated around the X axis
with an angle sampled uniformly between ``-max_degree`` and ``max_degree``.
Suggested in [1]_
Parameters
----------
probability : float
Float setting the probability of applying the operation.
ordered_ch_names : list
List of strings representing the channels of the montage considered.
Has to be in standard 10-20 style. The order has to be consistent with
the order of channels in the input matrices that will be fed to the
transform. This channel will be used to compute approximate sensors
positions from a standard 10-20 montage.
max_degree : float, optional
Maximum rotation. Rotation angles will be sampled between
``-max_degree`` and ``max_degree``. Defaults to 15 degrees.
spherical_splines : bool, optional
Whether to use spherical splines for the interpolation or not. When
``False``, standard scipy.interpolate.Rbf (with quadratic kernel) will
be used (as in the original paper). Defaults to True.
random_state: int | numpy.random.Generator, optional
Seed to be used to instantiate numpy random number generator instance.
Defaults to None.
References
----------
.. [1] Krell, M. M., & Kim, S. K. (2017). Rotational data augmentation for
electroencephalographic data. In 2017 39th Annual International
Conference of the IEEE Engineering in Medicine and Biology Society
(EMBC) (pp. 471-474).
"""
def __init__(
self,
probability,
ordered_ch_names,
max_degrees=15,
spherical_splines=True,
random_state=None,
):
sensors_positions_matrix = torch.as_tensor(
_get_standard_10_20_positions(ordered_ch_names=ordered_ch_names)
)
super().__init__(
probability=probability,
sensors_positions_matrix=sensors_positions_matrix,
axis="x",
max_degrees=max_degrees,
spherical_splines=spherical_splines,
random_state=random_state,
)
class Mixup(Transform):
"""Implements Iterator for Mixup for EEG data. See [1]_.
Implementation based on [2]_.
Parameters