Skip to content

Instantly share code, notes, and snippets.

@sylvchev
Last active March 26, 2023 00:14
Show Gist options
  • Save sylvchev/1d7fb587645ab2d055cf330a7715cde0 to your computer and use it in GitHub Desktop.
Save sylvchev/1d7fb587645ab2d055cf330a7715cde0 to your computer and use it in GitHub Desktop.
CSP filter on EEG data with MNE and Pyriemann
from mne import create_info, EpochsArray
from mne.decoding import CSP as CSP_MNE
from moabb.datasets import BNCI2014001
from moabb.paradigms import LeftRightImagery
import numpy as np
from pyriemann.estimation import Covariances
from pyriemann.spatialfilters import CSP as CSP_Pyr
n_components=8
# Get data
d = BNCI2014001()
p = LeftRightImagery()
ep, label, meta = p.get_data(d, subjects=[1], return_epochs=True)
X = ep.get_data()
# Compute CSP with Pyriemann
C = Covariances().fit_transform(X)
pyr_csp = CSP_Pyr(nfilter=n_components).fit(C, label)
# Apply CSP filters on input data
Xcsp_p = np.empty(shape=(X.shape[0], n_components, X.shape[2]))
for i, x in enumerate(X):
Xcsp_p[i] = pyr_csp.filters_ @ x
# Create new MNE epochs with CSP filtered signal
info = create_info([f'CSP{i}' for i in range(n_components)], sfreq=ep.info['sfreq'], ch_types='eeg')
ep_csp_p = EpochsArray(Xcsp_p, info, ep.events, event_id=ep.event_id)
ep_csp_p.plot(scalings={"eeg":1.3}, n_epochs=4)
# Computing CSP with MNE
csp_mne = CSP_MNE(n_components=n_components, transform_into='csp_space').fit(X, label)
Xcsp_m = csp_mne.transform(X)
# Visualize CSP-filtered signal
ep_csp_m = EpochsArray(Xcsp_m, info, ep.events, event_id=ep.event_id)
ep_csp_m.plot(scalings={"eeg":1.3}, n_epochs=4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment