AI Wiki中文/EN

STFT: windows, coverage and reconstructing a signal

短时傅里叶变换

Separate window length, hop and FFT length; reconstruct a complex STFT and expose missing coverage and phase.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Two tones are present—but which came first?

Synthesize a short signal with a 500 Hz cosine in its first half and a 2 kHz cosine in its second. One Fourier transform of the full record describes frequency composition, but a global magnitude spectrum does not directly reveal when each sound occurred. The short-time Fourier transform (STFT) slides an analysis window through time and analyzes each local segment. STFT definition and parameters

Windows are not necessarily disjoint boxes. Adjacent windows usually overlap, and smooth sample weights reduce abrupt segment-edge effects while also broadening spectral main peaks. Short windows locate rapid changes more closely; long windows observe more time and can help distinguish nearby frequencies. No single window suits every transient and sustained tone.

We retain a complex STFT to reconstruct the signal, then deliberately lose coverage or phase to expose failure. Finally, we pad a 32-sample window to a 128-point FFT: the spectrum becomes denser without recording any more time.

The complex STFT retains local frequency and phase; its inverse needs nonzero window coverage. Padding makes frequency samples denser while preserving the original FFT bins and observation duration.
The complex STFT retains local frequency and phase; its inverse needs nonzero window coverage. Padding makes frequency samples denser while preserving the original FFT bins and observation duration.

Window length, hop and FFT length have different jobs

Suppose the record has NN real samples at rate fsf_s. The window length is LL, successive windows start HH samples apart, and the FFT length is NFFT≥LN_{\mathrm{FFT}}\ge L. We use an even-length periodic Hann window:

w[j]=12−12cos⁡ ⁣(2πjL),j=0,…,L−1.w[j]=\frac12-\frac12\cos\!\left(\frac{2\pi j}{L}\right),\qquad j=0,\ldots,L-1.

“Periodic” means the denominator is LL, not the L−1L-1 of the symmetric Hann definition. Write the boundary-padded signal as xpx_p. Frame mm begins at mHmH, with no extra forward-FFT normalization:

Xm[k]=∑j=0L−1xp[mH+j]w[j]e−i2πkj/NFFT,k=0,…,NFFT/2.X_m[k]=\sum_{j=0}^{L-1}x_p[mH+j]w[j]e^{-i2\pi kj/N_{\mathrm{FFT}}},\quad k=0,\ldots,N_{\mathrm{FFT}}/2.

Conjugate symmetry recovers the negative frequencies of real signals, so we retain only nonnegative frequencies. Each complex value has magnitude and phase; magnitude or power plots display only part of the STFT. With PP samples padded on the left, midpoint time labels and frequency bins are:

tm=mH+L/2−Pfs,fk=kfsNFFT,Δf=fsNFFT.t_m=\frac{mH+L/2-P}{f_s},\qquad f_k=\frac{k f_s}{N_{\mathrm{FFT}}},\qquad \Delta f=\frac{f_s}{N_{\mathrm{FFT}}}.

At 8 kHz, L=32L=32 and H=8H=8 give 4 ms windows every 1 ms. A small hop does not supply independent 1 ms observations: overlapping windows share data. Edge windows also include artificial padding, making the time-label convention part of the specification.

Inverse FFT of a frame, cropped to its first LL samples, gives ym[j]=xp[mH+j]w[j]y_m[j]=x_p[mH+j]w[j]. Multiplying by the window again and adding frames accumulates each original sample times squared window weights. Divide by their corresponding sum:

x^p[n]=∑mym[n−mH]w[n−mH]D[n],D[n]=∑mw[n−mH]2>0.\hat x_p[n]=\frac{\sum_m y_m[n-mH]w[n-mH]}{D[n]},\qquad D[n]=\sum_m w[n-mH]^2>0.

Treat ww as zero outside its support. This is weighted overlap-add (OLA). Nonzero overlap-add (NOLA) requires a nonzero denominator at relevant positions, together with complete record coverage. The denominator need not be constant because the program divides pointwise. The Notes in the SciPy documentation give this denominator and the coverage conditions. Reconstruction and NOLA

