Time-Frequency Analysis

Initialize NeuroAnalyzer
using NeuroAnalyzer
import CairoMakie
# Quarto sets a default figure size (672 × 480 px), which overrides the sizes of
# NeuroAnalyzer figures: remove it
delete!(CairoMakie.Makie.CURRENT_DEFAULT_THEME, :resolution)
using ContinuousWavelets
NeuroAnalyzer.progress_bar = false

# preprocessed recording, EEG channels only
eeg = load_neuro("files/eeg/eeg.hdf")
eeg = keep_channel(eeg; ch = "eeg")

The EEG is non-stationary: its properties change over time. A power spectrum shows which frequencies are present in the whole analyzed segment, but not when they occur. A spectrogram shows how the spectrum changes over time: time on the X axis, frequency on the Y axis, and the power (or amplitude) at each time-frequency point coded by color.

Time and Frequency Resolution

Most spectrograms are calculated in short (usually overlapping) segments, which are tapered to reduce edge artifacts (spectral leakage). For a segment of \(n\) samples recorded at the sampling rate \(f_s\):

\[ T = \frac{n}{f_s} \]

\[ \Delta f = \frac{f_s}{n} = \frac{1}{T} \]

where:
\(T\) is the segment duration in seconds (the time resolution),
\(\Delta f\) is the distance between frequency bins in Hz (the frequency resolution).

For example, to separate two frequencies 0.1 Hz apart, a segment of at least 1 / 0.1 Hz = 10 seconds is needed.

Gabor limit: time and frequency resolution cannot both be arbitrarily good (the uncertainty principle):

\[ \Delta t \, \Delta f \geq \frac{1}{4 \pi} \]

  • short segments: good time resolution, poor frequency resolution
  • long segments: good frequency resolution, poor time resolution

The segment should contain at least one cycle of the lowest frequency of interest, preferably 2–3 cycles; the length of one cycle is \(1/f\):

frequency   cycle length   recommended segment
  0.5 Hz      2000 ms        4-6 s
  1 Hz        1000 ms        2-3 s
  3 Hz         333 ms        0.7-1 s
 10 Hz         100 ms        0.2-0.3 s

Overlapping segments (usually by 50–90%) give a smoother spectrogram: the overlap does not improve the time resolution, but it samples the time axis more densely.

High frequencies change quickly, so they require good time resolution; low frequencies require good frequency resolution. The solution is to use windows of different lengths for different frequencies: longer windows for low frequencies and shorter windows for high frequencies. This is what wavelets do:

         STFT: the same window           wavelets: the window length
         at all frequencies              decreases with frequency

 40 Hz   ├──────┤├──────┤├──────┤        ├─┤├─┤├─┤├─┤├─┤├─┤├─┤├─┤
 10 Hz   ├──────┤├──────┤├──────┤        ├────┤├────┤├────┤├────┤
  2 Hz   ├──────┤├──────┤├──────┤        ├──────────┤├──────────┤

         time ──────────────────         time ──────────────────

The frequencies analyzed may be spaced linearly or logarithmically. Logarithmic spacing gives more frequencies in the low range (useful when studying low frequencies, and matching the logarithmic scaling of the brain rhythms); linear spacing gives equal coverage of the whole range (useful for high frequencies).

Spectrograms in NeuroAnalyzer

plot_spectrogram() calculates and plots a spectrogram; by default the first 10 seconds of the signal are shown (seg), or a single epoch (ep) of an epoched object. The method is selected using method; flim sets the frequency range and frq = :log the logarithmic frequency axis.

spectrogram() returns the values: a named tuple with the powers p (frequencies, time points, channels, epochs), frequencies f and time points t:

sp = NeuroAnalyzer.spectrogram(eeg; ch = "O1")
println("Powers:      ", size(sp.p))
println("Frequencies: ", sp.f[1], " to ", sp.f[end], " Hz")
Powers:      (129, 9837, 1, 1)
Frequencies: 0.0 to 128.0 Hz

Tip: spectrogram() is also exported by DSP.jl, so it is called with the NeuroAnalyzer. prefix.

Short-time Fourier Transform

