Brain Rhythms

Imagining a movement does not add a signal to the EEG. It removes one: the 8 to 13 Hz mu rhythm over the matching side of the head drops, and a decoder reads that drop.

Learn what the five brain rhythms are, how to measure the power in each one, and how that power moves in time when you imagine a movement.

Choose what the person imagines, and watch two scalp channels. Compare the mu power on each side with rest. Then we build the whole measurement, piece by piece: sampling, the spectrum, windows, averaging, wavelets, and the drop itself.

You need a feel for a sine wave (a smooth wave that repeats a fixed number of times per second) and a little Python for the code. We build the rest from zero.

Built from primary sources: Pfurtscheller and Lopes da Silva (1999) on event-related desynchronization, Welch (1967), Thomson (1982), the BCI Competition IV dataset 2a description, the Neuromatch Academy time-frequency tutorial, and Mike X Cohen’s book Analyzing Neural Time Series Data (cited, not copied). Every idea is re-taught here in our own words and devices. Lesson 12 of the BCI series; it follows the recording map and leads to event-related potentials.

Imagine, then compare sides

Simulated, not recorded: each channel is 1/f background noise plus a narrow 10.5 Hz mu rhythm, made by random-phase spectral synthesis at 128 Hz and repeated every 32 s. The imagery gains are set by us (mu rhythm power cut to 35% of its resting value on the side opposite the hand, left alone on the other side) to mirror the direction that Pfurtscheller and Lopes da Silva (1999) describe. The bar and the percentage are measured live from the trace: the 8 to 13 Hz power in each 2 s window, compared with the same channel at rest.

Chapter 0

A Raw Trace Is a Crowd

See why one wobbling line from the scalp holds several steady waves at once, and why a decoder cares about their strength, not their shape

A volunteer sits in a chair with a cap of 22 small metal discs on her head. Each disc touches the scalp and measures a voltage. You press record and plot one of them. The screen shows a wobbling line that never repeats and never rests.

The line is small. Scalp voltages are a few tens of microvolts (a microvolt is one millionth of a volt). The line looks like noise. But it is not noise. Part of it is a crowd of steady waves, all added together, and each wave has its own speed.

The idea in plain words

Think of a choir that sings several notes at once. Your ear hears one sound. A trained musician hears the separate notes. The wobbling line is the one sound. The brain rhythms are the separate notes.

Each steady wave is a rhythm (also called an oscillation). Two numbers describe it. Its frequency is how many full cycles it makes each second, counted in hertz (Hz). Its amplitude is how tall the wave is, here in microvolts. A 10 Hz wave makes ten full up-and-down cycles every second.

The word that matters most for brain-computer interfaces is power. The power of a wave is its amplitude squared, then halved: a wave of amplitude A has power A²/2. A bigger wave has much more power. Doubling the amplitude gives four times the power.

Why a decoder reads power, not shape

The neurons under one disc do not fire in lockstep with a clock. Their rhythm drifts in phase from second to second. So the exact up-and-down shape of one wave is not stable. What is stable is how strong the wave is. The strength of the 10 Hz wave over one part of the head changes when the person moves, imagines moving, rests or falls asleep.

That is why this lesson is about measuring power in each frequency, and how that power moves in time. The recording map (lesson 3) showed where the scalp sits among the ways to listen to a brain. Here we learn to read it.

A worked example, one step at a time

Suppose a toy trace has just two rhythms. A 10 Hz wave has amplitude 15 µV. A 20 Hz wave has amplitude 5 µV. We add them, point by point. How much of the trace is each one?

  1. Power of the 10 Hz wave: 15²/2 = 225/2 = 112.5 µV².
  2. Power of the 20 Hz wave: 5²/2 = 25/2 = 12.5 µV².
  3. Total power: 112.5 + 12.5 = 125 µV². (Waves at different frequencies do not interfere in total power. Chapter 2 shows why.)
  4. Share of the 10 Hz wave: 112.5/125 = 90%. The 20 Hz wave holds the other 10%.

The 10 Hz wave is only three times taller than the 20 Hz wave. Yet it holds nine times the power. Squaring makes the tallest wave dominate. Remember this: later, a small drop in one wave will matter.

Now try it with real-sized rhythms. The device below adds five waves, one for each classic EEG band. Switch them on and off. The top view is the trace you would see. The bottom view is the same signal drawn as a list of how tall each wave is, one bar per frequency.

Add the rhythms up

Top: three seconds of the summed trace. Bottom: one bar per rhythm, tall for a big wave. Switch rhythms on and off, and watch the trace and the power shares change.

Illustrative: one sine wave per band with amplitudes we chose (delta 20, theta 8, alpha 15, beta 5, gamma 2 µV) and fixed phases. Real rhythms are never this clean. The swing and the power shares are computed from the waves you switch on.

Switch off alpha. The trace changes shape a lot, yet the bars show only one bar gone. Switch off gamma, the tiniest wave. The trace barely changes, but the bar chart tells you it was there. A bar chart makes small rhythms visible. A trace hides them under the big ones.

The data flow for the whole lesson

Here is the path every chapter fills in. The raw recording is an array with the shape (channels, samples). At 250 Hz, a 4 s trial from 22 channels is an array of 22 by 1,000 numbers. Each step turns it into something smaller and more useful.

  1. Raw array: (22, 1000), voltages in µV, one row per scalp disc.
  2. Spectrum: (22, 501), the power at each frequency from 0 to 125 Hz (Chapters 2 to 5).
  3. Spectrogram or wavelet map: (22, frequencies, time), the same power but moving in time (Chapters 6 and 7).
  4. Event-related change: power compared with a quiet baseline, in percent (Chapter 8).
  5. Feature vector: a few numbers per channel, ready for a classifier (Chapter 9).

The road

  1. Five rhythms, delta to gamma: the bands, where Hans Berger found alpha, and the mu rhythm.
  2. Reading frequency off samples: sampling, the Nyquist limit and the discrete Fourier transform.
  3. Leakage: why we taper: what a finite window does to a spectrum.
  4. Welch: averaging away the noise: a steadier power estimate.
  5. Multitaper: many windows, one epoch: Thomson’s trick for short windows.
  6. The spectrogram: power over frequency and time.
  7. Wavelets: resolution that follows the frequency.
  8. Event-related desynchronization: the mu drop of motor imagery.
  9. Traps: artifacts and the spectral floor.
  10. Field guide: numbers, code and where to go next.
A trace holds a 12 µV rhythm at 10 Hz and a 4 µV rhythm at 20 Hz. What share of the power does the 10 Hz rhythm hold?

Chapter 1

Five Rhythms, Delta to Gamma

Meet the five named bands, see the alpha rhythm appear when eyes close, and learn where the mu rhythm hides

In the 1920s a German psychiatrist named Hans Berger attached electrodes to the scalps of patients and of his own son Klaus, and recorded the faint voltage. He published his results in 1929 under the German title for “On the electroencephalogram of man”. It was the first human EEG paper.

