abc210c08accfc02f03b6a8a0d7db30703e771cf
[debian/gnuradio] / gnuradio-core / src / utils / gr_plot_data.py
1 #!/usr/bin/env python
2 #
3 # Copyright 2007,2008 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 matplotlib.interactive(True)
38 matplotlib.use('TkAgg')
39
40 class plot_data:
41     def __init__(self, datatype, filenames, options):
42         self.hfile = list()
43         self.legend_text = list()
44         for f in filenames:
45             self.hfile.append(open(f, "r"))
46             self.legend_text.append(f)
47
48         self.block_length = options.block
49         self.start = options.start
50         self.sample_rate = options.sample_rate
51
52         self.datatype = datatype
53         self.sizeof_data = datatype().nbytes    # number of bytes per sample in file
54
55         self.axis_font_size = 16
56         self.label_font_size = 18
57         self.title_font_size = 20
58         self.text_size = 22
59
60         # Setup PLOT
61         self.fig = figure(1, figsize=(16, 9), facecolor='w')
62         rcParams['xtick.labelsize'] = self.axis_font_size
63         rcParams['ytick.labelsize'] = self.axis_font_size
64         
65         self.text_file_pos = figtext(0.10, 0.88, "File Position: ", weight="heavy", size=self.text_size)
66         self.text_block    = figtext(0.40, 0.88, ("Block Size: %d" % self.block_length),
67                                      weight="heavy", size=self.text_size)
68         self.text_sr       = figtext(0.60, 0.88, ("Sample Rate: %.2f" % self.sample_rate),
69                                      weight="heavy", size=self.text_size)
70         self.make_plots()
71
72         self.button_left_axes = self.fig.add_axes([0.45, 0.01, 0.05, 0.05], frameon=True)
73         self.button_left = Button(self.button_left_axes, "<")
74         self.button_left_callback = self.button_left.on_clicked(self.button_left_click)
75
76         self.button_right_axes = self.fig.add_axes([0.50, 0.01, 0.05, 0.05], frameon=True)
77         self.button_right = Button(self.button_right_axes, ">")
78         self.button_right_callback = self.button_right.on_clicked(self.button_right_click)
79
80         self.xlim = self.sp_f.get_xlim()
81
82         self.manager = get_current_fig_manager()
83         connect('key_press_event', self.click)
84         show()
85         
86     def get_data(self, hfile):
87         self.text_file_pos.set_text("File Position: %d" % (hfile.tell()//self.sizeof_data))
88         f = scipy.fromfile(hfile, dtype=self.datatype, count=self.block_length)
89         #print "Read in %d items" % len(self.f)
90         if(len(f) == 0):
91             print "End of File"
92         else:
93             self.f = f
94             self.time = [i*(1/self.sample_rate) for i in range(len(self.f))]
95         
96     def make_plots(self):
97         self.sp_f = self.fig.add_subplot(2,1,1, position=[0.075, 0.2, 0.875, 0.6])
98         self.sp_f.set_title(("Amplitude"), fontsize=self.title_font_size, fontweight="bold")
99         self.sp_f.set_xlabel("Time (s)", fontsize=self.label_font_size, fontweight="bold")
100         self.sp_f.set_ylabel("Amplitude (V)", fontsize=self.label_font_size, fontweight="bold")
101         self.plot_f = list()
102
103         maxval = -1e12
104         minval = 1e12
105
106         for hf in self.hfile:
107             # if specified on the command-line, set file pointer
108             hf.seek(self.sizeof_data*self.start, 1)
109
110             self.get_data(hf)
111         
112             # Subplot for real and imaginary parts of signal
113             self.plot_f += plot(self.time, self.f, 'o-')
114             maxval = max(maxval, max(self.f))
115             minval = min(minval, min(self.f))
116
117         self.sp_f.set_ylim([1.5*minval, 1.5*maxval])
118
119         self.leg = self.sp_f.legend(self.plot_f, self.legend_text)
120
121         draw()
122
123     def update_plots(self):
124         maxval = -1e12
125         minval = 1e12
126         for hf,p in zip(self.hfile,self.plot_f):
127             self.get_data(hf)
128             p.set_data([self.time, self.f])
129             maxval = max(maxval, max(self.f))
130             minval = min(minval, min(self.f))
131
132         self.sp_f.set_ylim([1.5*minval, 1.5*maxval])
133         
134         draw()
135         
136     def click(self, event):
137         forward_valid_keys = [" ", "down", "right"]
138         backward_valid_keys = ["up", "left"]
139
140         if(find(event.key, forward_valid_keys)):
141             self.step_forward()
142             
143         elif(find(event.key, backward_valid_keys)):
144             self.step_backward()
145
146     def button_left_click(self, event):
147         self.step_backward()
148
149     def button_right_click(self, event):
150         self.step_forward()
151
152     def step_forward(self):
153         self.update_plots()
154
155     def step_backward(self):
156         for hf in self.hfile:
157             # Step back in file position
158             if(hf.tell() >= 2*self.sizeof_data*self.block_length ):
159                 hf.seek(-2*self.sizeof_data*self.block_length, 1)
160             else:
161                 hf.seek(-hf.tell(),1)
162         self.update_plots()
163         
164             
165
166 #FIXME: there must be a way to do this with a Python builtin
167 def find(item_in, list_search):
168     for l in list_search:
169         if item_in == l:
170             return True
171     return False
172
173 def main():
174     usage="%prog: [options] input_filenames"
175     description = "This is just a test program for this class. It should really be called by gr_plot_<datatype>.py for a specific type of file data (float, int, byte, etc.)."
176
177     parser = OptionParser(conflict_handler="resolve", usage=usage, description=description)
178     parser.add_option("-B", "--block", type="int", default=1000,
179                       help="Specify the block size [default=%default]")
180     parser.add_option("-s", "--start", type="int", default=0,
181                       help="Specify where to start in the file [default=%default]")
182     parser.add_option("-R", "--sample-rate", type="float", default=1.0,
183                       help="Set the sampler rate of the data [default=%default]")
184     
185     (options, args) = parser.parse_args ()
186     if len(args) < 1:
187         parser.print_help()
188         raise SystemExit, 1
189     filenames = args
190              
191     datatype=scipy.float32
192     dc = plot_data(datatype, filenames, options)
193
194 if __name__ == "__main__":
195     try:
196         main()
197     except KeyboardInterrupt:
198         pass
199