✦ Day 05 · Artifact Removal

Artifact Subspace
Reconstruction (ASR)

An intuitive, step-by-step masterclass on how ASR learns the baseline fingerprint of clean brain signals, scans continuous EEG with a sliding window, and reconstructs burst artifacts without throwing away your data.

💡 Intuitive Analogies ⚡ Stationarity vs Transient Bursts 🤝 ASR-ICA Synergy 📾 4-Step Process 📏 Chang & Blum $k=20\text{--}30$ Consensus 🔠 Geometric $L_1$-Median 🧩 Interactive Simulators 🐍 meegkit / asrpy / clean_rawdata
1

The Big Idea
Why We Need ASR for Mobile Brain Recording

Imagine you are recording someone wearing an EEG headset while walking or exercising. Every time they bite down, move their jaw, or twitch a neck muscle, a massive electrical spike blasts across the sensors.

Traditional cleaning gives you two bad choices:

  • Throw away the whole 1-second segment: If you do this every time the subject twitches, you lose over 50% of your recording!
  • Run ICA (Independent Component Analysis): ICA works great for steady, repeating eye blinks. But for random, sudden muscle pops, ICA gets confused because the muscle pop doesn't repeat consistently across the recording.

The Real-World Analogy: The Building Inspector

Think of ASR as an expert Building Inspector:

  1. Calibration: The inspector first measures how a healthy, sturdy building stands (the clean EEG baseline).
  2. Sliding Inspection: The inspector walks room by room (scanning short 500 ms windows).
  3. Detecting Damage: In one room, a wall is bulging outwards due to a sudden impact (a muscle pop in Channel 1).
  4. Local Repair: The inspector doesn't demolish the whole building (don't throw away the epoch)! Instead, they remove only the bulging wall and rebuild it to match the rest of the sturdy house.

๐Ÿค Why ASR is the Essential Pre-conditioner for ICA (Stationarity vs. Bursts)

Students often ask: "If we have ICA, why do we need ASR?" The answer lies in the mathematical assumptions of both methods:

โšก The ICA Vulnerability (Spatial Stationarity):

ICA assumes the spatial mixing matrix $\mathbf{A}$ is constant across the entire recording. Transient, 300 ยตV movement bursts or cable tugs violate stationarity, causing ICA to waste multiple components trying to model temporary noise, splitting genuine brain dipoles into unusable noise fragments.

๐Ÿ›ก๏ธ The ASR Solution (Subspace Pre-Conditioner):

ASR operates locally in short 500 ms sliding windows. It surgically removes transient, high-amplitude bursts and projects the remaining channels back to baseline. Once the bursts are gone, the clean, stationary data allows downstream ICA to isolate ocular and neural dipoles with pristine precision!


2

The 4-Step ASR Workflow
From Raw EEG to Cleaned Signal

Artifact Subspace Reconstruction follows a clean 4-step pipeline:

Step 01

1. Baseline Calibration

Record ~1 minute of clean resting EEG. Learn the healthy covariance matrix ($C_{ref}$) and baseline mixing matrix ($M$).

Step 02

2. Sliding Window PCA

Move a 500 ms sliding window across the EEG. Separate the multichannel signal into directional PCA components.

Step 03

3. Cutoff Threshold Check

Compare each component's variance to baseline. If variance exceeds cutoff ($k$ standard deviations), mark it as an artifact!

Step 04

4. Subspace Repair ($R$)

Zero out the bad component direction ($U=0$) and predict the missing brain wave using baseline matrix $M$.


3

Step 1: Baseline Calibration
Learning "Normal" Brain Statistics

Before ASR can clean artifacts, it needs to know what clean, baseline brain activity looks like for this specific person and electrode layout.

We collect a short calibration recording (e.g. 1 minute resting state with eyes open/closed, or automatically find the cleanest 15% segments of the dataset).

💡 Plain English Math Translation: Geometric $L_1$-Median
Equation: $\mathcal{G}(X) = \arg\min_{\mathbf{y}} \sum \|\mathbf{x}_i - \mathbf{y}\|_2$
What it means in plain English: Standard averages (means) get heavily skewed by extreme outliers. If you average 10 normal numbers and one huge 1,000 spike, the average explodes! The Geometric Median ($L_1$-Median) calculates the spatial baseline covariance matrix ($C_{ref}$) by finding the point that is closest to all clean windows, automatically ignoring any stray artifact bursts!
📊 Interactive Widget 1: $L_1$ Geometric Median vs Mean Baseline Step 1 Demo

Drag the red Artifact Outlier Burst slider below. Notice how the standard Mean Baseline (cyan dashed ellipse) gets pulled away by the spike, while the Geometric $L_1$-Median (solid magenta ellipse) stays anchored to healthy EEG!

