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