Пример #1
0
def test_io_layout_lay():
    """Test IO with .lay files"""
    tempdir = _TempDir()
    layout = read_layout("CTF151", scale=False)
    layout.save(op.join(tempdir, "foobar.lay"))
    layout_read = read_layout(op.join(tempdir, "foobar.lay"), path="./", scale=False)
    assert_array_almost_equal(layout.pos, layout_read.pos, decimal=2)
    assert_true(layout.names, layout_read.names)
Пример #2
0
def test_io_layout_lay():
    """Test IO with .lay files."""
    tempdir = _TempDir()
    layout = read_layout('CTF151', scale=False)
    layout.save(op.join(tempdir, 'foobar.lay'))
    layout_read = read_layout(op.join(tempdir, 'foobar.lay'), path='./',
                              scale=False)
    assert_array_almost_equal(layout.pos, layout_read.pos, decimal=2)
    assert layout.names == layout_read.names
Пример #3
0
def test_io_layout_lout():
    """Test IO with .lout files."""
    tempdir = _TempDir()
    layout = read_layout('Vectorview-all', scale=False)
    layout.save(op.join(tempdir, 'foobar.lout'))
    layout_read = read_layout(op.join(tempdir, 'foobar.lout'), path='./',
                              scale=False)
    assert_array_almost_equal(layout.pos, layout_read.pos, decimal=2)
    assert layout.names == layout_read.names
    print(layout)  # test repr
Пример #4
0
def test_io_layout_lout():
    """Test IO with .lout files"""
    tempdir = _TempDir()
    layout = read_layout("Vectorview-all", scale=False)
    layout.save(op.join(tempdir, "foobar.lout"))
    layout_read = read_layout(op.join(tempdir, "foobar.lout"), path="./", scale=False)
    assert_array_almost_equal(layout.pos, layout_read.pos, decimal=2)
    assert_true(layout.names, layout_read.names)

    print(layout)  # test repr
Пример #5
0
def test_make_grid_layout():
    """Test creation of grid layout"""
    tempdir = _TempDir()
    tmp_name = 'bar'
    lout_name = 'test_ica'
    lout_orig = read_layout(kind=lout_name, path=lout_path)
    layout = make_grid_layout(test_info)
    layout.save(op.join(tempdir, tmp_name + '.lout'))
    lout_new = read_layout(kind=tmp_name, path=tempdir)
    assert_array_equal(lout_new.kind, tmp_name)
    assert_array_equal(lout_orig.pos, lout_new.pos)
    assert_array_equal(lout_orig.names, lout_new.names)

    # Test creating grid layout with specified number of columns
    layout = make_grid_layout(test_info, n_col=2)
    # Vertical positions should be equal
    assert_true(layout.pos[0, 1] == layout.pos[1, 1])
    # Horizontal positions should be unequal
    assert_true(layout.pos[0, 0] != layout.pos[1, 0])
    # Box sizes should be equal
    assert_array_equal(layout.pos[0, 3:], layout.pos[1, 3:])
Пример #6
0
def test_make_eeg_layout():
    """Test creation of EEG layout"""
    tempdir = _TempDir()
    tmp_name = 'foo'
    lout_name = 'test_raw'
    lout_orig = read_layout(kind=lout_name, path=lout_path)
    info = Raw(fif_fname).info
    layout = make_eeg_layout(info)
    layout.save(op.join(tempdir, tmp_name + '.lout'))
    lout_new = read_layout(kind=tmp_name, path=tempdir, scale=False)
    assert_array_equal(lout_new.kind, tmp_name)
    assert_allclose(layout.pos, lout_new.pos, atol=0.1)
    assert_array_equal(lout_orig.names, lout_new.names)

    # Test input validation
    assert_raises(ValueError, make_eeg_layout, info, radius=-0.1)
    assert_raises(ValueError, make_eeg_layout, info, radius=0.6)
    assert_raises(ValueError, make_eeg_layout, info, width=-0.1)
    assert_raises(ValueError, make_eeg_layout, info, width=1.1)
    assert_raises(ValueError, make_eeg_layout, info, height=-0.1)
    assert_raises(ValueError, make_eeg_layout, info, height=1.1)
