API Reference#

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

Source Simulation#

source_simulation.py Module for simulating synthetic brain activity data for source-level measurements.

Specifically simulating event-related potential (ERP)-like signals for use in neuroimaging research (e.g., MEG/EEG source simulation). It supports flexible configuration of ERP waveform properties, source orientation (fixed or free), and trial-based simulation with reproducible randomization.

class calibrain.source_simulation.SourceSimulator(ERP_config=None, logger=None)[source]#

Bases: object

Simulates synthetic brain activity data for source-level measurements.

__init__(ERP_config=None, logger=None)[source]#

Initialize the SourceSimulator with parameters for simulating dipole sources.

Parameters:
  • ERP_config (Optional[Dict[str, Any]]) –

    Configuration dictionary for the ERP simulation parameters. If None, default values are used. Default values include:

    • tmin: -0.5 (start time of the ERP segment in seconds)

    • tmax: 0.5 (end time of the ERP segment in seconds)

    • stim_onset: 0.0 (time of stimulus onset in seconds, relative to the start of the ERP segment)

    • sfreq: 250 (sampling frequency in Hz)

    • fmin: 1 (minimum frequency for the bandpass filter in Hz)

    • fmax: 5 (maximum frequency for the bandpass filter in Hz)

    • amplitude: 1.0 (amplitude of the ERP waveform)

    • random_erp_timing: True (if True, the exact start time and duration of the ERP waveform within the post-stimulus window are randomized)

    • erp_min_length : Optional[int] (minimum length of the ERP waveform in samples; if None, a default value is used)

  • logger (Optional[logging.Logger], optional) – Logger instance, by default None.

simulate(orientation_type='fixed', n_sources=100, nnz=5, n_trials=1, global_seed=42)[source]#

Simulate multiple trials of source time courses.

This function generates synthetic source activity for n_trials trials using ERP-like signals. Each trial uses a unique random seed derived from the provided global_seed for reproducibility.

Parameters:
  • orientation_type (str) – Orientation of the sources, either “fixed” or “free”. Default is “fixed”.

  • n_sources (int) – Total number of sources to simulate. Default is 100.

  • nnz (int) – Number of non-zero (active) sources in each trial. Must be less than or equal to n_sources. Default is 5.

  • n_trials (int) – Number of trials to simulate. Default is 1.

  • global_seed (int) – Seed for the random number generator to ensure reproducibility across trials. Default is 42.

Returns:

  • x_all_trialsnp.ndarray

    Array of shape (n_trials, …) containing simulated source time courses. Shape depends on source orientation: - fixed: (n_trials, n_sources, n_times) - free: (n_trials, n_sources, 3, n_times)

  • active_indices_all_trialsnp.ndarray

    Array of shape (n_trials, nnz) containing indices of active sources per trial.

Return type:

Tuple[np.ndarray, np.ndarray]

calibrain.source_simulation.main()[source]#

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_builder.LeadfieldBuilder(config=None, leadfield_dir=None, 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

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

__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')[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’.

Sensor Simulation#

sensor_simulation.py Module for simulating synthetic brain activity data for sensor-level measurements.

class calibrain.sensor_simulation.SensorSimulator(logger=None)[source]#

Bases: object

Simulates synthetic brain activity data for sensor-level measurements.

__init__(logger=None)[source]#

Initialize the SensorSimulator. :type logger: Optional[Logger] :param logger: Logger instance for logging messages. If None, a default logger will be created. :type logger: Optional[logging.Logger]

simulate(x_trials, L, orientation_type='fixed', alpha_SNR=0.5, n_trials=1, global_seed=42)[source]#

Simulate sensor trials by projecting source data to sensor space and adding noise to the clean sensor data.

Parameters:
  • x_trials (List[np.ndarray]) – List of source time courses for each trial. Each element should be an array of shape (n_sources, n_times) for fixed orientation or (n_sources, 3, n_times) for free orientation.

  • L (np.ndarray) – Leadfield matrix (µV / nAm for EEG or fT / nAm for MEG). - ‘fixed’: Shape (n_sensors, n_sources). - ‘free’: Shape (n_sensors, 3, n_sources).

  • orientation_type (str) – Orientation type of the sources (‘fixed’ or ‘free’).

  • alpha_SNR (float) – Desired signal-to-noise ratio between 0 and 1. - 0.0 means full noise, no signal. - 1.0 means no noise, only signal.

  • n_trials (int) – Number of trials to simulate. Default is 1.

  • global_seed (int) – Global seed for random number generation to ensure reproducibility across trials.

Returns:

  • y_clean_all_trialsnp.ndarray

    Clean sensor data for all trials. Shape: (n_trials, n_sensors, n_times).

  • y_noisy_all_trialsnp.ndarray

    Noisy sensor data for all trials. Shape: (n_trials, n_sensors, n_times).

  • noise_all_trialsnp.ndarray

    Noise added to the clean sensor data for all trials. Shape: (n_trials, n_sensors, n_times).

  • noise_var_all_trialsnp.ndarray

    Noise variance for each trial. Shape: (n_trials,).

Return type:

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

calibrain.sensor_simulation.main()[source]#

Source Estimation#

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, init_gamma=None, verbose=True, logger=None)[source]#
calibrain.source_estimation.sqrtm_sym(M, inv=False)[source]#

