merged trondeau/digital-wip2 r4193:4730 into trunk - improves digital receiver and...
[debian/gnuradio] / gnuradio-core / src / python / gnuradio / blksimpl2 / 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 2, 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/digital 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 = 0.15
43 _def_gain_mu = 0.1
44 _def_mu = 0.5
45 _def_omega_relative_limit = 0.005
46
47
48 # /////////////////////////////////////////////////////////////////////////////
49 #                           DQPSK modulator
50 # /////////////////////////////////////////////////////////////////////////////
51
52 class dqpsk_mod(gr.hier_block2):
53     def __init__(self,
54                  samples_per_symbol=_def_samples_per_symbol,
55                  excess_bw=_def_excess_bw,
56                  gray_code=_def_gray_code,
57                  verbose=_def_verbose,
58                  log=_def_log):
59         """
60         Hierarchical block for RRC-filtered QPSK modulation.
61
62         The input is a byte stream (unsigned char) and the
63         output is the complex modulated signal at baseband.
64
65         @param samples_per_symbol: samples per symbol >= 2
66         @type samples_per_symbol: integer
67         @param excess_bw: Root-raised cosine filter excess bandwidth
68         @type excess_bw: float
69         @param gray_code: Tell modulator to Gray code the bits
70         @type gray_code: bool
71         @param verbose: Print information about modulator?
72         @type verbose: bool
73         @param debug: Print modualtion data to files?
74         @type debug: bool
75         """
76
77         gr.hier_block2.__init__(self, "dqpsk_mod",
78                                 gr.io_signature(1,1,gr.sizeof_char),       # Input signature
79                                 gr.io_signature(1,1,gr.sizeof_gr_complex)) # Output signature
80
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         # Define components from objects
118         self.define_component("bytes2chunks", self.bytes2chunks)
119         self.define_component("symbol_mapper", self.symbol_mapper)
120         self.define_component("diffenc", self.diffenc)
121         self.define_component("chunks2symbols", self.chunks2symbols)
122         self.define_component("rrc_filter", self.rrc_filter)
123
124         # Connect components
125         self.connect("self", 0, "bytes2chunks", 0)
126         self.connect("bytes2chunks", 0, "symbol_mapper", 0)
127         self.connect("symbol_mapper", 0, "diffenc", 0)
128         self.connect("diffenc", 0, "chunks2symbols", 0)
129         self.connect("chunks2symbols", 0, "rrc_filter", 0)
130         self.connect("rrc_filter", 0, "self", 0)
131
132         if verbose:
133             self._print_verbage()
134         
135         if log:
136             self._setup_logging()
137
138     def samples_per_symbol(self):
139         return self._samples_per_symbol
140
141     def bits_per_symbol(self=None):   # staticmethod that's also callable on an instance
142         return 2
143     bits_per_symbol = staticmethod(bits_per_symbol)      # make it a static method.  RTFM
144
145     def _print_verbage(self):
146         print "\nModulator:"
147         print "bits per symbol = %d" % self.bits_per_symbol()
148         print "Gray code = %s" % self._gray_code
149         print "RRS roll-off factor = %f" % self._excess_bw
150
151     def _setup_logging(self):
152         print "Modulation logging turned on."
153         self.define_component("bytes2chunks_dat", gr.file_sink(gr.sizeof_char, "tx_bytes2chunks.dat"))
154         self.define_component("symbol_mapper_dat", gr.file_sink(gr.sizeof_char, "tx_symbol_mapper.dat"))
155         self.define_component("diffenc_dat", gr.file_sink(gr.sizeof_char, "tx_diffenc.dat"))
156         self.define_component("chunks2symbols_dat", gr.file_sink(gr.sizeof_gr_complex, "tx_chunks2symbols.dat"))
157         self.define_component("rrc_filter_dat", gr.file_sink(gr.sizeof_gr_complex, "tx_rrc_filter.dat"))
158
159         self.connect("bytes2chunks", 0, "bytes2chunks_dat", 0)
160         self.connect("symbol_mapper", 0, "symbol_mapper_dat", 0)
161         self.connect("diffenc", 0, "diffenc_dat", 0)
162         self.connect("chunks2symbols", 0, "chunks2symbols_dat", 0)
163         self.connect("rrc_filter", 0, "rrc_filter_dat", 0)
164
165     def add_options(parser):
166         """
167         Adds QPSK modulation-specific options to the standard parser
168         """
169         parser.add_option("", "--excess-bw", type="float", default=_def_excess_bw,
170                           help="set RRC excess bandwith factor [default=%default] (PSK)")
171         parser.add_option("", "--no-gray-code", dest="gray_code",
172                           action="store_false", default=_def_gray_code,
173                           help="disable gray coding on modulated bits (PSK)")
174     add_options=staticmethod(add_options)
175
176
177     def extract_kwargs_from_options(options):
178         """
179         Given command line options, create dictionary suitable for passing to __init__
180         """
181         return modulation_utils.extract_kwargs_from_options(dqpsk_mod.__init__,
182                                                             ('self', 'fg'), options)
183     extract_kwargs_from_options=staticmethod(extract_kwargs_from_options)
184
185
186 # /////////////////////////////////////////////////////////////////////////////
187 #                           DQPSK demodulator
188 #
189 # Differentially coherent detection of differentially encoded qpsk
190 # /////////////////////////////////////////////////////////////////////////////
191
192 class dqpsk_demod(gr.hier_block2):
193
194     def __init__(self,
195                  samples_per_symbol=_def_samples_per_symbol,
196                  excess_bw=_def_excess_bw,
197                  costas_alpha=_def_costas_alpha,
198                  gain_mu=_def_gain_mu,
199                  mu=_def_mu,
200                  omega_relative_limit=_def_omega_relative_limit,
201                  gray_code=_def_gray_code,
202                  verbose=_def_verbose,
203                  log=_def_log):
204         """
205         Hierarchical block for RRC-filtered DQPSK demodulation
206
207         The input is the complex modulated signal at baseband.
208         The output is a stream of bits packed 1 bit per byte (LSB)
209
210         @param samples_per_symbol: samples per symbol >= 2
211         @type samples_per_symbol: float
212         @param excess_bw: Root-raised cosine filter excess bandwidth
213         @type excess_bw: float
214         @param costas_alpha: loop filter gain
215         @type costas_alphas: float
216         @param gain_mu: for M&M block
217         @type gain_mu: float
218         @param mu: for M&M block
219         @type mu: float
220         @param omega_relative_limit: for M&M block
221         @type omega_relative_limit: float
222         @param gray_code: Tell modulator to Gray code the bits
223         @type gray_code: bool
224         @param verbose: Print information about modulator?
225         @type verbose: bool
226         @param debug: Print modualtion data to files?
227         @type debug: bool
228         """
229
230         gr.hier_block2.__init__(self, "dqpsk_demod",
231                                 gr.io_signature(1,1,gr.sizeof_gr_complex), # Input signature
232                                 gr.io_signature(1,1,gr.sizeof_char))       # Output signature
233
234         self._samples_per_symbol = samples_per_symbol
235         self._excess_bw = excess_bw
236         self._costas_alpha = costas_alpha
237         self._mm_gain_mu = gain_mu
238         self._mm_mu = mu
239         self._mm_omega_relative_limit = omega_relative_limit
240         self._gray_code = gray_code
241
242         if samples_per_symbol < 2:
243             raise TypeError, "sbp must be >= 2, is %d" % samples_per_symbol
244
245         arity = pow(2,self.bits_per_symbol())
246  
247         # Automatic gain control
248         scale = (1.0/16384.0)
249         self.pre_scaler = gr.multiply_const_cc(scale)   # scale the signal from full-range to +-1
250         self.agc = gr.feedforward_agc_cc(16, 2.0)
251        
252         # RRC data filter
253         ntaps = 11 * samples_per_symbol
254         self.rrc_taps = gr.firdes.root_raised_cosine(
255             1.0,                      # gain
256             self._samples_per_symbol, # sampling rate
257             1.0,                      # symbol rate
258             self._excess_bw,          # excess bandwidth (roll-off factor)
259             ntaps)
260         self.rrc_filter=gr.interp_fir_filter_ccf(1, self.rrc_taps)        
261
262         # symbol clock recovery
263         self._mm_omega = self._samples_per_symbol
264         self._mm_gain_omega = .25 * self._mm_gain_mu * self._mm_gain_mu
265         self._costas_beta  = 0.25 * self._costas_alpha * self._costas_alpha
266         fmin = -0.01
267         fmax = 0.01
268         
269         self.receiver=gr.mpsk_receiver_cc(arity, pi/4.0,
270                                          self._costas_alpha, self._costas_beta,
271                                          fmin, fmax,
272                                          self._mm_mu, self._mm_gain_mu,
273                                          self._mm_omega, self._mm_gain_omega,
274                                          self._mm_omega_relative_limit)
275         
276         # Perform Differential decoding on the constellation
277         self.diffdec = gr.diff_phasor_cc()
278
279         # find closest constellation point
280         rot = 1
281         rotated_const = map(lambda pt: pt * rot, psk.constellation[arity])
282         self.slicer = gr.constellation_decoder_cb(rotated_const, range(arity))
283
284         if self._gray_code:
285             self.symbol_mapper = gr.map_bb(psk.gray_to_binary[arity])
286         else:
287             self.symbol_mapper = gr.map_bb(psk.ungray_to_binary[arity])
288         
289         # unpack the k bit vector into a stream of bits
290         self.unpack = gr.unpack_k_bits_bb(self.bits_per_symbol())
291  
292         # Define components
293         self.define_component("pre_scaler", self.pre_scaler)
294         self.define_component("agc", self.agc)
295         self.define_component("rrc_filter", self.rrc_filter)
296         self.define_component("receiver", self.receiver)
297         self.define_component("diffdec", self.diffdec)
298         self.define_component("slicer", self.slicer)
299         self.define_component("symbol_mapper", self.symbol_mapper)
300         self.define_component("unpack", self.unpack)
301
302         # Connect and Initialize base class
303         self.connect("self", 0, "pre_scaler", 0)
304         self.connect("pre_scaler", 0, "agc", 0)
305         self.connect("agc", 0, "rrc_filter", 0)
306         self.connect("rrc_filter", 0, "receiver", 0)
307         self.connect("receiver", 0, "diffdec", 0)
308         self.connect("diffdec", 0, "slicer", 0)
309         self.connect("slicer", 0, "symbol_mapper", 0)
310         self.connect("symbol_mapper", 0, "unpack", 0)
311         self.connect("unpack", 0, "self", 0)
312
313         if verbose:
314             self._print_verbage()
315         
316         if log:
317             self._setup_logging()
318
319     def samples_per_symbol(self):
320         return self._samples_per_symbol
321
322     def bits_per_symbol(self=None):   # staticmethod that's also callable on an instance
323         return 2
324     bits_per_symbol = staticmethod(bits_per_symbol)      # make it a static method.  RTFM
325
326     def _print_verbage(self):
327         print "\nDemodulator:"
328         print "bits per symbol:     %d"   % self.bits_per_symbol()
329         print "Gray code:           %s"   % self._gray_code
330         print "RRC roll-off factor: %.2f" % self._excess_bw
331         print "Costas Loop alpha:   %.2e" % self._costas_alpha
332         print "Costas Loop beta:    %.2e" % self._costas_beta
333         print "M&M mu:              %.2f" % self._mm_mu
334         print "M&M mu gain:         %.2e" % self._mm_gain_mu
335         print "M&M omega:           %.2f" % self._mm_omega
336         print "M&M omega gain:      %.2e" % self._mm_gain_omega
337         print "M&M omega limit:     %.2f" % self._mm_omega_relative_limit
338
339     def _setup_logging(self):
340         print "Demodulation logging turned on."
341         self.define_component("prescaler_dat",
342                               gr.file_sink(gr.sizeof_gr_complex, "rx_prescaler.dat"))
343         self.define_component("agc_dat",
344                               gr.file_sink(gr.sizeof_gr_complex, "rx_agc.dat"))
345         self.define_component("rrc_filter_dat",
346                               gr.file_sink(gr.sizeof_gr_complex, "rx_rrc_filter.dat"))
347         self.define_component("receiver_dat",
348                               gr.file_sink(gr.sizeof_gr_complex, "rx_receiver.dat"))
349         self.define_component("diffdec_dat",
350                               gr.file_sink(gr.sizeof_gr_complex, "rx_diffdec.dat"))
351         self.define_component("slicer_dat",
352                               gr.file_sink(gr.sizeof_char, "rx_slicer.dat"))
353         self.define_component("symbol_mapper_dat",
354                               gr.file_sink(gr.sizeof_char, "rx_symbol_mapper.dat"))
355         self.define_component("unpack_dat",
356                               gr.file_sink(gr.sizeof_char, "rx_unpack.dat"))
357
358         self.connect("pre_scaler", 0, "prescaler_dat", 0)
359         self.connect("agc", 0, "agc_dat", 0)
360         self.connect("rrc_filter", 0, "rrc_filter_dat", 0)
361         self.connect("receiver", 0, "receiver_dat", 0)
362         self.connect("diffdec", 0, "diffdec_dat", 0)
363         self.connect("slicer", 0, "slicer_dat", 0)
364         self.connect("symbol_mapper", 0, "symbol_mapper_dat", 0)
365         self.connect("unpack", 0, "unpack_dat", 0)
366
367     def add_options(parser):
368         """
369         Adds modulation-specific options to the standard parser
370         """
371         parser.add_option("", "--excess-bw", type="float", default=_def_excess_bw,
372                           help="set RRC excess bandwith factor [default=%default] (PSK)")
373         parser.add_option("", "--no-gray-code", dest="gray_code",
374                           action="store_false", default=_def_gray_code,
375                           help="disable gray coding on modulated bits (PSK)")
376         parser.add_option("", "--costas-alpha", type="float", default=None,
377                           help="set Costas loop alpha value [default=%default] (PSK)")
378         parser.add_option("", "--gain-mu", type="float", default=_def_gain_mu,
379                           help="set M&M symbol sync loop gain mu value [default=%default] (PSK)")
380         parser.add_option("", "--mu", type="float", default=_def_mu,
381                           help="set M&M symbol sync loop mu value [default=%default] (PSK)")
382     add_options=staticmethod(add_options)
383
384     def extract_kwargs_from_options(options):
385         """
386         Given command line options, create dictionary suitable for passing to __init__
387         """
388         return modulation_utils.extract_kwargs_from_options(
389             dqpsk_demod.__init__, ('self', 'fg'), options)
390     extract_kwargs_from_options=staticmethod(extract_kwargs_from_options)
391
392
393 #
394 # Add these to the mod/demod registry
395 #
396 modulation_utils.add_type_1_mod('dqpsk', dqpsk_mod)
397 modulation_utils.add_type_1_demod('dqpsk', dqpsk_demod)