Project F: The software pipeline
From a raw file to cleaned epochs to a topographic map, in MNE-Python, on public data. Build the pipeline before you have your own data so you can trust it when you do.
On this pageTwo evenings
Every EEGElectroencephalography (EEG) Recording the brain's electrical activity from electrodes on the scalp, a few tens of microvolts of blurred, summed cortical activity. Related: Electrocorticography (ECoG)Electrocorticography (ECoG) Recording from electrodes placed on the surface of the brain under the skull, usually during epilepsy surgery evaluation; cleaner and sharper than EEG. , Magnetoencephalography (MEG)Magnetoencephalography (MEG) Recording the tiny magnetic fields produced by cortical currents with superconducting sensors in a shielded room; less blurred by the skull than EEG, and far more expensive. , Volume conductionVolume conduction The spreading of currents from a source through the conductive tissues of the head, which is why one source shows up on many electrodes and why scalp EEG is blurry. , Microvolt (µV)Microvolt (µV) One millionth of a volt. Scalp EEG is tens of microvolts; a AA battery is 1.5 million of them. . Glossary entry analysis is the same six steps: load, filterFilter An operation that passes some frequencies and attenuates others; every filter also delays or distorts the timing of what it passes. Related: High-pass filterHigh-pass filter Removes slow drifts and DC offsets, passing everything above a cutoff; set it too high and you erase slow brain activity. , Low-pass filterLow-pass filter Removes fast content above a cutoff; the anti-alias filter is one, and so is the smoothing you apply to a noisy trace. , Notch filterNotch filter A very narrow filter that removes one frequency, usually 60 Hz mains hum; it also rings and distorts nearby content, so fix the hum at the source first. , Phase distortionPhase distortion Different frequencies being delayed by different amounts, which smears and shifts waveforms such as an ERP peak. . Glossary entry, re-reference, cut into epochsEpoch A fixed-length slice of the recording locked to an event, such as one second starting 200 milliseconds before each stimulus. Related: Trial averagingTrial averaging Adding many time-locked epochs together so the consistent response grows and the random noise shrinks by the square root of the number of trials. , Baseline correctionBaseline correction Subtracting the mean of the pre-stimulus interval from each epoch so trials line up. . Glossary entry around events, remove artifactsArtifact Anything in the recording that did not come from the brain: blinks, muscle, heartbeat, movement, sweat, mains hum, electrode pops. Related: Blink artifactBlink artifact The large, slow deflection an eye blink produces in frontal channels, often ten times the size of the brain signal. , Independent component analysis (ICA)Independent component analysis (ICA) A method that unmixes multichannel data into statistically independent sources, so blinks and heartbeat can be identified and removed. , Artifact subspace reconstruction (ASR)Artifact subspace reconstruction (ASR) An automatic method that detects short high-variance bursts and reconstructs them from clean data; common in real-time pipelines. . Glossary entry, and plot something across the scalp. MNE-PythonMNE-Python The standard open-source Python library for EEG and MEG analysis: filtering, epoching, ICA, topographies, source localization. Related: Independent component analysis (ICA)Independent component analysis (ICA) A method that unmixes multichannel data into statistically independent sources, so blinks and heartbeat can be identified and removed.. Glossary entry does each step in a line or two and is what nearly every lab uses. In this project you build the pipeline on the PhysioNetPhysioNet A free archive of physiological recordings including EEG, ECG, and sleep data, run out of MIT. Related: Sleep-EDFSleep-EDF A public PhysioNet dataset of whole-night sleep recordings with expert stage labels, the standard training set for automatic sleep staging. . Glossary entry motor dataset, where the events are known, so that by the time your own board produces data the pipeline is already tested and you know what every step does to the signal.
You cut the recording into one-second epochs and then apply a 0.5 Hz high-pass filter to each epoch. What goes wrong?
The filterFilter An operation that passes some frequencies and attenuates others; every filter also delays or distorts the timing of what it passes. Related: High-pass filterHigh-pass filter Removes slow drifts and DC offsets, passing everything above a cutoff; set it too high and you erase slow brain activity. , Low-pass filterLow-pass filter Removes fast content above a cutoff; the anti-alias filter is one, and so is the smoothing you apply to a noisy trace. , Notch filterNotch filter A very narrow filter that removes one frequency, usually 60 Hz mains hum; it also rings and distorts nearby content, so fix the hum at the source first. , Phase distortionPhase distortion Different frequencies being delayed by different amounts, which smears and shifts waveforms such as an ERP peak. . Glossary entry cannot do its job on one-second pieces. A 0.5 Hz high-pass has a time constant of a fraction of a second and needs a long stretch of data to settle; applied to a short epochEpoch A fixed-length slice of the recording locked to an event, such as one second starting 200 milliseconds before each stimulus. Related: Trial averagingTrial averaging Adding many time-locked epochs together so the consistent response grows and the random noise shrinks by the square root of the number of trials. , Baseline correctionBaseline correction Subtracting the mean of the pre-stimulus interval from each epoch so trials line up. . Glossary entry it smears the edges and can invent a slope across the whole epochEpoch A fixed-length slice of the recording locked to an event, such as one second starting 200 milliseconds before each stimulus. Related: Trial averagingTrial averaging Adding many time-locked epochs together so the consistent response grows and the random noise shrinks by the square root of the number of trials. , Baseline correctionBaseline correction Subtracting the mean of the pre-stimulus interval from each epoch so trials line up. . Glossary entry. FilterFilter An operation that passes some frequencies and attenuates others; every filter also delays or distorts the timing of what it passes. Related: High-pass filterHigh-pass filter Removes slow drifts and DC offsets, passing everything above a cutoff; set it too high and you erase slow brain activity. , Low-pass filterLow-pass filter Removes fast content above a cutoff; the anti-alias filter is one, and so is the smoothing you apply to a noisy trace. , Notch filterNotch filter A very narrow filter that removes one frequency, usually 60 Hz mains hum; it also rings and distorts nearby content, so fix the hum at the source first. , Phase distortionPhase distortion Different frequencies being delayed by different amounts, which smears and shifts waveforms such as an ERP peak. . Glossary entry the continuous recording first, then cut. This is the single most common ordering mistake and the reason the pipeline’s steps come in the order they do.
The dataset
PhysioNetPhysioNet A free archive of physiological recordings including EEG, ECG, and sleep data, run out of MIT. Related: Sleep-EDFSleep-EDF A public PhysioNet dataset of whole-night sleep recordings with expert stage labels, the standard training set for automatic sleep staging. . Glossary entry EEGElectroencephalography (EEG) Recording the brain's electrical activity from electrodes on the scalp, a few tens of microvolts of blurred, summed cortical activity. Related: Electrocorticography (ECoG)Electrocorticography (ECoG) Recording from electrodes placed on the surface of the brain under the skull, usually during epilepsy surgery evaluation; cleaner and sharper than EEG. , Magnetoencephalography (MEG)Magnetoencephalography (MEG) Recording the tiny magnetic fields produced by cortical currents with superconducting sensors in a shielded room; less blurred by the skull than EEG, and far more expensive. , Volume conductionVolume conduction The spreading of currents from a source through the conductive tissues of the head, which is why one source shows up on many electrodes and why scalp EEG is blurry. , Microvolt (µV)Microvolt (µV) One millionth of a volt. Scalp EEG is tens of microvolts; a AA battery is 1.5 million of them. . Glossary entry Motor Movement/Imagery, runs 3, 7, and 11 for a subject: the subject opens and closes the left or right fist when a target appears. Events are annotated in the file. 64 channels at 160 Hz.
The pipeline
import mne
from mne.datasets import eegbci
raws = []
for run in (3, 7, 11):
path = eegbci.load_data(subject=1, runs=[run])[0]
raw = mne.io.read_raw_edf(path, preload=True)
eegbci.standardize(raw); raw.set_montage('standard_1005')
raws.append(raw)
raw = mne.concatenate_raws(raws)
# 1. filter the continuous data
raw.filter(1., 40., fir_design='firwin')
# 2. re-reference to the average of all channels
raw.set_eeg_reference('average', projection=False)
# 3. events and epochs: T1 = left fist, T2 = right fist
events, event_id = mne.events_from_annotations(raw, event_id=dict(T1=1, T2=2))
epochs = mne.Epochs(raw, events, event_id, tmin=-1., tmax=4., baseline=None, preload=True)
# 4. artifact removal with ICA
ica = mne.preprocessing.ICA(n_components=20, random_state=0)
ica.fit(epochs)
ica.plot_components() # find the blink component by its frontal topography
ica.exclude = [0] # whichever index looked like a blink
epochs_clean = ica.apply(epochs.copy())
# 5. something across the scalp: mu-band power during movement vs. rest
mu = epochs_clean.copy().filter(8., 13.).apply_hilbert(envelope=True)
move = mu.copy().crop(0.5, 3.5).get_data().mean(axis=(0, 2))
rest = mu.copy().crop(-1., 0.).get_data().mean(axis=(0, 2))
mne.viz.plot_topomap((move - rest) / rest, epochs.info)
The final map should show a decrease in mu power over the motor cortex, opposite the moving hand: the event-related desynchronizationEvent-related desynchronization (ERD) The drop in rhythmic power over a cortical area when it becomes active, such as mu weakening when you imagine moving your hand. Related: Sensorimotor rhythm (mu)Sensorimotor rhythm (mu) An 8 to 13 Hz rhythm over motor cortex that weakens when you move, or imagine moving, the corresponding body part., Motor imageryMotor imagery Imagining a movement without making it, which changes rhythms over motor cortex in a way a classifier can sometimes detect.. Glossary entry that motor imageryMotor imagery Imagining a movement without making it, which changes rhythms over motor cortex in a way a classifier can sometimes detect. Related: Sensorimotor rhythm (mu)Sensorimotor rhythm (mu) An 8 to 13 Hz rhythm over motor cortex that weakens when you move, or imagine moving, the corresponding body part. , Event-related desynchronization (ERD)Event-related desynchronization (ERD) The drop in rhythmic power over a cortical area when it becomes active, such as mu weakening when you imagine moving your hand. , BCI inefficiencyBCI inefficiency The finding that around one in five people cannot control a motor-imagery BCI even after training; once called "BCI illiteracy," a label the field is retiring. . Glossary entry BCIsBrain-computer interface (BCI) A system that turns measured brain activity into control of something outside the body, from a cursor to a wheelchair to a speech synthesizer. Related: DecoderDecoder The algorithm that maps neural signals to intended actions, such as a classifier or a Kalman filter. , Closed loopClosed loop A system in which the output feeds back to influence the input, such as a user adjusting their brain activity while watching the cursor it controls. . Glossary entry decode. If it does, your pipeline works end to end on real data.
What each step is for
FilterFilter An operation that passes some frequencies and attenuates others; every filter also delays or distorts the timing of what it passes. Related: High-pass filterHigh-pass filter Removes slow drifts and DC offsets, passing everything above a cutoff; set it too high and you erase slow brain activity. , Low-pass filterLow-pass filter Removes fast content above a cutoff; the anti-alias filter is one, and so is the smoothing you apply to a noisy trace. , Notch filterNotch filter A very narrow filter that removes one frequency, usually 60 Hz mains hum; it also rings and distorts nearby content, so fix the hum at the source first. , Phase distortionPhase distortion Different frequencies being delayed by different amounts, which smears and shifts waveforms such as an ERP peak. . Glossary entry first, on continuous data. The high-pass removes drift; the low-pass removes muscle and hum. FiltersFilter An operation that passes some frequencies and attenuates others; every filter also delays or distorts the timing of what it passes. Related: High-pass filterHigh-pass filter Removes slow drifts and DC offsets, passing everything above a cutoff; set it too high and you erase slow brain activity. , Low-pass filterLow-pass filter Removes fast content above a cutoff; the anti-alias filter is one, and so is the smoothing you apply to a noisy trace. , Notch filterNotch filter A very narrow filter that removes one frequency, usually 60 Hz mains hum; it also rings and distorts nearby content, so fix the hum at the source first. , Phase distortionPhase distortion Different frequencies being delayed by different amounts, which smears and shifts waveforms such as an ERP peak. . Glossary entry need long stretches of data; see the prediction above. MNEMNE-Python The standard open-source Python library for EEG and MEG analysis: filtering, epoching, ICA, topographies, source localization. Related: Independent component analysis (ICA)Independent component analysis (ICA) A method that unmixes multichannel data into statistically independent sources, so blinks and heartbeat can be identified and removed. . Glossary entry’s default FIR filterFIR filter A filter that outputs a weighted sum of recent inputs only; symmetric ones delay every frequency equally, which preserves waveform shape. Related: IIR filterIIR filter A filter that feeds its output back into itself; cheap and sharp, but it delays different frequencies by different amounts. , Phase distortionPhase distortion Different frequencies being delayed by different amounts, which smears and shifts waveforms such as an ERP peak. . Glossary entry is zero-phase, so nothing shifts in time.
Re-reference. The file’s original reference is one electrodeElectrode The conductor that turns ion currents in tissue into electron currents in a wire; its chemistry and contact quality set the noise you live with. Related: Silver/silver-chloride (Ag/AgCl)Silver/silver-chloride (Ag/AgCl) The standard electrode material for biopotentials, because its chemistry produces a stable, low-noise, low-drift interface with salty gel. , Electrode impedanceElectrode impedance How hard it is to push current through the skin-electrode contact, typically 5 to 50 kilohms with gel and megohms dry, higher at low frequencies. , Half-cell potentialHalf-cell potential The DC voltage that appears wherever a metal meets an electrolyte; two electrodes with different half-cell potentials produce an offset that can swamp the signal. . Glossary entry, and everything is measured against it. The average reference subtracts the mean of all channels, which approximates a neutral reference when electrodesElectrode The conductor that turns ion currents in tissue into electron currents in a wire; its chemistry and contact quality set the noise you live with. Related: Silver/silver-chloride (Ag/AgCl)Silver/silver-chloride (Ag/AgCl) The standard electrode material for biopotentials, because its chemistry produces a stable, low-noise, low-drift interface with salty gel. , Electrode impedanceElectrode impedance How hard it is to push current through the skin-electrode contact, typically 5 to 50 kilohms with gel and megohms dry, higher at low frequencies. , Half-cell potentialHalf-cell potential The DC voltage that appears wherever a metal meets an electrolyte; two electrodes with different half-cell potentials produce an offset that can swamp the signal. . Glossary entry cover the head. The montages explainer is about why this changes every plot.
EpochEpoch A fixed-length slice of the recording locked to an event, such as one second starting 200 milliseconds before each stimulus. Related: Trial averagingTrial averaging Adding many time-locked epochs together so the consistent response grows and the random noise shrinks by the square root of the number of trials. , Baseline correctionBaseline correction Subtracting the mean of the pre-stimulus interval from each epoch so trials line up. . Glossary entry. Cut a window around each event. Now you can compare what happened after events to what happened before, and average across events to reduce noise.
Clean. ICAIndependent component analysis (ICA) A method that unmixes multichannel data into statistically independent sources, so blinks and heartbeat can be identified and removed. Related: ArtifactArtifact Anything in the recording that did not come from the brain: blinks, muscle, heartbeat, movement, sweat, mains hum, electrode pops.. Glossary entry unmixes the channels into components; blinks and heartbeat come out as their own components with characteristic topographies, and you subtract them. Look at every component’s map before you exclude it. Never exclude blindly.
Plot across the scalp. The topographic mapTopographic map The head-shaped colour plot of voltage or power at each electrode, interpolated between them. Related: MontageMontage The particular arrangement of which electrodes are subtracted from which, such as referential, bipolar, or average reference. . Glossary entry is EEGElectroencephalography (EEG) Recording the brain's electrical activity from electrodes on the scalp, a few tens of microvolts of blurred, summed cortical activity. Related: Electrocorticography (ECoG)Electrocorticography (ECoG) Recording from electrodes placed on the surface of the brain under the skull, usually during epilepsy surgery evaluation; cleaner and sharper than EEG. , Magnetoencephalography (MEG)Magnetoencephalography (MEG) Recording the tiny magnetic fields produced by cortical currents with superconducting sensors in a shielded room; less blurred by the skull than EEG, and far more expensive. , Volume conductionVolume conduction The spreading of currents from a source through the conductive tissues of the head, which is why one source shows up on many electrodes and why scalp EEG is blurry. , Microvolt (µV)Microvolt (µV) One millionth of a volt. Scalp EEG is tens of microvolts; a AA battery is 1.5 million of them. . Glossary entry’s native picture. Anything you compute per channel can be drawn on the head.
- Run the pipeline as written and get a topographic mapTopographic map The head-shaped colour plot of voltage or power at each electrode, interpolated between them. Related: MontageMontage The particular arrangement of which electrodes are subtracted from which, such as referential, bipolar, or average reference. . Glossary entry. Check that the mu decrease is over the correct hemisphere (left hand moves, right hemisphere decreases).
- Break it on purpose: filterFilter An operation that passes some frequencies and attenuates others; every filter also delays or distorts the timing of what it passes. Related: High-pass filterHigh-pass filter Removes slow drifts and DC offsets, passing everything above a cutoff; set it too high and you erase slow brain activity. , Low-pass filterLow-pass filter Removes fast content above a cutoff; the anti-alias filter is one, and so is the smoothing you apply to a noisy trace. , Notch filterNotch filter A very narrow filter that removes one frequency, usually 60 Hz mains hum; it also rings and distorts nearby content, so fix the hum at the source first. , Phase distortionPhase distortion Different frequencies being delayed by different amounts, which smears and shifts waveforms such as an ERP peak. . Glossary entry after epoching and compare the epochEpoch A fixed-length slice of the recording locked to an event, such as one second starting 200 milliseconds before each stimulus. Related: Trial averagingTrial averaging Adding many time-locked epochs together so the consistent response grows and the random noise shrinks by the square root of the number of trials. , Baseline correctionBaseline correction Subtracting the mean of the pre-stimulus interval from each epoch so trials line up. . Glossary entry edges. Skip re-referencing and compare the map. Skip ICAIndependent component analysis (ICA) A method that unmixes multichannel data into statistically independent sources, so blinks and heartbeat can be identified and removed. Related: ArtifactArtifact Anything in the recording that did not come from the brain: blinks, muscle, heartbeat, movement, sweat, mains hum, electrode pops. . Glossary entry and see whether blinks show up in the frontal channels of the average.
- Wrap the steps in a function that takes a subject number and returns the epochsEpoch A fixed-length slice of the recording locked to an event, such as one second starting 200 milliseconds before each stimulus. Related: Trial averagingTrial averaging Adding many time-locked epochs together so the consistent response grows and the random noise shrinks by the square root of the number of trials. , Baseline correctionBaseline correction Subtracting the mean of the pre-stimulus interval from each epoch so trials line up. . Glossary entry. Run it for five subjects. Note which ones show clean ERDEvent-related desynchronization (ERD) The drop in rhythmic power over a cortical area when it becomes active, such as mu weakening when you imagine moving your hand. Related: Sensorimotor rhythm (mu)Sensorimotor rhythm (mu) An 8 to 13 Hz rhythm over motor cortex that weakens when you move, or imagine moving, the corresponding body part. , Motor imageryMotor imagery Imagining a movement without making it, which changes rhythms over motor cortex in a way a classifier can sometimes detect. . Glossary entry and which do not.
- Save the cleaned epochsEpoch A fixed-length slice of the recording locked to an event, such as one second starting 200 milliseconds before each stimulus. Related: Trial averagingTrial averaging Adding many time-locked epochs together so the consistent response grows and the random noise shrinks by the square root of the number of trials. , Baseline correctionBaseline correction Subtracting the mean of the pre-stimulus interval from each epoch so trials line up. . Glossary entry to disk in MNEMNE-Python The standard open-source Python library for EEG and MEG analysis: filtering, epoching, ICA, topographies, source localization. Related: Independent component analysis (ICA)Independent component analysis (ICA) A method that unmixes multichannel data into statistically independent sources, so blinks and heartbeat can be identified and removed. . Glossary entry’s format. Your Phase 3 projects start from that file.