spectral_connectivity.transforms.ShortTimeFourierTransform#

class ShortTimeFourierTransform(time_series: NDArray[floating], sampling_frequency: float, *, detrend_type: str | None = 'constant', time_window_duration: float | None = None, time_window_step: float | None = None, start_time: float = 0, n_fft_samples: int | None = None, n_time_samples_per_window: int | None = None, n_time_samples_per_step: int | None = None, fft_workers: int | None = None)[source]#

Bases: object

Short-time Fourier transform using an L2-normalized Hann window.

The returned coefficients follow the same five-dimensional contract as Multitaper, with a singleton taper axis. This makes the transform directly usable with Connectivity.from_transform() and spectral_connectivity.wrapper.connectivity_to_xarray().

Parameters:
  • time_series (ndarray, shape (n_time_samples, n_trials, n_signals)) – Real-valued input signals (a complex series raises TypeError). Use prepare_time_series() for 1-D/2-D input. An xarray.DataArray is read by position; one whose dimension names put time, trials, or signals on another axis raises ValueError.

  • sampling_frequency (float) – Samples per second; required because it labels the frequency axis and scales power.

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

  • time_window_duration (float, optional) – Window length in seconds. Give this or n_time_samples_per_window.

  • time_window_step (float, optional) – Step between successive windows in seconds (defaults to the window duration, i.e. no overlap).

  • start_time (float, default=0) – Time of the first sample, in seconds (scalar only).

  • n_fft_samples (int, optional) – FFT length. Defaults to scipy.fft.next_fast_len of the window length, which may zero-pad (e.g. a 257-sample window gives 264 bins); pass the window length explicitly for an unpadded frequency grid. The directed measures (spectral Granger, DTF, PDC) depend slightly on this length: see the Notes of minimum_phase_decomposition().

  • n_time_samples_per_window (int, optional) – Window length in samples (alternative to time_window_duration).

  • n_time_samples_per_step (int, optional) – Step between windows in samples (alternative to time_window_step).

  • fft_workers (int, optional) – Worker threads for SciPy’s CPU FFT (-1 uses all cores).

Attributes:
detrend_type

Detrending applied to each window before the FFT.

equivalent_noise_bandwidth

Return periodic Hann equivalent noise bandwidth in Hz.

fft_workers

Worker threads for SciPy’s CPU FFT (None uses SciPy’s default).

frequencies

Frequency of each FFT bin in Hz, in standard FFT order.

n_fft_samples

FFT length of each window, which is also the number of frequency bins.

n_signals

Number of signals in the time series.

n_time_samples_per_step

Step between window starts, in samples.

n_time_samples_per_window

Window length in samples.

n_trials

Number of trials in the time series.

nyquist_frequency

Maximum resolvable frequency, in Hz.

observations_are_independent

Whether the trial observations may be counted as independent.

sampling_frequency

Samples per second, in Hz.

start_time

Time of the first sample, in seconds.

time

Center time of each window, in seconds.

time_bins_are_independent

Whether the time windows may be counted as independent observations.

time_series

Independent read-only copy of the input time-series snapshot.

time_window_duration

Window length in seconds, after rounding to whole samples.

time_window_step

Step between window starts in seconds, after rounding to whole samples.

Methods

fft()

Compute the tapered Fourier coefficients of every time window.

summarize_parameters()

Human-readable summary of the STFT's settings.

Methods

fft

Compute the tapered Fourier coefficients of every time window.

summarize_parameters

Human-readable summary of the STFT's settings.

Attributes

detrend_type

Detrending applied to each window before the FFT.

equivalent_noise_bandwidth

Return periodic Hann equivalent noise bandwidth in Hz.

fft_workers

Worker threads for SciPy's CPU FFT (None uses SciPy's default).

frequencies

Frequency of each FFT bin in Hz, in standard FFT order.

is_one_sided

The transform returns the full two-sided FFT spectrum (both positive and negative frequencies), so consumers must not assume a one-sided layout.

n_fft_samples

