spectral_connectivity.wrapper.multitaper_connectivity#

multitaper_connectivity(time_series: NDArray[floating] | DataArray, sampling_frequency: float | None = None, time_window_duration: float | None = None, method: str | list[str] | None = None, signal_names: Sequence[str | bytes | bool | int | float | integer | floating | bool | str_ | bytes_ | datetime64 | timedelta64] | None = None, squeeze: bool = False, connectivity_kwargs: dict[str, ~typing.Any] | None=None, *, time_window_step: float | None = None, time_halfbandwidth_product: float = 3, n_tapers: int | None = None, detrend_type: str | None = 'constant', transform_kwargs: Mapping[str, ~typing.Any] | None=None, group_labels: Sequence[Hashable] | NDArray[Any] | str | None = None, frequency_range: tuple[float, float] | None=None, frequency_decimation: int = 1, frequency_bands: Mapping[str, tuple[float, float]] | None=None, frequency_reduction: Literal['mean', 'integral']='mean', time_dim: Hashable | None = None, trial_dim: Hashable | None = None, signal_dim: Hashable | None = None, dtype: DTypeLike = <class 'numpy.complex128'>, minimum_phase_tolerance: float = 1e-08, minimum_phase_max_iterations: int = 500, **kwargs: Any) → DataArray | Dataset[source]#

Compute connectivity measures with multitaper spectral estimation.

This is the main high-level function for connectivity analysis. It performs multitaper spectral analysis on the input time series and computes the requested connectivity measures, returning results as labeled xarray objects.

Changed in version 3.0: For pairwise_spectral_granger_prediction and subset_pairwise_spectral_granger_prediction, sel(source=a, target=b) is a -> b; 2.x returned b -> a. The 2.x wrapper rejected the transfer-function measures and could not return phase_slope_index, group_delay, or delay, whose Connectivity arrays were already source first.

