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

Power spectra: periodogram, Welch, spectrogram and Lomb-Scargle

ProblemEstimate how the power of a random signal is distributed over frequency, as a whole or as it changes in time, from regularly or irregularly spaced samples
Devised byArthur Schuster (1898), the periodogram; M. S. Bartlett (1948) and Peter Welch (1967), averaging segments; Dennis Gabor (1946), short-time analysis; Nicholas Lomb (1976) and Jeffrey Scargle (1982), unevenly sampled data; Daniel Griffin and Jae Lim (1984), the inverse STFT
AccuracyPeriodogram, Welch and Lomb-Scargle values agree with SciPy to ; istft(stft(x)) reproduces to
Cost for samples in segments of ; Lomb-Scargle for frequencies
Read firstWindow functions, Preliminaries: probability
APIperiodogram, welch (SpectralScaling, Detrend), stft, istft, spectrogram, lomb_scargle, non_uniform_dft, fit_sinusoid

Overview

The power spectral density (PSD) of a stationary random signal says how its variance is spread over frequency: integrating it over all frequencies gives the variance. The periodogram, the squared magnitude of the DFT suitably scaled, is the obvious estimate and a poor one. Its bias is set by the window’s leakage, and its standard deviation equals its mean however long the signal, because longer records only add frequency bins. Welch’s method averages the periodograms of overlapping segments, trading resolution for a variance that falls with the number of segments. The spectrogram keeps the segments separate, giving a picture of how the spectrum evolves. For samples taken at irregular times, the Lomb-Scargle periodogram fits sinusoids by least squares instead.

Where it is used

Power spectra show how a random signal’s power is distributed over frequency.

  • Vibration and noise measurement. Welch’s method gives the power spectral density of accelerometer, microphone and sensor signals.
  • Spectrograms. Speech, music, bird song, radar micro-Doppler and EEG evolve in time, and the spectrogram shows how.
  • Astronomy and geophysics. The Lomb-Scargle periodogram handles unevenly sampled data, as in finding periods of variable stars and exoplanet transits.
  • Communications. Measuring the spectrum of a transmitter for regulatory limits.

History

Arthur Schuster (1898) introduced the periodogram to search for hidden periodicities in sunspot and meteorological records. It took half a century to understand its erratic behaviour: M. S. Bartlett (1948) proposed averaging periodograms of separate segments, and Peter Welch (1967) showed that overlapping windowed segments, computed by FFT, do better. Dennis Gabor (1946) introduced short-time Fourier analysis, and the spectrogram became a standard tool of speech research at Bell Labs. Astronomers, whose observations are interrupted by day, weather and seasons, needed spectra of unevenly sampled data. Nicholas Lomb (1976) and Jeffrey Scargle (1982) defined a periodogram equivalent to least-squares fitting of sinusoids.

The idea

The periodogram and its scaling

The power spectral density (PSD) of a signal says how its power is distributed over frequency. The most direct estimate takes the DFT of a record and squares its magnitude: the energy found at each frequency. This is the periodogram. For samples at rate , multiplied by a window , the one-sided periodogram is

For a real signal the negative frequencies duplicate the positive ones, so they are folded in: , except at DC and at the Nyquist frequency, which have no partner. The remaining factors fix the units, and there are two conventions, suited to two kinds of signal.

  • Density scaling, the factor shown above, gives units of power per hertz. Integrating the result over frequency gives the variance of the signal. It is the right scale for noise, whose power is spread over a band.
  • Spectrum scaling, with instead, gives units of power. A sinusoid of amplitude centred on a bin reads , its mean square. It is the right scale for tones, whose power is concentrated at a frequency.

The scalings follow SciPy, and the results agree with it to rounding error.

The periodogram has two defects, bias and variance, treated in the next two sections.

Bias: leakage

Figure 15.2. Periodogram and Welch estimates.

With no window, the strong tone’s leakage, decaying only as , buries a second tone 70 dB weaker and every bit of the noise floor. A Hann window’s leakage falls off steeply, revealing both. The window’s resolution and dynamic range carry over directly to the spectrum estimate (see windows).

Variance: Welch averaging

The second defect is that the periodogram of a noisy signal is itself extremely noisy, and taking a longer record does not help. A longer record gives more frequency bins, each as erratic as before. In statistical terms, each periodogram value of a Gaussian noise process is approximately the true density multiplied by a random factor distributed as , whose standard deviation equals its mean: the estimate is wrong by about 100%, whatever is.

The cure for a noisy estimate is to average several independent ones. Welch’s method cuts the record into shorter segments, computes a windowed periodogram of each, and averages them. Averaging independent estimates divides the standard deviation by . The price is resolution: shorter segments have wider bins.

