def __init__(self, rx_callback, SNR):
        """
        @param options Optparse option field for command line arguments.
        @param rx_callback Callback function for the event when a packet is received.
        """
        gr.flow_graph.__init__(self)

        self.samples_per_symbol = 2
        self.data_rate = 2000000
        payload_size = 128  # bytes

        self.packet_transmitter = ieee802_15_4_pkt.ieee802_15_4_mod_pkts(
            self, spb=self.samples_per_symbol, msgq_limit=2)

        # add some noise
        print " Setting SNR to ", SNR
        add = gr.add_cc()
        noise = gr.noise_source_c(gr.GR_GAUSSIAN, pow(10.0, -SNR / 20.0))

        self.packet_receiver = ieee802_15_4_pkt.ieee802_15_4_demod_pkts(
            self,
            callback=rx_callback,
            sps=self.samples_per_symbol,
            symbol_rate=self.data_rate,
            threshold=-1)

        self.connect(self.packet_transmitter, (add, 0))
        self.connect(noise, (add, 1))
        self.connect(add, self.packet_receiver)
 def test_002_freq (self):
     """ Add a fine frequency offset and see if that get's detected properly """
     fft_len = 32
     cp_len = 4
     # This frequency offset is normalized to rads, i.e. \pi == f_s/2
     max_freq_offset = 2*numpy.pi/fft_len # Otherwise, it's coarse
     freq_offset = ((2 * random.random()) - 1) * max_freq_offset
     sig_len = (fft_len + cp_len) * 10
     sync_symbol = [(random.randint(0, 1)*2)-1 for x in range(fft_len/2)] * 2
     tx_signal = sync_symbol[-cp_len:] + \
                 sync_symbol + \
                 [(random.randint(0, 1)*2)-1 for x in range(sig_len)]
     mult = gr.multiply_cc()
     add = gr.add_cc()
     sync = digital.ofdm_sync_sc_cfb(fft_len, cp_len, True)
     channel = gr.channel_model(0.005, freq_offset / 2.0 / numpy.pi)
     sink_freq   = gr.vector_sink_f()
     sink_detect = gr.vector_sink_b()
     self.tb.connect(gr.vector_source_c(tx_signal), channel, sync)
     self.tb.connect((sync, 0), sink_freq)
     self.tb.connect((sync, 1), sink_detect)
     self.tb.run()
     phi_hat = sink_freq.data()[sink_detect.data().index(1)]
     est_freq_offset = 2 * phi_hat / fft_len
     self.assertAlmostEqual(est_freq_offset, freq_offset, places=2)
    def __init__(self):
        gr.top_block.__init__(self)

        Rs = 8000
        f1 = 100
        f2 = 200

        npts = 2048

        self.qapp = QtGui.QApplication(sys.argv)

        src1 = gr.sig_source_c(Rs, gr.GR_SIN_WAVE, f1, 0.5, 0)
        src2 = gr.sig_source_c(Rs, gr.GR_SIN_WAVE, f2, 0.5, 0)
        src  = gr.add_cc()
        channel = filter.channel_model(0.001)
        thr = gr.throttle(gr.sizeof_gr_complex, 100*npts)
        self.snk1 = qtgui.const_sink_c(npts, "Constellation Example", 1)

        self.connect(src1, (src,0))
        self.connect(src2, (src,1))
        self.connect(src,  channel, thr, (self.snk1, 0))

        self.ctrl_win = control_box()
        self.ctrl_win.attach_signal1(src1)
        self.ctrl_win.attach_signal2(src2)

        # Get the reference pointer to the SpectrumDisplayForm QWidget
        pyQt  = self.snk1.pyqwidget()

        # Wrap the pointer as a PyQt SIP object
        # This can now be manipulated as a PyQt4.QtGui.QWidget
        pyWin = sip.wrapinstance(pyQt, QtGui.QWidget)

        self.main_box = dialog_box(pyWin, self.ctrl_win)
        self.main_box.show()
    def __init__(self, fg, noise_voltage=0.0, frequency_offset=0.0, epsilon=1.0, taps=[1.0,0.0]):
        ''' Creates a channel model that includes:
          - AWGN noise power in terms of noise voltage
          - A frequency offest in the channel in ratio
          - A timing offset ratio to model clock difference (epsilon)
          - Multipath taps
          '''

        print epsilon
        self.timing_offset = gr.fractional_interpolator_cc(0, epsilon)
        
        self.multipath = gr.fir_filter_ccc(1, taps)
        
        self.noise_adder = gr.add_cc()
        self.noise = gr.noise_source_c(gr.GR_GAUSSIAN,noise_voltage)
        self.freq_offset = gr.sig_source_c(1, gr.GR_SIN_WAVE, frequency_offset, 1.0, 0.0)
        self.mixer_offset = gr.multiply_cc()

        fg.connect(self.timing_offset, self.multipath)
        fg.connect(self.multipath, (self.mixer_offset,0))
        fg.connect(self.freq_offset,(self.mixer_offset,1))
        fg.connect(self.mixer_offset, (self.noise_adder,1))
        fg.connect(self.noise, (self.noise_adder,0))
        
        gr.hier_block.__init__(self, fg, self.timing_offset, self.noise_adder)
Exemple #5
0
    def set_waveform(self, type):
        self.lock()
        self.disconnect_all()
        if type == gr.GR_SIN_WAVE or type == gr.GR_CONST_WAVE:
            self._src = gr.sig_source_c(
                self[SAMP_RATE_KEY],  # Sample rate
                type,  # Waveform type
                self[WAVEFORM_FREQ_KEY],  # Waveform frequency
                self[AMPLITUDE_KEY],  # Waveform amplitude
                self[WAVEFORM_OFFSET_KEY])  # Waveform offset
        elif type == gr.GR_GAUSSIAN or type == gr.GR_UNIFORM:
            self._src = gr.noise_source_c(type, self[AMPLITUDE_KEY])
        elif type == "2tone":
            self._src1 = gr.sig_source_c(self[SAMP_RATE_KEY], gr.GR_SIN_WAVE,
                                         self[WAVEFORM_FREQ_KEY],
                                         self[AMPLITUDE_KEY] / 2.0, 0)
            if (self[WAVEFORM2_FREQ_KEY] is None):
                self[WAVEFORM2_FREQ_KEY] = -self[WAVEFORM_FREQ_KEY]

            self._src2 = gr.sig_source_c(self[SAMP_RATE_KEY], gr.GR_SIN_WAVE,
                                         self[WAVEFORM2_FREQ_KEY],
                                         self[AMPLITUDE_KEY] / 2.0, 0)
            self._src = gr.add_cc()
            self.connect(self._src1, (self._src, 0))
            self.connect(self._src2, (self._src, 1))
        elif type == "sweep":
            # rf freq is center frequency
            # waveform_freq is total swept width
            # waveform2_freq is sweep rate
            # will sweep from (rf_freq-waveform_freq/2) to (rf_freq+waveform_freq/2)
            if self[WAVEFORM2_FREQ_KEY] is None:
                self[WAVEFORM2_FREQ_KEY] = 0.1

            self._src1 = gr.sig_source_f(self[SAMP_RATE_KEY], gr.GR_TRI_WAVE,
                                         self[WAVEFORM2_FREQ_KEY], 1.0, -0.5)
            self._src2 = gr.frequency_modulator_fc(
                self[WAVEFORM_FREQ_KEY] * 2 * math.pi / self[SAMP_RATE_KEY])
            self._src = gr.multiply_const_cc(self[AMPLITUDE_KEY])
            self.connect(self._src1, self._src2, self._src)
        else:
            raise RuntimeError("Unknown waveform type")

        self.connect(self._src, self._u)
        self.unlock()

        if self._verbose:
            print "Set baseband modulation to:", waveforms[type]
            if type == gr.GR_SIN_WAVE:
                print "Modulation frequency: %sHz" % (n2s(
                    self[WAVEFORM_FREQ_KEY]), )
                print "Initial phase:", self[WAVEFORM_OFFSET_KEY]
            elif type == "2tone":
                print "Tone 1: %sHz" % (n2s(self[WAVEFORM_FREQ_KEY]), )
                print "Tone 2: %sHz" % (n2s(self[WAVEFORM2_FREQ_KEY]), )
            elif type == "sweep":
                print "Sweeping across %sHz to %sHz" % (n2s(
                    -self[WAVEFORM_FREQ_KEY] /
                    2.0), n2s(self[WAVEFORM_FREQ_KEY] / 2.0))
                print "Sweep rate: %sHz" % (n2s(self[WAVEFORM2_FREQ_KEY]), )
            print "TX amplitude:", self[AMPLITUDE_KEY]
 def test_002_freq (self):
     """ Add a fine frequency offset and see if that get's detected properly """
     fft_len = 32
     cp_len = 4
     freq_offset = 0.1 # Must stay < 2*pi/fft_len = 0.196 (otherwise, it's coarse)
     sig_len = (fft_len + cp_len) * 10
     sync_symbol = [(random.randint(0, 1)*2)-1 for x in range(fft_len/2)] * 2
     tx_signal = sync_symbol[-cp_len:] + \
                 sync_symbol + \
                 [(random.randint(0, 1)*2)-1 for x in range(sig_len)]
     mult = gr.multiply_cc()
     add = gr.add_cc()
     sync = digital.ofdm_sync_sc_cfb(fft_len, cp_len)
     sink_freq   = gr.vector_sink_f()
     sink_detect = gr.vector_sink_b()
     self.tb.connect(gr.vector_source_c(tx_signal), (mult, 0), (add, 0))
     self.tb.connect(gr.sig_source_c(2 * numpy.pi, gr.GR_SIN_WAVE, freq_offset, 1.0), (mult, 1))
     self.tb.connect(gr.noise_source_c(gr.GR_GAUSSIAN, .01), (add, 1))
     self.tb.connect(add, sync)
     self.tb.connect((sync, 0), sink_freq)
     self.tb.connect((sync, 1), sink_detect)
     self.tb.run()
     phi_hat = sink_freq.data()[sink_detect.data().index(1)]
     est_freq_offset = 2 * phi_hat / fft_len
     self.assertAlmostEqual(est_freq_offset, freq_offset, places=2)
 def test_001_detect (self):
     """ Send two bursts, with zeros in between, and check
     they are both detected at the correct position and no
     false alarms occur """
     n_zeros = 15
     fft_len = 32
     cp_len = 4
     sig_len = (fft_len + cp_len) * 10
     sync_symbol = [(random.randint(0, 1)*2)-1 for x in range(fft_len/2)] * 2
     tx_signal = [0,] * n_zeros + \
                 sync_symbol[-cp_len:] + \
                 sync_symbol + \
                 [(random.randint(0, 1)*2)-1 for x in range(sig_len)]
     tx_signal = tx_signal * 2
     add = gr.add_cc()
     sync = digital.ofdm_sync_sc_cfb(fft_len, cp_len)
     sink_freq   = gr.vector_sink_f()
     sink_detect = gr.vector_sink_b()
     self.tb.connect(gr.vector_source_c(tx_signal), (add, 0))
     self.tb.connect(gr.noise_source_c(gr.GR_GAUSSIAN, .01), (add, 1))
     self.tb.connect(add, sync)
     self.tb.connect((sync, 0), sink_freq)
     self.tb.connect((sync, 1), sink_detect)
     self.tb.run()
     sig1_detect = sink_detect.data()[0:len(tx_signal)/2]
     sig2_detect = sink_detect.data()[len(tx_signal)/2:]
     self.assertTrue(abs(sig1_detect.index(1) - (n_zeros + fft_len + cp_len)) < cp_len)
     self.assertTrue(abs(sig2_detect.index(1) - (n_zeros + fft_len + cp_len)) < cp_len)
     self.assertEqual(numpy.sum(sig1_detect), 1)
     self.assertEqual(numpy.sum(sig2_detect), 1)
    def __init__(self, rx_callback, spb, alpha, SNR):
        # m is constellation size
        # if diff==True we are doing DxPSK
        gr.flow_graph.__init__(self)

        fg = self

        # transmitter
        self.packet_transmitter = bbn_80211b_mod_pkts(fg, spb=spb, alpha=alpha,
                                                      gain=1)

        # add some noise
        add = gr.add_cc()
        noise = gr.noise_source_c(gr.GR_GAUSSIAN, pow(10.0,-SNR/20.0))

        # channel filter
        rx_filt_taps = gr.firdes.low_pass(1,spb,0.8,0.1,gr.firdes.WIN_HANN)
        rx_filt = gr.fir_filter_ccf(1,rx_filt_taps)

        # receiver
        self.bit_receiver = bbn_80211b_demod_pkts(self, spb=spb, alpha=alpha,
                                                  callback=rx_callback)

        fg.connect(self.packet_transmitter, (add,0))
        fg.connect(noise, (add,1))

        #xfile=gr.file_sink(gr.sizeof_gr_complex,"txdata");
        #fg.connect(add, xfile)

        fg.connect(add, rx_filt)
        fg.connect(rx_filt, self.bit_receiver)
    def test_003_multiburst (self):
        """ Send several bursts, see if the number of detects is correct.
        Burst lengths and content are random.
        """
        n_bursts = 42
        fft_len = 32
        cp_len = 4
        tx_signal = []
        for i in xrange(n_bursts):
            sync_symbol = [(random.randint(0, 1)*2)-1 for x in range(fft_len/2)] * 2
            tx_signal += [0,] * random.randint(0, 2*fft_len) + \
                         sync_symbol[-cp_len:] + \
                         sync_symbol + \
                         [(random.randint(0, 1)*2)-1 for x in range(fft_len * random.randint(5,23))]
        add = gr.add_cc()
        sync = digital.ofdm_sync_sc_cfb(fft_len, cp_len)
        sink_freq   = gr.vector_sink_f()
        sink_detect = gr.vector_sink_b()
        self.tb.connect(gr.vector_source_c(tx_signal), (add, 0))
        self.tb.connect(gr.noise_source_c(gr.GR_GAUSSIAN, .005), (add, 1))
        self.tb.connect(add, sync)
        self.tb.connect((sync, 0), sink_freq)
        self.tb.connect((sync, 1), sink_detect)
        self.tb.run()
        self.assertEqual(numpy.sum(sink_detect.data()), n_bursts,
                msg="""Because of statistics, it is possible (though unlikely)
that the number of detected bursts differs slightly. If the number of detects is
off by one or two, run the test again and see what happen.
Detection error was: %d """ % (numpy.sum(sink_detect.data()) - n_bursts)
        )
