osl_dynamics.analysis.connectivity#

Functions to calculate and plot network connectivity.

Note

This module is used in the following tutorials:

Module Contents#

Functions#

sliding_window_connectivity(data, window_length[, ...])

Calculate sliding window connectivity.

covariance_from_spectra(f, cpsd[, components, ...])

Calculates covariance from cross power spectra.

mean_coherence_from_spectra(f, coh[, components, ...])

Calculates mean coherence from spectra.

mean_connections(conn_map)

Average the edges for each node.

eigenvectors(conn_map[, n_eigenvectors, ...])

Calculate eigenvectors of a connectivity matrix.

gmm_threshold(conn_map[, subtract_mean, mean_weights, ...])

Threshold a connectivity matrix using the GMM method.

fit_gmm(conn_map[, subtract_mean, mean_weights, ...])

Fit a two component GMM to connections to identify a threshold.

threshold(conn_map, percentile[, subtract_mean, ...])

Return edges that exceed a threshold.

separate_edges(conn_map)

Separate positive and negative edges in a connectivity map.

spectral_reordering(corr_mat)

Spectral re-ordering for correlation matrices.

save(connectivity_map, parcellation_file[, filename, ...])

Save connectivity maps as image files.

save_interactive(connectivity_map, parcellation_file)

Save connectivity maps as interactive HTML plots.

osl_dynamics.analysis.connectivity.sliding_window_connectivity(data, window_length, step_size=None, conn_type='corr', concatenate=False)[source]#

Calculate sliding window connectivity.

Parameters:
  • data (list or np.ndarray) – Time series data. Shape must be (n_sessions, n_samples, n_channels) or (n_samples, n_channels).

  • window_length (int) – Window length in samples.

  • step_size (int, optional) – Number of samples to slide the window along the time series. If None, then step_size=window_length // 2.

  • conn_type (str, optional) – Metric to use to calculate pairwise connectivity in the network. Should use "corr" for Pearson correlation or "cov" for covariance.

  • concatenate (bool, optional) – Should we concatenate the sliding window connectivities from each array into one big time series?

Returns:

sliding_window_conn – Time series of connectivity matrices. Shape is (n_sessions, n_windows, n_channels, n_channels) or (n_windows, n_channels, n_channels).

Return type:

list or np.ndarray

osl_dynamics.analysis.connectivity.covariance_from_spectra(f, cpsd, components=None, frequency_range=None)[source]#

Calculates covariance from cross power spectra.

Parameters:
  • f (np.ndarray) – Frequency axis of the spectra. Only used if frequency_range is given. Shape must be (n_freq,).

  • cpsd (np.ndarray) – Cross power spectra. Shape must be (n_modes, n_channels, n_channels, n_freq).

  • components (np.ndarray, optional) – Spectral components. Shape must be (n_components, n_freq).

  • frequency_range (list, optional) – Frequency range to integrate the PSD over (Hz). Default is the full range.

Returns:

covar – Covariance over a frequency band for each component of each mode. Shape is (n_components, n_modes, n_channels, n_channels).

Return type:

np.ndarray

osl_dynamics.analysis.connectivity.mean_coherence_from_spectra(f, coh, components=None, frequency_range=None)[source]#

Calculates mean coherence from spectra.

Parameters:
  • f (np.ndarray) – Frequency axis of the spectra. Only used if frequency_range is given. Shape must be (n_freq,).

  • coh (np.ndarray) – Coherence for each channel. Shape must be (n_modes, n_channels, n_channels, n_freq).

  • components (np.ndarray, optional) – Spectral components. Shape must be (n_components, n_freq).

  • frequency_range (list, optional) – Frequency range to integrate the PSD over (Hz).

Returns:

mean_coh – Mean coherence over a frequency band for each component of each mode. Shape is (n_components, n_modes, n_channels, n_channels) or (n_modes, n_channels, n_channels) or (n_channels, n_channels).

Return type:

np.ndarray

osl_dynamics.analysis.connectivity.mean_connections(conn_map)[source]#

Average the edges for each node.

Parameters:

conn_map (np.ndarray) – A (…, n_channels, n_channels) connectivity matrix.

Returns:

mean_connections – A (…, n_channels) matrix.

Return type:

np.ndarray

osl_dynamics.analysis.connectivity.eigenvectors(conn_map, n_eigenvectors=1, absolute_value=False, as_network=False)[source]#

Calculate eigenvectors of a connectivity matrix.

Parameters:
  • conn_map (np.ndarray) – Connectivity matrix. Shape must be (…, n_channels, n_channels).

  • n_eigenvectors (int, optional) – Number of eigenvectors to include.

  • absolute_value (bool, optional) – Should we take the absolute value of the connectivity matrix before calculating the eigen decomposition?

  • as_network (bool, optional) – Should we return a matrix?