Segments may overlap. A tapered window gives little weight to the samples near the ends of each segment, so without overlap those samples would be largely wasted. Overlapping by half with a Hann window uses them, while the segments remain nearly independent:

Table 15.4. Bias and variance of Welch's estimate against segment length.

segment length (Hann, 50% overlap)segments averagedbin width (× fs)mean density (true 2.000)standard deviation ÷ mean
1638410.00012.0260.979
409670.00022.0110.377
1024310.00102.0120.188
2561270.00392.0100.097
645110.01561.9960.041

A single 16 384-point periodogram is as noisy as possible (ratio 0.98), with bins of width . 511 segments of 64 points have a ratio of 0.04, but bins 256 times wider. The ratio follows closely: Hann segments overlapping by half are nearly uncorrelated, so the overlap buys almost twice as many useful averages from the same data. The choice of segment length is the bias-variance trade-off: short segments give many averages (low variance) but coarse frequency resolution (bias).

The short-time Fourier transform and the spectrogram

The STFT computes the spectrum of each windowed frame , with hop . Its squared magnitude, scaled like a periodogram, is the spectrogram:

Figure 15.3. Spectrogram.

The chirp traces a straight line, and the tone appears at one second. Time and frequency resolution trade off through the frame length: a 256-sample frame at 8 kHz resolves 31 Hz and 32 ms. istft inverts the STFT by weighted overlap-add, , which is exact for an unmodified STFT and the least-squares signal for a modified one (Griffin and Lim). Largest reconstruction error of istft(stft(x)) away from the ends: 7.8e-16.

Unevenly sampled data: Lomb-Scargle

With irregular sample times there is no FFT, and the DFT sum is no longer orthogonal. The Lomb-Scargle periodogram instead fits by least squares at each frequency, with the offset chosen to decouple and (). The power is the variance the fit explains:

Figure 15.4. Lomb-Scargle periodogram.

Both tones stand out of 120 random samples. Irregular sampling has a benefit: there is no single Nyquist frequency, and frequencies far above the average sample rate can be detected. normalize divides by the total variance, giving the fraction of variance explained.

Algorithm

Welch’s method, for segments of samples with a given overlap.

  1. Step through the signal in strides of samples; each position at which a full segment fits gives one segment.
  2. For each segment: remove its mean or linear trend, if detrending is requested; multiply by the window; take a real FFT; and add to a running total for each bin .
  3. Divide the totals by the number of segments.
  4. Scale by for a density or for a spectrum, and double every bin except DC and Nyquist.

The periodogram is the special case of a single segment covering the whole signal.

STFT: steps 1 and 2 without the squaring and averaging; the complex spectrum of each frame is kept. ISTFT:

  1. inverse-FFT each frame and multiply it by the window again;
  2. add the frames into the output at their positions (overlap-add), and add the squared window into a second array at the same positions;
  3. divide the output by the second array wherever it is not negligible.

Lomb-Scargle, for samples at arbitrary times .

  1. Subtract the mean from the samples.
  2. For each requested angular frequency : compute from ; then compute the four sums over the data in the formula for , and combine them.

The cost is per frequency, with no FFT.

Implementation

    let step = m - overlap;
    let segments = (x.len() - m) / step + 1;
    let mut fft = RealFft::new(m)?;
    let bins = fft.spectrum_len();
    let mut power = vec![0.0; bins];
    let mut segment = vec![0.0; m];
    for s in 0..segments {
        segment.copy_from_slice(&x[s * step..s * step + m]);
        detrend_in_place(&mut segment, detrend);
        segment.iter_mut().zip(window).for_each(|(v, w)| *v *= w);
        let spectrum = fft.forward(&segment)?;
        power.iter_mut().zip(&spectrum).for_each(|(p, c)| *p += c.norm_sqr());
    }
    let scale = match scaling {
        SpectralScaling::Density => 1.0 / (fs * window.iter().map(|w| w * w).sum::<f64>()),
        SpectralScaling::Spectrum => 1.0 / window.iter().sum::<f64>().powi(2),
    } / segments as f64;
    let last_doubled = if m.is_multiple_of(2) { bins - 1 } else { bins };
    for (k, p) in power.iter_mut().enumerate() {
        *p *= scale * if k > 0 && k < last_doubled { 2.0 } else { 1.0 };
    }
  • periodogram is welch with one segment spanning the signal.
  • lomb_scargle takes angular frequencies, as SciPy does; non_uniformly_sampled_spectrum takes them in hertz.

In practice

//! Power spectra: periodogram, Welch averaging and the spectrogram.