Berger saw a repeating wave of about ten cycles a second. It was strongest when a person lay still with eyes closed. It faded when the person opened their eyes or was stimulated. He named it the alpha wave, after the first letter of the Greek alphabet. He gave the faster waves that took its place the name beta.

That naming habit stuck. Later workers added more Greek letters for the other speeds they found. Today we split the spectrum into five named bands. A band is just a range of frequencies that we agree to treat as one unit.

The five bands

BandRange (Hz)Where and when it is strong (textbook picture)
Deltaabout 1 to 4Deep sleep. Awake, slow drifts of this speed often come from eye blinks and sweat, not from the brain (Chapter 9).
Theta4 to 8Drowsiness, and often reported during memory and focus tasks.
Alpha8 to 13Relaxed wakefulness with eyes closed. Strongest at the back of the head.
Beta13 to 30Alert, active thinking. Also a beta component over the motor strip.
Gammaabove 30Fast and weak at the scalp. Easily swamped by muscle activity (Chapter 9).

Treat these edges as a convention. Labs shift them by a hertz or two, and the textbook pictures are broad tendencies, not rules. A rhythm does not know which band it belongs to. The bands exist so that people can name a range and compare results.

Mu: alpha’s twin over the motor strip

There is a second 8 to 13 Hz rhythm. It sits over the sensorimotor cortex, the strip of brain that sends movement commands and receives touch. On the scalp this strip lies under the central electrodes, named C3 (left), Cz (middle) and C4 (right). The rhythm there is called the mu rhythm. It comes with a faster partner near 20 Hz in the beta band.

Mu has the same speed as occipital alpha but a different job and a different place. It is strong when the motor strip is idle. When you move, or even prepare or imagine a move, it gets weaker. Pfurtscheller and Lopes da Silva (1999) call that fall an event-related desynchronization. The hero at the top of this page simulated it, and Chapter 8 builds the measurement.

Band power from a spectrum, step by step

To get the alpha power, we need a power spectral density (PSD). It lists, for each frequency, how much power sits near it, in µV² per Hz. Chapters 2 to 5 teach how to compute one. Here we use one that is already given, just to see how a band is read off it.

Take a toy PSD sampled every 1 Hz. The values from 8 Hz to 13 Hz are 8, 20, 46, 20, 8 and 5 µV²/Hz. The width of each step is 1 Hz.

  1. Multiply each value by the step width: 8, 20, 46, 20, 8, 5 (each times 1 Hz).
  2. Add them up: 8 + 20 + 46 + 20 + 8 + 5 = 107 µV².
  3. Read the result: the alpha band power is 107 µV². The peak bin at 10 Hz alone carries 46 of those, which is 43%.

Band powers are often compared as a ratio in decibels (dB). A decibel is ten times the base-10 logarithm of a power ratio. A ratio of 2 is about 3 dB. A ratio of 10 is 10 dB. Decibels let you put numbers that differ by factors of a thousand on one short axis.

Now see Berger’s result. The device makes 32 seconds of simulated EEG from the back of the head, with a spectrum we control, and measures the five band powers with a method you meet in Chapter 4.

Open and close the eyes

Top: two seconds of the trace. Bottom: the power in each band, in decibels (bars start at 8 dB). Switch between eyes open and eyes closed and watch which bar moves.

Simulated, not recorded: a 1/f background, a 20 Hz beta bump and a 10 Hz alpha peak, whose size we set to 10% of the closed-eyes size for eyes open. This mirrors the direction Berger reported (1929), not any measured size. Band edges used: 1 to 4, 4 to 8, 8 to 13, 13 to 30, 30 to 45 Hz. Powers are Welch estimates (Chapter 4) of 32 s at 128 Hz.

Only the alpha bar moves much. The delta bar is the tallest in both states. That is not a mistake. Brain spectra fall steeply with frequency, so the lowest band starts with the most power. Alpha is notable because it sticks out above the line its neighbours draw, not because it is the biggest bar. Chapter 9 returns to this falling line.

The failure mode: the peak that crosses a border

Symptom. A subject’s alpha band power looks tiny, although their trace plainly shows a clear wave. Measurement. Plot the PSD. The peak sits at 7.5 Hz, below the 8 Hz edge, so the band power count puts the wave in theta. Fix. Find each person’s own peak frequency first, then set the band around it, for example the peak plus or minus 2 Hz. Many labs do this because alpha speed differs between people.

Why does the delta bar stay the tallest, even with eyes closed and a strong alpha peak?

Chapter 2

Reading Frequency Off Samples

Turn a list of voltages into a spectrum, and learn why the length of the recording sets how finely you can tell two rhythms apart

A real EEG amplifier does not hand you a smooth curve. It measures the voltage at fixed instants and writes down numbers. In the public motor imagery dataset used for BCI Competition IV (dataset 2a), the amplifier took 250 measurements every second from each of 22 scalp electrodes. It also filtered the signal to pass 0.5 to 100 Hz and cut out the 50 Hz power-line hum with a notch filter.

So the recording is a list of numbers, one every 4 milliseconds. How do you find out how much 10 Hz is in a list like that? This chapter answers in three moves: how fast to sample, how to probe for one frequency, and how long you must listen.

How fast must we sample?

The number of samples per second is the sampling rate, written fs. With fs = 250 Hz, the highest frequency we can see is half of it, 125 Hz. This limit is the Nyquist frequency. A wave faster than that cannot be told apart from a slower one.

Here is the trap, with numbers. A 140 Hz wave sampled at 250 Hz gives the same list of numbers as a 110 Hz wave. The sampling grid sees 140 Hz as the mirror image of 250 − 140 = 110 Hz. This false identity is called aliasing. It is why the amplifier filters out everything above about 100 Hz before the sampler sees it. An analog filter in front of the sampler is the only cure, because once the numbers are written the mix-up cannot be undone. (The step in voltage between neighbouring numbers is another limit, treated in the quantization lesson.)

Probing for one frequency

Suppose you want to know how much 10 Hz is hidden in a list of N numbers. Here is a plain recipe. Make a pure 10 Hz wave sampled at the same instants. Multiply it with your data, number by number. Add up the products.

If the data contain a 10 Hz wave in step with your probe, the products are mostly positive, and the sum is large. If the data have no 10 Hz, the products swing positive and negative and cancel, and the sum is near zero. The sum measures how well the data match the probe.

One probe has a problem. If the data wave is shifted a quarter of a cycle, it fits a cosine perfectly and a sine not at all. So we use two probes at once, a cosine and a sine, and combine the two sums. A neat way to hold both is a complex number: a pair of numbers (real part, imaginary part) where the real part is the cosine sum and the imaginary part is the sine sum. The length of that pair is how much of the frequency is present, whatever its shift. That is the discrete Fourier transform (DFT).

Xk
The answer for probe number k: a complex number. Its length squared, |Xk|², says how much power the data hold at frequency k × fs/N.
∑n=0N−1
Add over all N samples, from the first (n = 0) to the last.
xn
The n-th voltage sample, in µV.
e−i 2π k n / N
The probe: a cosine and a sine (written together as one complex wave) that makes exactly k full cycles over the N samples.

