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:
objectShort-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 withConnectivity.from_transform()andspectral_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). Useprepare_time_series()for 1-D/2-D input. Anxarray.DataArrayis read by position; one whose dimension names put time, trials, or signals on another axis raisesValueError.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_lenof 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 ofminimum_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 (
-1uses all cores).
- Attributes:
detrend_typeDetrending applied to each window before the FFT.
equivalent_noise_bandwidthReturn periodic Hann equivalent noise bandwidth in Hz.
fft_workersWorker threads for SciPy’s CPU FFT (
Noneuses SciPy’s default).frequenciesFrequency of each FFT bin in Hz, in standard FFT order.
n_fft_samplesFFT length of each window, which is also the number of frequency bins.
n_signalsNumber of signals in the time series.
n_time_samples_per_stepStep between window starts, in samples.
n_time_samples_per_windowWindow length in samples.
n_trialsNumber of trials in the time series.
nyquist_frequencyMaximum resolvable frequency, in Hz.
observations_are_independentWhether the trial observations may be counted as independent.
sampling_frequencySamples per second, in Hz.
start_timeTime of the first sample, in seconds.
timeCenter time of each window, in seconds.
time_bins_are_independentWhether the time windows may be counted as independent observations.
time_seriesIndependent read-only copy of the input time-series snapshot.
time_window_durationWindow length in seconds, after rounding to whole samples.
time_window_stepStep between window starts in seconds, after rounding to whole samples.
Methods
fft()Compute the tapered Fourier coefficients of every time window.
Human-readable summary of the STFT's settings.
Methods
Compute the tapered Fourier coefficients of every time window.
Human-readable summary of the STFT's settings.
Attributes
Detrending applied to each window before the FFT.
Return periodic Hann equivalent noise bandwidth in Hz.
Worker threads for SciPy's CPU FFT (
Noneuses SciPy's default).Frequency of each FFT bin in Hz, in standard FFT order.
The transform returns the full two-sided FFT spectrum (both positive and negative frequencies), so consumers must not assume a one-sided layout.
FFT length of each window, which is also the number of frequency bins.
Number of signals in the time series.
Step between window starts, in samples.
Window length in samples.
Number of trials in the time series.
Maximum resolvable frequency, in Hz.
Whether the trial observations may be counted as independent.
Samples per second, in Hz.
Time of the first sample, in seconds.
Center time of each window, in seconds.
Whether the time windows may be counted as independent observations.
Independent read-only copy of the input time-series snapshot.
Window length in seconds, after rounding to whole samples.
Step between window starts in seconds, after rounding to whole samples.
- 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:
See also
Welch.equivalent_noise_bandwidthEquivalent noise bandwidth of Welch segments.
Notes
sampling_frequency * sum(window**2) / sum(window)**2equals1.5 / time_window_durationfor windows of at least three samples. The two-sample Hann window has bandwidthsampling_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_typesets, multiplied by each taper, and transformed with an FFT of lengthn_fft_samples. A transform with ataper_weightingother 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_tapersis 1).- Return type:
array
- 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, useConnectivity.frequencies: then_fft_samples // 2 + 1non-negative bins, 0 Hz up to Nyquist.- Returns:
Frequency values in Hz corresponding to FFT bins, as
numpy.fft.fftfreqorders them (non-negative frequencies first, then negative; for an evenn_fft_samplesthe 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_samplesis used as given. Otherwise it is a length at leastn_time_samples_per_windowthat is fast for the FFT (scipy.fft.next_fast_len), so windows may be zero-padded.- Returns:
Number of FFT samples.
- Return type:
- Raises:
ValueError – If the requested
n_fft_samplesis smaller thann_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:
- 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:
- 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_windowis used as given. Otherwise, iftime_window_durationis 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:
- 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:
- property nyquist_frequency: float#
Maximum resolvable frequency, in Hz.
- Returns:
Nyquist frequency in Hz,
sampling_frequency / 2.- Return type:
- 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 bytime_bins_are_independent.- Return type:
- 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:
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 inn_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). LikeWelch, which treats segments overlapping by at most 50% as approximately independent (Welch 1967; Percival & Walden 1993, sec. 6.17), windows count as independent whenn_time_samples_per_stepis at least half ofn_time_samples_per_window.Connectivitywarns when an expectation averages over correlated time bins.- Returns:
Truewhen successive windows overlap by at most half.- Return type:
- 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: