2d0c72c7621e73dd16ad83db52ddcadb6ba24d7f
[debian/gnuradio] / gr-utils / src / python / gr_filter_design.py
1 #!/usr/bin/env python
2
3 try:
4     import scipy
5     from scipy import fftpack
6 except ImportError:
7     print "Please install SciPy to run this script (http://www.scipy.org/)"
8     raise SystemExit, 1
9
10 import sys, os
11 from PyQt4 import Qt, QtCore, QtGui
12 import PyQt4.Qwt5 as Qwt
13 from optparse import OptionParser
14 from gnuradio import gr, blks2, eng_notation
15 from scipy import fftpack
16
17 from pyqt_filter import Ui_MainWindow
18 from pyqt_filter_firlpf import Ui_firlpfForm
19 from pyqt_filter_firhpf import Ui_firhpfForm
20
21 class gr_plot_filter(QtGui.QMainWindow):
22     def __init__(self, qapp, options):
23         QtGui.QWidget.__init__(self, None)
24         self.gui = Ui_MainWindow()
25         self.gui.setupUi(self)
26
27         self.connect(self.gui.filterTypeComboBox,
28                      Qt.SIGNAL("currentIndexChanged(const QString&)"),
29                      self.changed_filter_type)
30         self.connect(self.gui.filterDesignTypeComboBox,
31                      Qt.SIGNAL("currentIndexChanged(const QString&)"),
32                      self.changed_filter_design_type)
33
34         self.connect(self.gui.designButton,
35                      Qt.SIGNAL("released()"),
36                      self.design)
37
38         self.connect(self.gui.tabGroup,
39                      Qt.SIGNAL("currentChanged(int)"),
40                      self.tab_changed)
41
42         self.connect(self.gui.nfftEdit,
43                      Qt.SIGNAL("textEdited(QString)"),
44                      self.nfft_edit_changed)
45
46         self.gui.designButton.setShortcut("Return")
47
48         self.taps = []
49         self.fftdB = []
50         self.fftDeg = []
51         self.groupDelay = []
52         self.nfftpts = int(10000)
53         self.gui.nfftEdit.setText(Qt.QString("%1").arg(self.nfftpts))
54
55         self.gui.lpfPassBandRippleLabel.setVisible(False)
56         self.gui.lpfPassBandRippleEdit.setVisible(False)
57         self.gui.bpfPassBandRippleLabel.setVisible(False)
58         self.gui.bpfPassBandRippleEdit.setVisible(False)
59         self.gui.hpfPassBandRippleLabel.setVisible(False)
60         self.gui.hpfPassBandRippleEdit.setVisible(False)
61                 
62         # Initialize to LPF
63         self.gui.filterTypeWidget.setCurrentWidget(self.gui.firlpfPage)
64
65         # Set Axis labels
66         self.gui.freqPlot.setAxisTitle(self.gui.freqPlot.xBottom,
67                                        "Frequency (Hz)")
68         self.gui.freqPlot.setAxisTitle(self.gui.freqPlot.yLeft,
69                                        "Magnitude (dB)")
70         self.gui.timePlot.setAxisTitle(self.gui.timePlot.xBottom,
71                                        "Tap number")
72         self.gui.timePlot.setAxisTitle(self.gui.timePlot.yLeft,
73                                        "Amplitude")
74         self.gui.phasePlot.setAxisTitle(self.gui.phasePlot.xBottom,
75                                         "Frequency (Hz)")
76         self.gui.phasePlot.setAxisTitle(self.gui.phasePlot.yLeft,
77                                         "Phase (Radians)")
78         self.gui.groupPlot.setAxisTitle(self.gui.groupPlot.xBottom,
79                                         "Frequency (Hz)")
80         self.gui.groupPlot.setAxisTitle(self.gui.groupPlot.yLeft,
81                                         "Delay (sec)")
82
83         # Set up plot curves
84         self.rcurve = Qwt.QwtPlotCurve("Real")
85         self.rcurve.attach(self.gui.timePlot)
86         self.icurve = Qwt.QwtPlotCurve("Imag")
87         self.icurve.attach(self.gui.timePlot)
88
89         self.freqcurve = Qwt.QwtPlotCurve("PSD")
90         self.freqcurve.attach(self.gui.freqPlot)
91
92         self.phasecurve = Qwt.QwtPlotCurve("Phase")
93         self.phasecurve.attach(self.gui.phasePlot)
94
95         self.groupcurve = Qwt.QwtPlotCurve("Group Delay")
96         self.groupcurve.attach(self.gui.groupPlot)
97
98         # Create zoom functionality for the plots
99         self.timeZoomer = Qwt.QwtPlotZoomer(self.gui.timePlot.xBottom,
100                                             self.gui.timePlot.yLeft,
101                                             Qwt.QwtPicker.PointSelection,
102                                             Qwt.QwtPicker.AlwaysOn,
103                                             self.gui.timePlot.canvas())
104
105         self.freqZoomer = Qwt.QwtPlotZoomer(self.gui.freqPlot.xBottom,
106                                             self.gui.freqPlot.yLeft,
107                                             Qwt.QwtPicker.PointSelection,
108                                             Qwt.QwtPicker.AlwaysOn,
109                                             self.gui.freqPlot.canvas())
110
111         self.phaseZoomer = Qwt.QwtPlotZoomer(self.gui.phasePlot.xBottom,
112                                              self.gui.phasePlot.yLeft,
113                                              Qwt.QwtPicker.PointSelection,
114                                              Qwt.QwtPicker.AlwaysOn,
115                                              self.gui.phasePlot.canvas())
116
117         self.groupZoomer = Qwt.QwtPlotZoomer(self.gui.groupPlot.xBottom,
118                                              self.gui.groupPlot.yLeft,
119                                              Qwt.QwtPicker.PointSelection,
120                                              Qwt.QwtPicker.AlwaysOn,
121                                              self.gui.groupPlot.canvas())
122
123         # Set up pen for colors and line width
124         blue = QtGui.qRgb(0x00, 0x00, 0xFF)
125         blueBrush = Qt.QBrush(Qt.QColor(blue))
126         self.freqcurve.setPen(Qt.QPen(blueBrush, 2))
127         self.rcurve.setPen(Qt.QPen(blueBrush, 2))
128         self.phasecurve.setPen(Qt.QPen(blueBrush, 2))
129         self.groupcurve.setPen(Qt.QPen(blueBrush, 2))
130         
131         self.filterWindows = {"Hamming Window" : gr.firdes.WIN_HAMMING,
132                               "Hann Window" : gr.firdes.WIN_HANN,
133                               "Blackman Window" : gr.firdes.WIN_BLACKMAN,
134                               "Rectangular Window" : gr.firdes.WIN_RECTANGULAR,
135                               "Kaiser Window" : gr.firdes.WIN_KAISER,
136                               "Blackman-harris Window" : gr.firdes.WIN_BLACKMAN_hARRIS}
137
138         self.show()
139
140     def changed_filter_type(self, ftype):
141         strftype = str(ftype.toAscii())
142         if(ftype == "Low Pass"):
143             self.gui.filterTypeWidget.setCurrentWidget(self.gui.firlpfPage)
144         elif(ftype == "Band Pass"):
145             self.gui.filterTypeWidget.setCurrentWidget(self.gui.firbpfPage)
146         elif(ftype == "Complex Band Pass"):
147             self.gui.filterTypeWidget.setCurrentWidget(self.gui.firbpfPage)
148         elif(ftype == "Band Notch"):
149             self.gui.filterTypeWidget.setCurrentWidget(self.gui.firbnfPage)
150         elif(ftype == "High Pass"):
151             self.gui.filterTypeWidget.setCurrentWidget(self.gui.firhpfPage)
152         elif(ftype == "Root Raised Cosine"):
153             self.gui.filterTypeWidget.setCurrentWidget(self.gui.rrcPage)
154
155         self.design()
156         
157     def changed_filter_design_type(self, design):
158         if(design == "Equiripple"):
159             self.set_equiripple()
160         else:
161             self.set_windowed()
162             
163         self.design()
164
165     def set_equiripple(self):
166         self.equiripple = True
167         self.gui.lpfPassBandRippleLabel.setVisible(True)
168         self.gui.lpfPassBandRippleEdit.setVisible(True)
169         self.gui.bpfPassBandRippleLabel.setVisible(True)
170         self.gui.bpfPassBandRippleEdit.setVisible(True)
171         self.gui.hpfPassBandRippleLabel.setVisible(True)
172         self.gui.hpfPassBandRippleEdit.setVisible(True)
173         
174     def set_windowed(self):
175         self.equiripple = False
176         self.gui.lpfPassBandRippleLabel.setVisible(False)
177         self.gui.lpfPassBandRippleEdit.setVisible(False)
178         self.gui.bpfPassBandRippleLabel.setVisible(False)
179         self.gui.bpfPassBandRippleEdit.setVisible(False)
180         self.gui.hpfPassBandRippleLabel.setVisible(False)
181         self.gui.hpfPassBandRippleEdit.setVisible(False)
182         
183     def design(self):
184         ret = True
185         fs,r = self.gui.sampleRateEdit.text().toDouble()
186         ret = r and ret
187         gain,r = self.gui.filterGainEdit.text().toDouble()
188         ret = r and ret
189
190         if(ret):
191             winstr = str(self.gui.filterDesignTypeComboBox.currentText().toAscii())
192             ftype = str(self.gui.filterTypeComboBox.currentText().toAscii())
193
194             if(winstr == "Equiripple"):
195                 designer = {"Low Pass" : self.design_opt_lpf,
196                             "Band Pass" : self.design_opt_bpf,
197                             "High Pass" :  self.design_opt_hpf}        
198                 taps,r = designer[ftype](fs, gain)
199
200             else:
201                 designer = {"Low Pass" : self.design_win_lpf,
202                             "Band Pass" : self.design_win_bpf,
203                             "Complex Band Pass" : self.design_win_cbpf,
204                             "Band Notch" : self.design_win_bnf,
205                             "High Pass" :  self.design_win_hpf,
206                             "Root Raised Cosine" :  self.design_win_rrc}
207                 wintype = self.filterWindows[winstr]
208                 taps,r = designer[ftype](fs, gain, wintype)
209
210             if(r):
211                 self.taps = scipy.array(taps)
212                 self.get_fft(fs, self.taps, self.nfftpts)
213                 self.update_time_curves()
214                 self.update_freq_curves()
215                 self.update_phase_curves()
216                 self.update_group_curves()
217
218     # Filter design functions using a window
219     def design_win_lpf(self, fs, gain, wintype):
220         ret = True
221         pb,r = self.gui.endofLpfPassBandEdit.text().toDouble()
222         ret = r and ret
223         sb,r = self.gui.startofLpfStopBandEdit.text().toDouble()
224         ret = r and ret
225         atten,r = self.gui.lpfStopBandAttenEdit.text().toDouble()
226         ret = r and ret
227
228         if(ret):
229             tb = sb - pb
230             
231             taps = gr.firdes.low_pass_2(gain, fs, pb, tb,
232                                         atten, wintype)
233             return (taps, ret)
234         else:
235             return ([], ret)
236     
237     def design_win_bpf(self, fs, gain, wintype):
238         ret = True
239         pb1,r = self.gui.startofBpfPassBandEdit.text().toDouble()
240         ret = r and ret
241         pb2,r = self.gui.endofBpfPassBandEdit.text().toDouble()
242         ret = r and ret
243         tb,r  = self.gui.bpfTransitionEdit.text().toDouble()
244         ret = r and ret
245         atten,r = self.gui.bpfStopBandAttenEdit.text().toDouble()
246         ret = r and ret
247
248         if(r):
249             taps = gr.firdes.band_pass_2(gain, fs, pb1, pb2, tb,
250                                          atten, wintype)
251             return (taps,r)
252         else:
253             return ([],r)
254
255     def design_win_cbpf(self, fs, gain, wintype):
256         ret = True
257         pb1,r = self.gui.startofBpfPassBandEdit.text().toDouble()
258         ret = r and ret
259         pb2,r = self.gui.endofBpfPassBandEdit.text().toDouble()
260         ret = r and ret
261         tb,r  = self.gui.bpfTransitionEdit.text().toDouble()
262         ret = r and ret
263         atten,r = self.gui.bpfStopBandAttenEdit.text().toDouble()
264         ret = r and ret
265
266         if(r):
267             taps = gr.firdes.complex_band_pass_2(gain, fs, pb1, pb2, tb,
268                                                  atten, wintype)
269             return (taps,r)
270         else:
271             return ([],r)
272
273     def design_win_bnf(self, fs, gain, wintype):
274         ret = True
275         pb1,r = self.gui.startofBnfStopBandEdit.text().toDouble()
276         ret = r and ret
277         pb2,r = self.gui.endofBnfStopBandEdit.text().toDouble()
278         ret = r and ret
279         tb,r  = self.gui.bnfTransitionEdit.text().toDouble()
280         ret = r and ret
281         atten,r = self.gui.bnfStopBandAttenEdit.text().toDouble()
282         ret = r and ret
283
284         if(r):
285             taps = gr.firdes.band_reject_2(gain, fs, pb1, pb2, tb,
286                                            atten, wintype)
287             return (taps,r)
288         else:
289             return ([],r)
290
291     def design_win_hpf(self, fs, gain, wintype):
292         ret = True
293         sb,r = self.gui.endofHpfStopBandEdit.text().toDouble()
294         ret = r and ret
295         pb,r = self.gui.startofHpfPassBandEdit.text().toDouble()
296         ret = r and ret
297         atten,r = self.gui.hpfStopBandAttenEdit.text().toDouble()
298         ret = r and ret
299
300         if(r):
301             tb = pb - sb
302             taps = gr.firdes.high_pass_2(gain, fs, pb, tb,
303                                          atten, wintype)            
304             return (taps,r)
305         else:
306             return ([],r)
307
308     def design_win_rrc(self, fs, gain, wintype):
309         ret = True
310         sr,r = self.gui.rrcSymbolRateEdit.text().toDouble()
311         ret = r and ret
312         alpha,r = self.gui.rrcAlphaEdit.text().toDouble()
313         ret = r and ret
314         ntaps,r = self.gui.rrcNumTapsEdit.text().toInt()
315         ret = r and ret
316
317         if(r):
318             taps = gr.firdes.root_raised_cosine(gain, fs, sr,
319                                                 alpha, ntaps)
320             return (taps,r)
321         else:
322             return ([],r)
323
324     # Design Functions for Equiripple Filters
325     def design_opt_lpf(self, fs, gain, wintype=None):
326         ret = True
327         pb,r = self.gui.endofLpfPassBandEdit.text().toDouble()
328         ret = r and ret
329         sb,r = self.gui.startofLpfStopBandEdit.text().toDouble()
330         ret = r and ret
331         atten,r = self.gui.lpfStopBandAttenEdit.text().toDouble()
332         ret = r and ret
333         ripple,r = self.gui.lpfPassBandRippleEdit.text().toDouble()
334         ret = r and ret
335
336         if(ret):
337             taps = blks2.optfir.low_pass(gain, fs, pb, sb,
338                                          ripple, atten)
339             return (taps, ret)
340         else:
341             return ([], ret)
342     
343     def design_opt_bpf(self, fs, gain, wintype=None):
344         ret = True
345         pb1,r = self.gui.startofBpfPassBandEdit.text().toDouble()
346         ret = r and ret
347         pb2,r = self.gui.endofBpfPassBandEdit.text().toDouble()
348         ret = r and ret
349         tb,r  = self.gui.bpfTransitionEdit.text().toDouble()
350         ret = r and ret
351         atten,r = self.gui.bpfStopBandAttenEdit.text().toDouble()
352         ret = r and ret
353         ripple,r = self.gui.bpfPassBandRippleEdit.text().toDouble()
354         ret = r and ret
355
356         if(r):
357             sb1 = pb1 - tb
358             sb2 = pb2 + tb
359             taps = blks2.optfir.band_pass(gain, fs, sb1, pb1, pb2, sb2,
360                                           ripple, atten)
361             return (taps,r)
362         else:
363             return ([],r)
364
365     def design_opt_hpf(self, fs, gain, wintype=None):
366         ret = True
367         sb,r = self.gui.endofHpfStopBandEdit.text().toDouble()
368         ret = r and ret
369         pb,r = self.gui.startofHpfPassBandEdit.text().toDouble()
370         ret = r and ret
371         atten,r = self.gui.hpfStopBandAttenEdit.text().toDouble()
372         ret = r and ret
373         ripple,r = self.gui.hpfPassBandRippleEdit.text().toDouble()
374         ret = r and ret
375
376         if(r):
377             taps = blks2.optfir.high_pass(gain, fs, sb, pb,
378                                           atten, ripple)
379             return (taps,r)
380         else:
381             return ([],r)
382
383     def nfft_edit_changed(self, nfft):
384         infft,r = nfft.toInt()
385         if(r and (infft != self.nfftpts)):
386             self.nfftpts = infft
387             self.update_freq_curves()
388
389     def tab_changed(self, tab):
390         if(tab == 0):
391             self.update_freq_curves()
392         if(tab == 1):
393             self.update_time_curves()
394         if(tab == 2):
395             self.update_phase_curves()
396         if(tab == 3):
397             self.update_group_curves()
398         
399     def get_fft(self, fs, taps, Npts):
400         Ts = 1.0/fs
401         fftpts = fftpack.fft(taps, Npts)
402         self.freq = scipy.arange(0, fs, 1.0/(Npts*Ts))        
403         self.fftdB = 20.0*scipy.log10(abs(fftpts))
404         self.fftDeg = scipy.unwrap(scipy.angle(fftpts))
405         self.groupDelay = -scipy.diff(self.fftDeg)
406         
407     def update_time_curves(self):
408         ntaps = len(self.taps)
409         if(ntaps > 0):
410             if(type(self.taps[0]) == scipy.complex128):
411                 self.rcurve.setData(scipy.arange(ntaps), self.taps.real)
412                 self.icurve.setData(scipy.arange(ntaps), self.taps.imag)
413             else:
414                 self.rcurve.setData(scipy.arange(ntaps), self.taps)
415
416             # Reset the x-axis to the new time scale
417             ymax = 1.5 * max(self.taps)
418             ymin = 1.5 * min(self.taps)
419             self.gui.timePlot.setAxisScale(self.gui.timePlot.xBottom,
420                                            0, ntaps)
421             self.gui.timePlot.setAxisScale(self.gui.timePlot.yLeft,
422                                            ymin, ymax)
423             
424             # Set the zoomer base to unzoom to the new axis
425             self.timeZoomer.setZoomBase()
426             
427             self.gui.timePlot.replot()
428         
429     def update_freq_curves(self):
430         npts = len(self.fftdB)
431         if(npts > 0):
432             self.freqcurve.setData(self.freq, self.fftdB)
433             
434             # Reset the x-axis to the new time scale
435             ymax = 1.5 * max(self.fftdB[0:npts/2])
436             ymin = 1.1 * min(self.fftdB[0:npts/2])
437             xmax = self.freq[npts/2]
438             xmin = self.freq[0]
439             self.gui.freqPlot.setAxisScale(self.gui.freqPlot.xBottom,
440                                            xmin, xmax)
441             self.gui.freqPlot.setAxisScale(self.gui.freqPlot.yLeft,
442                                            ymin, ymax)
443             
444             # Set the zoomer base to unzoom to the new axis
445             self.freqZoomer.setZoomBase()
446             
447             self.gui.freqPlot.replot()
448
449
450     def update_phase_curves(self):
451         npts = len(self.fftDeg)
452         if(npts > 0):
453             self.phasecurve.setData(self.freq, self.fftDeg)
454             
455             # Reset the x-axis to the new time scale
456             ymax = 1.5 * max(self.fftDeg[0:npts/2])
457             ymin = 1.1 * min(self.fftDeg[0:npts/2])
458             xmax = self.freq[npts/2]
459             xmin = self.freq[0]
460             self.gui.phasePlot.setAxisScale(self.gui.phasePlot.xBottom,
461                                             xmin, xmax)
462             self.gui.phasePlot.setAxisScale(self.gui.phasePlot.yLeft,
463                                             ymin, ymax)
464             
465             # Set the zoomer base to unzoom to the new axis
466             self.phaseZoomer.setZoomBase()
467             
468             self.gui.phasePlot.replot()
469
470     def update_group_curves(self):
471         npts = len(self.groupDelay)
472         if(npts > 0):
473             self.groupcurve.setData(self.freq, self.groupDelay)
474             
475             # Reset the x-axis to the new time scale
476             ymax = 1.5 * max(self.groupDelay[0:npts/2])
477             ymin = 1.1 * min(self.groupDelay[0:npts/2])
478             xmax = self.freq[npts/2]
479             xmin = self.freq[0]
480             self.gui.groupPlot.setAxisScale(self.gui.groupPlot.xBottom,
481                                             xmin, xmax)
482             self.gui.groupPlot.setAxisScale(self.gui.groupPlot.yLeft,
483                                             ymin, ymax)
484             
485             # Set the zoomer base to unzoom to the new axis
486             self.groupZoomer.setZoomBase()
487             
488             self.gui.groupPlot.replot()
489
490
491 def setup_options():
492     usage="%prog: [options] (input_filename)"
493     description = ""
494
495     parser = OptionParser(conflict_handler="resolve",
496                           usage=usage, description=description)
497     return parser
498
499 def main(args):
500     parser = setup_options()
501     (options, args) = parser.parse_args ()
502
503     app = Qt.QApplication(args)
504     gplt = gr_plot_filter(app, options)
505     app.exec_()
506
507 if __name__ == '__main__':
508     main(sys.argv)
509