Spectral (multitaper)#

Multitaper spectral estimation#

Thomson’s multitaper method with Slepian (DPSS) tapers, for the quick analyses of a review viewer and for scripts alike:

Scaling: one-sided PSD in units**2 / Hz. The tapers have unit energy, so white noise of variance s2 has a PSD of 2 * s2 / fs and integrating the PSD over [0, fs/2] returns the signal’s variance. Each segment is demeaned first, which removes power within the half-bandwidth W = NW / T of 0 Hz as well (by about 1 / (2 NW) at the first bins).

Assumptions behind the intervals and the test#

The chi-square interval and the F test treat the K eigenspectra as independent estimates. That holds for spectra that are locally flat; on steep spectra (a dynamic range of more than ~40 dB, e.g. raw 1/f^3 iEEG) taper leakage correlates them and both become too liberal – prefer the jackknife interval and test (the defaults), or prewhiten. Within W of 0 Hz and of Nyquist the eigenspectra are real-valued or folded, so their degrees of freedom are about K, not 2K; the chi-square interval and the F test use K there.

Missing data#

NaN/inf marks missing data. nan_policy='raise' (the default) refuses it. nan_policy='omit' cuts the finite runs into non-overlapping segments of ONE length (segment_samples, default the longest run) and averages the segments’ eigenspectra: every estimate then has the same resolution and the same weight, so the level is not biased by short runs and the degrees of freedom are honest. Finite data in runs shorter than a segment, and the remainder of each run, are not used; a RuntimeWarning says so when that is more than half of it.

class brainmaze_eeg.spectral.MultitaperSpectrum(freqs: ndarray, psd: ndarray, ci_low: ndarray, ci_high: ndarray, log_var: ndarray, dof: ndarray, n_tapers: ndarray, n_segments: ndarray, nw: float, bandwidth: float, confidence: float)#

A multitaper PSD estimate.

psd, ci_low, ci_high, log_var and dof have the input’s leading shape plus a last axis of frequencies. n_tapers is the number of eigenspectra averaged per series (k times n_segments); dof the chi-square degrees of freedom per frequency (2 * n_tapers, n_tapers within bandwidth of 0 Hz and Nyquist); log_var the jackknife variance of ln(psd); bandwidth the half-bandwidth W in Hz.

bandwidth: float#
ci_high: ndarray#
ci_low: ndarray#
confidence: float#
dof: ndarray#
freqs: ndarray#
log_var: ndarray#
n_segments: ndarray#
n_tapers: ndarray#
nw: float#
psd: ndarray#
brainmaze_eeg.spectral.band_power(freqs, psd, bands: Dict[str, Sequence[float]]) → Dict[str, ndarray]#

Power in each named band [lo, hi] Hz: the PSD integrated over exactly that interval (interpolated at the edges), along the last axis.

brainmaze_eeg.spectral.multitaper_psd(x, fs: float, nw: float = 4.0, k: int | None = None, nfft: int | None = None, confidence: float = 0.95, ci_method: str = 'jackknife', nan_policy: str = 'raise', segment_samples: int | None = None) → MultitaperSpectrum#

Multitaper PSD of x along its last axis.

Parameters:
  • x (array_like) – Signal, (..., n_samples).

  • fs (float) – Sampling rate, Hz.

  • nw (float) – Time-half-bandwidth product; the half-bandwidth is W = nw / T Hz.

  • k (int, optional) – Number of tapers, default 2 * nw - 1; at most 2 * nw.

  • nfft (int, optional) – FFT length, default the next power of two of the segment length.

  • confidence (float) – Confidence level of ci_low / ci_high.

  • ci_method ({'jackknife', 'chi2'})

  • nan_policy ({'raise', 'omit'}) – See the module notes on missing data.

  • segment_samples (int, optional) – 'omit' only: the length every segment is cut to, default the longest finite run (of any series).

brainmaze_eeg.spectral.multitaper_spectrogram(x, fs: float, window_s: float, step_s: float | None = None, nw: float = 3.0, k: int | None = None, nfft: int | None = None, chunk: int = 64)#

Multitaper spectrogram of x along its last axis.

Returns (times, freqs, power) – times the window centres in seconds from the first sample, power of shape (..., n_freqs, n_times), each column exactly multitaper_psd() of that window. A window holding any NaN/inf is NaN (missing), never estimated across the gap. Windows are processed chunk at a time to bound memory.

brainmaze_eeg.spectral.normalize_spectrogram(power, mode: str = 'db', baseline: ndarray | None = None)#

Express a spectrogram (..., n_freqs, n_times) for display.

mode: 'db' – 10 log10(power); 'zscore' – per frequency, against the mean and SD over baseline time bins (default all); 'baseline' – dB change from the mean over baseline time bins. baseline is a boolean mask over time bins.

brainmaze_eeg.spectral.two_spectrum_test(a: MultitaperSpectrum, b: MultitaperSpectrum, method: str = 'jackknife') → Tuple[ndarray, ndarray]#

Are a and b estimates of the same spectrum? Frequency by frequency.

Returns (ratio, p): a.psd / b.psd and a two-sided p-value per frequency.

  • method='jackknife' (default): ln(a) - ln(b) over the jackknife standard error of both, against a t distribution with K_a + K_b - 2 degrees of freedom (in the spirit of Bokil et al., 2007). Robust to correlated eigenspectra.

  • method='f': the ratio against F(dof_a, dof_b) – exact for independent eigenspectra of a locally flat spectrum, too liberal on steep ones (see the module notes).

The frequency grids must match (same fs and nfft) and the two estimates should share nw and segment length, or one compares different resolutions. Neighbouring frequencies within the bandwidth are not independent – correct for multiple comparisons accordingly.