Skip to content

Instantly share code, notes, and snippets.

@tigerhawkvok
Last active March 17, 2020 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tigerhawkvok/84fd2b0853b19d98f450b727cc288c49 to your computer and use it in GitHub Desktop.
Save tigerhawkvok/84fd2b0853b19d98f450b727cc288c49 to your computer and use it in GitHub Desktop.
Smooth an input signal
#!python3
import numpy as np
from typing import Union
def smooth(inputSignal:Union[list, np.ndarray], windowLength:int= 11, window:str= 'flat') -> np.ndarray:
"""
Smooth the data using a window with requested size.
This method is based on the convolution of a scaled window with the signal.
The signal is prepared by introducing reflected copies of the signal
(with the window size) in both ends so that transient parts are minimized
in the begining and end part of the output signal.
input:
inputSignal: the input signal
windowLength: the dimension of the smoothing window; should be an odd integer
window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'
flat window will produce a moving average smoothing.
output:
the smoothed signal
example:
t = linspace(-2,2,0.1)
inputSignal = sin(t)+randn(len(t))*0.1
y = smooth(inputSignal)
see also:
numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve
scipy.signal.lfilter
# Adapted from https://scipy-cookbook.readthedocs.io/items/SignalSmooth.html
# with only minor changes
"""
#cSpell:ignore hanning, lfilter
assert inputSignal.ndim == 1, "smooth only accepts 1 dimension arrays."
assert isinstance(windowLength, int), "windowLength must be an integer"
assert inputSignal.size > windowLength, "Input vector needs to be bigger than window size."
if windowLength < 3:
return inputSignal
s = np.r_[inputSignal[windowLength - 1:0:-1], inputSignal, inputSignal[-2:-windowLength - 1:-1]]
if window == 'flat':
#moving average
wl = np.ones(windowLength,'d')
else:
if window is "hanning":
wl = np.hanning(windowLength)
elif window is "hamming":
wl = np.hamming(windowLength)
elif window is "bartlett":
wl = np.bartlett(windowLength)
elif window is "blackman":
wl = np.blackman(windowLength)
else:
raise ValueError("Window must be one of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'")
# Do the convolution
y = np.convolve(wl / wl.sum(), s, mode= 'valid')
return y[windowLength // 2 - 1:-windowLength // 2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment