bundles / scipy latest / scipy / signal / _spectral_py / stft
function
scipy.signal._spectral_py:stft
Signature
def stft ( x , fs = 1.0 , window = hann_periodic , nperseg = 256 , noverlap = None , nfft = None , detrend = False , return_onesided = True , boundary = zeros , padded = True , axis = -1 , scaling = spectrum ) Summary
Compute the Short Time Fourier Transform (legacy function).
Extended Summary
STFTs can be used as a way of quantifying the change of a nonstationary signal's frequency and phase content over time.
Parameters
x: array_likeTime series of measurement values
fs: float, optionalSampling frequency of the
xtime series. Defaults to 1.0.window: str or tuple or array_like, optionalDesired window to use. If
windowis a string or tuple, it is passed to get_window to generate the window values, which are DFT-even by default. See get_window for a list of windows and required parameters. Ifwindowis array_like it will be used directly as the window and its length must be nperseg. Defaults to a periodic Hann window.nperseg: int, optionalLength of each segment. Defaults to 256.
noverlap: int, optionalNumber of points to overlap between segments. If
None,noverlap = nperseg // 2. Defaults toNone. When specified, the COLA constraint must be met (see Notes below).nfft: int, optionalLength of the FFT used, if a zero padded FFT is desired. If
None, the FFT length isnperseg. Defaults toNone.detrend: str or function or `False`, optionalSpecifies how to detrend each segment. If
detrendis a string, it is passed as thetypeargument to thedetrendfunction. If it is a function, it takes a segment and returns a detrended segment. IfdetrendisFalse, no detrending is done. Defaults toFalse.return_onesided: bool, optionalIf
True, return a one-sided spectrum for real data. IfFalsereturn a two-sided spectrum. Defaults toTrue, but for complex data, a two-sided spectrum is always returned.boundary: str or None, optionalSpecifies whether the input signal is extended at both ends, and how to generate the new values, in order to center the first windowed segment on the first input point. This has the benefit of enabling reconstruction of the first input point when the employed window function starts at zero. Valid options are
['even', 'odd', 'constant', 'zeros', None]. Defaults to 'zeros', for zero padding extension. I.e.[1, 2, 3, 4]is extended to[0, 1, 2, 3, 4, 0]fornperseg=3.padded: bool, optionalSpecifies whether the input signal is zero-padded at the end to make the signal fit exactly into an integer number of window segments, so that all of the signal is included in the output. Defaults to
True. Padding occurs after boundary extension, ifboundaryis notNone, andpaddedisTrue, as is the default.axis: int, optionalAxis along which the STFT is computed; the default is over the last axis (i.e.
axis=-1).scaling: {'spectrum', 'psd'}The default 'spectrum' scaling allows each frequency line of Zxx to be interpreted as a magnitude spectrum. The 'psd' option scales each line to a power spectral density - it allows to calculate the signal's energy by numerically integrating over
abs(Zxx)**2.
Returns
f: ndarrayArray of sample frequencies.
t: ndarrayArray of segment times.
Zxx: ndarraySTFT of
x. By default, the last axis of Zxx corresponds to the segment times.
Notes
In order to enable inversion of an STFT via the inverse STFT in istft, the signal windowing must obey the constraint of "Nonzero OverLap Add" (NOLA), and the input signal must have complete windowing coverage (i.e. (x.shape[axis] - nperseg) % (nperseg-noverlap) == 0). The padded argument may be used to accomplish this.
Given a time-domain signal , a window , and a hop size = nperseg - noverlap, the windowed frame at time index is given by
The overlap-add (OLA) reconstruction equation is given by
The NOLA constraint ensures that every normalization term that appears in the denominator of the OLA reconstruction equation is nonzero. Whether a choice of window, nperseg, and noverlap satisfy this constraint can be tested with check_NOLA.
Array API Standard Support
stft is not in-scope for support of Python Array API Standard compatible backends other than NumPy.
See dev-arrayapi for more information.
Examples
import numpy as np from scipy import signal import matplotlib.pyplot as plt rng = np.random.default_rng()✓
fs = 10e3 N = 1e5 amp = 2 * np.sqrt(2) noise_power = 0.01 * fs / 2 time = np.arange(N) / float(fs) mod = 500*np.cos(2*np.pi*0.25*time) carrier = amp * np.sin(2*np.pi*3e3*time + mod) noise = rng.normal(scale=np.sqrt(noise_power), size=time.shape) noise *= np.exp(-time/5) x = carrier + noise✓
f, t, Zxx = signal.stft(x, fs, nperseg=1000)
✓plt.pcolormesh(t, f, np.abs(Zxx), vmin=0, vmax=amp, shading='gouraud') plt.title('STFT Magnitude') plt.ylabel('Frequency [Hz]') plt.xlabel('Time [sec]')✗
plt.show()
✓
E_x = sum(x**2) / fs # Energy of x f, t, Zxx = signal.stft(x, fs, nperseg=1000, return_onesided=False, scaling='psd') df, dt = f[1] - f[0], t[1] - t[0] E_Zxx = sum(np.sum(Zxx.real**2 + Zxx.imag**2, axis=0) * df) * dt✓
np.isclose(E_x, E_Zxx, rtol=1e-2)
✗See also
- ShortTimeFFT
Newer STFT/ISTFT implementation providing more features.
- check_COLA
Check whether the Constant OverLap Add (COLA) constraint is met
- check_NOLA
Check whether the Nonzero Overlap Add (NOLA) constraint is met
- csd
Cross spectral density by Welch's method.
- istft
Inverse Short Time Fourier Transform
- lombscargle
Lomb-Scargle periodogram for unevenly sampled data
- spectrogram
Spectrogram by Welch's method.
- welch
Power spectral density by Welch's method.
Aliases
-
scipy.signal.stft