Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Window functions

ProblemTaper a finite block of samples so that its spectrum suffers little leakage, trading frequency resolution against the dynamic range of the spectrum
Devised byJulius von Hann (1903, the cosine bell); Richard Hamming and John Tukey (1950s); R. B. Blackman and Tukey (1958); C. L. Dolph (1946), Chebyshev arrays; T. T. Taylor (1955); James Kaiser (1966, 1974); David Slepian (1978), prolate spheroidal sequences; Fredric Harris (1978), the standard survey
AccuracyAll 24 windows agree with scipy.signal.windows to about in both their symmetric and periodic forms (table below)
Cost for most; for the Dolph-Chebyshev window (a direct DFT) and per iteration for the DPSS
Read firstBackground: sampling and aliasing, The fast Fourier transform
APIgenerate_window, WindowType, one function per window in windows (hann, hamming, blackman, kaiser, chebwin, dpss, taylor, general_cosine, …)

Overview

The DFT of a block of samples treats the block as one period of a periodic signal. Unless a sinusoid fits a whole number of periods into the block, the period boundaries are discontinuous and its energy leaks into every frequency bin. A window multiplies the block before the transform, tapering it towards zero at the ends so the discontinuity disappears. The transform of the windowed signal is the true spectrum convolved with the window’s transform . That transform has a main lobe, which sets how close two frequencies can be and still be resolved, and side lobes, which set how weak a component can be and still be seen next to a strong one. No window is narrow and low at once. The many windows in the library are different choices along that trade-off, plus a few for special purposes.

Where it is used

Windows control what you see in a spectrum.

  • Spectrum analysers and audio analysis. The window trades frequency resolution against leakage: a Hann window for general use, flat-top for accurate amplitude measurement, Kaiser or Blackman-Harris for high dynamic range.
  • FIR filter design. Windowing the ideal impulse response gives a practical filter.
  • Radar and sonar. Tapering reduces sidelobes so that weak targets next to strong ones are not masked.
  • Short-time analysis. Every frame of a spectrogram is windowed.

History

The cosine-bell taper is named after the Austrian meteorologist Julius von Hann, who used it for smoothing in 1903. Richard Hamming and John Tukey introduced windowed spectral estimation at Bell Labs in the 1950s, and R. B. Blackman and Tukey’s The Measurement of Power Spectra (1958) made the windows standard. C. L. Dolph (1946) designed antenna arrays with equal side lobes from Chebyshev polynomials, the origin of the Dolph-Chebyshev window, and T. T. Taylor (1955) relaxed it for radar. James Kaiser (1966) approximated the optimally concentrated prolate spheroidal functions with Bessel functions. David Slepian (1978) gave the discrete prolate spheroidal sequences themselves, which David Thomson (1982) used in multitaper spectral estimation. Fredric Harris’s 1978 survey, “On the use of windows for harmonic analysis with the discrete Fourier transform”, defined the figures of merit still used.

The idea

Leakage, the main lobe and the side lobes

Where leakage comes from. A spectrum can only be computed from a finite record of samples. Taking a finite record is the same as multiplying the endless signal by a function that is 1 during the record and 0 outside it, a rectangular window. That multiplication changes the spectrum. Multiplying two signals in time convolves their spectra in frequency, so the spectrum we compute is the true spectrum smeared by the transform of the window.

The effect is clearest for a pure tone, whose true spectrum is a single spike. Convolving a spike with gives a copy of centred on the tone’s frequency. So instead of one sharp line, the tone appears as the whole shape of : a central main lobe, whose width limits how close two tones can be and still be told apart, and a series of side lobes that spread the tone’s energy to distant frequencies. That spreading is leakage. The side lobes of a strong tone can hide a weak one entirely.

(When a tone has exactly a whole number of cycles in the record, the DFT happens to sample only at its peak and its zeros, and no leakage is visible. For any other frequency it is.)

The remedy. The side lobes of the rectangular window are high because it switches on and off abruptly. A window that rises smoothly from zero and falls smoothly back has far lower side lobes. The price is a wider main lobe, because the taper makes the record effectively shorter. Every window is a compromise between the two:

