How To Apply A Binomial Low Pass Filter To Data In A Numpy Array?
Solution 1:
A binomial filter is a FIR filter whose coefficients can be generated by taking a row from Pascal's triangle. A quick way ("quick" as in just one line of code--not necessarily the most efficient) is with numpy.poly1d
:
In [15]: np.poly1d([1, 1])**2
Out[15]: poly1d([1, 2, 1])
In [16]: np.poly1d([1, 1])**3
Out[16]: poly1d([1, 3, 3, 1])
In [17]: np.poly1d([1, 1])**4
Out[17]: poly1d([1, 4, 6, 4, 1])
To use a set of these coefficients as a low pass filter, the values must be normalization so the sum is one. The sum of the coefficients of np.poly1d([1, 1])**n
is 2**n
, so we could divide the above result by 2**n
. Alternatively, we can generate coefficients that are already normalized by giving numpy.poly1d
[1/2, 1/2] instead of [1, 1]
(i.e. start with a normalized set of two coefficients). This function generates the filter coefficients for a given n:
defbinomcoeffs(n):
return (np.poly1d([0.5, 0.5])**n).coeffs
For example,
In [35]: binomcoeffs(3)
Out[35]: array([0.125, 0.375, 0.375, 0.125])
In [36]: binomcoeffs(5)
Out[36]: array([0.03125, 0.15625, 0.3125 , 0.3125 , 0.15625, 0.03125])
In [37]: binomcoeffs(15)
Out[37]:
array([3.05175781e-05, 4.57763672e-04, 3.20434570e-03, 1.38854980e-02,
4.16564941e-02, 9.16442871e-02, 1.52740479e-01, 1.96380615e-01,
1.96380615e-01, 1.52740479e-01, 9.16442871e-02, 4.16564941e-02,
1.38854980e-02, 3.20434570e-03, 4.57763672e-04, 3.05175781e-05])
To apply the filter to a signal, use convolution. There are several discrete convolution functions available, including numpy.convolve
, scipy.signal.convolve
, scipy.ndimage.convolve1d
. You can also use scipy.signal.lfilter
(give the coefficients as the b
argument, and set a=1
).
For concrete examples, check out "Applying a FIR filter", a short article that I wrote several years ago (and that has been edited by others since then). Note that the timings shown in that article might not be up-to-date. The code in both NumPy and SciPy is continually evolving. If you run those scripts now, you might get radically different results.
Post a Comment for "How To Apply A Binomial Low Pass Filter To Data In A Numpy Array?"