Check it on the smallest case. Take N = 4 and the data x = (0, 1, 0, −1). That is one full sine cycle across the window, so it should light up probe k = 1.

  1. Probe k = 1 uses the values e−iπn/2 = 1, −i, −1, i for n = 0 to 3.
  2. Multiply and add: X1 = 0·1 + 1·(−i) + 0·(−1) + (−1)·i = −2i.
  3. Its length squared: |X1|² = 4. The mirror probe k = 3 also gives 4. Probes k = 0 and k = 2 give 0.
  4. Check the energy: the data have energy 0²+1²+0²+(−1)² = 2, and 4 × 2 = 8 = 4 + 4. The probes keep every bit of the energy, and they split it by frequency.

Step 4 is why Chapter 0 could add the powers of rhythms at different frequencies. The probes are orthogonal: each one is blind to all the others. So the power at one frequency does not leak into another, as long as every wave fits a whole number of cycles. When a wave does not fit, it does leak. Chapter 3 is about that.

How long must we listen?

The probes at k = 0, 1, 2, … are spaced evenly. Their spacing in hertz is the bin width. It depends only on the length of the recording.

Δf
The gap between neighbouring probes, in Hz. Two rhythms closer than about this cannot be told apart.
fs
The sampling rate, 250 Hz in the competition dataset.
N
The number of samples in the window.
T
The window length in seconds, N/fs. A longer window means finer bins.

For a 4 s trial at 250 Hz, N = 1,000 and Δf = 0.25 Hz. The probes run from k = 0 to k = 500, which is 501 bins up to 125 Hz. That matches the (22, 501) shape in the road map of Chapter 0. A 0.5 s window gives only 2 Hz bins, which is too coarse to separate the 10 Hz alpha from an 11 Hz neighbour.

Listen longer to split two rhythms

The data hold two sine waves, at 10 Hz and 11 Hz. Choose how many seconds of data to analyse, and see whether the spectrum shows one hump or two.

Simulated: a 10 Hz sine (amplitude 1) and an 11 Hz sine (amplitude 0.7) plus a little white noise, sampled at 128 Hz and cut with a rectangular window. The smooth curve is the DFT zero-padded to 2,048 points for display; padding draws a smoother curve but adds no resolution. Peaks are counted above 20% of the tallest.

At 0.5 s the two waves melt into one hump. At 1 s they just separate. At 2 s and 4 s the gap is clear. The rule of thumb is that two rhythms need a gap larger than about 1/T to be resolved. A decoder that must answer in half a second gives up fine frequency detail. Chapter 5 shows a way to get less variance from such short windows, and Chapter 6 shows the cost of time against frequency in full.

A 2 s window is recorded at 250 Hz. What is the gap between neighbouring frequency bins?

Chapter 3

Leakage: Why We Taper

Watch a clean rhythm smear across the whole spectrum when the window cuts it mid-cycle, then fix the smear with a smooth window

Chapter 2 gave a promise: the probes are blind to each other, so power stays at its own frequency. That promise had a condition. Every wave must fit a whole number of cycles inside the window. A real 10.5 Hz rhythm does not know where your window starts and stops. It breaks that condition almost every time.

Picture a 1 s window on a 10.5 Hz wave. The window holds 10.5 cycles. At the right edge the wave is half way through a cycle, then the data stop. The DFT treats the window as if it repeated forever. At every repeat there is a sudden jump, from the end of one copy to the start of the next. A sudden jump contains every frequency. So the single rhythm now appears to have power everywhere.

The window is a multiplication

Cutting a recording to N samples is the same as multiplying the endless signal by a window function that is 1 inside and 0 outside. Multiplying in time smears in frequency: the spectrum you get is the true spectrum blurred by the spectrum of the window. This blur has a tall centre, the main lobe, and a trail of small bumps on both sides, the sidelobes. Power that lands in the sidelobes has leaked away from where it belongs.

The plain cut-out window is called rectangular. Its main lobe is narrow, 2 bins wide from null to null. But its first sidelobe is only about 13 dB below the peak, and the sidelobes die away slowly.

The fix is to fade the data in and out so there is no jump. A smooth bell-shaped window that goes to zero at both ends is a taper. The most common is the Hann window.

wn
The weight given to sample n. We multiply the sample by it before the DFT.
0.5 − 0.5
Shifts and scales a cosine so that it runs smoothly from 0 up to 1 and back to 0.
2π n / N
One full turn of the cosine across the N samples: zero weight at both ends, full weight in the middle.

The Hann window pays a price. Its main lobe is twice as wide, 4 bins from null to null, so it blurs close rhythms more. In return its sidelobes are far smaller.

Real numbers from a simulation

We simulated 128 samples at 128 Hz (so bins are 1 Hz apart) of a sine at 10.5 Hz, halfway between two bins. We measured how far below the peak the spectrum sits at three higher frequencies.

FrequencyRectangularHann
20 Hz−28.5 dB−67.3 dB
30 Hz−36.3 dB−86.9 dB
40 Hz−40.5 dB−98.3 dB

A decibel table is hard to feel, so turn it into a question. Suppose a faint real rhythm sits at 40 Hz, 50 dB below the big 10.5 Hz one. With the rectangular window, the leakage at 40 Hz is −40.5 dB. That is stronger than the faint rhythm by about 10 dB. The faint rhythm drowns. With the Hann window the leakage is −98 dB, far below the rhythm, so it shows.

Does this matter for EEG? Yes, when one source is far stronger than another. Slow drifts and eye blinks can be orders of magnitude larger in power than the gamma band. Leakage from them can bury the gamma. In our simple lesson spectrum the gap is smaller, so the effect is mild. The device below makes the gap large on purpose.

Find the faint tone

A big sine and a faint tone at 40 Hz share the window. Choose the window, then slide the big sine’s frequency. Look for a bump at 40 Hz.

10.50 Hz

Simulated: 128 samples at 128 Hz, so bins are 1 Hz apart. The big sine has amplitude 1. The faint tone sits exactly on the 40 Hz bin and is 50 dB lower in power (amplitude 0.0032). Dots are the real DFT bins; the thin curve is the zero-padded view. A tone counts as visible if its bin stands 6 dB or more above the bins on both sides.

Slide the frequency to exactly 10.00 Hz. With the rectangular window the leakage vanishes, because the wave now fits whole cycles, and the faint tone appears. Slide it away again and the floor rises. The result depended on luck. The Hann taper is boring in comparison: it gives the same clean floor everywhere. That reliability is why most EEG work tapers.

Keeping the units honest

A taper throws away signal energy at the edges. If we divided by the wrong number, the PSD would come out too small. The standard fix divides by the energy of the window, so the units stay µV² per Hz.