The rectangular window (no taper) has the narrowest main lobe but side lobes only 13 dB down, decaying slowly. Each smoother taper widens the main lobe and lowers the side lobes: Hann to −31 dB, Blackman to −58 dB, the four-term Blackman-Harris to −92 dB.

Families

  • Cosine sums : rectangular, Hann (), Hamming (0.54, 0.46, cancelling the first side lobe), Blackman, Nuttall, Blackman-Harris, and the flat top, whose main lobe is so flat that a tone between bins is measured with negligible amplitude error. general_cosine takes any coefficients.
  • Parametric windows with a knob for the trade-off: Kaiser (), Gaussian (), Tukey (the tapered fraction ), Dolph-Chebyshev (the side-lobe level, all lobes equal: the narrowest main lobe for that level), Taylor (nearly equal near-in lobes, then decaying), and the DPSS or Slepian window (the half-bandwidth ), which maximises the energy inside a band.
  • Others: triangular and Bartlett, Parzen, Bohman, Bartlett-Hann, cosine, exponential, Lanczos (a sinc), and the Kaiser-Bessel derived window used by the modified DCT.

Figure 15.1. Transforms of the parametric windows.

Figures of merit

Three numbers summarise how a window of length affects measurements made with it.

  • The coherent gain is the factor by which the window scales the amplitude of a tone. A taper reduces the samples near the ends, so the gain is below 1 and amplitudes must be divided by it.
  • The equivalent noise bandwidth , in bins, measures how much noise each bin collects. It is the width of the ideal rectangular filter that would pass the same noise power. A wider main lobe admits more noise, so tapering costs a little signal-to-noise ratio.
  • The scalloping loss is the amplitude lost by a tone that falls halfway between two bins, the worst case, where both neighbouring bins sample the main lobe on its slopes instead of at its peak.

Table 15.2. Figures of merit of common windows.

window (64 samples, periodic)coherent gainnoise bandwidth (bins)3 dB width (bins)highest side lobe (dB)scalloping loss (dB)main lobe width to first minimum (bins)
rectangular1.0001.000.89-13.33.922.00
Hann0.5001.501.44-31.51.424.00
Hamming0.5401.361.30-42.41.754.00
Blackman0.4201.731.64-58.11.106.00
Blackman-Harris0.3592.001.90-92.00.838.00
flat top0.2163.773.73-88.20.0110.00
Kaiser β = 80.4361.671.59-58.81.185.47
Dolph-Chebyshev 80 dB0.4161.731.65-73.71.106.45
DPSS NW = 30.4151.741.66-71.11.096.14
Tukey α = 0.50.7501.221.15-15.12.242.67
Gaussian σ = 80.3132.262.12-87.30.6711.44
Taylor n̄ = 4, 30 dB0.6481.171.12-29.12.382.97

The flat-top window measures amplitudes to 0.01 dB wherever the tone falls, at the price of a main lobe ten bins wide. The Dolph-Chebyshev and Taylor windows reach their design levels (−80 and −30 dB) only in their symmetric form. The periodic form drops a sample from a window one longer, which raises the highest lobe to −74 dB and −29 dB here.

Symmetric and periodic forms

Each function takes sym. A symmetric window () suits FIR filter design. A periodic window is the first samples of a symmetric window of length . It is the right choice for spectral analysis, because its DFT has the exact structure the formulas assume. For example, the periodic Hann window’s transform has just three non-zero bins.

The Dolph-Chebyshev and DPSS windows

The Dolph-Chebyshev window is defined through its transform, the Chebyshev polynomial sampled at points, and computed by an inverse DFT. The DPSS window is the eigenvector, for the largest eigenvalue, of a symmetric tridiagonal matrix that commutes with the band-concentration problem. The library finds that eigenvalue by bisection on Sturm sequence counts and the eigenvector by inverse iteration.

Testing against SciPy

Table 15.3. Windows against SciPy.

