mne_connectivity.decoding.CoherencyDecomposition#

class mne_connectivity.decoding.CoherencyDecomposition(info, method, indices, mode='multitaper', fmin=None, fmax=None, mt_bandwidth=None, mt_adaptive=False, mt_low_bias=True, cwt_freqs=None, cwt_n_cycles=7, n_components=None, rank=None, n_jobs=1, verbose=None)[source]#

Decompose connectivity sources using multivariate coherency-based methods.

Parameters:
infomne.Info

Information about the data which will be decomposed and transformed, such as that coming from an mne.Epochs object. The number of channels must match the subsequent input data.

methodstr

The multivariate method to use for the decomposition. Can be:

  • 'cacoh' - Canonical Coherency (CaCoh) [1]

  • 'mic' - Maximised Imaginary part of Coherency (MIC) [2]

indicestuple of array

A tuple of two arrays, containing the indices of the seed and target channels in the input data, respectively. The indices of only a single connection (i.e. between one group of seeds and one group of targets) is supported.

modestr (default ‘multitaper’)

The cross-spectral density computation method. Can be 'multitaper', 'fourier', or 'cwt_morlet'.

fminint | float | None (default None)

The lowest frequency of interest in Hz. Must not be None and only used if mode in ['multitaper', 'fourier'].

fmaxint | float | None (default None)

The highest frequency of interest in Hz. Must not be None and only used if mode in ['multitaper', 'fourier'].

mt_bandwidthint | float | None (default None)

The bandwidth of the multitaper windowing function in Hz to use when computing the cross-spectral density. Only used if mode='multitaper'.

mt_adaptivebool (default False)

Whether to use adaptive weights when combining the tapered spectra in the cross-spectral density. Only used if mode='multitaper'.

mt_low_biasbool (default True)

Whether to use tapers with over 90 percent spectral concentration within the bandwidth when computing the cross-spectral density. Only used if mode='multitaper'.

cwt_freqsarray of int or float | None (default None)

The frequencies of interest in Hz. Must not be None and only used if mode='cwt_morlet'.

cwt_n_cyclesint | float | array of int or float (default 7)

The number of cycles to use when constructing the Morlet wavelets. Fixed number or one per frequency. Only used if mode='cwt_morlet'.

n_componentsint | None (default None)

The number of connectivity components (sources) to extract from the data. If None, the number of components equal to the minimum rank of the seeds and targets is extracted (see the rank parameter). If an int, the number of components must be <= the minimum rank of the seeds and targets. E.g. if the seed channels had a rank of 5 and the target channels had a rank of 3, n_components must be <= 3.

ranktuple of int | None (default None)

A tuple of two ints, containing the degree of rank subspace projection to apply to the seed and target data, respectively, before filters are fit. If None, the rank of the seed and target data is used. If a tuple of ints, the entries must be <= the rank of the seed and target data. The minimum rank of the seeds and targets determines the maximum number of connectivity components (sources) which can be extracted from the data (see the n_components parameter). Specifying ranks below that of the data may reduce the degree of overfitting when computing the filters.

n_jobsint

The number of jobs to run in parallel (default 1). Requires the joblib package.

verbosebool, str, int, or None

If not None, override default verbose level (see mne.verbose() for more info). If used, it should be passed as a keyword-argument only.

Attributes:
filters_tuple of array, shape=(n_signals, n_components)

A tuple of two arrays containing the spatial filters for transforming the seed and target data, respectively.

patterns_tuple of array, shape=(n_components, n_signals)

A tuple of two arrays containing the spatial patterns corresponding to the spatial filters for the seed and target data, respectively.

Methods

fit(X[, y])

Compute connectivity decomposition filters for epoched data.

fit_transform(X[, y])

Fit filters to data, then transform and return it.

get_metadata_routing()

Get metadata routing of this object.

get_params([deep])

Get parameters for this estimator.

get_transformed_indices()

Get indices for the transformed data.

plot_filters(info[, components, ch_type, ...])

Plot topographic filters of components.

plot_patterns(info[, components, ch_type, ...])

Plot topographic patterns of components.

set_output(*[, transform])

Set output container.

set_params(**params)

Set the parameters of this estimator.

transform(X)

Decompose data into connectivity sources using the fitted filters.

Notes

The multivariate methods maximise connectivity between a set of seed and target signals in a frequency-resolved manner. The maximisation of connectivity involves fitting spatial filters to the cross-spectral density of the seed and target data, alongside which spatial patterns of the contributions to connectivity can be computed [3].

