Monday, February 22, 2010

Python Filter Design

I've never really done DSP as part of my day job. I've been to a few training classes and have some texts that just scratch the surface of filter design, modulation, and so on. Never really touched Matlab either. But I've gotten into Python, so I found out there are some interesting modules that handle DSP functions and the related math.

So how hard would it be to come up with a FIR filter that meets certain performance requirements? Well, you can play around with the Python SciPy and NumPy libraries and check the performance of your filter in a few easy lines.


"""
Design a FIR filter and show the frequency response in
a few easy lines
"""

from scipy import signal
from pylab import *

"""
Window types: boxcar, triang, blackman, hamming,
hanning, bartlett, parzen, bohman, blackmanharris,
nuttall, barthann, kaiser (needs beta),
gaussian (needs std),
general_gaussian (needs power, width),
slepian (needs width)
"""

def dbPlot(w, h):
plot(w, 20 * log(abs(h)) / log(10))

# firwin(number of taps, cutoff relative to Nyquist
# rate, window type)
b = signal.firwin(31, 0.4, window='nuttall')

# freqz(list of zeroes, list of poles)
(w, h) = signal.freqz(b, 1)

plot(w, log(abs(h))/log(10)*20)
show()


This gives me a nice graphic:



You can play around with different windows, as shown in the code comments, or add taps as needed to get the right transition and attenuation.

1 comment: