smooth_window#

pypillometry.signal.smooth_window(x, window_len=11, window='hanning', direction='center')[source]#

Smooth the data using a window with requested size.

This method is based on the convolution of a scaled window with the signal. The direction parameter controls whether the smoothing uses past, future, or both samples relative to each point.

Note: If using backward or forward smoothing, the smoothed signal will be shifted by half the window size. This is intentional for onset and offset detection, where the smoothed signal is used to detect the onset and offset of the blink.

Adapted from SciPy Cookbook: https://scipy-cookbook.readthedocs.io/items/SignalSmooth.html.

Parameters:
  • x (np.ndarray) – The input signal

  • window_len (int) – The dimension of the smoothing window; should be an odd integer

  • window (str) – The type of window from ‘flat’, ‘hanning’, ‘hamming’, ‘bartlett’, ‘blackman’. ‘flat’ window will produce a moving average smoothing.

  • direction (str) –

    • ‘center’: symmetric smoothing using both past and future samples (default)

    • ’backward’: only uses current and past samples (useful for onset detection before missing data, where future NaN shouldn’t affect the estimate)

    • ’forward’: only uses current and future samples (useful for offset detection after missing data, where past NaN shouldn’t affect the estimate)

Return type:

np.ndarray

Returns:

The smoothed signal (same length as input)

Examples

>>> rng = np.random.default_rng(0)
>>> signal = np.sin(np.linspace(0, 10, 200)) + rng.normal(0, 0.1, 200)
>>> # Standard centered smoothing
>>> smoothed = smooth_window(signal, window_len=11, window='hanning')
>>> smoothed.shape
(200,)
>>> # Backward-looking for onset detection
>>> smoothed_back = smooth_window(signal, window_len=11, direction='backward')
>>> # Forward-looking for offset detection
>>> smoothed_fwd = smooth_window(signal, window_len=11, direction='forward')