Merge branch 'upstream' into dfsg-orig
[debian/gnuradio] / gnuradio-core / src / python / gnuradio / blks2impl / dqpsk2.py
1 #
2 # Copyright 2009,2010 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/digital for examples
23
24 """
25 differential QPSK modulation and demodulation.
26 """
27
28 from gnuradio import gr, gru, modulation_utils2
29 from math import pi, sqrt
30 import psk
31 import cmath
32 from pprint import pprint
33
34 # default values (used in __init__ and add_options)
35 _def_samples_per_symbol = 2
36 _def_excess_bw = 0.35
37 _def_gray_code = True
38 _def_verbose = False
39 _def_log = False
40
41 _def_freq_alpha = 0.010
42 _def_phase_alpha = 0.01
43 _def_timing_alpha = 0.100
44 _def_timing_beta = 0.010
45 _def_timing_max_dev = 1.5
46
47
48 # /////////////////////////////////////////////////////////////////////////////
49 #                           DQPSK modulator
50 # /////////////////////////////////////////////////////////////////////////////
51
52 class dqpsk2_mod(gr.hier_block2):
53
54     def __init__(self,
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 samples_per_symbol: samples per symbol >= 2
67         @type samples_per_symbol: integer
68         @param excess_bw: Root-raised cosine filter excess bandwidth
69         @type excess_bw: float
70         @param gray_code: Tell modulator to Gray code the bits
71         @type gray_code: bool
72         @param verbose: Print information about modulator?
73         @type verbose: bool
74         @param debug: Print modualtion data to files?
75         @type debug: bool
76         """
77
78         gr.hier_block2.__init__(self, "dqpsk2_mod",
79                                 gr.io_signature(1, 1, gr.sizeof_char),       # Input signature
80                                 gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature
81
82         self._samples_per_symbol = samples_per_symbol
83         self._excess_bw = excess_bw
84         self._gray_code = gray_code
85
86         if samples_per_symbol < 2:
87             raise TypeError, ("sbp must be >= 2, is %f" % samples_per_symbol)
88
89         ntaps = 11 * samples_per_symbol
90  
91         arity = pow(2,self.bits_per_symbol())
92
93         # turn bytes into k-bit vectors
94         self.bytes2chunks = \
95           gr.packed_to_unpacked_bb(self.bits_per_symbol(), gr.GR_MSB_FIRST)
96
97         if self._gray_code:
98             self.symbol_mapper = gr.map_bb(psk.binary_to_gray[arity])
99         else:
100             self.symbol_mapper = gr.map_bb(psk.binary_to_ungray[arity])
101             
102         self.diffenc = gr.diff_encoder_bb(arity)
103
104         rot = .707 + .707j
105         rotated_const = map(lambda pt: pt * rot, psk.constellation[arity])
106         self.chunks2symbols = gr.chunks_to_symbols_bc(rotated_const)
107
108         # pulse shaping filter
109         nfilts = 32
110         ntaps = 11 * int(nfilts * self._samples_per_symbol)  # make nfilts filters of ntaps each
111         self.rrc_taps = gr.firdes.root_raised_cosine(
112             nfilts,          # gain
113             nfilts,          # sampling rate based on 32 filters in resampler
114             1.0,             # symbol rate
115             self._excess_bw, # excess bandwidth (roll-off factor)
116             ntaps)
117         self.rrc_filter = gr.pfb_arb_resampler_ccf(self._samples_per_symbol, self.rrc_taps)
118
119         if verbose:
120             self._print_verbage()
121         
122         if log:
123             self._setup_logging()
124             
125         # Connect & Initialize base class
126         self.connect(self, self.bytes2chunks, self.symbol_mapper, self.diffenc,
127                      self.chunks2symbols, self.rrc_filter, self)
128
129     def samples_per_symbol(self):
130         return self._samples_per_symbol
131
132     def bits_per_symbol(self=None):   # staticmethod that's also callable on an instance
133         return 2
134     bits_per_symbol = staticmethod(bits_per_symbol)      # make it a static method.  RTFM
135
136     def _print_verbage(self):
137         print "\nModulator:"
138         print "bits per symbol:     %d" % self.bits_per_symbol()
139         print "Gray code:           %s" % self._gray_code
140         print "RRS roll-off factor: %f" % self._excess_bw
141
142     def _setup_logging(self):
143         print "Modulation logging turned on."
144         self.connect(self.bytes2chunks,
145                      gr.file_sink(gr.sizeof_char, "tx_bytes2chunks.dat"))
146         self.connect(self.symbol_mapper,
147                      gr.file_sink(gr.sizeof_char, "tx_graycoder.dat"))
148         self.connect(self.diffenc,
149                      gr.file_sink(gr.sizeof_char, "tx_diffenc.dat"))        
150         self.connect(self.chunks2symbols,
151                      gr.file_sink(gr.sizeof_gr_complex, "tx_chunks2symbols.dat"))
152         self.connect(self.rrc_filter,
153                      gr.file_sink(gr.sizeof_gr_complex, "tx_rrc_filter.dat"))
154
155     def add_options(parser):
156         """
157         Adds QPSK modulation-specific options to the standard parser
158         """
159         parser.add_option("", "--excess-bw", type="float", default=_def_excess_bw,
160                           help="set RRC excess bandwith factor [default=%default] (PSK)")
161         parser.add_option("", "--no-gray-code", dest="gray_code",
162                           action="store_false", default=_def_gray_code,
163                           help="disable gray coding on modulated bits (PSK)")
164     add_options=staticmethod(add_options)
165
166
167     def extract_kwargs_from_options(options):
168         """
169         Given command line options, create dictionary suitable for passing to __init__
170         """
171         return modulation_utils2.extract_kwargs_from_options(dqpsk2_mod.__init__,
172                                                             ('self',), options)
173     extract_kwargs_from_options=staticmethod(extract_kwargs_from_options)
174
175
176 # /////////////////////////////////////////////////////////////////////////////
177 #                           DQPSK demodulator
178 #
179 # Differentially coherent detection of differentially encoded qpsk
180 # /////////////////////////////////////////////////////////////////////////////
181
182 class dqpsk2_demod(gr.hier_block2):
183
184     def __init__(self, 
185                  samples_per_symbol=_def_samples_per_symbol,
186                  excess_bw=_def_excess_bw,
187                  freq_alpha=_def_freq_alpha,
188                  phase_alpha=_def_phase_alpha,
189                  timing_alpha=_def_timing_alpha,
190                  timing_max_dev=_def_timing_max_dev,
191                  gray_code=_def_gray_code,
192                  verbose=_def_verbose,
193                  log=_def_log,
194                  sync_out=False):
195         """
196         Hierarchical block for RRC-filtered DQPSK demodulation
197
198         The input is the complex modulated signal at baseband.
199         The output is a stream of bits packed 1 bit per byte (LSB)
200
201         @param samples_per_symbol: samples per symbol >= 2
202         @type samples_per_symbol: float
203         @param excess_bw: Root-raised cosine filter excess bandwidth
204         @type excess_bw: float
205         @param freq_alpha: loop filter gain for frequency recovery
206         @type freq_alpha: float
207         @param phase_alpha: loop filter gain
208         @type phase_alphas: float
209         @param timing_alpha: timing loop alpha gain
210         @type timing_alpha: float
211         @param timing_max: timing loop maximum rate deviations
212         @type timing_max: float
213         @param gray_code: Tell modulator to Gray code the bits
214         @type gray_code: bool
215         @param verbose: Print information about modulator?
216         @type verbose: bool
217         @param log: Print modualtion data to files?
218         @type log: bool
219         @param sync_out: Output a sync signal on :1?
220         @type sync_out: bool
221         """
222         if sync_out: io_sig_out = gr.io_signaturev(2, 2, (gr.sizeof_char, gr.sizeof_gr_complex))
223         else: io_sig_out = gr.io_signature(1, 1, gr.sizeof_char)
224
225         gr.hier_block2.__init__(self, "dqpsk2_demod",
226                                 gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
227                                 io_sig_out)       # Output signature
228
229         self._samples_per_symbol = samples_per_symbol
230         self._excess_bw = excess_bw
231         self._freq_alpha = freq_alpha
232         self._freq_beta = 0.25*self._freq_alpha**2
233         self._phase_alpha = phase_alpha
234         self._timing_alpha = timing_alpha
235         self._timing_beta = _def_timing_beta
236         self._timing_max_dev=timing_max_dev
237         self._gray_code = gray_code
238
239         if samples_per_symbol < 2:
240             raise TypeError, "sbp must be >= 2, is %d" % samples_per_symbol
241
242         arity = pow(2,self.bits_per_symbol())
243  
244         # Automatic gain control
245         self.agc = gr.agc2_cc(0.6e-1, 1e-3, 1, 1, 100)
246         #self.agc = gr.feedforward_agc_cc(16, 2.0)
247
248         # Frequency correction
249         self.freq_recov = gr.fll_band_edge_cc(self._samples_per_symbol, self._excess_bw,
250                                               11*int(self._samples_per_symbol),
251                                               self._freq_alpha, self._freq_beta)
252
253
254         # symbol timing recovery with RRC data filter
255         nfilts = 32
256         ntaps = 11 * int(samples_per_symbol*nfilts)
257         taps = gr.firdes.root_raised_cosine(nfilts, nfilts,
258                                             1.0/float(self._samples_per_symbol),
259                                             self._excess_bw, ntaps)
260         self.time_recov = gr.pfb_clock_sync_ccf(self._samples_per_symbol,
261                                                 self._timing_alpha,
262                                                 taps, nfilts, nfilts/2, self._timing_max_dev)
263         self.time_recov.set_beta(self._timing_beta)
264         
265
266         # Perform phase / fine frequency correction
267         self._phase_beta  = 0.25 * self._phase_alpha * self._phase_alpha
268         # Allow a frequency swing of +/- half of the sample rate
269         fmin = -0.5
270         fmax = 0.5
271
272         self.phase_recov = gr.costas_loop_cc(self._phase_alpha,
273                                              self._phase_beta,
274                                              fmax, fmin, arity)
275
276
277         # Perform Differential decoding on the constellation
278         self.diffdec = gr.diff_phasor_cc()
279         
280         # find closest constellation point
281         rot = 1
282         rotated_const = map(lambda pt: pt * rot, psk.constellation[arity])
283         self.slicer = gr.constellation_decoder_cb(rotated_const, range(arity))
284
285         if self._gray_code:
286             self.symbol_mapper = gr.map_bb(psk.gray_to_binary[arity])
287         else:
288             self.symbol_mapper = gr.map_bb(psk.ungray_to_binary[arity])
289         
290         # unpack the k bit vector into a stream of bits
291         self.unpack = gr.unpack_k_bits_bb(self.bits_per_symbol())
292
293         if verbose:
294             self._print_verbage()
295         
296         if log:
297             self._setup_logging()
298  
299         # Connect
300         self.connect(self, self.agc, 
301                      self.freq_recov, self.time_recov, self.phase_recov,
302                      self.diffdec, self.slicer, self.symbol_mapper, self.unpack, self)
303         if sync_out: self.connect(self.time_recov, (self, 1))
304
305     def samples_per_symbol(self):
306         return self._samples_per_symbol
307
308     def bits_per_symbol(self=None):   # staticmethod that's also callable on an instance
309         return 2
310     bits_per_symbol = staticmethod(bits_per_symbol)      # make it a static method.  RTFM
311
312     def _print_verbage(self):
313         print "\nDemodulator:"
314         print "bits per symbol:     %d"   % self.bits_per_symbol()
315         print "Gray code:           %s"   % self._gray_code
316         print "RRC roll-off factor: %.2f" % self._excess_bw
317         print "FLL gain:            %.2f" % self._freq_alpha
318         print "Timing alpha gain:   %.2f" % self._timing_alpha
319         print "Timing beta gain:    %.2f" % self._timing_beta
320         print "Timing max dev:      %.2f" % self._timing_max_dev
321         print "Phase track alpha:   %.2e" % self._phase_alpha
322         print "Phase track beta:    %.2e" % self._phase_beta
323
324     def _setup_logging(self):
325         print "Modulation logging turned on."
326         self.connect(self.agc,
327                      gr.file_sink(gr.sizeof_gr_complex, "rx_agc.dat"))
328         self.connect(self.freq_recov,
329                      gr.file_sink(gr.sizeof_gr_complex, "rx_freq_recov.dat"))
330         self.connect(self.time_recov,
331                      gr.file_sink(gr.sizeof_gr_complex, "rx_time_recov.dat"))
332         self.connect(self.phase_recov,
333                      gr.file_sink(gr.sizeof_gr_complex, "rx_phase_recov.dat"))
334         self.connect(self.diffdec,
335                      gr.file_sink(gr.sizeof_gr_complex, "rx_diffdec.dat"))        
336         self.connect(self.slicer,
337                      gr.file_sink(gr.sizeof_char, "rx_slicer.dat"))
338         self.connect(self.symbol_mapper,
339                      gr.file_sink(gr.sizeof_char, "rx_gray_decoder.dat"))
340         self.connect(self.unpack,
341                      gr.file_sink(gr.sizeof_char, "rx_unpack.dat"))
342
343     def add_options(parser):
344         """
345         Adds DQPSK demodulation-specific options to the standard parser
346         """
347         parser.add_option("", "--excess-bw", type="float", default=_def_excess_bw,
348                           help="set RRC excess bandwith factor [default=%default] (PSK)")
349         parser.add_option("", "--no-gray-code", dest="gray_code",
350                           action="store_false", default=_def_gray_code,
351                           help="disable gray coding on modulated bits (PSK)")
352         parser.add_option("", "--freq-alpha", type="float", default=_def_freq_alpha,
353                           help="set frequency lock loop alpha gain value [default=%default] (PSK)")
354         parser.add_option("", "--phase-alpha", type="float", default=_def_phase_alpha,
355                           help="set phase tracking loop alpha value [default=%default] (PSK)")
356         parser.add_option("", "--timing-alpha", type="float", default=_def_timing_alpha,
357                           help="set timing symbol sync loop gain alpha value [default=%default] (GMSK/PSK)")
358         parser.add_option("", "--timing-beta", type="float", default=_def_timing_beta,
359                           help="set timing symbol sync loop gain beta value [default=%default] (GMSK/PSK)")
360         parser.add_option("", "--timing-max-dev", type="float", default=_def_timing_max_dev,
361                           help="set timing symbol sync loop maximum deviation [default=%default] (GMSK/PSK)")
362     add_options=staticmethod(add_options)
363
364     def extract_kwargs_from_options(options):
365         """
366         Given command line options, create dictionary suitable for passing to __init__
367         """
368         return modulation_utils2.extract_kwargs_from_options(
369             dqpsk2_demod.__init__, ('self',), options)
370     extract_kwargs_from_options=staticmethod(extract_kwargs_from_options)
371
372
373 #
374 # Add these to the mod/demod registry
375 #
376 modulation_utils2.add_type_1_mod('dqpsk2', dqpsk2_mod)
377 modulation_utils2.add_type_1_demod('dqpsk2', dqpsk2_demod)