CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-mne

MNE-Python provides comprehensive tools for analyzing MEG, EEG, and other neuroimaging data with advanced source estimation and connectivity analysis.

Pending
Overview
Eval results
Files

source-analysis.mddocs/

Source Analysis

Complete source analysis pipeline including forward modeling, boundary element modeling, minimum norm estimation, beamforming, and dipole fitting for localizing brain activity from MEG/EEG measurements.

Capabilities

Forward Modeling

Create forward solutions that model how brain activity propagates to sensors.

def make_forward_solution(info: Info, trans: Union[str, Transform], src: Union[str, SourceSpaces],
                         bem: Union[str, Dict], meg: bool = True, eeg: bool = True,
                         mindist: float = 0.0, ignore_ref: bool = False,
                         n_jobs: int = 1, verbose: Optional[Union[bool, str, int]] = None) -> Forward:
    """
    Create forward solution from BEM model and source space.
    
    Parameters:
    - info: Measurement info
    - trans: Head<->MRI coordinate transformation
    - src: Source space or path to source space file
    - bem: BEM model or path to BEM solution
    - meg: Include MEG channels
    - eeg: Include EEG channels
    - mindist: Minimum distance from sources to inner skull
    - ignore_ref: Ignore reference channels
    - n_jobs: Number of parallel jobs
    - verbose: Verbosity level
    
    Returns:
    Forward solution object
    """

def read_forward_solution(fname: str, include: Optional[List[str]] = None,
                         exclude: Optional[List[str]] = None,
                         verbose: Optional[Union[bool, str, int]] = None) -> Forward:
    """
    Read forward solution from file.
    
    Parameters:
    - fname: Path to forward solution file
    - include: Channel types to include
    - exclude: Channel types to exclude
    - verbose: Verbosity level
    
    Returns:
    Forward solution object
    """

def apply_forward(fwd: Forward, stc: SourceEstimate, info: Info,
                 start: Optional[int] = None, stop: Optional[int] = None,
                 use_cps: bool = True, verbose: Optional[Union[bool, str, int]] = None) -> Evoked:
    """
    Apply forward solution to source estimate.
    
    Parameters:
    - fwd: Forward solution
    - stc: Source estimate
    - info: Measurement info for output
    - start: Start sample index
    - stop: Stop sample index
    - use_cps: Use complex-valued source estimates
    - verbose: Verbosity level
    
    Returns:
    Evoked object with simulated sensor data
    """

def convert_forward_solution(fwd: Forward, surf_ori: bool = False, force_fixed: bool = False,
                           copy: bool = True, use_cps: bool = True,
                           verbose: Optional[Union[bool, str, int]] = None) -> Forward:
    """
    Convert forward solution between different formats.
    
    Parameters:
    - fwd: Forward solution to convert
    - surf_ori: Use surface-based orientation constraint
    - force_fixed: Force fixed orientation
    - copy: Make copy of forward solution
    - use_cps: Use complex-valued computations
    - verbose: Verbosity level
    
    Returns:
    Converted forward solution
    """

Source Spaces

Create and manipulate source spaces defining locations where brain activity is estimated.

def setup_source_space(subject: str, spacing: Union[str, int] = 'oct6',
                      surface: str = 'white', subjects_dir: Optional[str] = None,
                      add_dist: bool = True, n_jobs: int = 1,
                      verbose: Optional[Union[bool, str, int]] = None) -> SourceSpaces:
    """
    Set up cortical source space.
    
    Parameters:
    - subject: Subject name
    - spacing: Source spacing ('oct6', 'oct5', 'ico4', etc.)
    - surface: Cortical surface to use
    - subjects_dir: FreeSurfer subjects directory
    - add_dist: Add distance information
    - n_jobs: Number of parallel jobs
    - verbose: Verbosity level
    
    Returns:
    SourceSpaces object
    """

