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