signal smooth filtering (include moving average algorithm)

import numpy

def smooth(x,window_len=5,window=’hanning’):

“””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:
x: the input signal
window_len: 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)
x=sin(t)+randn(len(t))*0.1
y=smooth(x)

see also:

numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve
scipy.signal.lfilter

TODO: the window parameter could be the window itself if an array instead of a string
NOTE: length(output) != length(input), to correct this: return y[(window_len/2-1):-(window_len/2)] instead of just y.
“””

if x.ndim != 1:
raise ValueError, “smooth only accepts 1 dimension arrays.”

if x.size < window_len:
raise ValueError, “Input vector needs to be bigger than window size.”

if (window_len/2.0-int(window_len/2.0))==0:
raise ValueError, “Window length is not a odd number.”

if window_len<3:
return x
if not window in [‘flat’, ‘hanning’, ‘hamming’, ‘bartlett’, ‘blackman’]:
raise ValueError, “Window is on of ‘flat’, ‘hanning’, ‘hamming’, ‘bartlett’, ‘blackman'”

print(window_len)
s=numpy.r_[x[window_len-1:0:-1],x,x[-1:-window_len:-1]]

xDim_temp = x.shape
xDim = xDim_temp[0]

#print(len(s))
if window == ‘flat’: #moving average
w=numpy.ones(window_len,’d’)
else:
w=eval(‘numpy.’+window+'(window_len)’)

y=numpy.convolve(w/w.sum(),s,mode=’valid’)

yret = numpy.zeros(xDim)
for i in range(0,xDim):
yret[i] = y[i+(window_len-1)/2]
return yret

This entry was posted in Fundamental. Bookmark the permalink.

2 Responses to signal smooth filtering (include moving average algorithm)

  1. i’m seeing the site only now and really loved it! i love your post is so cool! lista de emails lista de emails lista de emails lista de emails lista de emails

Leave a Reply

Your email address will not be published. Required fields are marked *