def setup_volume_source_space(subject: str, pos: Union[float, Dict] = 5.0,
                             mri: Optional[str] = None, sphere: Optional[Tuple[float, float, float, float]] = None,
                             bem: Optional[Union[str, Dict]] = None, surface: Optional[str] = None,
                             mindist: float = 5.0, exclude: float = 0.0,
                             subjects_dir: Optional[str] = None, volume_label: Optional[Union[str, List[str]]] = None,
                             add_interpolator: bool = True, verbose: Optional[Union[bool, str, int]] = None) -> SourceSpaces:
    """
    Set up volume source space.
    
    Parameters:
    - subject: Subject name
    - pos: Source positions (grid spacing or position dictionary)
    - mri: MRI filename for coordinate system
    - sphere: Sphere parameters for source space
    - bem: BEM model for source space boundary
    - surface: Surface for source space boundary
    - mindist: Minimum distance from sources to boundary
    - exclude: Exclusion distance from boundary
    - subjects_dir: FreeSurfer subjects directory
    - volume_label: Volume label(s) to restrict sources
    - add_interpolator: Add volume interpolator
    - verbose: Verbosity level
    
    Returns:
    Volume SourceSpaces object
    """

def read_source_spaces(fname: str, patch_stats: bool = False,
                      verbose: Optional[Union[bool, str, int]] = None) -> SourceSpaces:
    """
    Read source spaces from file.
    
    Parameters:
    - fname: Path to source space file
    - patch_stats: Add patch statistics
    - verbose: Verbosity level
    
    Returns:
    SourceSpaces object
    """

def morph_source_spaces(src_from: SourceSpaces, subject_to: str,
                       surf: str = 'white', subjects_dir: Optional[str] = None,
                       verbose: Optional[Union[bool, str, int]] = None) -> SourceSpaces:
    """
    Morph source space from one subject to another.
    
    Parameters:
    - src_from: Source space to morph
    - subject_to: Target subject
    - surf: Surface to use for morphing
    - subjects_dir: FreeSurfer subjects directory
    - verbose: Verbosity level
    
    Returns:
    Morphed SourceSpaces object
    """

Boundary Element Modeling (BEM)

Create and manipulate boundary element models for forward solution computation.

def make_bem_model(subject: str, ico: Optional[int] = 4, conductivity: Tuple[float, ...] = (0.3, 0.006, 0.3),
                  subjects_dir: Optional[str] = None, verbose: Optional[Union[bool, str, int]] = None) -> List[Dict]:
    """
    Create BEM model surfaces.
    
    Parameters:
    - subject: Subject name
    - ico: Icosahedron subdivision level
    - conductivity: Conductivity values for each surface
    - subjects_dir: FreeSurfer subjects directory
    - verbose: Verbosity level
    
    Returns:
    List of BEM surface dictionaries
    """

def make_bem_solution(surfs: List[Dict], verbose: Optional[Union[bool, str, int]] = None) -> Dict:
    """
    Create BEM solution from surfaces.
    
    Parameters:
    - surfs: BEM surfaces from make_bem_model
    - verbose: Verbosity level
    
    Returns:
    BEM solution dictionary
    """

def read_bem_solution(fname: str, verbose: Optional[Union[bool, str, int]] = None) -> Dict:
    """
    Read BEM solution from file.
    
    Parameters:
    - fname: Path to BEM solution file
    - verbose: Verbosity level
    
    Returns:
    BEM solution dictionary
    """

def make_sphere_model(r0: Tuple[float, float, float] = (0.0, 0.0, 0.04),
                     head_radius: Optional[float] = None,
                     info: Optional[Info] = None, relative_radii: Tuple[float, ...] = (0.90, 0.92, 1.0),
                     sigmas: Tuple[float, ...] = (0.33, 0.004, 0.33),
                     verbose: Optional[Union[bool, str, int]] = None) -> Dict:
    """
    Create spherical head model.
    
    Parameters:
    - r0: Head center coordinates
    - head_radius: Head radius
    - info: Measurement info for automatic head radius
    - relative_radii: Relative radii of spherical shells
    - sigmas: Conductivity values
    - verbose: Verbosity level
    
    Returns:
    Spherical BEM model dictionary
    """

Minimum Norm Estimation

Compute distributed source estimates using minimum norm methods.