Пример #7
0
def test_make_eeg_layout():
    """Test creation of EEG layout"""
    tempdir = _TempDir()
    tmp_name = "foo"
    lout_name = "test_raw"
    lout_orig = read_layout(kind=lout_name, path=lout_path)
    info = Raw(fif_fname).info
    info["bads"].append(info["ch_names"][360])
    layout = make_eeg_layout(info, exclude=[])
    assert_array_equal(len(layout.names), len([ch for ch in info["ch_names"] if ch.startswith("EE")]))
    layout.save(op.join(tempdir, tmp_name + ".lout"))
    lout_new = read_layout(kind=tmp_name, path=tempdir, scale=False)
    assert_array_equal(lout_new.kind, tmp_name)
    assert_allclose(layout.pos, lout_new.pos, atol=0.1)
    assert_array_equal(lout_orig.names, lout_new.names)

    # Test input validation
    assert_raises(ValueError, make_eeg_layout, info, radius=-0.1)
    assert_raises(ValueError, make_eeg_layout, info, radius=0.6)
    assert_raises(ValueError, make_eeg_layout, info, width=-0.1)
    assert_raises(ValueError, make_eeg_layout, info, width=1.1)
    assert_raises(ValueError, make_eeg_layout, info, height=-0.1)
    assert_raises(ValueError, make_eeg_layout, info, height=1.1)
Пример #8
0
def test_make_eeg_layout():
    """Test creation of EEG layout."""
    tempdir = _TempDir()
    tmp_name = 'foo'
    lout_name = 'test_raw'
    lout_orig = read_layout(kind=lout_name, path=lout_path)
    info = read_info(fif_fname)
    info['bads'].append(info['ch_names'][360])
    layout = make_eeg_layout(info, exclude=[])
    assert_array_equal(len(layout.names), len([ch for ch in info['ch_names']
                                               if ch.startswith('EE')]))
    layout.save(op.join(tempdir, tmp_name + '.lout'))
    lout_new = read_layout(kind=tmp_name, path=tempdir, scale=False)
    assert_array_equal(lout_new.kind, tmp_name)
    assert_allclose(layout.pos, lout_new.pos, atol=0.1)
    assert_array_equal(lout_orig.names, lout_new.names)

    # Test input validation
    pytest.raises(ValueError, make_eeg_layout, info, radius=-0.1)
    pytest.raises(ValueError, make_eeg_layout, info, radius=0.6)
    pytest.raises(ValueError, make_eeg_layout, info, width=-0.1)
    pytest.raises(ValueError, make_eeg_layout, info, width=1.1)
    pytest.raises(ValueError, make_eeg_layout, info, height=-0.1)
    pytest.raises(ValueError, make_eeg_layout, info, height=1.1)
Пример #9
0
# Set our plotters to test mode
import matplotlib

matplotlib.use("Agg")  # for testing don't use X server
import matplotlib.pyplot as plt  # noqa

warnings.simplefilter("always")  # enable b/c these tests throw warnings


base_dir = op.join(op.dirname(__file__), "..", "..", "io", "tests", "data")
evoked_fname = op.join(base_dir, "test-ave.fif")
raw_fname = op.join(base_dir, "test_raw.fif")
event_name = op.join(base_dir, "test-eve.fif")
event_id, tmin, tmax = 1, -0.2, 0.2
layout = read_layout("Vectorview-all")


def _get_raw():
    return io.Raw(raw_fname, preload=False)


def _get_events():
    return read_events(event_name)


def _get_picks(raw):
    return [0, 1, 2, 6, 7, 8, 12, 13, 14]  # take a only few channels