Parameters:
  • time_series (NDArray[floating] or xarray.DataArray,) – shape (n_time_samples, n_trials, n_signals) or (n_time_samples, n_signals) Time series data, time first. In a 3-D array trials are the middle axis and signals the last: x[:, k, :] is trial k. An array of shape (500, 3, 40) is read as 500 time samples of 3 trials of 40 signals; if it holds 3 signals and 40 trials, pass np.swapaxes(x, 1, 2). Array input cannot be checked for this (a DataArray’s dimension names can). A 2-D array is one trial. For multiple trials, trials are averaged in spectral domain. For a DataArray, common time/trial/signal dimension names are inferred and transposed automatically; use time_dim, trial_dim, and signal_dim for domain-specific names. Ambiguous names raise rather than falling back to dimension position, though a single unrecognized dimension left for the one remaining role is assigned by elimination with a warning (a spectral name such as frequency or band is rejected instead, since it marks an already-transformed input). A dask-backed DataArray is rejected (materialize it first with DataArray.compute()). A numeric time index is interpreted as elapsed seconds (a sample index as sample numbers) and used to label output window centers. When sampling_frequency is given it is validated against the index; when it is omitted, an elapsed-seconds time coordinate infers it (a sample index cannot, having no time scale). Datetime, timedelta, and object-valued time coordinates are not yet supported and must first be converted to numeric elapsed seconds. When signal_names is omitted, labels from a 1-D index coordinate on the signal dimension are carried to the output’s source and target coordinates without changing their type; if such labels are present but unusable a warning is issued and default string labels are used.

  • sampling_frequency (float, optional) – Sampling rate in Hz of the time series data. Required for array input; for a DataArray it may be omitted and inferred from a sufficiently precise numeric elapsed-seconds time coordinate. Pass it explicitly when a low-precision or large-offset coordinate cannot resolve the rate reliably. An inferred rate of at most 1 Hz, or a coordinate whose units attribute says milliseconds, warns that the coordinate may be in milliseconds (read as seconds, it gives a rate 1000 times too low); passing the rate, or units="s" on the coordinate for a slow recording, silences it. A millisecond coordinate of data sampled faster than 1 kHz infers a rate above 1 Hz and is not detected unless its units attribute says milliseconds: set units or pass the rate.

  • time_window_duration (float, optional) – Duration of sliding window in seconds for time-resolved analysis. If None, analyzes entire time series (no time resolution).

  • method (str or list of str, optional) – Connectivity method(s) to compute. If None, computes the default set of real-valued measures that fit the xarray/NetCDF interface (see DEFAULT_METHODS) — not every measure. coherency is left out of the default because complex arrays are not portably serializable across all supported xarray versions and NetCDF engines, but it can be requested by name. Every directed measure is opt-in by name, including pairwise_spectral_granger_prediction and the directed-transfer-function family (directed_transfer_function, directed_coherence, partial_directed_coherence, generalized_partial_directed_coherence, direct_directed_transfer_function); the spectral Granger and transfer-function measures factorize the spectrum and dominate the cost (see the Notes on directed orientation). Measures with nonstandard layouts, including global_coherence, phase_slope_index, group_delay, delay, canonical_coherence, and blockwise spectral Granger, are available by name and return labeled DataArrays or Datasets with their component, group, candidate-delay, or frequency-reduced dimensions. "global_coherence" here pools each time window’s trials and tapers; to pool the windows too, use Connectivity.from_transform(transform, expectation_type="time_trials_tapers").global_coherence() (see Connectivity.global_coherence()). Examples: “magnitude_squared_coherence”, “imaginary_coherence”, “phase_locking_value”. The 2.x name "coherence_magnitude" still works through 3.x with a DeprecationWarning and keeps that variable name; it is removed in 4.0.

  • signal_names (sequence of scalar, optional) – Scalar, non-missing, unique xarray-compatible coordinate labels for signal channels. Integer labels must fit the signed 32-bit range for portable NetCDF3 serialization. Nested or structured labels are not supported. If None, uses the DataArray signal index when available, otherwise stringified indices.

  • squeeze (bool, default=False) – Only honored when a single method (a string) is requested, so the result is a DataArray. If there are exactly 2 channels, reduce a pairwise measure to the single ordered pair (first source, last target), returning a (time, frequency) array whose selected source and target are retained as scalar coordinates – so the pair (and, for directed measures, the direction) is still recorded. With more than 2 channels a warning is issued and the full matrix is returned; for power (no target axis) squeeze is a no-op. For multi-measure requests (which return a Dataset, whose variables can have incompatible axes such as power’s), squeeze is ignored with a warning.

  • connectivity_kwargs (dict, optional) – Settings for the measure (a Connectivity method), e.g. pairs for subset_pairwise_spectral_granger_prediction or n_components for canonical_coherency; passed to every requested measure, so a key a requested measure does not take raises TypeError. Transform settings do not go here (see transform_kwargs).

  • time_window_step (float, optional) – Step between successive windows in seconds, rounded to the nearest sample; defaults to the window duration (no overlap).

  • time_halfbandwidth_product (float, default=3) – DPSS time-half-bandwidth product NW; the concentration bandwidth is 2 * NW / time_window_duration Hz.

  • n_tapers (int, optional) – Number of DPSS tapers to request; defaults to floor(2 * NW) - 1. Only about 2 * NW - 1 are well concentrated: a taper whose spectral concentration is at or below 0.9 is dropped, with a warning, unless transform_kwargs={"is_low_bias": False}. The result’s mt_n_tapers and n_observations count the tapers used.

  • detrend_type ({"constant", "linear"} or None, default="constant") – Detrending applied to each window before the FFT; None for none.

  • transform_kwargs (mapping, optional) – Advanced Multitaper settings by name, e.g. {"n_fft_samples": 1024, "start_time": 0.5, "taper_weighting": "adaptive", "fft_workers": -1}. Every key must be a Multitaper setting (a misspelled one raises TypeError). The common settings above are named arguments of this function and cannot also be given here (ValueError), so each setting has one value.

  • group_labels (sequence or str, optional) – One label per signal naming the group it belongs to; labels are scalars such as integers or area names ("CA1"), and missing values (None, NaN) are rejected. Required by the group measures (canonical_coherence, canonical_coherency, maximized_imaginary_coherency, multivariate_interaction_measure, blockwise_spectral_granger_prediction and maximized_imaginary_coherency_components); an error is raised if no requested measure takes it (labels are passed only to the measures that do). It may instead be given in connectivity_kwargs, but not both. A single string, rather than a sequence, names a coordinate along the input DataArray’s signal dimension whose values are the labels, e.g. group_labels="region" for a region coordinate on channel.

  • frequency_range ((float, float), optional) – Frequency interval (low, high), both endpoints included; a bin lies on a bound when they differ by at most one part in a million of the bin’s spacing, plus rounding (see frequency_band_reduce()). delay, group_delay, and phase_slope_index receive it as their own frequency_range and consume only those bins; every other measure is computed from the full spectrum (Wilson-factorized measures factorize all of it) and then cropped to the same bins. Pass it here, not in connectivity_kwargs.

  • frequency_decimation (int, default=1) – Keep every Nth frequency bin after applying frequency_range. phase_slope_index and group_delay have no frequency axis and are left as computed over frequency_range; to make them combine fewer bins, pass connectivity_kwargs={"frequency_resolution": ...}.

  • frequency_bands (mapping of str to (float, float), optional) – Reduce the selected bins into named bands, both endpoints included, so adjacent bands sharing an endpoint both average a bin lying on it. With frequency_reduction="mean", scores are averaged, complex measures use a complex vector mean, and coherence_phase uses a circular mean. delay is frequency-resolved and is averaged like any score; phase_slope_index and group_delay are left as computed over frequency_range (call once per band, with frequency_range, for band values). Requesting frequency_bands or frequency_decimation with only those two measures raises ValueError.

  • frequency_reduction ({"mean", "integral"}, default="mean") – Band reduction. Integration is restricted to power and cross_spectral_density, where it yields band power/covariance; adjacent band integrals add up to their union without counting a shared edge bin twice (see frequency_band_reduce()). A band inside frequency_range integrates the same with and without the range, even when its edge falls between bins (given frequency_decimation=1; otherwise the kept bins start at the first bin in the range). A band reaching past the range is cut at the range’s bounds, or at the outer edge of the first or last selected bin’s cell where that lies further out.

  • time_dim (hashable, optional) – DataArray dimension containing time samples. Common names such as "time" and "sample" are inferred automatically.

  • trial_dim (hashable, optional) – DataArray dimension containing trials or epochs. Required for a 3-D DataArray when its role cannot be inferred unambiguously.

  • signal_dim (hashable, optional) – DataArray dimension containing signals or channels. Common names such as "signal" and "channel" are inferred automatically.

  • dtype (numpy.dtype, default=complex128) – Working precision for the connectivity computations.

  • minimum_phase_tolerance (float, default=1e-8) – Relative convergence tolerance of the Wilson factorization used by the directed measures.

  • minimum_phase_max_iterations (int, default=500) – Maximum Wilson iterations for the directed measures.

  • **kwargs –

    Advanced Multitaper settings given directly as keyword arguments.

    Deprecated since version 3.0: Pass them in transform_kwargs, which gives the same result; this route warns and is removed in 4.0. A setting given both ways raises ValueError, and a name that is not a Multitaper setting raises TypeError. Measure settings do not go here (see connectivity_kwargs).