Pk
The one-sided PSD estimate at bin k, in µV² per Hz. The method is called the periodogram.
|Xk|²
The squared length of the DFT of the windowed data, from Chapter 2.
fs
The sampling rate. Dividing by it turns power per bin into power per hertz.
∑ wn²
The window’s energy. For a rectangular window of N samples it is N. For a Hann window it is 3N/8, so 96 when N = 256.

The factor 2 folds the mirror half of the DFT onto the positive frequencies, so we only list 0 up to the Nyquist frequency. With this scaling, adding Pk times the bin width over all bins gives back the variance of the signal. That check catches most bugs.

Compared with a rectangular window, what does a Hann taper trade, and why does it pay off for EEG?

Chapter 4

Welch: Averaging Away the Noise

Cut a long recording into overlapping pieces, average their spectra, and trade a little frequency detail for a much steadier curve

You have a minute of resting EEG. You taper it, run the DFT on all of it, and plot the periodogram from Chapter 3. You expect a smooth curve with an alpha bump. Instead you get a forest of spikes. Bins next to each other differ by a factor of five or more. A friend records another minute, and the spikes land in different places.

The natural fix looks like more data. You record ten minutes. The forest gets denser, but it does not get smoother. Why?

Why a periodogram stays noisy

For a random signal like EEG, each bin of the periodogram is itself a random number. A standard result says its typical wobble is as large as its average. In plain words, the relative error of one bin is about 100%. More data gives you more bins that are each as noisy as before, because the bin width 1/T shrinks while each bin stays a single noisy draw.

You cannot beat noise in one number. But you can beat it by averaging many independent numbers. If each estimate has relative error 100%, then the average of K independent estimates has error 100%/√K. Four estimates halve the error. Hundred estimates cut it to 10%.

The idea of Welch’s method

Peter Welch’s 1967 paper gives the recipe. It is written for the fast Fourier transform, then new, which made this cheap.

  1. Cut the recording into segments of L samples. Let neighbouring segments overlap, usually by half.
  2. Taper each segment with a window such as Hann (Chapter 3), and compute its periodogram.
  3. Average the K periodograms, bin by bin.

Why overlap? A Hann taper nearly ignores the samples at the edges of each segment. If segments do not overlap, those samples are wasted. Overlapping by half lets the next segment use them at full weight. The overlapped estimates are not fully independent, so the gain is a little below 1/√K. But you get many more of them from the same data.

The price: wide bins

Each segment is short, L samples, so its bin width is fs/L (Chapter 2). A 2 s segment has 0.5 Hz bins. A 0.5 s segment has 2 Hz bins. You choose between a steady curve (many short segments) and fine detail (few long ones). This is the first of three trade-offs in this lesson that all say the same thing: you cannot have both.

A worked example

Take 60 s of EEG recorded at 256 Hz. That is N = 15,360 samples. Choose 2 s segments, so L = 512, with 50% overlap, so each segment starts 256 samples after the last.

  1. Count the segments: K = floor((15,360 − 512)/256) + 1 = 58 + 1 = 59.
  2. Bin width: fs/L = 256/512 = 0.5 Hz, giving 257 bins from 0 to 128 Hz.
  3. Ideal noise: 100%/√59 = 13%, if the 59 segments were independent. Overlap makes the true figure a little higher.
  4. Compare with one big periodogram: one segment of all 15,360 samples has 0.017 Hz bins and 100% noise per bin.

Now try it. The device holds 64 seconds of simulated EEG whose true spectrum we know exactly (the purple line). You choose the segment length and the overlap, and the device measures how far the Welch estimate wanders from the truth.

Tune Welch against the truth

Warm line: the Welch estimate. Purple line: the true spectrum. Pick a segment length, then switch the overlap. Short segments are steady but blunt. Long segments are sharp but noisy.

Simulated, not recorded: 64 s at 256 Hz made from the lesson’s illustrative spectrum (1/f background, a 10 Hz alpha peak, a 20 Hz beta bump). Hann taper on every segment. The spread is the standard deviation of estimate/truth minus 1 over the bins from 15 to 40 Hz, where the truth is smooth, measured on this one recording.

With 64 s segments you see a jagged line with a peak that is correct but hard to trust. With 0.5 s segments the line is steady but the alpha peak turns into a low hill: 2 Hz bins cannot show a peak that is under 2 Hz wide, so the height is wrong. At 2 s the compromise is good for this signal. A trial in a motor imagery experiment has only a few seconds, so you must choose with care.

The same thing in code

pythonfrom scipy.signal import welch
# x: (22, 1000) = 22 channels, 4 s at 250 Hz, in microvolts
f, Pxx = welch(x, fs=250, window="hann", nperseg=250, noverlap=125, axis=-1)
# f: (126,) 0, 1, ..., 125 Hz   Pxx: (22, 126) in uV^2/Hz
# K = floor((1000 - 125) / 125) = 7 segments, so about 38% noise per bin

With 1 s segments in a 4 s trial you average 7 pieces. The expected noise is about 100%/√7 = 38%. That is why a single trial’s spectrum still looks rough, and why BCI pipelines average over trials as well (Chapter 8).

The failure mode: a rhythm that moves

Symptom. The averaged spectrum shows a low, broad hump instead of a sharp alpha peak. Measurement. Compute Welch on the first and the second half of the recording. The peak sits at 9.5 Hz in one and 10.5 Hz in the other. The rhythm drifted, and averaging smeared it. Fix. Use shorter windows of time to track it (Chapter 6), or align the peak per segment before you average.

You change from 2 s Welch segments to 0.5 s segments on the same recording. What happens?

Chapter 5

Multitaper: Many Windows, One Epoch

View a single short window through several special tapers, average the results, and cut the noise without chopping the data into pieces

A BCI that moves a cursor cannot wait a minute for a clean spectrum. It must decide from a window of about one second. Chapter 4 splits that second into short pieces. Each piece has only a few samples. The bins become wide and the Hann taper throws away the edges of every piece.

David Thomson (1982) asked a different question. Why cut the data at all? Look at the whole second again and again, each time through a different window. If the windows are chosen well, each look gives an estimate with an independent error. Average the looks and the noise falls, as it did in Welch’s method.

What makes a good set of windows

We want windows that do two jobs. First, each window should leak as little as possible outside a chosen narrow range of frequencies. Second, the windows should not repeat each other: the estimates they give must be independent, so averaging them truly helps.

There is a family of windows that does both, found by David Slepian at Bell Labs. They are the discrete prolate spheroidal sequences, or Slepian tapers for short (also written DPSS). You choose two numbers. N is the number of samples. W is a half-bandwidth in hertz: the leakage is squeezed into the range from −W to +W around each frequency. The tapers come out as solutions of a matrix problem, and the first one looks like a smooth bell, like Hann. The second has one sign change, the third two, and so on. They are all orthogonal (Chapter 2), which is what makes the estimates independent.

The key knob is the time-bandwidth product, NW, where the window length T = N/fs is in seconds and W is in hertz, so NW = T × W. Fix T = 1 s and pick NW = 3. Then W = 3 Hz. The tapers hold their energy within ±3 Hz. The count of good tapers is about 2NW − 1 = 5. The sixth and later ones leak too much to be useful.

