MNE-Python Analysis Guide
Purpose
This skill encodes expert methodological knowledge for analyzing neurophysiological data (EEG, MEG, sEEG, ECoG, NIRS, eye-tracking) using MNE-Python (Gramfort et al., 2013; Gramfort et al., 2014). It covers the complete analysis pipeline with recommended parameters, code examples, and common pitfall warnings.
When to Use This Skill
Activate when the user:
- Asks about EEG/MEG/sEEG/ECoG/NIRS data analysis in Python
- Mentions MNE, MNE-Python, epochs, evoked, Raw, source estimate, ICA, ERP, ERF
- Wants to load neurophysiological data files (.fif, .edf, .bdf, .set, .vhdr, .mff, .cnt, .snirf)
- Needs preprocessing, time-frequency, source localization, decoding, or statistical testing guidance
- Wants to create MNE objects from numpy arrays or simulate data
Research Planning Protocol
- State the research question — What is the user investigating?
- Justify the method choice — Confirm MNE-Python fits their data type and goal.
- Declare expected outcomes — What output format? (ERP plots, TFR maps, source maps, decoding accuracy)
- Note assumptions and limitations — Data quality, sample size, MRI availability, montage info.
- Present the plan and WAIT for confirmation before writing code.
Verification Notice
This skill was generated by AI from MNE-Python source code and academic literature. All parameters, thresholds, and citations require independent verification. If you find errors, please open an issue at https://github.com/NeuroAIHub/awesome_cognitive_and_neuroscience_skills/issues.
Reference Files (Progressive Disclosure)
This skill uses layered references. Read the relevant file when the user's question goes deeper than the overview below:
| Topic |
Reference File |
When to Read |
| Data I/O (30+ formats) |
references/io_formats.md |
User asks about loading specific file formats, creating objects from arrays, or exporting |
| Preprocessing |
references/preprocessing.md |
User needs ICA details, Maxwell filtering, artifact annotation, bad channel detection, CSD, fNIRS/iEEG-specific preprocessing |
| Time-Frequency |
references/time_frequency.md |
User asks about TFR methods, PSD, CSD, baseline modes, array-level functions |
| Source Localization |
references/source_localization.md |
User needs forward modeling, inverse methods, beamformers, dipole fitting details |
| Decoding & MVPA |
references/decoding.md |
User asks about classification, temporal generalization, CSP, SPoC, receptive fields |
| Statistics |
references/statistics.md |
User needs cluster permutation, TFCE, ANOVA, adjacency matrices, correction methods |
| Visualization |
references/visualization.md |
User asks about plotting functions, publication figures, 3D brain rendering |
| Simulation |
references/simulation.md |
User wants to create synthetic data, simulate sources, add artifacts |
Pipeline Overview
Raw → Mark bad channels → Filter → ICA → Re-reference → Resample
→ Epochs → Evoked (ERP/ERF)
→ Time-Frequency (TFR/PSD)
→ Source Localization (MNE/dSPM/LCMV)
→ Decoding (MVPA)
→ Statistics (cluster permutation)
Core Data Structures
| Object |
Description |
Create from |
Raw |
Continuous data |
mne.io.read_raw_*() or mne.io.RawArray(data, info) |
Epochs |
Event-segmented data |
mne.Epochs(raw, events, ...) or mne.EpochsArray(data, info) |
Evoked |
Averaged epochs |
epochs.average() or mne.EvokedArray(data, info) |
SourceEstimate |
Brain-mapped activity |
apply_inverse(evoked, inv, ...) |
Spectrum |
Power spectrum |
raw.compute_psd() or epochs.compute_psd() |
AverageTFR |
Time-frequency map |
epochs.compute_tfr(method, freqs, ...) |
All objects carry an info attribute (mne.Info) with channel metadata that propagates through the pipeline.
Quick Start Pipeline
import mne
import numpy as np
# 1. Load
raw = mne.io.read_raw_fif('data_raw.fif', preload=True)
# or: raw = mne.io.read_raw_edf('data.edf', preload=True)
# 2. Preprocess
raw.filter(l_freq=0.1, h_freq=40.) # bandpass
raw.notch_filter(freqs=[50, 100]) # line noise
ica = mne.preprocessing.ICA(n_components=20, random_state=97, max_iter=800)
ica.fit(raw.copy().filter(l_freq=1., h_freq=None)) # fit on 1 Hz highpass copy
eog_idx, _ = ica.find_bads_eog(raw)
ica.exclude = eog_idx
ica.apply(raw)
raw.set_eeg_reference('average')
# 3. Epoch
events, event_id = mne.events_from_annotations(raw)
epochs = mne.Epochs(raw, events, event_id, tmin=-0.2, tmax=0.5,
baseline=(None, 0), preload=True,
reject=dict(eeg=150e-6))
# 4. ERP
evoked = epochs['target'].average()
evoked.plot_joint()
# 5. Time-frequency
freqs = np.arange(4, 30, 2)
power = epochs.compute_tfr(method="morlet", freqs=freqs, n_cycles=freqs / 2.)
power.plot()
# 6. Source localization (requires anatomy)
noise_cov = mne.compute_covariance(epochs, tmax=0., method='auto')
fwd = mne.read_forward_solution('sample-fwd.fif')
inv = mne.minimum_norm.make_inverse_operator(epochs.info, fwd, noise_cov)
stc = mne.minimum_norm.apply_inverse(evoked, inv, lambda2=1./9., method='dSPM')
# 7. Decoding
from mne.decoding import SlidingEstimator, cross_val_multiscore
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X = epochs.get_data(copy=True)
y = epochs.events[:, -1]
clf = make_pipeline(StandardScaler(), LogisticRegression(solver='liblinear'))
slider = SlidingEstimator(clf, scoring='roc_auc')
scores = cross_val_multiscore(slider, X, y, cv=5)
# 8. Statistics
from mne.stats import spatio_temporal_cluster_test
adjacency, _ = mne.channels.find_ch_adjacency(epochs.info, 'eeg')
T_obs, clusters, p_values, H0 = spatio_temporal_cluster_test(
[X_cond1, X_cond2], adjacency=adjacency, n_permutations=1000)
Common Pitfalls
- ICA on unfiltered data — Highpass ≥1 Hz before ICA fitting; slow drifts degrade decomposition (Jas et al., 2018)
- Baseline correction before ICA — Apply baseline after ICA, not before
- Filtering after epoching — Filter Raw, not Epochs, to avoid edge artifacts (Luck, 2014)
- Wrong rejection thresholds — Start with EEG 100–150 µV, adjust via
epochs.plot_drop_log()
- Forgetting
preload=True — Many operations require data in memory
- Re-referencing timing — Set reference after ICA but before epoching
- Events after resampling — Recompute events after downsampling, or resample Epochs directly
- Legacy API — Use
epochs.compute_tfr() / raw.compute_psd() instead of deprecated tfr_morlet() / psd_welch()
- Decoding data leakage — Always cross-validate; never fit scaler on test data
- Cluster test interpretation — Clusters show where effects exist, not their spatial/temporal extent (Maris & Oostenveld, 2007)
References
- Blankertz, B., et al. (2008). Optimizing spatial filters for robust EEG single-trial analysis. IEEE Signal Processing Magazine, 25(1), 41–56.
- Dale, A. M., et al. (2000). Dynamic statistical parametric mapping. Neuron, 26(1), 55–67.
- Gramfort, A., et al. (2013). MEG and EEG data analysis with MNE-Python. Frontiers in Neuroscience, 7, 267.
- Gramfort, A., et al. (2014). MNE software for processing MEG and EEG data. NeuroImage, 86, 446–460.
- Jas, M., et al. (2018). Autoreject: Automated artifact rejection for MEG and EEG data. NeuroImage, 159, 417–429.
- King, J.-R., & Dehaene, S. (2014). Characterizing the dynamics of mental representations. Trends in Cognitive Sciences, 18(4), 203–210.
- Luck, S. J. (2014). An Introduction to the Event-Related Potential Technique. MIT Press.
- Maris, E., & Oostenveld, R. (2007). Nonparametric statistical testing of EEG- and MEG-data. Journal of Neuroscience Methods, 164(1), 177–190.
- Pascual-Marqui, R. D. (2002). Standardized low-resolution brain electromagnetic tomography. Methods and Findings in Experimental and Clinical Pharmacology, 24(Suppl D), 5–12.
- Tallon-Baudry, C., et al. (1997). Oscillatory gamma-band activity induced by a visual search task. Journal of Neuroscience, 17(2), 722–734.
1---2name: mne-python-guide3description: Domain-validated pipeline guidance for EEG/MEG data analysis using MNE-Python: data loading, preprocessing (filtering, ICA, re-referencing), epoching, ERP/ERF computation, time-frequency decomposition, source localization, decoding/MVPA, statistical testing, simulation, and visualization. Use this skill whenever the user works with EEG/MEG/sEEG/ECoG/NIRS/eye-tracking data in Python, mentions MNE, or needs neurophysiological analysis guidance.4---56# MNE-Python Analysis Guide78## Purpose910This skill encodes expert methodological knowledge for analyzing neurophysiological data (EEG, MEG, sEEG, ECoG, NIRS, eye-tracking) using MNE-Python (Gramfort et al., 2013; Gramfort et al., 2014). It covers the complete analysis pipeline with recommended parameters, code examples, and common pitfall warnings.1112## When to Use This Skill1314Activate when the user:15- Asks about EEG/MEG/sEEG/ECoG/NIRS data analysis in Python16- Mentions MNE, MNE-Python, epochs, evoked, Raw, source estimate, ICA, ERP, ERF17- Wants to load neurophysiological data files (.fif, .edf, .bdf, .set, .vhdr, .mff, .cnt, .snirf)18- Needs preprocessing, time-frequency, source localization, decoding, or statistical testing guidance19- Wants to create MNE objects from numpy arrays or simulate data2021## Research Planning Protocol22231. **State the research question** — What is the user investigating?242. **Justify the method choice** — Confirm MNE-Python fits their data type and goal.253. **Declare expected outcomes** — What output format? (ERP plots, TFR maps, source maps, decoding accuracy)264. **Note assumptions and limitations** — Data quality, sample size, MRI availability, montage info.275. **Present the plan and WAIT for confirmation** before writing code.2829## Verification Notice3031> This skill was generated by AI from MNE-Python source code and academic literature. All parameters, thresholds, and citations require independent verification. If you find errors, please open an issue at https://github.com/NeuroAIHub/awesome_cognitive_and_neuroscience_skills/issues.3233## Reference Files (Progressive Disclosure)3435This skill uses layered references. Read the relevant file when the user's question goes deeper than the overview below:3637| Topic | Reference File | When to Read |38|-------|---------------|--------------|39| Data I/O (30+ formats) | `references/io_formats.md` | User asks about loading specific file formats, creating objects from arrays, or exporting |40| Preprocessing | `references/preprocessing.md` | User needs ICA details, Maxwell filtering, artifact annotation, bad channel detection, CSD, fNIRS/iEEG-specific preprocessing |41| Time-Frequency | `references/time_frequency.md` | User asks about TFR methods, PSD, CSD, baseline modes, array-level functions |42| Source Localization | `references/source_localization.md` | User needs forward modeling, inverse methods, beamformers, dipole fitting details |43| Decoding & MVPA | `references/decoding.md` | User asks about classification, temporal generalization, CSP, SPoC, receptive fields |44| Statistics | `references/statistics.md` | User needs cluster permutation, TFCE, ANOVA, adjacency matrices, correction methods |45| Visualization | `references/visualization.md` | User asks about plotting functions, publication figures, 3D brain rendering |46| Simulation | `references/simulation.md` | User wants to create synthetic data, simulate sources, add artifacts |4748## Pipeline Overview4950```51Raw → Mark bad channels → Filter → ICA → Re-reference → Resample52 → Epochs → Evoked (ERP/ERF)53 → Time-Frequency (TFR/PSD)54 → Source Localization (MNE/dSPM/LCMV)55 → Decoding (MVPA)56 → Statistics (cluster permutation)57```5859## Core Data Structures6061| Object | Description | Create from |62|--------|-------------|-------------|63| `Raw` | Continuous data | `mne.io.read_raw_*()` or `mne.io.RawArray(data, info)` |64| `Epochs` | Event-segmented data | `mne.Epochs(raw, events, ...)` or `mne.EpochsArray(data, info)` |65| `Evoked` | Averaged epochs | `epochs.average()` or `mne.EvokedArray(data, info)` |66| `SourceEstimate` | Brain-mapped activity | `apply_inverse(evoked, inv, ...)` |67| `Spectrum` | Power spectrum | `raw.compute_psd()` or `epochs.compute_psd()` |68| `AverageTFR` | Time-frequency map | `epochs.compute_tfr(method, freqs, ...)` |6970All objects carry an `info` attribute (`mne.Info`) with channel metadata that propagates through the pipeline.7172## Quick Start Pipeline7374```python75import mne76import numpy as np7778# 1. Load79raw = mne.io.read_raw_fif('data_raw.fif', preload=True)80# or: raw = mne.io.read_raw_edf('data.edf', preload=True)8182# 2. Preprocess83raw.filter(l_freq=0.1, h_freq=40.) # bandpass84raw.notch_filter(freqs=[50, 100]) # line noise85ica = mne.preprocessing.ICA(n_components=20, random_state=97, max_iter=800)86ica.fit(raw.copy().filter(l_freq=1., h_freq=None)) # fit on 1 Hz highpass copy87eog_idx, _ = ica.find_bads_eog(raw)88ica.exclude = eog_idx89ica.apply(raw)90raw.set_eeg_reference('average')9192# 3. Epoch93events, event_id = mne.events_from_annotations(raw)94epochs = mne.Epochs(raw, events, event_id, tmin=-0.2, tmax=0.5,95 baseline=(None, 0), preload=True,96 reject=dict(eeg=150e-6))9798# 4. ERP99evoked = epochs['target'].average()100evoked.plot_joint()101102# 5. Time-frequency103freqs = np.arange(4, 30, 2)104power = epochs.compute_tfr(method="morlet", freqs=freqs, n_cycles=freqs / 2.)105power.plot()106107# 6. Source localization (requires anatomy)108noise_cov = mne.compute_covariance(epochs, tmax=0., method='auto')109fwd = mne.read_forward_solution('sample-fwd.fif')110inv = mne.minimum_norm.make_inverse_operator(epochs.info, fwd, noise_cov)111stc = mne.minimum_norm.apply_inverse(evoked, inv, lambda2=1./9., method='dSPM')112113# 7. Decoding114from mne.decoding import SlidingEstimator, cross_val_multiscore115from sklearn.linear_model import LogisticRegression116from sklearn.pipeline import make_pipeline117from sklearn.preprocessing import StandardScaler118X = epochs.get_data(copy=True)119y = epochs.events[:, -1]120clf = make_pipeline(StandardScaler(), LogisticRegression(solver='liblinear'))121slider = SlidingEstimator(clf, scoring='roc_auc')122scores = cross_val_multiscore(slider, X, y, cv=5)123124# 8. Statistics125from mne.stats import spatio_temporal_cluster_test126adjacency, _ = mne.channels.find_ch_adjacency(epochs.info, 'eeg')127T_obs, clusters, p_values, H0 = spatio_temporal_cluster_test(128 [X_cond1, X_cond2], adjacency=adjacency, n_permutations=1000)129```130131## Common Pitfalls1321331. **ICA on unfiltered data** — Highpass ≥1 Hz before ICA fitting; slow drifts degrade decomposition (Jas et al., 2018)1342. **Baseline correction before ICA** — Apply baseline after ICA, not before1353. **Filtering after epoching** — Filter Raw, not Epochs, to avoid edge artifacts (Luck, 2014)1364. **Wrong rejection thresholds** — Start with EEG 100–150 µV, adjust via `epochs.plot_drop_log()`1375. **Forgetting `preload=True`** — Many operations require data in memory1386. **Re-referencing timing** — Set reference after ICA but before epoching1397. **Events after resampling** — Recompute events after downsampling, or resample Epochs directly1408. **Legacy API** — Use `epochs.compute_tfr()` / `raw.compute_psd()` instead of deprecated `tfr_morlet()` / `psd_welch()`1419. **Decoding data leakage** — Always cross-validate; never fit scaler on test data14210. **Cluster test interpretation** — Clusters show where effects exist, not their spatial/temporal extent (Maris & Oostenveld, 2007)143144## References145146- Blankertz, B., et al. (2008). Optimizing spatial filters for robust EEG single-trial analysis. *IEEE Signal Processing Magazine*, 25(1), 41–56.147- Dale, A. M., et al. (2000). Dynamic statistical parametric mapping. *Neuron*, 26(1), 55–67.148- Gramfort, A., et al. (2013). MEG and EEG data analysis with MNE-Python. *Frontiers in Neuroscience*, 7, 267.149- Gramfort, A., et al. (2014). MNE software for processing MEG and EEG data. *NeuroImage*, 86, 446–460.150- Jas, M., et al. (2018). Autoreject: Automated artifact rejection for MEG and EEG data. *NeuroImage*, 159, 417–429.151- King, J.-R., & Dehaene, S. (2014). Characterizing the dynamics of mental representations. *Trends in Cognitive Sciences*, 18(4), 203–210.152- Luck, S. J. (2014). *An Introduction to the Event-Related Potential Technique*. MIT Press.153- Maris, E., & Oostenveld, R. (2007). Nonparametric statistical testing of EEG- and MEG-data. *Journal of Neuroscience Methods*, 164(1), 177–190.154- Pascual-Marqui, R. D. (2002). Standardized low-resolution brain electromagnetic tomography. *Methods and Findings in Experimental and Clinical Pharmacology*, 24(Suppl D), 5–12.155- Tallon-Baudry, C., et al. (1997). Oscillatory gamma-band activity induced by a visual search task. *Journal of Neuroscience*, 17(2), 722–734.