FFT length of each window, which is also the number of frequency bins.

n_signals

Number of signals in the time series.

n_time_samples_per_step

Step between window starts, in samples.

n_time_samples_per_window

Window length in samples.

n_trials

Number of trials in the time series.

nyquist_frequency

Maximum resolvable frequency, in Hz.

observations_are_independent

Whether the trial observations may be counted as independent.

sampling_frequency

Samples per second, in Hz.

start_time

Time of the first sample, in seconds.

time

Center time of each window, in seconds.

time_bins_are_independent

Whether the time windows may be counted as independent observations.

time_series

Independent read-only copy of the input time-series snapshot.

time_window_duration

Window length in seconds, after rounding to whole samples.

time_window_step

Step between window starts in seconds, after rounding to whole samples.

property detrend_type: str | None#

Detrending applied to each window before the FFT.

property equivalent_noise_bandwidth: float#

Return periodic Hann equivalent noise bandwidth in Hz.

The resolved window determines the bandwidth independently of FFT zero-padding and frequency-grid spacing.

Returns:

Equivalent noise bandwidth of the resolved window, in Hz.

Return type:

float

See also

Welch.equivalent_noise_bandwidth

Equivalent noise bandwidth of Welch segments.

Notes

sampling_frequency * sum(window**2) / sum(window)**2 equals 1.5 / time_window_duration for windows of at least three samples. The two-sample Hann window has bandwidth sampling_frequency.

Examples

>>> stft = ShortTimeFourierTransform(
...     np.zeros((100, 1, 1)), 100, time_window_duration=0.5
... )
>>> round(stft.equivalent_noise_bandwidth, 6)
3.0
fft() → NDArray[complexfloating]#

Compute the tapered Fourier coefficients of every time window.

Each window is detrended as detrend_type sets, multiplied by each taper, and transformed with an FFT of length n_fft_samples. A transform with a taper_weighting other than "uniform" then rescales each taper’s coefficients by its weight.

Returns:

fourier_coefficients – Shape (n_time_windows, n_trials, n_tapers, n_fft_samples, n_signals). Complex-valued Fourier coefficients, with one entry per taper on the taper axis; a transform with a single window function, such as a Hann window, has a singleton taper axis (n_tapers is 1).

Return type:

array

property fft_workers: int | None#

Worker threads for SciPy’s CPU FFT (None uses SciPy’s default).

property frequencies: NDArray[floating]#

Frequency of each FFT bin in Hz, in standard FFT order.

These label the coefficients of fft(), negative frequencies included, not the results computed from them. To label the frequency axis of a power or connectivity result, use Connectivity.frequencies: the n_fft_samples // 2 + 1 non-negative bins, 0 Hz up to Nyquist.

Returns:

Frequency values in Hz corresponding to FFT bins, as numpy.fft.fftfreq orders them (non-negative frequencies first, then negative; for an even n_fft_samples the Nyquist bin is listed as negative).

Return type:

NDArray[float64], shape (n_fft_samples,)

Examples

>>> import numpy as np
>>> from spectral_connectivity import Connectivity, Multitaper
>>> rng = np.random.default_rng(0)
>>> multitaper = Multitaper(rng.standard_normal((100, 2, 2)), sampling_frequency=100)
>>> multitaper.frequencies.shape, multitaper.frequencies[[0, 1, 50, -1]].tolist()
((100,), [0.0, 1.0, -50.0, -1.0])
>>> connectivity = Connectivity.from_transform(multitaper)
>>> connectivity.frequencies.shape, connectivity.frequencies[[0, -1]].tolist()
((51,), [0.0, 50.0])
>>> connectivity.power(one_sided=True).shape  # (time, frequency, signal)
(1, 51, 2)
is_one_sided = False#

The transform returns the full two-sided FFT spectrum (both positive and negative frequencies), so consumers must not assume a one-sided layout.

property n_fft_samples: int#

FFT length of each window, which is also the number of frequency bins.