Without padding, a first frame beginning at original sample 0 has Hann weight w[0]=0w[0]=0. The first input sample may never receive any nonzero weight. A longer FFT cannot fix this. Check padding and hop jointly on the actual finite record rather than declaring invertibility from the window’s name.

For an even FFT length, Parseval’s relation for an unnormalized one-sided complex spectrum is:

∑j∣ym[j]∣2=∣Xm[0]∣2+∣Xm[NFFT/2]∣2+2∑k=1NFFT/2−1∣Xm[k]∣2NFFT.\sum_j|y_m[j]|^2=\frac{|X_m[0]|^2+|X_m[N_{\mathrm{FFT}}/2]|^2+2\sum_{k=1}^{N_{\mathrm{FFT}}/2-1}|X_m[k]|^2}{N_{\mathrm{FFT}}}.

Interior bins receive factor 2 because each represents a positive/negative frequency pair. DC and Nyquist count once. This is the energy of one windowed frame; adding energies across overlapping frames does not directly produce the original record’s energy.

Zero padding has a separate direct check. Pad the same LL-sample windowed segment to 4L4L points, and the original FFT values occur at every fourth new bin:

X4L[4k]=XL[k],ΔfL=fs/L,Δf4L=fs/(4L).X_{4L}[4k]=X_L[k],\qquad \Delta f_L=f_s/L,\quad \Delta f_{4L}=f_s/(4L).

This samples the spectrum of the same finite window more densely, helping peak inspection and interpolation. It adds no independent samples or observation time. Julius O. Smith’s textbook explains padding through spectral interpolation; smaller grid spacing is not the same as increased ability to distinguish nearby components. Zero padding and interpolation

Reconstruction should expose missing information

The complete Python 3.12/NumPy 1.26.4 program accepts at most 1,024 samples, an even window length from 4 to 128 and an even FFT length no greater than 512. It does not detrend. Default padding adds L/2L/2 samples on the left, then LL on the right plus enough to complete the hop grid. Output rows are frames; columns are nonnegative frequency bins.

"""Finite one-sided STFT and explicit weighted overlap-add reconstruction.

Raw unnormalized FFT, periodic Hann, even frame/FFT lengths, no detrending.
"""
import json
import numpy as np


def analyze(values,frame=32,hop=8,nfft=None,pad=True):
    x=np.asarray(values)
    if np.iscomplexobj(x):raise ValueError('Real signal required')
    x=np.asarray(x,dtype=float);nfft=frame if nfft is None else nfft
    if x.ndim!=1 or not 1<=len(x)<=1024 or not np.isfinite(x).all():raise ValueError('Use 1–1024 finite samples')
    if type(frame) is not int or not 4<=frame<=128 or frame%2 or type(hop) is not int or not 1<=hop<=frame or type(nfft) is not int or not frame<=nfft<=512 or nfft%2 or type(pad) is not bool:raise ValueError('Invalid frame, hop, FFT or padding')
    if not pad and len(x)<frame:raise ValueError('Unpadded signal needs a complete frame')
    left=frame//2 if pad else 0;work=np.pad(x,(left,frame if pad else 0))
    if pad:work=np.pad(work,(0,(-(len(work)-frame))%hop))
    window=.5-.5*np.cos(2*np.pi*np.arange(frame)/frame);starts=np.arange(0,len(work)-frame+1,hop)
    frames=np.array([work[i:i+frame]*window for i in starts]);spectrum=np.fft.rfft(frames,n=nfft,axis=1)
    return dict(spectrum=spectrum,window=window,starts=starts,left=left,length=len(x),work_length=len(work),nfft=nfft,hop=hop)