def _get_epochs():
Пример #10
0
scores = cross_val_score(clf, epochs_data_train, labels, cv=cv, n_jobs=1)

# Printing the results
class_balance = np.mean(labels == labels[0])
class_balance = max(class_balance, 1. - class_balance)
print("Classification accuracy: %f / Chance level: %f" % (np.mean(scores),
                                                          class_balance))

# plot CSP patterns estimated on full data for visualization
csp.fit_transform(epochs_data, labels)

evoked = epochs.average()
evoked.data = csp.patterns_.T
evoked.times = np.arange(evoked.data.shape[0])

layout = read_layout('EEG1005')
evoked.plot_topomap(times=[0, 1, 2, 61, 62, 63], ch_type='eeg', layout=layout,
                    scale_time=1, time_format='%i', scale=1,
                    unit='Patterns (AU)', size=1.5)

###############################################################################
# Look at performance over time

sfreq = raw.info['sfreq']
w_length = int(sfreq * 0.5)   # running classifier: window length
w_step = int(sfreq * 0.1)  # running classifier: window step size
w_start = np.arange(0, epochs_data.shape[2] - w_length, w_step)

scores_windows = []

for train_idx, test_idx in cv:
Пример #11
0
def culc_by_csp_and_lda(subject,
                        runs=[6, 10, 14],
                        event_id=dict(hands=2, feet=3)):
    tmin, tmax = -1., 4.

    raw_fnames = eegbci.load_data(subject, runs)
    raw_files = [
        read_raw_edf(f, preload=True, stim_channel='auto') for f in raw_fnames
    ]
    raw = concatenate_raws(raw_files)

    # strip channel names of "." characters
    raw.rename_channels(lambda x: x.strip('.'))

    # Apply band-pass filter
    raw.filter(7., 30., fir_design='firwin', skip_by_annotation='edge')

    events = find_events(raw, shortest_event=0, stim_channel='STI 014')

    picks = pick_types(raw.info,
                       meg=False,
                       eeg=True,
                       stim=False,
                       eog=False,
                       exclude='bads')

    # Read epochs (train will be done only between 1 and 2s)
    # Testing will be done with a running classifier
    epochs = Epochs(raw,
                    events,
                    event_id,
                    tmin,
                    tmax,
                    proj=True,
                    picks=picks,
                    baseline=None,
                    preload=True)
    epochs_train = epochs.copy().crop(tmin=1., tmax=2.)
    labels = epochs.events[:, -1] - 2

    # -----------------------LDAによる分類----------------------------

    # モンテカルロ相互検証ジェネレータを定義する(分散を減らす):
    scores = []
    epochs_data = epochs.get_data()
    epochs_data_train = epochs_train.get_data()

    cv = KFold(n_splits=5)
    # cv = ShuffleSplit(10, test_size=0.2, random_state=42)

    lda = sklearn.discriminant_analysis.LinearDiscriminantAnalysis()
    # lda = svm.SVC()
    csp = mne.decoding.CSP(n_components=4,
                           reg=None,
                           log=True,
                           norm_trace=False)

    clf = sklearn.pipeline.Pipeline([('CSP', csp), ('SVM', lda)])
    scores = cross_val_score(clf, epochs_data_train, labels, cv=cv, n_jobs=1)

    class_balance = np.mean(labels == labels[0])  # 0と1のラベルの数の比率
    class_balance = max(class_balance, 1. - class_balance)
    print("Classification accuracy: %f / Chance level: %f" %
          (np.mean(scores), class_balance))

    # # 視覚化のための完全なデータで推定されたCSPパターンのプロット
    csp.fit_transform(epochs_data, labels)
    layout = read_layout('EEG1005')
    csp.plot_patterns(epochs.info,
                      layout=layout,
                      ch_type='eeg',
                      units='Patterns (AU)',
                      size=1.5)

    # ---------------------------時間の経過とともにパフォーマンスを調べる------------------------------

    sfreq = raw.info['sfreq']  # サンプルレート
    w_length = int(sfreq * 0.5)  # running classifier: window length
    w_step = int(sfreq * 0.1)  # running classifier: window step size
    w_start = np.arange(0, epochs_data.shape[2] - w_length, w_step)
    scores_windows = []

    for train_idx, test_idx in cv.split(epochs_data_train):
        y_train, y_test = labels[train_idx], labels[test_idx]

        # ----------- train---------------
        X_train = csp.fit_transform(epochs_data_train[train_idx], y_train)
        lda.fit(X_train, y_train)

        # ------------test---------------
        # running classifier: test classifier on sliding window
        score_this_window = []
        for n in w_start:
            data = epochs_data[test_idx][:, :, n:(n + w_length)]
            X_test = csp.transform(data)
            score_this_window.append(lda.score(X_test, y_test))
        scores_windows.append(score_this_window)

    # Plot scores over time
    w_times = (w_start + w_length / 2.) / sfreq + epochs.tmin

    plt.figure()
    plt.plot(w_times, np.mean(scores_windows, 0), label='Score')
    plt.axvline(0, linestyle='--', color='k', label='Onset')
    plt.axhline(0.5, linestyle='-', color='k', label='Chance')
    plt.xlabel('time (s)')
    plt.ylabel('classification accuracy')
    plt.title('Classification score over time')
    plt.legend(loc='lower right')
    # plt.savefig(str(path) + "_svm.png")
    plt.show()
