mne_connectivity.VARConnectivity#
- class mne_connectivity.VARConnectivity(data, lags, n_nodes, names=None, method=None, n_epochs_used=None, **kwargs)[source]#
Connectivity class for vector autoregressive models (VAR).
The underlying data is an array of shape
(n_connections, n_lags).- Parameters:
- data
array, shape (n_connections, n_lags) The connectivity data.
n_connectionsis equal ton_nodes * n_nodes, as the data is expected to represent the interactions between all channels, i.e.,indices='all'in otherConnectivitycontainers.- lags
list|array The lags at which the connectivity data is computed over.
- n_nodes
int 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 ton_nodes. If a list of names, then it must be equal in length ton_nodes.- method
str|None The method name used to compute connectivity (default
None).- n_epochs_used
int|None The number of epochs used in the computation of connectivity (default
None).- **kwargs
dict Extra connectivity parameters, like
componentsfor multivariate connectivity with multiple components per connection, or extra parameters to be stored as xarrayattrs.
- data
- Attributes:
attrsXarray attributes of connectivity.
companionBlock companion matrix for the VAR model.
coordsThe coordinates of the xarray data.
dimsThe dimensions of the xarray data.
eigvalsEigenvalues of the companion matrix for the VAR model.
indicesIndices of connectivity data.
is_stableWhether the VAR model is stable.
lagsThe lags of the VAR model.
methodThe method used to compute connectivity.
n_epochs_usedNumber of epochs used in computation of connectivity.
n_nodesThe number of nodes in the original dataset.
namesNode names.
shapeShape of raveled connectivity.
xarrayXarray of the connectivity data.
Methods
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.
- property attrs#
Xarray attributes of connectivity.
See
xarray’sattrs.
- 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.
- 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'.
- output
- Returns:
- data
array The output connectivity data.
- data
- property indices#
Indices of connectivity data.
- Returns:
- indices
'all' VAR models represent the interactions between all channels.
- indices
- 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_used#
Number of epochs used in computation of connectivity.
Can be
None, if no epochs were used.
- property n_nodes#
The number of nodes in the original dataset.
Even if
indicesdefines 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_names
listofstr Node names. The order corresponds to the order in
con.- indices
tupleof array_like |None Two arrays with indices of connections for which the connections strengths are defined in
con. Only needed ifconis a 1D array.- n_lines
int|None If not
None, only then_linesstrongest connections (strength=abs(con)) are drawn.- node_angles
array, shape (n_node_names,) |None Array with node positions in degrees. If
None, the nodes are equally spaced on the circle. Seemne.viz.circular_layout().- node_width
float|None Width of each node in degrees. If
None, the minimum angle between any two nodes is used as the width.- node_height
float The relative height of the colored bar labeling each node. Default 1.0 is the standard height.
- node_colors
listoftuple|listofstr 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.
- facecolor
str Color to use for background. See
matplotlib.colors.- textcolor
str Color to use for text. See
matplotlib.colors.- node_edgecolor
str Color to use for lines around nodes. See
matplotlib.colors.- linewidth
float Line width to use for connections.
- colormap
str| instance ofmatplotlib.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 whenvminandvmaxspan zero:"berlin"on a darkfacecolor("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"toNone.- vmin
float|None Minimum value for colormap. If
None, it is determined automatically.- vmax
float|None Maximum value for colormap. If
None, it is determined automatically. If bothvminandvmaxareNoneand 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.
- title
str The figure title.
- colorbar_size
float Size of the colorbar.
- colorbar_pos
tuple, shape (2,) Position of the colorbar.
- fontsize_title
int Font size to use for title.
- fontsize_names
int Font size to use for node names.
- fontsize_colorbar
int Font size to use for colorbar.
- padding
float 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_linewidth
float Line width for nodes.
- showbool
Show figure if
True.
- node_names
- Returns:
- figinstance of
matplotlib.figure.Figure The figure handle.
- axinstance of
matplotlib.projections.polar.PolarAxes The subplot handle.
- figinstance of
Notes
This code is based on a circle graph example by Nicolas P. Rougier.
By default,
matplotlib.pyplot.savefig()does not takefacecolorinto 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
facecoloris not set viamatplotlib.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:
- data
array, 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_signalsshould match the number of signals in the VAR model.
- data
- Returns:
- predicted
array, shape ([n_epochs,] n_signals, n_times) Data as predicted by the VAR model, of the same shape as
data.
- predicted
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:
- mapping
dict Mapping from original node names (keys) to new node names (values).
- mapping
- save(fname, *, overwrite=False, verbose=None)#
Save connectivity data to disk (in HDF5 format).
- Parameters:
- fname
str|pathlib.Path The filepath to save the data. Data is saved as HDF5 files (the
.h5or.hdf5extensions).- overwritebool
Whether to overwrite the file, if it exists (default False).
- verbosebool |
str|int|None If not
None, override default verbose level (seemne.verbose()for more info). If used, it should be passed as a keyword-argument only.
- fname
See also
- property shape#
Shape of raveled connectivity.
- simulate(n_samples, noise_func=None, rng=None)#
Simulate data using the vector autoregressive (VAR) model.
- Parameters:
- n_samples
int Number of samples to generate.
- noise_func
callable()|None The function used to create the generating noise process. Each call to this function should return an array of shape
(n_nodes,). IfNone, Gaussian white noise with zero mean and unit variance is used.- rng
int| array_like ofint|SeedSequence|BitGenerator|Generator|None Seed passed to
numpy.random.default_rng(). IfNone(default), a newnumpy.random.Generatorseeded from entropy is used. Only used whennoise_funcisNone.Changed in version 1.0: Renamed to
rngfromrandom_state.
- n_samples
- Returns:
- data
array, shape (n_nodes, n_samples) Generated data.
- 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.VARConnectivity#
Compute vector autoregressive model (linear system)