API Reference

This section provides the auto-generated API documentation for the CaliBrain library.

Leadfield Simulation

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_simulation.LeadfieldSimulator(config, logger=None)[source]

Bases: object

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

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

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

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_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

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.

Data Simulation

class calibrain.data_simulation.DataSimulator(n_sensors=None, n_sources=None, n_times=100, tmin=-0.5, tmax=0.5, stim_onset=0.0, sfreq=250, fmin=1, fmax=5, nnz=3, alpha_snr_db=6.0, amplitude=5.0, randomize_erp_timing_within_post_stim=True, min_erp_duration_samples=None, n_trials=3, orientation_type='fixed', seed=None, logger=None, rng=None, leadfield_mode='random', leadfield_path=None, leadfield_config_path=None)[source]

Bases: object

Simulates brain activity data including source activity, leadfield, and sensor measurements.

Handles different leadfield generation modes (random, load, simulate) and noise addition based on specified SNR. Supports fixed and free source orientations.

inspect_matrix_values(matrix_name='Matrix')[source]

Prints summary statistics and checks for invalid values in a NumPy array.

Parameters: - matrix (np.ndarray): The matrix to inspect. - matrix_name (str): A name for the matrix used in print statements.

load_and_validate_leadfield(orientation_type)[source]

Loads a leadfield matrix from an .npz file and validates its shape based on the expected orientation type. Includes value inspection.

Parameters: - leadfield_file_path (str or Path): Path to the .npz file containing the leadfield. - orientation_type (str): The expected orientation type (“fixed” or “free”).

Returns: - np.ndarray: The loaded and validated leadfield matrix.

Raises: - FileNotFoundError: If the leadfield file does not exist. - KeyError: If the expected key is not found in the .npz file. - ValueError: If the loaded leadfield matrix shape is inconsistent with the orientation_type. - Exception: For other potential loading errors.

plot_active_sources(x, times, active_indices, stim_onset, nnz, save_dir=None, figure_name=None, trial_idx=None)[source]

Plot active sources for a specific trial.

plot_all_active_sources_single_figure(x, times, active_indices, stim_onset, save_dir=None, figure_name=None, trial_idx=None)[source]

Plot all specified active source signals on a single figure for a specific trial.

plot_all_sensor_signals_single_figure(y_data, times, sensor_indices=None, save_dir=None, figure_name=None, trial_idx=None, average_epochs=False)[source]

Plot sensor signals (overlay) for selected sensors. If average_epochs is True and y_data is 3D, plots the average across epochs for each channel. If average_epochs is False and y_data is 2D, plots the single trial data. Does NOT average across channels.

Parameters: - y_data (np.ndarray): Sensor measurements. Can be 2D (n_channels, n_times) for a single trial

or 3D (n_trials, n_channels, n_times) for multiple trials.

  • times (np.ndarray): Time vector corresponding to the signals.

  • sensor_indices (list or np.ndarray, optional): Indices of sensors to plot. If None, plots all sensors.

  • save_dir (str or Path, optional): Directory to save the figure.

  • figure_name (str, optional): Name of the figure file (without extension).

  • trial_idx (int, optional): Index of the trial being plotted (used for title if y_data is 2D and average_epochs is False).

  • average_epochs (bool): If True and y_data is 3D, plot the average across trials.

    If False and y_data is 3D, raises an error. If y_data is 2D, this primarily affects the title.

plot_sensor_signals(y_clean, y_noisy, sensor_indices=None, times=None, save_dir=None, figure_name=None, trial_idx=None)[source]

Plot clean and noisy sensor signals for specific sensors for a specific trial.

simulate(visualize=True, save_path='results/figures/data_sim/')[source]

Run the full data simulation pipeline.

Steps: 1. Get leadfield matrix (load, simulate, or random). 2. Generate source time courses. 3. Project sources to sensor space (clean measurements). 4. Add noise based on SNR. 5. Optionally visualize results.

Parameters:
  • visualize (bool, optional) – Whether to generate and save visualization plots, by default True. Requires leadfield_mode to be ‘simulate’ or a valid leadfield_config_path to be provided for obtaining MNE info.

  • save_path (str, optional) – Base directory to save visualization figures, by default “results/figures/data_sim/”.

Returns:

  • y_noisy : Noisy sensor measurements (n_sensors, n_times).

  • L : Leadfield matrix. Shape depends on orientation type, potentially reshaped for ‘free’.

  • x : Ground truth source activity. Shape depends on orientation type.

  • cov_scaled : Scaled noise covariance matrix (n_sensors, n_sensors).

  • noise_scaled : Scaled noise added (n_sensors, n_times).