Пример #12
0
    def main(self):

        raw1, events1 = self.load_data(1)

        event_dict = {'Main droite': 1, 'Deux pieds': 3}
        raw = []
        events = []
        epochs = []
        rawf = []
        tmin, tmax = -1., 4.
        scoresmean = []

        set_log_level(verbose='CRITICAL')

        for k in range(8):
            raws, eventss = self.load_data(k + 1)
            raw.append(raws)
            events.append(eventss)

            rawf.append(raw[k].copy().filter(8, 30, fir_design='firwin'))
            picks = pick_types(rawf[k].info,
                               meg=False,
                               eeg=True,
                               stim=False,
                               eog=False,
                               exclude='bads')

            epochs.append(
                Epochs(rawf[k],
                       events[k],
                       event_dict,
                       tmin,
                       tmax,
                       proj=True,
                       picks=picks,
                       baseline=None,
                       preload=True))

            labels = epochs[k].events[:, -1]

            scores = []
            epochs_data_train = epochs[k].get_data()
            cv = ShuffleSplit(10, test_size=0.2, random_state=42)

            #cv_split = cv.split(epochs_data_train)

            # Create the classifier model
            clf, csp = self.model(4)

            # Model Evaluation
            scores = self.evaluate(clf, epochs_data_train, cv, labels, 1)

            print("Subject %i, Classification accuracy: %f" %
                  (k + 1, np.mean(scores)))
            scoresmean.append(np.mean(scores))

            # CSP patterns estimated on full data
            csp.fit_transform(epochs_data_train, labels)

            if k == 2 or k == 6 or k == 19 or k == 7:
                layout = read_layout('eeg1005')
                csp.plot_patterns(epochs[k].info,
                                  layout=layout,
                                  ch_type='eeg',
                                  units='patterns (au)',
                                  size=1.5)

                plt.title("Subject %i, Classification accuracy: %f" %
                          (k + 1, np.mean(scores)))
                plt.show()

        # Eliminate artefacts
        reconst_raw = self.drop_artefacts(10, raw1, 0, 2)

        raw1.plot()
        reconst_raw.plot()
Пример #13
0
from mne.viz import (plot_topo_image_epochs, _get_presser,
                     mne_analyze_colormap, plot_evoked_topo)
from mne.viz.evoked import _line_plot_onselect
from mne.viz.utils import _fake_click