Returns:

eigenvectors – Eigenvectors. Shape is (n_eigenvectors, …, n_channels, n_channels) if as_network=True, otherwise it is (n_eigenvectors, …, n_channels). If n_eigenvectors=1, the first dimension is removed.

Return type:

np.ndarray.

osl_dynamics.analysis.connectivity.gmm_threshold(conn_map, subtract_mean=False, mean_weights=None, standardize=False, p_value=None, keep_positive_only=False, one_component_percentile=0, n_sigma=0, sklearn_kwargs=None, show=False, filename=None, plot_kwargs=None)[source]#

Threshold a connectivity matrix using the GMM method.

Wrapper for combining connectivity.fit_gmm and connectivity.threshold.

Parameters:
  • conn_map (np.ndarray) – Connectivity matrix. Shape must be (n_components, n_modes, n_channels, n_channels) or (n_modes, n_channels, n_channels) or (n_channels, n_channels).

  • subtract_mean (bool, optional) – Should we subtract the mean over modes before fitting a GMM?

  • mean_weights (np.ndarray, optional) – Numpy array with weightings for each mode/state to use to calculate the mean. Default is equal weighting.

  • standardize (bool, optional) – Should we standardize the input to the GMM?

  • p_value (float, optional) – Used to determine a threshold. We ensure the data points assigned to the ‘on’ component have a probability of less than p_value of belonging to the ‘off’ component.

  • keep_positive_only (bool, optional) – Should we only keep positive values to fit a GMM to?

  • one_component_percentile (float, optional) – Percentile threshold if only one component is found. Should be a between 0 and 100. E.g. for the 95th percentile, one_component_percentile=95.

  • n_sigma (float, optional) – Number of standard deviations of the ‘off’ component the mean of the ‘on’ component must be for the fit to be considered to have two components.

  • sklearn_kwargs (dict, optional) – Dictionary of keyword arguments to pass to sklearn.mixture.GaussianMixture.

  • show (bool, optional) – Should we show the GMM fit to the distribution of conn_map.

  • filename (str, optional) – Filename to save fit to.

  • plot_kwargs (dict, optional) – Dictionary of keyword arguments to pass to utils.plotting.plot_gmm.

Returns:

conn_map – Thresholded connectivity matrix. The shape is the same as the original conn_map.

Return type:

np.ndarray

osl_dynamics.analysis.connectivity.fit_gmm(conn_map, subtract_mean=False, mean_weights=None, standardize=False, p_value=None, keep_positive_only=False, one_component_percentile=0, n_sigma=0, sklearn_kwargs=None, show=False, filename=None, plot_kwargs=None)[source]#

Fit a two component GMM to connections to identify a threshold.

Parameters:
  • conn_map (np.ndarray) – Connectivity map. Shape must be (n_components, n_modes, n_channels, n_channels) or (n_modes, n_channels, n_channels) or (n_channels, n_channels).

  • subtract_mean (bool, optional) – Should we subtract the mean over modes before fitting a GMM?

  • mean_weights (np.ndarray, optional) – Numpy array with weightings for each mode/state to use to calculate the mean. Default is equal weighting.

  • standardize (bool, optional) – Should we standardize the input to the GMM?

  • p_value (float, optional) – Used to determine a threshold. We ensure the data points assigned to the ‘on’ component have a probability of less than p_value of belonging to the ‘off’ component.

  • keep_positive_only (bool, optional) – Should we only keep positive values to fit a GMM to?

  • one_component_percentile (float, optional) – Percentile threshold if only one component is found. Should be a between 0 and 100. E.g. for the 95th percentile, one_component_percentile=95.

  • n_sigma (float, optional) – Number of standard deviations of the ‘off’ component the mean of the ‘on’ component must be for the fit to be considered to have two components.

  • sklearn_kwargs (dict, optional) –

    Dictionary of keyword arguments to pass to sklearn.mixture.GaussianMixture Default is {"max_iter": 5000, "n_init": 10}.

  • show (bool, optional) – Should we show the GMM fit to the distribution of conn_map.

  • filename (str, optional) – Filename to save fit to.

  • plot_kwargs (dict, optional) –

    Dictionary of keyword arguments to pass to utils.plotting.plot_gmm.

Returns:

percentile – Percentile threshold. Shape is (n_components, n_modes) or (n_modes,).

Return type:

np.ndarray

osl_dynamics.analysis.connectivity.threshold(conn_map, percentile, subtract_mean=False, mean_weights=None, absolute_value=False, return_edges=False)[source]#

Return edges that exceed a threshold.

