]> git.gag.com Git - debian/gnuradio/blob - gnuradio-core/src/utils/gr_plot_fft_f.py
Merging ofdm2 branch -r7047:7321 into trunk. This updates the OFDM code to hier_block...
[debian/gnuradio] / gnuradio-core / src / utils / gr_plot_fft_f.py
1 #!/usr/bin/env python
2 #
3 # Copyright 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 import scipy
24 from pylab import *
25 from optparse import OptionParser
26 from scipy import fftpack
27 from math import log10
28
29 matplotlib.interactive(True)
30 matplotlib.use('TkAgg')
31
32 class draw_fft_f:
33     def __init__(self, filename, options):
34         self.hfile = open(filename, "r")
35         self.block_length = options.block
36         self.start = options.start
37         self.sample_rate = options.sample_rate
38
39         self.axis_font_size = 16
40         self.label_font_size = 18
41         self.title_font_size = 20
42         self.text_size = 22
43
44         # Setup PLOT
45         self.fig = figure(1, figsize=(16, 9), facecolor='w')
46         rcParams['xtick.labelsize'] = self.axis_font_size
47         rcParams['ytick.labelsize'] = self.axis_font_size
48         
49         self.text_file     = figtext(0.10, 0.94, ("File: %s" % filename), weight="heavy", size=self.text_size)
50         self.text_file_pos = figtext(0.10, 0.88, "File Position: ", weight="heavy", size=self.text_size)
51         self.text_block    = figtext(0.40, 0.88, ("Block Size: %d" % self.block_length),
52                                      weight="heavy", size=self.text_size)
53         self.text_sr       = figtext(0.60, 0.88, ("Sample Rate: %.2f" % self.sample_rate),
54                                      weight="heavy", size=self.text_size)
55         self.make_plots()
56
57         self.button_left_axes = self.fig.add_axes([0.45, 0.01, 0.05, 0.05], frameon=True)
58         self.button_left = Button(self.button_left_axes, "<")
59         self.button_left_callback = self.button_left.on_clicked(self.button_left_click)
60
61         self.button_right_axes = self.fig.add_axes([0.50, 0.01, 0.05, 0.05], frameon=True)
62         self.button_right = Button(self.button_right_axes, ">")
63         self.button_right_callback = self.button_right.on_clicked(self.button_right_click)
64
65         self.xlim = self.sp_f.get_xlim()
66
67         self.manager = get_current_fig_manager()
68         connect('draw_event', self.zoom)
69         connect('key_press_event', self.click)
70         show()
71         
72     def get_data(self):
73         self.text_file_pos.set_text("File Position: %d" % (self.hfile.tell()//4))
74         self.floats = scipy.fromfile(self.hfile, dtype=scipy.float32, count=self.block_length)
75         #print "Read in %d items" % len(self.floats)
76         if(len(self.floats) == 0):
77             print "End of File"
78         else:
79             self.f_fft = self.dofft(self.floats)
80
81             self.time = [i*(1/self.sample_rate) for i in range(len(self.floats))]
82             self.freq = self.calc_freq(self.time, self.sample_rate)
83             
84     def dofft(self, f):
85         N = len(f)
86         f_fft = fftpack.fftshift(scipy.fft(f))       # fft and shift axis
87         f_dB = list()
88         for f in f_fft:
89             try:
90                 f_dB.append(20*log10(abs(f/N)))  # convert to decibels, adjust power
91             except OverflowError:                # protect against taking log(0)
92                 f = 1e-14                        # not sure if this is the best way to do this
93                 f_dB.append(20*log10(abs(f/N)))
94                 
95         return f_dB
96
97     def calc_freq(self, time, sample_rate):
98         N = len(time)
99         Fs = 1.0 / (max(time) - min(time))
100         Fn = 0.5 * sample_rate
101         freq = [-Fn + i*Fs for i in range(N)]
102         return freq
103         
104     def make_plots(self):
105         # if specified on the command-line, set file pointer
106         self.hfile.seek(16*self.start, 1)
107
108         self.get_data()
109         
110         # Subplot for real and imaginary parts of signal
111         self.sp_f = self.fig.add_subplot(2,1,1, position=[0.075, 0.2, 0.4, 0.6])
112         self.sp_f.set_title(("Amplitude"), fontsize=self.title_font_size, fontweight="bold")
113         self.sp_f.set_xlabel("Time (s)", fontsize=self.label_font_size, fontweight="bold")
114         self.sp_f.set_ylabel("Amplitude (V)", fontsize=self.label_font_size, fontweight="bold")
115         self.plot_f = plot(self.time, self.floats, 'bo-')
116         self.sp_f.set_ylim([1.5*min(self.floats),
117                             1.5*max(self.floats)])
118
119         # Subplot for constellation plot
120         self.sp_fft = self.fig.add_subplot(2,2,1, position=[0.575, 0.2, 0.4, 0.6])
121         self.sp_fft.set_title(("FFT"), fontsize=self.title_font_size, fontweight="bold")
122         self.sp_fft.set_xlabel("Frequency (Hz)", fontsize=self.label_font_size, fontweight="bold")
123         self.sp_fft.set_ylabel("Power (dBm)", fontsize=self.label_font_size, fontweight="bold")
124         self.plot_fft = plot(self.freq, self.f_fft, '-bo')
125         self.sp_fft.set_ylim([min(self.f_fft)-10, max(self.f_fft)+10])
126         
127         draw()
128
129     def update_plots(self):
130         self.plot_f[0].set_data([self.time, self.floats])
131         self.sp_f.set_ylim([1.5*min(self.floats),
132                             1.5*max(self.floats)])
133
134         self.plot_fft[0].set_data([self.freq, self.f_fft])
135         self.sp_fft.set_ylim([min(self.f_fft)-10, max(self.f_fft)+10])
136
137         draw()
138         
139     def zoom(self, event):
140         newxlim = self.sp_f.get_xlim()
141         if(newxlim != self.xlim):
142             self.xlim = newxlim
143             xmin = max(0, int(ceil(self.sample_rate*self.xlim[0])))
144             xmax = min(int(ceil(self.sample_rate*self.xlim[1])), len(self.floats))
145
146             f = self.floats[xmin : xmax]
147             time = self.time[xmin : xmax]
148             
149             f_fft = self.dofft(f)
150             freq = self.calc_freq(time, self.sample_rate)
151                         
152             self.plot_fft[0].set_data(freq, f_fft)
153             self.sp_fft.axis([min(freq), max(freq),
154                               min(f_fft)-10, max(f_fft)+10])
155
156             draw()
157
158     def click(self, event):
159         forward_valid_keys = [" ", "down", "right"]
160         backward_valid_keys = ["up", "left"]
161
162         if(find(event.key, forward_valid_keys)):
163             self.step_forward()
164             
165         elif(find(event.key, backward_valid_keys)):
166             self.step_backward()
167
168     def button_left_click(self, event):
169         self.step_backward()
170
171     def button_right_click(self, event):
172         self.step_forward()
173
174     def step_forward(self):
175         self.get_data()
176         self.update_plots()
177
178     def step_backward(self):
179         # Step back in file position
180         if(self.hfile.tell() >= 8*self.block_length ):
181             self.hfile.seek(-8*self.block_length, 1)
182         else:
183             self.hfile.seek(-self.hfile.tell(),1)
184         self.get_data()
185         self.update_plots()
186         
187             
188
189 #FIXME: there must be a way to do this with a Python builtin
190 def find(item_in, list_search):
191     for l in list_search:
192         if item_in == l:
193             return True
194     return False
195
196 def main():
197     usage="%prog: [options] input_filename"
198     description = "Takes a GNU Radio floating point binary file and displays the sample data versus time as well as the frequency domain (FFT) plot. The y-axis values are plotted assuming volts as the amplitude of the I&Q streams and converted into dBm in the frequency domain (the 1/N power adjustment out of the FFT is performed internally). The script plots a certain block of data at a time, specified on the command line as -B or --block. This value defaults to 1000. The start position in the file can be set by specifying -s or --start and defaults to 0 (the start of the file). By default, the system assumes a sample rate of 1, so in time, each sample is plotted versus the sample number. To set a true time and frequency axis, set the sample rate (-R or --sample-rate) to the sample rate used when capturing the samples."
199
200     parser = OptionParser(conflict_handler="resolve", usage=usage, description=description)
201     parser.add_option("-B", "--block", type="int", default=1000,
202                       help="Specify the block size [default=%default]")
203     parser.add_option("-s", "--start", type="int", default=0,
204                       help="Specify where to start in the file [default=%default]")
205     parser.add_option("-R", "--sample-rate", type="float", default=1.0,
206                       help="Set the sampler rate of the data [default=%default]")
207     
208     (options, args) = parser.parse_args ()
209     if len(args) != 1:
210         parser.print_help()
211         raise SystemExit, 1
212     filename = args[0]
213
214     dc = draw_fft_f(filename, options)
215
216 if __name__ == "__main__":
217     try:
218         main()
219     except KeyboardInterrupt:
220         pass
221     
222
223