use lib_jsl_dsp::discrete::spectral::stft::spectrogram;
use lib_jsl_dsp::discrete::spectral::welch::{Detrend, SpectralScaling, periodogram, welch};
use lib_jsl_dsp::discrete::windows::{WindowType, generate_window};
use std::f64::consts::PI;

fn main() {
    let fs = 1000.0;
    // A tone of amplitude 2 at 125 Hz plus a little deterministic "noise".
    let x: Vec<f64> = (0..8192).map(|n| 2.0 * (2.0 * PI * 125.0 * n as f64 / fs).sin() + 0.1 * ((n * 7919 % 1013) as f64 / 506.5 - 1.0)).collect();
    let p = periodogram(&x, fs, &generate_window(WindowType::Flattop, x.len(), false), Detrend::Constant, SpectralScaling::Spectrum).unwrap();
    let (k, peak) = p.power.iter().enumerate().fold((0, 0.0), |b, (k, &v)| if v > b.1 { (k, v) } else { b });
    println!("flat-top periodogram: peak {:.4} V² at {} Hz (A²/2 = 2)", peak, p.frequencies[k]);
    let w = welch(&x, fs, &generate_window(WindowType::Hann, 512, false), 256, Detrend::Constant, SpectralScaling::Density).unwrap();
    let total: f64 = w.power.iter().sum::<f64>() * fs / 512.0;
    println!("Welch: {} segments; integrated density {total:.3} (signal power {:.3})", w.segments, x.iter().map(|v| v * v).sum::<f64>() / x.len() as f64);
    let s = spectrogram(&x, fs, &generate_window(WindowType::Hann, 256, false), 128, SpectralScaling::Density).unwrap();
    println!("spectrogram: {} frames × {} bins, first frame centred at {:.3} s", s.power.nrows(), s.power.ncols(), s.times[0]);
}
flat-top periodogram: peak 2.0000 V² at 125 Hz (A²/2 = 2)
Welch: 31 segments; integrated density 2.003 (signal power 2.003)
spectrogram: 63 frames × 129 bins, first frame centred at 0.128 s

The flat-top window with spectrum scaling reads the tone’s power exactly; the Welch density integrates to the signal power.

Strengths

  • Fast, nonparametric and well understood; the spectrogram shows time-varying content at a glance.
  • Lomb-Scargle handles gaps and irregular sampling without interpolation.

Weaknesses

  • Resolution is limited to about one bin of the segment length, and variance falls only with averaging.
  • The time-frequency trade-off of the spectrogram is fixed by the frame length; wavelets and parametric methods make other trade-offs.

Exercises

  1. Show that the density scaling makes the one-sided PSD of white noise of variance equal to .
  2. Show that the periodogram of Gaussian white noise has, at each interior bin, an exponential distribution with standard deviation equal to its mean.
  3. Show that the windowed segments of a Hann STFT with hop satisfy , and find the constant.
  4. Show that the Lomb-Scargle power at frequency equals the reduction in residual sum of squares of the best sinusoidal fit at that frequency (divided by two).
  5. Sample a sinusoid of frequency 3 at 50 random times in (an average rate of 5), and find it with lomb_scargle. What would an evenly sampled DFT show?
Hints and answers
  1. The one-sided density doubles the two-sided (variance spread evenly over ), so it is on .
  2. At an interior bin the real and imaginary parts of the DFT of Gaussian white noise are independent Gaussians of equal variance; the periodogram is their sum of squares, a variable (exponential), whose standard deviation equals its mean.
  3. For the periodic Hann window, and the shifted sum with cancels the cosine terms, leaving .
  4. The residual sum of squares of the best sinusoid at frequency falls by a constant: Lomb-Scargle is the least-squares fit to at each .
  5. An average rate of 5 samples per second leaves the Nyquist frequency near 2.5, below 3, but random sampling has no single Nyquist frequency and Lomb-Scargle finds the 3 Hz peak. An evenly sampled DFT at 5 samples per second would alias the 3 Hz sine to 2 Hz.

Further reading

  • P. D. Welch, “The use of fast Fourier transform for the estimation of power spectra”, IEEE Transactions on Audio and Electroacoustics 15 (1967) 70–73.
  • J. D. Scargle, “Studies in astronomical time series analysis II”, Astrophysical Journal 263 (1982) 835–853.
  • D. W. Griffin and J. S. Lim, “Signal estimation from modified short-time Fourier transform”, IEEE Transactions on Acoustics, Speech, and Signal Processing 32 (1984) 236–243.
  • D. B. Percival and A. T. Walden, Spectral Analysis for Physical Applications, Cambridge University Press, 1993.