0bca41037c4c1d08d5b561f7a45ff6746beeb017
[debian/gnuradio] / gr-msdd6000 / src / python-examples / ofdm / gr_plot_ofdm.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, pylab, math
24 import struct, sys
25 from pylab import *
26 from matplotlib.font_manager import fontManager, FontProperties
27 from optparse import OptionParser
28 from scipy import fftpack
29 from math import log10
30
31 matplotlib.interactive(True)
32 matplotlib.use('TkAgg')
33
34 class draw_constellation:
35     def __init__(self, options):
36         derot_file = "ofdm_frame_sink_c.dat"
37         acq_file = "ofdm_frame_acq_c.dat"
38         fft_file = "fft_out_c.dat"
39
40         self.h_derot_file = open(derot_file, "r")
41         self.h_acq_file = open(acq_file, "r")
42         self.h_fft_file = open(fft_file, "r")
43
44         self.occ_tones = options.occ_tones
45         self.fft_size  = options.fft_size
46         self.symbol = options.start
47         self.sample_rate = options.sample_rate
48         
49         self.axis_font_size = 16
50         self.label_font_size = 18
51         self.title_font_size = 20
52         self.text_size = 22
53         
54         # Setup PLOT
55         self.fig = figure(1, figsize=(14, 9), facecolor='w')
56         rcParams['xtick.labelsize'] = self.axis_font_size
57         rcParams['ytick.labelsize'] = self.axis_font_size
58
59         self.text_sym = figtext(0.05, 0.95, ("Symbol: %s" % self.symbol), weight="heavy", size=self.text_size)
60
61         self.make_plots()
62
63         self.button_left_axes = self.fig.add_axes([0.45, 0.01, 0.05, 0.05], frameon=True)
64         self.button_left = Button(self.button_left_axes, "<")
65         self.button_left_callback = self.button_left.on_clicked(self.button_left_click)
66
67         self.button_right_axes = self.fig.add_axes([0.50, 0.01, 0.05, 0.05], frameon=True)
68         self.button_right = Button(self.button_right_axes, ">")
69         self.button_right_callback = self.button_right.on_clicked(self.button_right_click)
70
71         self.xlim = self.sp_eq.get_xlim()
72
73         self.manager = get_current_fig_manager()
74         #connect('draw_event', self.zoom)
75         connect('key_press_event', self.click)
76         show()
77
78     def get_data(self):
79         self.text_sym.set_text("Symbol: %d" % (self.symbol))
80
81         derot_data = scipy.fromfile(self.h_derot_file, dtype=scipy.complex64, count=self.occ_tones)
82         acq_data = scipy.fromfile(self.h_acq_file, dtype=scipy.complex64, count=self.occ_tones)
83         fft_data = scipy.fromfile(self.h_fft_file, dtype=scipy.complex64, count=self.fft_size)
84         if(len(acq_data) == 0):
85             print "End of File"
86         else:
87             self.acq_data_reals = [r.real for r in acq_data]
88             self.acq_data_imags = [i.imag for i in acq_data]
89             self.derot_data_reals = [r.real for r in derot_data]
90             self.derot_data_imags = [i.imag for i in derot_data]
91
92             self.unequalized_angle = [math.atan2(x.imag, x.real) for x in fft_data]
93             self.equalized_angle = [math.atan2(x.imag, x.real) for x in acq_data]
94             self.derot_equalized_angle = [math.atan2(x.imag, x.real) for x in derot_data]
95
96             self.time = [i*(1/self.sample_rate) for i in range(len(acq_data))]
97             ffttime = [i*(1/self.sample_rate) for i in range(len(fft_data))]
98
99             self.freq = self.get_freq(ffttime, self.sample_rate)
100
101             for i in range(len(fft_data)):
102                 if(abs(fft_data[i]) == 0.0):
103                     fft_data[i] = complex(1e-6,1e-6)
104             self.fft_data = [20*log10(abs(f)) for f in fft_data]
105               
106     def get_freq(self, time, sample_rate, T=1):
107         N = len(time)
108         Fs = 1.0 / (max(time) - min(time))
109         Fn = 0.5 * sample_rate
110         freq = [-Fn + i*Fs for i in range(N)]
111         return freq
112
113     def make_plots(self):
114         self.h_acq_file.seek(8*self.symbol*self.occ_tones, 0)
115         self.h_fft_file.seek(8*self.symbol*self.fft_size, 0)
116         self.h_derot_file.seek(8*self.symbol*self.occ_tones, 0)
117
118         self.get_data()
119         
120         # Subplot:  constellation of rotated symbols
121         self.sp_const = self.fig.add_subplot(4,1,1, position=[0.15, 0.55, 0.3, 0.35])
122         self.sp_const.set_title(("Constellation"), fontsize=self.title_font_size, fontweight="bold")
123         self.sp_const.set_xlabel("Inphase", fontsize=self.label_font_size, fontweight="bold")
124         self.sp_const.set_ylabel("Qaudrature", fontsize=self.label_font_size, fontweight="bold")
125         self.plot_const = plot(self.acq_data_reals, self.acq_data_imags, 'bo')
126         self.plot_const += plot(self.derot_data_reals, self.derot_data_imags, 'ro')
127         self.sp_const.axis([-2, 2, -2, 2])
128
129         # Subplot: unequalized angle
130         self.sp_uneq = self.fig.add_subplot(4,2,1, position=[0.575, 0.55, 0.3, 0.35])
131         self.sp_uneq.set_title(("Unequalized Angle"), fontsize=self.title_font_size, fontweight="bold")
132         self.sp_uneq.set_xlabel("Time (s)", fontsize=self.label_font_size, fontweight="bold")
133         self.sp_uneq.set_ylabel("Angle", fontsize=self.label_font_size, fontweight="bold")
134         uneqscale = range(len(self.unequalized_angle))
135         self.plot_uneq = plot(uneqscale, self.unequalized_angle, 'bo')
136
137         # Subplot: equalized angle
138         self.sp_eq = self.fig.add_subplot(4,1,2, position=[0.15, 0.1, 0.3, 0.35])
139         self.sp_eq.set_title(("Equalized Angle"), fontsize=self.title_font_size, fontweight="bold")
140         self.sp_eq.set_xlabel("Time (s)", fontsize=self.label_font_size, fontweight="bold")
141         self.sp_eq.set_ylabel("Angle", fontsize=self.label_font_size, fontweight="bold")
142         eqscale = range(len(self.equalized_angle))
143         self.plot_eq = plot(eqscale, self.equalized_angle, 'bo')
144         self.plot_eq += plot(eqscale, self.derot_equalized_angle, 'ro', markersize=4)
145
146         # Subplot: FFT
147         self.sp_fft = self.fig.add_subplot(4,2,2, position=[0.575, 0.1, 0.3, 0.35])
148         self.sp_fft.set_title(("FFT"), fontsize=self.title_font_size, fontweight="bold")
149         self.sp_fft.set_xlabel("Frequency (MHz)", fontsize=self.label_font_size, fontweight="bold")
150         self.sp_fft.set_ylabel("Power (dBm)", fontsize=self.label_font_size, fontweight="bold")
151         self.plot_fft = plot(self.freq, self.fft_data, '-bo')
152
153         draw()
154
155     def update_plots(self):
156         eqscale = range(len(self.equalized_angle))
157         uneqscale = range(len(self.unequalized_angle))
158         self.plot_eq[0].set_data([eqscale, self.equalized_angle])
159         self.plot_eq[1].set_data([eqscale, self.derot_equalized_angle])
160         self.plot_uneq[0].set_data([uneqscale, self.unequalized_angle])
161         self.sp_eq.set_ylim([-4, 4])
162         self.sp_uneq.set_ylim([-4, 4])
163
164         #self.sp_iq.axis([min(self.time), max(self.time),
165         #                 1.5*min([min(self.acq_data_reals), min(self.acq_data_imags)]),
166         #                 1.5*max([max(self.acq_data_reals), max(self.acq_data_imags)])])
167
168         self.plot_const[0].set_data([self.acq_data_reals, self.acq_data_imags])
169         self.plot_const[1].set_data([self.derot_data_reals, self.derot_data_imags])
170         self.sp_const.axis([-2, 2, -2, 2])
171
172         self.plot_fft[0].set_data([self.freq, self.fft_data])
173
174         draw()
175         
176     def zoom(self, event):
177         newxlim = self.sp_eq.get_xlim()
178         if(newxlim != self.xlim):
179             self.xlim = newxlim
180             r = self.reals[int(ceil(self.xlim[0])) : int(ceil(self.xlim[1]))]
181             i = self.imags[int(ceil(self.xlim[0])) : int(ceil(self.xlim[1]))]
182
183             self.plot_const[0].set_data(r, i)
184             self.sp_const.axis([-2, 2, -2, 2])
185             self.manager.canvas.draw()
186             draw()
187
188     def click(self, event):
189         forward_valid_keys = [" ", "down", "right"]
190         backward_valid_keys = ["up", "left"]
191
192         if(find(event.key, forward_valid_keys)):
193             self.step_forward()
194             
195         elif(find(event.key, backward_valid_keys)):
196             self.step_backward()
197
198     def button_left_click(self, event):
199         self.step_backward()
200
201     def button_right_click(self, event):
202         self.step_forward()
203
204     def step_forward(self):
205         self.symbol += 1
206         self.get_data()
207         self.update_plots()
208
209     def step_backward(self):
210         # Step back in file position
211         self.symbol -= 1
212         if(self.h_acq_file.tell() >= 16*self.occ_tones):
213             self.h_acq_file.seek(-16*self.occ_tones, 1)
214         else:
215             self.symbol = 0
216             self.h_acq_file.seek(-self.h_acq_file.tell(),1)
217
218
219         if(self.h_derot_file.tell() >= 16*self.occ_tones):
220             self.h_derot_file.seek(-16*self.occ_tones, 1)
221         else:
222             self.symbol = 0
223             self.h_derot_file.seek(-self.h_derot_file.tell(),1)
224
225
226         if(self.h_fft_file.tell() >= 16*self.fft_size):
227             self.h_fft_file.seek(-16*self.fft_size, 1)
228         else:
229             self.symbol = 0
230             self.h_fft_file.seek(-self.h_fft_file.tell(),1)
231
232         self.get_data()
233         self.update_plots()
234         
235             
236
237 #FIXME: there must be a way to do this with a Python builtin
238 def find(item_in, list_search):
239     for l in list_search:
240         if item_in == l:
241             return True
242     return False
243
244 def main():
245     usage="%prog: [options]"
246
247     parser = OptionParser(conflict_handler="resolve", usage=usage)
248     parser.add_option("", "--fft-size", type="int", default=512,
249                       help="Specify the size of the FFT [default=%default]")
250     parser.add_option("", "--occ-tones", type="int", default=200,
251                       help="Specify the number of occupied tones [default=%default]")
252     parser.add_option("-s", "--start", type="int", default=0,
253                       help="Specify the starting symbol to plot [default=%default]")
254     parser.add_option("-R", "--sample-rate", type="float", default=1.0,
255                       help="Set the sampler rate of the data [default=%default]")
256     
257     (options, args) = parser.parse_args ()
258
259     dc = draw_constellation(options)
260
261 if __name__ == "__main__":
262     try:
263         main()
264     except KeyboardInterrupt:
265         pass
266     
267
268