Part VII: Health, Biosignals, and Wearable AI
Chapter 31: EEG, Neural Signals, and Brain-Computer Interfaces

Motor imagery and SSVEP BCIs

"They asked me to read a mind. I settled for reading a mind that was busy imagining its own left hand, which turned out to be a far more cooperative subject."

A Pragmatic AI Agent

Prerequisites

This section assumes the montages and rhythm vocabulary of Section 31.1 (the mu and beta sensorimotor bands, occipital versus central electrodes) and the artifact-cleaning and band-power features of Section 31.2. The spatial-filtering and covariance ideas lean on the dimensionality-reduction toolkit of Chapter 8, and the frequency decompositions come from Chapter 7. We build the two workhorse non-invasive paradigms on top of that foundation.

The Big Picture

Almost every non-invasive brain-computer interface that has ever controlled something in the real world runs on one of two tricks. The first, motor imagery, reads the brain's own idle chatter: when you imagine squeezing your left hand without moving it, the sensorimotor cortex on the opposite side quiets down in a way scalp electrodes can see. The second, the steady-state visually evoked potential (SSVEP), plants the signal for you: stare at a light flickering at 12 Hz and your visual cortex hums back at 12 Hz, loud and on cue. One paradigm is active and endogenous, the user generates intent from nothing; the other is reactive and exogenous, the user just points their eyes. That single distinction drives everything downstream: how much calibration you need, how fast you can spell, how tiring the interface is, and which classical algorithm wins. This section builds both decoders from their physiology up, because they remain the baselines that the foundation models of Section 31.4 have to beat.

Motor imagery: reading the sensorimotor idle

What is the signal? Over the hand area of motor cortex, neurons at rest oscillate together in the mu (roughly 8 to 12 Hz) and beta (13 to 30 Hz) bands. When you plan, execute, or merely imagine a movement, that local population desynchronizes and the band power drops. This is event-related desynchronization (ERD); the rebound after the imagined movement is event-related synchronization (ERS). Crucially the effect is somatotopic and contralateral: imagined left-hand movement suppresses mu power at the right-hemisphere electrode (C4), and imagined right-hand movement suppresses it at C3. A motor-imagery BCI is, at heart, a detector of where and in which band the power dropped.

Why is raw band power not enough? Because scalp EEG is badly volume-conducted: one cortical source smears across many electrodes, and the ERD at C3 is buried under unrelated activity picked up by the same sensor. The classical breakthrough is Common Spatial Patterns (CSP), a supervised spatial filter that learns linear combinations of channels which maximize the variance (band power) for one class while minimizing it for the other. Formally, given the average per-class spatial covariance matrices \(\Sigma_1\) and \(\Sigma_2\) of band-pass-filtered trials, CSP solves the generalized eigenproblem

$$\Sigma_1 \mathbf{w} = \lambda\,(\Sigma_1 + \Sigma_2)\,\mathbf{w},$$

and keeps the filters \(\mathbf{w}\) with the most extreme eigenvalues \(\lambda\). The largest \(\lambda\) give filters whose output variance is high for class 1 and low for class 2; the smallest give the mirror image. Project a trial through these filters, take the log-variance of each projection, and you have a compact, discriminative feature vector that a simple linear classifier can separate. Because ERD lives in a specific band, the standard production recipe is Filter Bank CSP (FBCSP): run CSP inside several sub-bands (for example 4 to 8, 8 to 12, ... 32 to 40 Hz), then select the informative band-and-filter combinations. FBCSP won the BCI Competition IV datasets and is still the reference baseline.

Key Insight

CSP and its modern successor, Riemannian geometry, are two answers to the same question: a trial is best described not by its raw samples but by its spatial covariance matrix. CSP whitens and diagonalizes that matrix per class; the Riemannian approach instead treats each covariance as a point on the curved manifold of symmetric positive-definite matrices and classifies by geodesic distance to a per-class mean (Minimum Distance to Riemannian Mean, MDM), or maps the manifold to a flat tangent space and runs an ordinary classifier there. The Riemannian tangent-space pipeline is now the strongest classical motor-imagery method and, unlike CSP, needs almost no per-session refitting, which is why it repeatedly tops the cross-subject leaderboards of the MOABB benchmark.