The short-time Fourier transform (STFT), introduced by Dennis Gabor, computes the Fourier transform in short, successive time windows rather than once over the whole signal; the signal is assumed to be stationary within each window.

Algorithm: split the signal into short (overlapping) windows, taper each window, compute its power spectrum, and place the spectra of successive windows side by side along the time axis: each spectrum becomes one vertical column of the spectrogram.

By default the window is 1 second long (wlen = sr(obj)) with 90% overlap (woverlap), and each window is tapered with a Hanning window (w = true):

plot_spectrogram(eeg; ch = "O1", flim = (0, 40))

The power of the slow posterior rhythm (around 5–6 Hz) is visible in the lowest part of the spectrogram, fluctuating over time.

To smooth the spectrogram, use smooth = true; ks sets the size of the kernel of the Gaussian blur (default 3; a larger kernel means more smoothing):

plot_spectrogram(eeg;
                 ch = "O1",
                 flim = (0, 40),
                 smooth = true)

Multi-taper Spectrogram

A single-taper spectrum has a high variance, giving a noisy spectrogram:

  • no tapering: highest noise (variance) and spectral leakage
  • single taper: less leakage, but still noisy

With many trials, the noise is reduced by averaging the trials. For a single trial, multi-taper analysis averages spectra calculated with several orthogonal tapers: the discrete prolate spheroidal sequences (DPSS, Slepian tapers):

  • they concentrate most of the power in the main lobe and minimize spectral leakage (broadband bias)
  • they are mutually orthogonal, so they produce uncorrelated estimates of the spectrum, which are averaged to reduce the variance
  • higher-order tapers have large values near the window edges (unlike the Hanning window, which is zero at both ends), so the data at the edges are not lost

Algorithm: multiply each window by each DPSS taper, compute the spectrum for each tapered copy, and average the spectra across tapers.

The result is a smoother spectrogram with a lower variance, at the cost of frequency resolution; this is useful for noisy data and for high frequencies (e.g. gamma), where the power is low.

plot_spectrogram(eeg;
                 ch = "O1",
                 flim = (0, 40),
                 method = :mt)

Number of tapers: for a window of duration \(T\) (seconds) and the required frequency resolution (bandwidth) \(\Delta F = 2W\) (Hz), the time-half-bandwidth product is:

\[ TW = \frac{T \times \Delta F}{2} \]

and the number of tapers is:

\[ K = 2 TW - 1 \]

For example, for a 10-second window and a resolution of 2 Hz: \(TW = 10\), \(K = 2 \times 10 - 1 = 19\).

  • more tapers (\(\uparrow K\)): better variance reduction (less noise)
  • wider bandwidth (\(\uparrow \Delta F\)): wider main lobe, i.e. a more blurred spectrogram

Using more tapers than \(2TW - 1\) does not improve the estimate: the additional tapers are poorly concentrated in the band and introduce leakage.

ntapers(obj; df) calculates this number for the epoch length of an object; for a spectrogram, the relevant duration is the window length (wlen), and the number of tapers is set with nt (default 7). With the default 1-second window and 7 tapers, the resolution is \(\Delta F = (K + 1) / T = 8\) Hz.

Frequency-dependent smoothing: with nt, all frequencies are smoothed over the same band (\(\pm W\) = ±4 Hz for 7 tapers and a 1-second window). Oscillations at high frequencies (e.g. gamma) are usually broadband, and their power is low and noisy, so a wider band is useful there, while low frequencies need a narrow band. fsmo sets the half-bandwidth \(W\) (Hz) for each frequency: a single value for all frequencies, or a tuple linearly spaced from fsmo[1] at 0 Hz to fsmo[2] at the Nyquist frequency. Each frequency \(f\) uses its own set of \(K(f) = 2TW(f) - 1\) tapers (as tapsmofrq in FieldTrip). Here \(W\) increases from 2 Hz at 0 Hz to 40 Hz at 128 Hz: 5 tapers at 5 Hz, 14 at 20 Hz, 26 at 40 Hz:

plot_spectrogram(eeg;
                 ch = "O1",
                 flim = (0, 60),
                 method = :mt,
                 fsmo = (2, 40))

