File: test_ems.py

package info (click to toggle)
python-mne 1.9.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 131,492 kB
  • sloc: python: 213,302; javascript: 12,910; sh: 447; makefile: 144
file content (93 lines) | stat: -rw-r--r-- 3,133 bytes parent folder | download
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
# Authors: The MNE-Python contributors.
# License: BSD-3-Clause
# Copyright the MNE-Python contributors.

from pathlib import Path

import numpy as np
import pytest
from numpy.testing import assert_array_almost_equal, assert_equal

pytest.importorskip("sklearn")

from sklearn.model_selection import StratifiedKFold

from mne import Epochs, io, pick_types, read_events
from mne.decoding import EMS, compute_ems

data_dir = Path(__file__).parents[2] / "io" / "tests" / "data"
raw_fname = data_dir / "test_raw.fif"
event_name = data_dir / "test-eve.fif"
tmin, tmax = -0.2, 0.5
event_id = dict(aud_l=1, vis_l=3)


def test_ems():
    """Test event-matched spatial filters."""
    raw = io.read_raw_fif(raw_fname, preload=False)

    # create unequal number of events
    events = read_events(event_name)
    events[-2, 2] = 3
    picks = pick_types(
        raw.info, meg=True, stim=False, ecg=False, eog=False, exclude="bads"
    )
    picks = picks[1:13:3]
    epochs = Epochs(
        raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), preload=True
    )
    pytest.raises(ValueError, compute_ems, epochs, ["aud_l", "vis_l"])
    epochs.equalize_event_counts(epochs.event_id)

    pytest.raises(KeyError, compute_ems, epochs, ["blah", "hahah"])
    surrogates, filters, conditions = compute_ems(epochs)
    assert_equal(list(set(conditions)), [1, 3])

    events = read_events(event_name)
    event_id2 = dict(aud_l=1, aud_r=2, vis_l=3)
    epochs = Epochs(
        raw,
        events,
        event_id2,
        tmin,
        tmax,
        picks=picks,
        baseline=(None, 0),
        preload=True,
    )
    epochs.equalize_event_counts(epochs.event_id)

    n_expected = sum([len(epochs[k]) for k in ["aud_l", "vis_l"]])

    pytest.raises(ValueError, compute_ems, epochs)
    surrogates, filters, conditions = compute_ems(epochs, ["aud_r", "vis_l"])
    assert_equal(n_expected, len(surrogates))
    assert_equal(n_expected, len(conditions))
    assert_equal(list(set(conditions)), [2, 3])

    # test compute_ems cv
    epochs = epochs["aud_r", "vis_l"]
    epochs.equalize_event_counts(epochs.event_id)
    cv = StratifiedKFold(n_splits=3)
    compute_ems(epochs, cv=cv)
    compute_ems(epochs, cv=2)
    pytest.raises(ValueError, compute_ems, epochs, cv="foo")
    pytest.raises(ValueError, compute_ems, epochs, cv=len(epochs) + 1)
    raw.close()

    # EMS transformer, check that identical to compute_ems
    X = epochs.get_data(copy=False)
    y = epochs.events[:, 2]
    X = X / np.std(X)  # X scaled outside cv in compute_ems
    Xt, coefs = list(), list()
    ems = EMS()
    assert_equal(ems.__repr__(), "<EMS: not fitted.>")
    # manual leave-one-out to avoid sklearn version problem
    for test in range(len(y)):
        train = np.setdiff1d(range(len(y)), np.atleast_1d(test))
        ems.fit(X[train], y[train])
        coefs.append(ems.filters_)
        Xt.append(ems.transform(X[[test]]))
    assert_equal(ems.__repr__(), "<EMS: fitted with 4 filters on 2 classes.>")
    assert_array_almost_equal(filters, np.mean(coefs, axis=0))
    assert_array_almost_equal(surrogates, np.vstack(Xt))