from mne.viz.topo import (_plot_update_evoked_topo_proj, iter_topography,
                          _imshow_tfr)

base_dir = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data')
evoked_fname = op.join(base_dir, 'test-ave.fif')
raw_fname = op.join(base_dir, 'test_raw.fif')
event_name = op.join(base_dir, 'test-eve.fif')
cov_fname = op.join(base_dir, 'test-cov.fif')
event_id, tmin, tmax = 1, -0.2, 0.2
layout = read_layout('Vectorview-all')


def _get_events():
    """Get events."""
    return read_events(event_name)


def _get_picks(raw):
    """Get picks."""
    return [0, 1, 2, 6, 7, 8, 306, 340, 341, 342]  # take a only few channels


def _get_epochs():
    """Get epochs."""
    raw = read_raw_fif(raw_fname)
Пример #14
0
epochs_data = epochs.get_data()

epochs.plot(picks=picks, scalings='auto', show=True, block=True)

epochs_data_train = epochs_train.get_data()
cv = ShuffleSplit(10, test_size=0.2, random_state=42)
cv_split = cv.split(epochs_data_train)

# Assemble a classifier
lda = LinearDiscriminantAnalysis()
csp = CSP(n_components=4, reg=None, log=True, norm_trace=False)

# Use scikit-learn Pipeline with cross_val_score function
clf = Pipeline([('CSP', csp), ('LDA', lda)])
scores = cross_val_score(clf, epochs_data_train, labels, cv=cv, n_jobs=1)

# Printing the results
class_balance = np.mean(labels == labels[0])
class_balance = max(class_balance, 1. - class_balance)
print("Classification accuracy: %f / Chance level: %f" %
      (np.mean(scores), class_balance))

# plot CSP patterns estimated on full data for visualization
csp.fit_transform(epochs_data, labels)

layout = read_layout('EEG1005')
csp.plot_patterns(epochs.info,
                  layout=layout,
                  ch_type='eeg',
                  units='Patterns (AU)',
                  size=1.5)
Пример #15
0
clf = Pipeline([("CSP", csp), ("SVC", svc)])
scores = cross_val_score(clf, epochs_data_train, labels, cv=cv, n_jobs=1)

# Printing the results
class_balance = np.mean(labels == labels[0])
class_balance = max(class_balance, 1.0 - class_balance)
print("Classification accuracy: %f / Chance level: %f" % (np.mean(scores), class_balance))

# plot CSP patterns estimated on full data for visualization
csp.fit_transform(epochs_data, labels)

evoked = epochs.average()
evoked.data = csp.patterns_.T
evoked.times = np.arange(evoked.data.shape[0])

layout = read_layout("EEG1005")
evoked.plot_topomap(
    times=[0, 1, 2, 61, 62, 63],
    ch_type="eeg",
    layout=layout,
    scale_time=1,
    time_format="%i",
    scale=1,
    unit="Patterns (AU)",
    size=1.5,
)

###############################################################################
# Look at performance over time

sfreq = raw.info["sfreq"]
Пример #16
0
X = meg_epochs.get_data()
y = emg_epochs.get_data().var(axis=2)[:, 0]  # target is EMG power

# Classification pipeline with SPoC spatial filtering and Ridge Regression
spoc = SPoC(n_components=2, log=True, reg='oas', rank='full')
clf = make_pipeline(spoc, Ridge())
# Define a two fold cross-validation
cv = KFold(n_splits=2, shuffle=False)

# Run cross validaton
y_preds = cross_val_predict(clf, X, y, cv=cv)

# Plot the True EMG power and the EMG power predicted from MEG data
fig, ax = plt.subplots(1, 1, figsize=[10, 4])
times = raw.times[meg_epochs.events[:, 0] - raw.first_samp]
ax.plot(times, y_preds, color='b', label='Predicted EMG')
ax.plot(times, y, color='r', label='True EMG')
ax.set_xlabel('Time (s)')
ax.set_ylabel('EMG Power')
ax.set_title('SPoC MEG Predictions')
plt.legend()
mne.viz.tight_layout()
plt.show()