Ŝ(f)
The multitaper PSD estimate at frequency f, in µV² per Hz.
K
The number of tapers used, usually 2NW − 1.
∑k=0K−1
Add the K squared spectra, one for each taper.
DFT(hk · x)
Multiply the data by taper k sample by sample, then take the DFT from Chapter 2.
hk
Slepian taper number k, scaled so that its squares add to 1. This scaling keeps the units right.

A worked example

A BCI window lasts 1 s at 256 Hz, so N = 256 samples. Choose NW = 3.

  1. Half-bandwidth: W = NW/T = 3/1 s = 3 Hz. Features narrower than about 2W = 6 Hz will blur together.
  2. Number of tapers: K = 2NW − 1 = 5.
  3. Noise left: about 100%/√5 = 45% per frequency, if the five estimates are independent.
  4. Compare NW = 2 and NW = 4: NW = 2 gives W = 2 Hz, K = 3, noise about 58%. NW = 4 gives W = 4 Hz, K = 7, noise about 38%.

Look at the pattern. Noise falls roughly as 1/√K. The blur grows as 2W, and K = 2NW − 1 = 2WT − 1. So K and the blur rise together. Welch has the same law, as Chapter 4 said: you pay for lower noise in lost resolution. Multitaper does not escape the trade. What it gives is a better deal at short windows: every sample counts at near-full weight, and the leakage is controlled by design rather than by luck.

Run it. The device draws one random 1 s epoch from a 64 s record. It shows the true spectrum (purple) and the estimate from the method you choose.

One second, three methods

Pick a method, then press New epoch a few times. For multitaper, change NW and watch the tapers in the strip underneath.

Simulated, not recorded: 1 s epochs (256 samples at 256 Hz) cut at random places from a 64 s record made from the lesson’s illustrative spectrum. Slepian tapers are computed in your browser (Percival and Walden’s tridiagonal method). Welch here uses 64-sample Hann segments with 50% overlap, zero-padded for display; its true bins are 4 Hz apart. The spread is the standard deviation of estimate/truth minus 1 over 15 to 40 Hz on this one epoch.

The Hann periodogram of one second is a jagged mess. Welch with 0.25 s pieces is steadier but its alpha peak is blunt. Multitaper at NW = 3 is steady and keeps the peak near the right place and height. Push NW to 4 and the line gets smoother still, but the alpha peak starts to spread: the tapers now blur ±4 Hz. Press New epoch a few times, because one lucky draw proves nothing.

The failure mode: too much bandwidth

Symptom. The mu peak at 10 Hz and the beta bump at 20 Hz both look right, but the 10 Hz peak is too low and too wide. Measurement. Compute W = NW/T. With T = 0.5 s and NW = 3, W = 6 Hz, so the peak is blurred over ±6 Hz. Fix. Pick NW so that 2W is smaller than the narrowest feature you need, or use a longer window. Do not use more than 2NW − 1 tapers, because the later ones leak.

A window lasts 0.5 s. You choose NW = 3. What are the half-bandwidth W and the number of tapers?

Chapter 6

The Spectrogram: Frequency Over Time

Slide a window along the trace, stack the spectra it gives, and see when each rhythm switched on and off

A volunteer imagines moving her right hand for 1.5 seconds. For that moment, her mu rhythm over the left side of the head gets weaker. Before and after, it is back to normal. You compute the Welch spectrum of the whole six-second trial. The spectrum shows a mu peak. It does not show that anything happened, because averaging mixes the quiet moment with the busy ones.

A single spectrum answers “how much at each frequency?” BCI needs a second question: “at what time?” The answer is a picture with two axes. Time runs left to right. Frequency runs bottom to top. Colour tells the power. This picture is a spectrogram.

How to build one

The recipe is the periodogram from Chapter 3, repeated along the trace. It is called the short-time Fourier transform (STFT). A deeper treatment lives in the STFT lesson; here is what a BCI engineer needs.

  1. Choose a window length L (say 1 s) and a hop (say 0.1 s).
  2. Take the first L seconds, multiply by a Hann taper, and compute the power spectrum. That is one column.
  3. Slide forward by the hop and do it again. Each step makes a new column.
  4. Stack the columns side by side and colour them by power in decibels.

Count the data flow for one channel of a 4 s trial at 250 Hz. The input is a vector of 1,000 numbers. With L = 250 samples (1 s) and a hop of 25 samples (0.1 s), the number of columns is floor((1,000 − 250)/25) + 1 = 31. Each column has 126 frequency bins, 0 to 125 Hz, 1 Hz apart. The output is a (126, 31) image per channel; for 22 channels, (22, 126, 31).

pythonfrom scipy.signal import spectrogram
f, t, Sxx = spectrogram(x, fs=250, window="hann", nperseg=250, noverlap=225, axis=-1)
# x: (22, 1000)   f: (126,)   t: (31,) window centres, 0.5 s ... 3.5 s
# Sxx: (22, 126, 31) in uV^2/Hz;  10*log10(Sxx) is what the picture shows

Read the picture like a weather map. Bright means strong power. We colour by decibels because power spans several orders of magnitude, and a straight scale would show only the loudest rhythm. A steady horizontal band means a rhythm that stays on. A band that fades for a while and then returns is what an ERD looks like. The hop sets only how smooth the picture looks, not how much detail it holds. The window decides that, as the next section shows.

You cannot have both

Here is the central trade-off, the second of this lesson’s three. A window of L seconds can only tell two frequencies apart if they differ by more than about 1/L hertz (Chapter 2). And it cannot place an event in time better than about L seconds, because everything inside the window is averaged into one column. A long window gives sharp frequencies and blurry times. A short window gives sharp times and blurry frequencies. Nothing in the method removes this. It is the same fact that makes a musical note need a few cycles before you can name its pitch.

Take numbers. With L = 2 s the bins are 0.5 Hz apart, but a burst that starts at 1.5 s can seem to begin up to a second early. With L = 0.25 s the burst edge is crisp, but the bins are 4 Hz apart, and a 10 Hz tone looks 16 Hz wide at its base, because the Hann main lobe is 4 bins wide from null to null.

The device holds six seconds of simulated EEG. A 10 Hz rhythm is on from 1.5 s to 3.0 s. Then a 12 Hz rhythm takes over until 4.5 s. The purple lines mark the truth. Change the window and see which half of the picture goes soft.

Trade time against frequency

Pick a window length. Short windows place the burst edges well but smear 10 and 12 Hz together. Long windows split the tones but blur the edges.

Simulated: sine bursts of amplitude 5 (10 Hz, then 12 Hz) on 1/f background noise, 128 Hz sampling, Hann window, a column every 0.05 s, zero-padded to 512 points for display. The two numbers in the read-out are measured from the picture’s own columns. Colour shows decibels over a 30 dB range below the brightest cell.