window (lengths 16 and 17, symmetric and periodic)largest difference from SciPy
barthann1.7e-16
bartlett1.2e-16
blackman0.0e0
blackmanharris0.0e0
bohman5.7e-17
boxcar0.0e0
chebwin 801.3e-15
cosine0.0e0
dpss 35.6e-16
exponential tau 30.0e0
flattop0.0e0
gaussian 2.51.1e-16
general_gaussian 1.5 30.0e0
general_hamming 0.60.0e0
hamming0.0e0
hann0.0e0
kaiser 85.6e-16
kaiser_bessel_derived1.1e-16
lanczos2.2e-16
nuttall0.0e0
parzen1.4e-17
taylor 4 301.7e-16
triang0.0e0
tukey 0.46.7e-16

Two windows need care. chebwin needs a Chebyshev polynomial of the right order and sign (a mistake there gives errors up to 0.99). dpss needs the eigenvector of the largest eigenvalue, but power iteration finds the eigenvalue of largest magnitude, which is the wrong one when the bandwidth exceeds a quarter of the sampling rate: dpss(7, 2.5) would be wrong by 0.31. The window tests compare with SciPy’s values.

Algorithm

Every function returns a window of samples.

Cosine-sum windows (Hann, Hamming, Blackman and the rest): for each sample , compute the angle , evenly spaced from to across the window, and evaluate with the family’s coefficients.

Kaiser: for each sample, map to a position in and evaluate , where is the modified Bessel function of order zero.

Dolph-Chebyshev, for a given side-lobe level:

  1. compute from the level, so that the Chebyshev polynomial reaches the wanted ratio between its main lobe and its ripples;
  2. sample at : this is the window’s transform;
  3. take the real DFT of those samples (with a half-sample phase shift for even ), and rotate the result so that the window is centred;
  4. divide by the largest value, so that the peak is 1.

DPSS, for a half-bandwidth :

  1. form the symmetric tridiagonal matrix whose eigenvectors are the Slepian sequences;
  2. find its largest eigenvalue by bisection, counting with a Sturm sequence how many eigenvalues lie below a trial value;
  3. find the corresponding eigenvector by inverse iteration with that eigenvalue as the shift;
  4. normalise it to a peak of 1.

Periodic form of any window: compute the symmetric window of length and drop its last sample.

Implementation

    let fac = linspace(-PI, PI, m2);
    let mut w = vec![0.0; m2];
    for (k, ak) in a.iter().enumerate() {
        for n in 0..m2 {
            w[n] += ak * ((k as f64) * fac[n]).cos();
        }
    }
    truncate(w, needs_trunc)
    // Gershgorin bounds, then bisection for the largest eigenvalue.
    let radius = |i: usize| (if i > 0 { e[i - 1].abs() } else { 0.0 }) + (if i + 1 < m2 { e[i].abs() } else { 0.0 });
    let (mut lo, mut hi) = (0..m2).fold((f64::INFINITY, f64::NEG_INFINITY), |(l, h), i| (l.min(d[i] - radius(i)), h.max(d[i] + radius(i))));
    for _ in 0..200 {
        let mid = 0.5 * (lo + hi);
        if mid <= lo || mid >= hi {
            break;
        }
        if count_below(&d, &e, mid) < m2 { lo = mid } else { hi = mid }
    }
    let lambda = hi + 4.0 * f64::EPSILON * hi.abs().max(1.0);

    // Inverse iteration: solve (T − λI) v_new = v by the tridiagonal (Thomas) elimination.
    let mut v = vec![1.0_f64; m2];
    for _ in 0..4 {
        let mut cp = vec![0.0; m2];
        let mut dp = vec![0.0; m2];
        let mut b0 = d[0] - lambda;
        if b0 == 0.0 {
            b0 = f64::EPSILON;
        }
        cp[0] = if m2 > 1 { e[0] / b0 } else { 0.0 };
        dp[0] = v[0] / b0;
        for i in 1..m2 {
            let mut den = d[i] - lambda - e[i - 1] * cp[i - 1];
            if den == 0.0 {
                den = f64::EPSILON;
            }
            cp[i] = if i + 1 < m2 { e[i] / den } else { 0.0 };
            dp[i] = (v[i] - e[i - 1] * dp[i - 1]) / den;
        }
        let mut x = vec![0.0; m2];
        x[m2 - 1] = dp[m2 - 1];
        for i in (0..m2 - 1).rev() {
            x[i] = dp[i] - cp[i] * x[i + 1];
        }
        let norm = x.iter().map(|t| t * t).sum::<f64>().sqrt();
        v = x.into_iter().map(|t| t / norm).collect();
    }
  • generate_window(WindowType, m, sym) dispatches to the individual functions; firwin and the spectral estimators accept a WindowType or a window vector.
  • The Kaiser-Bessel derived window is defined for even lengths only, as in SciPy. For an odd length the library returns the next even window with its last sample dropped.