An explicit n_fft_samples is used as given. Otherwise it is a length at least n_time_samples_per_window that is fast for the FFT (scipy.fft.next_fast_len), so windows may be zero-padded.

Returns:

Number of FFT samples.

Return type:

int

Raises:

ValueError – If the requested n_fft_samples is smaller than n_time_samples_per_window.

property n_signals: int#

Number of signals in the time series.

Returns:

Number of signals in the time series.

Return type:

int

property n_time_samples_per_step: int#

Step between window starts, in samples.

An explicit n_time_samples_per_step is used as given. Otherwise, if time_window_step is set, the step is the nearest whole number of samples in that duration. If neither is set, the step defaults to the window length (non-overlapping windows).

Returns:

Number of samples to advance between windows.

Return type:

int

Raises:

ValueError – If the resolved step is shorter than one sample.

property n_time_samples_per_window: int#

Window length in samples.

An explicit n_time_samples_per_window is used as given. Otherwise, if time_window_duration is set, the window is the nearest whole number of samples in that duration. If neither is set, the window is the whole time series.

Returns:

Number of time samples in each window.

Return type:

int

Raises:

ValueError – If the resolved window is shorter than the transform’s tapers allow or longer than the time series.

property n_trials: int#

Number of trials in the time series.

Returns:

Number of trials in the time series.

Return type:

int

property nyquist_frequency: float#

Maximum resolvable frequency, in Hz.

Returns:

Nyquist frequency in Hz, sampling_frequency / 2.

Return type:

float

property observations_are_independent: bool#

Whether the trial observations may be counted as independent.

Each window has one Hann-windowed estimate per trial, and trials are independent realizations, so this is always True. Correlation between overlapping windows, which matters only for expectations that also average over time, is reported by time_bins_are_independent.

Return type:

bool

property sampling_frequency: float#

Samples per second, in Hz.

property start_time: Any#

Time of the first sample, in seconds.

Returns an independent read-only copy of the start-time coordinate.

summarize_parameters() → str[source]#

Human-readable summary of the STFT’s settings.

Returns:

summary – Data shape, the Hann window, time windowing, and the window’s equivalent noise bandwidth, Nyquist frequency, and FFT length.

Return type:

str

Examples

>>> import numpy as np
>>> from spectral_connectivity.transforms import ShortTimeFourierTransform
>>> stft = ShortTimeFourierTransform(
...     np.zeros((1000, 1, 2)), sampling_frequency=100, time_window_duration=0.5
... )
>>> print(stft.summarize_parameters().splitlines()[0])
Short-Time Fourier Transform Configuration
property time: NDArray[floating]#

Center time of each window, in seconds.

Returns:

Time values in seconds for center of each time window, offset by start_time.

Return type:

NDArray[float64], shape (n_time_windows,)

property time_bins_are_independent: bool#

Whether the time windows may be counted as independent observations.

An expectation that averages over time ("time", "time_tapers", …) counts every window in n_observations. Windows that share samples are correlated, so beyond some overlap that count overstates the effective sample size and biases the measures that rely on it (pairwise phase consistency of independent signals, for example, is no longer centered on 0). Like Welch, which treats segments overlapping by at most 50% as approximately independent (Welch 1967; Percival & Walden 1993, sec. 6.17), windows count as independent when n_time_samples_per_step is at least half of n_time_samples_per_window. Connectivity warns when an expectation averages over correlated time bins.

Returns:

True when successive windows overlap by at most half.

Return type:

bool

property time_series: Any#

Independent read-only copy of the input time-series snapshot.

property time_window_duration: float#

Window length in seconds, after rounding to whole samples.

Returns:

Duration in seconds of each time window actually analyzed, n_time_samples_per_window / sampling_frequency (a requested duration is rounded to the nearest sample).

Return type:

float

property time_window_step: float#

Step between window starts in seconds, after rounding to whole samples.

Returns:

Step size in seconds between consecutive time windows actually taken, n_time_samples_per_step / sampling_frequency (a requested step is rounded to the nearest sample).

Return type:

float