Once fit, the filters can be used to transform data into the underlying connectivity components. Connectivity can be computed on this transformed data using the bivariate coherency-based methods of the mne_connectivity.spectral_connectivity_epochs and mne_connectivity.spectral_connectivity_time functions. These bivariate methods are:

  • "cohy" and "coh" for CaCoh [1]

  • "imcoh" for MIC [2]

The approach taken here is to optimise the connectivity in a given frequency band. Frequency bin-wise optimisation is offered in the multivariate coherency-based methods of the mne_connectivity.spectral_connectivity_epochs and mne_connectivity.spectral_connectivity_time functions.

References

fit(X, y=None)[source]#

Compute connectivity decomposition filters for epoched data.

Parameters:
Xarray, shape=(n_epochs, n_signals, n_times)

The input data which the connectivity decomposition filters should be fit to.

yNone

Ignored; exists for compatibility with scikit-learn pipelines.

Returns:
selfinstance of CoherencyDecomposition

The modified class instance.

fit_transform(X, y=None, **fit_params)[source]#

Fit filters to data, then transform and return it.

Parameters:
Xarray, shape=(n_epochs, n_signals, n_times)

The input data which the connectivity decomposition filters should be fit to and subsequently transformed.

yNone

Ignored; exists for compatibility with scikit-learn pipelines.

**fit_paramsdict

Additional fitting parameters passed to the fit method. Not used for this class.

Returns:
X_transformedarray, shape=(n_epochs, n_components*2, n_times)

The transformed data. The first n_components channels are the transformed seeds, and the last n_components channels are the transformed targets.

get_metadata_routing()#

Get metadata routing of this object.

Please check User Guide on how the routing mechanism works.

Returns:
routingMetadataRequest

A MetadataRequest encapsulating routing information.

get_params(deep=True)#

Get parameters for this estimator.

Parameters:
deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.

Returns:
paramsdict

Parameter names mapped to their values.

get_transformed_indices()[source]#

Get indices for the transformed data.

Returns:
indices_transformedtuple of array

Indices of seeds and targets in the transformed data with the form (seeds, targets) to be used when passing the data to spectral_connectivity_epochs and spectral_connectivity_time. Entries of the indices are arranged such that connectivity would be computed between the first seed component and first target component, second seed component and second target component, etc…

plot_filters(info, components=None, ch_type=None, scalings=None, sensors=True, show_names=False, mask=None, mask_params=None, contours=6, outlines='head', sphere=None, image_interp='cubic', extrapolate='auto', border='mean', res=64, size=1, cmap='RdBu_r', vlim=(None, None), cnorm=None, colorbar=True, cbar_fmt='%.1E', units='AU', axes=None, name_format=None, nrows=1, ncols='auto', show=True)[source]#

Plot topographic filters of components.

The filters are used to extract discriminant neural sources from the measured data (a.k.a. the backward model). [3].

Seed and target filters are plotted separately.

Parameters:
infomne.Info

Information about the sensors of the data which has been decomposed, such as that coming from an mne.Epochs object.

componentsint | array of int | None (default None)

The components to plot. If None, all components are shown.

ch_type‘mag’ | ‘grad’ | ‘planar1’ | ‘planar2’ | ‘eeg’ | None (default None)

The channel type to plot. For 'grad', the gradiometers are collected in pairs and the RMS for each pair is plotted. If None, the first available channel type from the order shown above is used.

scalingsdict | float | None (default None)

The scalings of the channel types to be applied for plotting. If None, uses dict(eeg=1e6, grad=1e13, mag=1e15).

sensorsbool | str (default True)

Whether to add markers for sensor locations. If str, should be a valid matplotlib format string (e.g., 'r+' for red plusses; see the Notes section of plot()). If True, black circles are used.

show_namesbool | callable() (default False)

Whether to show channel names next to each sensor marker. If callable, channel names will be formatted using the callable; e.g., to delete the prefix ‘MEG ‘ from all channel names, pass the function lambda x: x.replace('MEG ', ''). If mask is not None, only non-masked sensor names will be shown.

maskarray of bool, shape=(n_channels, n_filters) | None (default None)

An array specifying channel-filter combinations to highlight with a distinct plotting style. Array elements set to True will be plotted with the parameters given in mask_params. If None, no combinations will be highlighted.

mask_paramsdict | None (default None)

The plotting parameters for distinct combinations given in mask. Default None equals:

dict(marker='o', markerfacecolor='w', markeredgecolor='k',
     linewidth=0, markersize=4)