SSVEP: when you plant the signal yourself

What is the signal? The visual cortex is a frequency-faithful amplifier. Present a stimulus flickering at frequency \(f\) and the EEG over the occipital pole (Oz, O1, O2) develops a sharp spectral peak at \(f\) and its harmonics \(2f, 3f\). Give the user several on-screen targets, each flickering at a distinct frequency, and their gaze choice is written directly into the spectrum. There is no imagined intent to learn and, for many users, no calibration at all: the decoder just asks which reference frequency the occipital signal correlates with best.

How do we decode it robustly? A naive peak-picking FFT works but wastes the multi-channel structure and the harmonics. The standard method is Canonical Correlation Analysis (CCA). For each candidate frequency \(f_k\) you build a reference matrix \(Y_k\) of sines and cosines at \(f_k\) and its harmonics, then find the linear combinations of the EEG channels \(X\) and of the references \(Y_k\) whose canonical correlation \(\rho_k\) is maximal. The predicted target is \(\arg\max_k \rho_k\). CCA needs no training data because the references are synthetic. Its stronger cousins, Filter Bank CCA (FBCCA) and the calibration-based Task-Related Component Analysis (TRCA), push spellers past 100 to 200 bits per minute, the highest information-transfer rate (ITR) of any non-invasive BCI. That speed is exactly why SSVEP dominates practical spellers even though staring at flicker is tiring and unusable for anyone who cannot direct their gaze.

The listing below is a complete, dependency-light CCA decoder. It generates a short synthetic occipital trial that flickers at one of three target frequencies, then recovers the target purely by canonical correlation against synthetic sine-cosine references, with no training whatsoever.

import numpy as np
from scipy.stats import pearsonr

fs, T = 256, 2.0                       # 256 Hz, 2-second trials
t = np.arange(0, T, 1 / fs)
targets = [9.25, 11.25, 13.25]         # three flicker frequencies (Hz)

def reference(freq, n_harmonics=3):
    """Sine/cosine reference bank at freq and its harmonics."""
    cols = []
    for h in range(1, n_harmonics + 1):
        cols += [np.sin(2 * np.pi * h * freq * t),
                 np.cos(2 * np.pi * h * freq * t)]
    return np.column_stack(cols)       # shape (samples, 2*n_harmonics)

def cca_corr(X, Y):
    """Top canonical correlation between multichannel X and reference Y."""
    Xc, Yc = X - X.mean(0), Y - Y.mean(0)
    # whiten then take largest singular value of the cross-covariance
    Qx, _ = np.linalg.qr(Xc)
    Qy, _ = np.linalg.qr(Yc)
    return np.linalg.svd(Qx.T @ Qy, compute_uv=False)[0]

def decode(eeg):
    rhos = [cca_corr(eeg, reference(f)) for f in targets]
    return int(np.argmax(rhos)), rhos

rng = np.random.default_rng(0)
true_k = 1                             # user is looking at the 11.25 Hz target
clean = np.sin(2 * np.pi * targets[true_k] * t)
eeg = np.column_stack([clean, 0.6 * clean]) + rng.normal(0, 2.0, (len(t), 2))
pred, rhos = decode(eeg)
print("predicted target:", pred, " correlations:", np.round(rhos, 3))
A training-free SSVEP decoder: standard CCA scores each candidate flicker frequency by its canonical correlation with the occipital EEG and picks the maximum. Even at a signal-to-noise ratio where the flicker is invisible in a single channel, the multi-harmonic reference recovers the 11.25 Hz target.

Library Shortcut

The Riemannian motor-imagery pipeline that would take dozens of lines to write by hand, band-pass filtering, per-trial covariance estimation, tangent-space projection, and classification, collapses to about four lines with pyriemann and scikit-learn: make_pipeline(Covariances('oas'), TangentSpace(), LogisticRegression()) fit on epoched trials. The MOABB package goes further and reduces an entire cross-subject, leakage-safe benchmark, download, epoching, CSP or Riemannian pipeline, and within-session versus cross-subject scoring, to a config object, replacing several hundred lines of glue code and, more importantly, standardizing the evaluation split so results are comparable across papers.