##############################################################################
# Plot the contributions to the detected components (i.e., the forward model)

spoc.fit(X, y)
layout = read_layout('CTF151.lay')
spoc.plot_patterns(meg_epochs.info, layout=layout)
Пример #17
0
X = meg_epochs.get_data()
y = emg_epochs.get_data().var(axis=2)[:, 0]  # target is EMG power

# Classification pipeline with SPoC spatial filtering and Ridge Regression
spoc = SPoC(n_components=2, log=True, reg='oas', rank='full')
clf = make_pipeline(spoc, Ridge())
# Define a two fold cross-validation
cv = KFold(n_splits=2, shuffle=False)

# Run cross validaton
y_preds = cross_val_predict(clf, X, y, cv=cv)

# Plot the True EMG power and the EMG power predicted from MEG data
fig, ax = plt.subplots(1, 1, figsize=[10, 4])
times = raw.times[meg_epochs.events[:, 0] - raw.first_samp]
ax.plot(times, y_preds, color='b', label='Predicted EMG')
ax.plot(times, y, color='r', label='True EMG')
ax.set_xlabel('Time (s)')
ax.set_ylabel('EMG Power')
ax.set_title('SPoC MEG Predictions')
plt.legend()
mne.viz.tight_layout()
plt.show()

##############################################################################
# Plot the contributions to the detected components (i.e., the forward model)

spoc.fit(X, y)
layout = read_layout('CTF151.lay')
spoc.plot_patterns(meg_epochs.info, layout=layout)
Пример #18
0
# Set our plotters to test mode
import matplotlib
matplotlib.use('Agg')  # for testing don't use X server

warnings.simplefilter('always')  # enable b/c these tests throw warnings


base_dir = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data')
evoked_fname = op.join(base_dir, 'test-ave.fif')
raw_fname = op.join(base_dir, 'test_raw.fif')
cov_fname = op.join(base_dir, 'test-cov.fif')
event_name = op.join(base_dir, 'test-eve.fif')
event_id, tmin, tmax = 1, -0.1, 1.0
n_chan = 15
layout = read_layout('Vectorview-all')


def _get_raw():
    return io.Raw(raw_fname, preload=False)


def _get_events():
    return read_events(event_name)


def _get_picks(raw):
    return pick_types(raw.info, meg=True, eeg=False, stim=False,
                      ecg=False, eog=False, exclude='bads')

Пример #19
0
# %%
"""
Übung 2.4
*********

Beispielhafte Visualisierung eines Elektrodenlayouts

FÜr EEG-Aufzeichnungen bietet sich natürlich eine topographisch angepasste Heatmap an. Dazu benötigt man Information, wo im Raum jede Elektrode sitzt und kann dann durch Interpolation einen Oberfläche visualisieren.

Elektrodenposition sind standardisiert, und können z.B. aus mne ausgelesen  und geplottet werden. Passen Sie doch die Auswahl der Elektroden einmal an.

"""
from mne.channels import read_layout

layout = read_layout("EEG1005")
layout.plot()
picks = [layout.names.index(chan) for chan in ["Fpz", "C3"]]
layout.plot(picks=picks)
# %%
"""
Übung 2.4
*********

Beispielhafte Visualisierung einer Topographie

Im Folgenden simulieren wir ein Aktivitätsmuster, z.B. Potentiale zu einem bestimmten Zeitpunkt und plotten diese auf dem Skalp.


Dazu habe ich erstmal eine Funktion get_channel_pos geschrieben, welche die x/y Koordinaten bestimmter vorgegebener Kanäle aus dem Layout ausliest und für die Weiterverarbeitung mit plot_topomap anpasst.