Fixing up other plotting tools for data read errors.
[debian/gnuradio] / gr-utils / src / python / gr_plot_iq.py
1 #!/usr/bin/env python
2 #
3 # Copyright 2007,2008,2011 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 try:
24     import scipy
25 except ImportError:
26     print "Please install SciPy to run this script (http://www.scipy.org/)"
27     raise SystemExit, 1
28
29 try:
30     from pylab import *
31 except ImportError:
32     print "Please install Matplotlib to run this script (http://matplotlib.sourceforge.net/)"
33     raise SystemExit, 1
34
35 from optparse import OptionParser
36
37 class draw_iq:
38     def __init__(self, filename, options):
39         self.hfile = open(filename, "r")
40         self.block_length = options.block
41         self.start = options.start
42         self.sample_rate = options.sample_rate
43
44         self.datatype = scipy.complex64
45         self.sizeof_data = self.datatype().nbytes    # number of bytes per sample in file
46
47         self.axis_font_size = 16
48         self.label_font_size = 18
49         self.title_font_size = 20
50         self.text_size = 22
51
52         # Setup PLOT
53         self.fig = figure(1, figsize=(16, 9), facecolor='w')
54         rcParams['xtick.labelsize'] = self.axis_font_size
55         rcParams['ytick.labelsize'] = self.axis_font_size
56         
57         self.text_file     = figtext(0.10, 0.94, ("File: %s" % filename), weight="heavy", size=self.text_size)
58         self.text_file_pos = figtext(0.10, 0.88, "File Position: ", weight="heavy", size=self.text_size)
59         self.text_block    = figtext(0.40, 0.88, ("Block Size: %d" % self.block_length),
60                                      weight="heavy", size=self.text_size)
61         self.text_sr       = figtext(0.60, 0.88, ("Sample Rate: %.2f" % self.sample_rate),
62                                      weight="heavy", size=self.text_size)
63         self.make_plots()
64
65         self.button_left_axes = self.fig.add_axes([0.45, 0.01, 0.05, 0.05], frameon=True)
66         self.button_left = Button(self.button_left_axes, "<")
67         self.button_left_callback = self.button_left.on_clicked(self.button_left_click)
68
69         self.button_right_axes = self.fig.add_axes([0.50, 0.01, 0.05, 0.05], frameon=True)
70         self.button_right = Button(self.button_right_axes, ">")
71         self.button_right_callback = self.button_right.on_clicked(self.button_right_click)
72
73         self.xlim = self.sp_iq.get_xlim()
74
75         self.manager = get_current_fig_manager()
76         connect('key_press_event', self.click)
77         show()
78
79     def get_data(self):
80         self.text_file_pos.set_text("File Position: %d" % (self.hfile.tell()//self.sizeof_data))
81         try:
82             self.iq = scipy.fromfile(self.hfile, dtype=self.datatype, count=self.block_length)
83         except MemoryError:
84             print "End of File"
85         else:
86             self.reals = scipy.array([r.real for r in self.iq])
87             self.imags = scipy.array([i.imag for i in self.iq])
88             self.time = scipy.array([i*(1/self.sample_rate) for i in range(len(self.reals))])
89             
90     def make_plots(self):
91         # if specified on the command-line, set file pointer
92         self.hfile.seek(self.sizeof_data*self.start, 1)
93
94         self.get_data()
95         
96         # Subplot for real and imaginary parts of signal
97         self.sp_iq = self.fig.add_subplot(2,1,1, position=[0.075, 0.14, 0.85, 0.67])
98         self.sp_iq.set_title(("I&Q"), fontsize=self.title_font_size, fontweight="bold")
99         self.sp_iq.set_xlabel("Time (s)", fontsize=self.label_font_size, fontweight="bold")
100         self.sp_iq.set_ylabel("Amplitude (V)", fontsize=self.label_font_size, fontweight="bold")
101         self.plot_iq = plot(self.time, self.reals, 'bo-', self.time, self.imags, 'ro-')
102         self.sp_iq.set_ylim([1.5*min([self.reals.min(), self.imags.min()]),
103                              1.5*max([self.reals.max(), self.imags.max()])])
104         self.sp_iq.set_xlim(self.time.min(), self.time.max())
105         draw()
106
107     def update_plots(self):
108         self.plot_iq[0].set_data([self.time, self.reals])
109         self.plot_iq[1].set_data([self.time, self.imags])
110         self.sp_iq.set_ylim([1.5*min([self.reals.min(), self.imags.min()]),
111                              1.5*max([self.reals.max(), self.imags.max()])])
112         self.sp_iq.set_xlim(self.time.min(), self.time.max())
113         draw()
114         
115     def click(self, event):
116         forward_valid_keys = [" ", "down", "right"]
117         backward_valid_keys = ["up", "left"]
118
119         if(find(event.key, forward_valid_keys)):
120             self.step_forward()
121             
122         elif(find(event.key, backward_valid_keys)):
123             self.step_backward()
124
125     def button_left_click(self, event):
126         self.step_backward()
127
128     def button_right_click(self, event):
129         self.step_forward()
130
131     def step_forward(self):
132         self.get_data()
133         self.update_plots()
134
135     def step_backward(self):
136         # Step back in file position
137         if(self.hfile.tell() >= 2*self.sizeof_data*self.block_length ):
138             self.hfile.seek(-2*self.sizeof_data*self.block_length, 1)
139         else:
140             self.hfile.seek(-self.hfile.tell(),1)
141         self.get_data()
142         self.update_plots()
143         
144
145 def find(item_in, list_search):
146     try:
147         return list_search.index(item_in) != None
148     except ValueError:
149         return False
150         
151 def main():
152     usage="%prog: [options] input_filename"
153     description = "Takes a GNU Radio complex binary file and displays the I&Q data versus time. You can set the block size to specify how many points to read in at a time and the start position in 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 axis, set the sample rate (-R or --sample-rate) to the sample rate used when capturing the samples."
154
155     parser = OptionParser(conflict_handler="resolve", usage=usage, description=description)
156     parser.add_option("-B", "--block", type="int", default=1000,
157                       help="Specify the block size [default=%default]")
158     parser.add_option("-s", "--start", type="int", default=0,
159                       help="Specify where to start in the file [default=%default]")
160     parser.add_option("-R", "--sample-rate", type="float", default=1.0,
161                       help="Set the sampler rate of the data [default=%default]")
162     
163     (options, args) = parser.parse_args ()
164     if len(args) != 1:
165         parser.print_help()
166         raise SystemExit, 1
167     filename = args[0]
168
169     dc = draw_iq(filename, options)
170
171 if __name__ == "__main__":
172     try:
173         main()
174     except KeyboardInterrupt:
175         pass
176     
177
178