Compute the square root (or inverse square root) of symmetric matrices, handling both 2D and block-diagonal 3D cases.

calibrain.source_estimation.normalize_R(G, R, G_3, n_nzero, force_equal, n_src, n_orient)[source]#

Normalize the source covariance matrix (R) for consistency with eigenvalues.

This function normalizes the product G @ R @ G.T so that its trace matches a reference value (n_nzero).

Parameters:#

Gndarray, shape (n_chan, n_src * n_orient)

The lead-field or forward matrix after applying whitening and source scaling.

Rndarray

The source covariance matrix; may be a 1D vector (single orientation) or a block diagonal structure (multiple orientations).

G_3ndarray or None

Reshaped version of G for multi-orientation sources (n_src x n_orient x n_chan), or None for single orientation.

n_nzeroint

The number of non-zero sensor dimensions (typically, the number of sensors).

force_equalbool

If True, enforce equal orientation weights (i.e., treat sources with single orientation).

n_srcint

Number of sources (after accounting for orientation).

n_orientint

Number of orientations per source (1 for fixed, 3 for free orientation).

Returns:#

: G_R_Gt : ndarray

The normalized product G @ R @ G.T.

calibrain.source_estimation.get_G_3(G, n_orient)[source]#

Reshape and transpose the lead-field matrix G for multi-orientation sources.

Parameters:#

Gndarray, shape (n_chan, n_src * n_orient)

The original lead-field matrix, after whitening and orientation‐prior scaling.

n_orientint

Number of orientations per source (1 for fixed, 3 for free orientation).

Returns:#

: ndarray or None :

If n_orient > 1, returns an array of shape (n_src, n_orient, n_chan), so that each source’s 3×n_chan lead-field slice is one block. If n_orient == 1, returns None.

calibrain.source_estimation.R_sqrt_mult(other, R_sqrt)[source]#

Efficiently compute the multiplication: other @ R_sqrt.

This function handles both diagonal and block-diagonal cases for R_sqrt.

Parameters:#

otherndarray, shape (n_chan, n_src * n_orient) or similar

The matrix to be multiplied with R_sqrt.

R_sqrtndarray

The square root of the source covariance matrix R. It is either a 1D vector (for a diagonal matrix) or a 3D array (for block-diagonal multi-orientation case).

Returns:#

: out : ndarray

The result of the matrix multiplication.

calibrain.source_estimation.compute_reginv2(sing, n_nzero, lambda2)[source]#

Compute the regularized inverse of singular values.

This applies Tikhonov regularization in the SVD domain to handle small singular values.

Parameters:#

sing : array-like, singular values from the SVD. n_nzero : int, number of non-zero singular values (typically number of sensors). lambda2 : float, regularization parameter.

Returns:#

: reginv : array-like, the regularized inverses.

calibrain.source_estimation.compute_orient_prior(G, n_orient, loose=0.9)[source]#

Compute an orientation prior for sources.

The orientation prior weights help to scale the source estimates according to expected orientation variability (e.g., “loose” constraints for x and y directions).

Parameters:#

G : ndarray, the lead-field matrix. n_orient : int, number of orientations per source. loose : float, scaling factor for certain orientations.