contoursint | array (default 6)

The number of contour lines to draw. If 0, no contours will be drawn. If a positive integer, that number of contour levels are chosen using the matplotlib tick locator (may sometimes be inaccurate, use array for accuracy). If an array-like, the values are used as the contour levels. The values should be in µV for EEG, fT for magnetometers and fT/m for gradiometers. If colorbar=True, the colorbar will have ticks corresponding to the contour levels.

outlines‘head’ | dict | None (default ‘head’)

The outlines to be drawn. If ‘head’, the default head scheme will be drawn. If dict, each key refers to a tuple of x and y positions, the values in ‘mask_pos’ will serve as image mask. Alternatively, a matplotlib patch object can be passed for advanced masking options, either directly or as a function that returns patches (required for multi-axis plots). If None, nothing will be drawn.

spherefloat | array | mne.bem.ConductorModel | None | ‘auto’ | ‘eeglab’ (default None)

The sphere parameters to use for the head outline. Can be array-like of shape (4,) to give the X/Y/Z origin and radius in meters, or a single float to give just the radius (origin assumed 0, 0, 0). Can also be an instance of a spherical ConductorModel to use the origin and radius from that object. If 'auto' the sphere is fit to digitization points. If 'eeglab' the head circle is defined by EEG electrodes 'Fpz', 'Oz', 'T7', and 'T8' (if 'Fpz' is not present, it will be approximated from the coordinates of 'Oz'). None is equivalent to 'auto' when enough extra digitization points are available, and (0, 0, 0, 0.95) otherwise.

image_interpstr (default ‘cubic’)

The image interpolation to be used. Options are 'cubic' to use scipy.interpolate.CloughTocher2DInterpolator, 'nearest' to use scipy.spatial.Voronoi, or 'linear' to use scipy.interpolate.LinearNDInterpolator.

extrapolatestr

The extrapolation options. Can be one of:

  • 'box'

    Extrapolate to four points placed to form a square encompassing all data points, where each side of the square is three times the range of the data in the respective dimension.

  • 'local' (default for MEG sensors)

    Extrapolate only to nearby points (approximately to points closer than median inter-electrode distance). This will also set the mask to be polygonal based on the convex hull of the sensors.

  • 'head' (default for non-MEG sensors)

    Extrapolate out to the edges of the clipping circle. This will be on the head circle when the sensors are contained within the head circle, but it can extend beyond the head when sensors are plotted outside the head circle.

borderfloat | ‘mean’ (default ‘mean’)

The value to extrapolate to on the topomap borders. If 'mean', each extrapolated point has the average value of its neighbours.

resint (default 64)

The resolution of the topomap image (number of pixels along each side).

sizeint | float (default 1)

The side length of each subplot in inches.

cmapstr | matplotlib.colors.Colormap | (matplotlib.colors.Colormap, bool) | ‘interactive’ | None (default ‘RdBu_r’)

The colormap to use. If a str, should be a valid matplotlib colormap. If a tuple, the first value is matplotlib.colors.Colormap object to use and the second value is a boolean defining interactivity. In interactive mode the colors are adjustable by clicking and dragging the colorbar with left and right mouse button. Left mouse button moves the scale up and down and right mouse button adjusts the range. Hitting space bar resets the range. Up and down arrows can be used to change the colormap. If None, 'Reds' is used for data that is either all positive or all negative, and 'RdBu_r' is used otherwise. 'interactive' is equivalent to (None, True).

Warning

Interactive mode works smoothly only for a small amount of topomaps. Interactive mode is disabled by default for more than 2 topomaps.

vlimtuple of length 2 (default (None, None))

The lower and upper colormap bounds, respectively. If both entries are None, sets bounds to (min(data), max(data)). If one entry is None, the corresponding boundary is set at the min/max of the data.

cnormmatplotlib.colors.Normalize | None (default None)

How to normalize the colormap. If None, standard linear normalization is used. If not None, vlim is ignored. See the Matplotlib docs for more details on colormap normalization.

colorbarbool (default True)

Whether to plot a colorbar in the rightmost column of the figure.

cbar_fmtstr (default ‘%.1E’)

The formatting string for colorbar tick labels. See Format Specification Mini-Language for details.

unitsstr (default ‘AU’)

The units for the colorbar label. Ignored if colorbar=False.

axesmatplotlib.axes.Axes | list of matplotlib.axes.Axes | None (default None)

The axes to plot to. If None, a new figure will be created with the correct number of axes. If not None, the number of axes must match components.

