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:
multitaper_psd()– a power spectral density with confidence intervals (jackknife over the tapers, or chi-square);two_spectrum_test()– are two spectra the same, frequency by frequency?multitaper_spectrogram()andnormalize_spectrogram()– time-frequency power, in dB, as a z-score, or as change from a baseline;band_power()– power integrated over named bands.
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_varanddofhave the input’s leading shape plus a last axis of frequencies.n_tapersis the number of eigenspectra averaged per series (ktimesn_segments);dofthe chi-square degrees of freedom per frequency (2 * n_tapers,n_taperswithinbandwidthof 0 Hz and Nyquist);log_varthe jackknife variance ofln(psd);bandwidththe half-bandwidthWin 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
xalong 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 / THz.k (int, optional) – Number of tapers, default
2 * nw - 1; at most2 * 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
xalong its last axis.Returns
(times, freqs, power)–timesthe window centres in seconds from the first sample,powerof shape(..., n_freqs, n_times), each column exactlymultitaper_psd()of that window. A window holding any NaN/inf is NaN (missing), never estimated across the gap. Windows are processedchunkat 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 overbaselinetime bins (default all);'baseline'– dB change from the mean overbaselinetime bins.baselineis a boolean mask over time bins.
- brainmaze_eeg.spectral.two_spectrum_test(a: MultitaperSpectrum, b: MultitaperSpectrum, method: str = 'jackknife') Tuple[ndarray, ndarray]#
Are
aandbestimates of the same spectrum? Frequency by frequency.Returns
(ratio, p):a.psd / b.psdand 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 withK_a + K_b - 2degrees of freedom (in the spirit of Bokil et al., 2007). Robust to correlated eigenspectra.method='f': the ratio againstF(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
fsandnfft) and the two estimates should sharenwand segment length, or one compares different resolutions. Neighbouring frequencies within the bandwidth are not independent – correct for multiple comparisons accordingly.