Returns:#

: orient_prior : ndarray, shape (n_sources * n_orient,)

The prior weights for each source orientation.

calibrain.source_estimation.safe_svd(A, full_matrices=False)[source]#

Safely compute the SVD of matrix A.

Parameters:#

Andarray

The matrix for which to compute the singular value decomposition.

full_matricesbool

Flag determining if full or reduced SVD is computed.

Returns:#

: U, S, Vh : ndarrays

The left singular vectors, singular values, and right singular vectors.

calibrain.source_estimation.compute_eloreta_kernel(L, *, lambda2, n_orient, whitener, loose=1.0, max_iter=20)[source]#

Compute the eLORETA kernel and the posterior source covariance.

This function carries out the main steps of the eLORETA estimation:
  1. Whiten the lead-field matrix L.

  2. Apply the orientation prior to the source covariance.

  3. Initialize and iteratively update the source covariance matrix R.

  4. Normalize R and compute the effective gain matrix.

  5. Perform an SVD on the effective gain matrix and regularize the singular values.

  6. Assemble the final inverse operator (kernel K).

Parameters:#

Lndarray, shape (n_chan, n_src*n_orient)

The original lead-field matrix.

lambda2 : float, regularization parameter to stabilize the inversion. n_orient : int, the number of orientations per source (1 for fixed orientation, 3 for free orientation). whitener : ndarray, the whitening matrix derived from the noise covariance. loose : float, parameter for the orientation prior (looseness of the constraints). max_iter : int, maximum number of iterations for the iterative fitting procedure.

Returns:#

: K : ndarray, the eLORETA kernel (inverse operator) used to compute source estimates. Sigma : ndarray, the posterior source covariance matrix.

calibrain.source_estimation.eloreta(L, y, noise_var=None, noise_type='oracle', n_orient=1, verbose=True, logger=None)[source]#

Compute the eLORETA solution for EEG/MEG inverse modeling.

This is the main interface function that:
  • Preprocesses the lead-field and data,

  • Applies noise whitening,

  • Computes the eLORETA kernel,

  • And finally estimates the source activity.

Parameters:#

Lndarray, shape (n_chan, n_src*n_orient)

The lead-field (forward) matrix mapping sources to sensors.

yndarray, shape (n_chan, n_times) or (n_chan,)

The sensor data (EEG/MEG recordings) to be inverted.

n_orientint

Number of orientations per source (1 for fixed or 3 for free orientation).

Returns:#

: x : ndarray

The estimated source activations. The shape will be (n_src, n_times) for single orientation or (n_src, n_orient, n_times) for free orientations.

Sigmandarray

The posterior source covariance, characterizing the uncertainty in estimates.

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

Bases: BaseEstimator, RegressorMixin

__init__(solver, solver_params=None, n_orient=1, logger=None)[source]#

Initialize the SourceEstimator class.

Parameters: - solver (callable): The inverse solver function (e.g., gamma_map, eloreta). - solver_params (dict, optional): Parameters for the solver function. - logger (logging.Logger, optional): Logger instance for logging messages. - n_orient (int, optional): Number of orientations for the sources.

Default is 1 (for fixed orientation) or 3 (for free orientation).

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.

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

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_indices (np.ndarray): Indices of active sources. - posterior_cov (np.ndarray): Posterior covariance matrix of estimated sources.

Uncertainty Estimation#

class calibrain.uncertainty_estimation.UncertaintyEstimator(confidence_levels=None, logger=None)[source]#

Bases: object

__init__(confidence_levels=None, logger=None)[source]#

Initialize the uncertainty estimator.

Parameters:#

confidence_levelslist, optional

List of confidence levels to compute confidence ellipses. Default is np.arange(0.0, 1.1, 0.1).

loggerlogging.Logger, optional

Logger instance for logging messages.

construct_full_covariance(x=None, x_hat_active_indices=None, posterior_cov=None, orientation_type='fixed')[source]#

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

Return type:

ndarray

Parameters:#

xnp.ndarray

Ground truth source activity values for active components. Shape: (n_sources, n_times) for fixed orientation or (n_sources, 3, n_times) for free orientation.

x_hat_active_indicesnp.ndarray

Indices of the active reconstructed sources in the original x_hat.