def reconstruct(state):
    z=state['spectrum'];w=state['window'];frames=np.fft.irfft(z,n=state['nfft'],axis=1)[:,:len(w)]
    numerator=np.zeros(state['work_length']);denominator=numerator.copy()
    for start,frame in zip(state['starts'],frames):
        numerator[start:start+len(w)]+=frame*w;denominator[start:start+len(w)]+=w*w
    sl=slice(state['left'],state['left']+state['length']);den=denominator[sl];num=numerator[sl];covered=den>1e-12
    values=np.divide(num,den,out=np.zeros_like(num),where=covered)
    return dict(values=values,denominator=den,covered=covered,exactly_invertible=bool(covered.all()))


def frame_energy(spectrum,nfft):
    power=abs(spectrum)**2;weights=np.full(power.shape[-1],2.);weights[0]=weights[-1]=1
    return np.sum(power*weights,axis=-1)/nfft


def demo():
    rate=8000;n=128;t=np.arange(n)/rate;x=.7*np.cos(2*np.pi*np.where(np.arange(n)<64,500,2000)*t)+.1
    state=analyze(x);back=reconstruct(state);raw=analyze(x,pad=False);lost=reconstruct(raw)
    n0=32;segment=np.cos(2*np.pi*750*np.arange(n0)/rate)*(.5-.5*np.cos(2*np.pi*np.arange(n0)/n0));short=np.fft.rfft(segment);dense=np.fft.rfft(segment,n=128)
    return dict(rate=rate,samples=x.tolist(),starts=state['starts'].tolist(),centers=((state['starts']+16-state['left'])/rate).tolist(),
                frequencies=np.fft.rfftfreq(32,1/rate).tolist(),magnitude=abs(state['spectrum']).tolist(),
                max_reconstruction_error=float(np.max(abs(back['values']-x))),denominator=back['denominator'].tolist(),
                unpadded_missing=np.flatnonzero(~lost['covered']).tolist(),unpadded_first_input=float(x[0]),
                frame_energies=frame_energy(state['spectrum'],32).tolist(),
                zero_padding=dict(short_magnitude=abs(short).tolist(),dense_magnitude=abs(dense).tolist(),
                                  old_bins_error=float(np.max(abs(short-dense[::4]))),short_spacing_hz=250.,dense_spacing_hz=62.5,window_samples=32))


if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))

The synthetic 128-sample signal switches from 500 Hz in its first 64 samples to 2 kHz in its last 64, with cosine amplitude 0.7 and DC offset 0.1. Default complex-spectrum reconstruction has maximum absolute error about 2.22×10−162.22\times10^{-16}. Without padding, the first input value 0.8 lacks coverage and receives covered=False. Filling that output position with 0 is a convention, not successful recovery.

reconstruct consumes internal state returned by analyze; frame_energy likewise assumes the even-FFT contract. They are not general validators for arbitrary external objects. Numerical coverage requires a denominator above 10−1210^{-12}. A very small denominator can amplify error even when mathematically nonzero.

A separate 32-sample segment padded to 128 points changes frequency spacing from 250 Hz to 62.5 Hz while observing only 4 ms. dense[::4] agrees with the original complex spectrum, not merely its magnitude. Multiplying [1,2,3,4] by [0,0.5,1,0.5] gives [0,1,3,2]; both the time-domain and one-sided spectral calculations give energy 14.

For MM frames, FFT computation takes O(MNFFTlog⁡NFFT)O(MN_{\mathrm{FFT}}\log N_{\mathrm{FFT}}), windowing and OLA take O(ML)O(ML), complex spectra occupy O(MNFFT)O(MN_{\mathrm{FFT}}), and reconstruction buffers occupy O(N+L)O(N+L). Zero padding and denser frame placement have real computational costs.

Displaying a spectrum does not recover a sound

The complex STFTs of xx and −x-x are negatives of one another, but their magnitudes agree. Invertibility of the complete complex STFT with valid coverage therefore does not imply that a magnitude spectrogram uniquely determines a waveform. Arbitrarily editing time-frequency cells may also create a matrix inconsistent with any exact STFT. We reconstruct only an unmodified complex spectrum and do not estimate phase.

