Leadfield Simulation#
L#
Module for simulating leadfield matrices using MNE-Python.
Provides a configurable framework for setting up and running a leadfield simulation pipeline. Handles various MNE-Python components, such as source space, BEM model, montage, info object, forward solution, and leadfield matrix, allowing loading from files or creating them based on configuration.
- class calibrain.leadfield_builder.LeadfieldBuilder(config=None, leadfield_dir=None, logger=None)[source]#
Bases:
objectSimulates leadfield matrices based on a configuration dictionary.
Handles the creation or loading of necessary MNE-Python components like source space, BEM model, montage, info, and forward solution.
- self.logger#
Logger instance for logging messages.
- Type:
- data_path#
Path to the data directory.
- Type:
Path
- subjects_dir#
Path to the FreeSurfer subjects directory.
- Type:
Path
- save_path#
Base path where generated files (source space, BEM, etc.) will be saved.
- Type:
Path
- __init__(config=None, leadfield_dir=None, logger=None)[source]#
Initialize the LeadfieldBuilder.
- Parameters:
config (dict) – Configuration dictionary containing paths and parameters for each simulation step (data, source_space, bem_model, montage, info, forward_solution, leadfield).
channel_type (str, optional) – Type of channels to simulate (‘eeg’, ‘meg’, or ‘grad’). If None, all channel types will be simulated. Default is None.
leadfield_dir (str, optional) – Directory where leadfield matrices are stored or will be saved.
self.logger (logging.Logger, optional) – Custom self.logger instance. If None, a default self.logger is created, by default None.
- Raises:
FileNotFoundError – If data_path or subjects_dir specified in the config do not exist.
- handle_source_space()[source]#
Load or create the source space.
Reads the source space from the file specified in config[‘source_space’][‘fname’] if it exists. Otherwise, creates a new source space using mne.setup_source_space with parameters from the configuration. Saves the created source space if config[‘source_space’][‘save’] is True.
- Returns:
The loaded or created source space object.
- Return type:
- handle_bem_model()[source]#
Load or create the BEM (Boundary Element Model) solution.
Reads the BEM solution from the file specified in config[‘bem_model’][‘fname’] if it exists. Otherwise, creates a new BEM model using mne.make_bem_model and computes the solution using mne.make_bem_solution with parameters from the configuration. Saves the created BEM solution if config[‘bem_model’][‘save’] is True.
- Returns:
The loaded or created BEM solution object.
- Return type:
- handle_montage()[source]#
Load or create the sensor montage.
Reads the montage from the file specified in config[‘montage’][‘fname’] if it exists. Otherwise, creates a standard montage using mne.channels.make_standard_montage with parameters from the configuration. Saves the created montage if config[‘montage’][‘save’] is True.
- Returns:
The loaded or created montage object.
- Return type:
- handle_info()[source]#
Load or create the MNE measurement info object.
Reads the info from the file specified in config[‘info’][‘fname’] if it exists. Otherwise, creates a new info object using mne.create_info with parameters from the configuration, associating it with the montage obtained via handle_montage. Saves the created info object if config[‘info’][‘save’] is True.
- Returns:
The loaded or created info object.
- Return type:
- Raises:
ValueError – If info cannot be created because the montage is missing or invalid.
- handle_forward_solution(info, src, bem)[source]#
Load or create the forward solution.
Reads the forward solution from the file specified in config[‘forward_solution’][‘fname’] if it exists and has a valid suffix. Otherwise, creates a new forward solution using mne.make_forward_solution with parameters from the configuration. Converts the solution to fixed orientation if config[‘forward_solution’][‘orientation_type’] is ‘fixed’. Saves the created forward solution if config[‘forward_solution’][‘save’] is True.
- Parameters:
info (mne.Info) – The measurement info object.
src (mne.SourceSpaces) – The source space object.
bem (mne.bem.ConductorModel) – The BEM solution object.
- Returns:
The loaded or created forward solution object.
- Return type:
- handle_leadfield(fwd=None)[source]#
Load or extract the leadfield matrix.
Reads the leadfield matrix from the .npz file specified in config[‘leadfield’][‘fname’] if it exists. Otherwise, extracts the leadfield data from the provided forward solution fwd. Reshapes the matrix for free orientation if necessary. Saves the extracted leadfield matrix if config[‘leadfield’][‘save’] is True.
- Parameters:
fwd (mne.Forward, optional) – The forward solution object. Required if the leadfield matrix is not loaded from a file, by default None.
- Returns:
The leadfield matrix. Shape is (n_sensors, n_sources) for fixed orientation or (n_sensors, n_sources, 3) for free orientation.
- Return type:
np.ndarray
- Raises:
ValueError – If the leadfield cannot be loaded from a file and fwd is not provided, or if a loaded leadfield file is invalid.
- simulate()[source]#
Run the full simulation pipeline.
Executes the sequence of handling/creating source space, BEM model, info object, forward solution, and finally the leadfield matrix, based on the provided configuration.
- Returns:
The final leadfield matrix. Shape depends on the orientation type.
- Return type:
np.ndarray
- Raises:
RuntimeError – If any step in the pipeline fails.
- get_leadfield(subject='fsaverage', orientation_type='fixed', retrieve_mode='load')[source]#
Get or generate the leadfield matrix based on the specified mode.
Updates self.n_sensors and self.n_sources based on the obtained leadfield.
- Parameters:
subject (str)
- Returns:
The leadfield matrix (L). Shape depends on orientation_type: - ‘fixed’: (n_sensors, n_sources) - ‘free’: (n_sensors, n_sources, 3)
- Return type:
np.ndarray
- Raises:
ValueError – If retrieve_mode is invalid, required paths are missing, or loaded/simulated leadfield has unexpected dimensions/format.
FileNotFoundError – If leadfield_dir does not exist when mode=’load’.