name_formatstr | None (default None)

The string format for axes titles. If None, uses f"{method}%%01d", i.e. the method name followed by the component number.

nrowsint | ‘auto’ (default ‘auto’)

The number of rows of components to plot. If 'auto', the necessary number will be inferred.

ncolsint | ‘auto’ (default ‘auto’)

The number of columns of components to plot. If 'auto', the necessary number will be inferred. If nrows='auto' and ncols='auto', becomes nrows=1, ncols='auto'.

showbool (default True)

Whether to show the figure.

Returns:
figslist of matplotlib.figure.Figure

The seed and target figures, respectively.

plot_patterns(info, components=None, ch_type=None, scalings=None, sensors=True, show_names=False, mask=None, mask_params=None, contours=6, outlines='head', sphere=None, image_interp='cubic', extrapolate='auto', border='mean', res=64, size=1, cmap='RdBu_r', vlim=(None, None), cnorm=None, colorbar=True, cbar_fmt='%.1E', units='AU', axes=None, name_format=None, nrows=1, ncols='auto', show=True)[source]#

Plot topographic patterns of components.

The patterns explain how the measured data was generated from the neural sources (a.k.a. the forward model) [3].

Seed and target patterns are plotted separately.

Parameters:
infomne.Info

Information about the sensors of the data which has been decomposed, such as that coming from an mne.Epochs object.

componentsint | array of int | None (default None)

The components to plot. If None, all components are shown.

ch_type‘mag’ | ‘grad’ | ‘planar1’ | ‘planar2’ | ‘eeg’ | None (default None)

The channel type to plot. For 'grad', the gradiometers are collected in pairs and the RMS for each pair is plotted. If None, the first available channel type from the order shown above is used.

scalingsdict | float | None (default None)

The scalings of the channel types to be applied for plotting. If None, uses dict(eeg=1e6, grad=1e13, mag=1e15).

sensorsbool | str (default True)

Whether to add markers for sensor locations. If str, should be a valid matplotlib format string (e.g., 'r+' for red plusses; see the Notes section of plot()). If True, black circles are used.

show_namesbool | callable() (default False)

Whether to show channel names next to each sensor marker. If callable, channel names will be formatted using the callable; e.g., to delete the prefix ‘MEG ‘ from all channel names, pass the function lambda x: x.replace('MEG ', ''). If mask is not None, only non-masked sensor names will be shown.

maskarray of bool, shape=(n_channels, n_patterns) | None (default None)

An array specifying channel-pattern combinations to highlight with a distinct plotting style. Array elements set to True will be plotted with the parameters given in mask_params. If None, no combinations will be highlighted.

mask_paramsdict | None (default None)

The plotting parameters for distinct combinations given in mask. Default None equals:

dict(marker='o', markerfacecolor='w', markeredgecolor='k',
     linewidth=0, markersize=4)
contoursint | array (default 6)

The number of contour lines to draw. If 0, no contours will be drawn. If a positive integer, that number of contour levels are chosen using the matplotlib tick locator (may sometimes be inaccurate, use array for accuracy). If an array-like, the values are used as the contour levels. The values should be in µV for EEG, fT for magnetometers and fT/m for gradiometers. If colorbar=True, the colorbar will have ticks corresponding to the contour levels.

outlines‘head’ | dict | None (default ‘head’)

The outlines to be drawn. If ‘head’, the default head scheme will be drawn. If dict, each key refers to a tuple of x and y positions, the values in ‘mask_pos’ will serve as image mask. Alternatively, a matplotlib patch object can be passed for advanced masking options, either directly or as a function that returns patches (required for multi-axis plots). If None, nothing will be drawn.

spherefloat | array | mne.bem.ConductorModel | None | ‘auto’ | ‘eeglab’ (default None)

The sphere parameters to use for the head outline. Can be array-like of shape (4,) to give the X/Y/Z origin and radius in meters, or a single float to give just the radius (origin assumed 0, 0, 0). Can also be an instance of a spherical ConductorModel to use the origin and radius from that object. If 'auto' the sphere is fit to digitization points. If 'eeglab' the head circle is defined by EEG electrodes 'Fpz', 'Oz', 'T7', and 'T8' (if 'Fpz' is not present, it will be approximated from the coordinates of 'Oz'). None is equivalent to 'auto' when enough extra digitization points are available, and (0, 0, 0, 0.95) otherwise.

image_interpstr (default ‘cubic’)

