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.
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
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.
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.
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.
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?
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.
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.
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.
Chapter 1
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.
| Band | Range (Hz) | Where and when it is strong (textbook picture) |
|---|---|---|
| Delta | about 1 to 4 | Deep sleep. Awake, slow drifts of this speed often come from eye blinks and sweat, not from the brain (Chapter 9). |
| Theta | 4 to 8 | Drowsiness, and often reported during memory and focus tasks. |
| Alpha | 8 to 13 | Relaxed wakefulness with eyes closed. Strongest at the back of the head. |
| Beta | 13 to 30 | Alert, active thinking. Also a beta component over the motor strip. |
| Gamma | above 30 | Fast 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.
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.
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.
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.
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.
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.
Chapter 2
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.
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.)
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).
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.
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.
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.
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.
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.
Chapter 3
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.
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.
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.
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.
| Frequency | Rectangular | Hann |
|---|---|---|
| 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.
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.
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.
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.
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.
Chapter 4
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?
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%.
Peter Welch’s 1967 paper gives the recipe. It is written for the fast Fourier transform, then new, which made this cheap.
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.
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.
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.
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.
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.
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).
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.
Chapter 5
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.
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.
A BCI window lasts 1 s at 256 Hz, so N = 256 samples. Choose NW = 3.
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.
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.
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.
Chapter 6
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.
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.
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.
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.
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.
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.
Chapter 7
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.)
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.
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.
Choose n = 5 cycles. Compute the two blurs at three frequencies.
| Frequency | Time blur σt = 5/(2πf) | Frequency blur σf = f/5 |
|---|---|---|
| 4 Hz | 199 ms | 0.8 Hz |
| 10 Hz | 80 ms | 2 Hz |
| 40 Hz | 20 ms | 8 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.
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.
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.
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.
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.
Chapter 8
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.
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.
Work two cases. The baseline power over C3 is R = 40 µV².
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%.
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.
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.
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.
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.
Chapter 9
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.
| Trap | Where it lands | How to spot it | What to do |
|---|---|---|---|
| Eye blinks and eye movements | Delta and theta, strongest at frontal electrodes | Large slow bumps in the raw trace, with a stereotyped frontal shape | Reject the trial, or remove the component (the ICA lesson shows how) |
| Muscle activity (EMG) | Broadband above about 20 Hz; hits beta and gamma | A raised, flat-topped high-frequency floor near the temples and neck; bursts when the jaw moves | Avoid gamma on the scalp unless it is controlled; check with a clenching recording |
| Power-line noise | One sharp spike at 50 or 60 Hz (and its multiples) | A needle in the spectrum at the mains frequency | A notch filter, as the dataset’s amplifier did at 50 Hz, or a spectrum-based cleaner |
| The 1/f floor | Every band: power falls steadily with frequency | A straight line on a log-log plot; its slope can change without any rhythm changing | Measure 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.
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.
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².
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.
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.
Chapter 10
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).
| Term | Value or rule | Where it comes from |
|---|---|---|
| Bands | delta 1 to 4, theta 4 to 8, alpha 8 to 13, beta 13 to 30, gamma above 30 Hz | Convention; edges vary by a hertz or two (Chapter 1) |
| Dataset 2a recording | 9 people, 22 EEG channels, 250 Hz, band-pass 0.5 to 100 Hz, 50 Hz notch, 288 trials per session | BCI Competition IV dataset 2a description |
| Dataset 2a trial | tone at 0 s, cue at 2 s for 1.25 s, imagery until 6 s; left hand, right hand, feet, tongue | Same description |
| Nyquist frequency | fs/2 = 125 Hz at 250 Hz | Chapter 2 |
| Bin width | Δf = fs/N = 1/T (0.25 Hz for 4 s) | Chapter 2 |
| Leakage, 10.5 Hz sine, 128 samples | at 40 Hz: rectangular −40.5 dB, Hann −98.3 dB | Our simulation, Chapter 3 |
| Periodogram PSD | Pk = 2|Xk|²/(fs ∑ w²), in µV²/Hz | Chapter 3 |
| Welch | K = floor((N − L)/step) + 1 segments; noise about 100%/√K; bins fs/L | Welch (1967); Chapter 4 |
| Multitaper | W = NW/T, K = 2NW − 1 tapers, noise about 100%/√K | Thomson (1982); Chapter 5 |
| STFT trade | frequency detail about 1/L, time detail about L | Chapter 6 |
| Morlet wavelet | σt = n/(2πf), σf = f/n, product 1/(2π) | Chapter 7 |
| ERD / ERS | 100 × (A − R)/R, negative is ERD | Pfurtscheller and Lopes da Silva (1999) |
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.
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.
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.