0
# MNE-Python
1
2
A comprehensive Python library for analyzing magnetoencephalography (MEG), electroencephalography (EEG), and other neuroimaging data. MNE-Python provides complete workflows from raw data processing through advanced source estimation and connectivity analysis, supporting over 20 file formats and offering both command-line tools and programmatic APIs.
3
4
## Package Information
5
6
- **Package Name**: mne
7
- **Language**: Python
8
- **Installation**: `pip install mne`
9
- **Documentation**: https://mne.tools/
10
11
## Core Imports
12
13
```python
14
import mne
15
```
16
17
Common patterns for data loading and analysis:
18
19
```python
20
import mne
21
from mne import read_raw_fif, create_info, EpochsArray
22
from mne.preprocessing import ICA
23
from mne.time_frequency import tfr_morlet
24
import numpy as np
25
```
26
27
## Basic Usage
28
29
```python
30
import mne
31
import numpy as np
32
33
# Load sample data
34
sample_data_folder = mne.datasets.sample.data_path()
35
sample_data_raw_file = (sample_data_folder / 'MEG' / 'sample' /
36
'sample_audvis_filt-0-40_raw.fif')
37
raw = mne.io.read_raw_fif(sample_data_raw_file, preload=True)
38
39
# Basic preprocessing
40
raw.filter(1, 40, fir_design='firwin') # Band-pass filter
41
raw.notch_filter(60) # Remove line noise
42
43
# Create epochs around events
44
events = mne.find_events(raw)
45
epochs = mne.Epochs(raw, events, tmin=-0.2, tmax=0.5, preload=True)
46
47
# Compute evoked response
48
evoked = epochs.average()
49
50
# Visualize data
51
raw.plot() # Interactive raw data browser
52
evoked.plot() # Plot evoked response
53
evoked.plot_topomap() # Topographic map
54
```
55
56
## Architecture
57
58
MNE-Python follows a modular architecture organized around key data structures and processing stages:
59
60
- **Core Data Containers**: `Raw`, `Epochs`, `Evoked`, `Info` objects store and manage neuroimaging data with rich metadata
61
- **I/O Module**: Comprehensive support for 20+ file formats with unified interfaces
62
- **Preprocessing Pipeline**: Filtering, artifact detection, ICA, Maxwell filtering, and signal space projection
63
- **Time-Frequency Analysis**: Spectral estimation, wavelets, cross-spectral density, and connectivity
64
- **Source Analysis**: Forward modeling, minimum norm estimation, beamforming, and dipole fitting
65
- **Statistical Framework**: Cluster-based permutation testing and multiple comparisons correction
66
- **Visualization Engine**: Interactive plotting, 3D brain visualization, and publication-quality figures
67
68
This design enables seamless data flow from raw recordings to publication-ready results while maintaining flexibility for custom analysis workflows.
69
70
## Capabilities
71
72
### Data Input/Output
73
74
Complete support for neuroimaging file formats including FIF, EDF, BrainVision, EEGLAB, CTF, KIT, and many others. Provides unified interfaces for reading, writing, and converting between formats.
75
76
```python { .api }
77
def read_raw_fif(fname: str, preload: bool = False) -> Raw: ...
78
def read_raw_edf(fname: str, preload: bool = False) -> Raw: ...
79
def read_epochs(fname: str, preload: bool = True) -> Epochs: ...
80
def read_evokeds(fname: str) -> List[Evoked]: ...
81
def create_info(ch_names: List[str], sfreq: float, ch_types: Union[str, List[str]]) -> Info: ...
82
def find_events(raw: Raw, stim_channel: Optional[str] = None) -> ArrayLike: ...
83
def compute_covariance(epochs: Epochs, tmin: Optional[float] = None, tmax: Optional[float] = None) -> Covariance: ...
84
```
85
86
[Data I/O](./data-io.md)
87
88
### Data Preprocessing
89
90
Comprehensive preprocessing tools including filtering, artifact detection and removal, independent component analysis (ICA), Maxwell filtering, and signal space projection (SSP).
91
92
```python { .api }
93
class ICA:
94
def fit(self, inst: Union[Raw, Epochs], picks: Optional[Union[str, List]] = None) -> 'ICA': ...
95
def apply(self, inst: Union[Raw, Epochs], exclude: Optional[List[int]] = None) -> Union[Raw, Epochs]: ...
96
def find_bads_ecg(self, inst: Union[Raw, Epochs]) -> List[int]: ...
97
98
def maxwell_filter(raw: Raw, origin: Union[str, Tuple[float, float, float]] = 'auto') -> Raw: ...
99
def annotate_amplitude(raw: Raw, peak: Optional[float] = None) -> Annotations: ...
100
```
101
102
[Preprocessing](./preprocessing.md)
103
104
### Time-Frequency Analysis
105
106
Advanced spectral analysis including power spectral density estimation, time-frequency decomposition using wavelets and multitaper methods, and cross-spectral density computation.
107
108
```python { .api }
109
def tfr_morlet(epochs: Epochs, freqs: ArrayLike, n_cycles: Union[float, ArrayLike]) -> AverageTFR: ...
110
def psd_welch(inst: Union[Raw, Epochs], fmin: float = 0, fmax: float = np.inf) -> Spectrum: ...
111
def csd_morlet(epochs: Epochs, frequencies: ArrayLike) -> CrossSpectralDensity: ...
112
113
class Spectrum:
114
def plot(self, picks: Optional[Union[str, List]] = None) -> Figure: ...
115
def plot_topomap(self, bands: Dict[str, Tuple[float, float]]) -> Figure: ...
116
```
117
118
[Time-Frequency Analysis](./time-frequency.md)
119
120
### Source Analysis and Inverse Solutions
121
122
Complete source analysis pipeline including forward modeling, boundary element modeling, minimum norm estimation, beamforming, and dipole fitting for localizing brain activity.
123
124
```python { .api }
125
def make_forward_solution(info: Info, trans: Transform, src: SourceSpaces, bem: Union[str, BEM]) -> Forward: ...
126
def make_inverse_operator(info: Info, forward: Forward, noise_cov: Covariance) -> InverseOperator: ...
127
def apply_inverse(evoked: Evoked, inverse_operator: InverseOperator, lambda2: float) -> SourceEstimate: ...
128
def make_lcmv(info: Info, forward: Forward, data_cov: Covariance) -> Beamformer: ...
129
```
130
131
[Source Analysis](./source-analysis.md)
132
133
### Statistical Analysis
134
135
Statistical methods including cluster-based permutation testing, multiple comparisons correction, and specialized ERP analysis tools designed for neuroimaging data.
136
137
```python { .api }
138
def permutation_cluster_test(X: ArrayLike, threshold: float, adjacency: Optional[ArrayLike] = None) -> Tuple: ...
139
def fdr_correction(pvals: ArrayLike, alpha: float = 0.05) -> Tuple[ArrayLike, float]: ...
140
def linear_regression(design_matrix: ArrayLike, data: ArrayLike) -> Dict: ...
141
```
142
143
[Statistical Analysis](./statistics.md)
144
145
### Visualization
146
147
Comprehensive visualization tools including interactive data browsers, topographic maps, 3D brain visualization, and publication-quality plotting functions.
148
149
```python { .api }
150
def plot_topomap(data: ArrayLike, info: Info, **kwargs) -> Figure: ...
151
def plot_evoked_joint(evoked: Evoked, times: Optional[ArrayLike] = None) -> Figure: ...
152
153
class Brain:
154
def __init__(self, subject: str, hemi: str, surf: str, subjects_dir: str): ...
155
def add_data(self, array: ArrayLike, **kwargs) -> Brain: ...
156
```
157
158
[Visualization](./visualization.md)
159
160
### Machine Learning and Decoding
161
162
Machine learning tools for decoding neural signals including common spatial patterns (CSP), temporal decoding, encoding models, and cross-validation utilities.
163
164
```python { .api }
165
class CSP:
166
def fit(self, X: ArrayLike, y: ArrayLike) -> 'CSP': ...
167
def transform(self, X: ArrayLike) -> ArrayLike: ...
168
169
class SlidingEstimator:
170
def __init__(self, base_estimator, scoring: Optional[str] = None): ...
171
def fit(self, X: ArrayLike, y: ArrayLike) -> 'SlidingEstimator': ...
172
def predict(self, X: ArrayLike) -> ArrayLike: ...
173
```
174
175
[Machine Learning](./machine-learning.md)
176
177
### Sample Datasets
178
179
Built-in access to standard neuroimaging datasets for testing, tutorials, and benchmarking including sample MEG/EEG data, phantom measurements, and specialized datasets.
180
181
```python { .api }
182
def data_path(path: Optional[str] = None, force_update: bool = False) -> str: ...
183
def load_data(path: Optional[str] = None) -> Dict: ...
184
185
# Available datasets
186
sample: SampleDataset
187
somato: SomatoDataset
188
multimodal: MultimodalDataset
189
spm_face: SPMFaceDataset
190
```
191
192
[Sample Datasets](./datasets.md)
193
194
## Types
195
196
```python { .api }
197
class Info:
198
"""Measurement information container with channel details and acquisition parameters."""
199
ch_names: List[str]
200
sfreq: float
201
bads: List[str]
202
def copy(self) -> 'Info': ...
203
204
class Raw:
205
"""Continuous data container with methods for filtering and preprocessing."""
206
info: Info
207
def load_data(self) -> 'Raw': ...
208
def filter(self, l_freq: Optional[float], h_freq: Optional[float]) -> 'Raw': ...
209
def plot(self, **kwargs) -> Figure: ...
210
211
class Epochs:
212
"""Epoched data container for event-related analysis."""
213
info: Info
214
events: ArrayLike
215
def average(self) -> Evoked: ...
216
def get_data(self) -> ArrayLike: ...
217
218
class Evoked:
219
"""Averaged evoked response container."""
220
info: Info
221
data: ArrayLike
222
times: ArrayLike
223
def plot(self, **kwargs) -> Figure: ...
224
def plot_topomap(self, **kwargs) -> Figure: ...
225
226
class SourceEstimate:
227
"""Source-level activity estimates on cortical surface."""
228
data: ArrayLike
229
vertices: List[ArrayLike]
230
tmin: float
231
tstep: float
232
def plot(self, **kwargs) -> Brain: ...
233
```