Choosing a paradigm, and paying for it in calibration

When do you pick which? The trade is between autonomy and burden. SSVEP is fast, near-zero-calibration, and robust, but it commandeers the eyes and needs a screen of flickering targets, which rules it out for gaze-impaired users and for eyes-free control. Motor imagery is self-paced, screen-free, and works with the eyes closed, which makes it the paradigm of choice for the most severely paralyzed users and for continuous control such as steering a wheelchair or a cursor; the price is heavy per-subject calibration and a stubborn population of "BCI-illiterate" users (commonly cited around 15 to 30 percent) who never produce a separable ERD. A pragmatic middle ground is the hybrid BCI, which combines an SSVEP "switch" to arm the system with motor imagery for the actual command, or fuses both feature streams.

The evaluation trap. The single most common way to publish an inflated motor-imagery number is to shuffle trials from one recording session into train and test. EEG has slow drifts (electrode impedance, alertness, cap position) so trials minutes apart are correlated; a random split leaks that shared state and flatters the model. The honest protocols are leave-one-session-out and, hardest of all, leave-one-subject-out, the same leakage-safe discipline demanded in Chapter 5. Report the operating point with calibrated confidence rather than a bare accuracy, because a BCI that abstains when unsure is far safer than one that guesses; the calibration and abstention machinery of Chapter 18 applies directly.

Practical Example: an SSVEP wheelchair in an assistive-tech lab

A clinical rehabilitation group builds a shared-control wheelchair for a user with late-stage ALS who retains eye movement. Four LEDs on the armrest display flicker at 8.57, 10, 12, and 15 Hz for turn-left, forward, turn-right, and stop. An eight-electrode occipital cap feeds an FBCCA decoder that scores a decision every 1.5 seconds and only issues a command when the winning canonical correlation clears a confidence threshold, otherwise it holds position. Because CCA needs no training, the user drove within minutes of cap placement, no motor-imagery calibration session required. The design lesson is the one from Chapter 27 on neuromotor interfaces: the BCI supplies discrete intent while onboard lidar and inertial sensing handle obstacle avoidance and smooth motion, so a missed or noisy brain command degrades to "keep going straight" rather than a collision.

Research Frontier

The current state of the art is closing the calibration gap that has always penalized motor imagery. Riemannian transfer learning with Riemannian Procrustes Analysis and covariance-recentering aligns a new subject's data to a source pool so a decoder trained on others works with minutes, not hours, of setup. On the SSVEP side, deep methods such as EEGNet, compact convolutional networks, and the SSVEPNet and DeepConvNet families now rival CCA and TRCA while tolerating shorter windows, which pushes ITR higher. Looming over both is the shift to self-supervised EEG foundation models (Chapter 17 gives the pretraining recipe): rather than fit CSP per subject, pretrain a backbone on thousands of unlabeled hours and fine-tune a small head, the approach detailed for LaBraM, EEGPT, BIOT, and CBraMod in Section 31.4.

Exercise

Extend the CCA listing into an ITR calculator. (1) Run the decoder over many synthetic trials at several noise levels and estimate accuracy \(p\) for each. (2) With \(N=3\) targets and a 2-second window plus a 0.5-second gaze shift, compute the information transfer rate using Wolpaw's formula, \(B = \log_2 N + p\log_2 p + (1-p)\log_2\frac{1-p}{N-1}\) bits per selection, converted to bits per minute. (3) Add a fourth target and a confidence threshold that abstains when the top correlation is too close to the runner-up; plot accuracy, abstention rate, and effective ITR as you sweep the threshold. Which threshold maximizes real throughput once you charge time for abstained trials?

Self-Check

What's Next

In Section 31.4, we move from these hand-designed spatial filters to learned ones: EEG foundation models (LaBraM, EEGPT, BIOT, CBraMod) that pretrain on massive unlabeled recordings and then fine-tune to motor imagery, SSVEP, and clinical tasks with a fraction of the per-subject calibration that CSP and TRCA demand.