Exemple #10
0
 def test_002_freq(self):
     """ Add a fine frequency offset and see if that get's detected properly """
     fft_len = 32
     cp_len = 4
     # This frequency offset is normalized to rads, i.e. \pi == f_s/2
     max_freq_offset = 2 * numpy.pi / fft_len  # Otherwise, it's coarse
     freq_offset = ((2 * random.random()) - 1) * max_freq_offset
     sig_len = (fft_len + cp_len) * 10
     sync_symbol = [(random.randint(0, 1) * 2) - 1
                    for x in range(fft_len / 2)] * 2
     tx_signal = sync_symbol[-cp_len:] + \
                 sync_symbol + \
                 [(random.randint(0, 1)*2)-1 for x in range(sig_len)]
     mult = gr.multiply_cc()
     add = gr.add_cc()
     sync = digital.ofdm_sync_sc_cfb(fft_len, cp_len, True)
     channel = gr.channel_model(0.005, freq_offset / 2.0 / numpy.pi)
     sink_freq = gr.vector_sink_f()
     sink_detect = gr.vector_sink_b()
     self.tb.connect(gr.vector_source_c(tx_signal), channel, sync)
     self.tb.connect((sync, 0), sink_freq)
     self.tb.connect((sync, 1), sink_detect)
     self.tb.run()
     phi_hat = sink_freq.data()[sink_detect.data().index(1)]
     est_freq_offset = 2 * phi_hat / fft_len
     self.assertAlmostEqual(est_freq_offset, freq_offset, places=2)
    def __init__(self, noise_voltage=0.0, frequency_offset=0.0, epsilon=1.0, taps=[1.0,0.0], noise_seed=3021):
        ''' Creates a channel model that includes:
          - AWGN noise power in terms of noise voltage
          - A frequency offest in the channel in ratio
          - A timing offset ratio to model clock difference (epsilon)
          - Multipath taps
          '''
	gr.hier_block2.__init__(self, "channel_model",
				gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
				gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature

        #print epsilon
        self.timing_offset = gr.fractional_interpolator_cc(0, epsilon)
        
        self.multipath = gr.fir_filter_ccc(1, taps)
        
        self.noise_adder = gr.add_cc()
        self.noise = gr.noise_source_c(gr.GR_GAUSSIAN, noise_voltage, noise_seed)
        self.freq_offset = gr.sig_source_c(1, gr.GR_SIN_WAVE, frequency_offset, 1.0, 0.0)
        self.mixer_offset = gr.multiply_cc()

        self.connect(self, self.timing_offset, self.multipath)
        self.connect(self.multipath, (self.mixer_offset,0))
        self.connect(self.freq_offset,(self.mixer_offset,1))
        self.connect(self.mixer_offset, (self.noise_adder,1))
        self.connect(self.noise, (self.noise_adder,0))
        self.connect(self.noise_adder, self)
Exemple #12
0
    def __init__(self):
        gr.top_block.__init__(self, "FFT Sink Test")

        fft_size = 256

        # build our flow graph
        input_rate = 2048.0e3

        #Generate some noise
        noise = gr.noise_source_c(gr.GR_UNIFORM, 1.0/10)

        # Generate a complex sinusoid
        src1 = gr.sig_source_c (input_rate, gr.GR_SIN_WAVE, 2e3, 1)
        #src1 = gr.sig_source_c(input_rate, gr.GR_CONST_WAVE, 57.50e3, 1)

        # We add these throttle blocks so that this demo doesn't
        # suck down all the CPU available.  Normally you wouldn't use these.
        thr1 = gr.throttle(gr.sizeof_gr_complex, input_rate)

        test_fft = zmq_fft_sink_c(title="Complex Data", fft_size=fft_size,
                            sample_rate=input_rate, baseband_freq=100e3,
                            ref_level=0, y_per_div=20, y_divs=10)

        combine1 = gr.add_cc()
        #self.connect(src1, (combine1, 0))
        #self.connect(noise,(combine1, 1))
        self.connect(src1, thr1, test_fft)
    def __init__(self, sample_rate, noise_voltage, frequency_offset, seed=False):

	gr.hier_block2.__init__(self, "awgn_channel",
			        gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
				gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature
				        
        # Create the Gaussian noise source
        if not seed:
            self.noise = gr.noise_source_c(gr.GR_GAUSSIAN, noise_voltage)
        else:
            rseed = int(time.time())
            self.noise = gr.noise_source_c(gr.GR_GAUSSIAN, noise_voltage, rseed)

        self.adder =  gr.add_cc()

        # Create the frequency offset
        self.offset = gr.sig_source_c(1, gr.GR_SIN_WAVE,
                                      frequency_offset, 1.0, 0.0)
        self.mixer = gr.multiply_cc()

        # Connect the components
        self.connect(self, (self.mixer, 0))
        self.connect(self.offset, (self.mixer, 1))
        self.connect(self.mixer, (self.adder, 0))
        self.connect(self.noise, (self.adder, 1))
	self.connect(self.adder, self)
    def __init__(self, frame, panel, vbox, argv):
        stdgui2.std_top_block.__init__ (self, frame, panel, vbox, argv)

        pspectrum_len = 1024

        # build our flow graph
        input_rate = 2e6

        #Generate some noise
        noise = gr.noise_source_c(gr.GR_GAUSSIAN, 1.0/10)

        # Generate a complex sinusoid
        #source = gr.file_source(gr.sizeof_gr_complex, 'foobar2.dat', repeat=True)

        src1 = gr.sig_source_c (input_rate, gr.GR_SIN_WAVE, -500e3, 1)
        src2 = gr.sig_source_c (input_rate, gr.GR_SIN_WAVE, 500e3, 1)
        src3 = gr.sig_source_c (input_rate, gr.GR_SIN_WAVE, -250e3, 2)

        # We add these throttle blocks so that this demo doesn't
        # suck down all the CPU available.  Normally you wouldn't use these.
        thr1 = gr.throttle(gr.sizeof_gr_complex, input_rate)

        sink1 = spectrum_sink_c (panel, title="Spectrum Sink", pspectrum_len=pspectrum_len,
                            sample_rate=input_rate, baseband_freq=0,
                            ref_level=0, y_per_div=20, y_divs=10, m = 70, n = 3, nsamples = 1024)
        vbox.Add (sink1.win, 1, wx.EXPAND)

        combine1=gr.add_cc()
        self.connect(src1,(combine1,0))
        self.connect(src2,(combine1,1))
        self.connect(src3,(combine1,2))
        self.connect(noise, (combine1,3))
        self.connect(combine1,thr1, sink1)
Exemple #15
0
    def test_003_multiburst(self):
        """ Send several bursts, see if the number of detects is correct.
        Burst lengths and content are random.
        """
        n_bursts = 42
        fft_len = 32
        cp_len = 4
        tx_signal = []
        for i in xrange(n_bursts):
            sync_symbol = [(random.randint(0, 1) * 2) - 1
                           for x in range(fft_len / 2)] * 2
            tx_signal += [0,] * random.randint(0, 2*fft_len) + \
                         sync_symbol[-cp_len:] + \
                         sync_symbol + \
                         [(random.randint(0, 1)*2)-1 for x in range(fft_len * random.randint(5,23))]
        add = gr.add_cc()
        sync = digital.ofdm_sync_sc_cfb(fft_len, cp_len)
        sink_freq = gr.vector_sink_f()
        sink_detect = gr.vector_sink_b()
        channel = gr.channel_model(0.005)
        self.tb.connect(gr.vector_source_c(tx_signal), channel, sync)
        self.tb.connect((sync, 0), sink_freq)
        self.tb.connect((sync, 1), sink_detect)
        self.tb.run()
        n_bursts_detected = numpy.sum(sink_detect.data())
        # We allow for one false alarm or missed burst
        self.assertTrue(
            abs(n_bursts_detected - n_bursts) <= 1,
            msg="""Because of statistics, it is possible (though unlikely)
that the number of detected bursts differs slightly. If the number of detects is
off by one or two, run the test again and see what happen.
Detection error was: %d """ % (numpy.sum(sink_detect.data()) - n_bursts))
    def __init__(self, n_sinusoids = 1, SNR = 10, samp_rate = 32e3, nsamples = 2048):
        gr.hier_block2.__init__(self, "ESPRIT/MUSIC signal generator",
                                gr.io_signature(0, 0, gr.sizeof_float),
                                gr.io_signature(1, 1, gr.sizeof_gr_complex))
        sigampl = 10.0**(SNR/10.0) # noise power is 1
        self.srcs = list()

        self.n_sinusoids = n_sinusoids
        self.samp_rate = samp_rate
        # create our signals ...
        for s in range(n_sinusoids):
            self.srcs.append(gr.sig_source_c(samp_rate,
                gr.GR_SIN_WAVE,1000 * s + 2000,
                numpy.sqrt(sigampl/n_sinusoids)))

        seed = ord(os.urandom(1))
        self.noise = gr.noise_source_c(gr.GR_GAUSSIAN, 1, seed)
        self.add = gr.add_cc()
        self.head = gr.head(gr.sizeof_gr_complex, nsamples)
        self.sink = gr.vector_sink_f(vlen=n_sinusoids)
        # wire it up ... 
        for s in range(n_sinusoids):
            self.connect(self.srcs[s], (self.add, s))
        # Additive noise
        self.connect(self.noise, (self.add, n_sinusoids))
        self.connect(self.add, self.head, self)
Exemple #17
0
 def test_001_detect(self):
     """ Send two bursts, with zeros in between, and check
     they are both detected at the correct position and no
     false alarms occur """
     n_zeros = 15
     fft_len = 32
     cp_len = 4
     sig_len = (fft_len + cp_len) * 10
     sync_symbol = [(random.randint(0, 1) * 2) - 1
                    for x in range(fft_len / 2)] * 2
     tx_signal = [0,] * n_zeros + \
                 sync_symbol[-cp_len:] + \
                 sync_symbol + \
                 [(random.randint(0, 1)*2)-1 for x in range(sig_len)]
     tx_signal = tx_signal * 2
     add = gr.add_cc()
     sync = digital.ofdm_sync_sc_cfb(fft_len, cp_len)
     sink_freq = gr.vector_sink_f()
     sink_detect = gr.vector_sink_b()
     self.tb.connect(gr.vector_source_c(tx_signal), (add, 0))
     self.tb.connect(gr.noise_source_c(gr.GR_GAUSSIAN, .005), (add, 1))
     self.tb.connect(add, sync)
     self.tb.connect((sync, 0), sink_freq)
     self.tb.connect((sync, 1), sink_detect)
     self.tb.run()
     sig1_detect = sink_detect.data()[0:len(tx_signal) / 2]
     sig2_detect = sink_detect.data()[len(tx_signal) / 2:]
     self.assertTrue(
         abs(sig1_detect.index(1) - (n_zeros + fft_len + cp_len)) < cp_len)
     self.assertTrue(
         abs(sig2_detect.index(1) - (n_zeros + fft_len + cp_len)) < cp_len)
     self.assertEqual(numpy.sum(sig1_detect), 1)
     self.assertEqual(numpy.sum(sig2_detect), 1)
    def __init__(self, rx_callback, SNR):
        """
        @param options Optparse option field for command line arguments.
        @param rx_callback Callback function for the event when a packet is received.
        """
        gr.flow_graph.__init__(self)

        self.samples_per_symbol = 2
	self.data_rate = 2000000
        payload_size = 128             # bytes

	self.packet_transmitter = ieee802_15_4_pkt.ieee802_15_4_mod_pkts(self, spb=self.samples_per_symbol, msgq_limit=2)

        # add some noise
	print " Setting SNR to ", SNR
        add = gr.add_cc()
        noise = gr.noise_source_c(gr.GR_GAUSSIAN, pow(10.0,-SNR/20.0))

        self.packet_receiver = ieee802_15_4_pkt.ieee802_15_4_demod_pkts(self,
                                                                callback=rx_callback,
                                                                sps=self.samples_per_symbol,
                                                                symbol_rate=self.data_rate,
                                                                threshold=-1)

        self.connect (self.packet_transmitter, (add,0))
        self.connect (noise, (add,1))
        self.connect(add,  self.packet_receiver)
 def run_flow_graph(sync_sym1, sync_sym2, data_sym):
     top_block = gr.top_block()
     carr_offset = random.randint(-max_offset/2, max_offset/2) * 2
     tx_data = shift_tuple(sync_sym1, carr_offset) + \
               shift_tuple(sync_sym2, carr_offset) + \
               shift_tuple(data_sym,  carr_offset)
     channel = [rand_range(min_chan_ampl, max_chan_ampl) * numpy.exp(1j * rand_range(0, 2 * numpy.pi)) for x in range(fft_len)]
     src = gr.vector_source_c(tx_data, False, fft_len)
     chan= gr.multiply_const_vcc(channel)
     noise = gr.noise_source_c(gr.GR_GAUSSIAN, wgn_amplitude)
     add = gr.add_cc(fft_len)
     chanest = digital.ofdm_chanest_vcvc(sync_sym1, sync_sym2, 1)
     sink = gr.vector_sink_c(fft_len)
     top_block.connect(src, chan, (add, 0), chanest, sink)
     top_block.connect(noise, gr.stream_to_vector(gr.sizeof_gr_complex, fft_len), (add, 1))
     top_block.run()
     channel_est = None
     carr_offset_hat = 0
     rx_sym_est = [0,] * fft_len
     tags = sink.tags()
     for tag in tags:
         if pmt.pmt_symbol_to_string(tag.key) == 'ofdm_sync_carr_offset':
             carr_offset_hat = pmt.pmt_to_long(tag.value)
             self.assertEqual(carr_offset, carr_offset_hat)
         if pmt.pmt_symbol_to_string(tag.key) == 'ofdm_sync_chan_taps':
             channel_est = shift_tuple(pmt.pmt_c32vector_elements(tag.value), carr_offset)
     shifted_carrier_mask = shift_tuple(carrier_mask, carr_offset)
     for i in range(fft_len):
         if shifted_carrier_mask[i] and channel_est[i]:
             self.assertAlmostEqual(channel[i], channel_est[i], places=0)
             rx_sym_est[i] = (sink.data()[i] / channel_est[i]).real
     return (carr_offset, list(shift_tuple(rx_sym_est, -carr_offset_hat)))
def build_graph (input, raw, snr, freq_offset, coeffs, mag):

    # Initialize empty flow graph
    fg = gr.top_block ()

    # Set up file source
    src = gr.file_source (1, input)

    # Set up GMSK modulator, 2 samples per symbol
    mod = gmsk_mod(2)

    # Amplify the signal
    tx_amp = 1
    amp = gr.multiply_const_cc(1)
    amp.set_k(tx_amp)

    # Compute proper noise voltage based on SNR
    SNR = 10.0**(snr/10.0)
    power_in_signal = abs(tx_amp)**2
    noise_power = power_in_signal/SNR
    noise_voltage = math.sqrt(noise_power)

    # Generate noise
    rseed = int(time.time())
    noise = gr.noise_source_c(gr.GR_GAUSSIAN, noise_voltage, rseed)
    adder = gr.add_cc()
    fg.connect(noise, (adder, 1))
    
    # Create the frequency offset, 0 for now
    offset = gr.sig_source_c(1, gr.GR_SIN_WAVE, freq_offset, 1.0, 0.0)
    mixer = gr.multiply_cc()
    fg.connect(offset, (mixer, 1))

    # Pass the noisy data to the matched filter
    dfile = open(coeffs, 'r')
    data = []
    for line in dfile:
      data.append(complex(*map(float,line.strip().strip("()").split(" "))).conjugate())
    dfile.close()
    data.reverse()
    mfilter = gr.fir_filter_ccc(1, data)


    # Connect the flow graph
    fg.connect(src, mod)
    fg.connect(mod, (mixer, 0))
    fg.connect(mixer, (adder, 0))

    if mag:
      raw_dst = gr.file_sink (gr.sizeof_float, raw)
      magnitude = gr.complex_to_mag(1)
      fg.connect(adder, mfilter, magnitude, raw_dst)
    else:
      raw_dst = gr.file_sink (gr.sizeof_gr_complex, raw)
      fg.connect(adder, mfilter, raw_dst)

    print "SNR(db): " + str(snr)
    print "Frequency Offset: " + str(freq_offset)

    return fg
Exemple #21
0
    def __init__(self):
        gr.top_block.__init__(self)

        parser = OptionParser(option_class=eng_option)
        parser.add_option(
            "-f",
            "--freq1",
            type="eng_float",
            default=1e6,
            help="set waveform frequency to FREQ [default=%default]")
        parser.add_option(
            "-g",
            "--freq2",
            type="eng_float",
            default=1e6,
            help="set waveform frequency to FREQ [default=%default]")
        parser.add_option(
            "-a",
            "--amplitude1",
            type="eng_float",
            default=16e3,
            help="set waveform amplitude to AMPLITUDE [default=%default]",
            metavar="AMPL")
        parser.add_option(
            "-b",
            "--amplitude2",
            type="eng_float",
            default=16e3,
            help="set waveform amplitude to AMPLITUDE [default=%default]",
            metavar="AMPL")

        parser.add_option(
            "-i",
            "--interp",
            type="int",
            default=32,
            help="assume fgpa interpolation rate is INTERP [default=%default]")

        (options, args) = parser.parse_args()
        if len(args) != 0:
            parser.print_help()
            raise SystemExit, 1

        src0 = gr.sig_source_c(master_clock / options.interp, gr.GR_SIN_WAVE,
                               options.freq1, options.amplitude1)
        src1 = gr.sig_source_c(master_clock / options.interp, gr.GR_SIN_WAVE,
                               options.freq2, options.amplitude2)

        adder = gr.add_cc()

        c2s = gr.complex_to_interleaved_short()

        stdout_sink = gr.file_descriptor_sink(gr.sizeof_short, 1)

        self.connect(src0, (adder, 0))
        self.connect(src1, (adder, 1))
        self.connect(adder, c2s, stdout_sink)
Exemple #22
0
    def __init__(self, frame, panel, vbox, argv):
        stdgui2.std_top_block.__init__(self, frame, panel, vbox, argv)

        fft_size = 256

        # build our flow graph
        input_rate = 2048.0e3

        # Generate some noise
        noise = gr.noise_source_c(gr.GR_UNIFORM, 1.0 / 10)

        # Generate a complex sinusoid
        # src1 = gr.sig_source_c (input_rate, gr.GR_SIN_WAVE, 2e3, 1)
        src1 = gr.sig_source_c(input_rate, gr.GR_CONST_WAVE, 57.50e3, 1)

        # We add these throttle blocks so that this demo doesn't
        # suck down all the CPU available.  Normally you wouldn't use these.
        thr1 = gr.throttle(gr.sizeof_gr_complex, input_rate)

        sink1 = fft_sink_c(
            panel,
            title="Complex Data",
            fft_size=fft_size,
            sample_rate=input_rate,
            baseband_freq=100e3,
            ref_level=0,
            y_per_div=20,
            y_divs=10,
        )
        vbox.Add(sink1.win, 1, wx.EXPAND)

        combine1 = gr.add_cc()
        self.connect(src1, (combine1, 0))
        self.connect(noise, (combine1, 1))
        self.connect(combine1, thr1, sink1)

        # src2 = gr.sig_source_f (input_rate, gr.GR_SIN_WAVE, 2e3, 1)
        src2 = gr.sig_source_f(input_rate, gr.GR_CONST_WAVE, 57.50e3, 1)
        thr2 = gr.throttle(gr.sizeof_float, input_rate)
        sink2 = fft_sink_f(
            panel,
            title="Real Data",
            fft_size=fft_size * 2,
            sample_rate=input_rate,
            baseband_freq=100e3,
            ref_level=0,
            y_per_div=20,
            y_divs=10,
        )
        vbox.Add(sink2.win, 1, wx.EXPAND)

        combine2 = gr.add_ff()
        c2f2 = gr.complex_to_float()

        self.connect(src2, (combine2, 0))
        self.connect(noise, c2f2, (combine2, 1))
        self.connect(combine2, thr2, sink2)
Exemple #23
0
    def __init__(self):
        gr.top_block.__init__(self)

        self._nsamples = 1000000
        self._audio_rate = 8000

        # Set up N channels with their own baseband and IF frequencies
        self._N = 5
        chspacing = 16000
        freq = [10, 20, 30, 40, 50]
        f_lo = [0, 1*chspacing, -1*chspacing, 2*chspacing, -2*chspacing]

        self._if_rate = 4*self._N*self._audio_rate

        # Create a signal source and frequency modulate it
        self.sum = gr.add_cc ()
        for n in xrange(self._N):
            sig = gr.sig_source_f(self._audio_rate, gr.GR_SIN_WAVE, freq[n], 0.5)
            fm = fmtx(f_lo[n], self._audio_rate, self._if_rate)
            self.connect(sig, fm)
            self.connect(fm, (self.sum, n))

        self.head = gr.head(gr.sizeof_gr_complex, self._nsamples)
        self.snk_tx = gr.vector_sink_c()
        self.channel = blks2.channel_model(0.1)

        self.connect(self.sum, self.head, self.channel, self.snk_tx)


        # Design the channlizer
        self._M = 10
        bw = chspacing/2.0
        t_bw = chspacing/10.0
        self._chan_rate = self._if_rate / self._M
        self._taps = gr.firdes.low_pass_2(1, self._if_rate, bw, t_bw,
                                          attenuation_dB=100,
                                          window=gr.firdes.WIN_BLACKMAN_hARRIS)
        tpc = math.ceil(float(len(self._taps)) /  float(self._M))

        print "Number of taps:     ", len(self._taps)
        print "Number of channels: ", self._M
        print "Taps per channel:   ", tpc

        self.pfb = blks2.pfb_channelizer_ccf(self._M, self._taps)

        self.connect(self.channel, self.pfb)

        # Create a file sink for each of M output channels of the filter and connect it
        self.fmdet = list()
        self.squelch = list()
        self.snks = list()
        for i in xrange(self._M):
            self.fmdet.append(blks2.nbfm_rx(self._audio_rate, self._chan_rate))
            self.squelch.append(blks2.standard_squelch(self._audio_rate*10))
            self.snks.append(gr.vector_sink_f())
            self.connect((self.pfb, i), self.fmdet[i], self.squelch[i], self.snks[i])
Exemple #24
0
    def __init__(self):
        gr.top_block.__init__(self)

        self._nsamples = 1000000
        self._audio_rate = 8000

        # Set up N channels with their own baseband and IF frequencies
        self._N = 5
        chspacing = 16000
        freq = [10, 20, 30, 40, 50]
        f_lo = [0, 1*chspacing, -1*chspacing, 2*chspacing, -2*chspacing]

        self._if_rate = 4*self._N*self._audio_rate

        # Create a signal source and frequency modulate it
        self.sum = gr.add_cc ()
        for n in xrange(self._N):
            sig = gr.sig_source_f(self._audio_rate, gr.GR_SIN_WAVE, freq[n], 0.5)
            fm = fmtx(f_lo[n], self._audio_rate, self._if_rate)
            self.connect(sig, fm)
            self.connect(fm, (self.sum, n))

        self.head = gr.head(gr.sizeof_gr_complex, self._nsamples)
        self.snk_tx = gr.vector_sink_c()
        self.channel = blks2.channel_model(0.1)

        self.connect(self.sum, self.head, self.channel, self.snk_tx)


        # Design the channlizer
        self._M = 10
        bw = chspacing/2.0
        t_bw = chspacing/10.0
        self._chan_rate = self._if_rate / self._M
        self._taps = gr.firdes.low_pass_2(1, self._if_rate, bw, t_bw, 
                                          attenuation_dB=100,
                                          window=gr.firdes.WIN_BLACKMAN_hARRIS)
        tpc = math.ceil(float(len(self._taps)) /  float(self._M))

        print "Number of taps:     ", len(self._taps)
        print "Number of channels: ", self._M
        print "Taps per channel:   ", tpc
        
        self.pfb = blks2.pfb_channelizer_ccf(self._M, self._taps)
        
        self.connect(self.channel, self.pfb)
        
        # Create a file sink for each of M output channels of the filter and connect it
        self.fmdet = list()
        self.squelch = list()
        self.snks = list()
        for i in xrange(self._M):
            self.fmdet.append(blks2.nbfm_rx(self._audio_rate, self._chan_rate))
            self.squelch.append(blks2.standard_squelch(self._audio_rate*10))
            self.snks.append(gr.vector_sink_f())
            self.connect((self.pfb, i), self.fmdet[i], self.squelch[i], self.snks[i])
Exemple #25
0
    def __init__(self):
        gr.hier_block2.__init__(self, "symbol_0_slicer",
                                gr.io_signature(2, 2, gr.sizeof_gr_complex),
                                gr.io_signature(1, 1, gr.sizeof_float))
        adder = gr.add_cc()
        to_mag = gr.complex_to_mag_squared()

        self.connect((self, 0), (adder, 0))
        self.connect((self, 1), (adder, 1))
        self.connect(adder, to_mag, self)
Exemple #26
0
    def __init__(self, tx_id, rx_id, sample_rate, filename):
        """
        Parameters:

        sample_rate: int or float
            sample_rate of the flowgraph

        filename: string
            file containing the channel model

        Notes:
            The modelfile was created with the pickle module and contains a list
            of sum of cisoids, each sum of cisoids models the Doppler spectrum
            with a specific delay. If one list element is empty this means that
            there exist no scatterers with the specified delay. Each sum of
            cisoids, i.e. list element, contains again a list of amplitudes and
            frequencies.

        """

        gr.hier_block2.__init__(self, "Channel Sounder Measurement",
                                gr.io_signature(1, 1, gr.sizeof_gr_complex),
                                gr.io_signature(1, 1, gr.sizeof_gr_complex))

        self.sample_rate = sample_rate
        fp = open(filename, 'r')

        model = pickle.load(fp)

        self.taps_delays = []
        # check for non-empty list elements to find multipath components with a
        # certain delay
        for idx, mpc in enumerate(model):
            if mpc:
                self.taps_delays.append(idx)

        # print 'taps_delays', self.taps_delays
        # create a tapped delay line structure, since the amplitudes of the sum
        # of cisoids already contain all the information about the power of a
        # Doppler spectrum, the power delay profile is set to 1 for all delays.
        self.mpc_channel = mpc_channel_cc(self.taps_delays,
                                          [1] * len(self.taps_delays))

        # loop through all delays
        for idx, delay in enumerate(self.taps_delays):
            adder = gr.add_cc()
            # loop through all cisoids of a delay
            for iidx, (freq, ampl) in enumerate(model[delay]):
                src = gr.sig_source_c(sample_rate, gr.GR_COS_WAVE, freq, ampl)
                self.connect(src, (adder, iidx))
            # print iidx
            self.connect(adder, (self.mpc_channel, idx + 1))

        self.connect(self,       (self.mpc_channel, 0))
        self.connect(self.mpc_channel, self)
Exemple #27
0
    def __init__(self):
        gr.top_block.__init__(self)

        self._N = 2000000  # number of samples to use
        self._fs = 1000  # initial sampling rate
        self._M = M = 9  # Number of channels to channelize
        self._ifs = M * self._fs  # initial sampling rate

        # Create a set of taps for the PFB channelizer
        self._taps = filter.firdes.low_pass_2(
            1,
            self._ifs,
            475.50,
            50,
            attenuation_dB=100,
            window=filter.firdes.WIN_BLACKMAN_hARRIS)

        # Calculate the number of taps per channel for our own information
        tpc = scipy.ceil(float(len(self._taps)) / float(self._M))
        print "Number of taps:     ", len(self._taps)
        print "Number of channels: ", self._M
        print "Taps per channel:   ", tpc

        # Create a set of signals at different frequencies
        #   freqs lists the frequencies of the signals that get stored
        #   in the list "signals", which then get summed together
        self.signals = list()
        self.add = gr.add_cc()
        freqs = [-70, -50, -30, -10, 10, 20, 40, 60, 80]
        for i in xrange(len(freqs)):
            f = freqs[i] + (M / 2 - M + i + 1) * self._fs
            self.signals.append(
                gr.sig_source_c(self._ifs, gr.GR_SIN_WAVE, f, 1))
            self.connect(self.signals[i], (self.add, i))

        self.head = gr.head(gr.sizeof_gr_complex, self._N)

        # Construct the channelizer filter
        self.pfb = filter.pfb.channelizer_ccf(self._M, self._taps, 1)

        # Construct a vector sink for the input signal to the channelizer
        self.snk_i = gr.vector_sink_c()

        # Connect the blocks
        self.connect(self.add, self.head, self.pfb)
        self.connect(self.add, self.snk_i)

        # Use this to play with the channel mapping
        #self.pfb.set_channel_map([5,6,7,8,0,1,2,3,4])

        # Create a vector sink for each of M output channels of the filter and connect it
        self.snks = list()
        for i in xrange(self._M):
            self.snks.append(gr.vector_sink_c())
            self.connect((self.pfb, i), self.snks[i])
    def __init__(self):
        gr.top_block.__init__(self)

        Rs = 8000
        f1 = 100
        f2 = 200

        npts = 2048

        self.qapp = QtGui.QApplication(sys.argv)

        src1 = gr.sig_source_c(Rs, gr.GR_SIN_WAVE, f1, 0.1, 0)
        src2 = gr.sig_source_c(Rs, gr.GR_SIN_WAVE, f2, 0.1, 0)
        src  = gr.add_cc()
        channel = filter.channel_model(0.01)
        thr = gr.throttle(gr.sizeof_gr_complex, 100*npts)
        self.snk1 = qtgui.time_sink_c(npts, Rs,
                                      "Complex Time Example", 1)

        self.connect(src1, (src,0))
        self.connect(src2, (src,1))
        self.connect(src,  channel, thr, (self.snk1, 0))
        #self.connect(src1, (self.snk1, 1))
        #self.connect(src2, (self.snk1, 2))

        self.ctrl_win = control_box()
        self.ctrl_win.attach_signal1(src1)
        self.ctrl_win.attach_signal2(src2)

        # Get the reference pointer to the SpectrumDisplayForm QWidget
        pyQt  = self.snk1.pyqwidget()

        # Wrap the pointer as a PyQt SIP object
        # This can now be manipulated as a PyQt4.QtGui.QWidget
        pyWin = sip.wrapinstance(pyQt, QtGui.QWidget)

        # Example of using signal/slot to set the title of a curve
        pyWin.connect(pyWin, QtCore.SIGNAL("setTitle(int, QString)"),
                      pyWin, QtCore.SLOT("setTitle(int, QString)"))
        pyWin.emit(QtCore.SIGNAL("setTitle(int, QString)"), 0, "Re{sum}")
        self.snk1.set_title(1, "Im{Sum}")
        #self.snk1.set_title(2, "Re{src1}")
        #self.snk1.set_title(3, "Im{src1}")
        #self.snk1.set_title(4, "Re{src2}")
        #self.snk1.set_title(5, "Im{src2}")

        # Can also set the color of a curve
        #self.snk1.set_color(5, "blue")

        self.snk1.set_update_time(0.5)

        #pyWin.show()
        self.main_box = dialog_box(pyWin, self.ctrl_win)
        self.main_box.show()
Exemple #29
0
 def _get_gauss_rand_proc_c(self):
     """ Returns the Gaussian random process.
     """
     spec_getter = getattr(self.model, 'get_' + self.spec_type)
     if self.spec_type in self.model.specs_odd:
         from winelo.channel import spec2soc
         soc = spec2soc(spec_getter(), method=self.method, N=self.N)
         sources = []
         adder = gr.add_cc()
         for idx, (freq, ampl) in enumerate(soc.get_soc()):
             sources.append(gr.sig_source_c(self.sample_rate,
                                            gr.GR_COS_WAVE, freq, ampl))
             self.connect(sources[idx],
                          gr.skiphead(gr.sizeof_gr_complex,
                                      randint(low=0, high=self.sample_rate)),
                          (adder, idx))
         return adder
     elif self.spec_type in self.model.specs_even:
         from winelo.channel import spec2sos
         # real part of the gaussian random process
         sos_real = spec2sos(spec_getter(), method=self.method, N=self.N)
         sources_real = []
         adder_real = gr.add_ff()
         for idx, (freq, ampl) in enumerate(sos_real.get_sos()):
             sources_real.append(gr.sig_source_f(self.sample_rate,
                                                 gr.GR_COS_WAVE, freq,
                                                 ampl))
             self.connect(sources_real[idx],
                          gr.skiphead(gr.sizeof_float,
                                      randint(low=0, high=self.sample_rate)),
                          (adder_real, idx))
         # imaginary part of the gaussian random process
         sos_imaginary = spec2sos(spec_getter(), method=self.method,
                                  N=self.N + 1)
         sources_imag = []
         adder_imag = gr.add_ff()
         for idx, (freq, ampl) in enumerate(sos_imaginary.get_sos()):
             sources_imag.append(gr.sig_source_f(self.sample_rate,
                                                 gr.GR_COS_WAVE, freq,
                                                 ampl))
             self.connect(sources_imag[idx],
                          gr.skiphead(gr.sizeof_float,
                                      randint(low=0, high=self.sample_rate)),
                          (adder_imag, idx))
         float2complex = gr.float_to_complex()
         self.connect(adder_real, (float2complex, 0))
         self.connect(adder_imag, (float2complex, 1))
         return float2complex
     else:
         print 'You picked a non-existant Doppler spectrum'
         print 'Pick one of the following: ', \
               self.model.specs_even + self.model.specs_odd
         return None
Exemple #30
0
    def __init__(self, frame, panel, vbox, argv):
        stdgui2.std_top_block.__init__(self, frame, panel, vbox, argv)

        fft_size = 256

        # build our flow graph
        input_rate = 2048.0e3

        #Generate some noise
        noise = gr.noise_source_c(gr.GR_UNIFORM, 1.0 / 10)

        # Generate a complex sinusoid
        #src1 = gr.sig_source_c (input_rate, gr.GR_SIN_WAVE, 2e3, 1)
        src1 = gr.sig_source_c(input_rate, gr.GR_CONST_WAVE, 57.50e3, 1)

        # We add these throttle blocks so that this demo doesn't
        # suck down all the CPU available.  Normally you wouldn't use these.
        thr1 = gr.throttle(gr.sizeof_gr_complex, input_rate)

        sink1 = fft_sink_c(panel,
                           title="Complex Data",
                           fft_size=fft_size,
                           sample_rate=input_rate,
                           baseband_freq=100e3,
                           ref_level=0,
                           y_per_div=20,
                           y_divs=10)
        vbox.Add(sink1.win, 1, wx.EXPAND)

        combine1 = gr.add_cc()
        self.connect(src1, (combine1, 0))
        self.connect(noise, (combine1, 1))
        self.connect(combine1, thr1, sink1)

        #src2 = gr.sig_source_f (input_rate, gr.GR_SIN_WAVE, 2e3, 1)
        src2 = gr.sig_source_f(input_rate, gr.GR_CONST_WAVE, 57.50e3, 1)
        thr2 = gr.throttle(gr.sizeof_float, input_rate)
        sink2 = fft_sink_f(panel,
                           title="Real Data",
                           fft_size=fft_size * 2,
                           sample_rate=input_rate,
                           baseband_freq=100e3,
                           ref_level=0,
                           y_per_div=20,
                           y_divs=10)
        vbox.Add(sink2.win, 1, wx.EXPAND)

        combine2 = gr.add_ff()
        c2f2 = gr.complex_to_float()

        self.connect(src2, (combine2, 0))
        self.connect(noise, c2f2, (combine2, 1))
        self.connect(combine2, thr2, sink2)
Exemple #31
0
    def __init__(self):
        gr.top_block.__init__(self)

        Rs = 8000
        f1 = 100
        f2 = 200

        npts = 2048

        self.qapp = QtGui.QApplication(sys.argv)
        
        src1 = gr.sig_source_c(Rs, gr.GR_SIN_WAVE, f1, 0.1, 0)
        src2 = gr.sig_source_c(Rs, gr.GR_SIN_WAVE, f2, 0.1, 0)
        src  = gr.add_cc()
        channel = gr.channel_model(0.01)
        thr = gr.throttle(gr.sizeof_gr_complex, 100*npts)
        self.snk1 = qtgui.time_sink_c(npts, Rs,
                                      "Complex Time Example", 3)

        self.connect(src1, (src,0))
        self.connect(src2, (src,1))
        self.connect(src,  channel, thr, (self.snk1, 0))
        self.connect(src1, (self.snk1, 1))
        self.connect(src2, (self.snk1, 2))

        self.ctrl_win = control_box()
        self.ctrl_win.attach_signal1(src1)
        self.ctrl_win.attach_signal2(src2)

        # Get the reference pointer to the SpectrumDisplayForm QWidget
        pyQt  = self.snk1.pyqwidget()

        # Wrap the pointer as a PyQt SIP object
        # This can now be manipulated as a PyQt4.QtGui.QWidget
        pyWin = sip.wrapinstance(pyQt, QtGui.QWidget)

        # Example of using signal/slot to set the title of a curve
        pyWin.connect(pyWin, QtCore.SIGNAL("setTitle(int, QString)"),
                      pyWin, QtCore.SLOT("setTitle(int, QString)"))
        pyWin.emit(QtCore.SIGNAL("setTitle(int, QString)"), 0, "Re{sum}")
        self.snk1.set_title(1, "Im{Sum}")
        self.snk1.set_title(2, "Re{src1}")
        self.snk1.set_title(3, "Im{src1}")
        self.snk1.set_title(4, "Re{src2}")
        self.snk1.set_title(5, "Im{src2}")

        # Can also set the color of a curve
        #self.snk1.set_color(5, "blue")

        #pyWin.show()
        self.main_box = dialog_box(pyWin, self.ctrl_win)
        self.main_box.show()
Exemple #32
0
    def __init__(self, avg_len):
        gr.hier_block2.__init__(self, "dc_block",
                                gr.io_signature(1, 1, gr.sizeof_gr_complex),
                                gr.io_signature(1, 1, gr.sizeof_gr_complex))

        self.mvg_avg = gr.moving_average_cc(avg_len,
                                            complex(-1.0, 0.0) / avg_len,
                                            4 * avg_len)
        self.adder = gr.add_cc()

        self.connect(self, self.mvg_avg, (self.adder, 0))
        self.connect(self, (self.adder, 1))
        self.connect(self.adder, self)
Exemple #33
0
    def __init__(self):
        gr.hier_block2.__init__(self,
                                "symbol_0_slicer",
                                gr.io_signature(2, 2, gr.sizeof_gr_complex),
                                gr.io_signature(1, 1, gr.sizeof_float))
        adder = gr.add_cc()
        to_mag = gr.complex_to_mag_squared()

        self.connect((self, 0), (adder, 0))
        self.connect((self, 1), (adder, 1))
        self.connect(adder,
                     to_mag,
                     self)
Exemple #34
0
    def __init__(self):
        gr.top_block.__init__(self)

        self._N = 2000000        # number of samples to use
        self._fs = 1000          # initial sampling rate
        self._M = M = 9          # Number of channels to channelize
        self._ifs = M*self._fs   # initial sampling rate

        # Create a set of taps for the PFB channelizer
        self._taps = filter.firdes.low_pass_2(1, self._ifs, 475.50, 50,
                                              attenuation_dB=100,
                                              window=filter.firdes.WIN_BLACKMAN_hARRIS)

        # Calculate the number of taps per channel for our own information
        tpc = scipy.ceil(float(len(self._taps)) /  float(self._M))
        print "Number of taps:     ", len(self._taps)
        print "Number of channels: ", self._M
        print "Taps per channel:   ", tpc

        # Create a set of signals at different frequencies
        #   freqs lists the frequencies of the signals that get stored
        #   in the list "signals", which then get summed together
        self.signals = list()
        self.add = gr.add_cc()
        freqs = [-70, -50, -30, -10, 10, 20, 40, 60, 80]
        for i in xrange(len(freqs)):
            f = freqs[i] + (M/2-M+i+1)*self._fs
            self.signals.append(gr.sig_source_c(self._ifs, gr.GR_SIN_WAVE, f, 1))
            self.connect(self.signals[i], (self.add,i))

        self.head = gr.head(gr.sizeof_gr_complex, self._N)

        # Construct the channelizer filter
        self.pfb = filter.pfb.channelizer_ccf(self._M, self._taps, 1)

        # Construct a vector sink for the input signal to the channelizer
        self.snk_i = gr.vector_sink_c()

        # Connect the blocks
        self.connect(self.add, self.head, self.pfb)
        self.connect(self.add, self.snk_i)

        # Use this to play with the channel mapping
        #self.pfb.set_channel_map([5,6,7,8,0,1,2,3,4])

        # Create a vector sink for each of M output channels of the filter and connect it
        self.snks = list()
        for i in xrange(self._M):
            self.snks.append(gr.vector_sink_c())
            self.connect((self.pfb, i), self.snks[i])
Exemple #35
0
    def __init__(self):
        gr.top_block.__init__(self)

        self._N = 10000000  # number of samples to use
        self._fs = 10000  # initial sampling rate
        self._decim = 20  # Decimation rate

        # Generate the prototype filter taps for the decimators with a 200 Hz bandwidth
        self._taps = gr.firdes.low_pass_2(1,
                                          self._fs,
                                          200,
                                          150,
                                          attenuation_dB=120,
                                          window=gr.firdes.WIN_BLACKMAN_hARRIS)

        # Calculate the number of taps per channel for our own information
        tpc = scipy.ceil(float(len(self._taps)) / float(self._decim))
        print "Number of taps:     ", len(self._taps)
        print "Number of filters:  ", self._decim
        print "Taps per channel:   ", tpc

        # Build the input signal source
        # We create a list of freqs, and a sine wave is generated and added to the source
        # for each one of these frequencies.
        self.signals = list()
        self.add = gr.add_cc()
        freqs = [10, 20, 2040]
        for i in xrange(len(freqs)):
            self.signals.append(
                gr.sig_source_c(self._fs, gr.GR_SIN_WAVE, freqs[i], 1))
            self.connect(self.signals[i], (self.add, i))

        self.head = gr.head(gr.sizeof_gr_complex, self._N)

        # Construct a PFB decimator filter
        self.pfb = blks2.pfb_decimator_ccf(self._decim, self._taps, 0)

        # Construct a standard FIR decimating filter
        self.dec = gr.fir_filter_ccf(self._decim, self._taps)

        self.snk_i = gr.vector_sink_c()

        # Connect the blocks
        self.connect(self.add, self.head, self.pfb)
        self.connect(self.add, self.snk_i)

        # Create the sink for the decimated siganl
        self.snk = gr.vector_sink_c()
        self.connect(self.pfb, self.snk)
Exemple #36
0
  def __init__ ( self, noise_power, coherence_time, taps ):
    gr.hier_block2.__init__(self,
      "fading_channel", 
      gr.io_signature( 1, 1, gr.sizeof_gr_complex ),
      gr.io_signature( 1, 1, gr.sizeof_gr_complex ) )

    inp = gr.kludge_copy( gr.sizeof_gr_complex )
    self.connect( self, inp )
    
    tap1_delay = gr.delay( gr.sizeof_gr_complex, 1 )
    tap2_delay = gr.delay( gr.sizeof_gr_complex, 2 )
    self.connect( inp, tap1_delay )
    self.connect( inp, tap2_delay )
    
    fd = 100
    z = numpy.arange(-fd+0.1,fd,0.1)
    t = numpy.sqrt(1. / ( pi * fd * numpy.sqrt( 1. - (z/fd)**2 ) ) )
    
    tap1_noise = ofdm.complex_white_noise( 0.0, taps[0] )
    tap1_filter = gr.fft_filter_ccc(1, t)
    self.connect( tap1_noise, tap1_filter )
    
    tap1_mult = gr.multiply_cc()
    self.connect( tap1_filter, (tap1_mult,0) )
    self.connect( tap1_delay, (tap1_mult,1) )
    
    tap2_noise = ofdm.complex_white_noise( 0.0, taps[1] )
    tap2_filter = gr.fft_filter_ccc(1, t)
    
    self.connect( tap2_noise, tap2_filter )
    
    tap2_mult = gr.multiply_cc()
    self.connect( tap2_filter, (tap2_mult,0) )
    self.connect( tap2_delay, (tap2_mult,1) )
    
    noise_src = ofdm.complex_white_noise( 0.0, sqrt( noise_power ) )
    chan = gr.add_cc()
    
    self.connect( inp, (chan,0) )
    self.connect( tap1_mult, (chan,1) )
    self.connect( tap2_mult, (chan,2) )
    self.connect( noise_src, (chan,3) )
    
    self.connect( chan, self )
    
    log_to_file( self, tap1_filter, "data/tap1_filter.compl")
    log_to_file( self, tap1_filter, "data/tap1_filter.float", mag=True)
    log_to_file( self, tap2_filter, "data/tap2_filter.compl")
    log_to_file( self, tap2_filter, "data/tap2_filter.float", mag=True)
Exemple #37
0
    def __init__(self, frame, panel, vbox, argv):
        stdgui2.std_top_block.__init__(self, frame, panel, vbox, argv)

        default_input_rate = 1e6
        if len(argv) > 1:
            input_rate = int(argv[1])
        else:
            input_rate = default_input_rate

        if len(argv) > 2:
            v_scale = float(argv[2])  # start up at this v_scale value
        else:
            v_scale = None  # start up in autorange mode, default

        if len(argv) > 3:
            t_scale = float(argv[3])  # start up at this t_scale value
        else:
            t_scale = .00003 * default_input_rate / input_rate  # old behavior

        print "input rate %s  v_scale %s  t_scale %s" % (input_rate, v_scale,
                                                         t_scale)

        # Generate a complex sinusoid
        ampl = 1.0e3
        self.src0 = gr.sig_source_c(input_rate, gr.GR_SIN_WAVE,
                                    25.1e3 * input_rate / default_input_rate,
                                    ampl)
        self.noise = gr.sig_source_c(
            input_rate, gr.GR_SIN_WAVE,
            11.1 * 25.1e3 * input_rate / default_input_rate, ampl / 10)
        #self.noise =gr.noise_source_c(gr.GR_GAUSSIAN, ampl/10)
        self.combine = gr.add_cc()

        # We add this throttle block so that this demo doesn't suck down
        # all the CPU available.  You normally wouldn't use it...
        self.thr = gr.throttle(gr.sizeof_gr_complex, input_rate)

        scope = scope_sink_c(panel,
                             "Secret Data",
                             sample_rate=input_rate,
                             v_scale=v_scale,
                             t_scale=t_scale)
        vbox.Add(scope.win, 1, wx.EXPAND)

        # Ultimately this will be
        # self.connect("src0 throttle scope")
        self.connect(self.src0, (self.combine, 0))
        self.connect(self.noise, (self.combine, 1))
        self.connect(self.combine, self.thr, scope)
Exemple #38
0
    def test_000(self):
        N = 1000  # number of samples to use
        M = 5  # Number of channels
        fs = 1000  # baseband sampling rate
        ifs = M * fs  # input samp rate to decimator
        channel = 0  # Extract channel 0

        taps = filter.firdes.low_pass_2(
            1,
            ifs,
            fs / 2,
            fs / 10,
            attenuation_dB=80,
            window=filter.firdes.WIN_BLACKMAN_hARRIS)

        signals = list()
        add = gr.add_cc()
        freqs = [-200, -100, 0, 100, 200]
        for i in xrange(len(freqs)):
            f = freqs[i] + (M / 2 - M + i + 1) * fs
            signals.append(gr.sig_source_c(ifs, gr.GR_SIN_WAVE, f, 1))
            self.tb.connect(signals[i], (add, i))

        head = gr.head(gr.sizeof_gr_complex, N)
        s2ss = gr.stream_to_streams(gr.sizeof_gr_complex, M)
        pfb = filter.pfb_decimator_ccf(M, taps, channel)
        snk = gr.vector_sink_c()

        self.tb.connect(add, head, s2ss)
        for i in xrange(M):
            self.tb.connect((s2ss, i), (pfb, i))
        self.tb.connect(pfb, snk)

        self.tb.run()

        Ntest = 50
        L = len(snk.data())
        t = map(lambda x: float(x) / fs, xrange(L))

        # Create known data as complex sinusoids for the baseband freq
        # of the extracted channel is due to decimator output order.
        phase = 0
        expected_data = map(lambda x: math.cos(2.*math.pi*freqs[2]*x+phase) + \
                                1j*math.sin(2.*math.pi*freqs[2]*x+phase), t)

        dst_data = snk.data()

        self.assertComplexTuplesAlmostEqual(expected_data[-Ntest:],
                                            dst_data[-Ntest:], 4)
Exemple #39
0
    def __init__(self, noise_dB=-20., fir_taps=[1]):
        gr.hier_block2.__init__(self, 'my_channel',
                gr.io_signature(1,1,gr.sizeof_gr_complex),
                gr.io_signature(1,1,gr.sizeof_gr_complex))
        noise_adder = gr.add_cc()
        noise = gr.noise_source_c(gr.GR_GAUSSIAN, 10**(noise_dB/20.), random.randint(0,2**30))
        # normalize taps
        firtabsum = float(sum(map(abs,fir_taps)))
        fir_taps = [ i / firtabsum for i in fir_taps]
        multipath = gr.fir_filter_ccc(1,fir_taps)

        self.connect(noise, (noise_adder,1))
        self.connect(self, noise_adder, multipath, self)

        self.__dict__.update(locals()) # didn't feel like using self all over the place
Exemple #40
0
    def __init__(self, noise_power, coherence_time, taps):
        gr.hier_block2.__init__(self, "fading_channel",
                                gr.io_signature(1, 1, gr.sizeof_gr_complex),
                                gr.io_signature(1, 1, gr.sizeof_gr_complex))

        inp = gr.kludge_copy(gr.sizeof_gr_complex)
        self.connect(self, inp)

        tap1_delay = gr.delay(gr.sizeof_gr_complex, 1)
        tap2_delay = gr.delay(gr.sizeof_gr_complex, 2)
        self.connect(inp, tap1_delay)
        self.connect(inp, tap2_delay)

        fd = 100
        z = numpy.arange(-fd + 0.1, fd, 0.1)
        t = numpy.sqrt(1. / (pi * fd * numpy.sqrt(1. - (z / fd)**2)))

        tap1_noise = ofdm.complex_white_noise(0.0, taps[0])
        tap1_filter = gr.fft_filter_ccc(1, t)
        self.connect(tap1_noise, tap1_filter)

        tap1_mult = gr.multiply_cc()
        self.connect(tap1_filter, (tap1_mult, 0))
        self.connect(tap1_delay, (tap1_mult, 1))

        tap2_noise = ofdm.complex_white_noise(0.0, taps[1])
        tap2_filter = gr.fft_filter_ccc(1, t)

        self.connect(tap2_noise, tap2_filter)

        tap2_mult = gr.multiply_cc()
        self.connect(tap2_filter, (tap2_mult, 0))
        self.connect(tap2_delay, (tap2_mult, 1))

        noise_src = ofdm.complex_white_noise(0.0, sqrt(noise_power))
        chan = gr.add_cc()

        self.connect(inp, (chan, 0))
        self.connect(tap1_mult, (chan, 1))
        self.connect(tap2_mult, (chan, 2))
        self.connect(noise_src, (chan, 3))

        self.connect(chan, self)

        log_to_file(self, tap1_filter, "data/tap1_filter.compl")
        log_to_file(self, tap1_filter, "data/tap1_filter.float", mag=True)
        log_to_file(self, tap2_filter, "data/tap2_filter.compl")
        log_to_file(self, tap2_filter, "data/tap2_filter.float", mag=True)
Exemple #41
0
    def __init__(self):
        gr.top_block.__init__(self)

        parser = OptionParser(option_class=eng_option)
        parser.add_option(
            "-f", "--freq1", type="eng_float", default=1e6, help="set waveform frequency to FREQ [default=%default]"
        )
        parser.add_option(
            "-g", "--freq2", type="eng_float", default=1e6, help="set waveform frequency to FREQ [default=%default]"
        )
        parser.add_option(
            "-a",
            "--amplitude1",
            type="eng_float",
            default=16e3,
            help="set waveform amplitude to AMPLITUDE [default=%default]",
            metavar="AMPL",
        )
        parser.add_option(
            "-b",
            "--amplitude2",
            type="eng_float",
            default=16e3,
            help="set waveform amplitude to AMPLITUDE [default=%default]",
            metavar="AMPL",
        )

        parser.add_option(
            "-i", "--interp", type="int", default=32, help="assume fgpa interpolation rate is INTERP [default=%default]"
        )

        (options, args) = parser.parse_args()
        if len(args) != 0:
            parser.print_help()
            raise SystemExit, 1

        src0 = gr.sig_source_c(master_clock / options.interp, gr.GR_SIN_WAVE, options.freq1, options.amplitude1)
        src1 = gr.sig_source_c(master_clock / options.interp, gr.GR_SIN_WAVE, options.freq2, options.amplitude2)

        adder = gr.add_cc()

        c2s = gr.complex_to_interleaved_short()

        stdout_sink = gr.file_descriptor_sink(gr.sizeof_short, 1)

        self.connect(src0, (adder, 0))
        self.connect(src1, (adder, 1))
        self.connect(adder, c2s, stdout_sink)
Exemple #42
0
    def test_000(self):
        N = 1000  # number of samples to use
        M = 5  # Number of channels
        fs = 1000  # baseband sampling rate
        ifs = M * fs  # input samp rate to decimator
        channel = 0  # Extract channel 0

        taps = filter.firdes.low_pass_2(
            1, ifs, fs / 2, fs / 10, attenuation_dB=80, window=filter.firdes.WIN_BLACKMAN_hARRIS
        )

        signals = list()
        add = gr.add_cc()
        freqs = [-200, -100, 0, 100, 200]
        for i in xrange(len(freqs)):
            f = freqs[i] + (M / 2 - M + i + 1) * fs
            signals.append(gr.sig_source_c(ifs, gr.GR_SIN_WAVE, f, 1))
            self.tb.connect(signals[i], (add, i))

        head = gr.head(gr.sizeof_gr_complex, N)
        s2ss = gr.stream_to_streams(gr.sizeof_gr_complex, M)
        pfb = filter.pfb_decimator_ccf(M, taps, channel)
        snk = gr.vector_sink_c()

        self.tb.connect(add, head, s2ss)
        for i in xrange(M):
            self.tb.connect((s2ss, i), (pfb, i))
        self.tb.connect(pfb, snk)

        self.tb.run()

        Ntest = 50
        L = len(snk.data())
        t = map(lambda x: float(x) / fs, xrange(L))

        # Create known data as complex sinusoids for the baseband freq
        # of the extracted channel is due to decimator output order.
        phase = 0
        expected_data = map(
            lambda x: math.cos(2.0 * math.pi * freqs[2] * x + phase)
            + 1j * math.sin(2.0 * math.pi * freqs[2] * x + phase),
            t,
        )

        dst_data = snk.data()

        self.assertComplexTuplesAlmostEqual(expected_data[-Ntest:], dst_data[-Ntest:], 4)
Exemple #43
0
    def __init__(self, noise_dB=-20., fir_taps=[1]):
        gr.hier_block2.__init__(self, 'my_channel',
                                gr.io_signature(1, 1, gr.sizeof_gr_complex),
                                gr.io_signature(1, 1, gr.sizeof_gr_complex))
        noise_adder = gr.add_cc()
        noise = gr.noise_source_c(gr.GR_GAUSSIAN, 10**(noise_dB / 20.),
                                  random.randint(0, 2**30))
        # normalize taps
        firtabsum = float(sum(map(abs, fir_taps)))
        fir_taps = [i / firtabsum for i in fir_taps]
        multipath = gr.fir_filter_ccc(1, fir_taps)

        self.connect(noise, (noise_adder, 1))
        self.connect(self, noise_adder, multipath, self)

        self.__dict__.update(
            locals())  # didn't feel like using self all over the place
Exemple #44
0
    def __init__(self):
        gr.top_block.__init__(self)

        Rs = 8000
        f1 = 1000
        f2 = 2000

        fftsize = 2048

        self.qapp = QtGui.QApplication(sys.argv)
        
        src1 = gr.sig_source_c(Rs, gr.GR_SIN_WAVE, f1, 0.1, 0)
        src2 = gr.sig_source_c(Rs, gr.GR_SIN_WAVE, f2, 0.1, 0)
        src  = gr.add_cc()
        channel = gr.channel_model(0.001)
        thr = gr.throttle(gr.sizeof_gr_complex, 100*fftsize)

        self.snk1 = qtgui2.sink_c(fftsize, gr.firdes.WIN_BLACKMAN_hARRIS,
                                 0, Rs,
                                 "Complex Signal Example",
                                True, True, False, True, True, True, True)
                                #True, False, False, False, False, True, False)
								#fft , wfall, 3dwf , time , const, oGL , formui

        # Get the reference pointer to the SpectrumDisplayForm QWidget
        pyQt  = self.snk1.pyqwidget()
        # Wrap the pointer as a PyQt SIP object
        # This can now be manipulated as a PyQt4.QtGui.QWidget
        self.pyWin = sip.wrapinstance(pyQt, QtGui.QWidget)

        self.connect(src1, (src,0))
        self.connect(src2, (src,1))
        self.connect(src,  channel, thr, self.snk1)

        self.ctrl_win = control_box(self.snk1)
        self.ctrl_win.attach_signal1(src1)
        self.ctrl_win.attach_signal2(src2)

        

        self.main_box = dialog_box(self.pyWin, self.ctrl_win)

 

        self.main_box.show()
Exemple #45
0
    def __init__(self):
        gr.top_block.__init__(self)

        self._N = 10000000  # number of samples to use
        self._fs = 10000  # initial sampling rate
        self._decim = 20  # Decimation rate

        # Generate the prototype filter taps for the decimators with a 200 Hz bandwidth
        self._taps = filter.firdes.low_pass_2(
            1, self._fs, 200, 150, attenuation_dB=120, window=filter.firdes.WIN_BLACKMAN_hARRIS
        )

        # Calculate the number of taps per channel for our own information
        tpc = scipy.ceil(float(len(self._taps)) / float(self._decim))
        print "Number of taps:     ", len(self._taps)
        print "Number of filters:  ", self._decim
        print "Taps per channel:   ", tpc

        # Build the input signal source
        # We create a list of freqs, and a sine wave is generated and added to the source
        # for each one of these frequencies.
        self.signals = list()
        self.add = gr.add_cc()
        freqs = [10, 20, 2040]
        for i in xrange(len(freqs)):
            self.signals.append(gr.sig_source_c(self._fs, gr.GR_SIN_WAVE, freqs[i], 1))
            self.connect(self.signals[i], (self.add, i))

        self.head = gr.head(gr.sizeof_gr_complex, self._N)

        # Construct a PFB decimator filter
        self.pfb = filter.pfb.decimator_ccf(self._decim, self._taps, 0)

        # Construct a standard FIR decimating filter
        self.dec = filter.fir_filter_ccf(self._decim, self._taps)

        self.snk_i = gr.vector_sink_c()

        # Connect the blocks
        self.connect(self.add, self.head, self.pfb)
        self.connect(self.add, self.snk_i)

        # Create the sink for the decimated siganl
        self.snk = gr.vector_sink_c()
        self.connect(self.pfb, self.snk)
Exemple #46
0
    def __init__(self, constellation, f, N0=0.25, seed=-666L):
        """
        constellation - a constellation object used for modulation.
        f - a finite state machine specification used for coding.
        N0 - noise level
        seed - random seed
        """
        super(trellis_tb, self).__init__()
        # packet size in bits (make it multiple of 16 so it can be packed in a short)
        packet_size = 1024 * 16
        # bits per FSM input symbol
        bitspersymbol = int(round(math.log(f.I()) /
                                  math.log(2)))  # bits per FSM input symbol
        # packet size in trellis steps
        K = packet_size / bitspersymbol

        # TX
        src = gr.lfsr_32k_source_s()
        # packet size in shorts
        src_head = gr.head(gr.sizeof_short, packet_size / 16)
        # unpack shorts to symbols compatible with the FSM input cardinality
        s2fsmi = gr.packed_to_unpacked_ss(bitspersymbol, gr.GR_MSB_FIRST)
        # initial FSM state = 0
        enc = trellis.encoder_ss(f, 0)
        mod = gr.chunks_to_symbols_sc(constellation.points(), 1)

        # CHANNEL
        add = gr.add_cc()
        noise = gr.noise_source_c(gr.GR_GAUSSIAN, math.sqrt(N0 / 2), seed)

        # RX
        # data preprocessing to generate metrics for Viterbi
        metrics = trellis.constellation_metrics_cf(
            constellation.base(), digital_swig.TRELLIS_EUCLIDEAN)
        # Put -1 if the Initial/Final states are not set.
        va = trellis.viterbi_s(f, K, 0, -1)
        # pack FSM input symbols to shorts
        fsmi2s = gr.unpacked_to_packed_ss(bitspersymbol, gr.GR_MSB_FIRST)
        # check the output
        self.dst = gr.check_lfsr_32k_s()

        self.connect(src, src_head, s2fsmi, enc, mod)
        self.connect(mod, (add, 0))
        self.connect(noise, (add, 1))
        self.connect(add, metrics, va, fsmi2s, self.dst)
Exemple #47
0
 def run_flow_graph(sync_sym1, sync_sym2, data_sym):
     top_block = gr.top_block()
     carr_offset = random.randint(-max_offset / 2, max_offset / 2) * 2
     tx_data = shift_tuple(sync_sym1, carr_offset) + \
               shift_tuple(sync_sym2, carr_offset) + \
               shift_tuple(data_sym,  carr_offset)
     channel = [
         rand_range(min_chan_ampl, max_chan_ampl) *
         numpy.exp(1j * rand_range(0, 2 * numpy.pi))
         for x in range(fft_len)
     ]
     src = gr.vector_source_c(tx_data, False, fft_len)
     chan = gr.multiply_const_vcc(channel)
     noise = gr.noise_source_c(gr.GR_GAUSSIAN, wgn_amplitude)
     add = gr.add_cc(fft_len)
     chanest = digital.ofdm_chanest_vcvc(sync_sym1, sync_sym2, 1)
     sink = gr.vector_sink_c(fft_len)
     top_block.connect(src, chan, (add, 0), chanest, sink)
     top_block.connect(
         noise, gr.stream_to_vector(gr.sizeof_gr_complex, fft_len),
         (add, 1))
     top_block.run()
     channel_est = None
     carr_offset_hat = 0
     rx_sym_est = [
         0,
     ] * fft_len
     tags = sink.tags()
     for tag in tags:
         if pmt.pmt_symbol_to_string(
                 tag.key) == 'ofdm_sync_carr_offset':
             carr_offset_hat = pmt.pmt_to_long(tag.value)
             self.assertEqual(carr_offset, carr_offset_hat)
         if pmt.pmt_symbol_to_string(tag.key) == 'ofdm_sync_chan_taps':
             channel_est = shift_tuple(
                 pmt.pmt_c32vector_elements(tag.value), carr_offset)
     shifted_carrier_mask = shift_tuple(carrier_mask, carr_offset)
     for i in range(fft_len):
         if shifted_carrier_mask[i] and channel_est[i]:
             self.assertAlmostEqual(channel[i],
                                    channel_est[i],
                                    places=0)
             rx_sym_est[i] = (sink.data()[i] / channel_est[i]).real
     return (carr_offset, list(shift_tuple(rx_sym_est,
                                           -carr_offset_hat)))
Exemple #48
0
 def __init__(self,ampl_i,band,symbol_rate,sps):
     gr.hier_block2.__init__(self,"Channel",
                             gr.io_signature(1,1,gr.sizeof_gr_complex),
                             gr.io_signature(1,1,gr.sizeof_gr_complex))
     
     self.symbol_rate = symbol_rate
     self.sample_rate=symbol_rate*sps
     self.fading = False
     self.adder = gr.add_cc()
     self.noise = gr.noise_source_c(gr.GR_GAUSSIAN, 1, -42)
     self.ampl = gr.multiply_const_cc(ampl_i)
     self.taps = gr.firdes.low_pass_2 (1,280,band/2,5,80,gr.firdes.WIN_KAISER)
     self.filter=gr.fir_filter_ccf(1,self.taps)
     
     #Connects
     self.connect(self,self.filter,(self.adder,0))
     self.connect(self.noise, self.ampl, (self.adder,1))
     self.connect(self.adder, self)
  def test_100(self):
    vlen = 256
    N = int( 5e5 )
    soff=40
    taps = [1.0,0.0,2e-1+0.1j,1e-4-0.04j]
    freqoff = 0.0
    snr_db = 10
    rms_amplitude = 8000
    
    
    data = [1 + 1j] * vlen
    #data2 = [2] * vlen
    
    src = gr.vector_source_c( data, True, vlen )
    v2s = gr.vector_to_stream(gr.sizeof_gr_complex,vlen)
    
    
    #interp = gr.fractional_interpolator_cc(0.0,soff)
    interp = moms(1000000,1000000+soff)
    
    fad_chan = gr.fir_filter_ccc(1,taps)
    
    freq_shift = gr.multiply_cc()
    norm_freq = freqoff / vlen
    freq_off_src = gr.sig_source_c(1.0, gr.GR_SIN_WAVE, norm_freq, 1.0, 0.0 )
    
    snr = 10.0**(snr_db/10.0)
    noise_sigma = sqrt( rms_amplitude**2 / snr)
    awgn_chan = gr.add_cc()
    awgn_noise_src = ofdm.complex_white_noise( 0.0, noise_sigma )
    
    dst = gr.null_sink( gr.sizeof_gr_complex )

    limit = gr.head( gr.sizeof_gr_complex * vlen, N )
    
    
    self.tb.connect( src, limit, v2s, interp, fad_chan,freq_shift, awgn_chan, dst )
    self.tb.connect( freq_off_src,(freq_shift,1))
    self.tb.connect( awgn_noise_src,(awgn_chan,1))
    
    r = time_it( self.tb )
    
    print "Rate: %s Samples/second" \
      % eng_notation.num_to_str( float(N) * vlen / r ) 
Exemple #50
0
    def __init__(self, ampl_i, band, symbol_rate, sps):
        gr.hier_block2.__init__(self, "Channel",
                                gr.io_signature(1, 1, gr.sizeof_gr_complex),
                                gr.io_signature(1, 1, gr.sizeof_gr_complex))

        self.symbol_rate = symbol_rate
        self.sample_rate = symbol_rate * sps
        self.fading = False
        self.adder = gr.add_cc()
        self.noise = gr.noise_source_c(gr.GR_GAUSSIAN, 1, -42)
        self.ampl = gr.multiply_const_cc(ampl_i)
        self.taps = gr.firdes.low_pass_2(1, 280, band / 2, 5, 80,
                                         gr.firdes.WIN_KAISER)
        self.filter = gr.fir_filter_ccf(1, self.taps)

        #Connects
        self.connect(self, self.filter, (self.adder, 0))
        self.connect(self.noise, self.ampl, (self.adder, 1))
        self.connect(self.adder, self)
Exemple #51
0
    def test_100(self):
        vlen = 256
        N = int(5e5)
        soff = 40
        taps = [1.0, 0.0, 2e-1 + 0.1j, 1e-4 - 0.04j]
        freqoff = 0.0
        snr_db = 10
        rms_amplitude = 8000

        data = [1 + 1j] * vlen
        #data2 = [2] * vlen

        src = gr.vector_source_c(data, True, vlen)
        v2s = gr.vector_to_stream(gr.sizeof_gr_complex, vlen)

        #interp = gr.fractional_interpolator_cc(0.0,soff)
        interp = moms(1000000, 1000000 + soff)

        fad_chan = gr.fir_filter_ccc(1, taps)

        freq_shift = gr.multiply_cc()
        norm_freq = freqoff / vlen
        freq_off_src = gr.sig_source_c(1.0, gr.GR_SIN_WAVE, norm_freq, 1.0,
                                       0.0)

        snr = 10.0**(snr_db / 10.0)
        noise_sigma = sqrt(rms_amplitude**2 / snr)
        awgn_chan = gr.add_cc()
        awgn_noise_src = ofdm.complex_white_noise(0.0, noise_sigma)

        dst = gr.null_sink(gr.sizeof_gr_complex)

        limit = gr.head(gr.sizeof_gr_complex * vlen, N)

        self.tb.connect(src, limit, v2s, interp, fad_chan, freq_shift,
                        awgn_chan, dst)
        self.tb.connect(freq_off_src, (freq_shift, 1))
        self.tb.connect(awgn_noise_src, (awgn_chan, 1))

        r = time_it(self.tb)

        print "Rate: %s Samples/second" \
          % eng_notation.num_to_str( float(N) * vlen / r )
	def __init__(self, frame, panel, vbox, argv):
		stdgui2.std_top_block.__init__(self, frame, panel, vbox, argv)

	        self.frame = frame
	        self.panel = panel

		parser = OptionParser(usage="%prog: [options]")
		parser.add_option("-N", "--dpsslength", type="int", 
			help="Length of the DPSS", default="512")
		parser.add_option("-B", "--timebandwidthproduct", type="float", 
			help="Time Bandwidthproduct used to calculate the DPSS", default="3")
		parser.add_option("-K", "--tapers", type="int", 
			help="Number of Tapers used to calculate the Spectrum", default="5")
		parser.add_option("-W", "--weighting", type="choice", choices=("unity", "eigenvalues" ,"adaptive" ),
			help="weighting-type to be used (unity, eigenvalues, adaptive) ", default="adaptive")
		(options, args) = parser.parse_args ()

		self.options = options


		#setting up our signal
		self.samplingrate = 48000
		self.source = gr.sig_source_c(self.samplingrate, gr.GR_SIN_WAVE, 3000, 1)
		self.noise = gr.noise_source_c(gr.GR_GAUSSIAN,0.5)
		self.add = gr.add_cc()
		self.throttle = gr.throttle(gr.sizeof_gr_complex, self.samplingrate)
		#the actual spectrum estimator
		self.v2s = gr.vector_to_stream(gr.sizeof_float, self.options.dpsslength)
		self.mtm = specest.mtm(N = self.options.dpsslength, NW = self.options.timebandwidthproduct, K = self.options.tapers, weighting = self.options.weighting)
		self.scope = specest.spec_sink_f(panel,
						title='Spectrum with %s weighting, Length %i and %i Tapers' % ( self.options.weighting, self.options.dpsslength, self.options.tapers ),
						spec_size=self.options.dpsslength,
						sample_rate=self.samplingrate,
						ref_level=80,
						avg_alpha=0.8,
						y_per_div=20)

		self.connect(self.source, (self.add, 0) )
		self.connect(self.noise, (self.add, 1) )
		self.connect(self.add, self.throttle, self.mtm)
		self.connect(self.mtm, self.v2s, self.scope)
        	self._build_gui(vbox)
    def __init__(self, sample_rate):
        gr.hier_block2.__init__(self, "example_signal_1",
                                gr.io_signature(0, 0, 0),                    # Input signature
                                gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature

        src0 = gr.sig_source_c (sample_rate,    # sample rate
                                gr.GR_SIN_WAVE, # waveform type
                                350,            # frequency
                                1.0,            # amplitude
                                0)              # DC Offset

        src1 = gr.sig_source_c (sample_rate,    # sample rate
                                gr.GR_SIN_WAVE, # waveform type
                                440,            # frequency
                                1.0,            # amplitude
                                0)              # DC Offset
        sum = gr.add_cc()
        self.connect(src0, (sum, 0))
        self.connect(src1, (sum, 1))
        self.connect(sum, self)
Exemple #54
0
    def __init__(self):
        gr.top_block.__init__(self)

        # Make a local QtApp so we can start it from our side
        self.qapp = QtGui.QApplication(sys.argv)

        fftsize = 2048

        self.src = gr.sig_source_c(1, gr.GR_SIN_WAVE, 0.1, 1)
        self.nse = gr.noise_source_c(gr.GR_GAUSSIAN, 0.0)
        self.add = gr.add_cc()
        self.thr = gr.throttle(gr.sizeof_gr_complex, 100 * fftsize)
        self.snk = qtgui.sink_c(fftsize, gr.firdes.WIN_BLACKMAN_hARRIS)

        self.connect(self.src, (self.add, 0))
        self.connect(self.nse, (self.add, 1))
        self.connect(self.add, self.thr, self.snk)

        # Tell the sink we want it displayed
        self.pyobj = sip.wrapinstance(self.snk.pyqwidget(), QtGui.QWidget)
        self.pyobj.show()
Exemple #55
0
    def __init__(self, noise_voltage, frequency_offset):
        gr.hier_block2.__init__(self, "awgn_channel",
                                gr.io_signature(1, 1, gr.sizeof_gr_complex),
                                gr.io_signature(1, 1, gr.sizeof_gr_complex))

        self.noise_adder = gr.add_cc()
        self.noise = gr.noise_source_c(gr.GR_GAUSSIAN, noise_voltage)
        self.offset = gr.sig_source_c(1, gr.GR_SIN_WAVE, frequency_offset, 1.0,
                                      0.0)
        self.mixer_offset = gr.multiply_cc()

        self.connect(self, (self.mixer_offset, 0))
        self.connect(self.offset, (self.mixer_offset, 1))
        self.connect(self.mixer_offset, (self.noise_adder, 1))
        self.connect(self.noise, (self.noise_adder, 0))
        self.connect(self.noise_adder, self)

        try:
            gr.hier_block.update_var_names(self, "awgn_channel", vars())
            gr.hier_block.update_var_names(self, "awgn_channel", vars(self))
        except:
            pass
Exemple #56
0
    def __init__(self):
        gr.top_block.__init__(self)

        Rs = 8000
        f1 = 1000
        f2 = 2000

        fftsize = 2048

        self.qapp = QtGui.QApplication(sys.argv)

        src1 = gr.sig_source_c(Rs, gr.GR_SIN_WAVE, f1, 0.1, 0)
        src2 = gr.sig_source_c(Rs, gr.GR_SIN_WAVE, f2, 0.1, 0)
        src = gr.add_cc()
        channel = gr.channel_model(0.001)
        thr = gr.throttle(gr.sizeof_gr_complex, 100 * fftsize)
        self.snk1 = qtgui.sink_c(fftsize, gr.firdes.WIN_BLACKMAN_hARRIS, 0, Rs,
                                 "Complex Signal Example", True, True, False,
                                 True, False)

        self.connect(src1, (src, 0))
        self.connect(src2, (src, 1))
        self.connect(src, channel, thr, self.snk1)

        self.ctrl_win = control_box()
        self.ctrl_win.attach_signal1(src1)
        self.ctrl_win.attach_signal2(src2)

        # Get the reference pointer to the SpectrumDisplayForm QWidget
        pyQt = self.snk1.pyqwidget()

        # Wrap the pointer as a PyQt SIP object
        # This can now be manipulated as a PyQt4.QtGui.QWidget
        self.pyWin = sip.wrapinstance(pyQt, QtGui.QWidget)

        self.main_box = dialog_box(self.pyWin, self.ctrl_win)

        self.main_box.show()
Exemple #57
0
    def __init__(self, N, fs, fd, ca_shift, snr=0):
        gr.hier_block2.__init__(self, "simulated_source",
                                gr.io_signature(0, 0, 0),
                                gr.io_signature(1, 1, gr.sizeof_gr_complex))

        code = ca_code(svn=1, fs=fs, ca_shift=ca_shift)
        code = ravel(array([code for _ in range(N)]))

        n = arange(len(code))
        f = e**(2j * pi * fd * n / fs)
        x = (code * f)

        # Add noise.
        signal_power = sum(sqrt(abs(x))) / len(x)
        noise_voltage = sqrt(signal_power / 10**(snr / 10.0))

        src = gr.vector_source_c(x)
        noise = gr.noise_source_c(gr.GR_UNIFORM, noise_voltage)
        add = gr.add_cc()
        self.connect(src, (add, 0))
        self.connect(noise, (add, 1))

        self.connect(add, self)