def make_inverse_operator(info: Info, forward: Forward, noise_cov: Covariance,
                         loose: Union[float, str] = 0.2, depth: Optional[float] = 0.8,
                         fixed: bool = False, limit_depth_chs: bool = True,
                         use_cps: bool = True, verbose: Optional[Union[bool, str, int]] = None) -> InverseOperator:
    """
    Create inverse operator for source estimation.
    
    Parameters:
    - info: Measurement info
    - forward: Forward solution
    - noise_cov: Noise covariance matrix
    - loose: Loose orientation constraint (0-1)
    - depth: Depth weighting parameter
    - fixed: Use fixed orientation constraint
    - limit_depth_chs: Limit depth weighting to channels
    - use_cps: Use cortical patch statistics
    - verbose: Verbosity level
    
    Returns:
    InverseOperator object
    """

def apply_inverse(evoked: Evoked, inverse_operator: InverseOperator, lambda2: float,
                 method: str = 'dSPM', pick_ori: Optional[str] = None,
                 prepared: bool = False, label: Optional[Label] = None,
                 method_params: Optional[Dict] = None, return_residual: bool = False,
                 use_cps: bool = True, verbose: Optional[Union[bool, str, int]] = None) -> SourceEstimate:
    """
    Apply inverse operator to evoked data.
    
    Parameters:
    - evoked: Evoked data
    - inverse_operator: Inverse operator
    - lambda2: Regularization parameter
    - method: Inverse method ('MNE', 'dSPM', 'sLORETA', 'eLORETA')
    - pick_ori: Orientation picking ('normal', 'max-power')
    - prepared: Whether inverse operator is prepared
    - label: Restrict sources to label
    - method_params: Additional method parameters
    - return_residual: Return residual as well
    - use_cps: Use cortical patch statistics
    - verbose: Verbosity level
    
    Returns:
    SourceEstimate object
    """

def apply_inverse_epochs(epochs: Epochs, inverse_operator: InverseOperator, lambda2: float,
                        method: str = 'dSPM', pick_ori: Optional[str] = None,
                        prepared: bool = False, label: Optional[Label] = None,
                        method_params: Optional[Dict] = None, return_generator: bool = False,
                        use_cps: bool = True, verbose: Optional[Union[bool, str, int]] = None) -> List[SourceEstimate]:
    """
    Apply inverse operator to epochs.
    
    Parameters:
    - epochs: Epochs data
    - inverse_operator: Inverse operator
    - lambda2: Regularization parameter
    - method: Inverse method
    - pick_ori: Orientation picking
    - prepared: Whether inverse operator is prepared
    - label: Restrict sources to label
    - method_params: Additional method parameters
    - return_generator: Return generator instead of list
    - use_cps: Use cortical patch statistics
    - verbose: Verbosity level
    
    Returns:
    List of SourceEstimate objects
    """

def compute_source_psd(raw: Raw, inverse_operator: InverseOperator, lambda2: float = 1.0 / 9.0,
                      method: str = 'dSPM', tmin: Optional[float] = None, tmax: Optional[float] = None,
                      fmin: float = 0.0, fmax: float = 200.0, pick_ori: Optional[str] = None,
                      label: Optional[Label] = None, n_fft: int = 2048, overlap: float = 0.5,
                      prepared: bool = False, method_params: Optional[Dict] = None,
                      dB: bool = False, return_sensor: bool = False,
                      bandwidth: str = 'hann', adaptive: bool = False, low_bias: bool = True,
                      normalization: str = 'length', n_jobs: int = 1,
                      verbose: Optional[Union[bool, str, int]] = None) -> SourceEstimate:
    """
    Compute source power spectral density using minimum norm.
    
    Parameters:
    - raw: Raw data
    - inverse_operator: Inverse operator
    - lambda2: Regularization parameter
    - method: Inverse method
    - tmin: Start time
    - tmax: End time
    - fmin: Minimum frequency
    - fmax: Maximum frequency
    - pick_ori: Orientation picking
    - label: Restrict to label
    - n_fft: FFT length
    - overlap: Overlap fraction
    - prepared: Whether inverse is prepared
    - method_params: Method parameters
    - dB: Return in decibels
    - return_sensor: Return sensor PSD as well
    - bandwidth: Multitaper bandwidth
    - adaptive: Use adaptive weights
    - low_bias: Reduce bias
    - normalization: Normalization method
    - n_jobs: Number of parallel jobs
    - verbose: Verbosity level
    
    Returns:
    SourceEstimate with PSD data
    """

Beamforming