The spectrogram is smoother at high frequencies, and the low frequencies keep their resolution. Notes:

  • the time resolution is the window length (wlen) for all frequencies
  • a narrow-band peak is spread over \(\pm W\); when \(W\) increases with frequency, the spread is asymmetric and the peak frequency is biased downwards: to locate peaks, use a constant fsmo (or nt)
  • \(W\) below \(1 / T\) (1 Hz for a 1-second window) is raised to \(1 / T\) (one taper); a single taper at the lowest frequencies gives a noisy estimate, so start fsmo at about 2 Hz
  • the number of tapers grows with \(T \times W\): for wide smoothing, use a shorter window

Morlet Wavelet

A Morlet wavelet is a complex sine wave tapered by a Gaussian. Its spectrum is a Gaussian centered at the frequency of the wavelet, so convolving the signal with the wavelet acts as a band-pass filter; the magnitude of the result is the amplitude of the signal at that frequency over time. The width of the Gaussian is set by the number of cycles (ncyc): more cycles give better frequency resolution and worse time resolution. For details, see the introduction to the wavelet transform.

plot_spectrogram(eeg;
                 ch = "O1",
                 flim = (0, 40),
                 method = :mw)

The default number of cycles (32) gives a high frequency resolution but a poor time resolution (horizontal bands). A number of cycles that increases with frequency (here from 3 to 15, spaced logarithmically) gives a better time resolution at all frequencies:

plot_spectrogram(eeg;
                 ch = "O1",
                 flim = (0, 40),
                 method = :mw,
                 ncyc = (3, 15))

Logarithmic frequency axis:

plot_spectrogram(eeg;
                 ch = "O1",
                 flim = (1, 40),
                 method = :mw,
                 frq = :log)

Gaussian-Hilbert

The signal is filtered with Gaussian band-pass filters (width gw, default 10 Hz) centered at successive frequencies, and the amplitude envelope of each filtered signal is obtained using the Hilbert transform. For details, see the introduction to the Hilbert transform.

plot_spectrogram(eeg;
                 ch = "O1",
                 flim = (0, 40),
                 method = :gh)

Hilbert-Huang

The signal is decomposed into intrinsic mode functions using empirical mode decomposition, and the instantaneous frequency and amplitude of each function are obtained using the Hilbert transform. The result is a sparse map: at each time point, each mode contributes power at one frequency. For details, see the introduction to the Hilbert transform.

plot_spectrogram(eeg;
                 ch = "O1",
                 flim = (0, 40),
                 method = :hht)

Continuous Wavelet Transform

The continuous wavelet transform (CWT) gives a scalogram: the magnitude of the wavelet coefficients at each scale (converted to frequency) and time point. The default wavelet is wavelet(Morlet(2π), β = 2); other wavelets from ContinuousWavelets.jl can be selected using wt. For details, see the introduction to the wavelet transform.

plot_spectrogram(eeg;
                 ch = "O1",
                 flim = (0, 40),
                 method = :cwt)

Multi-channel Spectrogram

For several channels, the spectrogram of each channel is averaged over time into a single row: the X axis shows the frequencies and the Y axis the channels.

plot_spectrogram(eeg;
                 ch = "eeg",
                 flim = (0, 40))

The posterior (parietal, occipital and temporal) channels have the highest power at low frequencies.

Topographical Map

The spectrograms of individual channels can be shown at the electrode locations:

plot_spectrogram(eeg;
                 ch = "eeg",
                 flim = (0, 40),
                 type = :topo,
                 gui = false)

In the interactive window (gui = true), clicking a spectrogram opens it enlarged in a new window.

Thresholding

Regions of the spectrogram can be marked using a threshold; only the values meeting the threshold are shown. Here, the regions with power ≥ 0 dB:

plot_spectrogram(eeg;
                 ch = "O1",
                 flim = (0, 40),
                 smooth = true,
                 threshold = 0,
                 threshold_type = :geq)

The threshold_type sets the rule:

  • :eq: values equal to the threshold
  • :neq: values not equal to the threshold
  • :geq: values ≥ the threshold
  • :leq: values ≤ the threshold
  • :g: values > the threshold
  • :l: values < the threshold
  • :in: values within the threshold range (inclusive), threshold = (low, high)
  • :bin: values within the threshold range (exclusive), threshold = (low, high)