calibrain.LeadfieldBuilder#

class calibrain.LeadfieldBuilder(config=None, leadfield_dir=None, logger=None)[source]#

Simulates 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.

config#

The configuration dictionary driving the simulation process.

Type:

dict

self.logger#

Logger instance for logging messages.

Type:

logging.Logger

data_path#

Path to the data directory.

Type:

Path

subject#

Subject identifier.

Type:

str

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

Methods

get_leadfield([subject, orientation_type, ...])

Get or generate the leadfield matrix based on the specified mode.

handle_bem_model()

Load or create the BEM (Boundary Element Model) solution.

handle_forward_solution(info, src, bem)

Load or create the forward solution.

handle_info()

Load or create the MNE measurement info object.

handle_leadfield([fwd])

Load or extract the leadfield matrix.

handle_montage()

Load or create the sensor montage.

handle_source_space()

Load or create the source space.

simulate()

Run the full simulation pipeline.

__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:

mne.SourceSpaces

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:

mne.bem.ConductorModel

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:

mne.channels.DigMontage

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:

mne.Info

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:
Returns:

The loaded or created forward solution object.

Return type:

mne.Forward

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', config=None, n_sensors=64, n_sources=1284, return_metadata=False)[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) when return_metadata is False. When True, returns a LeadfieldData object that includes both the leadfield matrix and its associated sensor metadata.

Return type:

np.ndarray or LeadfieldData

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’.