Use beamforming methods for source estimation with spatial filtering.

def make_lcmv(info: Info, forward: Forward, data_cov: Covariance, reg: float = 0.05,
             noise_cov: Optional[Covariance] = None, label: Optional[Label] = None,
             pick_ori: Optional[str] = None, rank: Optional[Union[str, int, Dict]] = None,
             weight_norm: Optional[str] = 'unit-noise-gain', reduce_rank: bool = False,
             depth: Optional[float] = None, inversion: str = 'matrix',
             verbose: Optional[Union[bool, str, int]] = None) -> Dict:
    """
    Compute LCMV (linearly constrained minimum variance) beamformer weights.
    
    Parameters:
    - info: Measurement info
    - forward: Forward solution
    - data_cov: Data covariance matrix
    - reg: Regularization parameter
    - noise_cov: Noise covariance matrix
    - label: Restrict to label
    - pick_ori: Orientation constraint
    - rank: Data rank specification
    - weight_norm: Weight normalization
    - reduce_rank: Reduce rank of covariance
    - depth: Depth weighting
    - inversion: Matrix inversion method
    - verbose: Verbosity level
    
    Returns:
    Dictionary with beamformer weights and filters
    """

def apply_lcmv(evoked: Evoked, filters: Dict, max_ori_out: str = 'signed',
              verbose: Optional[Union[bool, str, int]] = None) -> SourceEstimate:
    """
    Apply LCMV beamformer to evoked data.
    
    Parameters:
    - evoked: Evoked data to beamform
    - filters: LCMV filters from make_lcmv
    - max_ori_out: Maximum orientation output
    - verbose: Verbosity level
    
    Returns:
    SourceEstimate with beamformed data
    """

def apply_lcmv_epochs(epochs: Epochs, filters: Dict, max_ori_out: str = 'signed',
                     return_generator: bool = False, verbose: Optional[Union[bool, str, int]] = None) -> List[SourceEstimate]:
    """
    Apply LCMV beamformer to epochs.
    
    Parameters:
    - epochs: Epochs data to beamform
    - filters: LCMV filters from make_lcmv
    - max_ori_out: Maximum orientation output
    - return_generator: Return generator instead of list
    - verbose: Verbosity level
    
    Returns:
    List of SourceEstimate objects
    """

def make_dics(info: Info, forward: Forward, csd: CrossSpectralDensity, reg: float = 0.05,
             label: Optional[Label] = None, pick_ori: Optional[str] = None,
             rank: Optional[Union[str, int, Dict]] = None, weight_norm: Optional[str] = 'unit-noise-gain',
             reduce_rank: bool = False, depth: Optional[float] = None,
             real_filter: bool = True, inversion: str = 'matrix',
             verbose: Optional[Union[bool, str, int]] = None) -> Dict:
    """
    Compute DICS (Dynamic Imaging of Coherent Sources) beamformer weights.
    
    Parameters:
    - info: Measurement info
    - forward: Forward solution
    - csd: Cross-spectral density matrix
    - reg: Regularization parameter
    - label: Restrict to label
    - pick_ori: Orientation constraint
    - rank: Data rank specification
    - weight_norm: Weight normalization
    - reduce_rank: Reduce rank of CSD matrix
    - depth: Depth weighting
    - real_filter: Use real-valued filters
    - inversion: Matrix inversion method
    - verbose: Verbosity level
    
    Returns:
    Dictionary with DICS beamformer weights and filters
    """

def apply_dics_csd(csd: CrossSpectralDensity, filters: Dict, verbose: Optional[Union[bool, str, int]] = None) -> SourceEstimate:
    """
    Apply DICS beamformer to cross-spectral density.
    
    Parameters:
    - csd: Cross-spectral density matrix
    - filters: DICS filters from make_dics
    - verbose: Verbosity level
    
    Returns:
    SourceEstimate with beamformed CSD
    """

Dipole Fitting

Fit equivalent current dipoles to explain sensor measurements.

