Source Estimation#

SE#

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.