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