At 0.25 s the burst starts where the purple line says, but the two tones fuse into one fat band. At 2 s there are two thin bands, but each runs a long way past its purple end. At 1 s you get a decent compromise for this signal. In real motor imagery work the window is also near one second, for the same reason.

The failure mode: a window that fits one event

Symptom. The mu drop looks like it starts before the cue appeared. Measurement. The window is 2 s long and its column is centred on the time label, so the first column that overlaps the cue already holds a second of post-cue data. Plot the window edges, not just the centres. Fix. Use a shorter window for timing claims, and say which time stamp (centre or edge) the figure uses.

You halve the STFT window length, from 1 s to 0.5 s. What happens to the picture?

Chapter 7

Wavelets: Resolution That Follows Frequency

Shrink the window as the frequency rises, so every rhythm is judged over the same number of its own cycles

Chapter 6 used one window length for every frequency. That is a strange deal. A 1 s window holds only 4 cycles of a 4 Hz wave, but 40 cycles of a 40 Hz wave. The slow wave is poorly measured and the fast wave is measured far longer than it needs. A 40 Hz burst might last a quarter of a second. A 1 s window smears it.

A better rule says: look at every rhythm for the same number of its own cycles. Slow rhythms get long windows. Fast rhythms get short ones. This is the idea behind wavelet analysis, and it is the standard tool for time-frequency work in neuroscience. Mike X Cohen’s book Analyzing Neural Time Series Data builds the whole subject around it, and the Neuromatch Academy time-frequency tutorial runs the same steps in code. (For wavelets in general signal processing, see the wavelets lesson.)

The Morlet wavelet

A wavelet is a short wave packet: a few cycles of a wave that fade in and out. The favourite for EEG is the Morlet wavelet, a complex sine wave multiplied by a bell curve (a Gaussian). For each frequency f we make one wavelet. We slide it along the data and, at each time, multiply and add, exactly as the DFT probe did in Chapter 2. The answer at each time is a complex number. Its squared length is the power at that time and frequency.

ψ(t)
The wavelet for one frequency f, as a function of time t around its centre.
ei 2π f t
A cosine and a sine of frequency f, written as one complex wave. This part finds the rhythm.
e−t² / (2σt²)
The bell curve that fades the wave in and out. This part fixes the time.
σt = n / (2π f)
The width of the bell in seconds. It shrinks as f grows. n is the number of cycles, the one knob you choose.

This width rule is where the magic sits. The bell and its own spectrum are a matched pair: a narrow bell in time has a wide spectrum, and the reverse. The spread in frequency is σf = 1/(2πσt) = f/n. (Both are standard deviations of the wavelet’s amplitude.) So the relative frequency blur σf/f = 1/n is the same at every frequency, while the time blur gets shorter as the frequency rises.

A worked table

Choose n = 5 cycles. Compute the two blurs at three frequencies.

FrequencyTime blur σt = 5/(2πf)Frequency blur σf = f/5
4 Hz199 ms0.8 Hz
10 Hz80 ms2 Hz
40 Hz20 ms8 Hz

The product of the two blurs is 1/(2π) = 0.159 in every row. For a bell-shaped wavelet that product cannot go lower. With n = 5 the 40 Hz wavelet sees a burst 10 times more sharply in time than the 4 Hz one, and pays by being 10 times wider in hertz. For EEG that is usually the right pay: high rhythms are short-lived and have broad peaks.

Choosing the number of cycles

The number of cycles n sets how the trade is split. Small n (like 3) gives sharp timing and blunt frequency. Large n (like 12) gives sharp frequency and blurred timing. There is no correct value. You choose it from the question: “When does a 20 Hz burst start?” wants a small n. “Is the peak at 10 Hz or 11 Hz?” wants a large one. Some analysts let n grow slowly with frequency to balance the two.

The device holds six seconds of simulated EEG with a slow 5 Hz burst and a short 24 Hz burst. Compare a 1 s STFT with Morlet wavelets, and slide n.

Change the number of cycles

Purple lines mark the truth: a 5 Hz burst from 1.0 to 2.5 s and a 24 Hz burst from 3.0 to 3.4 s. Switch method, then slide the cycles. The strip underneath draws the wavelets at 5, 10 and 24 Hz.

5

Simulated: sine bursts of amplitude 5 on 1/f background noise, 128 Hz sampling. Wavelet power uses the kernel scaled to sum its envelope to 1, so a sine of equal size gives equal power at every frequency. Colour shows decibels over a 30 dB range below the brightest cell. The two numbers in the read-out are measured from the picture, each against its own row’s peak.

With the STFT, the 24 Hz burst is a pale smudge that starts early and ends late. With Morlet wavelets at n = 5 it is a compact bright patch near its purple line, while the 5 Hz burst is a clean band. Raise n to 12 and the 24 Hz patch spreads in time again, while the bands thin in frequency. The wavelet does not remove the trade. It spends the trade where the physics wants it spent.

The failure mode: the edge of the trial

Symptom. The 4 Hz power at the start of every trial is oddly low. Measurement. The 4 Hz wavelet with n = 5 has σt = 0.2 s, so it needs about 3σt = 0.6 s of data on each side. At the edge half the wavelet has no data to multiply. Fix. Cut a longer epoch than you need and drop the first and last 0.6 s after the transform, or use a baseline that avoids the edge. The same rule applies to the 0.5 to 1.5 s baseline in Chapter 8.

A Morlet wavelet uses n = 5 cycles. How does its width in time change from 10 Hz to 40 Hz?

Chapter 8

Event-Related Desynchronization

Measure the drop in mu power that follows an imagined movement, in percent of a quiet baseline, averaged over trials

Now we can do what the hero showed. In BCI Competition IV dataset 2a, nine volunteers sat in front of a screen and imagined movements. Each trial ran like this. At t = 0 s a cross appeared and a short tone sounded. At t = 2 s an arrow pointed left, right, down or up for 1.25 s: left hand, right hand, both feet, or tongue. The volunteer imagined that movement until the cross vanished at t = 6 s. No feedback was given. Each session held 288 trials, 72 per class, over 22 scalp channels sampled at 250 Hz.

What does the EEG do during those four seconds of imagery? Not much to the eye. But the power of the mu rhythm over the motor strip changes, and that change is what decoders in this field read.

Two kinds of response to an event

An event, such as a cue or a movement, makes the brain respond in two different ways. The first is an event-related potential (ERP): a small voltage bump locked to the event, with the same shape and timing in every trial. Lesson 13 covers it (event-related potentials). The second is a change in the strength of an ongoing rhythm. It begins around the event, but its waves are not locked to it: their phase is random from trial to trial.

Pfurtscheller and Lopes da Silva (1999) name the second kind. A fall in rhythm power is an event-related desynchronization (ERD). A rise is an event-related synchronization (ERS). The name comes from a picture: many neurons firing in step make a big rhythm, so a drop means they fell out of step. The paper reports that the effect is specific to a frequency band, and that one scalp spot can show ERD while another shows ERS at the same time.

The formula, in percent

