"""
.. _ex-xdawn-denoising:
===============
XDAWN Denoising
===============
XDAWN filters are trained from epochs, signal is projected in the sources
space and then projected back in the sensor space using only the first two
XDAWN components. The process is similar to an ICA, but is
supervised in order to maximize the signal to signal + noise ratio of the
evoked response :footcite:`RivetEtAl2009, RivetEtAl2011`.
.. warning:: As this denoising method exploits the known events to
maximize SNR of the contrast between conditions it can lead
to overfitting. To avoid a statistical analysis problem you
should split epochs used in fit with the ones used in
apply method.
"""
from mne import Epochs, compute_raw_covariance, io, pick_types, read_events
from mne.datasets import sample
from mne.preprocessing import Xdawn
from mne.viz import plot_epochs_image
print(__doc__)
data_path = sample.data_path()
meg_path = data_path / "MEG" / "sample"
raw_fname = meg_path / "sample_audvis_filt-0-40_raw.fif"
event_fname = meg_path / "sample_audvis_filt-0-40_raw-eve.fif"
tmin, tmax = -0.1, 0.3
event_id = dict(vis_r=4)
raw = io.read_raw_fif(raw_fname, preload=True)
raw.filter(1, 20, fir_design="firwin")
events = read_events(event_fname)
raw.info["bads"] = ["MEG 2443"]
picks = pick_types(raw.info, meg=True, eeg=False, stim=False, eog=False, exclude="bads")
raw.apply_proj()
epochs = Epochs(
raw,
events,
event_id,
tmin,
tmax,
proj=True,
picks=picks,
baseline=None,
preload=True,
verbose=False,
)
plot_epochs_image(epochs["vis_r"], picks=[230], vmin=-500, vmax=500)
signal_cov = compute_raw_covariance(raw, picks=picks)
xd = Xdawn(n_components=2, signal_cov=signal_cov, rank="info")
xd.fit(epochs)
epochs_denoised = xd.apply(epochs)
plot_epochs_image(epochs_denoised["vis_r"], picks=[230], vmin=-500, vmax=500)