Imported Upstream version 3.0.4
[debian/gnuradio] / gnuradio-core / src / python / gnuradio / blksimpl / dqpsk.py
1 #
2 # Copyright 2005,2006 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 # See gnuradio-examples/python/gmsk2 for examples
23
24 """
25 differential QPSK modulation and demodulation.
26 """
27
28 from gnuradio import gr, gru, modulation_utils
29 from math import pi, sqrt
30 import psk
31 import cmath
32 import Numeric
33 from pprint import pprint
34
35 # default values (used in __init__ and add_options)
36 _def_samples_per_symbol = 2
37 _def_excess_bw = 0.35
38 _def_gray_code = True
39 _def_verbose = False
40 _def_log = False
41
42 _def_costas_alpha = None
43 _def_gain_mu = 0.03
44 _def_mu = 0.05
45 _def_omega_relative_limit = 0.005
46
47
48 # /////////////////////////////////////////////////////////////////////////////
49 #                           DQPSK modulator
50 # /////////////////////////////////////////////////////////////////////////////
51
52 class dqpsk_mod(gr.hier_block):
53
54     def __init__(self, fg,
55                  samples_per_symbol=_def_samples_per_symbol,
56                  excess_bw=_def_excess_bw,
57                  gray_code=_def_gray_code,
58                  verbose=_def_verbose,
59                  log=_def_log):
60         """
61         Hierarchical block for RRC-filtered QPSK modulation.
62
63         The input is a byte stream (unsigned char) and the
64         output is the complex modulated signal at baseband.
65
66         @param fg: flow graph
67         @type fg: flow graph
68         @param samples_per_symbol: samples per symbol >= 2
69         @type samples_per_symbol: integer
70         @param excess_bw: Root-raised cosine filter excess bandwidth
71         @type excess_bw: float
72         @param gray_code: Tell modulator to Gray code the bits
73         @type gray_code: bool
74         @param verbose: Print information about modulator?
75         @type verbose: bool
76         @param debug: Print modualtion data to files?
77         @type debug: bool
78         """
79
80         self._fg = fg
81         self._samples_per_symbol = samples_per_symbol
82         self._excess_bw = excess_bw
83         self._gray_code = gray_code
84
85         if not isinstance(samples_per_symbol, int) or samples_per_symbol < 2:
86             raise TypeError, ("sbp must be an integer >= 2, is %d" % samples_per_symbol)
87
88         ntaps = 11 * samples_per_symbol
89  
90         arity = pow(2,self.bits_per_symbol())
91
92         # turn bytes into k-bit vectors
93         self.bytes2chunks = \
94           gr.packed_to_unpacked_bb(self.bits_per_symbol(), gr.GR_MSB_FIRST)
95
96         if self._gray_code:
97             self.symbol_mapper = gr.map_bb(psk.binary_to_gray[arity])
98         else:
99             self.symbol_mapper = gr.map_bb(psk.binary_to_ungray[arity])
100             
101         self.diffenc = gr.diff_encoder_bb(arity)
102
103         rot = .707 + .707j
104         rotated_const = map(lambda pt: pt * rot, psk.constellation[arity])
105         self.chunks2symbols = gr.chunks_to_symbols_bc(rotated_const)
106
107         # pulse shaping filter
108         self.rrc_taps = gr.firdes.root_raised_cosine(
109             self._samples_per_symbol, # gain  (sps since we're interpolating by sps)
110             self._samples_per_symbol, # sampling rate
111             1.0,                      # symbol rate
112             self._excess_bw,          # excess bandwidth (roll-off factor)
113             ntaps)
114
115         self.rrc_filter = gr.interp_fir_filter_ccf(self._samples_per_symbol, self.rrc_taps)
116
117         if verbose:
118             self._print_verbage()
119         
120         if log:
121             self._setup_logging()
122             
123         # Connect & Initialize base class
124         self._fg.connect(self.bytes2chunks, self.symbol_mapper, self.diffenc,
125                          self.chunks2symbols, self.rrc_filter)
126         gr.hier_block.__init__(self, self._fg, self.bytes2chunks, self.rrc_filter)
127
128     def samples_per_symbol(self):
129         return self._samples_per_symbol
130
131     def bits_per_symbol(self=None):   # staticmethod that's also callable on an instance
132         return 2
133     bits_per_symbol = staticmethod(bits_per_symbol)      # make it a static method.  RTFM
134
135     def _print_verbage(self):
136         print "bits per symbol = %d" % self.bits_per_symbol()
137         print "Gray code = %s" % self._gray_code
138         print "RRS roll-off factor = %f" % self._excess_bw
139
140     def _setup_logging(self):
141         print "Modulation logging turned on."
142         self._fg.connect(self.bytes2chunks,
143                          gr.file_sink(gr.sizeof_char, "bytes2chunks.dat"))
144         self._fg.connect(self.symbol_mapper,
145                          gr.file_sink(gr.sizeof_char, "graycoder.dat"))
146         self._fg.connect(self.diffenc,
147                          gr.file_sink(gr.sizeof_char, "diffenc.dat"))        
148         self._fg.connect(self.chunks2symbols,
149                          gr.file_sink(gr.sizeof_gr_complex, "chunks2symbols.dat"))
150         self._fg.connect(self.rrc_filter,
151                          gr.file_sink(gr.sizeof_gr_complex, "rrc_filter.dat"))
152
153     def add_options(parser):
154         """
155         Adds QPSK modulation-specific options to the standard parser
156         """
157         parser.add_option("", "--excess-bw", type="float", default=_def_excess_bw,
158                           help="set RRC excess bandwith factor [default=%default] (PSK)")
159         parser.add_option("", "--no-gray-code", dest="gray_code",
160                           action="store_false", default=_def_gray_code,
161                           help="disable gray coding on modulated bits (PSK)")
162     add_options=staticmethod(add_options)
163
164
165     def extract_kwargs_from_options(options):
166         """
167         Given command line options, create dictionary suitable for passing to __init__
168         """
169         return modulation_utils.extract_kwargs_from_options(dqpsk_mod.__init__,
170                                                             ('self', 'fg'), options)
171     extract_kwargs_from_options=staticmethod(extract_kwargs_from_options)
172
173
174 # /////////////////////////////////////////////////////////////////////////////
175 #                           DQPSK demodulator
176 #
177 # Differentially coherent detection of differentially encoded qpsk
178 # /////////////////////////////////////////////////////////////////////////////
179
180 class dqpsk_demod(gr.hier_block):
181
182     def __init__(self, fg,
183                  samples_per_symbol=_def_samples_per_symbol,
184                  excess_bw=_def_excess_bw,
185                  costas_alpha=_def_costas_alpha,
186                  gain_mu=_def_gain_mu,
187                  mu=_def_mu,
188                  omega_relative_limit=_def_omega_relative_limit,
189                  gray_code=_def_gray_code,
190                  verbose=_def_verbose,
191                  log=_def_log):
192         """
193         Hierarchical block for RRC-filtered DQPSK demodulation
194
195         The input is the complex modulated signal at baseband.
196         The output is a stream of bits packed 1 bit per byte (LSB)
197
198         @param fg: flow graph
199         @type fg: flow graph
200         @param samples_per_symbol: samples per symbol >= 2
201         @type samples_per_symbol: float
202         @param excess_bw: Root-raised cosine filter excess bandwidth
203         @type excess_bw: float
204         @param costas_alpha: loop filter gain
205         @type costas_alphas: float
206         @param gain_mu: for M&M block
207         @type gain_mu: float
208         @param mu: for M&M block
209         @type mu: float
210         @param omega_relative_limit: for M&M block
211         @type omega_relative_limit: float
212         @param gray_code: Tell modulator to Gray code the bits
213         @type gray_code: bool
214         @param verbose: Print information about modulator?
215         @type verbose: bool
216         @param debug: Print modualtion data to files?
217         @type debug: bool
218         """
219
220         self._fg = fg
221         self._samples_per_symbol = samples_per_symbol
222         self._excess_bw = excess_bw
223         self._costas_alpha = costas_alpha
224         self._gain_mu = gain_mu
225         self._mu = mu
226         self._omega_relative_limit = omega_relative_limit
227         self._gray_code = gray_code
228
229         if samples_per_symbol < 2:
230             raise TypeError, "sbp must be >= 2, is %d" % samples_per_symbol
231
232         arity = pow(2,self.bits_per_symbol())
233  
234         # Automatic gain control
235         scale = (1.0/16384.0)
236         self.pre_scaler = gr.multiply_const_cc(scale)   # scale the signal from full-range to +-1
237         #self.agc = gr.agc2_cc(0.6e-1, 1e-3, 1, 1, 100)
238         self.agc = gr.feedforward_agc_cc(16, 1.0)
239        
240         # Costas loop (carrier tracking)
241         if self._costas_alpha is None:   # If no alpha value was specified by the user
242             alpha_dir = {2:0.075, 3:0.09, 4:0.09, 5:0.095, 6:0.10, 7:0.105}
243             self._costas_alpha = alpha_dir[self._samples_per_symbol]
244         
245         costas_order = 4        
246         # The value of beta is now set to be underdamped; this value can have a huge impact on the
247         # performance of QPSK. Set to 0.25 for critically damped or higher for underdamped responses.
248         beta = .35 * self._costas_alpha * self._costas_alpha
249         self.costas_loop = gr.costas_loop_cc(self._costas_alpha, beta, 0.02, -0.02, costas_order)
250
251         # RRC data filter
252         ntaps = 11 * samples_per_symbol
253         self.rrc_taps = gr.firdes.root_raised_cosine(
254             self._samples_per_symbol, # gain
255             self._samples_per_symbol, # sampling rate
256             1.0,                      # symbol rate
257             self._excess_bw,          # excess bandwidth (roll-off factor)
258             ntaps)
259
260         self.rrc_filter=gr.fir_filter_ccf(1, self.rrc_taps)
261
262         # symbol clock recovery
263         omega = self._samples_per_symbol
264         gain_omega = .25 * self._gain_mu * self._gain_mu
265         self.clock_recovery=gr.clock_recovery_mm_cc(omega, gain_omega,
266                                                     self._mu, self._gain_mu,
267                                                     self._omega_relative_limit)
268
269         self.diffdec = gr.diff_phasor_cc()
270         #self.diffdec = gr.diff_decoder_bb(arity)
271
272         # find closest constellation point
273         rot = 1
274         #rot = .707 + .707j
275         rotated_const = map(lambda pt: pt * rot, psk.constellation[arity])
276         #print "rotated_const = %s" % rotated_const
277
278         self.slicer = gr.constellation_decoder_cb(rotated_const, range(arity))
279
280         if self._gray_code:
281             self.symbol_mapper = gr.map_bb(psk.gray_to_binary[arity])
282         else:
283             self.symbol_mapper = gr.map_bb(psk.ungray_to_binary[arity])
284
285         
286         # unpack the k bit vector into a stream of bits
287         self.unpack = gr.unpack_k_bits_bb(self.bits_per_symbol())
288
289         if verbose:
290             self._print_verbage()
291         
292         if log:
293             self._setup_logging()
294  
295         # Connect & Initialize base class
296         self._fg.connect(self.pre_scaler, self.agc, self.costas_loop,
297                          self.rrc_filter, self.clock_recovery,
298                          self.diffdec, self.slicer, self.symbol_mapper,
299                          self.unpack)
300         gr.hier_block.__init__(self, self._fg, self.pre_scaler, self.unpack)
301
302     def samples_per_symbol(self):
303         return self._samples_per_symbol
304
305     def bits_per_symbol(self=None):   # staticmethod that's also callable on an instance
306         return 2
307     bits_per_symbol = staticmethod(bits_per_symbol)      # make it a static method.  RTFM
308
309     def _print_verbage(self):
310         print "bits per symbol = %d"         % self.bits_per_symbol()
311         print "Gray code = %s"               % self._gray_code
312         print "RRC roll-off factor = %.2f"   % self._excess_bw
313         print "Costas Loop alpha = %.5f"     % self._costas_alpha
314         print "M&M symbol sync gain = %.5f"  % self._gain_mu
315         print "M&M symbol sync mu = %.5f"    % self._mu
316         print "M&M omega relative limit = %.5f" % self._omega_relative_limit
317         
318
319     def _setup_logging(self):
320         print "Modulation logging turned on."
321         self._fg.connect(self.pre_scaler,
322                          gr.file_sink(gr.sizeof_gr_complex, "prescaler.dat"))
323         self._fg.connect(self.agc,
324                          gr.file_sink(gr.sizeof_gr_complex, "agc.dat"))
325         self._fg.connect(self.costas_loop,
326                          gr.file_sink(gr.sizeof_gr_complex, "costas_loop.dat"))
327         self._fg.connect((self.costas_loop,1),
328                          gr.file_sink(gr.sizeof_gr_complex, "costas_error.dat"))
329         self._fg.connect(self.rrc_filter,
330                          gr.file_sink(gr.sizeof_gr_complex, "rrc_filter.dat"))
331         self._fg.connect(self.clock_recovery,
332                          gr.file_sink(gr.sizeof_gr_complex, "clock_recovery.dat"))
333         self._fg.connect((self.clock_recovery,1),
334                         gr.file_sink(gr.sizeof_gr_complex, "clock_recovery_error.dat"))
335         self._fg.connect(self.diffdec,
336                          gr.file_sink(gr.sizeof_gr_complex, "diffdec.dat"))        
337         self._fg.connect(self.slicer,
338                          gr.file_sink(gr.sizeof_char, "slicer.dat"))
339         self._fg.connect(self.symbol_mapper,
340                          gr.file_sink(gr.sizeof_char, "gray_decoder.dat"))
341         self._fg.connect(self.unpack,
342                          gr.file_sink(gr.sizeof_char, "unpack.dat"))
343
344     def add_options(parser):
345         """
346         Adds modulation-specific options to the standard parser
347         """
348         parser.add_option("", "--excess-bw", type="float", default=_def_excess_bw,
349                           help="set RRC excess bandwith factor [default=%default] (PSK)")
350         parser.add_option("", "--no-gray-code", dest="gray_code",
351                           action="store_false", default=_def_gray_code,
352                           help="disable gray coding on modulated bits (PSK)")
353         parser.add_option("", "--costas-alpha", type="float", default=None,
354                           help="set Costas loop alpha value [default=%default] (PSK)")
355         parser.add_option("", "--gain-mu", type="float", default=_def_gain_mu,
356                           help="set M&M symbol sync loop gain mu value [default=%default] (PSK)")
357         parser.add_option("", "--mu", type="float", default=_def_mu,
358                           help="set M&M symbol sync loop mu value [default=%default] (PSK)")
359     add_options=staticmethod(add_options)
360
361     def extract_kwargs_from_options(options):
362         """
363         Given command line options, create dictionary suitable for passing to __init__
364         """
365         return modulation_utils.extract_kwargs_from_options(
366             dqpsk_demod.__init__, ('self', 'fg'), options)
367     extract_kwargs_from_options=staticmethod(extract_kwargs_from_options)
368
369
370 #
371 # Add these to the mod/demod registry
372 #
373 modulation_utils.add_type_1_mod('dqpsk', dqpsk_mod)
374 modulation_utils.add_type_1_demod('dqpsk', dqpsk_demod)