Returns:

result – A plain single-quantity method returns a DataArray. Component-resolved and multi-quantity methods return a Dataset even when requested alone; multiple methods are merged into one Dataset without flattening their semantic dimensions.

Tip: method="magnitude_squared_coherence" returns a single DataArray, while the default method=None returns a Dataset of every measure in DEFAULT_METHODS: select one with result["magnitude_squared_coherence"]. Without time_window_duration the whole recording is one window, so time is a dimension of length 1: drop it for plotting with result.isel(time=0) or result.squeeze("time").

Return type:

xarray.DataArray or xarray.Dataset

Examples

>>> import numpy as np
>>> rng = np.random.default_rng(0)
>>> # Generate coupled oscillator data
>>> t = np.arange(0, 1, 1/500)  # 500 Hz, 1 second
>>> sig1 = np.sin(2*np.pi*10*t) + 0.1*rng.standard_normal(len(t))
>>> sig2 = np.sin(2*np.pi*10*t + np.pi/4) + 0.1*rng.standard_normal(len(t))
>>> # Shape (n_time, n_channels); a single trial of 2 signals. The 2-D form
>>> # is promoted to a single-trial 3-D array internally.
>>> data = np.stack([sig1, sig2], axis=-1)  # (500, 2)
>>>
>>> # Compute coherence
>>> coherence = multitaper_connectivity(
...     data, sampling_frequency=500,
...     method="magnitude_squared_coherence",
...     signal_names=["Signal_1", "Signal_2"]
... )
>>> coherence.dims
('time', 'frequency', 'source', 'target')
>>> coherence.sizes["time"]  # one window: the whole recording
1
>>> coherence.squeeze("time").dims  # e.g. for plotting against frequency
('frequency', 'source', 'target')
>>> # Compute multiple measures
>>> measures = multitaper_connectivity(
...     data, sampling_frequency=500,
...     method=["magnitude_squared_coherence", "imaginary_coherence"]
... )
>>> list(measures.data_vars)
['magnitude_squared_coherence', 'imaginary_coherence']
>>> # An xarray.DataArray labels axes by dimension name and can supply the
>>> # sampling rate and channel labels itself (no sampling_frequency needed).
>>> import xarray as xr
>>> da = xr.DataArray(
...     data,
...     dims=("time", "channel"),
...     coords={"time": t, "channel": ["Signal_1", "Signal_2"]},
... )
>>> coherence = multitaper_connectivity(da, method="magnitude_squared_coherence")
>>> coherence.coords["source"].values.tolist()
['Signal_1', 'Signal_2']

Notes

Uses multitaper spectral estimation for robust power spectral density estimation before computing connectivity measures. This provides better spectral estimates than single-taper methods, especially for short time series.