posterior_covnp.ndarray

Full Posterior covariance matrix. Shape: (n_active_sources, n_active_sources) for fixed orientation or

(n_active_sources*3, n_active_sources*3) for free orientation.

orientation_typestr

Orientation type of the sources, either ‘fixed’ or ‘free’.

Returns:#

: full_posterior_cov : np.ndarray

Full covariance matrix of shape (n_total_components, n_total_components), where n_total_components is the total number of source components.

get_confidence_intervals_data(x, x_hat, posterior_cov, orientation_type)[source]#

Computes confidence intervals and counts of true values within those intervals.

Return type:

tuple[ndarray, ndarray, ndarray]

Parameters:#

xnp.ndarray

Ground truth source activity. Shape (n_sources, n_times).

x_hatnp.ndarray

Estimated source activity (posterior mean). Shape (n_sources, n_times).

posterior_covnp.ndarray

Posterior covariance matrix of shape (n_sources, n_sources).

orientation_typestr

Orientation type, either ‘free’ or ‘fixed’.

Returns:#

: tuple

  • ci_lower_stacked (np.ndarray): Lower bounds of confidence intervals for each confidence level.

    Shape (n_confidence_levels, n_active_components, n_times).

  • ci_upper_stacked (np.ndarray): Upper bounds of confidence intervals for each confidence level.

    Shape (n_confidence_levels, n_active_components, n_times).

  • counts_array (np.ndarray): Counts of true values within confidence intervals for each confidence level.

    Shape (n_confidence_levels, 3, n_times) for free orientation, or (n_confidence_levels, 1, n_times) for fixed orientation.

debug_covariance(posterior_cov, full_posterior_cov, step_name)[source]#

Debug covariance matrix properties

Metric Evaluation#

class calibrain.metric_evaluation.MetricEvaluator(confidence_levels=None, metrics=None, logger=None)[source]#

Bases: object

__init__(confidence_levels=None, metrics=None, logger=None)[source]#

Initialize the MetricEvaluator with confidence levels, metrics, and a logger. :type confidence_levels: ndarray :param confidence_levels: Array of confidence levels to evaluate metrics against. :type confidence_levels: np.ndarray, optional :type metrics: list[str] :param metrics: List of metric names (method names) to evaluate. :type metrics: list[str], optional :type logger: Logger :param logger: Logger instance for logging debug and error messages. :type logger: logging.Logger, optional

mean_calibration_error(empirical_coverage, **kwargs)[source]#

Calculate the area under the curve (AUC) deviation, which measures the average calibration error. :type kwargs: :param kwargs: Additional keyword arguments that may be needed for metric calculations:

  • ‘empirical_coverage’: np.ndarray, empirical coverage values.

Returns:

The AUC deviation value.

Return type:

float

max_underconfidence_deviation(empirical_coverage, **kwargs)[source]#

Calculate the maximum positive deviation from the confidence levels (). :type empirical_coverage: :param empirical_coverage: Empirical coverage values. :type empirical_coverage: np.ndarray :type kwargs: :param kwargs: Additional keyword arguments that may be needed for metric calculations:

  • ‘empirical_coverage’: np.ndarray, empirical coverage values.

Returns:

The maximum positive deviation value.

Return type:

float

max_overconfidence_deviation(empirical_coverage, **kwargs)[source]#

Calculate the maximum negative deviation from the confidence levels. :type empirical_coverage: :param empirical_coverage: Empirical coverage values. :type empirical_coverage: np.ndarray :type kwargs: :param kwargs: Additional keyword arguments that may be needed for metric calculations:

  • ‘empirical_coverage’: np.ndarray, empirical coverage values.

Returns:

The maximum negative deviation value.

Return type:

float

mean_absolute_deviation(empirical_coverage, **kwargs)[source]#

Calculate the mean absolute deviation from the confidence levels.#

kwargsdict

Additional keyword arguments that may be needed for metric calculations: - ‘empirical_coverage’: np.ndarray, empirical coverage values.

returns:

The maximum absolute deviation value.

rtype:

float

mean_signed_deviation(empirical_coverage, **kwargs)[source]#

Calculate the mean signed deviation from the confidence levels.#

kwargsdict

