spectrum#
- pypillometry.signal.spectrum(signal, fs, mask=None, window='200 s', overlap=0.5, max_missing=0.3, segments=None, detrend='linear', taper='hann')[source]#
Power spectral density of a signal with missing samples (Welch’s method).
- Parameters:
signal (np.ndarray or np.ma.MaskedArray) – the signal, sampled at fs; masked, NaN and inf samples are missing
fs (float) – sampling rate in Hz
mask (np.ndarray, optional) – boolean array, True for additional missing samples
window (float, str or Quantity, optional) – length of the windows (plain numbers are ms; default 200 s). The lowest frequency of the spectrum is one cycle per window. Limited to the length of the longest segment.
overlap (float, optional) – overlap of neighbouring windows as a fraction of their length (default 0.5)
max_missing (float, optional) – windows with a larger fraction of missing samples are skipped (default 0.3). The gaps in the windows that are used are bridged linearly, which removes power at high frequencies in proportion to the amount of missing data.
segments (list of (start, stop), optional) – sample indices of segments (e.g., blocks of an experiment); windows lie within one segment. Default: the whole signal.
detrend ({"linear", "constant"} or False, optional) – trend removed from each window before the transform (default “linear”)
taper (str, optional) – window function from
scipy.signal.get_window()(default “hann”)
- Return type:
- Returns:
named tuple
(freqs, power, nwindows, window)
Examples
White noise with standard deviation 2 at 100 Hz has a flat spectrum of
2**2 / (fs / 2):>>> rng = np.random.default_rng(0) >>> x = rng.normal(0, 2, 60000) >>> sp = spectrum(x, fs=100, window="10 s") >>> sp.nwindows, float(sp.freqs[0]) (119, 0.1) >>> bool(np.isclose(sp.power.mean(), 4 / 50, rtol=0.02)) True