Choose window length with event duration and frequency separation in mind; choose hop with temporal sampling density, coverage and cost in mind. Speech models may further apply logarithms or Mel pooling. OLA cannot restore information discarded by those operations. The cited SciPy 1.15.3 stft documentation marks that interface as legacy and points to a newer interface. This article examines the mathematical conditions rather than recommending the older API as a new project’s default. Interface status and conditions

Make each parameter’s role testable

  1. Understanding. At 8 kHz, what durations correspond to a 32-sample window and an 8-sample hop? Does a 1 ms hop mean each frame contains only 1 ms of data?

    Answer: The window lasts 4 ms and the hop 1 ms. Each frame still uses 4 ms of data, with substantial overlap between neighbors.

  2. Calculation. Apply the periodic Hann window [0,0.5,1,0.5] to [1,2,3,4]. What is the resulting energy, and why not simply add one-sided squared magnitudes?

    Answer: The windowed segment [0,1,3,2] has energy 14. An unnormalized FFT requires division by its length, and interior one-sided bins must be doubled, unlike DC and Nyquist.

  3. Counterexample. Without padding, the first input 0.8 receives only window weight 0. Can increasing the FFT from 32 to 128 recover it?

    Answer: No. Window multiplication has already erased that value. Padding adds spectral samples without changing the coverage denominator. Window placement, boundaries or coverage must change.

  4. Method choice. Two nearby frequencies are difficult to distinguish with a 32-sample window. Should a zero-padded 128-point FFT be called “four times the resolution”?

    Answer: No. Grid spacing decreases by four, but observation time remains 4 ms. Padding helps read peak shapes; gaining more distinguishing information requires considering a longer observation window and its temporal-localization cost.

Normalization is part of the method

The prerequisite is the Fourier transform. The pinned SciPy documentation supports window, hop, boundary and OLA/NOLA definitions. The padding textbook supports the interpolation explanation. This program independently implements raw FFTs and actual denominators; its outputs were not matched to library scaling conventions. Reconstruction, energy and padding results belong to this example, not a library-compatibility or phase-recovery evaluation.

Make a prediction, then check

Does padding a 32-sample frame to a 128-point FFT fix a missing first sample?

Choose one answer

Learning objectives

  • Define frame times and bins under explicit padding.
  • Derive the squared-window OLA denominator.
  • Check one-sided Parseval energy and finite coverage.
  • Distinguish denser FFT bins from more observation information.

Prerequisites & connections

Explore related knowledge →

References

  1. SciPy 1.15.3: scipy.signal.stft
    SciPy contributors · 2025
  2. Spectral Audio Signal Processing: Zero Padding in the Time Domain
    Julius O. Smith III

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-13 · Single AI author checked periodic Hann definition, frame/time/frequency axes, raw one-sided FFT, weighted OLA squared-window denominator with finite coverage, Parseval factors and zero-padding interpolation against scoped SciPy1.15.3 Notes and SASP. Six paired equations and four explained exercises. Internal state/even-FFT contracts explicit; no phase retrieval or library scaling compatibility claim.

  • Checked direct4-point DFT, padded reconstruction, missing first sample, actual coverage under hop changes, weighted one-sided energy14 and unchanged old complex bins after32→128 padding.
  • Four computed SVGs bind exact bilingual MDX. The five-topic group passed eleven numeric/encoding checks and 30 isolated language/width cases with four fallback fonts; ten actual screenshots inspected by the AI author. Literal-prose AST checked before freezing. Full article browser acceptance is separate; no human peer review.

Source locations checked:

  • SciPy 1.15.3: scipy.signal.stft · Read parameters, returns, Notes window/OLA equations and NOLA/coverage conditions. The interface is marked legacy. Our raw-FFT implementation checks actual finite denominators and is not a SciPy scaling compatibility test.
  • Spectral Audio Signal Processing: Zero Padding in the Time Domain · Read frequency interpolation, Practical Zero Padding, equation3.45 and peak-interpolation excerpt. Used for the unchanged-observation-time distinction; publication year not verified and no book figures copied.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.