mne_connectivity.EpochVARConnectivity#

class mne_connectivity.EpochVARConnectivity(data, lags, n_nodes, names=None, method=None, events=None, event_id=None, **kwargs)[source]#

Connectivity class for vector autoregressive models (VAR) with epoch dimension.

The underlying data is an array of shape (n_epochs, n_connections, n_lags).

Parameters:
dataarray, shape (n_epochs, n_connections, n_lags)

The connectivity data. n_connections is equal to n_nodes * n_nodes, as the data is expected to represent the interactions between all channels, i.e., indices='all' in other Connectivity containers.

lagslist | array

The lags at which the connectivity data is computed over.

n_nodesint

The number of nodes in the dataset used to compute connectivity. This should be equal to the number of signals in the original dataset.

namesarray_like | None

The names of the nodes of the dataset used to compute connectivity. If None (default), then names will be a list of integers from 0 to n_nodes. If a list of names, then it must be equal in length to n_nodes.

methodstr | None

The method name used to compute connectivity (default None).

eventsarray of int, shape (n_events, 3) | None

The events array. Default is None.

event_iddict | None

Mapping from condition descriptions (strings) to integer event codes. Default is None.

**kwargsdict

Extra connectivity parameters, like components for multivariate connectivity with multiple components per connection, or extra parameters to be stored as xarray attrs.

Attributes:
attrs

Xarray attributes of connectivity.

companion

Block companion matrix for the VAR model.

coords

The coordinates of the xarray data.

dims

The dimensions of the xarray data.

eigvals

Eigenvalues of the companion matrix for the VAR model.

event_id

Mapping from condition descriptions (strings) to integer event codes.

events

The events array, for those event types found in event_id.

indices

Indices of connectivity data.

is_stable

Whether the VAR model is stable.

lags

The lags of the VAR model.

method

The method used to compute connectivity.

n_epochs

The number of epochs the connectivity data varies over.

n_nodes

The number of nodes in the original dataset.

names

Node names.

shape

Shape of raveled connectivity.

xarray

Xarray of the connectivity data.

Methods

append(epoch_conn)

Append another epoched connectivity structure, in place.

combine_epochs([method])

Aggregate connectivity data over epochs.

copy()

Return a deep copy of the connectivity container.

get_data([output])

Get connectivity data as a numpy array.

plot_circle(**kwargs)

Visualize connectivity as a circular graph.

predict(data)

Predict samples on data using the vector autoregressive (VAR) model.

rename_nodes(mapping)

Rename nodes.

save(fname, *[, overwrite, verbose])

Save connectivity data to disk (in HDF5 format).

simulate(n_samples[, noise_func, rng])

Simulate data using the vector autoregressive (VAR) model.

append(epoch_conn)#

Append another epoched connectivity structure, in place.

Parameters:
epoch_conninstance of EpochConnectivity or EpochTemporalConnectivity or EpochSpectralConnectivity or EpochSpectroTemporalConnectivity

The connectivity container to append. Must be of the same type as the current container instance.

Returns:
selfinstance of EpochConnectivity or EpochTemporalConnectivity or EpochSpectralConnectivity or EpochSpectroTemporalConnectivity

The altered connectivity container with the new epochs appended. The instance type matches that of the current container instance.

property attrs#

Xarray attributes of connectivity.

See xarray’s attrs.

combine_epochs(method='mean')#

Aggregate connectivity data over epochs.

Parameters:
method'mean' | 'median' | callable()

How to aggregate the data across epochs. If callable, must take a NumPy array of shape (n_epochs, ...) as input and return an array collapsed over the epoch dimension. Default is 'mean'.

Returns:
coninstance of Connectivity or SpectralConnectivity or TemporalConnectivity or SpectroTemporalConnectivity

The connectivity data aggregated over the epoch dimension. Instance type reflects that of the current connectivity instance, without the epoch dimension.

Notes

Passing in np.median is considered unsafe for complex data. Pass the string "median" instead to compute the marginal median (i.e., the median of the real and imaginary components separately). See discussion here: scipy/scipy#12676

property companion#

Block companion matrix for the VAR model.

property coords#

The coordinates of the xarray data.

copy()#

Return a deep copy of the connectivity container.

property dims#

The dimensions of the xarray data.

property eigvals#

Eigenvalues of the companion matrix for the VAR model.

property event_id#

Mapping from condition descriptions (strings) to integer event codes.

property events#

The events array, for those event types found in event_id.

get_data(output='compact')#

Get connectivity data as a numpy array.

Parameters:
output'compact' | 'raveled' | 'dense'

How to format the output:

  • 'raveled' will represent each connectivity matrix as a (..., n_connections, ...) array.

  • 'dense' will return each connectivity matrix as a (..., n_nodes, n_nodes, ...) array.

  • 'compact' (default) is an alias for 'dense'.

Returns:
dataarray

The output connectivity data.

property indices#

Indices of connectivity data.

Returns:
indices'all'

VAR models represent the interactions between all channels.

property is_stable#

Whether the VAR model is stable.

property lags#

The lags of the VAR model.

property method#

The method used to compute connectivity.

property n_epochs#

The number of epochs the connectivity data varies over.

property n_nodes#

The number of nodes in the original dataset.

Even if indices defines a subset of nodes that were computed, this should be the total number of nodes in the original dataset.

property names#

Node names.

plot_circle(**kwargs)#

Visualize connectivity as a circular graph.

Parameters:
node_nameslist of str

Node names. The order corresponds to the order in con.