Additional keyword arguments that may be needed for metric calculations: - ‘empirical_coverage’: np.ndarray, empirical coverage values.

returns:

The mean signed deviation value.

rtype:

float

mean_posterior_std(cov, **kwargs)[source]#

Calculate the mean posterior standard deviation. :type kwargs: :param kwargs: Additional keyword arguments that may be needed for metric calculations:

  • ‘cov’: np.ndarray, covariance matrix for uncertainty metrics.

Returns:

The mean posterior standard deviation.

Return type:

float

emd(x, x_hat, orientation_type, subject, fwd_path, **kwargs)[source]#

Compute Earth Mover’s Distance (EMD) between true and estimated source activations. Adapted from BSI-ZOO Parameters: - x : (n_sources, n_times) or (n_sources, 3, n_times)

Ground truth source time courses.

  • x_hatsame shape as x

    Estimated source time courses.

  • orientation_typestr

    ‘fixed’ or ‘free’ for orientation modeling.

  • subjectstr

    Subject ID used to locate the forward model.

Returns: - float

Earth Mover’s Distance between normalized source distributions.

jaccard_error(x, x_hat, orientation_type=None, **kwargs)[source]#

TODO: To be checked! Calculate Jaccard error between true and estimated active source sets.

Parameters:
  • x (np.ndarray) – True source activations

  • x_hat (np.ndarray) – Estimated source activations

  • orientation_type (str, optional) – ‘fixed’ or ‘free’ for orientation modeling

  • **kwargs (dict) – Additional arguments

Returns:

Jaccard error (1 - Jaccard index) between active source sets

Return type:

float

mse(x, x_hat, orientation_type, **kwargs)[source]#
euclidean_distance(x, x_hat, orientation_type, subject, nnz, fwd_path, **kwargs)[source]#

adapted from BSI-ZOO

f1(x, x_hat, orientation_type, **kwargs)[source]#

adapted from BSI-ZOO

accuracy(x, x_hat, orientation_type, **kwargs)[source]#

Calculate accuracy between true and estimated active source sets.

Accuracy = (TP + TN) / (TP + TN + FP + FN) where: - TP: True Positives (correctly identified active sources) - TN: True Negatives (correctly identified inactive sources) - FP: False Positives (incorrectly identified as active) - FN: False Negatives (missed active sources)

Parameters:
  • x (np.ndarray) – True source activations (n_sources, n_times) or (n_sources, 3, n_times)

  • x_hat (np.ndarray) – Estimated source activations (same shape as x)

  • orientation_type (str) – ‘fixed’ or ‘free’ for orientation modeling

  • **kwargs (dict) – Additional arguments

Returns:

Accuracy score between 0.0 and 1.0 (higher is better)

Return type:

float

evaluate_and_store_metrics(current_results_dict, metric_suffix='', **kwargs)[source]#

Evaluate metrics and update the results dictionary.

Parameters:
  • current_results_dict (dict) – Dictionary to store the results of the metrics.

  • metric_suffix (str, optional) – Suffix to add to metric keys (e.g., “_all_sources”, “_active_indices”).

  • kwargs (dict) – Additional keyword arguments that may be needed for metric calculations: - ‘empirical_coverage’: np.ndarray, empirical coverage values. - ‘cov’: np.ndarray, covariance matrix for uncertainty metrics.

Visualization#

class calibrain.visualization.Visualizer(base_save_path='results/figures', logger=None)[source]#

Bases: object

__init__(base_save_path='results/figures', logger=None)[source]#
plot_source_signals(ERP_config, x_trial, x_active_indices=None, units=None, trial_idx=None, title='Source Signals', save_dir=None, file_name=None, show=True)[source]#
plot_sensor_signals(ERP_config, y_trials, trial_idx=None, channels=None, units=None, mode='stack', title='Sensor Signals', save_dir=None, file_name=None, show=True)[source]#
plot_stc_3d_brain(ERP_config, x_one_trial, x_hat_one_trial, orientations, source_units, sample_idx, subject, subjects_dir, fwd_path, save_dir=None, file_name=None, show=False)[source]#

Plot source estimates with complete headless support.