def fit_dipole(evoked: Evoked, cov: Covariance, bem: Union[str, Dict], trans: Union[str, Transform],
              min_dist: float = 5.0, n_jobs: int = 1, pos: Optional[ArrayLike] = None,
              ori: Optional[ArrayLike] = None, rank: Optional[Union[str, int, Dict]] = None,
              verbose: Optional[Union[bool, str, int]] = None) -> Tuple[Dipole, ArrayLike]:
    """
    Fit dipoles to evoked data.
    
    Parameters:
    - evoked: Evoked data to fit
    - cov: Noise covariance matrix
    - bem: BEM model or path to BEM file
    - trans: Head<->MRI transformation
    - min_dist: Minimum distance from inner skull
    - n_jobs: Number of parallel jobs
    - pos: Initial dipole positions
    - ori: Initial dipole orientations
    - rank: Data rank specification
    - verbose: Verbosity level
    
    Returns:
    Tuple of (Dipole object, residual variance)
    """

def read_dipole(fname: str, verbose: Optional[Union[bool, str, int]] = None) -> Dipole:
    """
    Read dipole from file.
    
    Parameters:
    - fname: Path to dipole file
    - verbose: Verbosity level
    
    Returns:
    Dipole object
    """

Source Estimate Manipulation

Work with source estimates including morphing between subjects and extracting label time courses.

def compute_source_morph(src_from: Union[SourceSpaces, SourceEstimate], subject_to: str,
                        spacing: Optional[Union[int, List]] = None, smooth: Optional[int] = None,
                        warn: bool = True, xhemi: bool = False, subjects_dir: Optional[str] = None,
                        verbose: Optional[Union[bool, str, int]] = None) -> SourceMorph:
    """
    Compute morphing between source spaces or subjects.
    
    Parameters:
    - src_from: Source space or source estimate to morph from
    - subject_to: Target subject
    - spacing: Target spacing
    - smooth: Smoothing steps
    - warn: Warn about topology changes
    - xhemi: Include cross-hemisphere morphing
    - subjects_dir: FreeSurfer subjects directory
    - verbose: Verbosity level
    
    Returns:
    SourceMorph object
    """

def extract_label_time_course(stcs: Union[SourceEstimate, List[SourceEstimate]], labels: List[Label],
                             src: SourceSpaces, mode: str = 'mean', allow_empty: bool = False,
                             return_generator: bool = False, verbose: Optional[Union[bool, str, int]] = None) -> ArrayLike:
    """
    Extract time course from labels.
    
    Parameters:
    - stcs: Source estimate(s)
    - labels: Labels to extract from
    - src: Source space
    - mode: Extraction mode ('mean', 'max', 'pca_flip')
    - allow_empty: Allow empty labels
    - return_generator: Return generator
    - verbose: Verbosity level
    
    Returns:
    Label time courses array
    """

def stc_to_label(stc: SourceEstimate, src: SourceSpaces, smooth: bool = True,
                subjects_dir: Optional[str] = None, connected: bool = False,
                verbose: Optional[Union[bool, str, int]] = None) -> List[Label]:
    """
    Convert source estimate to labels.
    
    Parameters:
    - stc: Source estimate
    - src: Source space
    - smooth: Smooth label boundaries
    - subjects_dir: FreeSurfer subjects directory
    - connected: Require connected labels
    - verbose: Verbosity level
    
    Returns:
    List of Label objects
    """

Usage Examples

Forward Solution and Inverse Operator

import mne

# Load data and create forward solution
info = mne.io.read_info('sample_audvis-ave.fif')
trans = 'sample-trans.fif'
src = mne.read_source_spaces('sample-oct6-src.fif')  
bem = mne.read_bem_solution('sample-5120-bem-sol.fif')

# Create forward solution
fwd = mne.make_forward_solution(info, trans, src, bem, 
                               meg=True, eeg=True, mindist=5.0)

# Load noise covariance
noise_cov = mne.read_cov('sample-cov.fif')

# Create inverse operator
inverse_operator = mne.minimum_norm.make_inverse_operator(
    info, fwd, noise_cov, loose=0.2, depth=0.8)

# Apply to evoked data
evoked = mne.read_evokeds('sample_audvis-ave.fif', condition='Left Auditory')
stc = mne.minimum_norm.apply_inverse(evoked, inverse_operator, 
                                    lambda2=1.0/9.0, method='dSPM')

# Visualize source estimate
stc.plot(subject='sample', subjects_dir=subjects_dir)

LCMV Beamforming