The image interpolation to be used. Options are 'cubic' to use scipy.interpolate.CloughTocher2DInterpolator, 'nearest' to use scipy.spatial.Voronoi, or 'linear' to use scipy.interpolate.LinearNDInterpolator.

extrapolatestr

The extrapolation options. Can be one of:

  • 'box'

    Extrapolate to four points placed to form a square encompassing all data points, where each side of the square is three times the range of the data in the respective dimension.

  • 'local' (default for MEG sensors)

    Extrapolate only to nearby points (approximately to points closer than median inter-electrode distance). This will also set the mask to be polygonal based on the convex hull of the sensors.

  • 'head' (default for non-MEG sensors)

    Extrapolate out to the edges of the clipping circle. This will be on the head circle when the sensors are contained within the head circle, but it can extend beyond the head when sensors are plotted outside the head circle.

borderfloat | ‘mean’ (default ‘mean’)

The value to extrapolate to on the topomap borders. If 'mean', each extrapolated point has the average value of its neighbours.

resint (default 64)

The resolution of the topomap image (number of pixels along each side).

sizeint | float (default 1)

The side length of each subplot in inches.

cmapstr | matplotlib.colors.Colormap | (matplotlib.colors.Colormap, bool) | ‘interactive’ | None (default ‘RdBu_r’)

The colormap to use. If a str, should be a valid matplotlib colormap. If a tuple, the first value is matplotlib.colors.Colormap object to use and the second value is a boolean defining interactivity. In interactive mode the colors are adjustable by clicking and dragging the colorbar with left and right mouse button. Left mouse button moves the scale up and down and right mouse button adjusts the range. Hitting space bar resets the range. Up and down arrows can be used to change the colormap. If None, 'Reds' is used for data that is either all positive or all negative, and 'RdBu_r' is used otherwise. 'interactive' is equivalent to (None, True).

Warning

Interactive mode works smoothly only for a small amount of topomaps. Interactive mode is disabled by default for more than 2 topomaps.

vlimtuple of length 2 (default (None, None))

The lower and upper colormap bounds, respectively. If both entries are None, sets bounds to (min(data), max(data)). If one entry is None, the corresponding boundary is set at the min/max of the data.

cnormmatplotlib.colors.Normalize | None (default None)

How to normalize the colormap. If None, standard linear normalization is used. If not None, vlim is ignored. See the Matplotlib docs for more details on colormap normalization.

colorbarbool (default True)

Whether to plot a colorbar in the rightmost column of the figure.

cbar_fmtstr (default ‘%.1E’)

The formatting string for colorbar tick labels. See Format Specification Mini-Language for details.

unitsstr (default ‘AU’)

The units for the colorbar label. Ignored if colorbar=False.

axesmatplotlib.axes.Axes | list of matplotlib.axes.Axes | None (default None)

The axes to plot to. If None, a new figure will be created with the correct number of axes. If not None, the number of axes must match components.

name_formatstr | None (default None)

The string format for axes titles. If None, uses f"{method}%%01d", i.e. the method name followed by the component number.

nrowsint | ‘auto’ (default ‘auto’)

The number of rows of components to plot. If 'auto', the necessary number will be inferred.

ncolsint | ‘auto’ (default ‘auto’)

The number of columns of components to plot. If 'auto', the necessary number will be inferred. If nrows='auto' and ncols='auto', becomes nrows=1, ncols='auto'.

showbool (default True)

Whether to show the figure.

Returns:
figslist of matplotlib.figure.Figure

The seed and target figures, respectively.

set_output(*, transform=None)#

Set output container.

See Introducing the set_output API for an example on how to use the API.

Parameters:
transform{“default”, “pandas”, “polars”}, default=None

Configure output of transform and fit_transform.

  • “default”: Default output format of a transformer

  • “pandas”: DataFrame output

  • “polars”: Polars output

  • None: Transform configuration is unchanged

Added in version 1.4: “polars” option was added.

Returns:
selfestimator instance

Estimator instance.

set_params(**params)#

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.

Parameters:
**paramsdict

Estimator parameters.

Returns:
selfestimator instance

Estimator instance.

transform(X)[source]#

Decompose data into connectivity sources using the fitted filters.

Parameters:
Xarray, shape=((n_epochs, ) n_signals, n_times)

The data to be transformed by the connectivity decomposition filters.

Returns:
X_transformedarray, shape=((n_epochs, ) n_components*2, n_times)

The transformed data. The first n_components channels are the transformed seeds, and the last n_components channels are the transformed targets.