indicestuple of array_like | None

Two arrays with indices of connections for which the connections strengths are defined in con. Only needed if con is a 1D array.

n_linesint | None

If not None, only the n_lines strongest connections (strength=abs(con)) are drawn.

node_anglesarray, shape (n_node_names,) | None

Array with node positions in degrees. If None, the nodes are equally spaced on the circle. See mne.viz.circular_layout().

node_widthfloat | None

Width of each node in degrees. If None, the minimum angle between any two nodes is used as the width.

node_heightfloat

The relative height of the colored bar labeling each node. Default 1.0 is the standard height.

node_colorslist of tuple | list of str

List with the color to use for each node. If fewer colors than nodes are provided, the colors will be repeated. Any color supported by matplotlib can be used, e.g., RGBA tuples, named colors.

facecolorstr

Color to use for background. See matplotlib.colors.

textcolorstr

Color to use for text. See matplotlib.colors.

node_edgecolorstr

Color to use for lines around nodes. See matplotlib.colors.

linewidthfloat

Line width to use for connections.

colormapstr | instance of matplotlib.colors.Colormap | None

Colormap to use for coloring the connections. If None (default), a diverging colormap is used when the drawn connections have both positive and negative values, or when vmin and vmax span zero: "berlin" on a dark facecolor ("RdBu_r" with matplotlib < 3.10) and "RdBu_r" on a light one. Otherwise, "hot" is used.

Changed in version 1.0: The default changed from "hot" to None.

vminfloat | None

Minimum value for colormap. If None, it is determined automatically.

vmaxfloat | None

Maximum value for colormap. If None, it is determined automatically. If both vmin and vmax are None and the drawn connections have both positive and negative values, the limits are symmetric around zero.

Changed in version 1.0: Automatic limits for data with both signs are symmetric around zero.

colorbarbool

Display a colorbar or not.

titlestr

The figure title.

colorbar_sizefloat

Size of the colorbar.

colorbar_postuple, shape (2,)

Position of the colorbar.

fontsize_titleint

Font size to use for title.

fontsize_namesint

Font size to use for node names.

fontsize_colorbarint

Font size to use for colorbar.

paddingfloat

Space to add around figure to accommodate long labels.

axinstance of matplotlib.projections.polar.PolarAxes | None

The axes to use to plot the connectivity circle.

interactivebool

When enabled, left-click on a node to show only connections to that node. Right-click shows all connections.

node_linewidthfloat

Line width for nodes.

showbool

Show figure if True.

Returns:
figinstance of matplotlib.figure.Figure

The figure handle.

axinstance of matplotlib.projections.polar.PolarAxes

The subplot handle.

Notes

This code is based on a circle graph example by Nicolas P. Rougier.

By default, matplotlib.pyplot.savefig() does not take facecolor into account when saving, even if set when a figure is generated. This can be addressed via, e.g.:

>>> fig.savefig(fname_fig, facecolor='black')

If facecolor is not set via matplotlib.pyplot.savefig(), the figure labels, title, and legend may be cut off in the output figure.

predict(data)#

Predict samples on data using the vector autoregressive (VAR) model.

The result of this method is used for calculating the residuals.

Parameters:
dataarray, shape ([n_epochs,] n_signals, n_times)

Epoched or continuous data. If the VAR model is time-varying (i.e., there are different models per epoch), then the data should also be epoched, with one epoch per VAR model. n_signals should match the number of signals in the VAR model.

Returns:
predictedarray, shape ([n_epochs,] n_signals, n_times)

Data as predicted by the VAR model, of the same shape as data.

Notes

Residuals are obtained by residuals = x - var.predict(x).

To compute residual covariances from epoched data:

# compute the covariance of the residuals
# rows are observations, columns are variables
t = residuals.shape[0]  # n_epochs
sampled_residuals = np.concatenate(
    np.split(residuals[:, :, lags:], t, 0), axis=2
).squeeze(0)
residuals_cov = np.cov(sampled_residuals)
rename_nodes(mapping)#

Rename nodes.

Parameters:
mappingdict

Mapping from original node names (keys) to new node names (values).

save(fname, *, overwrite=False, verbose=None)#

Save connectivity data to disk (in HDF5 format).

Parameters:
fnamestr | pathlib.Path

The filepath to save the data. Data is saved as HDF5 files (the .h5 or .hdf5 extensions).

overwritebool

Whether to overwrite the file, if it exists (default False).

verbosebool | str | int | 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.

property shape#

Shape of raveled connectivity.

simulate(n_samples, noise_func=None, rng=None)#

Simulate data using the vector autoregressive (VAR) model.

Parameters:
n_samplesint

Number of samples to generate.

noise_funccallable() | None

The function used to create the generating noise process. Each call to this function should return an array of shape (n_nodes,). If None, Gaussian white noise with zero mean and unit variance is used.

rngint | array_like of int | SeedSequence | BitGenerator | Generator | None

Seed passed to numpy.random.default_rng(). If None (default), a new numpy.random.Generator seeded from entropy is used. Only used when noise_func is None.

Changed in version 1.0: Renamed to rng from random_state.

Returns:
dataarray, shape (n_nodes, n_samples)

Generated data.

Notes

If the VAR model is time-varying (i.e., there are different models per epoch), the data is simulated from the average of these models.

property xarray#

Xarray of the connectivity data.

Examples using mne_connectivity.EpochVARConnectivity#

Compute vector autoregressive model (linear system)

Compute vector autoregressive model (linear system)