Imported Upstream version 3.2.2
[debian/gnuradio] / gnuradio-core / src / python / gnuradio / gruimpl / gnuplot_freqz.py
1 #!/usr/bin/env python
2 #
3 # Copyright 2005,2007 Free Software Foundation, Inc.
4
5 # This file is part of GNU Radio
6
7 # GNU Radio is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3, or (at your option)
10 # any later version.
11
12 # GNU Radio is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16
17 # You should have received a copy of the GNU General Public License
18 # along with GNU Radio; see the file COPYING.  If not, write to
19 # the Free Software Foundation, Inc., 51 Franklin Street,
20 # Boston, MA 02110-1301, USA.
21
22
23 __all__ = ['gnuplot_freqz']
24
25 import tempfile
26 import os
27 import math
28 import numpy
29
30 from gnuradio import gr
31 from gnuradio.gruimpl.freqz import freqz
32
33
34 def gnuplot_freqz (hw, Fs=None, logfreq=False):
35
36     """hw is a tuple of the form (h, w) where h is sequence of complex
37     freq responses, and w is a sequence of corresponding frequency
38     points.  Plot the frequency response using gnuplot.  If Fs is
39     provide, use it as the sampling frequency, else use 2*pi.
40
41     Returns a handle to the gnuplot graph. When the handle is reclaimed
42     the graph is torn down."""
43     
44     data_file = tempfile.NamedTemporaryFile ()
45     cmd_file = os.popen ('gnuplot', 'w')
46
47     h, w = hw
48     ampl = 20 * numpy.log10 (numpy.absolute (h) + 1e-9)
49     phase = map (lambda x: math.atan2 (x.imag, x.real), h)
50     
51     if Fs:
52         w *= (Fs/(2*math.pi))
53
54     for freq, a, ph in zip (w, ampl, phase):
55         data_file.write ("%g\t%g\t%g\n" % (freq, a, ph))
56
57     data_file.flush ()
58
59     cmd_file.write ("set grid\n")
60     if logfreq:
61         cmd_file.write ("set logscale x\n")
62     else:
63         cmd_file.write ("unset logscale x\n")
64     cmd_file.write ("plot '%s' using 1:2 with lines\n" % (data_file.name,))
65     cmd_file.flush ()
66     
67     return (cmd_file, data_file)
68
69
70 def test_plot ():
71     sample_rate = 2.0e6
72     taps = gr.firdes.low_pass (1.0,           # gain
73                                sample_rate,   # sampling rate
74                                200e3,         # low pass cutoff freq
75                                100e3,         # width of trans. band
76                                gr.firdes.WIN_HAMMING)
77     # print len (taps)
78     return gnuplot_freqz (freqz (taps, 1), sample_rate)
79
80 if __name__ == '__main__':
81     handle = test_plot ()
82     raw_input ('Press Enter to continue: ')