Return type:

Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]

Raises:

ValueError – If visualization is requested but MNE info cannot be obtained (e.g., leadfield_mode is not ‘simulate’ and leadfield_config_path is missing).

visualize_leadfield(leadfield_matrix, orientation_type='fixed', save_path=None, show=False)[source]

Visualize the leadfield matrix as a heatmap.

Parameters:
  • leadfield_matrix (np.ndarray) – The leadfield matrix. - ‘fixed’: Shape (n_sensors, n_sources). - ‘free’: Shape (n_sensors, n_sources, 3).

  • orientation_type (str, optional) – Orientation type (‘fixed’ or ‘free’), by default “fixed”.

  • save_path (Optional[str], optional) – Path to save the figure. If None, not saved, by default None.

  • show (bool, optional) – If True, display the plot, by default False.

Raises:

ValueError – If leadfield_matrix is invalid or orientation_type is unsupported.

Return type:

None

visualize_leadfield_topomap(leadfield_matrix, info, x, orientation_type='fixed', save_path=None, title=None, show=False)[source]

Visualize leadfield patterns as topomaps for active sources.

Parameters:
  • leadfield_matrix (np.ndarray) – The leadfield matrix. - ‘fixed’: Shape (n_sensors, n_sources). - ‘free’: Shape (n_sensors, n_sources, 3).

  • info (mne.Info) – MNE info object containing sensor locations.

  • x (np.ndarray) – Source activity matrix to determine active sources. - ‘fixed’: Shape (n_sources, n_times). - ‘free’: Shape (n_sources, 3, n_times).

  • orientation_type (str, optional) – Orientation type (‘fixed’ or ‘free’), by default “fixed”.

  • save_path (Optional[str], optional) – Path to save the figure. If None, not saved, by default None.

  • title (Optional[str], optional) – Title for the entire figure, by default None.

  • show (bool, optional) – If True, display the plot, by default False.

Raises:

ValueError – If inputs are invalid or orientation_type is unsupported.

Return type:

None

visualize_signals(x, y_clean, y_noisy, active_sources=None, nnz_to_plot=-1, sfreq=100.0, max_sensors=3, plot_sensors_together=False, shift=20.0, figsize=(14, 10), save_path='results/figures/data_sim.png', show=False)[source]

Visualize source activity and sensor measurements.

Plots active source time courses and compares clean vs. noisy sensor signals.

Parameters:
  • x (np.ndarray) – Source activity. Shape depends on orientation type.

  • y_clean (np.ndarray) – Clean sensor measurements (n_sensors, n_times).

  • y_noisy (np.ndarray) – Noisy sensor measurements (n_sensors, n_times).

  • active_sources (Optional[np.ndarray], optional) – Indices of non-zero (active) sources. If None, they are determined from x, by default None.

  • nnz_to_plot (int, optional) – Number of non-zero sources to plot. If -1, plot all non-zero sources found, by default -1.

  • sfreq (float, optional) – Sampling frequency in Hz, by default 100.0.

  • max_sensors (int, optional) – Maximum number of sensors to plot, by default 3.

  • plot_sensors_together (bool, optional) – If True, plot all sensors on the same subplot. If False, stack plots vertically, by default False.

  • shift (float, optional) – Vertical shift between sensors when plotting together, by default 20.0.

  • figsize (Tuple[float, float], optional) – Figure size for the plot, by default (14, 10).

  • save_path (Optional[str], optional) – Path to save the figure. If None, the figure is not saved, by default ‘results/figures/data_sim.png’.

  • show (bool, optional) – If True, display the plot, by default False.

Return type:

None

Source Estimation

class calibrain.source_estimation.SourceEstimator(solver, solver_params=None, n_orient=1, logger=None)[source]

Bases: BaseEstimator, RegressorMixin

fit(L, y)[source]

Fit the inverse solver to the data.

Parameters: - L (np.ndarray): Leadfield matrix of shape (n_sensors, n_sources). - y (np.ndarray): Observed EEG/MEG signals of shape (n_sensors, n_times).

Returns: - self: The fitted estimator.

predict(y=None, noise_var=None)[source]

Predict the source activity given the observed signals.

Parameters: - y (np.ndarray, optional): Observed EEG/MEG signals of shape (n_sensors, n_times). If None, uses the signals provided during fit. - noise_var (float): Noise variance.

Returns: - x_hat (np.ndarray): Estimated source activity of shape (n_sources, n_times). - active_set (np.ndarray): Indices of active sources. - posterior_cov (np.ndarray): Posterior covariance matrix of estimated sources.