ERD%
The change in band power as a percent of the baseline. Negative means a drop (ERD). Positive means a rise (ERS).
A
The band power at the moment you measure, for example from 3.5 s to 5.5 s after the trial starts.
R
The band power in a quiet reference interval before the cue. It is each person’s own “normal” level, so people with big and small mu rhythms compare fairly.
R
The same reference, used again as the divisor so that the answer is a fraction of normal.

Work two cases. The baseline power over C3 is R = 40 µV².

  1. Imagining the right hand: A = 22 µV². ERD% = 100 × (22 − 40)/40 = −45%. A drop of 45%.
  2. After the movement ends: A = 52 µV². ERD% = 100 × (52 − 40)/40 = +30%. That is a synchronization, an ERS.

Why we square first, then average

Here is the step that trips most newcomers. To see an ERP you average the raw voltages over trials. The locked bump adds up, and the random background cancels. For ERD you must do the opposite order. The mu waves in different trials have random phase, so averaging raw voltages would cancel the rhythm you want to measure. First turn every trial into power (a Morlet wavelet at 10 Hz, as in Chapter 7, or a band-pass filter followed by squaring). Then average the powers. Power is never negative, so it cannot cancel.

The data flow for one class and one channel: (trials, samples) raw voltage, for example (72, 2000) at 250 Hz for 8 s; wavelet at 10.5 Hz gives power (72, 2000); the mean over trials gives (2000,); divide by R and subtract 1 for ERD%.

Where it appears

Mu ERD follows the body map of the motor strip. Imagining the right hand lowers mu mainly over the left side, at C3. Imagining the left hand lowers it at C4. Imagining the feet tends to show near the midline, at Cz. This opposite-side pattern is what the hero displayed. After the imagery stops, a beta rise is often reported, called the post-movement beta rebound.

A single trial is noisy. Averaging N trials cuts the wobble by about √N (Chapter 4 gave the same law). The device makes the dataset-like trials for you: eight seconds each, cue at 2 s, imagery until 6 s. Pick a class and a channel and change how many trials you average.

Average the drop over trials

The warm line is the average ERD in percent. The thin lines are single trials. The purple band is the baseline R. Try the opposite channel from the hand, then drag the trial count down to 1.

24

Simulated, not recorded. Trial timing follows the dataset 2a paradigm (cue at 2 s, imagery to 6 s); the ERD depths (mu power left at 40% on the side opposite the hand, 90% at Cz, and unchanged on the same side; for feet, 50% at Cz and 90% at C3 and C4) and the baseline of 0.5 to 1.5 s are our illustrative choices. Each trial is 1/f noise plus a 10.5 Hz mu rhythm, 128 Hz sampling; power comes from a 5-cycle Morlet wavelet at 10.5 Hz, smoothed over 0.25 s. The readings come from the simulated trials you see.

At 24 trials the average shows a clean dip after the cue, which recovers once imagery ends. With one trial, the same dip hides in jitter. The drop is usually modest compared with the wobble in a single trial, which is why decoding a single imagined movement is hard, and why training data come from hundreds of trials.

The failure mode: a bad baseline

Symptom. A volunteer shows a huge positive “ERS” after the cue, in every class and every channel. Measurement. Plot the baseline power for each trial. In many trials the baseline interval holds a startle from the warning tone, so R is far too low and every later value looks high. Fix. Pick a reference interval that is quiet and away from the cue and the tone, state it in the methods, and check the spread of R across trials before trusting any percent.

Why do we turn each trial into power before averaging trials when we measure ERD?

Chapter 9

Traps: Artifacts and the Spectral Floor

Spot the four ways a band-power number can lie, and read the spectrum before you trust any feature built from it

A student builds a motor imagery decoder. It reads gamma power at the temples. It scores far above chance. She is delighted. Then a colleague watches the recording and sees the volunteer clench her jaw every time she imagines the movement. The decoder is reading the jaw, not the brain. Nothing is wrong with the arithmetic of Chapters 2 to 8. The numbers are exact. They just measure something else.

An artifact is any part of the recorded voltage that does not come from the brain activity you want. Scalp electrodes pick up everything near them. Here are the four traps that matter most for band power.

Four ways a band lies

TrapWhere it landsHow to spot itWhat to do
Eye blinks and eye movementsDelta and theta, strongest at frontal electrodesLarge slow bumps in the raw trace, with a stereotyped frontal shapeReject the trial, or remove the component (the ICA lesson shows how)
Muscle activity (EMG)Broadband above about 20 Hz; hits beta and gammaA raised, flat-topped high-frequency floor near the temples and neck; bursts when the jaw movesAvoid gamma on the scalp unless it is controlled; check with a clenching recording
Power-line noiseOne sharp spike at 50 or 60 Hz (and its multiples)A needle in the spectrum at the mains frequencyA notch filter, as the dataset’s amplifier did at 50 Hz, or a spectrum-based cleaner
The 1/f floorEvery band: power falls steadily with frequencyA straight line on a log-log plot; its slope can change without any rhythm changingMeasure the peak above the line, not the whole band

The muscle row deserves a second look. Muthukumaraswamy’s 2013 review of high-frequency activity in MEG and EEG reports that muscle activity overlaps with brain activity across roughly 20 to 300 Hz, and that even resting recordings are heavily contaminated at high frequencies. That is why scalp gamma is a hard signal to trust. Mu and beta are lower and far less affected, which is one reason motor imagery BCIs use them.

The aperiodic floor, explained

Chapter 1 showed that delta had the most power even with a strong alpha peak. The reason is that EEG power falls as frequency rises, roughly along a straight line on a log-log plot. This smooth falling background is the aperiodic part (it has no rhythm). The bumps that stand above it, like alpha, are the periodic part.

The trap is that a band sum adds both. Donoghue and colleagues (2020) show that this can mix up the two in standard analyses: a change in the slope of the background looks like a change in oscillation power, though no rhythm moved. Their remedy models each spectrum as a background plus peaks, and measures the peaks. Our device does the simplest version of the same idea for alpha: it draws a straight line through the log-log spectrum on either side of the peak, and reports how far the peak stands above that line.

A worked example

The background gets steeper, and nothing else changes. Say the theta band holds 50 µV² in the clean spectrum. After the slope change, the background across 4 to 8 Hz is about 1.95 times higher, so the band holds about 98 µV².

  1. Naive change: 10 × log10(98/50) = 10 × 0.29 = about +2.9 dB. It looks like more theta rhythm.
  2. Look for a peak: there is no bump in the 4 to 8 Hz range, only the line itself moving up.
  3. Verdict: no theta rhythm appeared. The floor under the band rose. The same slide moves delta even more.

Contaminate the spectrum

The dashed purple line is a clean spectrum. Switch traps on. The warm line is what a decoder would see. Below it, each band shows its power change in decibels.