plot_source_and_sensors(x_one_trial, x_active_indices, y_clean_one_trial, y_noisy_one_trial, nnz, ERP_config=None, source_units=202(FIFF_UNIT_AM), sensor_units=107(FIFF_UNIT_V), orientation_type='fixed', max_sensors=3, plot_sensors_together=False, shift=20.0, figsize=(14, 10), file_name='data_simulation.png', 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. Includes a line indicating stimulus onset. Uses self.tmin and self.tmax for the time axis.

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 self.sfreq.

  • 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

plot_active_sources(x_one_trial_one_time, x_hat_one_trial_one_time, x_active_indices, x_hat_active_indices, n_sources, source_units=202(FIFF_UNIT_AM), orientation_type='fixed', save_path=None, file_name=None, title=None, show=True)[source]#

Plot the active sources at a specific time step, or averaged across time, comparing ground truth and estimated values.

Parameters:
  • x (np.ndarray) – Ground truth values for components specified by active_indices.

  • x_hat (np.ndarray) – Estimated values for components specified by active_indices.

  • x_active_indices (np.ndarray) – Indices of active sources in the ground truth.

  • x_hat_active_indices (np.ndarray) – Indices of active sources in the estimated values.

  • n_sources (int) – Total number of sources.

  • source_units (str, optional) – Units for the source signals, by default FIFF.FIFF_UNIT_AM

  • orientation_type (str, optional) – Orientation type for the plot, by default “fixed”

  • save_path (Optional[str], optional) – Path to save the plot, by default None

  • file_name (Optional[str], optional) – Name of the file to save the plot, by default None

  • title (Optional[str], optional) – Title of the plot, by default None

  • show (bool, optional) – Whether to show the plot, by default True

plot_ci(x_one_trial_one_time, x_hat_one_trial_one_time, x_active_indices, x_hat_active_indices, n_sources, source_units, ci_lower, ci_upper, confidence_levels, orientation_type='fixed', sharey=True, file_name='active_sources_ci', save_path=None, show=True, figsize=(12, 6))[source]#
plot_calibration_curve(confidence_levels, empirical_coverage, result=None, which_legend='active_indices', file_name='calibration_curve', save_path=None, show=True)[source]#

Visualizes the calibration curve.

Parameters: - empirical_coverage (np.ndarray): 1D array of empirical coverage values,

corresponding to each confidence level in self.confidence_levels.

  • results (dict): Dictionary possibly containing calibration metrics.

  • which_legend (str): Specifies which set of metrics to display in the legend.

  • file_name (str): Base name for the saved plot file.

plot_all(x_trials, x_active_indices_trials, x_hat_one_trial, x_hat_active_indices_one_trial, y_clean_trials, y_noisy_trials, trial_idx=0, n_sources=1, subject=None, subjects_dir=None, fwd_path=None, nnz=1, ERP_config=None, sample_idx=0, source_units=202(FIFF_UNIT_AM), sensor_units=107(FIFF_UNIT_V), confidence_levels=None, empirical_coverages=None, ci_lower=None, ci_upper=None, orientation_type='fixed', result=None, experiment_dir=None)[source]#

Comprehensive visualization wrapper that generates all plots for experiment analysis.

This is a high-level wrapper function that orchestrates multiple visualization methods to create a complete set of plots for ERP source localization analysis.

Generated Visualizations: - Source signal plots (individual and all trials) - Sensor signal plots (stacked and concatenated) - 3D brain surface plots (if available) - Source-sensor comparison plots - Active source analysis plots - Confidence interval plots - Calibration curve plots

Called Methods: - plot_source_signals() - Source time series visualization - plot_sensor_signals() - Sensor measurements visualization - plot_stc_3d_brain() - 3D brain surface visualization - plot_source_and_sensors() - Combined source-sensor plots - plot_active_sources() - Active source comparison - plot_ci() - Confidence interval visualization - plot_calibration_curve() - Uncertainty calibration analysis

Parameters:
  • x_trials (np.ndarray) – Source activity trials, shape (n_trials, n_sources, n_times)

  • x_active_indices_trials (np.ndarray) – Active source indices per trial

  • x_hat_one_trial (np.ndarray) – Estimated source activity for one trial

  • x_hat_active_indices_one_trial (np.ndarray) – Estimated active source indices for one trial

  • y_clean_trials (np.ndarray) – Clean sensor measurements, shape (n_trials, n_sensors, n_times)

  • y_noisy_trials (np.ndarray) – Noisy sensor measurements, shape (n_trials, n_sensors, n_times)

  • trial_idx (int, optional) – Trial index for single-trial visualizations, by default 0

  • n_sources (int, optional) – Total number of sources, by default 1

  • subject (str, optional) – Subject name for brain plots

  • subjects_dir (str, optional) – FreeSurfer subjects directory

  • fwd_path (str, optional) – Forward model path

  • nnz (int, optional) – Number of non-zero sources, by default 1

  • ERP_config (dict, optional) – ERP configuration parameters

  • sample_idx (int, optional) – Time sample index for brain plots, by default 0

  • source_units (str, optional) – Source signal units, by default FIFF.FIFF_UNIT_AM

  • sensor_units (str, optional) – Sensor signal units, by default FIFF.FIFF_UNIT_V

  • confidence_levels (np.ndarray, optional) – Confidence levels for uncertainty analysis

  • empirical_coverages (dict, optional) – Empirical coverage data for calibration

  • ci_lower (np.ndarray, optional) – Lower confidence bounds

  • ci_upper (np.ndarray, optional) – Upper confidence bounds

  • orientation_type (str, optional) – Source orientation type, by default “fixed”

  • result (dict, optional) – Analysis results containing metrics

  • experiment_dir (str, optional) – Experiment directory for saving plots

Notes

This wrapper function automatically saves all plots to organized subdirectories: - data_simulation/ - Data visualization plots - uncertainty_analysis/ - Uncertainty quantification plots

All plots are saved with show=False for batch processing compatibility.

Examples

>>> viz = Visualizer(base_save_path="results/figures")
>>> viz.plot_all(
...     x_trials=x_trials,
...     x_active_indices_trials=active_indices,
...     x_hat_one_trial=x_hat,
...     # ... other parameters
... )
calibrain.visualization.main()[source]#

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.

calibrain.utils.save_subjects_mne_info(subjects=['CC120166', 'CC120264', 'CC120309', 'CC120313'], fwd_dir='examples/BSI-ZOO_forward_data')[source]#
calibrain.utils.inspect_object(obj, show_private=False)[source]#

Print attributes and methods of a Python object separately.

Parameters: - obj: The object to inspect. - show_private (bool): If True, include private attributes/methods (starting with ‘_’).

Returns: - dict with ‘attributes’ and ‘methods’ keys

Benchmarking#

class calibrain.benchmark.Benchmark(solver, solver_param_grid, data_param_grid, ERP_config, source_simulator, leadfield_builder, sensor_simulator, uncertainty_estimator, metric_evaluator, random_state=42, logger=None)[source]#
__init__(solver, solver_param_grid, data_param_grid, ERP_config, source_simulator, leadfield_builder, sensor_simulator, uncertainty_estimator, metric_evaluator, random_state=42, logger=None)[source]#

Initialize the Benchmark class.

Parameters:#

solvercallable

The solver function (e.g., gamma_map, eloreta).

solver_param_griddict

Grid of solver hyperparameters (e.g. noise_type, init_gamma).

data_param_griddict

Grid of data generation hyperparameters.

ERP_configdict

Configuration for ERP simulation.

source_simulatorSourceSimulator

Instance of SourceSimulator for generating source data.

leadfield_builderLeadfieldBuilder

Instance of LeadfieldBuilder for generating leadfields.

sensor_simulatorSensorSimulator

Instance of SensorSimulator for generating data.

uncertainty_estimatorUncertaintyEstimator

Instance of UncertaintyEstimator for uncertainty estimation.

metric_evaluatorMetricEvaluator

Instance of MetricEvaluator for evaluating metrics.

random_stateint, optional

Random seed for reproducibility.

loggerlogging.Logger, optional

Logger instance for logging messages.

create_experiment_directory(base_dir, params, desired_order)[source]#

Create a directory structure for the experiment, with subdirectories for each parameter in a specified order, followed by any remaining parameters.

Parameters: - base_dir (str): Base directory for the experiment. - params (dict): Dictionary of parameters. - desired_order (list): List of parameter keys in the desired order for the directory structure.

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

run(nruns=2, fig_path='results/figures/uncertainty_analysis_figures')[source]#

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

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