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