Parameters:
  • conn_map (np.ndarray) – Connectivity matrix to threshold. Shape must be (n_components, n_modes, n_channels, n_channels), (n_modes, n_channels, n_channels) or (n_channels, n_channels).

  • percentile (float or np.ndarray) – Percentile to threshold with. Should be between 0 and 100. Shape must be (n_components, n_modes), (n_modes,) or a float.

  • subtract_mean (bool, optional) – Should we subtract the mean over modes before thresholding? The thresholding is only done to identify edges, the values returned in conn_map are not mean subtracted.

  • mean_weights (np.ndarray, optional) – Weights when calculating the mean over modes.

  • absolute_value (bool, optional) – Should we take the absolute value before thresholding? The thresholding is only done to identify edges, the values returned in conn_map are not absolute values. If subtract_mean=True, the mean is subtracted before the absolute value.

  • return_edges (bool, optional) – Should we return a boolean array for whether edges are above the threshold?

Returns:

conn_map – Connectivity matrix with connections below the threshold set to zero. Or a boolean array if return_edges=True. Shape is the same as the original conn_map.

Return type:

np.ndarray

osl_dynamics.analysis.connectivity.separate_edges(conn_map)[source]#

Separate positive and negative edges in a connectivity map.

Parameters:

conn_map (np.ndarray) – Connectivity map. Any shape.

Returns:

  • pos_conn_map (np.ndarray) – Connectivity map with positive edges. Shape is the same as conn_map.

  • neg_conn_map (np.ndarray) – Connectivity map with negative edges. Shape is the same as conn_map.

osl_dynamics.analysis.connectivity.spectral_reordering(corr_mat)[source]#

Spectral re-ordering for correlation matrices.

Parameters:

corr_mat (np.ndarray) – Correlation matrix. Shape must be (n_channels, n_channels).

Returns:

  • reorder_corr_mat (np.ndarray) – Re-ordered correlation matrix. Shape is (n_channels, n_channels).

  • order (np.ndarray) – New ordering. Shape is (n_channels,).

osl_dynamics.analysis.connectivity.save(connectivity_map, parcellation_file, filename=None, component=None, threshold=0, plot_kwargs=None, axes=None, combined=False, titles=None)[source]#

Save connectivity maps as image files.

This function is a wrapper for nilearn.plotting.plot_connectome.

Parameters:
  • connectivity_map (np.ndarray) – Matrices containing connectivity strengths to plot. Shape must be (n_components, n_modes, n_channels, n_channels), (n_modes, n_channels, n_channels) or (n_channels, n_channels).

  • parcellation_file (str) – Name of parcellation file used.

  • filename (str, optional) – Output filename. If None is passed then the image is shown on screen. Must have extension .png, .pdf or .svg.

  • component (int, optional) – Spectral component to save.

  • threshold (float or np.ndarray, optional) – Threshold to determine which connectivity to show. Should be between 0 and 1. If a float is passed the same threshold is used for all modes. Otherwise, threshold should be a numpy array of shape (n_modes,).

  • plot_kwargs (dict, optional) – Keyword arguments to pass to the nilearn plotting function.

  • axes (list, optional) – List of matplotlib axes to plot the connectivity maps on.

  • combined (bool, optional) – Should the connectivity maps be combined on the same figure? The combined image is always shown on screen (for Juptyer notebooks). Note if True is passed, the individual images will be deleted.

  • titles (list, optional) – List of titles for each connectivity map. Only used if combined=True.

Examples

Change colormap and views:

connectivity.save(
    ...,
    plot_kwargs={
        "edge_cmap": "red_transparent_full_alpha_range",
        "display_mode": "lyrz",
    },
)
osl_dynamics.analysis.connectivity.save_interactive(connectivity_map, parcellation_file, filename=None, component=None, threshold=0, plot_kwargs=None)[source]#

Save connectivity maps as interactive HTML plots.

This function is a wrapper for nilearn.plotting.view_connectome

Parameters:
  • connectivity_map (np.ndarray) – Matrices containing connectivity strengths to plot. Shape must be (n_components, n_modes, n_channels, n_channels), (n_modes, n_channels, n_channels) or (n_channels, n_channels).

  • parcellation_file (str) – Name of parcellation file used.

  • filename (str, optional) – Output filename. If None is passed then the image is shown on screen. Must have extension .html.

  • component (int, optional) – Spectral component to save.

  • threshold (float or np.ndarray, optional) – Threshold to determine which connectivity to show. Should be between 0 and 1. If a float is passed the same threshold is used for all modes. Otherwise, threshold should be a numpy array of shape (n_modes,).

  • plot_kwargs (dict, optional) – Keyword arguments to pass to the nilearn plotting function.