Fixing up other plotting tools for data read errors.
[debian/gnuradio] / gr-utils / src / python / plot_data.py
1 #
2 # Copyright 2007,2008,2011 Free Software Foundation, Inc.
3
4 # This file is part of GNU Radio
5
6 # GNU Radio is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3, or (at your option)
9 # any later version.
10
11 # GNU Radio is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with GNU Radio; see the file COPYING.  If not, write to
18 # the Free Software Foundation, Inc., 51 Franklin Street,
19 # Boston, MA 02110-1301, USA.
20
21
22 try:
23     import scipy
24 except ImportError:
25     print "Please install SciPy to run this script (http://www.scipy.org/)"
26     raise SystemExit, 1
27
28 try:
29     from pylab import *
30 except ImportError:
31     print "Please install Matplotlib to run this script (http://matplotlib.sourceforge.net/)"
32     raise SystemExit, 1
33
34 from optparse import OptionParser
35
36 class plot_data:
37     def __init__(self, datatype, filenames, options):
38         self.hfile = list()
39         self.legend_text = list()
40         for f in filenames:
41             self.hfile.append(open(f, "r"))
42             self.legend_text.append(f)
43
44         self.block_length = options.block
45         self.start = options.start
46         self.sample_rate = options.sample_rate
47
48         self.datatype = datatype
49         self.sizeof_data = datatype().nbytes    # number of bytes per sample in file
50
51         self.axis_font_size = 16
52         self.label_font_size = 18
53         self.title_font_size = 20
54         self.text_size = 22
55
56         # Setup PLOT
57         self.fig = figure(1, figsize=(16, 9), facecolor='w')
58         rcParams['xtick.labelsize'] = self.axis_font_size
59         rcParams['ytick.labelsize'] = self.axis_font_size
60         
61         self.text_file_pos = figtext(0.10, 0.88, "File Position: ", weight="heavy", size=self.text_size)
62         self.text_block    = figtext(0.40, 0.88, ("Block Size: %d" % self.block_length),
63                                      weight="heavy", size=self.text_size)
64         self.text_sr       = figtext(0.60, 0.88, ("Sample Rate: %.2f" % self.sample_rate),
65                                      weight="heavy", size=self.text_size)
66         self.make_plots()
67
68         self.button_left_axes = self.fig.add_axes([0.45, 0.01, 0.05, 0.05], frameon=True)
69         self.button_left = Button(self.button_left_axes, "<")
70         self.button_left_callback = self.button_left.on_clicked(self.button_left_click)
71
72         self.button_right_axes = self.fig.add_axes([0.50, 0.01, 0.05, 0.05], frameon=True)
73         self.button_right = Button(self.button_right_axes, ">")
74         self.button_right_callback = self.button_right.on_clicked(self.button_right_click)
75
76         self.xlim = self.sp_f.get_xlim()
77
78         self.manager = get_current_fig_manager()
79         connect('key_press_event', self.click)
80         show()
81         
82     def get_data(self, hfile):
83         self.text_file_pos.set_text("File Position: %d" % (hfile.tell()//self.sizeof_data))
84         try:
85             f = scipy.fromfile(hfile, dtype=self.datatype, count=self.block_length)
86         except MemoryError:
87             print "End of File"
88         else:
89             self.f = scipy.array(f)
90             self.time = scipy.array([i*(1/self.sample_rate) for i in range(len(self.f))])
91         
92     def make_plots(self):
93         self.sp_f = self.fig.add_subplot(2,1,1, position=[0.075, 0.2, 0.875, 0.6])
94         self.sp_f.set_title(("Amplitude"), fontsize=self.title_font_size, fontweight="bold")
95         self.sp_f.set_xlabel("Time (s)", fontsize=self.label_font_size, fontweight="bold")
96         self.sp_f.set_ylabel("Amplitude (V)", fontsize=self.label_font_size, fontweight="bold")
97         self.plot_f = list()
98
99         maxval = -1e12
100         minval = 1e12
101
102         for hf in self.hfile:
103             # if specified on the command-line, set file pointer
104             hf.seek(self.sizeof_data*self.start, 1)
105
106             self.get_data(hf)
107         
108             # Subplot for real and imaginary parts of signal
109             self.plot_f += plot(self.time, self.f, 'o-')
110             maxval = max(maxval, self.f.max())
111             minval = min(minval, self.f.min())
112
113         self.sp_f.set_ylim([1.5*minval, 1.5*maxval])
114
115         self.leg = self.sp_f.legend(self.plot_f, self.legend_text)
116
117         draw()
118
119     def update_plots(self):
120         maxval = -1e12
121         minval = 1e12
122         for hf,p in zip(self.hfile,self.plot_f):
123             self.get_data(hf)
124             p.set_data([self.time, self.f])
125             maxval = max(maxval, self.f.max())
126             minval = min(minval, self.f.min())
127
128         self.sp_f.set_ylim([1.5*minval, 1.5*maxval])
129         
130         draw()
131         
132     def click(self, event):
133         forward_valid_keys = [" ", "down", "right"]
134         backward_valid_keys = ["up", "left"]
135
136         if(find(event.key, forward_valid_keys)):
137             self.step_forward()
138             
139         elif(find(event.key, backward_valid_keys)):
140             self.step_backward()
141
142     def button_left_click(self, event):
143         self.step_backward()
144
145     def button_right_click(self, event):
146         self.step_forward()
147
148     def step_forward(self):
149         self.update_plots()
150
151     def step_backward(self):
152         for hf in self.hfile:
153             # Step back in file position
154             if(hf.tell() >= 2*self.sizeof_data*self.block_length ):
155                 hf.seek(-2*self.sizeof_data*self.block_length, 1)
156             else:
157                 hf.seek(-hf.tell(),1)
158         self.update_plots()
159         
160
161 def find(item_in, list_search):
162     try:
163         return list_search.index(item_in) != None
164     except ValueError:
165         return False