-
Notifications
You must be signed in to change notification settings - Fork 165
/
motor_imagery.py
424 lines (335 loc) · 13 KB
/
motor_imagery.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
"""Motor Imagery Paradigms"""
import abc
import logging
from moabb.datasets import utils
from moabb.datasets.fake import FakeDataset
from moabb.paradigms.base import BaseParadigm
log = logging.getLogger(__name__)
class BaseMotorImagery(BaseParadigm):
"""Base Motor imagery paradigm.
Please use one of the child classes
Parameters
----------
filters: list of list (defaults [[7, 35]])
bank of bandpass filter to apply.
events: List of str | None (default None)
event to use for epoching. If None, default to all events defined in
the dataset.
tmin: float (default 0.0)
Start time (in second) of the epoch, relative to the dataset specific
task interval e.g. tmin = 1 would mean the epoch will start 1 second
after the beginning of the task as defined by the dataset.
tmax: float | None, (default None)
End time (in second) of the epoch, relative to the beginning of the
dataset specific task interval. tmax = 5 would mean the epoch will end
5 second after the beginning of the task as defined in the dataset. If
None, use the dataset value.
baseline: None | tuple of length 2
The time interval to consider as “baseline” when applying baseline
correction. If None, do not apply baseline correction.
If a tuple (a, b), the interval is between a and b (in seconds),
including the endpoints.
Correction is applied by computing the mean of the baseline period
and subtracting it from the data (see mne.Epochs)
channels: list of str | None (default None)
list of channel to select. If None, use all EEG channels available in
the dataset.
resample: float | None (default None)
If not None, resample the eeg data with the sampling rate provided.
"""
def __init__(
self,
filters=([7, 35],),
events=None,
tmin=0.0,
tmax=None,
baseline=None,
channels=None,
resample=None,
):
super().__init__()
self.filters = filters
self.events = events
self.channels = channels
self.baseline = baseline
self.resample = resample
if tmax is not None:
if tmin >= tmax:
raise (ValueError("tmax must be greater than tmin"))
self.tmin = tmin
self.tmax = tmax
def is_valid(self, dataset):
ret = True
if not (dataset.paradigm == "imagery"):
ret = False
# check if dataset has required events
if self.events:
if not set(self.events) <= set(dataset.event_id.keys()):
ret = False
# we should verify list of channels, somehow
return ret
@abc.abstractmethod
def used_events(self, dataset):
pass
@property
def datasets(self):
if self.tmax is None:
interval = None
else:
interval = self.tmax - self.tmin
return utils.dataset_search(
paradigm="imagery", events=self.events, interval=interval, has_all_events=True
)
@property
def scoring(self):
return "accuracy"
class SinglePass(BaseMotorImagery):
"""Single Bandpass filter motor Imagery.
Motor imagery paradigm with only one bandpass filter (default 8 to 32 Hz)
Parameters
----------
fmin: float (default 8)
cutoff frequency (Hz) for the high pass filter
fmax: float (default 32)
cutoff frequency (Hz) for the low pass filter
events: List of str | None (default None)
event to use for epoching. If None, default to all events defined in
the dataset.
tmin: float (default 0.0)
Start time (in second) of the epoch, relative to the dataset specific
task interval e.g. tmin = 1 would mean the epoch will start 1 second
after the beginning of the task as defined by the dataset.
tmax: float | None, (default None)
End time (in second) of the epoch, relative to the beginning of the
dataset specific task interval. tmax = 5 would mean the epoch will end
5 second after the beginning of the task as defined in the dataset. If
None, use the dataset value.
baseline: None | tuple of length 2
The time interval to consider as “baseline” when applying baseline
correction. If None, do not apply baseline correction.
If a tuple (a, b), the interval is between a and b (in seconds),
including the endpoints.
Correction is applied by computing the mean of the baseline period
and subtracting it from the data (see mne.Epochs)
channels: list of str | None (default None)
list of channel to select. If None, use all EEG channels available in
the dataset.
resample: float | None (default None)
If not None, resample the eeg data with the sampling rate provided.
"""
def __init__(self, fmin=8, fmax=32, **kwargs):
if "filters" in kwargs.keys():
raise (ValueError("MotorImagery does not take argument filters"))
super().__init__(filters=[[fmin, fmax]], **kwargs)
class FilterBank(BaseMotorImagery):
"""Filter Bank MI."""
def __init__(
self,
filters=([8, 12], [12, 16], [16, 20], [20, 24], [24, 28], [28, 32]),
**kwargs,
):
"""init"""
super().__init__(filters=filters, **kwargs)
class LeftRightImagery(SinglePass):
"""Motor Imagery for left hand/right hand classification
Metric is 'roc_auc'
"""
def __init__(self, **kwargs):
if "events" in kwargs.keys():
raise (ValueError("LeftRightImagery dont accept events"))
super().__init__(events=["left_hand", "right_hand"], **kwargs)
def used_events(self, dataset):
return {ev: dataset.event_id[ev] for ev in self.events}
@property
def scoring(self):
return "roc_auc"
class FilterBankLeftRightImagery(FilterBank):
"""Filter Bank Motor Imagery for left hand/right hand classification
Metric is 'roc_auc'
"""
def __init__(self, **kwargs):
if "events" in kwargs.keys():
raise (ValueError("LeftRightImagery dont accept events"))
super().__init__(events=["left_hand", "right_hand"], **kwargs)
def used_events(self, dataset):
return {ev: dataset.event_id[ev] for ev in self.events}
@property
def scoring(self):
return "roc_auc"
class FilterBankMotorImagery(FilterBank):
"""
Filter bank n-class motor imagery.
Metric is 'roc-auc' if 2 classes and 'accuracy' if more
Parameters
-----------
events: List of str
event labels used to filter datasets (e.g. if only motor imagery is
desired).
n_classes: int,
number of classes each dataset must have. If events is given,
requires all imagery sorts to be within the events list.
"""
def __init__(self, n_classes=2, **kwargs):
"docstring"
super().__init__(**kwargs)
self.n_classes = n_classes
if self.events is None:
log.warning("Choosing from all possible events")
else:
assert n_classes <= len(self.events), "More classes than events specified"
def is_valid(self, dataset):
ret = True
if not dataset.paradigm == "imagery":
ret = False
if self.events is None:
if not len(dataset.event_id) >= self.n_classes:
ret = False
else:
overlap = len(set(self.events) & set(dataset.event_id.keys()))
if not overlap >= self.n_classes:
ret = False
return ret
def used_events(self, dataset):
out = {}
if self.events is None:
for k, v in dataset.event_id.items():
out[k] = v
if len(out) == self.n_classes:
break
else:
for event in self.events:
if event in dataset.event_id.keys():
out[event] = dataset.event_id[event]
if len(out) == self.n_classes:
break
if len(out) < self.n_classes:
raise (
ValueError(
f"Dataset {dataset.code} did not have enough "
f"events in {self.events} to run analysis"
)
)
return out
@property
def datasets(self):
if self.tmax is None:
interval = None
else:
interval = self.tmax - self.tmin
return utils.dataset_search(
paradigm="imagery",
events=self.events,
interval=interval,
has_all_events=False,
)
@property
def scoring(self):
if self.n_classes == 2:
return "roc_auc"
else:
return "accuracy"
class MotorImagery(SinglePass):
"""
N-class motor imagery.
Metric is 'roc-auc' if 2 classes and 'accuracy' if more
Parameters
-----------
events: List of str
event labels used to filter datasets (e.g. if only motor imagery is
desired).
n_classes: int,
number of classes each dataset must have. If events is given,
requires all imagery sorts to be within the events list.
fmin: float (default 8)
cutoff frequency (Hz) for the high pass filter
fmax: float (default 32)
cutoff frequency (Hz) for the low pass filter
tmin: float (default 0.0)
Start time (in second) of the epoch, relative to the dataset specific
task interval e.g. tmin = 1 would mean the epoch will start 1 second
after the beginning of the task as defined by the dataset.
tmax: float | None, (default None)
End time (in second) of the epoch, relative to the beginning of the
dataset specific task interval. tmax = 5 would mean the epoch will end
5 second after the beginning of the task as defined in the dataset. If
None, use the dataset value.
baseline: None | tuple of length 2
The time interval to consider as “baseline” when applying baseline
correction. If None, do not apply baseline correction.
If a tuple (a, b), the interval is between a and b (in seconds),
including the endpoints.
Correction is applied by computing the mean of the baseline period
and subtracting it from the data (see mne.Epochs)
channels: list of str | None (default None)
list of channel to select. If None, use all EEG channels available in
the dataset.
resample: float | None (default None)
If not None, resample the eeg data with the sampling rate provided.
"""
def __init__(self, n_classes=None, **kwargs):
super().__init__(**kwargs)
self.n_classes = n_classes
if self.events is None:
log.warning("Choosing from all possible events")
elif self.n_classes is not None:
assert n_classes <= len(self.events), "More classes than events specified"
def is_valid(self, dataset):
ret = True
if not dataset.paradigm == "imagery":
ret = False
elif self.n_classes is None and self.events is None:
pass
elif self.events is None:
if not len(dataset.event_id) >= self.n_classes:
ret = False
else:
overlap = len(set(self.events) & set(dataset.event_id.keys()))
if self.n_classes is not None and not overlap >= self.n_classes:
ret = False
return ret
def used_events(self, dataset):
out = {}
if self.events is None:
for k, v in dataset.event_id.items():
out[k] = v
if self.n_classes is None:
self.n_classes = len(out)
else:
for event in self.events:
if event in dataset.event_id.keys():
out[event] = dataset.event_id[event]
if len(out) == self.n_classes:
break
if len(out) < self.n_classes:
raise (
ValueError(
f"Dataset {dataset.code} did not have enough "
f"events in {self.events} to run analysis"
)
)
return out
@property
def datasets(self):
if self.tmax is None:
interval = None
else:
interval = self.tmax - self.tmin
return utils.dataset_search(
paradigm="imagery",
events=self.events,
interval=interval,
has_all_events=False,
)
@property
def scoring(self):
if self.n_classes == 2:
return "roc_auc"
else:
return "accuracy"
class FakeImageryParadigm(LeftRightImagery):
"""Fake Imagery for left hand/right hand classification."""
@property
def datasets(self):
return [FakeDataset(["left_hand", "right_hand"], paradigm="imagery")]
def is_valid(self, dataset):
return True