For directed measures (e.g. pairwise_spectral_granger_prediction) the source and target axes are oriented so that result.sel(source=a, target=b) is the influence from a to b, the same order as the underlying Connectivity arrays, where result[..., i, j] is i -> j. Signed undirected phase measures (coherence_phase, imaginary_coherency, phase_lag_index, weighted_phase_lag_index) are positive at sel(source=a, target=b) when a leads b.

Every measure variable has a long_name. Known units are recorded as units ("1" for dimensionless scores, "rad" for phase, "s" for delay; spectral densities are "(<units>)^2/Hz" when an input DataArray states its units, and "(<units>)^2" once integrated over a band). Power and cross-spectral density omit units when input units are unknown. Non-index coordinates on an input DataArray’s signal dimension (e.g. region) are carried as source_<name>/target_<name> with their attrs unchanged, so those attrs must be NetCDF-serializable to save the result.

Each measure variable also records how to read it, from the same record list_measures() returns: interpretation, sign_convention (measures whose sign or angle says which signal leads), value_range_lower/value_range_upper (theoretical bounds, see docs/CONNECTIVITY_METRIC_RANGES.md; an unbounded side omitted; value_range_applies_to="magnitude" for complex measures), quantity and formula (the coherency family), and diagonal_policy, what a self-connection holds (defined in docs/CONNECTIVITY_METRIC_RANGES.md); a policy with a nominal value adds diagonal_value. nan_for_zero_power_signal (0 or 1) says whether every entry involving a zero-power signal is NaN. group_delay’s other value variables, group_delay_slope and group_delay_r_value, record their own.

power has a source axis, the one it shares with the pairwise measures in a Dataset; component filters and patterns index channels along signal because they cover both sides of a connection. Use power.rename(source="signal") for a standalone channel axis.

Real-valued results write with any NetCDF engine (booleans are stored as 0/1). Complex results (coherency, cross_spectral_density, canonical_coherency, and the global-coherence vectors) need an engine that stores complex data, e.g. result.to_netcdf("result.h5", engine="h5netcdf", invalid_netcdf=True), or netCDF4 >= 1.7 with xarray >= 2024.10 and engine="netcdf4", auto_complex=True (open with the same option).

The result records provenance as NetCDF-safe attributes so a saved file is self-describing:

  • output_schema_version=1, transform, sampling_frequency, n_trials, n_signals, n_observations, and independence flags – common known facts. n_observations is the actual raw expectation count, not an effective independent sample size.

  • transform_parameters_json – remaining settings in estimator and execution records, with optional values stored as JSON null.

  • spectral_bandwidth with its definition and units – full DPSS concentration bandwidth when using generated DPSS tapers. It is distinct from frequency_bin_spacing on a uniform returned grid; cropping and decimation update spacing, and band reduction removes frequency_bin_spacing. Selecting bins afterward with xarray keeps the attribute unchanged, so recompute spacing from the frequency coordinate after such a selection.

  • The 15 scalar mt_* attributes released in 2.0.1 – deprecated compatibility copies through 3.x, removed in 4.0. The supported Multitaper.frequency_resolution property and parameter helpers retain their names and values. New transform/execution settings get no copies.

  • measure and measure_kwargs_json – the measure name as requested and a canonical, JSON-normalized representation of its keyword arguments. A result requested by the deprecated "coherence_magnitude" records that name, and its variable has that name too.

  • arg_<key> / arg_<key>_json – each measure keyword argument individually for quick inspection; a scalar is stored as-is under arg_<key>, while a structured or non-finite value is stored as a JSON string under arg_<key>_json (parse with json.loads; measure_kwargs_json is the canonical record).

  • package, package_version, backend, expectation_type – software provenance; backend is "cpu" or "gpu".

  • input_attrs_json – a canonical, JSON-normalized record of attributes carried over from an input xarray.DataArray (e.g. subject or session metadata). Keeping the complete mapping in one record preserves arbitrary keys without collisions or invalid NetCDF attribute names.

Unambiguous scalar recording coordinates (e.g. subject/session) retain their values and attrs; one named like a coordinate or variable of the result (e.g. frequency, or band when frequency_bands is given) is not carried over, with a warning. Labels along averaged trial axes are omitted.

JSON records are canonical for scalar, numpy, mapping, and sequence values. A value outside those kinds is recorded best-effort via its repr, which may embed a memory address and is therefore not guaranteed reproducible across runs.

References

[1]

Thomson, D. J. (1982). Spectrum estimation and harmonic analysis. Proceedings of the IEEE, 70(9), 1055-1096.

[2]

Percival, D. B., & Walden, A. T. (1993). Spectral Analysis for Physical Applications: Multitaper and Conventional Univariate Techniques.