Using Python to design FIR filter

 

FIR

Scientific calculation in python is easy and effective. With matplotlib and numpy, we have some powerful tools to visualize and calculate.

In this example python and pylab (which includes matplotlib and numpy) is used to calculate coefficients for a FIR filter and afterwards the results are plotted.

To design the filter the window method is used. In our example we design a typ 1 filter. So first we calculate our coefficients with the approach that we want to get an ideal rectangle in the frequency domain. This rectangle transformed into the time domain is the sinc function. See formula 1. Now we sample this function for the number of tabs with our sample frequency to get our coefficients. The calculation in the code is separated in a function, which returns x and y values for the time plot.

(1)   \begin{equation*} rect(\frac{f}{2f_g}) \rightarrow =2*f_g*si(2*\pi*t*f_g) \end{equation*}

Now we add a hamming window to smooth the time domain. And get less overshoot in the frequency domain.

To get the frequency domain we do a fft and show the result in a subplot.

#Author: Tobias Markus
import pylab as p
 
def calcCoef(fg,fs,tabs):
    x = p.linspace(-(tabs-1)/2.0,(tabs-1)/2.0,tabs)*2.0/p.double(fs)
    y = p.sinc(p.double(fg)*p.double(x))
    y = y/sum(y)
    return x,y
 
# parameters for the FIR filter
fg = 1500 
fs = 10000
tabs = 101
 
# get x and y values of the time domain
x = calcCoef(fg,fs,tabs)[0]
y = calcCoef(fg,fs,tabs)[1]
 
# add window
y = y*p.hamming(tabs)
 
# calculate frequency domain
y_fft = abs(p.fft(y,fs))[0:fs/2.0]
 
# setting up the plots
p.subplot(2,1,1)
p.plot(x,y,"b*")
p.ylabel("amplitude")
p.xlabel("time in s")
p.title("time domain")
 
p.subplot(2,1,2)
p.semilogy(y_fft,"b")
p.ylabel("magnitude in dB")
p.xlabel("frequency in Hz")
p.title("frequency domain")
 
p.subplots_adjust(hspace=0.5)
p.show()

 

Dieser Beitrag wurde unter DSP, Python abgelegt und mit , , , verschlagwortet. Setze ein Lesezeichen auf den Permalink.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht.

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.