Outlier Magnitude: 5.0 x

4

Steps 2 & 3: Sliding Window PCA & The Cutoff Rule
Finding Abnormal Noise Directions

Step 2 — The 500 ms Sliding Spotlight: As the continuous EEG recording streams, ASR slides a short 500 ms window across the data sample by sample. Inside this window, Principal Component Analysis (PCA) decomposes the multi-channel signal into independent directional axes ($v_1, v_2, \dots, v_Q$).

Step 3 — The Cutoff Rule ($k$ Standard Deviations): For each component direction, ASR asks: "Is the variance in this direction abnormally huge compared to baseline?"

$$\text{Threshold } z_i = \mu_i + k \cdot s_i$$
💡 Plain English Math Translation: The Cutoff Parameter $k$
The cutoff parameter $k$ is like a volume limit set in standard deviations. If a component's energy is within $k$ standard deviations of clean baseline, it passes through untouched ($U=1$). If it spikes beyond $k$, ASR flags it as an artifact ($U=0$)!

๐Ÿ“Š Empirical Cutoff ($k$) Guidelines from Literature

Early studies suggested $k = 5$ for real-time BCI, but landmark validation studies (Chang et al., 2018; Blum et al., 2019) proved that low $k$ values over-clean and attenuate genuine Event-Related Potentials (ERPs). Follow these evidence-based thresholds:

โ˜… Recommended Standard

$k = 20 \text{ to } 30$ (Cognitive EEG & ERPs)

Optimal for resting-state and ERP paradigms. Removes high-voltage muscle twitches and channel pops while strictly preserving P300/N100 amplitudes and 10 Hz alpha power.

Mobile Motion Mode

$k = 10 \text{ to } 20$ (MoBI / Wearable EEG)

Designed for Mobile Brain/Body Imaging where subjects walk, run, or manipulate objects. Handles heavier biomechanical noise without destroying signals.

โš ๏ธ Caution: Over-Cleaning

$k < 10$ (Aggressive BCI Only)

Attenuates natural high-amplitude brain waves and synthetically compresses neural variance. Avoid in cognitive and clinical neuroscience!

Subspace Reconstruction vs. Window Drop (The $>66\%$ Rule):
If an artifact corrupts only 1โ€“3 dimensions out of 32 channels, ASR reconstructs the missing activity with $R$. But if a massive artifact corrupts $>66\%$ of all dimensions simultaneously, the remaining clean subspace is too small to mathematically predict the missing channels. In this case, `clean_rawdata` switches from reconstruction to window rejection (`window_criterion = 0.25`), safely excising the entire unrecoverable epoch.


5

Step 4: Subspace Repair ($R$ Operator)
Rebuilding Missing Brain Signals

Here comes the magical step of ASR: How do we repair the corrupted signal without dropping the data window?

When component 1 is flagged as an artifact, ASR zeroes out component 1 in diagonal matrix $U$ ($U_{11}=0$). Then, it uses the Reference Mixing Matrix $M$ (which knows how healthy brain channels normally talk to each other) to predict what brain wave should have been there!

💡 Plain English Math Translation: The Reconstruction Operator $R$
Equation: $R = M \left( U V^T M \right)^+ V^T$
In plain English: Take the remaining clean channel components ($U V^T$), pass them back through the healthy baseline mixing structure ($M$), and solve for the best matching uncorrupted brain signal!
🧩 Interactive Widget 2: Reconstruction Matrix $R$ & Cutoff Sandbox Step 4 Demo

Move the Cutoff (k) slider below. Watch the diagonal rejection matrix $U$ zero out bad components (red cells), and see the green reconstructed wave cleanly restore the true 10 Hz brain wave from the corrupted red wave!

Cutoff Parameter ($k$): k = 15 Optimal Research
Ref Mixing $M$
×
Rejection $U$
×
PCA Basis $V^T$
=
Operator $R$

6

Interactive Visual Simulators
Visualizing Vector Projection & Live EEG Engine

📐 Interactive Widget 3: 2D Subspace Vector Projection 2D Vector View

This diagram shows 2-channel space (Fp1 vs Fz). The green ellipse is clean baseline EEG. Click Inject Muscle Burst to watch the vector shoot out past the threshold boundary. Then click Reconstruct Subspace to watch ASR pull the point back onto the baseline ellipse!

🎬 Interactive Widget 4: Live 4-Channel ASR Sliding Window Engine Real-Time Engine

Watch ASR process continuous multi-channel EEG in real time with a 500 ms sliding window spotlight! Red = Raw corrupted signal, Green/Teal = ASR Reconstructed Output.

Cutoff ($k$): k = 15
Scrub Timeline:

Production ASR Pipeline & Code Reference

1. Always High-Pass Filter First ($\ge 0.5 \text{ to } 1.0 \text{ Hz}$): ASR requires zero-mean signals. Low-frequency baseline drifts severely distort PCA variance estimates.

2. NEVER Common-Average Reference (CAR) Before ASR: CAR subtracts the channel mean, reducing spatial matrix rank by 1. That causes matrix singularity in the pseudo-inverse $M^+$! Apply CAR after ASR.

import mne
from meegkit.asr import ASR

# 1. Load continuous raw EEG dataset
raw = mne.io.read_raw_fif("sample_raw.fif", preload=True)

# 2. Mandatory: High-pass filter at 1.0 Hz (ASR requires zero-mean data)
# DO NOT apply Common Average Referencing (CAR) before ASR!
raw.filter(l_freq=1.0, h_freq=40.0)

# 3. Pick EEG channels and extract numpy array
raw_eeg = raw.copy().pick('eeg')
data = raw_eeg.get_data()
sfreq = raw.info['sfreq']

# 4. Initialize ASR with empirical research standard cutoff (k = 20 to 30)
asr = ASR(sfreq=sfreq, cutoff=20)

# 5. Fit ASR on 60 seconds of clean resting baseline (or cleanest segment)
calibration_samples = int(60 * sfreq)
asr.fit(data[:, :calibration_samples])

# 6. Apply subspace reconstruction across continuous EEG
clean_data, _ = asr.transform(data)
raw_eeg._data = clean_data

# 7. NOW apply Common Average Reference (CAR) and proceed to ICA
raw_eeg.set_eeg_reference('average')
print("ASR Cleaning Complete! Ready for stationary ICA.")
% 1. Load continuous raw dataset into EEGLAB
EEG = pop_loadset('filename', 'sample_raw.set');

% 2. Run clean_rawdata pipeline with standard research parameters
% Note: clean_artifacts handles highpass, bad channels, ASR, and CAR automatically
EEG_clean = clean_artifacts(EEG, ...
    'FlatlineCriterion', 5, ...       % Drop channels flatlining > 5s
    'Highpass', [0.5 1.0], ...         % Transition band for baseline removal
    'ChannelCriterion', 0.8, ...       % Remove channels with low correlation < 0.8
    'LineNoiseCriterion', 4, ...       % Drop channels with extreme 50/60 Hz noise
    'BurstCriterion', 20, ...          % ASR Cutoff (k = 20: Recommended Research Standard)
    'WindowCriterion', 0.25, ...       % Drop epochs with > 66% corrupted channels
    'BurstRejection', 'on', ...        % Enable ASR subspace reconstruction
    'Distance', 'Euclidian');

% 3. Apply Common Average Reference (CAR) AFTER ASR
EEG_clean = pop_reref(EEG_clean, []);

% 4. Proceed to ICA with clean stationary data
EEG_clean = pop_runica(EEG_clean, 'extended', 1);

Student Self-Check Quiz

Q1: What does ASR do when it detects a component spiking beyond the cutoff threshold $k$?

A) It deletes the entire 1-second data recording window.
B) It zeroes out only the corrupted component direction ($U=0$) and reconstructs the brain signal using baseline covariance $M$.
C) It mutes all EEG channels completely.

Q2: Why must Common Average Referencing (CAR) be performed AFTER ASR, not before?

A) CAR makes muscle noise louder.
B) CAR reduces spatial matrix rank by 1, destroying pseudoinverse calculation in ASR.
C) CAR changes the sampling rate.

📚

Further Reading & Resources

  1. Real-Time Neuroimaging and Cognitive Monitoring Using Wearable Dry EEG (Mullen et al., 2015) 📑
    Landmark IEEE Transactions on Biomedical Engineering paper introducing Artifact Subspace Reconstruction (ASR), $L_1$ geometric median covariance estimation, and mobile artifact rejection in real time.
  2. Cognionics Mobile EEG & UCSD SCCN Artifact Subspace Reconstruction Demo 🎥
    Live demonstration by UCSD Swartz Center for Computational Neuroscience (SCCN) showcasing real-time ASR burst reconstruction on dry mobile EEG data streamed via LabStreamingLayer into EEGLAB/BCILAB inside a moving vehicle.
  3. meegkit Python Package: Artifact Subspace Reconstruction (ASR) Module Documentation 📖
    Official API documentation and code reference for running ASR and Riemannian ASR on MNE-Python data (`meegkit.asr.ASR`).
  4. EEGLAB / SCCN: Clean_rawdata Plugin & ASR Algorithm Repository 📘
    Official UCSD Swartz Center for Computational Neuroscience (SCCN) repository and documentation for `clean_rawdata` and `clean_artifacts()` in EEGLAB.