set_fit_request(*, L: bool | None | str = '$UNCHANGED$') SourceEstimator

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

L (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for L parameter in fit.

Returns:

self – The updated object.

Return type:

object

set_predict_request(*, noise_var: bool | None | str = '$UNCHANGED$') SourceEstimator

Configure whether metadata should be requested to be passed to the predict method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to predict.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

noise_var (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for noise_var parameter in predict.

Returns:

self – The updated object.

Return type:

object

set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') SourceEstimator

Configure whether metadata should be requested to be passed to the score method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config()). Please check the User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to score if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to score.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Parameters:

sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in score.

Returns:

self – The updated object.

Return type:

object

calibrain.source_estimation.eloreta(L, y, **kwargs)[source]
calibrain.source_estimation.gamma_map(L, y, noise_var=None, noise_type='oracle', n_orient=1, max_iter=1000, tol=1e-15, update_mode=2, gammas=None, verbose=True, logger=None)[source]

Uncertainty Estimation

class calibrain.uncertainty_estimation.UncertaintyEstimator(orientation_type, x, x_hat, active_set, posterior_cov, experiment_dir=None, logger=None)[source]

Bases: object

construct_full_covariance()[source]

Create a full covariance matrix corresponding to all source components, embedding the posterior covariance of the active set.

Handles both ‘fixed’ and ‘free’ orientation types by inspecting the shape of self.x and the self.orientation_type attribute.

Returns: - full_posterior_cov (np.ndarray): Full posterior covariance matrix.

Shape: (n_total_components, n_total_components).

Raises: - ValueError: If input shapes, orientation_type, or active_set indices are inconsistent. - AttributeError: If required attributes (x, active_set, posterior_cov, orientation_type) are missing.

plot_active_sources_single_time_step(time_step=0)[source]

Plot the active sources for a single time step, comparing ground truth and estimated sources. Handles both 3D and 2D input shapes for x and x_hat.

plot_posterior_covariance_matrix()[source]

Plot the posterior covariance matrix.

plot_sorted_posterior_variances(top_k=None)[source]

Plot the sorted variances from the covariance matrix, highlighting the top-k variances.

plot_source_estimates(posterior_cov, orientations)[source]

Plot source estimates and save the visualizations.

Parameters: - posterior_cov (np.ndarray): Posterior covariance matrix. - experiment_dir (str): Path to the experiment directory. - orientations (list): List of orientations for visualization.

plot_top_relevant_CE_pairs(top_k=5, confidence_level=0.95)[source]

Identify the top-k relevant pairs of dimensions (based on covariance magnitude) and plot their confidence ellipses.

reshape_source_data(n_times)[source]

Reshape data based on the orientation type.

Parameters: - n_times (int): Number of time points.

Returns: - x (np.ndarray): Reshaped ground truth source activity. - x_hat (np.ndarray): Reshaped estimated source activity.

visualize_confidence_intervals(confidence_levels=None, time_point=0)[source]

Visualize confidence intervals and save the results. Handles both fixed and free orientation.

Parameters: - confidence_levels (list, optional): List of confidence levels to visualize. If None, defaults to 10 levels from 0.1 to 0.99. - time_point (int): Time point to visualize for the proportion of hits plot.

visualize_sorted_covariances(top_k=None)[source]

Visualize the sorted magnitudes of covariances for all pairs of dimensions.

Utilities

calibrain.utils.load_config(config_file, logger=None)[source]

Load the configuration from a YAML file.

Parameters: :rtype: dict

  • config_file (str): Path to the YAML configuration file.

  • logger (logging.Logger, optional): Logger instance for logging messages. If None, a default logger will be created.

Raises: - FileNotFoundError: If the configuration file is not found. - yaml.YAMLError: If there is an error parsing the YAML file. - ValueError: If the configuration file is empty or invalid.

Returns: - config (dict): The loaded configuration as a dictionary.

Benchmarking

class calibrain.benchmark.Benchmark(solver, solver_param_grid, data_param_grid, data_simulator, metrics, logger=None)[source]

Bases: object

create_experiment_directory(base_dir, params)[source]

Create a directory structure for the experiment, with subdirectories for each parameter.

Parameters: - base_dir (str): Base directory for the experiment. - params (dict): Dictionary of parameters.

Returns: - experiment_dir (str): Path to the experiment directory.

run(nruns=1)[source]

Run benchmarking by iterating over combinations of solver and data parameters.

Returns: - results (pd.DataFrame): DataFrame containing the results for each parameter combination.