Illustrative spectra, not recordings: the lesson’s 1/f background with an alpha peak and a beta bump, plus a blink term (large below 6 Hz), a broad muscle term (rising from 20 Hz, peaking near 45 Hz), a 50 Hz spike, and a steeper floor (the background times (f/20)−0.6). Here gamma means 30 to 80 Hz. Peak above floor: a straight line fitted in log-log on 2 to 6 Hz and 16 to 40 Hz, compared with the spectrum at 10 Hz. Muscle and gamma facts follow Muthukumaraswamy (2013). The fit is imperfect on purpose: a floor-fitting method inherits the contamination in the points it fits.

Switch on the steeper floor alone. Delta rises by 6.1 dB and theta by 2.9 dB, though no rhythm changed. Alpha moves only 0.5 dB, because its own peak dominates its band. Now switch on muscle: gamma jumps by 8.7 dB and beta by 2.2 dB. The 50 Hz line adds 7.8 dB to gamma. Blinks add 9.1 dB to delta and 3.4 dB to theta. The alpha peak above the floor starts at 8.1 dB and falls to 6.3 dB with muscle on, because the muscle raises the floor that the line is fitted to. A fit inherits the trap it tries to avoid. Each trap leaves its own fingerprint across the five boxes, and the fingerprint is how you spot it.

From spectrum to features

Once the spectrum is clean, the usual motor imagery feature is the log band power of each channel in mu and beta: the logarithm turns a skewed power into a bell-shaped number, so classifiers treat it better. With 22 channels and two bands, one trial becomes a 44-number vector. Ramoser, Müller-Gerking and Pfurtscheller (2000) went one step further: they found spatial filters that mix channels so that the log variance of the output differs most between left-hand and right-hand imagery. That method, common spatial patterns, is still a strong baseline for this task.

The steeper-floor switch raises delta by about 6 dB and theta by about 3 dB, yet no rhythm was added. What explains the rise?

Chapter 10

Field Guide

Keep the numbers, the checklist and the core code, and see where each idea leads next

A rhythm is a number you have to earn. You sample the voltage fast enough (Chapter 2). You taper it so one strong rhythm cannot hide a faint one (Chapter 3). You average to tame the noise, by segments or by tapers (Chapters 4 and 5). You choose a window in time and pick your side of the time-frequency trade (Chapters 6 and 7). You compare with a quiet baseline of the same person (Chapter 8). Then you ask what else could have moved the number (Chapter 9).

The numbers and terms

TermValue or ruleWhere it comes from
Bandsdelta 1 to 4, theta 4 to 8, alpha 8 to 13, beta 13 to 30, gamma above 30 HzConvention; edges vary by a hertz or two (Chapter 1)
Dataset 2a recording9 people, 22 EEG channels, 250 Hz, band-pass 0.5 to 100 Hz, 50 Hz notch, 288 trials per sessionBCI Competition IV dataset 2a description
Dataset 2a trialtone at 0 s, cue at 2 s for 1.25 s, imagery until 6 s; left hand, right hand, feet, tongueSame description
Nyquist frequencyfs/2 = 125 Hz at 250 HzChapter 2
Bin widthΔf = fs/N = 1/T (0.25 Hz for 4 s)Chapter 2
Leakage, 10.5 Hz sine, 128 samplesat 40 Hz: rectangular −40.5 dB, Hann −98.3 dBOur simulation, Chapter 3
Periodogram PSDPk = 2|Xk|²/(fs ∑ w²), in µV²/HzChapter 3
WelchK = floor((N − L)/step) + 1 segments; noise about 100%/√K; bins fs/LWelch (1967); Chapter 4
MultitaperW = NW/T, K = 2NW − 1 tapers, noise about 100%/√KThomson (1982); Chapter 5
STFT tradefrequency detail about 1/L, time detail about LChapter 6
Morlet waveletσt = n/(2πf), σf = f/n, product 1/(2π)Chapter 7
ERD / ERS100 × (A − R)/R, negative is ERDPfurtscheller and Lopes da Silva (1999)

The checklist

  1. Write down the sampling rate, the filters the amplifier applied, and the band edges you use.
  2. Taper every window. Use Hann for Welch, Slepian tapers for multitaper.
  3. Check the units. Summing Pk times the bin width should give back the variance of the signal.
  4. Pick the window from the narrowest feature you must split (1/T) and the noise you can afford (1/√K).
  5. Square first, then average across trials when the rhythm is not phase-locked.
  6. Use a quiet baseline away from the cue and the tone, and state its interval.
  7. Cut long epochs and drop the wavelet edges.
  8. Plot the spectrum before any feature. Look for the blink, the muscle floor and the mains spike.
  9. Report ERD in percent of baseline, with the band, the channel and the number of trials.

The core as code

pythonimport numpy as np
from scipy.signal import welch, fftconvolve

# x: (trials, channels, samples) = (72, 22, 2000): 8 s at 250 Hz, microvolts
def psd(x, fs=250, seg_s=1.0):
    L = int(seg_s * fs)
    f, P = welch(x, fs=fs, window="hann", nperseg=L, noverlap=L // 2, axis=-1)
    return f, P                                      # P: (72, 22, L/2+1) in uV^2/Hz

def band_power(f, P, lo, hi):
    m = (f >= lo) & (f < hi)
    return P[..., m].sum(-1) * (f[1] - f[0])           # (72, 22): power per trial and channel

def erd_percent(x, fs=250, f0=10.5, n_cycles=5, base=(0.5, 1.5)):
    s = n_cycles * fs / (2 * np.pi * f0)                # Morlet width in samples: sigma_t * fs
    t = np.arange(-int(3 * s), int(3 * s) + 1)               # about +-3 sigma, in samples
    k = np.exp(2j * np.pi * f0 * t / fs) * np.exp(-t**2 / (2 * s**2))   # complex Morlet
    k = k / np.abs(k).sum()                             # envelope sums to 1
    z = fftconvolve(x, k[None, None, :], mode="same", axes=-1)
    power = np.abs(z) ** 2                              # SQUARE FIRST: (72, 22, 2000)
    m = power.mean(axis=0)                              # THEN average trials: (22, 2000)
    R = m[:, int(base[0] * fs):int(base[1] * fs)].mean(-1, keepdims=True)
    return 100 * (m - R) / R                             # (22, 2000); negative = ERD

We ran this function on random noise of shape (72, 22, 2000). It returned shape (22, 2000), and the mean ERD between 2 s and 6 s was +0.7%, near zero as it should be. We have not run it on the dataset. Check the shapes on your own data, and repeat the noise test.

Where each idea leads next

Sources

Opened and checked for this lesson:

Cited by their standard reference details only, not re-read for this lesson:

All spectra, traces and trials in the devices are simulated and labelled as such.

The takeaway. Brain rhythms are measured, not seen. Every number in a motor imagery decoder is a choice of window, taper, average and baseline, and each choice trades one thing for another. A mu drop of 45% only means something when you can say how you got it.

Now press Teach and explain, from memory, how a drop in mu power becomes a number: from the raw (22, 1000) array to a percent of baseline. Then go back to the hero and try each hand again.

Brain Rhythms: BCI series, lesson 12
Back to Gleams