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_predictionandsubset_pairwise_spectral_granger_prediction,sel(source=a, target=b)isa -> b; 2.x returnedb -> a. The 2.x wrapper rejected the transfer-function measures and could not returnphase_slope_index,group_delay, ordelay, whoseConnectivityarrays 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 trialk. 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, passnp.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; usetime_dim,trial_dim, andsignal_dimfor 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 asfrequencyorbandis rejected instead, since it marks an already-transformed input). A dask-backed DataArray is rejected (materialize it first withDataArray.compute()). A numeric time index is interpreted as elapsed seconds (asampleindex as sample numbers) and used to label output window centers. Whensampling_frequencyis given it is validated against the index; when it is omitted, an elapsed-secondstimecoordinate infers it (asampleindex 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. Whensignal_namesis omitted, labels from a 1-D index coordinate on the signal dimension are carried to the output’ssourceandtargetcoordinates 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
timecoordinate. 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 whoseunitsattribute says milliseconds, warns that the coordinate may be in milliseconds (read as seconds, it gives a rate 1000 times too low); passing the rate, orunits="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 itsunitsattribute says milliseconds: setunitsor 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.coherencyis 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, includingpairwise_spectral_granger_predictionand 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, includingglobal_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, useConnectivity.from_transform(transform, expectation_type="time_trials_tapers").global_coherence()(seeConnectivity.global_coherence()). Examples: “magnitude_squared_coherence”, “imaginary_coherence”, “phase_locking_value”. The 2.x name"coherence_magnitude"still works through 3.x with aDeprecationWarningand 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 selectedsourceandtargetare 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; forpower(no target axis) squeeze is a no-op. For multi-measure requests (which return a Dataset, whose variables can have incompatible axes such aspower’s), squeeze is ignored with a warning.connectivity_kwargs (dict, optional) – Settings for the measure (a
Connectivitymethod), e.g.pairsforsubset_pairwise_spectral_granger_predictionorn_componentsforcanonical_coherency; passed to every requested measure, so a key a requested measure does not take raisesTypeError. Transform settings do not go here (seetransform_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 is2 * NW / time_window_durationHz.n_tapers (int, optional) – Number of DPSS tapers to request; defaults to
floor(2 * NW) - 1. Only about2 * NW - 1are well concentrated: a taper whose spectral concentration is at or below 0.9 is dropped, with a warning, unlesstransform_kwargs={"is_low_bias": False}. The result’smt_n_tapersandn_observationscount the tapers used.detrend_type ({"constant", "linear"} or None, default="constant") – Detrending applied to each window before the FFT;
Nonefor none.transform_kwargs (mapping, optional) – Advanced
Multitapersettings by name, e.g.{"n_fft_samples": 1024, "start_time": 0.5, "taper_weighting": "adaptive", "fft_workers": -1}. Every key must be aMultitapersetting (a misspelled one raisesTypeError). 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_predictionandmaximized_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 inconnectivity_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 aregioncoordinate onchannel.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 (seefrequency_band_reduce()).delay,group_delay, andphase_slope_indexreceive it as their ownfrequency_rangeand 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 inconnectivity_kwargs.frequency_decimation (int, default=1) – Keep every Nth frequency bin after applying
frequency_range.phase_slope_indexandgroup_delayhave no frequency axis and are left as computed overfrequency_range; to make them combine fewer bins, passconnectivity_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, andcoherence_phaseuses a circular mean.delayis frequency-resolved and is averaged like any score;phase_slope_indexandgroup_delayare left as computed overfrequency_range(call once per band, withfrequency_range, for band values). Requestingfrequency_bandsorfrequency_decimationwith only those two measures raisesValueError.frequency_reduction ({"mean", "integral"}, default="mean") – Band reduction. Integration is restricted to
powerandcross_spectral_density, where it yields band power/covariance; adjacent band integrals add up to their union without counting a shared edge bin twice (seefrequency_band_reduce()). A band insidefrequency_rangeintegrates the same with and without the range, even when its edge falls between bins (givenfrequency_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
Multitapersettings 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 raisesValueError, and a name that is not aMultitapersetting raisesTypeError. Measure settings do not go here (seeconnectivity_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 defaultmethod=Nonereturns a Dataset of every measure inDEFAULT_METHODS: select one withresult["magnitude_squared_coherence"]. Withouttime_window_durationthe whole recording is one window, sotimeis a dimension of length 1: drop it for plotting withresult.isel(time=0)orresult.squeeze("time").- Return type:
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) thesourceandtargetaxes are oriented so thatresult.sel(source=a, target=b)is the influence fromatob, the same order as the underlyingConnectivityarrays, whereresult[..., i, j]isi -> j. Signed undirected phase measures (coherence_phase,imaginary_coherency,phase_lag_index,weighted_phase_lag_index) are positive atsel(source=a, target=b)whenaleadsb.Every measure variable has a
long_name. Known units are recorded asunits("1"for dimensionless scores,"rad"for phase,"s"for delay; spectral densities are"(<units>)^2/Hz"when an input DataArray states itsunits, and"(<units>)^2"once integrated over a band). Power and cross-spectral density omitunitswhen input units are unknown. Non-index coordinates on an input DataArray’s signal dimension (e.g.region) are carried assource_<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, seedocs/CONNECTIVITY_METRIC_RANGES.md; an unbounded side omitted;value_range_applies_to="magnitude"for complex measures),quantityandformula(the coherency family), anddiagonal_policy, what a self-connection holds (defined indocs/CONNECTIVITY_METRIC_RANGES.md); a policy with a nominal value addsdiagonal_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_slopeandgroup_delay_r_value, record their own.powerhas asourceaxis, the one it shares with the pairwise measures in a Dataset; component filters and patterns index channels alongsignalbecause they cover both sides of a connection. Usepower.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 andengine="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_observationsis the actual raw expectation count, not an effective independent sample size.transform_parameters_json– remaining settings inestimatorandexecutionrecords, with optional values stored as JSONnull.spectral_bandwidthwith its definition and units – full DPSS concentration bandwidth when using generated DPSS tapers. It is distinct fromfrequency_bin_spacingon a uniform returned grid; cropping and decimation update spacing, and band reduction removesfrequency_bin_spacing. Selecting bins afterward with xarray keeps the attribute unchanged, so recompute spacing from thefrequencycoordinate 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 supportedMultitaper.frequency_resolutionproperty and parameter helpers retain their names and values. New transform/execution settings get no copies.measureandmeasure_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 underarg_<key>, while a structured or non-finite value is stored as a JSON string underarg_<key>_json(parse withjson.loads;measure_kwargs_jsonis the canonical record).package,package_version,backend,expectation_type– software provenance;backendis"cpu"or"gpu".input_attrs_json– a canonical, JSON-normalized record of attributes carried over from an inputxarray.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, orbandwhenfrequency_bandsis 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.