ASR example#

This example demonstrates a full ASR workflow on short EEG data:

  1. Calibrate ASR on a mostly clean segment.

  2. Apply ASR in 1-second windows.

  3. Compare raw and cleaned traces and quantify amplitude reduction.

This is intended as a first-pass inspection example rather than a benchmark: it shows how the calibration choice propagates to the cleaned output.

The most useful outputs are the calibration retention mask and the channel-wise RMS attenuation summary.

Uses meegkit.ASR().

References#

import os

import matplotlib.pyplot as plt
import numpy as np

from meegkit.asr import ASR
from meegkit.utils.matrix import sliding_window

# THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
raw = np.load(os.path.join("..", "tests", "data", "eeg_raw.npy"))
sfreq = 250

Calibration and processing#

We use the first 30 seconds as a calibration segment. In practice, this segment should be as artifact-free as possible because ASR thresholds are derived from it.

# Train on a clean portion of data
asr = ASR(method="euclid")
train_idx = np.arange(0 * sfreq, 30 * sfreq, dtype=int)
_, sample_mask = asr.fit(raw[:, train_idx])
selected_fraction = np.mean(sample_mask)

# Apply filter using sliding (non-overlapping) windows
X = sliding_window(raw, window=int(sfreq), step=int(sfreq))
Y = np.zeros_like(X)
for i in range(X.shape[1]):
    Y[:, i, :] = asr.transform(X[:, i, :])

raw = X.reshape(8, -1)  # reshape to (n_chans, n_times)
clean = Y.reshape(8, -1)

# A simple quality metric: root-mean-square attenuation per channel.
rms_before = np.sqrt(np.mean(raw ** 2, axis=1))
rms_after = np.sqrt(np.mean(clean ** 2, axis=1))
rms_ratio = rms_after / np.maximum(rms_before, np.finfo(float).eps)

Plot the results#

The gray overlay marks the 30-second calibration region actually used by the code. The hatched overlay shows the subset of that region that ASR kept while estimating its clean-data statistics.

What to look for: - After ASR, sharp bursts should be attenuated in many channels. - The RMS ratio (after/before) should generally be below 1. - Strong attenuation everywhere would suggest over-aggressive calibration.

times = np.arange(raw.shape[-1]) / sfreq
f, ax = plt.subplots(8, sharex=True, figsize=(9, 6))
for i in range(8):
    ax[i].fill_between(train_idx / sfreq, 0, 1, color="grey", alpha=.3,
                       transform=ax[i].get_xaxis_transform(),
                       label="calibration window")
    ax[i].fill_between(train_idx / sfreq, 0, 1, where=sample_mask.flat,
                       transform=ax[i].get_xaxis_transform(),
                       facecolor="none", hatch="...", edgecolor="k",
                       label="selected window")
    ax[i].plot(times, raw[i], lw=.5, label="before ASR")
    ax[i].plot(times, clean[i], label="after ASR", lw=.5)
    ax[i].set_ylim([-50, 50])
    ax[i].set_ylabel(f"ch{i}")
    ax[i].set_yticks([])
ax[0].set_title("Raw and cleaned EEG traces")
ax[i].set_xlabel("Time (s)")
ax[0].legend(fontsize="small", bbox_to_anchor=(1.04, 1), borderaxespad=0)
plt.subplots_adjust(hspace=0, right=0.75)
plt.suptitle("Before/after ASR")

fig, axm = plt.subplots(1, 1, figsize=(7, 3))
axm.bar(np.arange(raw.shape[0]), rms_ratio)
axm.axhline(1.0, color="k", ls=":", lw=1)
axm.set_xlabel("Channel")
axm.set_ylabel("RMS ratio (after / before)")
axm.set_title("Channel-wise attenuation summary")
axm.set_xticks(np.arange(raw.shape[0]))
axm.grid(True, axis="y", ls=":", alpha=.4)
plt.tight_layout()

print(f"Median RMS ratio across channels: {np.median(rms_ratio):.3f}")
print(f"Fraction of calibration samples retained: {selected_fraction:.3f}")
print("Interpretation: if only a small fraction of the calibration window is")
print("retained, the chosen segment may not be clean enough for stable ASR.")
plt.show()
  • Before/after ASR, Raw and cleaned EEG traces
  • Channel-wise attenuation summary
Median RMS ratio across channels: 0.941
Fraction of calibration samples retained: 0.932
Interpretation: if only a small fraction of the calibration window is
retained, the chosen segment may not be clean enough for stable ASR.

Total running time of the script: (0 minutes 0.957 seconds)

Gallery generated by Sphinx-Gallery