mne_connectivity.EpochTemporalConnectivity#
- class mne_connectivity.EpochTemporalConnectivity(data, times, n_nodes, names=None, indices='all', method=None, events=None, event_id=None, **kwargs)[source]#
Connectivity class with epoch and time dimensions.
The underlying data is an array of shape
(n_epochs, n_connections[, n_components], n_times).n_componentsis an optional dimension for multivariate methods where each connection has multiple components of connectivity.- Parameters:
- data
array, shape (n_epochs, n_connections[, n_components], n_times) The connectivity data.
n_connectionsis equal ton_nodes * n_nodesifindices='all',n_nodes * (n_nodes - 1) / 2ifindicesis'lower'or'upper', or the length of the arrays inindicesif a tuple of arrays.- times
list|array The times 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.- indices
tupleof array_like |'lower'|'upper'|'all' The indices of channels connectivity was computed between. If a tuple, then contains two array-likes, where the first array represents the channel indices of the seeds, and the second array represents the channel indices of the targets. For multivariate methods, the seed and target indices should consist of nested arrays containing the channel indices for each multivariate connection. If
'lower', connectivity represents the lower-triangular part of the connectivity matrix. If'upper', connectivity represents the upper-triangular part of the connectivity matrix. If'all', connectivity represents all connections. Indices for multivarate methods should only be specified as a tuple of arrays.- method
str|None The method name used to compute connectivity (default
None).- events
arrayofint, shape (n_events, 3) |None The events array. Default is
None.- event_id
dict|None Mapping from condition descriptions (strings) to integer event codes. Default is
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.
companionGenerate block companion matrix for a vector autoregressive (VAR) model.
coordsThe coordinates of the xarray data.
dimsThe dimensions of the xarray data.
event_idMapping from condition descriptions (strings) to integer event codes.
eventsThe events array, for those event types found in
event_id.indicesIndices of connectivity data.
methodThe method used to compute connectivity.
n_epochsThe number of epochs the connectivity data varies over.
n_nodesThe number of nodes in the original dataset.
namesNode names.
shapeShape of raveled connectivity.
timesThe time points of the connectivity data.
xarrayXarray of the connectivity data.
Methods
append(epoch_conn)Append another epoched connectivity structure, in place.
combine_epochs([method])Aggregate connectivity data over epochs.
combine_times([method, tmin, tmax])Aggregate connectivity data over times.
copy()Return a deep copy of the connectivity container.
get_data([output, missing])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)Save connectivity data to disk.
simulate(n_samples[, noise_func, random_state])Simulate data using the vector autoregressive (VAR) model.
eigvals
is_stable
- append(epoch_conn)#
Append another epoched connectivity structure, in place.
- Parameters:
- epoch_conninstance of
EpochConnectivityorEpochTemporalConnectivityorEpochSpectralConnectivityorEpochSpectroTemporalConnectivity The connectivity container to append. Must be of the same type as the current container instance.
- epoch_conninstance of
- Returns:
- selfinstance of
EpochConnectivityorEpochTemporalConnectivityorEpochSpectralConnectivityorEpochSpectroTemporalConnectivity The altered connectivity container with the new epochs appended. The instance type matches that of the current container instance.
- selfinstance of
- property attrs#
Xarray attributes of connectivity.
See
xarray’sattrs.
- 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 aNumPy arrayof shape(n_epochs, ...)as input and return an array collapsed over the epoch dimension. Default is'mean'.
- method
- Returns:
- coninstance of
ConnectivityorSpectralConnectivityorTemporalConnectivityorSpectroTemporalConnectivity The connectivity data aggregated over the epoch dimension. Instance type reflects that of the current connectivity instance, without the epoch dimension.
- coninstance of
Notes
Passing in
np.medianis 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
- combine_times(method='mean', tmin=None, tmax=None)#
Aggregate connectivity data over times.
- Parameters:
- method
'mean'|'median'|callable() How to aggregate the data across times. If
callable, must take aNumPy arrayof shape(..., n_times)as input and return an array collapsed over the time dimension. Default is'mean'.- tmin, tmax
float|None First and last times to aggregate over, in seconds. If
Noneuse the first or last times in the data, respectively. Default isNone.
- method
- Returns:
- coninstance of
ConnectivityorEpochConnectivityorSpectralConnectivityorEpochSpectralConnectivity The connectivity data aggregated over the time dimension. Instance type reflects that of the current connectivity instance, without the time dimension.
- coninstance of
Notes
Passing in
np.medianis 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#
Generate block companion matrix for a vector autoregressive (VAR) model.
Returns the data matrix if the VAR model order (i.e., the number of lags) is 1.
- 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 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', missing='raise')#
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) will return'raveled'ifindicesis a tuple of arrays, or'dense'ifindicesis'all','lower', or'upper'.
- missing
'raise'|float How to handle missing values in the dense connectivity matrix when these cannot be filled in (see notes for more information). If
'raise', an error is raised. If a float, the missing values are filled with that float. Ignored ifoutput='raveled'. Default is'raise'.
- output
- Returns:
Notes
Handling missing values for dense outputs
If
indicesis not'all'andoutput='dense', there may be missing values from the full connectivity matrix that need to be filled in:When
indicesis'lower'or'upper', the missing values will try to be inferred based on the existing ones, falling back to the behaviour determined by themissingparameter if they cannot be inferred.When
indicesis a tuple andindicesrepresents a subset of the full connectivity matrix, the missing values will not be inferred, and the behaviour is determined by themissingparameter.When
indicesis a tuple andindicesrepresents the full connectivity matrix, there are no missing values to fill in.
Handling dense outputs for multivariate connectivity
Because multivariate connectivity data can involve multiple channels per connection, it is not possible to represent the data in a dense matrix form where each row/column represent a single channel.
Instead, the multivariate data is mapped into a new space, based on the set of channels that define each node. E.g., the multivariate indices:
( [[0, 1], [0, 1], [2, 3]], # seeds [[2, 3], [4, 5], [4, 5]] # targets )
contains the following sets of channels:
[0, 1](node 0);[2, 3](node 1); and[4, 5](node 2). Based on this, the multivariate indices can be mapped to a new space with indices:( [0, 0, 1], # seeds [1, 2, 2] # targets )
For a dense connectivity matrix, this would return a
(3, 3)upper-triangular array.To ensure the mapping from the original multivariate indices to the new dense matrix space is traceable,
multivariate_nodesis returned, which contains the (unmasked form) of each node in the position where it exists in the dense matrix space. For the above example,multivariate_nodeswould be[[0, 1], [2, 3], [4, 5]].
- property indices#
Indices of connectivity data.
- 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
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.LinearSegmentedColormap Colormap to use for coloring the connections.
- 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.- 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)#
Save connectivity data to disk.
Can later be loaded using the function
read_connectivity().- Parameters:
- fname
str|pathlib.Path The filepath to save the data. Data is saved as netCDF files (
.ncextension).
- fname
- property shape#
Shape of raveled connectivity.
- simulate(n_samples, noise_func=None, random_state=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.- random_state
int| array_like ofint|SeedSequence|BitGenerator|Generator|None Seed passed to
numpy.random.default_rng()to generate the default Gaussian noise whennoise_funcisNone. IfNone(default), a newnumpy.random.Generatorseeded from entropy is used.
- 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 times#
The time points of the connectivity data.
- property xarray#
Xarray of the connectivity data.