In practice

//! Window functions: shapes, figures of merit, and the periodic and symmetric forms.

use lib_jsl_dsp::discrete::windows::{WindowType, generate_window};

fn main() {
    for (name, kind) in [("Hann", WindowType::Hann), ("Blackman-Harris", WindowType::BlackmanHarris), ("Kaiser β = 8", WindowType::Kaiser { beta: 8.0 }), ("flat top", WindowType::Flattop)] {
        let w = generate_window(kind, 1024, false);
        let (s1, s2): (f64, f64) = (w.iter().sum(), w.iter().map(|v| v * v).sum());
        println!("{name:<16} coherent gain {:.4}, equivalent noise bandwidth {:.3} bins", s1 / 1024.0, 1024.0 * s2 / (s1 * s1));
    }
    // Symmetric windows suit filter design; periodic ones (sym = false) suit spectral analysis.
    println!("symmetric Hann(5): {:?}", generate_window(WindowType::Hann, 5, true));
    println!("periodic Hann(5):  {:?}", generate_window(WindowType::Hann, 5, false));
}
Hann             coherent gain 0.5000, equivalent noise bandwidth 1.500 bins
Blackman-Harris  coherent gain 0.3588, equivalent noise bandwidth 2.004 bins
Kaiser β = 8     coherent gain 0.4357, equivalent noise bandwidth 1.666 bins
flat top         coherent gain 0.2156, equivalent noise bandwidth 3.770 bins
symmetric Hann(5): [0.0, 0.5, 1.0, 0.5, 0.0]
periodic Hann(5):  [0.0, 0.34549150281252633, 0.9045084971874737, 0.9045084971874737, 0.34549150281252633]

Strengths

  • A choice of trade-offs: resolution (rectangular, Hann), dynamic range (Blackman-Harris, Chebyshev, DPSS), amplitude accuracy (flat top), or a tunable mix (Kaiser).

Weaknesses

  • No window is best for every purpose; low side lobes always cost resolution and noise bandwidth.

Exercises

  1. Show that the periodic Hann window of length has a DFT with only three non-zero bins.
  2. Derive the Hamming coefficients 0.54 and 0.46 from the condition that the first side lobe vanishes (approximately 25/46 and 21/46).
  3. Show that the equivalent noise bandwidth of any window is at least 1 bin, with equality only for the rectangular window.
  4. Compute the scalloping loss of the rectangular window, , and check it against the table.
  5. Explain why the Dolph-Chebyshev window of very large length has impulsive end samples, and why Taylor’s modification avoids them.
Hints and answers
  1. The periodic Hann window is , a constant plus two complex exponentials, so its DFT has non-zero entries only at .
  2. Choose and so that the Dirichlet kernel terms cancel at the first side-lobe peak: this gives (rounded to 0.54) and (0.46).
  3. Equivalent noise bandwidth is by Cauchy-Schwarz, with equality iff is constant.
  4. A tone midway between bins sees the window’s response at half a bin: for the rectangle , i.e. a loss of dB.
  5. Dolph-Chebyshev windows have all side lobes at equal height; for large lengths the only way to keep them equal is an impulsive pair of samples at the ends. Taylor windows let the far side lobes decay, which removes the impulses.

Further reading

  • F. J. Harris, “On the use of windows for harmonic analysis with the discrete Fourier transform”, Proceedings of the IEEE 66 (1978) 51–83.
  • A. H. Nuttall, “Some windows with very good sidelobe behavior”, IEEE Transactions on Acoustics, Speech, and Signal Processing 29 (1981) 84–91.
  • D. Slepian, “Prolate spheroidal wave functions, Fourier analysis, and uncertainty — V: the discrete case”, Bell System Technical Journal 57 (1978) 1371–1430.
  • R. B. Blackman and J. W. Tukey, The Measurement of Power Spectra, Dover, 1958.