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:
- info
mne.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.- method
str
The multivariate method to use for the decomposition. Can be:
- indices
tuple
ofarray
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.
- mode
str
(default ‘multitaper’) The cross-spectral density computation method. Can be
'multitaper'
,'fourier'
, or'cwt_morlet'
.- fmin
int
|float
|None
(defaultNone
) The lowest frequency of interest in Hz. Must not be
None
and only used ifmode in ['multitaper', 'fourier']
.- fmax
int
|float
|None
(defaultNone
) The highest frequency of interest in Hz. Must not be
None
and only used ifmode in ['multitaper', 'fourier']
.- mt_bandwidth
int
|float
|None
(defaultNone
) 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_freqs
array
ofint
orfloat
|None
(defaultNone
) The frequencies of interest in Hz. Must not be
None
and only used ifmode='cwt_morlet'
.- cwt_n_cycles
int
|float
|array
ofint
orfloat
(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_components
int
|None
(defaultNone
) 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 therank
parameter). If anint
, 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.- rank
tuple
ofint
|None
(defaultNone
) 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 then_components
parameter). Specifying ranks below that of the data may reduce the degree of overfitting when computing the filters.- n_jobs
int
The number of jobs to run in parallel (default 1). Requires the joblib package.
- verbosebool,
str
,int
, orNone
If not None, override default verbose level (see
mne.verbose()
for more info). If used, it should be passed as a keyword-argument only.
- info
- Attributes:
- filters_
tuple
ofarray
, shape=(n_signals, n_components) A tuple of two arrays containing the spatial filters for transforming the seed and target data, respectively.
- patterns_
tuple
ofarray
, 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.
- filters_
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 of this object.
get_params
([deep])Get parameters for this estimator.
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
andmne_connectivity.spectral_connectivity_time
functions. These bivariate methods are: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
andmne_connectivity.spectral_connectivity_time
functions.References
- fit(X, y=None)[source]#
Compute connectivity decomposition filters for epoched data.
- Parameters:
- Returns:
- selfinstance of
CoherencyDecomposition
The modified class instance.
- selfinstance of
- fit_transform(X, y=None, **fit_params)[source]#
Fit filters to data, then transform and return it.
- Parameters:
- X
array
, shape=(n_epochs, n_signals, n_times) The input data which the connectivity decomposition filters should be fit to and subsequently transformed.
- y
None
Ignored; exists for compatibility with scikit-learn pipelines.
- **fit_params
dict
Additional fitting parameters passed to the
fit
method. Not used for this class.
- X
- Returns:
- X_transformed
array
, shape=(n_epochs, n_components*2, n_times) The transformed data. The first
n_components
channels are the transformed seeds, and the lastn_components
channels are the transformed targets.
- X_transformed
- get_metadata_routing()#
Get metadata routing of this object.
Please check User Guide on how the routing mechanism works.
- Returns:
- routing
MetadataRequest
A
MetadataRequest
encapsulating routing information.
- routing
- get_params(deep=True)#
Get parameters for this estimator.
- get_transformed_indices()[source]#
Get indices for the transformed data.
- Returns:
- indices_transformed
tuple
ofarray
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
andspectral_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…
- indices_transformed
- 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:
- info
mne.Info
Information about the sensors of the data which has been decomposed, such as that coming from an
mne.Epochs
object.- components
int
|array
ofint
|None
(defaultNone
) The components to plot. If None, all components are shown.
- ch_type‘mag’ | ‘grad’ | ‘planar1’ | ‘planar2’ | ‘eeg’ |
None
(defaultNone
) 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.- scalings
dict
|float
|None
(defaultNone
) The scalings of the channel types to be applied for plotting. If None, uses
dict(eeg=1e6, grad=1e13, mag=1e15)
.- sensorsbool |
str
(defaultTrue
) 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 ofplot()
). If True, black circles are used.- show_namesbool |
callable()
(defaultFalse
) 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 ', '')
. Ifmask
is not None, only non-masked sensor names will be shown.- mask
array
of bool, shape=(n_channels, n_filters) |None
(defaultNone
) 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_params
dict
|None
(defaultNone
) The plotting parameters for distinct combinations given in
mask
. Default None equals:dict(marker='o', markerfacecolor='w', markeredgecolor='k', linewidth=0, markersize=4)
- contours
int
|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. Ifcolorbar=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.
- sphere
float
|array
|mne.bem.ConductorModel
|None
| ‘auto’ | ‘eeglab’ (defaultNone
) 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_interp
str
(default ‘cubic’) The image interpolation to be used. Options are
'cubic'
to usescipy.interpolate.CloughTocher2DInterpolator
,'nearest'
to usescipy.spatial.Voronoi
, or'linear'
to usescipy.interpolate.LinearNDInterpolator
.- extrapolate
str
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.
- border
float
| ‘mean’ (default ‘mean’) The value to extrapolate to on the topomap borders. If
'mean'
, each extrapolated point has the average value of its neighbours.- res
int
(default 64) The resolution of the topomap image (number of pixels along each side).
- size
int
|float
(default 1) The side length of each subplot in inches.
- cmap
str
|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.
- vlim
tuple
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.- cnorm
matplotlib.colors.Normalize
|None
(defaultNone
) 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_fmt
str
(default ‘%.1E’) The formatting string for colorbar tick labels. See Format Specification Mini-Language for details.
- units
str
(default ‘AU’) The units for the colorbar label. Ignored if
colorbar=False
.- axes
matplotlib.axes.Axes
|list
ofmatplotlib.axes.Axes
|None
(defaultNone
) 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_format
str
|None
(defaultNone
) The string format for axes titles. If None, uses
f"{method}%%01d"
, i.e. the method name followed by the component number.- nrows
int
| ‘auto’ (default ‘auto’) The number of rows of components to plot. If
'auto'
, the necessary number will be inferred.- ncols
int
| ‘auto’ (default ‘auto’) The number of columns of components to plot. If
'auto'
, the necessary number will be inferred. Ifnrows='auto'
andncols='auto'
, becomesnrows=1, ncols='auto'
.- showbool (default
True
) Whether to show the figure.
- info
- Returns:
- figs
list
ofmatplotlib.figure.Figure
The seed and target figures, respectively.
- figs
- 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:
- info
mne.Info
Information about the sensors of the data which has been decomposed, such as that coming from an
mne.Epochs
object.- components
int
|array
ofint
|None
(defaultNone
) The components to plot. If None, all components are shown.
- ch_type‘mag’ | ‘grad’ | ‘planar1’ | ‘planar2’ | ‘eeg’ |
None
(defaultNone
) 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.- scalings
dict
|float
|None
(defaultNone
) The scalings of the channel types to be applied for plotting. If None, uses
dict(eeg=1e6, grad=1e13, mag=1e15)
.- sensorsbool |
str
(defaultTrue
) 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 ofplot()
). If True, black circles are used.- show_namesbool |
callable()
(defaultFalse
) 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 ', '')
. Ifmask
is not None, only non-masked sensor names will be shown.- mask
array
of bool, shape=(n_channels, n_patterns) |None
(defaultNone
) 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_params
dict
|None
(defaultNone
) The plotting parameters for distinct combinations given in
mask
. Default None equals:dict(marker='o', markerfacecolor='w', markeredgecolor='k', linewidth=0, markersize=4)
- contours
int
|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. Ifcolorbar=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.
- sphere
float
|array
|mne.bem.ConductorModel
|None
| ‘auto’ | ‘eeglab’ (defaultNone
) 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_interp
str
(default ‘cubic’) The image interpolation to be used. Options are
'cubic'
to usescipy.interpolate.CloughTocher2DInterpolator
,'nearest'
to usescipy.spatial.Voronoi
, or'linear'
to usescipy.interpolate.LinearNDInterpolator
.- extrapolate
str
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.
- border
float
| ‘mean’ (default ‘mean’) The value to extrapolate to on the topomap borders. If
'mean'
, each extrapolated point has the average value of its neighbours.- res
int
(default 64) The resolution of the topomap image (number of pixels along each side).
- size
int
|float
(default 1) The side length of each subplot in inches.
- cmap
str
|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.
- vlim
tuple
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.- cnorm
matplotlib.colors.Normalize
|None
(defaultNone
) 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_fmt
str
(default ‘%.1E’) The formatting string for colorbar tick labels. See Format Specification Mini-Language for details.
- units
str
(default ‘AU’) The units for the colorbar label. Ignored if
colorbar=False
.- axes
matplotlib.axes.Axes
|list
ofmatplotlib.axes.Axes
|None
(defaultNone
) 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_format
str
|None
(defaultNone
) The string format for axes titles. If None, uses
f"{method}%%01d"
, i.e. the method name followed by the component number.- nrows
int
| ‘auto’ (default ‘auto’) The number of rows of components to plot. If
'auto'
, the necessary number will be inferred.- ncols
int
| ‘auto’ (default ‘auto’) The number of columns of components to plot. If
'auto'
, the necessary number will be inferred. Ifnrows='auto'
andncols='auto'
, becomesnrows=1, ncols='auto'
.- showbool (default
True
) Whether to show the figure.
- info
- Returns:
- figs
list
ofmatplotlib.figure.Figure
The seed and target figures, respectively.
- figs
- 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
andfit_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:
- self
estimator
instance Estimator instance.
- self
- 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.
- transform(X)[source]#
Decompose data into connectivity sources using the fitted filters.
- Parameters:
- X
array
, shape=((n_epochs, ) n_signals, n_times) The data to be transformed by the connectivity decomposition filters.
- X
- Returns:
- X_transformed
array
, shape=((n_epochs, ) n_components*2, n_times) The transformed data. The first
n_components
channels are the transformed seeds, and the lastn_components
channels are the transformed targets.
- X_transformed