19 from math
import factorial
23 r"""Smooth (and optionally differentiate) data with a Savitzky-Golay filter. 24 The Savitzky-Golay filter removes high frequency noise from data. 25 It has the advantage of preserving the original shape and 26 features of the signal better than other types of filtering 27 approaches, such as moving averages techniques. 30 y : array_like, shape (N,) 31 the values of the time history of the signal. 33 the length of the window. Must be an odd integer number. 35 the order of the polynomial used in the filtering. 36 Must be less then `window_size` - 1. 38 the order of the derivative to compute (default = 0 means only smoothing) 41 ys : ndarray, shape (N) 42 the smoothed signal (or it's n-th derivative). 45 The Savitzky-Golay is a type of low-pass filter, particularly 46 suited for smoothing noisy data. The main idea behind this 47 approach is to make for each point a least-square fit with a 48 polynomial of high order over a odd-sized window centered at 52 t = np.linspace(-4, 4, 500) 53 y = np.exp( -t**2 ) + np.random.normal(0, 0.05, t.shape) 54 ysg = savitzky_golay(y, window_size=31, order=4) 55 import matplotlib.pyplot as plt 56 plt.plot(t, y, label='Noisy signal') 57 plt.plot(t, np.exp(-t**2), 'k', lw=1.5, label='Original signal') 58 plt.plot(t, ysg, 'r', label='Filtered signal')
63 .. [1] A. Savitzky, M. J. E. Golay, Smoothing and Differentiation of
64 Data by Simplified Least Squares Procedures. Analytical
65 Chemistry, 1964, 36 (8), pp 1627-1639.
66 .. [2] Numerical Recipes 3rd Edition: The Art of Scientific Computing
67 W.H. Press, S.A. Teukolsky, W.T. Vetterling, B.P. Flannery
68 Cambridge University Press ISBN-13: 9780521880688
71 def __init__(self, window_size, order, deriv=0, rate=1):
73 self.window_size = window_size
79 self.window_size = np.abs(np.int(self.window_size))
80 self.order = np.abs(np.int(self.order))
81 except ValueError as msg:
82 raise ValueError("ValueError: window_size and order have to be of type int - {}".format(msg))
83 if self.window_size % 2 != 1 or self.window_size < 1:
84 raise TypeError("window_size size must be a positive odd number")
85 if self.window_size < self.order + 2:
86 raise TypeError("window_size is too small for the polynomials order")
90 self.order_range = list(range(self.order+1))
91 half_window = (self.window_size -1) // 2
92 # precompute coefficients
93 b = np.mat([[k**i for i in self.order_range] for k in range(-half_window, half_window+1)])
94 m = np.linalg.pinv(b).A[self.deriv] * self.rate**self.deriv * factorial(self.deriv)
95 # pad the signal at the extremes with
96 # values taken from the signal itself
97 firstvals = y[0] - np.abs( y[1:half_window+1][::-1] - y[0] )
98 lastvals = y[-1] + np.abs(y[-half_window-1:-1][::-1] - y[-1])
99 y = np.concatenate((firstvals, y, lastvals))
100 return np.convolve( m[::-1], y, mode='valid')
102 if __name__ == "__main__":
104 # create some sample twoD data
105 x = np.linspace(-3,3,100)
106 Z = np.exp( np.negative(x))
109 Zn = Z + np.random.normal( 0, 0.2, Z.shape )
111 sg = savitzky_golay(window_size=29, order=4)