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