Go to the documentation of this file.00001
00002
00003
00004
00005
00006 import numpy
00007
00008 def smooth(x,window_len=11,window='hanning'):
00009 """smooth the data using a window with requested size.
00010
00011 This method is based on the convolution of a scaled window with the signal.
00012 The signal is prepared by introducing reflected copies of the signal
00013 (with the window size) in both ends so that transient parts are minimized
00014 in the begining and end part of the output signal.
00015
00016 input:
00017 x: the input signal
00018 window_len: the dimension of the smoothing window; should be an odd integer
00019 window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'
00020 flat window will produce a moving average smoothing.
00021
00022 output:
00023 the smoothed signal
00024
00025 example:
00026
00027 t=linspace(-2,2,0.1)
00028 x=sin(t)+randn(len(t))*0.1
00029 y=smooth(x)
00030
00031 see also:
00032
00033 numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve
00034 scipy.signal.lfilter
00035
00036 TODO: the window parameter could be the window itself if an array instead of a string
00037 NOTE: length(output) != length(input), to correct this: return y[(window_len/2-1):-(window_len/2)] instead of just y.
00038 """
00039
00040 if x.ndim != 1:
00041 raise ValueError, "smooth only accepts 1 dimension arrays."
00042
00043 if x.size < window_len:
00044 raise ValueError, "Input vector needs to be bigger than window size."
00045
00046
00047 if window_len<3:
00048 return x
00049
00050
00051 if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
00052 raise ValueError, "Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'"
00053
00054
00055 s=numpy.r_[x[window_len-1:0:-1],x,x[-1:-window_len:-1]]
00056
00057 if window == 'flat':
00058 w=numpy.ones(window_len,'d')
00059 else:
00060 w=eval('numpy.'+window+'(window_len)')
00061
00062 y=numpy.convolve(w/w.sum(),s,mode='valid')
00063 return y
00064
00065
00066
00067
00068
00069 if __name__=='__main__':
00070 from numpy import *
00071 from pylab import *
00072
00073 t=linspace(-4,4,100)
00074 x=sin(t)
00075 xn=x+randn(len(t))*0.1
00076 y=smooth(x)
00077
00078 ws=31
00079
00080 subplot(211)
00081 plot(ones(ws))
00082
00083 windows=['flat', 'hanning', 'hamming', 'bartlett', 'blackman']
00084
00085 hold(True)
00086 for w in windows[1:]:
00087 eval('plot('+w+'(ws) )')
00088
00089 axis([0,30,0,1.1])
00090
00091 legend(windows)
00092 title("The smoothing windows")
00093 subplot(212)
00094 plot(x)
00095 plot(xn)
00096 for w in windows:
00097 plot(smooth(xn,10,w))
00098 l=['original signal', 'signal with noise']
00099 l.extend(windows)
00100
00101 legend(l)
00102 title("Smoothing a noisy signal")
00103 show()
00104
00105
hrl_lib
Author(s): Cressel Anderson, Travis Deyle, Advait Jain, Hai Nguyen, Advisor: Prof. Charlie Kemp, Lab: Healthcare Robotics Lab at Georgia Tech
autogenerated on Wed Nov 27 2013 11:34:06