import mne

# Load epochs and compute covariance
epochs = mne.read_epochs('sample-epo.fiv')
data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15)
noise_cov = mne.compute_covariance(epochs, tmin=-0.2, tmax=0.0)

# Load forward solution
fwd = mne.read_forward_solution('sample-fwd.fif')

# Make LCMV beamformer
filters = mne.beamformer.make_lcmv(epochs.info, fwd, data_cov, 
                                  reg=0.05, noise_cov=noise_cov)

# Apply to evoked data
evoked = epochs.average()
stc = mne.beamformer.apply_lcmv(evoked, filters)

# Plot result
stc.plot(subject='sample', subjects_dir=subjects_dir)

DICS Beamforming for Connectivity

import mne
from mne.time_frequency import csd_morlet

# Load epochs
epochs = mne.read_epochs('sample-epo.fiv')

# Compute cross-spectral density in alpha band
csd = csd_morlet(epochs, frequencies=[10], n_cycles=7)

# Load forward solution  
fwd = mne.read_forward_solution('sample-fwd.fif')

# Make DICS beamformer
filters = mne.beamformer.make_dics(epochs.info, fwd, csd, reg=0.05)

# Apply to CSD
stc = mne.beamformer.apply_dics_csd(csd, filters)

# Plot alpha power
stc.plot(subject='sample', subjects_dir=subjects_dir)

Dipole Fitting

import mne

# Load evoked data and noise covariance
evoked = mne.read_evokeds('sample_audvis-ave.fif', condition='Right Auditory')
cov = mne.read_cov('sample-cov.fiv')

# Load BEM model and transformation
bem = mne.read_bem_solution('sample-5120-bem-sol.fiv')
trans = 'sample-trans.fif'

# Fit dipole
dipole, residual = mne.fit_dipole(evoked, cov, bem, trans, min_dist=5.0)

# Plot dipole locations
dipole.plot_locations(trans, 'sample', subjects_dir, mode='orthoview')

Types

class Forward:
    """Forward solution container."""
    sol: Dict  # Solution dictionary
    source_ori: int  # Source orientation info
    src: SourceSpaces  # Source space
    info: Info  # Measurement info
    
    def copy(self) -> 'Forward': ...

class SourceSpaces:
    """Source space container."""  
    def __init__(self, spaces: List[Dict], info: Optional[Dict] = None): ...
    def plot(self, **kwargs) -> Figure: ...
    def save(self, fname: str) -> None: ...

class InverseOperator:
    """Inverse operator container."""
    def __init__(self): ...

class SourceEstimate:
    """Surface source estimate."""
    data: ArrayLike  # Source data (n_sources, n_times)
    vertices: List[ArrayLike]  # Source vertices for each hemisphere
    tmin: float  # Start time
    tstep: float  # Time step
    subject: Optional[str]  # Subject name
    
    def plot(self, subject: Optional[str] = None, **kwargs) -> Brain: ...
    def get_peak(self, **kwargs) -> Tuple: ...
    def save(self, fname: str) -> None: ...

class SourceMorph:
    """Source morphing container."""
    def apply(self, stc: SourceEstimate) -> SourceEstimate: ...
    def save(self, fname: str) -> None: ...

class Dipole:
    """Dipole container."""
    pos: ArrayLike  # Dipole positions
    ori: ArrayLike  # Dipole orientations  
    gof: ArrayLike  # Goodness of fit
    amplitude: ArrayLike  # Dipole amplitudes
    times: ArrayLike  # Time points
    
    def plot_locations(self, trans: Transform, subject: str, **kwargs) -> Figure: ...

class Label:
    """Brain surface label."""
    vertices: ArrayLike  # Label vertices
    pos: ArrayLike  # Vertex positions
    values: ArrayLike  # Vertex values
    hemi: str  # Hemisphere ('lh' or 'rh')
    name: str  # Label name
    subject: str  # Subject name
    
    def center_of_mass(self, subject: str, **kwargs) -> ArrayLike: ...

Install with Tessl CLI

npx tessl i tessl/pypi-mne

docs

data-io.md

datasets.md

index.md

machine-learning.md

preprocessing.md

source-analysis.md

statistics.md

time-frequency.md

visualization.md

tile.json