Пример #1
0
    def test_002_t(self):
        # Generate frames with AWGN and test SNR estimation
        sample_rate = 10.0e6
        frame_duration = 1.0e-3
        test_duration = 0.1 * frame_duration
        snr = 10
        scale_value = 15.0
        samples_per_frame = int(round(frame_duration * sample_rate))
        samples_per_test = int(round(test_duration * sample_rate))
        random_samples_skip = 0  #np.random.randint(samples_per_frame)
        preamble_seq = zadoffchu(63, 1, 0)
        preamble_pwr_sum = np.sum(np.abs(preamble_seq)**2)

        print "***** Start test 002 *****"
        framer = specmonitor.framer_c(sample_rate, frame_duration,
                                      preamble_seq)
        awgn = analog.noise_source_c(analog.GR_GAUSSIAN, 1.0 / snr)
        add = blocks.add_cc()
        scaler = blocks.multiply_const_vcc([complex(scale_value)])
        mag2 = blocks.complex_to_mag_squared()
        mavg = blocks.moving_average_ff(
            len(preamble_seq), 1.0 / len(preamble_seq)
        )  # i need to divide by the preamble size in case the preamble seq has amplitude 1 (sum of power is len)
        sqrtavg = blocks.transcendental("sqrt")

        # I have to compensate the amplitude of the input signal (scale) either through a feedback normalization loop that computes the scale, or manually (not practical)
        # additionally I have to scale down by the len(preamble)==sum(abs(preamble)^2) because the cross-corr does not divide by the preamble length
        #scaler2 = blocks.multiply_const_vcc([complex(1.0)/scale_value/len(preamble_seq)]) # if no feedback normalization loop, I have to scale the signal compensating additionally the scaling factor
        corr_est = specmonitor.corr_est_norm_cc(
            preamble_seq, 1, 0)  #digital.corr_est_cc(preamble_seq, 1, 0)
        tag_db = blocks.tag_debug(gr.sizeof_gr_complex, "tag debugger")
        head = blocks.head(gr.sizeof_gr_complex, samples_per_test)
        dst = blocks.vector_sink_c()

        skiphead = blocks.skiphead(gr.sizeof_float, random_samples_skip)
        skiphead2 = blocks.skiphead(gr.sizeof_gr_complex, random_samples_skip)
        skiphead3 = blocks.skiphead(gr.sizeof_gr_complex, random_samples_skip)
        debug_vec = blocks.vector_sink_f()
        debug_vec2 = blocks.vector_sink_c()
        debug_vec3 = blocks.vector_sink_c()

        self.tb.connect(framer, (add, 0))
        self.tb.connect(awgn, (add, 1))
        self.tb.connect(add, scaler)
        self.tb.connect(scaler, mag2, mavg, sqrtavg)

        self.tb.connect(scaler, corr_est)
        self.tb.connect(corr_est, tag_db)
        self.tb.connect(corr_est, head, dst)

        self.tb.connect(sqrtavg, skiphead, debug_vec)
        self.tb.connect(scaler, skiphead2, debug_vec2)

        self.tb.run()
        result_data = dst.data()
        debug_vec_data = debug_vec.data()
        debug_vec_data2 = debug_vec2.data()
        debug_vec_data3 = debug_vec3.data()
    def __init__(self, num_ports=2, n_skip_ahead=8192):
        gr.hier_block2.__init__(
            self, "TwinRx Phase Offset Estimate",
            gr.io_signaturev(num_ports, num_ports, gen_sig_io(num_ports,gr.sizeof_gr_complex)),
            gr.io_signaturev(num_ports-1, num_ports-1, gen_sig_io(num_ports-1,gr.sizeof_float)),
        )

        ##################################################
        # Parameters
        ##################################################
        self.n_skip_ahead = n_skip_ahead
        self.num_ports = num_ports

        # Create skip head blocks and connect them to the inputs
        self.skiphead = []
        for p in range(0, num_ports):
            object_name_skiphead = 'blocks_skiphead_'+str(p)
            self.skiphead.append(blocks.skiphead(gr.sizeof_gr_complex*1, n_skip_ahead))
            self.connect((self, p), (self.skiphead[p], 0))

        #Create blocks computing subtracted phases and connect the results to the outputs
        self.multiply_conjugate = []
        self.complex_to_arg = []
        for p in range(0, num_ports-1):
            self.multiply_conjugate.append(blocks.multiply_conjugate_cc(1))
            self.complex_to_arg.append(blocks.complex_to_arg(1))

            self.connect((self.skiphead[0], 0), (self.multiply_conjugate[p], 0))
            self.connect((self.skiphead[p+1], 0), (self.multiply_conjugate[p], 1))
            self.connect((self.multiply_conjugate[p], 0), (self.complex_to_arg[p], 0))
            self.connect((self.complex_to_arg[p], 0), (self, p))
Пример #3
0
    def __init__(
            self,
            n_written_samples,
            constellation_obj,
            #pre_diff_code,
            samples_per_symbol,
            excess_bw,
            burst_len,
            zero_pad_len,
            linear_gain=1.0,
            frequency_offset=0.0):
        super(GeneralModFlowgraph, self).__init__()

        # params
        self.n_written_samples = int(n_written_samples)
        self.n_offset_samples = int(
            np.random.randint(0, self.n_written_samples))
        self.constellation_obj = constellation_obj
        self.samples_per_symbol = samples_per_symbol  #TODO
        self.excess_bw = excess_bw  # TODO
        self.linear_gain = float(linear_gain)
        self.burst_len = burst_len
        # TODO: make burst_len also variable
        randgen = random_generator.load_param(zero_pad_len)
        # if isinstance(zero_pad_len,tuple):
        #     self.zero_pad_len = zero_pad_len[1]
        #     self.pad_dist = zero_pad_len[0]
        # else:
        #     self.zero_pad_len = [zero_pad_len]
        #     self.pad_dist = 'constant'
        if isinstance(frequency_offset, tuple):
            assert frequency_offset[0] == 'uniform'
            self.frequency_offset = frequency_offset[1]
        else:  # it is just a value
            self.frequency_offset = [frequency_offset]
        # print 'This is the frequency offset:',frequency_offset
        # self.burst_len = burst_len if not issubclass(burst_len.__class__,ts.ValueGenerator) else burst_len.generate()
        # self.zero_pad_len = zero_pad_len  if not issubclass(zero_pad_len.__class__,ts.ValueGenerator) else zero_pad_len.generate()
        data2send = np.random.randint(0, 256, 1000)

        # phy
        self.data_gen = blocks.vector_source_b(data2send, True)
        self.mod = digital.generic_mod(
            self.constellation_obj,
            samples_per_symbol=self.samples_per_symbol,
            #self.pre_diff_code,
            excess_bw=self.excess_bw)
        self.tagger = blocks.stream_to_tagged_stream(gr.sizeof_gr_complex, 1,
                                                     self.burst_len,
                                                     "packet_len")
        # self.burst_shaper = digital.burst_shaper_cc((1+0*1j,),100,self.zero_pad_len,False)
        self.burst_shaper = specmonitor.random_burst_shaper_cc(
            randgen.dynrandom(), 0, self.frequency_offset, "packet_len")
        self.skiphead = blocks.skiphead(gr.sizeof_gr_complex,
                                        self.n_offset_samples)
        self.head = blocks.head(gr.sizeof_gr_complex, self.n_written_samples)
        self.dst = blocks.vector_sink_c()
        # dst = blocks.file_sink(gr.sizeof_gr_complex,args['targetfolder']+'/tmp.bin')

        self.setup_flowgraph()
Пример #4
0
    def test_001_t(self):
        # set up fg
        test_len = 1000
        packet_len = test_len
        pulse_send = (200, 300, 100)
        pulse_wait = (100, 100)
        amplitude = 0.5

        num_skip = 0  # skip samples with skiphead
        num_xcorr = 300  # num of xcorrs to determine delay samples

        src = radar.signal_generator_sync_pulse_c(packet_len, pulse_send,
                                                  pulse_wait, amplitude,
                                                  "packet_len")
        head = blocks.head(8, test_len)
        skiphead = blocks.skiphead(8, num_skip)
        est = radar.estimator_sync_pulse_c(num_xcorr, "packet_len")
        res = radar.print_results()
        debug = blocks.message_debug()

        self.tb.connect(src, skiphead, head)
        self.tb.connect((head, 0),
                        (est, 0))  # TX stream (undelayed but skiped)
        self.tb.connect((src, 0), (est, 1))  # RX stream (delayed but unskiped)
        self.tb.msg_connect(est, 'Msg out', res, 'Msg in')
        self.tb.msg_connect(est, 'Msg out', debug, 'store')
        self.tb.run()

        # check data
        msg = debug.get_message(0)
        num_skip_est = pmt.to_long(pmt.nth(1, pmt.nth(1, msg)))
        self.assertEqual(num_skip_est, num_skip)
Пример #5
0
	def __init__(self):
		gr.top_block.__init__(self)

		usage = "%prog: [options] samples_file"
		parser = OptionParser(option_class=eng_option, usage=usage)
  		parser.add_option("-m", "--dab-mode", type="int", default=1,
        	     	help="DAB mode [default=%default]")
  		parser.add_option('-u', '--usrp-source', action="store_true", default=False,
	     		help="Samples from USRP (-> resample from 2 MSPS to 2.048 MSPS)")
		(options, args) = parser.parse_args ()

		dp = dab.dab_parameters(options.dab_mode)
		filename = args[0]

		self.src = blocks.file_source(gr.sizeof_gr_complex, filename, False)
		self.resample = blocks.rational_resampler_ccc(2048,2000)
		self.rate_detect_ns = dab.detect_null.detect_null(dp.ns_length, False)
		self.rate_estimator = dab.blocks.estimate_sample_rate_bf(dp.sample_rate, dp.frame_length)
		self.decimate = blocks.keep_one_in_n(gr.sizeof_float, dp.frame_length)
		self.ignore_first = blocks.skiphead(gr.sizeof_float, 1)
		self.sink = blocks.vector_sink_f()

		if options.usrp_source:
			self.connect(self.src, self.resample, self.rate_detect_ns, self.rate_estimator, self.decimate, self.ignore_first, self.sink)
		else:
			self.connect(self.src, self.rate_detect_ns, self.rate_estimator, self.decimate, self.ignore_first, self.sink)
	def test_001_t (self):
		# set up fg
		test_len = 1000
		packet_len = test_len
		pulse_send = (200,300,100)
		pulse_wait = (100,100)
		amplitude = 0.5
		
		num_skip = 5 # skip samples with skiphead
		num_xcorr = 300 # num of xcorrs to determine delay samples
		
		src = radar.signal_generator_sync_pulse_c(packet_len,pulse_send,pulse_wait,amplitude,"packet_len")
		head = blocks.head(8,test_len)
		skiphead = blocks.skiphead(8,num_skip)
		est = radar.estimator_sync_pulse_c(num_xcorr,"packet_len")
		res = radar.print_results()
		debug = blocks.message_debug()
		
		self.tb.connect(src,skiphead,head)
		self.tb.connect((head,0),(est,0)) # TX stream (undelayed but skiped)
		self.tb.connect((src,0),(est,1)) # RX stream (delayed but unskiped)
		self.tb.msg_connect(est,'Msg out',res,'Msg in')
		self.tb.msg_connect(est,'Msg out',debug,'store')
		self.tb.run ()
		
		# check data
		msg = debug.get_message(0)
		num_skip_est = pmt.to_long(pmt.nth(1,pmt.nth(1,msg)))
		self.assertEqual(num_skip_est,num_skip)
Пример #7
0
def run_RF_Rx_on_repeat(outputfile, params, sample_rate, n_rx_samples,
                        n_skip_samples):
    ### Set variables based on given stage parameters
    gaindB = params['rx_gaindB']
    centre_freq = params['rf_frequency']

    print 'STATUS: Going to store', n_rx_samples, 'samples. Going to skip', n_skip_samples

    tb = gr.top_block()
    usrp_source = uhd.usrp_source(
        ",".join(("", "")),
        uhd.stream_args(
            cpu_format="fc32",
            channels=range(1),
        ),
    )
    usrp_source.set_samp_rate(sample_rate)
    usrp_source.set_center_freq(centre_freq, 0)
    usrp_source.set_gain(gaindB, 0)
    skip = blocks.skiphead(gr.sizeof_gr_complex, n_skip_samples)
    head = blocks.head(gr.sizeof_gr_complex, n_rx_samples)
    fsink = blocks.file_sink(gr.sizeof_gr_complex, outputfile)

    tb.connect(usrp_source, skip)
    tb.connect(skip, head)
    tb.connect(head, fsink)

    tb.run()
Пример #8
0
def processInput1tx(file_num, snr):
    freq = numpy.random.permutation([0, -2.5e6, 2.5e6])
    source_A = blocks.vector_source_b(
        map(int, numpy.random.randint(0, 255, 1000000)), True)

    throttle_A = blocks.throttle(gr.sizeof_char * 1, samp_rate_base, True)

    constellation_modulator_A = digital.generic_mod(
        constellation=constellation_variable,
        differential=False,
        samples_per_symbol=sps,
        pre_diff_code=True,
        excess_bw=0.35,
        verbose=False,
        log=False,
    )

    sig_source_A = analog.sig_source_c(upsamp_rate, analog.GR_COS_WAVE,
                                       freq[0],
                                       (10**(snr / 20)) * noise_amplitude, 0)

    resampler_A = filter.rational_resampler_ccc(10,
                                                2,
                                                taps=None,
                                                fractional_bw=None)

    multiply_A = blocks.multiply_vcc(1)

    channel_A = channels.fading_model(12, 0, False, 4.0, 0)

    add_block = blocks.add_vcc(1)

    channel = channels.channel_model(noise_voltage=noise_amplitude,
                                     frequency_offset=0.0,
                                     epsilon=1.0,
                                     taps=(1 + 1j, ),
                                     noise_seed=0,
                                     block_tags=False)

    skip_head = blocks.skiphead(gr.sizeof_gr_complex * 1, 1024)
    head_block = blocks.head(gr.sizeof_gr_complex * 1, 1000000)
    file_sink = blocks.file_sink(
        gr.sizeof_gr_complex * 1,
        'data_1tx_' + str(snr) + 'dB_' + str(file_num) + '.dat', False)

    tb = gr.top_block()

    tb.connect(source_A, throttle_A, constellation_modulator_A, resampler_A,
               (multiply_A, 0))
    tb.connect(sig_source_A, (multiply_A, 1))
    tb.connect(multiply_A, channel_A)

    tb.connect(channel_A, channel)

    tb.connect(channel, skip_head)
    tb.connect(skip_head, head_block)
    tb.connect(head_block, file_sink)

    tb.run()
Пример #9
0
    def test_003_small_frame_mod(self):
        num_frames = 300
        total_subcarriers = 8
        used_subcarriers = 4
        channel_map = np.array(
            (0, 0, 1, 1, 1, 1, 0,
             0))  #ft.get_channel_map(used_subcarriers, total_subcarriers)
        payload_symbols = 8
        overlap = 4
        taps = ft.generate_phydyas_filter(total_subcarriers, overlap)

        preamble = ft.get_preamble(total_subcarriers)
        num_preamble_symbols = len(preamble) // total_subcarriers
        payload = ft.get_payload(payload_symbols, used_subcarriers)
        payload = np.tile(payload, num_frames).flatten()

        src = blocks.vector_source_b(payload, repeat=False)
        framer = fbmc.frame_generator_bvc(used_subcarriers, total_subcarriers,
                                          payload_symbols, overlap,
                                          channel_map, preamble)
        snk_frame = blocks.vector_sink_c(total_subcarriers)  # a debug output

        mod = fbmc.tx_sdft_vcc(taps, total_subcarriers)
        demod = fbmc.rx_sdft_cvc(taps, total_subcarriers)
        skipper = blocks.skiphead(8 * total_subcarriers, 4)

        snk_rx = blocks.vector_sink_c(total_subcarriers)
        deframer = fbmc.deframer_vcb(used_subcarriers, total_subcarriers,
                                     num_preamble_symbols, payload_symbols,
                                     overlap, channel_map)
        snk = blocks.vector_sink_b(1)
        self.tb.connect(src, framer, mod, demod, skipper, deframer, snk)
        self.tb.connect(framer, snk_frame)
        self.tb.connect(skipper, snk_rx)
        self.tb.run()

        res = np.array(snk.data())
        print "len(res) = ", len(res), ", len(payload) = ", len(payload)
        print "ref: ", payload
        print "res: ", res

        moddata = np.array(snk_frame.data())
        print "len(moddata) = ", len(moddata)
        rxdata = np.array(snk_rx.data())
        print "len(rxdata) = ", len(
            rxdata), " diff: ", len(moddata) - len(rxdata)

        # plt.plot(rxdata.real * 0.03)
        # for i in range(len(moddata)):
        #     if (i + 1) % total_subcarriers == 0:
        #         plt.axvline(i)
        # plt.plot(moddata.real)
        # plt.grid()
        # plt.show()

        print "len(payload) = ", len(payload)
        print "len(result ) = ", len(res)

        self.assertTupleEqual(tuple(payload[:len(res)]), tuple(res))
Пример #10
0
    def test_001_t(self):
        # We check if with a constant source, the SNR is measured correctly
        sample_rate = 1e6
        frame_duration = 1.0e-3
        test_duration = 1.5 * frame_duration
        snr = np.random.rand() * 1000
        zc_seq_len = 71

        samples_per_frame = int(round(frame_duration * sample_rate))
        samples_per_test = int(round(test_duration * sample_rate))
        snr_estim_sample_window = zc_seq_len  #int(round(samples_per_frame/20))
        random_samples_skip = np.random.randint(
            samples_per_frame / 2) + samples_per_frame / 2
        preamble_seq = zadoffchu.generate_sequence(zc_seq_len, 1, 0)
        preamble_pwr_sum = np.sum(np.abs(preamble_seq)**2)

        print "***** Start test 001 *****"
        framer = specmonitor.framer_c(sample_rate, frame_duration,
                                      preamble_seq)
        const_source = blocks.vector_source_c([1.0 / snr], True)
        add = blocks.add_cc()
        skiphead = blocks.skiphead(gr.sizeof_gr_complex, random_samples_skip)
        corr_est = specmonitor.corr_est_norm_cc(
            preamble_seq, 1, 0)  #digital.corr_est_cc(preamble_seq, 1, 0)
        snr_est = specmonitor.framer_snr_est_cc(snr_estim_sample_window,
                                                preamble_seq.size)
        # tag_db = blocks.tag_debug(gr.sizeof_gr_complex, "tag debugger")
        head = blocks.head(gr.sizeof_gr_complex, samples_per_test)
        dst = blocks.vector_sink_c()

        self.tb.connect(framer, (add, 0))
        self.tb.connect(const_source, (add, 1))
        self.tb.connect(add, skiphead)
        self.tb.connect(skiphead, head)
        self.tb.connect(head, corr_est)
        self.tb.connect(corr_est, snr_est)
        # self.tb.connect(snr_est,tag_db)
        self.tb.connect(snr_est, dst)

        self.tb.run()
        x_data = dst.data()

        snrdB = snr_est.SNRdB()
        y_data = np.abs(x_data)**2

        # print "Random Initial Skip: ", random_samples_skip
        # print "y_data size: ", len(y_data)

        start_preamble_idx = samples_per_frame - random_samples_skip + preamble_seq.size
        sig_range = np.arange(start_preamble_idx,
                              start_preamble_idx + preamble_seq.size)
        floor_range = np.arange(sig_range[-1] + 1,
                                sig_range[-1] + 1 + snr_estim_sample_window)
        y_pwr = np.mean(y_data[sig_range])
        floor_pwr = np.mean(y_data[floor_range])
        py_snrdB = 10 * np.log10(y_pwr / floor_pwr)

        self.assertAlmostEqual(py_snrdB, 20 * np.log10(snr), 1)
        self.assertAlmostEqual(snrdB, 20 * np.log10(snr), 1)
Пример #11
0
 def test_skip_12678(self):
     skip_cnt = 12678
     expected_result = tuple(self.src_data[skip_cnt:])
     src1 = blocks.vector_source_i(self.src_data)
     op = blocks.skiphead(gr.sizeof_int, skip_cnt)
     dst1 = blocks.vector_sink_i()
     self.tb.connect(src1, op, dst1)
     self.tb.run()
     dst_data = dst1.data()
     self.assertEqual(expected_result, dst_data)
Пример #12
0
 def test_skip_12678(self):
     skip_cnt = 12678
     expected_result = tuple(self.src_data[skip_cnt:])
     src1 = blocks.vector_source_i(self.src_data)
     op = blocks.skiphead(gr.sizeof_int, skip_cnt)
     dst1 = blocks.vector_sink_i()
     self.tb.connect(src1, op, dst1)
     self.tb.run()
     dst_data = dst1.data()
     self.assertEqual(expected_result, dst_data)
Пример #13
0
    def __init__(self):
        gr.hier_block2.__init__(self, "BitErrors",
                                gr.io_signature(1, 1, gr.sizeof_char),
                                gr.io_signature(1, 1, gr.sizeof_int))

        intdump_decim = min(int(N_BITS / 10), 100000)
        self.connect(self, blocks.skiphead(gr.sizeof_char, SKIP),
                     blocks.not_bb(), blocks.and_const_bb(1),
                     blocks.uchar_to_float(),
                     blocks.integrate_ff(intdump_decim),
                     blocks.multiply_const_ff(1.0 / intdump_decim), self)
    def __init__(self, M):
        gr.hier_block2.__init__(self,
            "overlap_serial_to_parallel_cvc",
            gr.io_signature(1, 1, gr.sizeof_gr_complex*1),
            gr.io_signature(1, 1, gr.sizeof_gr_complex*M),
        )

        ##################################################
        # Parameters
        ##################################################
        self.M = M

        ##################################################
        # Blocks
        ##################################################
        ##self.fbmc_vector_reshape_vcvc_1 = fbmc_vector_reshape_vcvc(M/2, M)
        ##self.fbmc_vector_reshape_vcvc_0 = fbmc_vector_reshape_vcvc(M, M/2)
        self.fbmc_vector_copy_vcvc_0 = ofdm.fbmc_vector_copy_vcvc(M/2, 2)
        self.blocks_stream_to_vector_0 = blocks.stream_to_vector(gr.sizeof_gr_complex*1, M/2)
        # self.blocks_skiphead_0 = blocks.skiphead(gr.sizeof_gr_complex*M/2, 1)

        ##################################################
        # Connections
        ##################################################
        # self.connect((self.blocks_skiphead_0, 0), (self.fbmc_vector_reshape_vcvc_1, 0))
        self.connect((self, 0), (self.blocks_stream_to_vector_0, 0))
        self.connect((self.blocks_stream_to_vector_0, 0), (self.fbmc_vector_copy_vcvc_0, 0))
        # self.connect((self.fbmc_vector_copy_vcvc_0, 0), (self, 0))
        # self.connect((self.fbmc_vector_copy_vcvc_0, 0), (self.fbmc_vector_reshape_vcvc_0, 0))
        # self.connect((self.fbmc_vector_reshape_vcvc_0, 0), (self.blocks_skiphead_0, 0))
        # self.connect((self.fbmc_vector_reshape_vcvc_0, 0), (self, 0))
        

        # self.fbmc_vector_copy_vcvc_0 = fbmc.vector_copy_vcvc(M, 2)
        self.blocks_vector_to_stream_0 = blocks.vector_to_stream(gr.sizeof_gr_complex*1, M/2)
        self.blocks_stream_to_vector_0_0 = blocks.stream_to_vector(gr.sizeof_gr_complex*M/2, 2)
        # self.blocks_stream_to_vector_0 = blocks.stream_to_vector(gr.sizeof_gr_complex*1, M)
        self.blocks_skiphead_0 = blocks.skiphead(gr.sizeof_gr_complex*M/2, 1)

        # ##################################################
        # # Connections
        # ##################################################
        # self.connect((self.blocks_stream_to_vector_0, 0), (self.fbmc_vector_copy_vcvc_0, 0))
#         self.connect((self.fbmc_vector_copy_vcvc_0, 0), (self.blocks_vector_to_stream_0, 0))
#         # self.connect((self.blocks_vector_to_stream_0, 0), (self.blocks_stream_to_vector_0_0, 0))
#         self.connect((self.blocks_vector_to_stream_0, 0), (self.blocks_skiphead_0, 0))
#         self.connect((self.blocks_skiphead_0, 0), (self.blocks_stream_to_vector_0_0, 0))
#         # self.connect((self, 0), (self.blocks_stream_to_vector_0, 0))
#         self.connect((self.blocks_stream_to_vector_0_0, 0), (self, 0))
        
        self.connect((self.fbmc_vector_copy_vcvc_0, 0),(self.blocks_skiphead_0, 0))
        self.connect((self.blocks_skiphead_0, 0), (self.blocks_stream_to_vector_0_0, 0))
        # self.connect((self, 0), (self.blocks_stream_to_vector_0, 0))
        self.connect((self.blocks_stream_to_vector_0_0, 0), (self, 0))
def run_test(f, Kb, bitspersymbol, K, channel, modulation, dimensionality,
             tot_constellation, N0, seed):
    tb = gr.top_block()
    L = len(channel)

    # TX
    # this for loop is TOO slow in python!!!
    packet = [0] * (K + 2 * L)
    random.seed(seed)
    for i in range(len(packet)):
        packet[i] = random.randint(0, 2**bitspersymbol - 1)  # random symbols
    for i in range(L):  # first/last L symbols set to 0
        packet[i] = 0
        packet[len(packet) - i - 1] = 0
    src = blocks.vector_source_s(packet, False)
    mod = digital.chunks_to_symbols_sf(modulation[1], modulation[0])

    # CHANNEL
    isi = filter.fir_filter_fff(1, channel)
    add = blocks.add_ff()
    noise = analog.noise_source_f(analog.GR_GAUSSIAN, math.sqrt(N0 / 2), seed)

    # RX
    skip = blocks.skiphead(
        gr.sizeof_float, L
    )  # skip the first L samples since you know they are coming from the L zero symbols
    #metrics = trellis.metrics_f(f.O(),dimensionality,tot_constellation,digital.TRELLIS_EUCLIDEAN) # data preprocessing to generate metrics for Viterbi
    #va = trellis.viterbi_s(f,K+L,0,0) # Put -1 if the Initial/Final states are not set.
    va = trellis.viterbi_combined_s(
        f, K + L, 0, 0, dimensionality, tot_constellation,
        digital.TRELLIS_EUCLIDEAN
    )  # using viterbi_combined_s instead of metrics_f/viterbi_s allows larger packet lengths because metrics_f is complaining for not being able to allocate large buffers. This is due to the large f.O() in this application...
    dst = blocks.vector_sink_s()

    tb.connect(src, mod)
    tb.connect(mod, isi, (add, 0))
    tb.connect(noise, (add, 1))
    #tb.connect (add,metrics)
    #tb.connect (metrics,va,dst)
    tb.connect(add, skip, va, dst)

    tb.run()

    data = dst.data()
    ntotal = len(data) - L
    nright = 0
    for i in range(ntotal):
        if packet[i + L] == data[i]:
            nright = nright + 1
        #else:
        #print "Error in ", i

    return (ntotal, ntotal - nright)
Пример #16
0
    def __init__(self):
        grc_wxgui.top_block_gui.__init__(self, title="Top Block")
        _icon_path = "/usr/share/icons/hicolor/32x32/apps/gnuradio-grc.png"
        self.SetIcon(wx.Icon(_icon_path, wx.BITMAP_TYPE_ANY))

        ##################################################
        # Variables
        ##################################################
        self.samp_rate = samp_rate = 48000

        ##################################################
        # Blocks
        ##################################################
        self.rational_resampler_xxx_1 = filter.rational_resampler_fff(
                interpolation=4160,
                decimation=4800,
                taps=None,
                fractional_bw=None,
        )
        self.rational_resampler_xxx_0 = filter.rational_resampler_fff(
                interpolation=9600,
                decimation=samp_rate,
                taps=None,
                fractional_bw=None,
        )
        self.blocks_wavfile_source_0 = blocks.wavfile_source(sys.argv[1], False)
        self.blocks_skiphead_0 = blocks.skiphead(gr.sizeof_float*1, 1)
        self.blocks_multiply_const_vxx_0 = blocks.multiply_const_vff((255, ))
        self.blocks_keep_one_in_n_1 = blocks.keep_one_in_n(gr.sizeof_float*1, 2)
        self.blocks_keep_one_in_n_0 = blocks.keep_one_in_n(gr.sizeof_float*1, 2)
        self.blocks_float_to_uchar_0 = blocks.float_to_uchar()
        self.blocks_float_to_complex_0 = blocks.float_to_complex(1)
        self.blocks_file_sink_0 = blocks.file_sink(gr.sizeof_char*1, sys.argv[1]+".gray", False)
        self.blocks_file_sink_0.set_unbuffered(False)
        self.blocks_complex_to_mag_0 = blocks.complex_to_mag(1)
        self.band_pass_filter_0 = filter.fir_filter_fff(1, firdes.band_pass(
        	1, samp_rate, 500, 4200, 2000, firdes.WIN_HAMMING, 6.76))

        ##################################################
        # Connections
        ##################################################
        self.connect((self.blocks_wavfile_source_0, 0), (self.band_pass_filter_0, 0))
        self.connect((self.band_pass_filter_0, 0), (self.rational_resampler_xxx_0, 0))
        self.connect((self.rational_resampler_xxx_0, 0), (self.blocks_skiphead_0, 0))
        self.connect((self.blocks_skiphead_0, 0), (self.blocks_keep_one_in_n_1, 0))
        self.connect((self.rational_resampler_xxx_0, 0), (self.blocks_keep_one_in_n_0, 0))
        self.connect((self.blocks_keep_one_in_n_0, 0), (self.blocks_float_to_complex_0, 0))
        self.connect((self.blocks_keep_one_in_n_1, 0), (self.blocks_float_to_complex_0, 1))
        self.connect((self.blocks_float_to_complex_0, 0), (self.blocks_complex_to_mag_0, 0))
        self.connect((self.blocks_complex_to_mag_0, 0), (self.rational_resampler_xxx_1, 0))
        self.connect((self.rational_resampler_xxx_1, 0), (self.blocks_multiply_const_vxx_0, 0))
        self.connect((self.blocks_multiply_const_vxx_0, 0), (self.blocks_float_to_uchar_0, 0))
        self.connect((self.blocks_float_to_uchar_0, 0), (self.blocks_file_sink_0, 0))
Пример #17
0
    def test_003_small_frame_mod(self):
        num_frames = 300
        total_subcarriers = 8
        used_subcarriers = 4
        channel_map = np.array((0, 0, 1, 1, 1, 1, 0, 0)) #ft.get_channel_map(used_subcarriers, total_subcarriers)
        payload_symbols = 8
        overlap = 4
        taps = ft.generate_phydyas_filter(total_subcarriers, overlap)

        preamble = ft.get_preamble(total_subcarriers)
        num_preamble_symbols = len(preamble) // total_subcarriers
        payload = ft.get_payload(payload_symbols, used_subcarriers)
        payload = np.tile(payload, num_frames).flatten()


        src = blocks.vector_source_b(payload, repeat=False)
        framer = fbmc.frame_generator_bvc(used_subcarriers, total_subcarriers, payload_symbols, overlap, channel_map, preamble)
        snk_frame = blocks.vector_sink_c(total_subcarriers)  # a debug output

        mod = fbmc.tx_sdft_vcc(taps, total_subcarriers)
        demod = fbmc.rx_sdft_cvc(taps, total_subcarriers)
        skipper = blocks.skiphead(8 * total_subcarriers, 4)

        snk_rx = blocks.vector_sink_c(total_subcarriers)
        deframer = fbmc.deframer_vcb(used_subcarriers, total_subcarriers, num_preamble_symbols, payload_symbols, overlap, channel_map)
        snk = blocks.vector_sink_b(1)
        self.tb.connect(src, framer, mod, demod, skipper, deframer, snk)
        self.tb.connect(framer, snk_frame)
        self.tb.connect(skipper, snk_rx)
        self.tb.run()

        res = np.array(snk.data())
        print "len(res) = ", len(res), ", len(payload) = ", len(payload)
        print "ref: ", payload
        print "res: ", res

        moddata = np.array(snk_frame.data())
        print "len(moddata) = ", len(moddata)
        rxdata = np.array(snk_rx.data())
        print "len(rxdata) = ", len(rxdata), " diff: ", len(moddata) - len(rxdata)

        # plt.plot(rxdata.real * 0.03)
        # for i in range(len(moddata)):
        #     if (i + 1) % total_subcarriers == 0:
        #         plt.axvline(i)
        # plt.plot(moddata.real)
        # plt.grid()
        # plt.show()

        print "len(payload) = ", len(payload)
        print "len(result ) = ", len(res)

        self.assertTupleEqual(tuple(payload[:len(res)]), tuple(res))
Пример #18
0
    def test_004_config_frame_mod(self):
        num_frames = 10
        cfg = fbmc.fbmc_config(num_used_subcarriers=20, num_payload_sym=16, num_overlap_sym=4, modulation="QPSK",
                                    preamble="IAM", samp_rate=250000)
        total_subcarriers = cfg.num_total_subcarriers()  # 8
        used_subcarriers = cfg.num_used_subcarriers()  # 4
        channel_map = cfg.channel_map()  # ft.get_channel_map(used_subcarriers, total_subcarriers)
        payload_symbols = cfg.num_payload_sym()  # 8
        overlap = cfg.num_overlap_sym()  # 4
        taps = cfg.phydyas_impulse_taps(cfg.num_total_subcarriers(), cfg.num_overlap_sym())  # ft.generate_phydyas_filter(total_subcarriers, overlap)

        preamble = ft.get_preamble(total_subcarriers)
        num_preamble_symbols = len(preamble) // total_subcarriers
        payload = ft.get_payload(payload_symbols, used_subcarriers)
        payload = np.tile(payload, num_frames).flatten()

        src = blocks.vector_source_b(payload, repeat=False)
        framer = fbmc.frame_generator_bvc(used_subcarriers, total_subcarriers, payload_symbols, overlap, channel_map, preamble)
        snk_frame = blocks.vector_sink_c(total_subcarriers)  # a debug output

        mod = fbmc.tx_sdft_vcc(taps, total_subcarriers)
        demod = fbmc.rx_sdft_cvc(taps, total_subcarriers)
        skipper = blocks.skiphead(8 * total_subcarriers, 4)

        snk_rx = blocks.vector_sink_c(total_subcarriers)
        deframer = fbmc.deframer_vcb(used_subcarriers, total_subcarriers, num_preamble_symbols, payload_symbols, overlap, channel_map)
        snk = blocks.vector_sink_b(1)
        self.tb.connect(src, framer, mod, demod, skipper, deframer, snk)
        self.tb.connect(framer, snk_frame)
        self.tb.connect(skipper, snk_rx)
        self.tb.run()

        res = np.array(snk.data())
        print res
        print payload

        moddata = np.array(snk_frame.data())
        print "len(moddata) = ", len(moddata)
        rxdata = np.array(snk_rx.data())
        print "len(rxdata) = ", len(rxdata)

        # plt.plot(rxdata.real * 0.03)
        # for i in range(len(moddata)):
        #     if (i + 1) % total_subcarriers == 0:
        #         plt.axvline(i)
        # plt.plot(moddata.real)
        # plt.grid()
        # plt.show()

        print "len(payload) = ", len(payload)
        print "len(result)  = ", len(res)

        self.assertTupleEqual(tuple(payload[:len(res)]), tuple(res))
Пример #19
0
    def __init__(self):
        gr.top_block.__init__(self, "Top Block")

        ##################################################
        # Variables
        ##################################################
        self.samp_rate = samp_rate = 1E6
        self.gain = gain = 0
        self.f0 = f0 = 3.625E9
        self.bandwidth = bandwidth = 5

        ##################################################
        # Blocks
        ##################################################
        self.uhd_usrp_source_1 = uhd.usrp_source(
            ",".join(("", "")),
            uhd.stream_args(
                cpu_format="fc32",
                channels=range(1),
            ),
        )
        self.uhd_usrp_source_1.set_samp_rate(samp_rate)
        self.uhd_usrp_source_1.set_center_freq(f0, 0)
        self.uhd_usrp_source_1.set_gain(gain, 0)
        self.uhd_usrp_source_1.set_antenna("TX/RX", 0)
        self.uhd_usrp_source_1.set_bandwidth(bandwidth, 0)
        self.blocks_skiphead_0 = blocks.skiphead(gr.sizeof_gr_complex * 1, 20)
        self.blocks_nlog10_ff_0 = blocks.nlog10_ff(10, 1, 0)
        self.blocks_multiply_xx_0 = blocks.multiply_vcc(1)
        self.blocks_head_0 = blocks.head(gr.sizeof_gr_complex * 1, 1000)
        self.blocks_file_sink_1 = blocks.file_sink(
            gr.sizeof_float * 1,
            "/home/odroid/Documents/2ndRF/calibration/Power", False)
        self.blocks_file_sink_1.set_unbuffered(False)
        self.blocks_conjugate_cc_0 = blocks.conjugate_cc()
        self.blocks_complex_to_real_0 = blocks.complex_to_real(1)

        ##################################################
        # Connections
        ##################################################
        self.connect((self.blocks_complex_to_real_0, 0),
                     (self.blocks_nlog10_ff_0, 0))
        self.connect((self.blocks_conjugate_cc_0, 0),
                     (self.blocks_multiply_xx_0, 1))
        self.connect((self.blocks_head_0, 0), (self.blocks_conjugate_cc_0, 0))
        self.connect((self.blocks_head_0, 0), (self.blocks_multiply_xx_0, 0))
        self.connect((self.blocks_multiply_xx_0, 0),
                     (self.blocks_complex_to_real_0, 0))
        self.connect((self.blocks_nlog10_ff_0, 0),
                     (self.blocks_file_sink_1, 0))
        self.connect((self.blocks_skiphead_0, 0), (self.blocks_head_0, 0))
        self.connect((self.uhd_usrp_source_1, 0), (self.blocks_skiphead_0, 0))
Пример #20
0
 def test_symbol_src ( self, arity ):
   vlen = 1
   N = int( 1e7 )
   
   demapper = ofdm.generic_demapper_vcb( vlen )
   const = demapper.get_constellation( arity )
   assert( len( const ) == 2**arity )
   
   symsrc = ofdm.symbol_random_src( const, vlen )
   # tx = transmitter_hier_bc(M=M,K=K,qam_size=qam_size,syms_per_frame=syms_per_frame,theta_sel=theta_sel,exclude_preamble=exclude_preamble,sel_preamble=None)
   acc = ofdm.accumulator_cc()
   skiphead = blocks.skiphead( gr.sizeof_gr_complex, N-1 )
   limit = blocks.head( gr.sizeof_gr_complex, 1 )
   dst = blocks.vector_sink_c()
   
   c2mag = blocks.complex_to_mag_squared()
   acc_c2m = ofdm.accumulator_ff()
   skiphead_c2m = blocks.skiphead( gr.sizeof_float, N-1 )
   limit_c2m = blocks.head( gr.sizeof_float, 1 )
   dst_c2m = blocks.vector_sink_f()
   
   tb = gr.top_block ( "test__block" )
   tb.connect( symsrc, acc, skiphead, limit, dst )
   tb.connect( symsrc, c2mag, acc_c2m, skiphead_c2m, limit_c2m, dst_c2m )
   tb.run()
   
   data = numpy.array( dst.data() )
   data_c2m = numpy.array( dst_c2m.data() )
   
   m = data / N
   av_pow = data_c2m / N
   
   assert( abs( m ) < 0.01 )
   assert( abs( 1.0 - av_pow ) < 0.5  )
   
   print "Uniform distributed random symbol source has"
   print "\tno offset for N=%d, relative error: %f" % (arity, abs( m ) )
   print "\tAverage signal power equal 1.0, relative error: %f\t\tOK" \
          % ( abs( 1.0 - av_pow ) )
Пример #21
0
    def __init__(self,mod,delay=0,n_0=0,min_errors=100):
        ModMeasurementGraph.__init__(self, mod, "BER Measurement")
        self.__probe_thread = None
        self._did_timeout = False  
                
        # Blocks
        self.src = digital.glfsr_source_b(8, True, 0, 1)
        # self.src = blocks.vector_source_b(np.concatenate((np.ones(5,dtype='B'),np.zeros(10,dtype='B'))).tolist(),True)
        # self.src = blocks.vector_source_b(np.zeros(10,dtype='B').tolist(),True)
        self.noise = analog.noise_source_c(analog.GR_GAUSSIAN, math.sqrt(float(n_0)), 0)
        self.delay = blocks.delay(gr.sizeof_char,delay)
        self.add = blocks.add_vcc(1)
        self.skiphead_orig = blocks.skiphead(gr.sizeof_char,500)
        self.skiphead_rx = blocks.skiphead(gr.sizeof_char,500)

        self.pack_rx_bits = blocks.pack_k_bits_bb(8)
        self.pack_msg_bits = blocks.pack_k_bits_bb(8)
        self.ber_measure = fec.ber_bf(True, min_errors, -7.0)
        self.ber_sink = blocks.vector_sink_f(1)
                
        # Connections
        self.connect(self.src,self.mod_in_bits)

        # Adding noise to tx output of mod
        self.connect(self.mod_out_signal,(self.add,0))
        self.connect(self.noise,(self.add,1))
        self.connect(self.add,self.mod_in_signal)

        # Rx bits from mod to ber measure
        self.connect(self.mod_out_bits,self.skiphead_rx)
        self.connect(self.skiphead_rx,self.pack_rx_bits)
        self.connect(self.pack_rx_bits,(self.ber_measure,1))

        # delayed bits to ber measure
        self.connect(self.src,self.delay)
        self.connect(self.delay,self.skiphead_orig)
        self.connect(self.skiphead_orig,self.pack_msg_bits)
        self.connect(self.pack_msg_bits,(self.ber_measure,0))  
        self.connect(self.ber_measure,self.ber_sink)
def run_test(f, Kb, bitspersymbol, K, channel, modulation, dimensionality, tot_constellation, N0, seed):
    tb = gr.top_block()
    L = len(channel)

    # TX
    # this for loop is TOO slow in python!!!
    packet = [0] * (K + 2 * L)
    random.seed(seed)
    for i in range(len(packet)):
        packet[i] = random.randint(0, 2 ** bitspersymbol - 1)  # random symbols
    for i in range(L):  # first/last L symbols set to 0
        packet[i] = 0
        packet[len(packet) - i - 1] = 0
    src = blocks.vector_source_s(packet, False)
    mod = digital.chunks_to_symbols_sf(modulation[1], modulation[0])

    # CHANNEL
    isi = filter.fir_filter_fff(1, channel)
    add = blocks.add_ff()
    noise = analog.noise_source_f(analog.GR_GAUSSIAN, math.sqrt(N0 / 2), seed)

    # RX
    skip = blocks.skiphead(
        gr.sizeof_float, L
    )  # skip the first L samples since you know they are coming from the L zero symbols
    # metrics = trellis.metrics_f(f.O(),dimensionality,tot_constellation,digital.TRELLIS_EUCLIDEAN) # data preprocessing to generate metrics for Viterbi
    # va = trellis.viterbi_s(f,K+L,0,0) # Put -1 if the Initial/Final states are not set.
    va = trellis.viterbi_combined_s(
        f, K + L, 0, 0, dimensionality, tot_constellation, digital.TRELLIS_EUCLIDEAN
    )  # using viterbi_combined_s instead of metrics_f/viterbi_s allows larger packet lengths because metrics_f is complaining for not being able to allocate large buffers. This is due to the large f.O() in this application...
    dst = blocks.vector_sink_s()

    tb.connect(src, mod)
    tb.connect(mod, isi, (add, 0))
    tb.connect(noise, (add, 1))
    # tb.connect (add,metrics)
    # tb.connect (metrics,va,dst)
    tb.connect(add, skip, va, dst)

    tb.run()

    data = dst.data()
    ntotal = len(data) - L
    nright = 0
    for i in range(ntotal):
        if packet[i + L] == data[i]:
            nright = nright + 1
        # else:
        # print "Error in ", i

    return (ntotal, ntotal - nright)
Пример #23
0
    def __init__(self, n_samples, n_offset_samples, n_prbs, linear_gain,
                 pad_interval, mcs, frequency_offset):
        super(GrLTETracesFlowgraph, self).__init__()
        self.subcarrier_spacing = 15000

        # params
        self.n_samples = n_samples
        self.n_prbs = n_prbs
        self.linear_gain = linear_gain
        self.mcs = mcs

        # derived params
        self.fft_size = GrLTETracesFlowgraph.prb_mapping[self.n_prbs]
        self.samp_rate = float(self.fft_size * self.subcarrier_spacing)
        n_prbs_str = "%02d" % (self.n_prbs, )
        mcs_str = "%02d" % (self.mcs)
        fname = '{}/lte_dump_prb_{}_mcs_{}.32fc'.format(
            frames_path, n_prbs_str, mcs_str)
        self.expected_bw = GrLTETracesFlowgraph.fftsize_mapping[self.fft_size]
        self.resamp_ratio = 20.0e6 / self.samp_rate
        self.n_samples_per_frame = int(10.0e-3 * self.samp_rate)
        self.n_offset_samples = int(
            lf.random_generator.load_value(n_offset_samples))
        randgen = lf.random_generator.load_generator(pad_interval)
        # scale by sampling rate
        new_params = tuple(
            [int(v / self.resamp_ratio) for v in randgen.params])
        randgen.params = new_params
        if isinstance(frequency_offset, tuple):
            assert frequency_offset[0] == 'uniform'
            self.frequency_offset = frequency_offset[1]
        else:  # it is just a value
            self.frequency_offset = [frequency_offset]

        # blocks
        self.file_reader = blocks.file_source(gr.sizeof_gr_complex, fname,
                                              True)
        self.tagger = blocks.stream_to_tagged_stream(gr.sizeof_gr_complex, 1,
                                                     self.n_samples_per_frame,
                                                     "packet_len")
        self.burst_shaper = specmonitor.random_burst_shaper_cc(
            randgen.dynrandom(), 0, self.frequency_offset, "packet_len")
        # self.resampler = filter.rational_resampler_base_ccc(interp,decim,taps)
        self.resampler = filter.fractional_resampler_cc(
            0, 1 / self.resamp_ratio)
        self.skiphead = blocks.skiphead(gr.sizeof_gr_complex,
                                        self.n_offset_samples)
        self.head = blocks.head(gr.sizeof_gr_complex, self.n_samples)
        self.dst = blocks.vector_sink_c()

        self.setup_flowgraph()
Пример #24
0
    def __init__(self):
        gr.top_block.__init__(self, "Simulator Sync Pulse")
        Qt.QWidget.__init__(self)
        self.setWindowTitle("Simulator Sync Pulse")
        qtgui.util.check_set_qss()
        try:
            self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc'))
        except:
            pass
        self.top_scroll_layout = Qt.QVBoxLayout()
        self.setLayout(self.top_scroll_layout)
        self.top_scroll = Qt.QScrollArea()
        self.top_scroll.setFrameStyle(Qt.QFrame.NoFrame)
        self.top_scroll_layout.addWidget(self.top_scroll)
        self.top_scroll.setWidgetResizable(True)
        self.top_widget = Qt.QWidget()
        self.top_scroll.setWidget(self.top_widget)
        self.top_layout = Qt.QVBoxLayout(self.top_widget)
        self.top_grid_layout = Qt.QGridLayout()
        self.top_layout.addLayout(self.top_grid_layout)

        self.settings = Qt.QSettings("GNU Radio", "simulator_sync_pulse")
        self.restoreGeometry(self.settings.value("geometry").toByteArray())

        ##################################################
        # Variables
        ##################################################
        self.samp_rate = samp_rate = 250000
        self.num_skip = num_skip = 50
        self.num_corr = num_corr = 75

        ##################################################
        # Blocks
        ##################################################
        self._num_corr_range = Range(0, 100, 1, 75, 200)
        self._num_corr_win = RangeWidget(self._num_corr_range, self.set_num_corr, "num_corr", "counter_slider", float)
        self.top_layout.addWidget(self._num_corr_win)
        self.radar_signal_generator_sync_pulse_c_0 = radar.signal_generator_sync_pulse_c(2**12, ((300,50,200)), ((100,200,50)), 0.5, "packet_len")
        self.radar_print_results_0 = radar.print_results(False, "")
        self.radar_estimator_sync_pulse_c_0 = radar.estimator_sync_pulse_c(int(num_corr), "packet_len")
        self.blocks_throttle_0 = blocks.throttle(gr.sizeof_gr_complex*1, samp_rate,True)
        self.blocks_skiphead_0 = blocks.skiphead(gr.sizeof_gr_complex*1, num_skip)

        ##################################################
        # Connections
        ##################################################
        self.msg_connect((self.radar_estimator_sync_pulse_c_0, 'Msg out'), (self.radar_print_results_0, 'Msg in'))
        self.connect((self.blocks_skiphead_0, 0), (self.radar_estimator_sync_pulse_c_0, 0))
        self.connect((self.blocks_throttle_0, 0), (self.radar_estimator_sync_pulse_c_0, 1))
        self.connect((self.radar_signal_generator_sync_pulse_c_0, 0), (self.blocks_skiphead_0, 0))
        self.connect((self.radar_signal_generator_sync_pulse_c_0, 0), (self.blocks_throttle_0, 0))
    def __init__(self, options):
        gr.top_block.__init__(self, name = "top_block")


        ##################################################
        # Variables
        ##################################################
        self.samp_rate = samp_rate = 1e6
        self.fft_len = fft_len = options.fft_length
        self.ebn0 = ebn0 = options.ebn0
        self.cp_len = cp_len = options.cp_length
        self.bits_per_symbol = bits_per_symbol = 8

        ##################################################
        # Blocks
        ##################################################
        self.digital_ofdm_mod_0 = grc_blks2.packet_mod_i(digital.ofdm_mod(
        		options=grc_blks2.options(
        			modulation="qam256",
        			fft_length=fft_len,
        			occupied_tones=40,
        			cp_length=cp_len,
        			pad_for_usrp=True,
        			log=None,
        			verbose=None,
        		),
        	),
        	payload_length=0,
        )
        self.blocks_throttle_0 = blocks.throttle(gr.sizeof_gr_complex*1, samp_rate)
        self.blocks_skiphead_0 = blocks.skiphead(gr.sizeof_gr_complex*1, (fft_len+cp_len)*1)
        self.blocks_file_sink_0 = blocks.file_sink(gr.sizeof_gr_complex*1, "./%d_%d_%d_%d_%s.bin" % (fft_len, cp_len, options.ebn0, options.it, options.type), False)
        self.blocks_file_sink_0.set_unbuffered(False)
        self.blocks_add_xx_0 = blocks.add_vcc(1)
        self.analog_random_source_x_0 = blocks.vector_source_i(map(int, numpy.random.randint(0, 2, 1000)), True)
        self.analog_noise_source_x_0 = analog.noise_source_c(analog.GR_GAUSSIAN, 1.0 / math.sqrt(2.0 * bits_per_symbol * 10**(ebn0/10.0)), 0)

        self.channels_selective_fading_model_0 = channels.selective_fading_model( 8, 10.0/samp_rate, False, 4.0, 0, options.delay, options.mag, 128 )

        ##################################################
        # Connections
        ##################################################
        self.connect((self.blocks_throttle_0, 0), (self.blocks_file_sink_0, 0))
        self.connect((self.analog_random_source_x_0, 0), (self.digital_ofdm_mod_0, 0))
        self.connect((self.digital_ofdm_mod_0, 0), (self.channels_selective_fading_model_0, 0))
        self.connect((self.blocks_skiphead_0, 0), (self.blocks_throttle_0, 0))
        self.connect((self.blocks_add_xx_0, 0), (self.blocks_skiphead_0, 0))
        self.connect((self.channels_selective_fading_model_0, 0), (self.blocks_add_xx_0, 0))
        self.connect((self.analog_noise_source_x_0, 0), (self.blocks_add_xx_0, 1))
    def __init__(self, snr_val, verbose=False):
        gr.top_block.__init__(self, name="SNR estimation accuracy test")
        zc_seq_len = 503  #199

        sample_rate = 1e6
        frame_duration = 2.0e-3
        test_duration = 1.5 * frame_duration
        samples_per_frame = int(round(frame_duration * sample_rate))
        samples_per_test = int(round(test_duration * sample_rate))
        n_samples_snr_estim = zc_seq_len  #int(round(samples_per_frame/20))
        random_samples_skip = np.random.randint(
            samples_per_frame / 2) + samples_per_frame / 2
        preamble_seq = zadoffchu.generate_sequence(zc_seq_len, 1, 0)
        preamble_pwr_sum = np.sum(np.abs(preamble_seq)**2)
        sigma_val = 1 / float(10.0**(snr_val / 20.0))
        thres = 0.25

        # if samples_per_test-random_samples_skip+2*preamble_seq.size+n_samples_snr_estim >= samples_per_test:
        #     print "The test duration is not long enough"
        #     exit()

        self.framer = specmonitor.framer_c(sample_rate, frame_duration,
                                           preamble_seq)
        self.awgn = analog.noise_source_c(analog.GR_GAUSSIAN, sigma_val)
        self.add = blocks.add_cc()
        self.skiphead = blocks.skiphead(gr.sizeof_gr_complex,
                                        random_samples_skip)
        self.corr_est = specmonitor.corr_est_norm_cc(
            preamble_seq, 1, 0,
            thres)  #digital.corr_est_cc(preamble_seq, 1, 0)
        self.snr_est = specmonitor.framer_snr_est_cc(n_samples_snr_estim,
                                                     preamble_seq.size)
        if verbose is True:
            self.tag_db = blocks.tag_debug(gr.sizeof_gr_complex,
                                           "tag debugger")
        self.head = blocks.head(gr.sizeof_gr_complex, samples_per_test)
        self.dst = blocks.vector_sink_c()

        self.connect(self.framer, (self.add, 0))
        self.connect(self.awgn, (self.add, 1))
        self.connect(self.add, self.skiphead)
        self.connect(self.skiphead, self.head)
        self.connect(self.head, self.corr_est)
        self.connect(self.corr_est, self.snr_est)
        if verbose is True:
            self.connect(self.snr_est, self.tag_db)
        self.connect(self.snr_est, self.dst)
    def __init__(self,
                 samp_rate_hz,
                 sps,
                 SF,
                 shr,
                 filtered_preamble_code,
                 alpha=1e-3,
                 beta=5,
                 time_gap_chips=11,
                 max_offset_hz=0,
                 max_num_filters=1,
                 output_correlator_index=0):
        gr.hier_block2.__init__(
            self,
            "SpaRSe_synchronization_cc",
            gr.io_signature(1, 1, gr.sizeof_gr_complex),  # Input signature
            gr.io_signature3(3, 3, gr.sizeof_gr_complex, gr.sizeof_gr_complex,
                             gr.sizeof_float))  # Output signature

        self.delta_phi = lpwan.SpaRSe_utils.calculate_phase_increments(
            samp_rate_hz, SF, sps, max_offset_hz, max_num_filters)

        # Define blocks
        self.rotators = [blocks.rotator_cc(-phi) for phi in self.delta_phi]
        self.matched_filters = [
            filter.fft_filter_ccf(1,
                                  np.flipud(np.conj(filtered_preamble_code)))
            for i in xrange(len(self.delta_phi))
        ]
        self.preamble_detector = preamble_detector_cc(shr, sps, SF,
                                                      time_gap_chips, alpha,
                                                      beta, self.delta_phi,
                                                      output_correlator_index)
        self.skiphead = blocks.skiphead(
            gr.sizeof_gr_complex,
            sps * (SF + time_gap_chips) +
            4)  # the +4 is "empirical" but well tested for sps=4

        # Connect blocks with preamble detector and outputs
        for i in xrange(len(self.delta_phi)):
            self.connect(self, self.rotators[i], self.matched_filters[i],
                         (self.preamble_detector, i))
        self.connect(self, self.skiphead,
                     (self.preamble_detector, len(self.delta_phi)))
        for i in xrange(3):
            self.connect((self.preamble_detector, i), (self, i))
Пример #28
0
    def __init__(self,n_samples,
                 n_offset_samples,
                 n_prbs,
                 linear_gain,
                 pad_interval,
                 frequency_offset):
        super(GrLTEULTracesFlowgraph, self).__init__()

        # params
        self.n_samples = n_samples
        self.n_offset_samples = int(lf.random_generator.load_value(n_offset_samples))
        self.linear_gain = linear_gain
        trace_number = 0

        #derived
        subcarrier_spacing = 15000
        fftsize = GrLTEULTracesFlowgraph.prb_mapping[n_prbs]#50]
        self.samp_rate = float(fftsize*subcarrier_spacing)
        self.expected_bw = GrLTEULTracesFlowgraph.fftsize_mapping[fftsize]
        self.fname = GrLTEULTracesFlowgraph.lte_up_filenames[trace_number]
        self.fname = os.path.expanduser(os.path.join('~/tmp/lte_frames/ul',self.fname))
        self.n_samples_per_frame = int(10.0e-3*self.samp_rate)
        self.resamp_ratio = 20.0e6/self.samp_rate
        randgen = lf.random_generator.load_generator(pad_interval)
        # scale by sampling rate
        new_params = [int(v/self.resamp_ratio) for v in randgen.params]
        randgen = lf.random_generator(randgen.dist_name,new_params)

        if isinstance(frequency_offset,tuple):
            assert frequency_offset[0]=='uniform'
            self.frequency_offset = frequency_offset[1]
        else: # it is just a value
            self.frequency_offset = [frequency_offset]

        # blocks
        self.file_reader = blocks.file_source(gr.sizeof_gr_complex,self.fname,True)
        self.tagger = blocks.stream_to_tagged_stream(gr.sizeof_gr_complex,1,self.n_samples_per_frame,"packet_len")
        self.burst_shaper = random_burst_shaper_cc(randgen.dynrandom(), 0, self.frequency_offset,"packet_len")
        self.resampler = filter.fractional_resampler_cc(0,1/self.resamp_ratio)
        self.skiphead = blocks.skiphead(gr.sizeof_gr_complex,
                                        self.n_offset_samples)
        self.head = blocks.head(gr.sizeof_gr_complex, self.n_samples)
        self.dst = blocks.vector_sink_c()

        self.setup_flowgraph()
Пример #29
0
	def __init__(self):
		gr.hier_block2.__init__(self, "deinterleaver",
				gr.io_signature(1, 1, gr.sizeof_char),	# Input signature
				gr.io_signature(1, 1, gr.sizeof_char))	# Output signature

		self.demux = blocks.stream_to_streams(gr.sizeof_char, INTERLEAVER_I)
		self.shift_registers = [dvb.fifo_shift_register_bb(INTERLEAVER_M * j)
				for j in range(INTERLEAVER_I)]
		# Deinterleaver shift registers are reversed compared to interleaver
		self.shift_registers.reverse()
		self.mux = blocks.streams_to_stream(gr.sizeof_char, INTERLEAVER_I)
		# Remove the uninitialised zeros that come out of the deinterleaver
		self.skip = blocks.skiphead(gr.sizeof_char, DELAY)

		self.connect(self, self.demux)
		for j in range(INTERLEAVER_I):
			self.connect((self.demux, j), self.shift_registers[j], (self.mux, j))
		self.connect(self.mux, self.skip, self)
Пример #30
0
  def sim ( self, arity, snr_db, N ):
    
    vlen = 1
    N = int( N )
    snr = 10.0**(snr_db/10.0)
    
    sigpow = 1.0
    noise_pow = sigpow / snr
    
    demapper = ofdm.generic_demapper_vcb( vlen )
    const = demapper.get_constellation( arity )
    assert( len( const ) == 2**arity )
    
    symsrc = ofdm.symbol_random_src( const, vlen )
    noise_src = ofdm.complex_white_noise( 0.0, sqrt( noise_pow ) )
    channel = blocks.add_cc()
    bitmap_src = blocks.vector_source_b( [arity] * vlen, True, vlen )
    bm_trig_src = blocks.vector_source_b( [1], True )
    ref_bitstream = blocks.unpack_k_bits_bb( arity )
    bitstream_xor = blocks.xor_bb()
    bitstream_c2f = blocks.char_to_float()
    acc_biterr = ofdm.accumulator_ff()
    skiphead = blocks.skiphead( gr.sizeof_float, N-1 )
    limit = blocks.head( gr.sizeof_float, 1 )
    dst = blocks.vector_sink_f()
    
    tb = gr.top_block ( "test_block" )
    
    tb.connect( (symsrc,0), (channel,0) )
    tb.connect( noise_src,  (channel,1) )
    tb.connect( channel,     (demapper,0), (bitstream_xor,0) )
    tb.connect( bitmap_src,  (demapper,1) )
    tb.connect( bm_trig_src, (demapper,2) )
    tb.connect( (symsrc,1), ref_bitstream, (bitstream_xor,1) )
    tb.connect( bitstream_xor, bitstream_c2f, acc_biterr )
    tb.connect( acc_biterr, skiphead, limit, dst )

    tb.run()
    
    bit_errors = numpy.array( dst.data() )
    assert( len( bit_errors ) == 1 )
    bit_errors = bit_errors[0]
    
    return bit_errors / N
    def __init__(self, snr_val, cfo=0, sto=0, verbose=False):
        gr.top_block.__init__(self, name="CFO estimation test")
        zc_seq_len = 503  #199
        sample_rate = 1e6
        frame_duration = 2.0e-3
        test_duration = 1.5 * frame_duration
        sigma_val = 1 / float(10.0**(snr_val / 20.0))
        thres = 0.25

        samples_per_frame = int(round(frame_duration * sample_rate))
        samples_per_test = int(round(test_duration * sample_rate))
        n_samples_snr_estim = zc_seq_len
        random_samples_skip = np.random.randint(
            samples_per_frame / 2) + samples_per_frame / 2
        preamble_seq = zadoffchu.generate_sequence(zc_seq_len, 1, 0)
        preamble_pwr_sum = np.sum(np.abs(preamble_seq)**2)

        self.framer = specmonitor.framer_c(sample_rate, frame_duration,
                                           preamble_seq)
        self.channel = channels.channel_model(sigma_val, cfo, sto, [1 + 1j])
        self.skiphead = blocks.skiphead(gr.sizeof_gr_complex,
                                        random_samples_skip)
        self.corr_est = specmonitor.corr_est_norm_cc(
            preamble_seq, 1, 0,
            thres)  #digital.corr_est_cc(preamble_seq, 1, 0)
        self.snr_est = specmonitor.framer_snr_est_cc(n_samples_snr_estim,
                                                     preamble_seq.size)
        if verbose is True:
            self.tag_db = blocks.tag_debug(gr.sizeof_gr_complex,
                                           "tag debugger")
        self.head = blocks.head(gr.sizeof_gr_complex, samples_per_test)
        self.dst = blocks.vector_sink_c()
        self.dst2 = blocks.vector_sink_c()

        self.connect(self.framer, self.channel)
        self.connect(self.channel, self.skiphead)
        # self.connect(self.framer,self.skiphead)
        self.connect(self.skiphead, self.head)
        self.connect(self.head, self.corr_est)
        self.connect(self.corr_est, self.snr_est)
        self.connect((self.corr_est, 1), self.dst2)
        if verbose is True:
            self.connect(self.snr_est, self.tag_db)
        self.connect(self.snr_est, self.dst)
Пример #32
0
    def test_skip_tags(self):
        skip_cnt = 25
        expected_result = tuple(self.src_data[skip_cnt:])

        src_tags = tuple([make_tag('foo', 'bar', 1, 'src'),
                          make_tag('baz', 'qux', 50, 'src')])
        src1 = blocks.vector_source_i(self.src_data, tags=src_tags)
        op = blocks.skiphead(gr.sizeof_int, skip_cnt)
        dst1 = blocks.vector_sink_i()
        self.tb.connect(src1, op, dst1)
        self.tb.run()
        dst_data = dst1.data()
        self.assertEqual(expected_result, dst_data)
        self.assertEqual(dst1.tags()[0].offset, 25, "Tag offset is incorrect")
        self.assertEqual(len(dst1.tags()), 1, "Wrong number of tags received")
        self.assertEqual(pmt.to_python(
            dst1.tags()[0].key), "baz", "Tag key is incorrect")
        self.assertEqual(pmt.to_python(
            dst1.tags()[0].value), "qux", "Tag value is incorrect")
Пример #33
0
    def test_skip_tags(self):
        skip_cnt = 25
        expected_result = tuple(self.src_data[skip_cnt:])

        src_tags = tuple([make_tag('foo', 'bar', 1, 'src'),
                          make_tag('baz', 'qux', 50, 'src')])
        src1 = blocks.vector_source_i(self.src_data, tags=src_tags)
        op = blocks.skiphead(gr.sizeof_int, skip_cnt)
        dst1 = blocks.vector_sink_i()
        self.tb.connect(src1, op, dst1)
        self.tb.run()
        dst_data = dst1.data()
        self.assertEqual(expected_result, dst_data)
        self.assertEqual(dst1.tags()[0].offset, 25, "Tag offset is incorrect")
        self.assertEqual(len(dst1.tags()), 1, "Wrong number of tags received")
        self.assertEqual(pmt.to_python(
            dst1.tags()[0].key), "baz", "Tag key is incorrect")
        self.assertEqual(pmt.to_python(
            dst1.tags()[0].value), "qux", "Tag value is incorrect")
Пример #34
0
    def setup(self):
        self.skip = blocks.skiphead(self.dsize, self._start)

        n = 0
        self.srcs = list()
        self._data_min = sys.maxint
        self._data_max = -sys.maxint - 1
        for f in self._filelist:
            data,_min,_max = self.read_samples(f, self._start, self._nsamps)
            if(_min < self._data_min):
                self._data_min = _min
            if(_max > self._data_max):
                self._data_max = _max

            self.srcs.append(self.src_type(data))

            # Set default labels based on file names
            fname = f.split("/")[-1]
            if(type(self.gui_snk) == qtgui.time_sink_c_sptr):
                self.gui_snk.set_line_label(n, "Re{{{0}}}".format(fname))
                self.gui_snk.set_line_label(n+1, "Im{{{0}}}".format(fname))
                n += 2
            else:
                self.gui_snk.set_line_label(n, "{0}".format(fname))
                n += 1

        self.connect(self.srcs[0], self.skip)
        self.connect(self.skip, (self.gui_snk, 0))

        for i,s in enumerate(self.srcs[1:]):
            self.connect(s, (self.gui_snk, i+1))

        self.gui_snk.set_update_time(0)
        self.gui_snk.enable_menu(False)
        self.auto_scale(self._auto_scale)

        # Get Python Qt references
        pyQt  = self.gui_snk.pyqwidget()
        self.pyWin = sip.wrapinstance(pyQt, QtGui.QWidget)

        self._is_setup = True
Пример #35
0
    def setup(self):
        self.skip = blocks.skiphead(self.dsize, self._start)

        n = 0
        self.srcs = list()
        self._data_min = sys.maxint
        self._data_max = -sys.maxint - 1
        for f in self._filelist:
            data, _min, _max = self.read_samples(f, self._start, self._nsamps)
            if _min < self._data_min:
                self._data_min = _min
            if _max > self._data_max:
                self._data_max = _max

            self.srcs.append(self.src_type(data))

            # Set default labels based on file names
            fname = f.split("/")[-1]
            if type(self.gui_snk) == qtgui.time_sink_c_sptr:
                self.gui_snk.set_line_label(n, "Re{{{0}}}".format(fname))
                self.gui_snk.set_line_label(n + 1, "Im{{{0}}}".format(fname))
                n += 2
            else:
                self.gui_snk.set_line_label(n, "{0}".format(fname))
                n += 1

        self.connect(self.srcs[0], self.skip)
        self.connect(self.skip, (self.gui_snk, 0))

        for i, s in enumerate(self.srcs[1:]):
            self.connect(s, (self.gui_snk, i + 1))

        self.gui_snk.set_update_time(0)
        self.gui_snk.enable_menu(False)
        self.auto_scale(self._auto_scale)

        # Get Python Qt references
        pyQt = self.gui_snk.pyqwidget()
        self.pyWin = sip.wrapinstance(pyQt, QtGui.QWidget)

        self._is_setup = True
Пример #36
0
    def __init__(self, snr, snr_reference, sink_file):
        gr.hier_block2.__init__(
            self,
            "snr_head_file",
            gr.io_signature(1, 1, gr.sizeof_gr_complex * 1),
            gr.io_signature(0, 0, 0),
        )
        noise_amp = 10**(-snr / (snr_reference * 20.0))

        self.head = blocks.head(gr.sizeof_gr_complex * 1, 1024)
        self.skiphead = blocks.skiphead(gr.sizeof_gr_complex * 1, 10000)
        self.file_sink = blocks.file_sink(gr.sizeof_gr_complex * 1, sink_file,
                                          False)
        self.file_sink.set_unbuffered(False)
        self.add = blocks.add_vcc(1)
        self.noise_source = analog.fastnoise_source_c(analog.GR_GAUSSIAN,
                                                      noise_amp, 0, 8192)

        self.connect(self.noise_source, (self.add, 0), self.skiphead,
                     self.head, self.file_sink)
        self.connect(self, (self.add, 1))
Пример #37
0
def emulate_repeating_RF_channel(outputfile, framed_signal, fparams,
                                 n_sections, Nsuperframe, params, Nsettle):
    ### Set variables based on given parameters
    tot_linear_gain, noise_voltage = read_and_assert_channel_amplitudes(params)
    freq_offset = params.get('channel_frequency_offset', 0)
    DC_offset = params.get('DC_offset', 0)
    DC_offset *= np.exp(1j * 2 * np.pi *
                        np.random.rand(1))  # add a random phase
    DC_offset = DC_offset[0]
    # TODO: Understand why you get a list here

    print 'final SNRdB:', 10 * np.log10(tot_linear_gain**2 / noise_voltage**2)

    # get needed global parameters
    frame_period = fparams.frame_period

    ### Read Signal already Framed and apply channel effects, keep repeating, and writes the result to a temp file
    # GNURadio Flowgraph
    tb = gr.top_block()
    random_TxRx_unsync = np.random.randint(1000)
    Rx_num_samples = Nsuperframe + Nsettle  # the settle is important both for the HW and pdetec history
    Rx_num_samples += frame_period + 10  # we will only choose peaks whose frame is whole. I just add an guard interval of a few samples

    source = blocks.vector_source_c(framed_signal, True)  # keep repeating
    attenuation = blocks.multiply_const_cc(tot_linear_gain + 0 * 1j)
    channel = channels.channel_model(noise_voltage, freq_offset)
    dc_block = blocks.add_const_cc(DC_offset + 0 * 1j)
    skip = blocks.skiphead(gr.sizeof_gr_complex, random_TxRx_unsync)
    head = blocks.head(gr.sizeof_gr_complex, Rx_num_samples)
    fsink = blocks.file_sink(gr.sizeof_gr_complex, outputfile)

    tb.connect(source, attenuation)
    tb.connect(attenuation, channel)
    tb.connect(channel, dc_block)
    tb.connect(dc_block, skip)
    tb.connect(skip, head)
    tb.connect(head, fsink)

    tb.run()
Пример #38
0
    def fft_channelizer( self, fft_len, channel_bins):
        #do a fwd fft
        self.fft_channelizer_s2v = blocks.stream_to_vector( gr.sizeof_gr_complex*1, fft_len)
        self.fft_channelizer_fft_fwd = fft.fft_vcc( fft_len, True, (window.blackmanharris(1024)), True, 1)
        self.fft_channelizer_v2s = blocks.vector_to_stream( gr.sizeof_gr_complex*1, fft_len)
        self.connect(   self.fft_channelizer_s2v,
                        self.fft_channelizer_fft_fwd,
                        self.fft_channelizer_v2s)

        #per channel
        self.fft_channelizer_skiphead = []
        self.fft_channelizer_keep_m_in_n = []
        self.fft_channelizer_stream2vector = []
        self.fft_channelizer_multiply_const = []
        self.fft_channelizer_fft_rev = []
        self.fft_channelizer_vector2stream = []
        for from_bin, to_bin in channel_bins:
            #output samp rate: samp_rate / (fft_len/keep)
            keep = to_bin - from_bin
            fft_channelizer_taps = taps.taps(keep)

            self.fft_channelizer_skiphead.append( blocks.skiphead(gr.sizeof_gr_complex*1, from_bin))
            self.fft_channelizer_keep_m_in_n.append( blocks.keep_m_in_n(gr.sizeof_gr_complex, keep, fft_len, 0))
            self.fft_channelizer_stream2vector.append( blocks.stream_to_vector(gr.sizeof_gr_complex*1, keep))
            self.fft_channelizer_multiply_const.append( blocks.multiply_const_vcc(fft_channelizer_taps))
            self.fft_channelizer_fft_rev.append( fft.fft_vcc( keep, False, (window.blackmanharris(1024)), True, 1))
            self.fft_channelizer_vector2stream.append( blocks.vector_to_stream( gr.sizeof_gr_complex*1, keep))

            self.connect(   self.fft_channelizer_v2s,
                            self.fft_channelizer_skiphead[-1],
                            self.fft_channelizer_keep_m_in_n[-1],
                            self.fft_channelizer_stream2vector[-1],
                            self.fft_channelizer_multiply_const[-1],
                            self.fft_channelizer_fft_rev[-1],
                            self.fft_channelizer_vector2stream[-1])


        return self.fft_channelizer_s2v, self.fft_channelizer_vector2stream
Пример #39
0
    def setup(self):
        self.skip = blocks.skiphead(self.dsize, self._start)

        n = 0
        self.srcs = list()
        self._data_min = sys.maxsize
        self._data_max = -sys.maxsize - 1
        for f in self._filelist:
            data,_min,_max = self.read_samples(f, self._start,
                                               self._nsamps, self._psd_size)
            if(_min < self._data_min):
                self._data_min = _min
            if(_max > self._data_max):
                self._data_max = _max

            self.srcs.append(self.src_type(data))

            # Set default labels based on file names
            fname = f.split("/")[-1]
            self.gui_snk.set_line_label(n, "{0}".format(fname))
            n += 1

        self.connect(self.srcs[0], self.skip)
        self.connect(self.skip, (self.gui_snk, 0))

        for i,s in enumerate(self.srcs[1:]):
            self.connect(s, (self.gui_snk, i+1))

        self.gui_snk.set_update_time(0);
        self.gui_snk.set_time_per_fft(self._psd_size / self._samp_rate)
        self.gui_snk.enable_menu(False)
        self.gui_snk.set_fft_average(self._avg)

        # Get Python Qt references
        pyQt = self.gui_snk.pyqwidget()
        self.pyWin = sip.wrapinstance(pyQt, QtGui.QWidget)

        self._is_setup = True
Пример #40
0
    def setup(self):
        self.skip = blocks.skiphead(self.dsize, self._start)

        n = 0
        self.srcs = list()
        self._data_min = sys.maxint
        self._data_max = -sys.maxint - 1
        for f in self._filelist:
            data,_min,_max = self.read_samples(f, self._start,
                                               self._nsamps, self._psd_size)
            if(_min < self._data_min):
                self._data_min = _min
            if(_max > self._data_max):
                self._data_max = _max

            self.srcs.append(self.src_type(data))

            # Set default labels based on file names
            fname = f.split("/")[-1]
            self.gui_snk.set_line_label(n, "{0}".format(fname))
            n += 1

        self.connect(self.srcs[0], self.skip)
        self.connect(self.skip, (self.gui_snk, 0))

        for i,s in enumerate(self.srcs[1:]):
            self.connect(s, (self.gui_snk, i+1))

        self.gui_snk.set_update_time(0);
        self.gui_snk.set_time_per_fft(self._psd_size/self._samp_rate)
        self.gui_snk.enable_menu(False)
        self.gui_snk.set_fft_average(self._avg)

        # Get Python Qt references
        pyQt = self.gui_snk.pyqwidget()
        self.pyWin = sip.wrapinstance(pyQt, QtGui.QWidget)

        self._is_setup = True
Пример #41
0
    def __init__(self):
        gr.top_block.__init__(self)

        usage = "%prog: [options] samples_file"
        parser = OptionParser(option_class=eng_option, usage=usage)
        parser.add_option("-m",
                          "--dab-mode",
                          type="int",
                          default=1,
                          help="DAB mode [default=%default]")
        parser.add_option(
            '-u',
            '--usrp-source',
            action="store_true",
            default=False,
            help="Samples from USRP (-> resample from 2 MSPS to 2.048 MSPS)")
        (options, args) = parser.parse_args()

        dp = grdab.dab_parameters(options.dab_mode)
        filename = args[0]

        self.src = blocks.file_source(gr.sizeof_gr_complex, filename, False)
        self.resample = blocks.rational_resampler_ccc(2048, 2000)
        self.rate_detect_ns = grdab.detect_null.detect_null(
            dp.ns_length, False)
        self.rate_estimator = grdab.blocks.estimate_sample_rate_bf(
            dp.sample_rate, dp.frame_length)
        self.decimate = blocks.keep_one_in_n(gr.sizeof_float, dp.frame_length)
        self.ignore_first = blocks.skiphead(gr.sizeof_float, 1)
        self.sink = blocks.vector_sink_f()

        if options.usrp_source:
            self.connect(self.src, self.resample, self.rate_detect_ns,
                         self.rate_estimator, self.decimate, self.ignore_first,
                         self.sink)
        else:
            self.connect(self.src, self.rate_detect_ns, self.rate_estimator,
                         self.decimate, self.ignore_first, self.sink)
Пример #42
0
def run_test(seed,blocksize):
        tb = gr.top_block()

	##################################################
	# Variables
	##################################################
	M = 2
	K = 1
	P = 2
	h = (1.0*K)/P
	L = 3
	Q = 4
        frac = 0.99
        f = trellis.fsm(P,M,L)

        # CPFSK signals
        #p = numpy.ones(Q)/(2.0)
        #q = numpy.cumsum(p)/(1.0*Q)

        # GMSK signals
        BT=0.3;
        tt=numpy.arange(0,L*Q)/(1.0*Q)-L/2.0;
        #print tt
        p=(0.5*scipy.special.erfc(2*math.pi*BT*(tt-0.5)/math.sqrt(math.log(2.0))/math.sqrt(2.0))-0.5*scipy.special.erfc(2*math.pi*BT*(tt+0.5)/math.sqrt(math.log(2.0))/math.sqrt(2.0)))/2.0;
        p=p/sum(p)*Q/2.0;
        #print p
        q=numpy.cumsum(p)/Q;
        q=q/q[-1]/2.0;
        #print q

        (f0T,SS,S,F,Sf,Ff,N) = fsm_utils.make_cpm_signals(K,P,M,L,q,frac)
        #print N
        #print Ff
        Ffa = numpy.insert(Ff,Q,numpy.zeros(N),axis=0)
        #print Ffa
        MF = numpy.fliplr(numpy.transpose(Ffa))
        #print MF
        E = numpy.sum(numpy.abs(Sf)**2,axis=0)
        Es = numpy.sum(E)/f.O()
        #print Es

        constellation = numpy.reshape(numpy.transpose(Sf),N*f.O())
        #print Ff
        #print Sf
        #print constellation
        #print numpy.max(numpy.abs(SS - numpy.dot(Ff , Sf)))

	EsN0_db = 10.0
        N0 =  Es * 10.0**(-(1.0*EsN0_db)/10.0)
        #N0 = 0.0
        #print N0
        head = 4
        tail = 4
        numpy.random.seed(seed*666)
        data = numpy.random.randint(0, M, head+blocksize+tail+1)
        #data = numpy.zeros(blocksize+1+head+tail,'int')
        for i in range(head):
            data[i]=0
        for i in range(tail+1):
            data[-i]=0



	##################################################
	# Blocks
	##################################################
	random_source_x_0 = blocks.vector_source_b(data.tolist(), False)
	digital_chunks_to_symbols_xx_0 = digital.chunks_to_symbols_bf((-1, 1), 1)
	filter_interp_fir_filter_xxx_0 = filter.interp_fir_filter_fff(Q, p)
	analog_frequency_modulator_fc_0 = analog.frequency_modulator_fc(2*math.pi*h*(1.0/Q))

	blocks_add_vxx_0 = blocks.add_vcc(1)
	analog_noise_source_x_0 = analog.noise_source_c(analog.GR_GAUSSIAN, (N0/2.0)**0.5, -long(seed))

	blocks_multiply_vxx_0 = blocks.multiply_vcc(1)
	analog_sig_source_x_0 = analog.sig_source_c(Q, analog.GR_COS_WAVE, -f0T, 1, 0)
        # only works for N=2, do it manually for N>2...
	filter_fir_filter_xxx_0_0 = filter.fir_filter_ccc(Q, MF[0].conjugate())
	filter_fir_filter_xxx_0_0_0 = filter.fir_filter_ccc(Q, MF[1].conjugate())
	blocks_streams_to_stream_0 = blocks.streams_to_stream(gr.sizeof_gr_complex*1, int(N))
	blocks_skiphead_0 = blocks.skiphead(gr.sizeof_gr_complex*1, int(N*(1+0)))
	viterbi = trellis.viterbi_combined_cb(f, head+blocksize+tail, 0, -1, int(N),
					      constellation, digital.TRELLIS_EUCLIDEAN)

        blocks_vector_sink_x_0 = blocks.vector_sink_b()

	##################################################
	# Connections
	##################################################
	tb.connect((random_source_x_0, 0), (digital_chunks_to_symbols_xx_0, 0))
	tb.connect((digital_chunks_to_symbols_xx_0, 0), (filter_interp_fir_filter_xxx_0, 0))
	tb.connect((filter_interp_fir_filter_xxx_0, 0), (analog_frequency_modulator_fc_0, 0))
	tb.connect((analog_frequency_modulator_fc_0, 0), (blocks_add_vxx_0, 0))
	tb.connect((analog_noise_source_x_0, 0), (blocks_add_vxx_0, 1))
	tb.connect((blocks_add_vxx_0, 0), (blocks_multiply_vxx_0, 0))
	tb.connect((analog_sig_source_x_0, 0), (blocks_multiply_vxx_0, 1))
	tb.connect((blocks_multiply_vxx_0, 0), (filter_fir_filter_xxx_0_0, 0))
	tb.connect((blocks_multiply_vxx_0, 0), (filter_fir_filter_xxx_0_0_0, 0))
	tb.connect((filter_fir_filter_xxx_0_0, 0), (blocks_streams_to_stream_0, 0))
	tb.connect((filter_fir_filter_xxx_0_0_0, 0), (blocks_streams_to_stream_0, 1))
	tb.connect((blocks_streams_to_stream_0, 0), (blocks_skiphead_0, 0))
	tb.connect((blocks_skiphead_0, 0), (viterbi, 0))
	tb.connect((viterbi, 0), (blocks_vector_sink_x_0, 0))


        tb.run()
        dataest = blocks_vector_sink_x_0.data()
        #print data
        #print numpy.array(dataest)
        perr = 0
        err = 0
        for i in range(blocksize):
          if data[head+i] != dataest[head+i]:
            #print i
            err += 1
        if err != 0 :
          perr = 1
        return (err,perr)
Пример #43
0
    def __init__(self, decim=50, decim_df=.2, decim_f=.4, device_address="type=b200", device_arguments="master_clock_rate=30.72e6", df_ref=0, df_test=10e3, f_sample=960e3*4, f_sig=6e9, g_ref=0, g_sig=0, g_test=49, n_samples=1<<24, name="test", pass_tags=False, port_base=6880, f_dsp=0):
        gr.top_block.__init__(self, "Ampm Cli")

        ##################################################
        # Parameters
        ##################################################
        self.decim = decim
        self.decim_df = decim_df
        self.decim_f = decim_f
        self.device_address = device_address
        self.device_arguments = device_arguments
        self.df_ref = df_ref
        self.df_test = df_test
        self.f_sample = f_sample
        self.f_sig = f_sig
        self.g_ref = g_ref
        self.g_sig = g_sig
        self.g_test = g_test
        self.n_samples = n_samples
        self.name = name
        self.pass_tags = pass_tags
        self.port_base = port_base
        self.f_dsp = f_dsp

        ##################################################
        # Variables
        ##################################################
        self.info = info = {"name":name, "f_sig":f_sig, "df_ref":df_ref, "f_sample":f_sample, "decim":decim}
        self.filename = filename = "{:s}_f0{:.5g}_df{:.5g}_fs{:.5g}_d{:.5g}".format(name, f_sig/1e6, df_ref, f_sample/1e6, decim)

        ##################################################
        # Blocks
        ##################################################
        self.zeromq_sub_source_0_2_0 = zeromq.sub_source(gr.sizeof_float, decim**0, "tcp://localhost:{}".format(port_base + 9), 100, pass_tags)
        self.zeromq_sub_source_0_2 = zeromq.sub_source(gr.sizeof_gr_complex, decim**0, "tcp://localhost:{}".format(port_base + 0), 100, pass_tags)
        self.zeromq_sub_source_0_1 = zeromq.sub_source(gr.sizeof_gr_complex, decim**1, "tcp://localhost:6881", 100, pass_tags)
        self.zeromq_sub_source_0_0 = zeromq.sub_source(gr.sizeof_gr_complex, decim**3, "tcp://localhost:6883", 100, pass_tags)
        self.zeromq_sub_source_0 = zeromq.sub_source(gr.sizeof_gr_complex, decim**2, "tcp://localhost:6882", 100, pass_tags)
        self.zeromq_pub_sink_0_1_2 = zeromq.pub_sink(gr.sizeof_float, decim**0, "tcp://*:{}".format(port_base + 9), 100, pass_tags)
        self.zeromq_pub_sink_0_1_1 = zeromq.pub_sink(gr.sizeof_gr_complex, decim**1, "tcp://*:{}".format(port_base + 1), 100, pass_tags)
        self.zeromq_pub_sink_0_1_0_0 = zeromq.pub_sink(gr.sizeof_gr_complex, decim**3, "tcp://*:{}".format(port_base + 3), 100, pass_tags)
        self.zeromq_pub_sink_0_1_0 = zeromq.pub_sink(gr.sizeof_gr_complex, decim**2, "tcp://*:{}".format(port_base + 2), 100, pass_tags)
        self.zeromq_pub_sink_0_1 = zeromq.pub_sink(gr.sizeof_gr_complex, decim**0, "tcp://*:{}".format(port_base + 0), 100, pass_tags)
        self.uhd_usrp_source_0_0 = uhd.usrp_source(
        	",".join((device_address, device_arguments)),
        	uhd.stream_args(
        		cpu_format="fc32",
        		channels=range(2),
        	),
        )
        self.uhd_usrp_source_0_0.set_subdev_spec("A:A A:B", 0)
        self.uhd_usrp_source_0_0.set_time_unknown_pps(uhd.time_spec())
        self.uhd_usrp_source_0_0.set_samp_rate(f_sample)
        self.uhd_usrp_source_0_0.set_center_freq(uhd.tune_request(target_freq=f_sig , dsp_freq=f_dsp, rf_freq_policy=uhd.tune_request.POLICY_AUTO, dsp_freq_policy=uhd.tune_request.POLICY_MANUAL), 0)
        self.uhd_usrp_source_0_0.set_gain(g_sig, 0)
        self.uhd_usrp_source_0_0.set_bandwidth(30.72e6, 0)
        self.uhd_usrp_source_0_0.set_center_freq(uhd.tune_request(target_freq=f_sig + df_ref, dsp_freq=f_dsp, rf_freq_policy=uhd.tune_request.POLICY_AUTO, dsp_freq_policy=uhd.tune_request.POLICY_MANUAL), 1)
        self.uhd_usrp_source_0_0.set_gain(g_ref, 1)
        self.uhd_usrp_source_0_0.set_bandwidth(30.72e6, 1)
        self.blocks_stream_to_vector_0_1_0 = blocks.stream_to_vector(gr.sizeof_gr_complex*1, decim**3)
        self.blocks_stream_to_vector_0_1 = blocks.stream_to_vector(gr.sizeof_gr_complex*1, decim**2)
        self.blocks_stream_to_vector_0_0_0 = blocks.stream_to_vector(gr.sizeof_float*1, decim**0)
        self.blocks_stream_to_vector_0_0 = blocks.stream_to_vector(gr.sizeof_gr_complex*1, decim**0)
        self.blocks_stream_to_vector_0 = blocks.stream_to_vector(gr.sizeof_gr_complex*1, decim**1)
        self.blocks_skiphead_0 = blocks.skiphead(gr.sizeof_gr_complex*decim**3, n_samples/decim**3)
        self.blocks_head_0_1 = blocks.head(gr.sizeof_gr_complex*decim**1, n_samples/decim**1)
        self.blocks_head_0_0 = blocks.head(gr.sizeof_gr_complex*decim**3, n_samples/decim**3)
        self.blocks_head_0 = blocks.head(gr.sizeof_gr_complex*decim**2, n_samples/decim**2)
        self.blocks_file_meta_sink_0_3_0 = blocks.file_meta_sink(gr.sizeof_float*decim**0, "{}_w.bin".format(filename), f_sample, decim**3, blocks.GR_FILE_FLOAT, False, 1<<20, "", True)
        self.blocks_file_meta_sink_0_3_0.set_unbuffered(False)
        self.blocks_file_meta_sink_0_3 = blocks.file_meta_sink(gr.sizeof_gr_complex*decim**0, "{}_0.bin".format(filename), f_sample, decim**3, blocks.GR_FILE_FLOAT, True, 1<<20, "", True)
        self.blocks_file_meta_sink_0_3.set_unbuffered(False)
        self.blocks_file_meta_sink_0_1 = blocks.file_meta_sink(gr.sizeof_gr_complex*decim**1, "{}_1.bin".format(filename), f_sample, decim**2, blocks.GR_FILE_FLOAT, True, 1<<20, "", True)
        self.blocks_file_meta_sink_0_1.set_unbuffered(False)
        self.blocks_file_meta_sink_0_0 = blocks.file_meta_sink(gr.sizeof_gr_complex*decim**3, "{}_3.bin".format(filename), f_sample, decim**0, blocks.GR_FILE_FLOAT, True, 1<<20, "", True)
        self.blocks_file_meta_sink_0_0.set_unbuffered(False)
        self.blocks_file_meta_sink_0 = blocks.file_meta_sink(gr.sizeof_gr_complex*decim**2, "{}_2.bin".format(filename), f_sample, decim**1, blocks.GR_FILE_FLOAT, True, 1<<20, "", True)
        self.blocks_file_meta_sink_0.set_unbuffered(False)
        self.blocks_ctrlport_probe2_c_0_1 = blocks.ctrlport_probe2_c("d0", "diff0", 1024, gr.DISPTIME)
        self.blocks_ctrlport_probe2_c_0_0 = blocks.ctrlport_probe2_c("b", "input b", 1024, gr.DISPTIME)
        self.blocks_ctrlport_probe2_c_0 = blocks.ctrlport_probe2_c("a", "input a", 1024, gr.DISPTIME)
        self.blocks_ctrlport_monitor_0 = not True or monitor()
        self.Ampm_0 = Ampm(
            decim=decim,
            decim_df=decim_df,
            decim_f=decim_f,
        )

        ##################################################
        # Connections
        ##################################################
        self.connect((self.Ampm_0, 0), (self.blocks_ctrlport_probe2_c_0_1, 0))    
        self.connect((self.Ampm_0, 2), (self.blocks_stream_to_vector_0, 0))    
        self.connect((self.Ampm_0, 3), (self.blocks_stream_to_vector_0_0, 0))    
        self.connect((self.Ampm_0, 4), (self.blocks_stream_to_vector_0_0_0, 0))    
        self.connect((self.Ampm_0, 1), (self.blocks_stream_to_vector_0_1, 0))    
        self.connect((self.Ampm_0, 0), (self.blocks_stream_to_vector_0_1_0, 0))    
        self.connect((self.blocks_head_0, 0), (self.blocks_file_meta_sink_0, 0))    
        self.connect((self.blocks_head_0_0, 0), (self.blocks_file_meta_sink_0_0, 0))    
        self.connect((self.blocks_head_0_1, 0), (self.blocks_file_meta_sink_0_1, 0))    
        self.connect((self.blocks_skiphead_0, 0), (self.blocks_head_0_0, 0))    
        self.connect((self.blocks_stream_to_vector_0, 0), (self.zeromq_pub_sink_0_1_1, 0))    
        self.connect((self.blocks_stream_to_vector_0_0, 0), (self.zeromq_pub_sink_0_1, 0))    
        self.connect((self.blocks_stream_to_vector_0_0_0, 0), (self.zeromq_pub_sink_0_1_2, 0))    
        self.connect((self.blocks_stream_to_vector_0_1, 0), (self.zeromq_pub_sink_0_1_0, 0))    
        self.connect((self.blocks_stream_to_vector_0_1_0, 0), (self.zeromq_pub_sink_0_1_0_0, 0))    
        self.connect((self.uhd_usrp_source_0_0, 0), (self.Ampm_0, 0))    
        self.connect((self.uhd_usrp_source_0_0, 1), (self.Ampm_0, 1))    
        self.connect((self.uhd_usrp_source_0_0, 0), (self.blocks_ctrlport_probe2_c_0, 0))    
        self.connect((self.uhd_usrp_source_0_0, 1), (self.blocks_ctrlport_probe2_c_0_0, 0))    
        self.connect((self.zeromq_sub_source_0, 0), (self.blocks_head_0, 0))    
        self.connect((self.zeromq_sub_source_0_0, 0), (self.blocks_skiphead_0, 0))    
        self.connect((self.zeromq_sub_source_0_1, 0), (self.blocks_head_0_1, 0))    
        self.connect((self.zeromq_sub_source_0_2, 0), (self.blocks_file_meta_sink_0_3, 0))    
        self.connect((self.zeromq_sub_source_0_2_0, 0), (self.blocks_file_meta_sink_0_3_0, 0))    
	def __init__(self):
		gr.top_block.__init__(self)

		# FIXME When I try larger matrices, I get allocation errors
		# from the console.

		# Load the parity check matrix.
		parity_check_matrix=LDPC_parity_check_matrix(alist_filename=\
		          "H_100_3_5_encoding-ready.alist")

		# The gap g for each matrix is listed in the README file in
		# the alist_files directory.
		g = 2
		t = parity_check_matrix.numRows - g
		H = parity_check_matrix.H

		# Simulate actual data by generating an array of random 
		# numbers of length k.
		k = parity_check_matrix.k
		dataword = random_integers(0,1,(1,k))[0].reshape(1,k)
		# Need to make it a tuple
		dataword_tuple = ()
		for index in range(k):
			dataword_tuple=dataword_tuple+(int(dataword[0][index]),)
		
		# Create signal source.
		src = blocks.vector_source_i(dataword_tuple)
		
		# This is a preprocessing step required for the encoder.
		# You don't need to do this repeatedly during real-time
		# encoding. 
		[invT,invPhi,E,A,B,D,n,k] = \
					 extractUpperTriangulationMatrixParameters(H,t,g)

		str2vec = blocks.stream_to_vector(4, k)
		vec2str = blocks.vector_to_stream(4, n)

		# Setup encoder and decoder.
		encoder = Richardson_Urbanke_encoder_ss(invT,invPhi,E,A,B,D,\
		                                        n,k,g)
		decoder = bit_flip_decoder_ss(parity_check_matrix)

		# Use blocks.skiphead to extract the last k bits from the
		# the codeword. This is s, the systematic part.
		skip_ahead = blocks.skiphead(4, n-k)
		
		# FIXME need to add a channel block to introduce some errors
		# and test the decoder

		# Connect the blocks and run.
		dst = blocks.vector_sink_i()
		self.connect(src,str2vec,encoder,decoder,\
			         vec2str,skip_ahead,dst)
		self.run ()
		result_data = dst.data()
		
		# Check resulting dataword against original dataword
		test = dataword - result_data
		if (test.any()):
			print 'Test failed.'
		else:
			print 'Test passed.'
Пример #45
0
  def sim ( self, arity, snr_db, N ):
    
    vlen = 10
    N = int( N )
    snr = 10.0**(snr_db/10.0)
    
    sigpow = 1.0
    noise_pow = sigpow / snr
    #skipping first symbol due to demapper implementation (demmaper assumes that the first symbol is ID and do not decode ui)
    skiphead_src = blocks.skiphead( gr.sizeof_char, vlen+3)#vlen+3 )
    demapper = ofdm.generic_demapper_vcb( vlen,N/vlen+1 )
    const = demapper.get_constellation( arity )
    assert( len( const ) == 2**arity )
    
    symsrc = ofdm.symbol_random_src( const, vlen )
    #noise_src = ofdm.complex_white_noise( 0.0, sqrt( noise_pow ) )
    noise_src = analog.fastnoise_source_c(analog.GR_GAUSSIAN, 0.0, 0, 8192)
    channel = blocks.add_cc()
    ch_model = channels.channel_model(
            noise_voltage=0.0,
            frequency_offset=0.0,
            epsilon=1.0,
            #taps = (0.998160541385960,0.0605566335500750,0.00290305927764350),
            taps = (1,0),
            noise_seed=8192,
            block_tags=False
        )
    bitmap_src = blocks.vector_source_b( [arity] * vlen, True, vlen )
    #bm_trig_src = blocks.vector_source_b( [1], True )
    ref_bitstream = blocks.unpack_k_bits_bb( arity )
    bitstream_xor = blocks.xor_bb()
    bitstream_c2f = blocks.char_to_float()
    acc_biterr = ofdm.accumulator_ff()
    skiphead = blocks.skiphead( gr.sizeof_float, N-1 )
    limit = blocks.head( gr.sizeof_float, 1 )
    dst = blocks.vector_sink_f()
    
    rec_dst = blocks.vector_sink_b()
    ref_dst = blocks.vector_sink_b()
    
    tb = gr.top_block ( "test_block" )
    #tb.connect( (symsrc,0),blocks.vector_to_stream(gr.sizeof_gr_complex ,vlen),blocks.head(gr.sizeof_gr_complex,N/arity),blocks.null_sink(gr.sizeof_gr_complex))
    
    #tb.connect( (symsrc,0),fft.fft_vcc(vlen,False,[],True),blocks.vector_to_stream(gr.sizeof_gr_complex ,vlen), ch_model, (channel,0) )
    tb.connect( (symsrc,0),blocks.vector_to_stream(gr.sizeof_gr_complex ,vlen), ch_model, (channel,0) )
    tb.connect( noise_src,  (channel,1) )
    #tb.connect( channel, blocks.stream_to_vector(gr.sizeof_gr_complex ,vlen),fft.fft_vcc(vlen,True,[],True),  (demapper,0), (bitstream_xor,0) )
    tb.connect( channel, blocks.stream_to_vector(gr.sizeof_gr_complex ,vlen), (demapper,0), (bitstream_xor,0) )
    tb.connect( bitmap_src,  (demapper,1) )
    #tb.connect( bm_trig_src, (demapper,2) )
    tb.connect( (symsrc,1),blocks.vector_to_stream(gr.sizeof_char ,vlen),skiphead_src, ref_bitstream, (bitstream_xor,1) )
    tb.connect( bitstream_xor, bitstream_c2f, acc_biterr )
    tb.connect( acc_biterr, skiphead, limit, dst )
    tb.connect( demapper, rec_dst )
    tb.connect( ref_bitstream,  ref_dst )

    tb.run()
    
    bit_errors = numpy.array( dst.data() )
    assert( len( bit_errors ) == 1 )
    bit_errors = bit_errors[0]
    
    rec_data = list(rec_dst.data())
    ref_data = list(ref_dst.data())
    
    print "ref_data: ", ref_data[:2000]
    print "size ref_data: ", len(ref_data)#[:2320
    print "rec_data: ", rec_data[:500]
    print "size rec_data: ", len(rec_data)#[:2320
    
    return bit_errors / N
Пример #46
0
def main():
    args = get_arguments()
    constellation = {
            1:digital.constellation_bpsk(),
            2:digital.constellation_qpsk(),
            3:digital.constellation_8psk(),
    }
    
    occupied_carriers=(range(-26, -21) + range(-20, -7) +
                       range(-6, 0) + range(1, 7) +
                       range(8, 21) + range(22, 27),)
    pilot_carriers=((-21, -7, 7, 21),)
    pilot_symbols=tuple([(1, -1, 1, -1),])
    
    packet_len_tag = "packet_length"
    fft_len = 64
    cp_len = 16
    
    tb = gr.top_block()
    
    if args.freq == None:
        data_source = mimoots.file_source2(
                itemsize=(gr.sizeof_gr_complex, gr.sizeof_gr_complex),
                filename=(
                        '1.'.join(args.from_file.rsplit('.',1)),
                        '2.'.join(args.from_file.rsplit('.',1))
                )
        )
        
    else:
        data_source = mimoots.uhd_source(freq=args.freq, gain=args.gain)
       
    skip0 = blocks.skiphead(
            itemsize=gr.sizeof_gr_complex,
            nitems_to_skip=args.skiphead
    )
    
    skip1 = blocks.skiphead(
            itemsize=gr.sizeof_gr_complex,
            nitems_to_skip=args.skiphead
    )
    
    #ofdm_frames1 = mimoots.ofdm_receive_frames_cb(
    #        nofdm_frames=args.nframes,
    #        nofdm_symbols=args.nsymbols,
    #        constellation=constellation[args.bits],
    #        occupied_carriers=occupied_carriers,
    #        pilot_carriers=pilot_carriers,
    #        pilot_symbols=pilot_symbols,
    #        debug=args.debug
    #)
    
    #ofdm_frames2 = mimoots.ofdm_receive_frames_cb(
    #        nofdm_frames=args.nframes,
    #        nofdm_symbols=args.nsymbols,
    #        constellation=constellation[args.bits],
    #        occupied_carriers=occupied_carriers,
    #        pilot_carriers=pilot_carriers,
    #        pilot_symbols=pilot_symbols,
    #        debug=args.debug
    #)
    
    ofdm_framer0 = mimoots.ofdm_basebandsignal_to_frames_cvc(
            fft_len=fft_len,
            cp_len=cp_len,
            nofdm_symbols=args.nsymbols
    )
    ofdm_framer1 = mimoots.ofdm_basebandsignal_to_frames_cvc(
            fft_len=fft_len,
            cp_len=cp_len,
            nofdm_symbols=args.nsymbols
    )
    
    ofdm_symboler0 = mimoots.ofdm_frame_to_symbols_vcc(
            fft_len=fft_len,
            cp_len=cp_len,
            occupied_carriers=occupied_carriers,
            pilot_carriers=pilot_carriers,
            pilot_symbols=pilot_symbols,
            constellation=constellation[args.bits],
            nofdm_symbols=args.nsymbols,
            packet_len_tag=packet_len_tag
    )
    ofdm_symboler1 = mimoots.ofdm_frame_to_symbols_vcc(
            fft_len=fft_len,
            cp_len=cp_len,
            occupied_carriers=occupied_carriers,
            pilot_carriers=pilot_carriers,
            pilot_symbols=pilot_symbols,
            constellation=constellation[args.bits],
            nofdm_symbols=args.nsymbols,
            packet_len_tag=packet_len_tag
    )
    
    ofdm_demapper0 = mimoots.ofdm_symbol_demapper_cb(
            constellation=constellation[args.bits],
            packet_len_tag=packet_len_tag
    )
    ofdm_demapper1 = mimoots.ofdm_symbol_demapper_cb(
            constellation=constellation[args.bits],
            packet_len_tag=packet_len_tag
    )
    
    data_sink0 = blocks.vector_sink_b()
    data_sink1 = blocks.vector_sink_b()
    
    tb.connect((data_source, 0), skip0, ofdm_framer0, ofdm_symboler0, 
               ofdm_demapper0, data_sink0)
    tb.connect((data_source, 1), skip1, ofdm_framer1, ofdm_symboler1, 
               ofdm_demapper1, data_sink1)
    
    tb.run()
    
    random.seed(42)
    #data_expected = tuple(args.nframes*[random.randint(0,255) for x in xrange(args.bits*60)])
    
    
    data_len = utils.ofdm_get_data_len(
            nofdm_symbols=args.nsymbols,
            noccupied_carriers=len(occupied_carriers[0]),
            constellation=constellation[args.bits]
    )
    
    if args.dummy_frame == True:
        data_expected = [
                tuple(data_len*[0] + args.nframes*[1 for x in xrange(data_len)]),
                tuple(data_len*[0] + args.nframes*[2 for x in xrange(data_len)])
        ]
    else:
        data_expected = [
                tuple(args.nframes*[1 for x in xrange(data_len)]),
                tuple(args.nframes*[2 for x in xrange(data_len)])
        ]
    
    data = [data_sink0.data(), data_sink1.data()] 
    
    len_data = []
    len_data_expected = []
    ignored_correlations = []
    biterrors_complete = []
    biterrorrate_complete = []
    
    for data_index in range(2):
        biterror = 0
        index = 0
        for i,j in itertools.izip_longest(data[data_index], data_expected[data_index]):
            index += 1
            if i != j:
                if i is None or j is None:
                    biterror += 8
                else:
                    #print("Index: {} data: {} expected: {}".format(index, i, j))
                    biterror += bin(i^j).count("1")

        bits = args.bits
    
        len_data = len(data[data_index])
        len_data_expected = len(data_expected[data_index])
        ignored_correlations = (len(data_expected[data_index])-len(data[data_index]))/(args.bits*60)
        biterrors_complete = float(biterror)/float(8*len(data_expected[data_index]))
        biterrorrate_complete = float(biterror)/float(8*len(data_expected[data_index]))
    
        print '{}:len(data): {}'.format(data_index, len_data)
        print '{}:len(data_expected): {}'.format(data_index, len_data_expected)
        print '{}:Correlation didn\'t work: {} times'.format(data_index, ignored_correlations)
        print '{}:biterrors: {} biterrorrate: {}'.format(data_index, biterror, biterrorrate_complete)
        print "\n"
Пример #47
0
def main():
    args = get_arguments()
    constellation = {
            1:digital.constellation_bpsk(),
            2:digital.constellation_qpsk(),
            3:digital.constellation_8psk(),
    }

    packet_len_tag = "packet_length"
    fft_len = 64
    cp_len = 16
    
    occupied_carriers=(range(-26, -21) + range(-20, -7) +
                       range(-6, 0) + range(1, 7) +
                       range(8, 21) + range(22, 27),)
    pilot_carriers=((-21, -7, 7, 21),)
    pilot_symbols=tuple([(1, -1, 1, -1),])
    
    tb = gr.top_block()
    
    if args.freq == None:
        data_source = blocks.file_source(
                itemsize=gr.sizeof_gr_complex,
                filename=args.from_file
        )
        
    else:
        data_source = mimoots.uhd_source(freq=args.freq, gain=args.gain)
       
    skip = blocks.skiphead(
            itemsize=gr.sizeof_gr_complex,
            nitems_to_skip=args.skiphead
    )
    
    #ofdm_frames = mimoots.ofdm_receive_frames_cb(
    #        nofdm_frames=args.nframes,
    #        nofdm_symbols=args.nsymbols,
    #        constellation=constellation[args.bits],
    #        occupied_carriers=occupied_carriers,
    #        pilot_carriers=pilot_carriers,
    #        pilot_symbols=pilot_symbols,
    #        debug=args.debug
    #)
    
    ofdm_framer = mimoots.ofdm_basebandsignal_to_frames_cvc(
            fft_len=fft_len,
            cp_len=cp_len,
            nofdm_symbols=args.nsymbols
    )
    
    ofdm_symboler = mimoots.ofdm_frame_to_symbols_vcc(
            fft_len=fft_len,
            cp_len=cp_len,
            occupied_carriers=occupied_carriers,
            pilot_carriers=pilot_carriers,
            pilot_symbols=pilot_symbols,
            constellation=constellation[args.bits],
            nofdm_symbols=args.nsymbols,
            packet_len_tag=packet_len_tag
    );
    
    ofdm_demapper = mimoots.ofdm_symbol_demapper_cb(
            constellation=constellation[args.bits],
            packet_len_tag=packet_len_tag
    );
    
    data_sink = blocks.vector_sink_b()
    
    tb.connect(data_source, skip, ofdm_framer, ofdm_symboler, ofdm_demapper, data_sink)

    tb.run()
    
    random.seed(42)
    #data_expected = tuple(args.nframes*[random.randint(0,255) for x in xrange(args.bits*60)])
    
    
    data_len = utils.ofdm_get_data_len(
            nofdm_symbols=args.nsymbols,
            noccupied_carriers=len(occupied_carriers[0]),
            constellation=constellation[args.bits]
    )
    
    if args.dummy_frame == True:
        data_expected = tuple(data_len*[0] + args.nframes*[1 for x in xrange(data_len)])
    else:
        data_expected = tuple(args.nframes*[1 for x in xrange(data_len)])
    
    data = data_sink.data() 
   
    # TODO: args.bits*60=datalen, 60 depends on len of data_carriers
    len_data = []
    len_data_expected = []
    ignored_correlations = []
    biterrors_complete = []
    biterrorrate_complete = []
    
    biterror = 0
    index = 0
    for i,j in itertools.izip_longest(data, data_expected):
        index += 1
        if i != j:
            if i is None or j is None:
                biterror += 8
            else:
                #print("Index: {} data: {} expected: {}".format(index, i, j))
                biterror += bin(i^j).count("1")
                
    bits = args.bits
    
    len_data = len(data)
    len_data_expected = len(data_expected)
    ignored_correlations = (len(data_expected)-len(data))/(args.bits*60)
    biterrors_complete = float(biterror)/float(8*len(data_expected))
    biterrorrate_complete = float(biterror)/float(8*len(data_expected))
    
    print 'len(data): {}'.format(len_data)
    print 'len(data_expected): {}'.format(len_data_expected)
    print 'Correlation didn\'t work: {} times'.format(ignored_correlations)
    print 'biterrors: {} biterrorrate: {}'.format(biterror, biterrorrate_complete)
    def test_004_t(self):
        # set up fg
        M = 16
        syms_per_frame = 20
        num_frame = int(math.pow(2,10))
        indices = [3,6,10,14] # num_users = 2
        sel_preamble = 1 # standard one-vector preamble
        zero_pads = 4
        extra_pad = 1
        sel_eq = 1 # three-tap equalizer

        # prepare test data containers
        src_data = list()
        expected_result1 = list()   # expected res for user 1
        expected_result2 = list()   # expected res for user 2
        preamble = list()
        

        # prepare preamble
        if sel_preamble == 0: # standard one vector center preamble [1,-j,-1,j]
            center_preamble = [0, 0, -1, 1j,1, -1j, -1, 1j,0, -1j, -1, 1j,1, -1j, -1, 1j]
        elif sel_preamble == 1: # standard preamble with triple repetition
            tmp = [0, 0, -1, 1j,1, -1j, -1, 1j,0, -1j, -1, 1j,1, -1j, -1, 1j]
            center_preamble = tmp*3 #[1/math.sqrt(3), -1j/math.sqrt(3), -1/math.sqrt(3), 1j/math.sqrt(3)]*((int)(M/4))*3
        elif sel_preamble ==2: # IAM-R preamble [1, -1,-1, 1]
            center_preamble = [0, 0, -1, 1, 1, -1, -1, 1, 0, 0, -1, 1,1, -1, -1, 1]
        else: # standard one vector center preamble [1,-j,-1,j]
            center_preamble = [0, 0, -1, 1j,1, -1j, -1, 1j,0, -1j, -1, 1j,1, -1j, -1, 1j]

        preamble.extend([0]*zero_pads*M)
        preamble.extend(center_preamble)
        preamble.extend([0]*zero_pads*M)
        if extra_pad:
            preamble.extend([0]*M)

        # print len(preamble)

        # prepare test data
        for k in range(num_frame):
            # each frame will be multiplied by a random factor.
            factor = int(random.random()*10)+1
            tmp = [x*factor for x in preamble]
            src_data.extend(tmp)    # preamble is prepended.
            for l in range(2*syms_per_frame*M):
                if (l%M<3) or (l%M>14) or (l%M>6 and l%M<10):
                    src_data.extend([0])
                elif ((l%M>=3) and (l%M<=6)):
                    #belong to user1
                    data = int((random.random()*10+1)*abs(center_preamble[l%M]))
                    expected_result1.append(data)
                    src_data.append(data*factor)
                else:
                    # belong to user2
                    data = int((random.random()*10+1)*abs(center_preamble[l%M]))
                    expected_result2.append(data)
                    src_data.append(data*factor)

        src_data.extend([0]*M) # we add this in order to feed the system with samples till the last relevant sample is acquired.

        # print "src:"
        # for k in range((syms_per_frame*2+len(preamble)/M)*num_frame):
        #     print src_data[k*M:(k+1)*M]
        # # print str(len(src_data)-len(preamble)*num_frame)


        src = blocks.vector_source_c(src_data,vlen=M)
        scp = ofdm.fbmc_subchannel_processing_mu_vcvc(M=M,syms_per_frame=syms_per_frame,indices=indices,sel_preamble=sel_preamble,zero_pads=zero_pads,extra_pad=extra_pad,sel_eq=sel_eq)
        skh = blocks.skiphead(gr.sizeof_gr_complex*M, 1)
        rem = fbmc_remove_preamble_vcvc(M, syms_per_frame, sel_preamble, zero_pads, extra_pad)
        avm1 = ofdm.fbmc_asymmetrical_vector_mask_vcvc(M,3,6)
        avm2 = ofdm.fbmc_asymmetrical_vector_mask_vcvc(M,10,14)
        dst1 = blocks.vector_sink_c(vlen=4)
        dst2 = blocks.vector_sink_c(vlen=5)
        dst99 = blocks.vector_sink_c(vlen=M)

        self.tb.connect((src,0),(scp,0))
        self.tb.connect((scp,0),(skh,0))
        self.tb.connect((skh,0),(rem,0))
        self.tb.connect((rem,0),avm1)
        self.tb.connect((rem,0),avm2)
        self.tb.connect((avm1,0),dst1)
        self.tb.connect((avm2,0),dst2)

        # estimation probe is connected to dst99
        self.tb.connect((scp,1),dst99)
        self.tb.run ()
        # check data
        result_data1 = dst1.data()
        result_data2 = dst2.data()

        result_data99 = dst99.data()

        # print "res:"
        # for k in range(syms_per_frame*2*num_frame):
        #     print result_data1[k*4:(k+1)*4]

        # print "res99:"
        # for k in range(syms_per_frame*2*num_frame):
        #     print result_data99[k*M:(k+1)*M]
        # for i in range(len(result_data2)):
        #     print str(i)+"\t"+str(result_data2[i])
        # print result_data
        self.assertComplexTuplesAlmostEqual(expected_result1,result_data1,6)
        self.assertComplexTuplesAlmostEqual(expected_result2,result_data2,6)
Пример #49
0
    def __init__(self):
        grc_wxgui.top_block_gui.__init__(self, title="Top Block")
        _icon_path = "/usr/share/icons/hicolor/32x32/apps/gnuradio-grc.png"
        self.SetIcon(wx.Icon(_icon_path, wx.BITMAP_TYPE_ANY))

        ##################################################
        # Variables
        ##################################################
        self.symbol_rate = symbol_rate = 60000
        self.symbol_period = symbol_period = pow(symbol_rate,-1)
        self.samp_rate = samp_rate = 300e3
        self.samp_per_sym = samp_per_sym = 5
        self.packet_len = packet_len = 256
        self.decimation = decimation = 1
        self.bits_per_sym = bits_per_sym = 1
        self.Sq_Thresh = Sq_Thresh = -30
        self.RF_Gain = RF_Gain = 20
        self.Fc = Fc = 175e6

        ##################################################
        # Blocks
        ##################################################
        _Sq_Thresh_sizer = wx.BoxSizer(wx.VERTICAL)
        self._Sq_Thresh_text_box = forms.text_box(
        	parent=self.GetWin(),
        	sizer=_Sq_Thresh_sizer,
        	value=self.Sq_Thresh,
        	callback=self.set_Sq_Thresh,
        	label="Squelch Threshold",
        	converter=forms.float_converter(),
        	proportion=0,
        )
        self._Sq_Thresh_slider = forms.slider(
        	parent=self.GetWin(),
        	sizer=_Sq_Thresh_sizer,
        	value=self.Sq_Thresh,
        	callback=self.set_Sq_Thresh,
        	minimum=-50,
        	maximum=20,
        	num_steps=1000,
        	style=wx.SL_HORIZONTAL,
        	cast=float,
        	proportion=1,
        )
        self.GridAdd(_Sq_Thresh_sizer, 0, 2, 1, 1)
        _RF_Gain_sizer = wx.BoxSizer(wx.VERTICAL)
        self._RF_Gain_text_box = forms.text_box(
        	parent=self.GetWin(),
        	sizer=_RF_Gain_sizer,
        	value=self.RF_Gain,
        	callback=self.set_RF_Gain,
        	label="RF Gain",
        	converter=forms.float_converter(),
        	proportion=0,
        )
        self._RF_Gain_slider = forms.slider(
        	parent=self.GetWin(),
        	sizer=_RF_Gain_sizer,
        	value=self.RF_Gain,
        	callback=self.set_RF_Gain,
        	minimum=0,
        	maximum=50,
        	num_steps=1000,
        	style=wx.SL_HORIZONTAL,
        	cast=float,
        	proportion=1,
        )
        self.GridAdd(_RF_Gain_sizer, 0, 0, 1, 1)
        _Fc_sizer = wx.BoxSizer(wx.VERTICAL)
        self._Fc_text_box = forms.text_box(
        	parent=self.GetWin(),
        	sizer=_Fc_sizer,
        	value=self.Fc,
        	callback=self.set_Fc,
        	label="Center Frequency",
        	converter=forms.float_converter(),
        	proportion=0,
        )
        self._Fc_slider = forms.slider(
        	parent=self.GetWin(),
        	sizer=_Fc_sizer,
        	value=self.Fc,
        	callback=self.set_Fc,
        	minimum=50e6,
        	maximum=1700e6,
        	num_steps=1000,
        	style=wx.SL_HORIZONTAL,
        	cast=float,
        	proportion=1,
        )
        self.GridAdd(_Fc_sizer, 0, 1, 1, 1)
        self.osmosdr_source_0_0 = osmosdr.source( args="numchan=" + str(1) + " " + 'rtl_tcp=10.0.0.13:1234' )
        self.osmosdr_source_0_0.set_sample_rate(samp_rate)
        self.osmosdr_source_0_0.set_center_freq(Fc+10e6, 0)
        self.osmosdr_source_0_0.set_freq_corr(0, 0)
        self.osmosdr_source_0_0.set_dc_offset_mode(0, 0)
        self.osmosdr_source_0_0.set_iq_balance_mode(0, 0)
        self.osmosdr_source_0_0.set_gain_mode(False, 0)
        self.osmosdr_source_0_0.set_gain(RF_Gain, 0)
        self.osmosdr_source_0_0.set_if_gain(0, 0)
        self.osmosdr_source_0_0.set_bb_gain(0, 0)
        self.osmosdr_source_0_0.set_antenna("", 0)
        self.osmosdr_source_0_0.set_bandwidth(0, 0)
          
        self.osmosdr_source_0 = osmosdr.source( args="numchan=" + str(1) + " " + 'rtl_tcp=10.0.0.12:1234' )
        self.osmosdr_source_0.set_sample_rate(samp_rate)
        self.osmosdr_source_0.set_center_freq(Fc, 0)
        self.osmosdr_source_0.set_freq_corr(0, 0)
        self.osmosdr_source_0.set_dc_offset_mode(0, 0)
        self.osmosdr_source_0.set_iq_balance_mode(0, 0)
        self.osmosdr_source_0.set_gain_mode(False, 0)
        self.osmosdr_source_0.set_gain(0, 0)
        self.osmosdr_source_0.set_if_gain(0, 0)
        self.osmosdr_source_0.set_bb_gain(0, 0)
        self.osmosdr_source_0.set_antenna("", 0)
        self.osmosdr_source_0.set_bandwidth(0, 0)
          
        self.blocks_skiphead_0_0 = blocks.skiphead(gr.sizeof_gr_complex*1, int(samp_rate)*5)
        self.blocks_skiphead_0 = blocks.skiphead(gr.sizeof_gr_complex*1, int(samp_rate)*5)
        self.blocks_pack_k_bits_bb_0_0 = blocks.pack_k_bits_bb(8)
        self.blocks_pack_k_bits_bb_0 = blocks.pack_k_bits_bb(8)
        self.blocks_null_sink_0_0 = blocks.null_sink(gr.sizeof_float*1)
        self.blocks_null_sink_0 = blocks.null_sink(gr.sizeof_float*1)
        self.blocks_float_to_char_0_0 = blocks.float_to_char(1, 1)
        self.blocks_float_to_char_0 = blocks.float_to_char(1, 1)
        self.blks2_tcp_sink_0_0_0 = grc_blks2.tcp_sink(
        	itemsize=gr.sizeof_char*1,
        	addr="127.0.0.1",
        	port=3493,
        	server=True,
        )
        self.blks2_tcp_sink_0_0 = grc_blks2.tcp_sink(
        	itemsize=gr.sizeof_char*1,
        	addr="127.0.0.1",
        	port=3491,
        	server=True,
        )
        self.analog_pwr_squelch_xx_0_0 = analog.pwr_squelch_cc(Sq_Thresh, 0.01, 5, True)
        self.analog_pwr_squelch_xx_0 = analog.pwr_squelch_cc(-10, 0.01, 5, True)
        self.analog_fm_demod_cf_0_0 = analog.fm_demod_cf(
        	channel_rate=samp_rate,
        	audio_decim=decimation,
        	deviation=75e3,
        	audio_pass=120e3,
        	audio_stop=140e3,
        	gain=1.0,
        	tau=75e-6,
        )
        self.analog_fm_demod_cf_0 = analog.fm_demod_cf(
        	channel_rate=samp_rate,
        	audio_decim=decimation,
        	deviation=75e3,
        	audio_pass=120e3,
        	audio_stop=140e3,
        	gain=1.0,
        	tau=75e-6,
        )
        self.RPi_Rx_RPi_Rx_0_0 = RPi_Rx.RPi_Rx(bits_per_sym, samp_per_sym, packet_len, 65)
        self.RPi_Rx_RPi_Rx_0 = RPi_Rx.RPi_Rx(bits_per_sym, samp_per_sym, packet_len, 65)

        ##################################################
        # Connections
        ##################################################
        self.connect((self.analog_fm_demod_cf_0, 0), (self.RPi_Rx_RPi_Rx_0, 0))
        self.connect((self.RPi_Rx_RPi_Rx_0, 0), (self.blocks_null_sink_0, 0))
        self.connect((self.RPi_Rx_RPi_Rx_0, 0), (self.blocks_float_to_char_0, 0))
        self.connect((self.analog_pwr_squelch_xx_0, 0), (self.analog_fm_demod_cf_0, 0))
        self.connect((self.blocks_skiphead_0, 0), (self.analog_pwr_squelch_xx_0, 0))
        self.connect((self.osmosdr_source_0, 0), (self.blocks_skiphead_0, 0))
        self.connect((self.blocks_float_to_char_0, 0), (self.blocks_pack_k_bits_bb_0, 0))
        self.connect((self.blocks_pack_k_bits_bb_0, 0), (self.blks2_tcp_sink_0_0, 0))
        self.connect((self.blocks_float_to_char_0_0, 0), (self.blocks_pack_k_bits_bb_0_0, 0))
        self.connect((self.blocks_pack_k_bits_bb_0_0, 0), (self.blks2_tcp_sink_0_0_0, 0))
        self.connect((self.analog_fm_demod_cf_0_0, 0), (self.RPi_Rx_RPi_Rx_0_0, 0))
        self.connect((self.RPi_Rx_RPi_Rx_0_0, 0), (self.blocks_null_sink_0_0, 0))
        self.connect((self.RPi_Rx_RPi_Rx_0_0, 0), (self.blocks_float_to_char_0_0, 0))
        self.connect((self.analog_pwr_squelch_xx_0_0, 0), (self.analog_fm_demod_cf_0_0, 0))
        self.connect((self.blocks_skiphead_0_0, 0), (self.analog_pwr_squelch_xx_0_0, 0))
        self.connect((self.osmosdr_source_0_0, 0), (self.blocks_skiphead_0_0, 0))
    def __init__(self, M=1024, K=4, qam_size=16, syms_per_frame=10, boundaries=[], theta_sel=0, sel_eq=0, exclude_preamble=0, sel_preamble=0, zero_pads=1, extra_pad=False):
        # for now, following assumption should be made:
        # each user should be allocated with same number of subchannels.
        lb = len(boundaries)

        assert(lb>0), "The array that defines user boundaries cannot be passed as empty."
        assert(lb%2 == 0), "Unbalanced boundary definition."

        allocated = list()
        for i in range(1,(lb/2)+1):
            allocated.append(boundaries[2*i-1]-boundaries[2*i-2]+1)
            if i>=2:
                assert(allocated[i-2] == allocated[i-1]), "Each user should be allocated with same number of subchannels."

        output_signature = list()
        for i in range(lb/2):
            output_signature.append(gr.sizeof_gr_complex*(boundaries[2*i+1]-boundaries[2*i]+1))

        # print(output_signature)
        gr.hier_block2.__init__(self,
            "fbmc_receiver_multiuser_cb",
            gr.io_signature(1, 1, gr.sizeof_gr_complex*1),  # Input signature
            gr.io_signature(lb/2, lb/2, gr.sizeof_char*1))  # Output signature

        ##################################################
        # Parameters
        ##################################################
        self.theta_sel = theta_sel
        self.exclude_preamble = exclude_preamble
        self.sel_eq = sel_eq
        self.M = M
        self.K = K
        self.qam_size = qam_size
        self.syms_per_frame = syms_per_frame

        ##################################################
        # Variables
        ##################################################
        if self.exclude_preamble == 1 and self.sel_eq != 3:
            self.sel_eq = sel_eq = 3
            warnings.warn("Since exclude_preamble is set as 1, sel_eq is forced to be 3 (no equalizer)")

        self.skip = skip = 0
        if exclude_preamble == 1 or sel_eq == 3 or sel_eq== 0:
            self.skip = skip = 0
        else:
            self.skip = skip = 1

        # Assertions
        assert(M>0 and K>0 and qam_size>0), "M, K and qam_size should be bigger than 0"
        assert((math.log(M)/math.log(2))==int(math.log(M)/math.log(2))), "M should be a power of 2"
        assert(K==4), "for now only K=4 s supported."
        assert(qam_size==4 or qam_size==16 or qam_size==64 or qam_size==128 or qam_size==256 ), "Only 4-,16-,64-,128-,256-qam constellations are supported."
        assert(theta_sel==0 or theta_sel==1)
        assert(exclude_preamble==0 or exclude_preamble==1)
        


        ##################################################
        # Blocks
        ##################################################
        self.ofdm_fbmc_subchannel_processing_mu_vcvc_0 = ofdm.fbmc_subchannel_processing_mu_vcvc(M=M,syms_per_frame=syms_per_frame,indices=boundaries,sel_preamble=sel_preamble,zero_pads=zero_pads,extra_pad=extra_pad,sel_eq=sel_eq)
        self.ofdm_fbmc_separate_vcvc_0 = ofdm.fbmc_separate_vcvc(M, 2)
        self.ofdm_fbmc_remove_preamble_vcvc_0 = ofdm.fbmc_remove_preamble_vcvc(M, syms_per_frame, sel_preamble, zero_pads, extra_pad)
        self.ofdm_fbmc_polyphase_network_vcvc_3 = ofdm.fbmc_polyphase_network_vcvc(M, K, K*M-1, True)
        self.ofdm_fbmc_polyphase_network_vcvc_2 = ofdm.fbmc_polyphase_network_vcvc(M, K, K*M-1, True)
        self.ofdm_fbmc_overlapping_serial_to_parallel_cvc_0 = ofdm.fbmc_overlapping_serial_to_parallel_cvc(M)
        self.ofdm_fbmc_oqam_postprocessing_vcvc_0 = ofdm.fbmc_oqam_postprocessing_vcvc(M, 0, theta_sel)
        self.ofdm_fbmc_junction_vcvc_0 = ofdm.fbmc_junction_vcvc(M, 2)
        self.ofdm_fbmc_beta_multiplier_vcvc_1 = ofdm.fbmc_beta_multiplier_vcvc(M, K, K*M-1, 0)
        self.fft_vxx_1 = fft.fft_vcc(M, True, ([]), True, 1)
        self.blocks_skiphead_0_0 = blocks.skiphead(gr.sizeof_gr_complex*M, skip)
        self.blocks_skiphead_0 = blocks.skiphead(gr.sizeof_gr_complex*M, 2*K-1-1)
        self.blocks_null_sink_0 = blocks.null_sink(gr.sizeof_gr_complex*M)
        self.blks2_selector_0_0 = grc_blks2.selector(
            item_size=gr.sizeof_gr_complex*M,
            num_inputs=2,
            num_outputs=1,
            input_index=exclude_preamble,
            output_index=0,
        )

        ##################################################
        # Connections
        ##################################################
        self.connect((self.blks2_selector_0_0, 0), (self.ofdm_fbmc_oqam_postprocessing_vcvc_0, 0))
        self.connect((self.ofdm_fbmc_remove_preamble_vcvc_0, 0), (self.blks2_selector_0_0, 0))
        self.connect((self.blocks_skiphead_0_0, 0), (self.blks2_selector_0_0, 1))
        self.connect((self.blocks_skiphead_0_0, 0), (self.ofdm_fbmc_remove_preamble_vcvc_0, 0))
        self.connect((self.ofdm_fbmc_beta_multiplier_vcvc_1, 0), (self.blocks_skiphead_0, 0))
        self.connect((self.fft_vxx_1, 0), (self.ofdm_fbmc_beta_multiplier_vcvc_1, 0))
        self.connect((self.blocks_skiphead_0, 0), (self.ofdm_fbmc_subchannel_processing_mu_vcvc_0, 0))
        self.connect((self.ofdm_fbmc_junction_vcvc_0, 0), (self.fft_vxx_1, 0))
        self.connect((self.ofdm_fbmc_subchannel_processing_mu_vcvc_0, 1), (self.blocks_null_sink_0, 0))
        self.connect((self.ofdm_fbmc_subchannel_processing_mu_vcvc_0, 0), (self.blocks_skiphead_0_0, 0))
        self.connect((self, 0), (self.ofdm_fbmc_overlapping_serial_to_parallel_cvc_0, 0))
        self.connect((self.ofdm_fbmc_separate_vcvc_0, 0), (self.ofdm_fbmc_polyphase_network_vcvc_2, 0))
        self.connect((self.ofdm_fbmc_separate_vcvc_0, 1), (self.ofdm_fbmc_polyphase_network_vcvc_3, 0))
        self.connect((self.ofdm_fbmc_overlapping_serial_to_parallel_cvc_0, 0), (self.ofdm_fbmc_separate_vcvc_0, 0))
        self.connect((self.ofdm_fbmc_polyphase_network_vcvc_2, 0), (self.ofdm_fbmc_junction_vcvc_0, 0))
        self.connect((self.ofdm_fbmc_polyphase_network_vcvc_3, 0), (self.ofdm_fbmc_junction_vcvc_0, 1))
        # blocks
        # self.ofdm_fbmc_receiver_demo_0 = ofdm.fbmc_receiver_demo(M, K, qam_size, syms_per_frame, M, theta_sel, sel_eq, exclude_preamble, sel_preamble, zero_pads, extra_pad)
        # instead of calling receiver_demo block we copy the content of that block and change subchannel processing part. 10.03.2015
        # this way receiver_demo file will stay as original, multiuser case not implemented.




        asymms = list()
        for i in range(lb/2):
            asymms.append(ofdm.fbmc_asymmetrical_vector_mask_vcvc(M,boundaries[2*i],boundaries[2*i+1]))
            # print(str(i))

        sym_est = list()
        for i in range(lb/2):
            sym_est.append(ofdm.fbmc_symbol_estimation_vcb(allocated[i], qam_size))

        # connections
        for i in range(lb/2):
            self.connect((self.ofdm_fbmc_oqam_postprocessing_vcvc_0, 0), (asymms[i], 0))
            self.connect((asymms[i], 0),(sym_est[i], 0))
            self.connect((sym_est[i], 0),(self,i))
Пример #51
0
    def __init__(self, M=1024, K=4, qam_size=16, syms_per_frame=10, carriers=924, theta_sel=0, sel_eq=0, exclude_preamble=0, sel_preamble=0, zero_pads=1, extra_pad=False):
        gr.hier_block2.__init__(self,
            "fbmc_receiver_hier_cb",
            gr.io_signature(1, 1, gr.sizeof_gr_complex*1),
            gr.io_signature(1, 1, gr.sizeof_char*1),
        )

        ##################################################
        # Parameters
        ##################################################
        self.theta_sel = theta_sel
        self.exclude_preamble = exclude_preamble
        self.sel_eq = sel_eq
        self.M = M
        self.K = K
        self.qam_size = qam_size
        self.syms_per_frame = syms_per_frame

        ##################################################
        # Variables
        ##################################################
        if self.exclude_preamble == 1 and self.sel_eq != 3:
            self.sel_eq = sel_eq = 3
            warnings.warn("Since exclude_preamble is set as 1, sel_eq is forced to be 3 (no equalizer)")

        self.skip = skip = 0
        if exclude_preamble == 1 or sel_eq == 3 or sel_eq== 0:
            self.skip = skip = 0
        else:
            self.skip = skip = 1

        # Assertions
        assert(M>0 and K>0 and qam_size>0), "M, K and qam_size should be bigger than 0"
        assert((math.log(M)/math.log(2))==int(math.log(M)/math.log(2))), "M should be a power of 2"
        assert(K==4), "for now only K=4 s supported."
        assert(qam_size==4 or qam_size==16 or qam_size==64 or qam_size==128 or qam_size==256 ), "Only 4-,16-,64-,128-,256-qam constellations are supported."
        assert(theta_sel==0 or theta_sel==1)
        assert(exclude_preamble==0 or exclude_preamble==1)
        


        ##################################################
        # Blocks
        ##################################################
        self.ofdm_vector_mask_0 = ofdm.vector_mask(M, (M-carriers)/2, carriers, [])
        self.ofdm_fbmc_symbol_estimation_vcb_0 = ofdm.fbmc_symbol_estimation_vcb(carriers, qam_size)
        # unsigned int M, unsigned int syms_per_frame, int sel_preamble, int zero_pads, bool extra_pad, int sel_eq
        self.ofdm_fbmc_subchannel_processing_vcvc_0 = ofdm.fbmc_subchannel_processing_vcvc(M, syms_per_frame, sel_preamble, zero_pads, extra_pad, sel_eq)
        self.ofdm_fbmc_separate_vcvc_0 = ofdm.fbmc_separate_vcvc(M, 2)
        self.ofdm_fbmc_remove_preamble_vcvc_0 = ofdm.fbmc_remove_preamble_vcvc(M, syms_per_frame, sel_preamble, zero_pads, extra_pad)
        self.ofdm_fbmc_polyphase_network_vcvc_3 = ofdm.fbmc_polyphase_network_vcvc(M, K, K*M-1, True)
        self.ofdm_fbmc_polyphase_network_vcvc_2 = ofdm.fbmc_polyphase_network_vcvc(M, K, K*M-1, True)
        self.ofdm_fbmc_overlapping_serial_to_parallel_cvc_0 = ofdm.fbmc_overlapping_serial_to_parallel_cvc(M)
        self.ofdm_fbmc_oqam_postprocessing_vcvc_0 = ofdm.fbmc_oqam_postprocessing_vcvc(M, 0, theta_sel)
        self.ofdm_fbmc_junction_vcvc_0 = ofdm.fbmc_junction_vcvc(M, 2)
        self.ofdm_fbmc_beta_multiplier_vcvc_1 = ofdm.fbmc_beta_multiplier_vcvc(M, K, K*M-1, 0)
        self.fft_vxx_1 = fft.fft_vcc(M, True, ([]), True, 1)
        self.blocks_skiphead_0_0 = blocks.skiphead(gr.sizeof_gr_complex*M, skip)
        self.blocks_skiphead_0 = blocks.skiphead(gr.sizeof_gr_complex*M, 2*K-1-1)
        self.blocks_null_sink_0 = blocks.null_sink(gr.sizeof_gr_complex*M)
        self.blks2_selector_0_0 = grc_blks2.selector(
            item_size=gr.sizeof_gr_complex*M,
            num_inputs=2,
            num_outputs=1,
            input_index=exclude_preamble,
            output_index=0,
        )

        ##################################################
        # Connections
        ##################################################
        self.connect((self.blks2_selector_0_0, 0), (self.ofdm_fbmc_oqam_postprocessing_vcvc_0, 0))
        self.connect((self.ofdm_fbmc_remove_preamble_vcvc_0, 0), (self.blks2_selector_0_0, 0))
        self.connect((self.blocks_skiphead_0_0, 0), (self.blks2_selector_0_0, 1))
        self.connect((self.blocks_skiphead_0_0, 0), (self.ofdm_fbmc_remove_preamble_vcvc_0, 0))
        self.connect((self.ofdm_fbmc_beta_multiplier_vcvc_1, 0), (self.blocks_skiphead_0, 0))
        self.connect((self.fft_vxx_1, 0), (self.ofdm_fbmc_beta_multiplier_vcvc_1, 0))
        self.connect((self.blocks_skiphead_0, 0), (self.ofdm_fbmc_subchannel_processing_vcvc_0, 0))
        self.connect((self.ofdm_fbmc_junction_vcvc_0, 0), (self.fft_vxx_1, 0))
        self.connect((self.ofdm_fbmc_symbol_estimation_vcb_0, 0), (self, 0))
        self.connect((self.ofdm_fbmc_subchannel_processing_vcvc_0, 1), (self.blocks_null_sink_0, 0))
        self.connect((self.ofdm_vector_mask_0, 0), (self.ofdm_fbmc_symbol_estimation_vcb_0, 0))
        self.connect((self.ofdm_fbmc_oqam_postprocessing_vcvc_0, 0), (self.ofdm_vector_mask_0, 0))
        self.connect((self.ofdm_fbmc_subchannel_processing_vcvc_0, 0), (self.blocks_skiphead_0_0, 0))
        self.connect((self, 0), (self.ofdm_fbmc_overlapping_serial_to_parallel_cvc_0, 0))
        self.connect((self.ofdm_fbmc_separate_vcvc_0, 0), (self.ofdm_fbmc_polyphase_network_vcvc_2, 0))
        self.connect((self.ofdm_fbmc_separate_vcvc_0, 1), (self.ofdm_fbmc_polyphase_network_vcvc_3, 0))
        self.connect((self.ofdm_fbmc_overlapping_serial_to_parallel_cvc_0, 0), (self.ofdm_fbmc_separate_vcvc_0, 0))
        self.connect((self.ofdm_fbmc_polyphase_network_vcvc_2, 0), (self.ofdm_fbmc_junction_vcvc_0, 0))
        self.connect((self.ofdm_fbmc_polyphase_network_vcvc_3, 0), (self.ofdm_fbmc_junction_vcvc_0, 1))
Пример #52
0
    def __init__(self, storageval):
        gr.top_block.__init__(self, "Top Block")

        ##################################################
        # Variables
        ##################################################
        self.samp_rate = samp_rate = 192000
        self.pulse_width = pulse_width = 0.07
        self.pseudo_frequency = pseudo_frequency = 1
        self.fft_size = fft_size = 1024
        self.blocksize = blocksize = int(samp_rate / fft_size * pseudo_frequency *1.0 / (1.0 / pulse_width))  / 2
        self.timeout_blocks = timeout_blocks = int(samp_rate/fft_size * 1.0/blocksize)
        self.target_freq = target_freq = 457000
        self.measure = measure = 0
        self.firdes_tap = firdes_tap = firdes.low_pass(1, samp_rate, 500, 1000, firdes.WIN_HAMMING, 6.76)
        self.base_freq = base_freq = 450000
        self.burst_trigger = burst_trigger = 0.75
        self.storageval = storageval

        ##################################################
        # Blocks
        ##################################################
        self.probe = blocks.probe_signal_f()
        self.stbpilot_signal_level_0 = stbpilot.signal_level(6, timeout_blocks)
        def _measure_probe():
            while True:
                val = self.probe.level()
                try:
                    self.set_measure(val)
                    self.storageval.value = val
                except AttributeError:
                    pass
                time.sleep(1.0 / (1))
        _measure_thread = threading.Thread(target=_measure_probe)
        _measure_thread.daemon = True
        _measure_thread.start()
        self.freq_xlating_fir_filter_xxx_0 = filter.freq_xlating_fir_filter_ccc(1, (firdes_tap), -(base_freq - target_freq), samp_rate)
        self.fft_vxx_0 = fft.fft_vcc(fft_size, True, (), True, 1)
        self.fcdproplus_fcdproplus_0 = fcdproplus.fcdproplus("",1)
        self.fcdproplus_fcdproplus_0.set_lna(1)
        self.fcdproplus_fcdproplus_0.set_mixer_gain(1)
        self.fcdproplus_fcdproplus_0.set_if_gain(0)
        self.fcdproplus_fcdproplus_0.set_freq_corr(0)
        self.fcdproplus_fcdproplus_0.set_freq(base_freq)
          
        self.blocks_vector_to_stream_0 = blocks.vector_to_stream(gr.sizeof_gr_complex*1, fft_size)
        self.blocks_threshold_ff_0 = blocks.threshold_ff(burst_trigger, burst_trigger, 0)
        self.blocks_stream_to_vector_0 = blocks.stream_to_vector(gr.sizeof_gr_complex*1, fft_size)
        self.blocks_skiphead_0 = blocks.skiphead(gr.sizeof_float*1, (int(target_freq*1.0*fft_size/samp_rate)+1)*0+513)
        self.blocks_multiply_xx_0 = blocks.multiply_vff(1)
        self.blocks_keep_one_in_n_1 = blocks.keep_one_in_n(gr.sizeof_float*1, fft_size)
        self.blocks_complex_to_mag_0 = blocks.complex_to_mag(1)

        ##################################################
        # Connections
        ##################################################
        self.connect((self.fft_vxx_0, 0), (self.blocks_vector_to_stream_0, 0))
        self.connect((self.blocks_stream_to_vector_0, 0), (self.fft_vxx_0, 0))
        self.connect((self.blocks_vector_to_stream_0, 0), (self.blocks_complex_to_mag_0, 0))
        self.connect((self.fcdproplus_fcdproplus_0, 0), (self.freq_xlating_fir_filter_xxx_0, 0))
        self.connect((self.freq_xlating_fir_filter_xxx_0, 0), (self.blocks_stream_to_vector_0, 0))
        self.connect((self.blocks_keep_one_in_n_1, 0), (self.blocks_threshold_ff_0, 0))
        self.connect((self.blocks_threshold_ff_0, 0), (self.blocks_multiply_xx_0, 0))
        self.connect((self.blocks_keep_one_in_n_1, 0), (self.blocks_multiply_xx_0, 1))
        self.connect((self.blocks_complex_to_mag_0, 0), (self.blocks_skiphead_0, 0))
        self.connect((self.blocks_skiphead_0, 0), (self.blocks_keep_one_in_n_1, 0))
        self.connect((self.blocks_multiply_xx_0, 0), (self.stbpilot_signal_level_0, 0))
        self.connect((self.stbpilot_signal_level_0, 0), (self.probe, 0))
Пример #53
0
  def __init__( self, options, log = False ):
    
    ## Read configuration
    config = station_configuration()
    
    fft_length    = config.fft_length
    #cp_length     = config.cp_length
    block_header  = config.training_data
    data_subc     = config.data_subcarriers
    virtual_subc  = config.virtual_subcarriers
    total_subc    = config.subcarriers
    block_length  = config.block_length
    frame_length  = config.frame_length
    
    L             = block_header.mm_periodic_parts
    
        
    cp_length     = config.cp_length


    
    print "data_subc: ", config.data_subcarriers
    print "total_subc: ", config.subcarriers
    print "frame_lengthframe_length: ", frame_length
    
    
    ## Set Input/Output signature
    gr.hier_block2.__init__( self, 
        "fbmc_inner_receiver",
        gr.io_signature(
            1, 1,
            gr.sizeof_gr_complex ),
        gr.io_signaturev(
            4, 4,
            [gr.sizeof_float * total_subc,    # Normalized |CTF|^2 
            gr.sizeof_char,                       # Frame start
            gr.sizeof_gr_complex * total_subc, # OFDM blocks, SNR est
            gr.sizeof_float] ) )      # CFO
    
    
    ## Input and output ports
    self.input = rx_input = self
    
    out_ofdm_blocks = ( self, 2 )
    out_frame_start = ( self, 1 )
    out_disp_ctf    = ( self, 0 )
    out_disp_cfo    = ( self, 3 )
    #out_snr_pream    = ( self, 3 )
    
    
    
    
    ## pre-FFT processing
    
    '''
    ## Compute autocorrelations for S&C preamble
    ## and cyclic prefix
    
    self._sc_metric = sc_metric = autocorrelator( fft_length/2, fft_length/2 )
    self._gi_metric = gi_metric = autocorrelator( fft_length, cp_length )
    
    self.connect( rx_input, sc_metric )
    self.connect( rx_input, gi_metric )
    terminate_stream(self, gi_metric)
    
    ## Sync. Output contains OFDM blocks
    sync = ofdm.time_sync( fft_length/2, 1)
    self.connect( rx_input, ( sync, 0 ) )
    self.connect( sc_metric, ( sync, 1 ) )
    self.connect( sc_metric, ( sync, 2 ) )
    
    ofdm_blocks = ( sync, 0 )
    frame_start = ( sync, 1 )
    log_to_file( self, ( sync, 1 ), "data/fbmc_peak_detector.char" )
    '''
    if options.ideal is False and options.ideal2 is False:
        #Testing old/new metric
        self.tm = schmidl.recursive_timing_metric(2*fft_length)
        self.connect( self.input, self.tm)
        #log_to_file( self, self.tm, "data/fbmc_rec_sc_metric_ofdm.float" )
        
        timingmetric_shift = 0 #-2 #int(-cp_length * 0.8)
        tmfilter = filter.fft_filter_fff(1, [2./fft_length]*(fft_length/2))# ofdm.lms_fir_ff( fft_length, 1e-3 ) #; filter.fir_filter_fff(1, [1./fft_length]*fft_length)
        self.connect( self.tm, tmfilter )
        self.tm = tmfilter
        #log_to_file( self, self.tm, "data/fbmc_rec_sc_metric_ofdm2.float" )
        
        self._pd_thres = 0.6
        self._pd_lookahead = fft_length # empirically chosen
        peak_detector = ofdm.peak_detector_02_fb(self._pd_lookahead, self._pd_thres)
        self.connect(self.tm, peak_detector)
        #log_to_file( self, peak_detector, "data/fbmc_rec_peak_detector.char" )
        
        
        #frame_start = [0]*frame_length
        #frame_start[0] = 1
        #frame_start = blocks.vector_source_b(frame_start,True)
        
        #OLD
        #delayed_timesync = blocks.delay(gr.sizeof_char,
         #                           (frame_length-10)*fft_length/2 - fft_length/4 -1 + timingmetric_shift)
        delayed_timesync = blocks.delay(gr.sizeof_char,
                                    (frame_length-10)*fft_length/2 - fft_length/4  + int(2.5*fft_length)  + timingmetric_shift-1)
        #delayed_timesync = blocks.delay(gr.sizeof_char,
                                    #(frame_length-10)*fft_length/2 - fft_length/4 + int(3.5*fft_length)  + timingmetric_shift-1)
        self.connect( peak_detector, delayed_timesync )
        
        self.block_sampler = ofdm.vector_sampler(gr.sizeof_gr_complex,fft_length/2*frame_length)
        
        self.connect(self.input,self.block_sampler)
        self.connect(delayed_timesync,(self.block_sampler,1))
        #log_to_file( self, self.block_sampler, "data/fbmc_block_sampler.compl" )
        
        vt2s = blocks.vector_to_stream(gr.sizeof_gr_complex*fft_length,
                                                frame_length/2)
        self.connect(self.block_sampler,vt2s)
        #terminate_stream(self,ofdm_blocks)
        
        ofdm_blocks = vt2s
        
        '''
        # TODO: dynamic solution
        vt2s = blocks.vector_to_stream(gr.sizeof_gr_complex*block_length/2,
                                                frame_length)
        self.connect(self.block_sampler,vt2s)
        terminate_stream(self,( sync, 0 ))
        ofdm_blocks = vt2s
        '''
        
        
        
        
        
        ##stv_help = blocks.stream_to_vector(gr.sizeof_gr_complex*config.fft_length/2, 1)
        #stv_help = blocks.vector_to_stream(gr.sizeof_gr_complex*config.fft_length/2, 2)
       ##self.connect(ofdm_blocks, stv_help)
        ##ofdm_blocks = stv_help
        #ofdm_blocks = ( sync, 0 )
        #frame_start = ( sync, 1 )
        #log_to_file(self, frame_start, "data/frame_start.compl")
        
        #log_to_file( self, sc_metric, "data/sc_metric.float" )
        #log_to_file( self, gi_metric, "data/gi_metric.float" )
        #log_to_file( self, (sync,1), "data/sync.float" )
        
    #    log_to_file(self,ofdm_blocks,"data/ofdm_blocks_original.compl")
        frame_start = [0]*int(frame_length/2)
        frame_start[0] = 1
        frame_start = blocks.vector_source_b(frame_start,True)          
        
        #frame_start2 = [0]*int(frame_length/2)
        #frame_start2[0] = 1
        #frame_start2 = blocks.vector_source_b(frame_start2,True)
    
    if options.disable_time_sync or options.ideal or options.ideal2:
      if options.ideal is False and options.ideal2 is False:
        terminate_stream(self, ofdm_blocks)
        terminate_stream(self, frame_start)
      
      serial_to_parallel = blocks.stream_to_vector(gr.sizeof_gr_complex,fft_length)
      #discard_cp = ofdm.vector_mask(block_length,cp_length,fft_length,[])
      #serial_to_parallel = blocks.stream_to_vector(gr.sizeof_gr_complex,block_length)
      #discard_cp = ofdm.vector_mask(block_length,cp_length,fft_length,[])
      #self.connect( rx_input,serial_to_parallel)
      
      #self.connect( rx_input, blocks.delay(gr.sizeof_gr_complex,0),serial_to_parallel)
      initial_skip = blocks.skiphead(gr.sizeof_gr_complex,2*fft_length)
      self.connect( rx_input, initial_skip)
      if options.ideal is False and options.ideal2 is False:          
          self.connect(  initial_skip, serial_to_parallel)
          ofdm_blocks = serial_to_parallel
      else:
          ofdm_blocks = initial_skip
      #self.connect( rx_input, serial_to_parallel, discard_cp )
      
      frame_start = [0]*int(frame_length/2)
      frame_start[0] = 1
      frame_start = blocks.vector_source_b(frame_start,True)
      
      #frame_start2 = [0]*int(frame_length/2)
      #frame_start2[0] = 1
      #frame_start2 = blocks.vector_source_b(frame_start2,True)
      
      print "Disabled time synchronization stage"
    
    print"\t\t\t\t\tframe_length = ",frame_length
    
    if options.ideal is False and options.ideal2 is False:
        ## Extract preamble, feed to Morelli & Mengali frequency offset estimator
        assert( block_header.mm_preamble_pos == 0 )
        morelli_foe = ofdm.mm_frequency_estimator( fft_length, 2, 1, config.fbmc )
        sampler_preamble = ofdm.vector_sampler( gr.sizeof_gr_complex * fft_length,
                                                1 )
        self.connect( ofdm_blocks, ( sampler_preamble, 0 ) )
        self.connect( frame_start, blocks.delay( gr.sizeof_char, 1 ), ( sampler_preamble, 1 ) )
        self.connect( sampler_preamble, morelli_foe )
        freq_offset = morelli_foe
        print "FRAME_LENGTH: ", frame_length
        #log_to_file( self, sampler_preamble, "data/sampler_preamble.compl" )
        #log_to_file( self, rx_input, "data/rx_input.compl" )
        #log_to_file( self, ofdm_blocks, "data/rx_input.compl" )

        
        #Extracting preamble for SNR estimation
        #fft_snr_est = fft_blocks.fft_vcc( fft_length, True, [], True )
        #self.connect( sampler_preamble, blocks.stream_to_vector(gr.sizeof_gr_complex*fft_length/2, 2),  fft_snr_est )
        
        
        ## Remove virtual subcarriers
        #if fft_length > data_subc:
          #subcarrier_mask_snr_est = ofdm.vector_mask( fft_length, virtual_subc/2,
                        #                       total_subc, [] )
          #self.connect( fft_snr_est, subcarrier_mask_snr_est )
          #fft_snr_est = subcarrier_mask_snr_est
          #log_to_file(self, ofdm_blocks, "data/vec_mask.compl")
           ## Least Squares estimator for channel transfer function (CTF)
        
        #self.connect( fft_snr_est, out_snr_pream ) # Connecting to output
        
        ## Adaptive LMS FIR filtering of frequency offset
        lms_fir = ofdm.lms_fir_ff( 20, 1e-3 ) # TODO: verify parameter choice
        self.connect( freq_offset, lms_fir )
        freq_offset = lms_fir
        
        self.connect(freq_offset, blocks.keep_one_in_n(gr.sizeof_float,20) ,out_disp_cfo)
    else:
        self.connect(blocks.vector_source_f ([1]) ,out_disp_cfo)

    
    #log_to_file(self, lms_fir, "data/lms_fir.float")
    
    if options.disable_freq_sync or options.ideal or options.ideal2:
      if options.ideal is False and options.ideal2 is False:  
          terminate_stream(self, freq_offset)
          freq_offset = blocks.vector_source_f([0.0],True)
      print "Disabled frequency synchronization stage"
    
    if options.ideal is False and options.ideal2 is False:
        ## Correct frequency shift, feed-forward structure
        frequency_shift = ofdm.frequency_shift_vcc( fft_length, -1.0/fft_length,
                                                    0)
        
        #freq_shift = blocks.multiply_cc()
        #norm_freq = -0.1 / config.fft_length
        #freq_off = self.freq_off_src = analog.sig_source_c(1.0, analog.GR_SIN_WAVE, norm_freq, 1.0, 0.0 )
        
        self.connect( ofdm_blocks, ( frequency_shift, 0 ) )
        self.connect( freq_offset, ( frequency_shift, 1 ) )
        self.connect( frame_start,blocks.delay( gr.sizeof_char, 0), ( frequency_shift, 2 ) )
        
        

        
        #self.connect(frequency_shift,s2help)
        #ofdm_blocks = s2help
        ofdm_blocks = frequency_shift
    #terminate_stream(self, frequency_shift)
    
    
    
    #inner_pb_filt = self._inner_pilot_block_filter = fbmc_inner_pilot_block_filter()
    #self.connect(ofdm_blocks,inner_pb_filt)
    #self.connect(frame_start,(inner_pb_filt,1))
    #self.connect((inner_pb_filt,1),blocks.null_sink(gr.sizeof_char))
    
    #ofdm_blocks = (inner_pb_filt,0)
    
    
    overlap_ser_to_par = ofdm.fbmc_overlapping_serial_to_parallel_cvc(fft_length)
    self.separate_vcvc = ofdm.fbmc_separate_vcvc(fft_length, 2)
    self.polyphase_network_vcvc_1 = ofdm.fbmc_polyphase_network_vcvc(fft_length, 4, 4*fft_length-1, True)
    self.polyphase_network_vcvc_2 = ofdm.fbmc_polyphase_network_vcvc(fft_length, 4, 4*fft_length-1, True)
    self.junction_vcvc = ofdm.fbmc_junction_vcvc(fft_length, 2)
    self.fft_fbmc = fft_blocks.fft_vcc(fft_length, True, [], True)
    
    print "config.training_data.fbmc_no_preambles: ", config.training_data.fbmc_no_preambles
    #center_preamble = [1, -1j, -1, 1j]
    
    #self.preamble = preamble = [0]*total_subc + center_preamble*((int)(total_subc/len(center_preamble)))+[0]*total_subc
    
    self.preamble = preamble = config.training_data.fbmc_pilotsym_fd_list
    #inv_preamble = 1. / numpy.array(self.preamble)
    #print "self.preamble: ", len(self.preamble
    #print "inv_preamble: ", list(inv_preamble)
    
    #print "self.preamble", self.preamble
    #print "self.preamble2", self.preamble2
    
    
    self.multiply_const= ofdm.multiply_const_vcc(([1.0/(math.sqrt(fft_length*0.6863))]*total_subc))    
    self.beta_multiplier_vcvc = ofdm.fbmc_beta_multiplier_vcvc(total_subc, 4, 4*fft_length-1, 0)
    #self.skiphead = blocks.skiphead(gr.sizeof_gr_complex*total_subc, 2*4-1-1)
    self.skiphead = blocks.skiphead(gr.sizeof_gr_complex*total_subc,2)
    self.skiphead_1 = blocks.skiphead(gr.sizeof_gr_complex*total_subc, 0)
    #self.remove_preamble_vcvc = ofdm.fbmc_remove_preamble_vcvc(total_subc, config.frame_data_part/2, config.training_data.fbmc_no_preambles*total_subc/2)
    #self.subchannel_processing_vcvc = ofdm.fbmc_subchannel_processing_vcvc(total_subc, config.frame_data_part, 1, 2, 1, 0)
    self.oqam_postprocessing_vcvc = ofdm.fbmc_oqam_postprocessing_vcvc(total_subc, 0, 0)
    
    #log_to_file( self, ofdm_blocks, "data/PRE_FBMC.compl" )
    #log_to_file( self, self.fft_fbmc, "data/FFT_FBMC.compl" )

    if options.ideal is False and options.ideal2 is False:
        self.subchannel_processing_vcvc = ofdm.fbmc_subchannel_processing_vcvc(total_subc, config.frame_data_part, 3, 2, 1, 0)
        help2 = blocks.keep_one_in_n(gr.sizeof_gr_complex*total_subc,frame_length)
        self.connect ((self.subchannel_processing_vcvc,1),help2)
        #log_to_file( self, self.subchannel_processing_vcvc, "data/fbmc_subc.compl" )

    
    #terminate_stream(self, help2)
    
    if options.ideal is False and options.ideal2 is False:
        self.connect(ofdm_blocks, blocks.vector_to_stream(gr.sizeof_gr_complex, fft_length),overlap_ser_to_par)
    else:
        self.connect(ofdm_blocks,overlap_ser_to_par)
        
    self.connect(overlap_ser_to_par, self.separate_vcvc)
    self.connect((self.separate_vcvc, 1), (self.polyphase_network_vcvc_2, 0))
    self.connect((self.separate_vcvc, 0), (self.polyphase_network_vcvc_1, 0))
    self.connect((self.polyphase_network_vcvc_1, 0), (self.junction_vcvc, 0))
    self.connect((self.polyphase_network_vcvc_2, 0), (self.junction_vcvc, 1))
    self.connect(self.junction_vcvc, self.fft_fbmc)
    
    ofdm_blocks = self.fft_fbmc
    print "config.dc_null: ", config.dc_null
    if fft_length > data_subc:
      subcarrier_mask_fbmc = ofdm.vector_mask_dc_null( fft_length, virtual_subc/2,
                                           total_subc, config.dc_null, [] )
      self.connect( ofdm_blocks, subcarrier_mask_fbmc )
      ofdm_blocks = subcarrier_mask_fbmc
      #log_to_file(self, ofdm_blocks, "data/vec_mask.compl")
       ## Least Squares estimator for channel transfer function (CTF)
      #log_to_file( self, subcarrier_mask, "data/OFDM_Blocks.compl" )
      
    
    self.connect(ofdm_blocks, self.beta_multiplier_vcvc)
    
    ofdm_blocks = self.beta_multiplier_vcvc
    #self.connect(ofdm_blocks,self.multiply_const)
    #self.connect(self.multiply_const, (self.skiphead, 0))
    
    self.connect(ofdm_blocks, (self.skiphead, 0))
    #log_to_file( self, self.skiphead, "data/fbmc_skiphead_4.compl" )
    
    
    #self.connect(ofdm_blocks, self.multiply_const)
    #self.connect(self.multiply_const, self.beta_multiplier_vcvc)
    #self.connect((self.beta_multiplier_vcvc, 0), (self.skiphead, 0))
    if options.ideal or options.ideal2:
        self.connect((self.skiphead, 0),(self.skiphead_1, 0))
    else:
        self.connect((self.skiphead, 0), (self.subchannel_processing_vcvc, 0))
        self.connect((self.subchannel_processing_vcvc, 0), (self.skiphead_1, 0))
        
    #log_to_file( self, self.skiphead, "data/fbmc_subc.compl" )    
    #self.connect((self.skiphead_1, 0),(self.remove_preamble_vcvc, 0))
    #self.connect((self.remove_preamble_vcvc, 0),  (self.oqam_postprocessing_vcvc, 0))
    
    #ofdm_blocks = self.oqam_postprocessing_vcvc
    #log_to_file( self, self.subchannel_processing_vcvc, "data/subc_0.compl" )
    #log_to_file( self, (self.subchannel_processing_vcvc,1), "data/subc_1.compl" )
    
    
    
    self.connect((self.skiphead_1, 0),(self.oqam_postprocessing_vcvc, 0))
    #self.connect((self.oqam_postprocessing_vcvc, 0), (self.remove_preamble_vcvc, 0) )
    
    ofdm_blocks = (self.oqam_postprocessing_vcvc, 0)#(self.remove_preamble_vcvc, 0)
    #log_to_file( self, (self.oqam_postprocessing_vcvc, 0), "data/fbmc_before_remove.compl" )
    
    #log_to_file( self, self.skiphead, "data/SKIP_HEAD_FBMC.compl" )
    #log_to_file( self, self.beta_multiplier_vcvc, "data/BETA_REC_FBMC.compl" )
    #log_to_file( self, self.oqam_postprocessing_vcvc, "data/REC_OUT_FBMC.compl" )
        
    

    
    
    
    
    
    """ DISABLED OFDM CHANNEL ESTIMATION PREMBLE -> CORRECT LATER to compare FBMC and OFDM channel estimation
    #TAKING THE CHANNEL ESTIMATION PREAMBLE
    chest_pre_trigger = blocks.delay( gr.sizeof_char, 3 )
    sampled_chest_preamble = ofdm.vector_sampler( gr.sizeof_gr_complex * fft_length/2, 2 )
      
    self.connect( frame_start,       chest_pre_trigger )
    self.connect( chest_pre_trigger, ( sampled_chest_preamble, 1 ) )
    self.connect( frequency_shift,       ( sampled_chest_preamble, 0 ) )
    #ofdm_blocks = sampled_chest_preamble
    
        
    ## FFT
    fft = fft_blocks.fft_vcc( fft_length, True, [], True )
    self.connect( sampled_chest_preamble, fft )
    ofdm_blocks_est = fft
    log_to_file( self, sampled_chest_preamble, "data/SAMPLED_EST_PREAMBLE.compl" )
    log_to_file( self, ofdm_blocks_est, "data/FFT.compl" )
    
    
    ## Remove virtual subcarriers
    if fft_length > data_subc:
      subcarrier_mask = ofdm.vector_mask( fft_length, virtual_subc/2,
                                           total_subc, [] )
      self.connect( ofdm_blocks_est, subcarrier_mask )
      ofdm_blocks_est = subcarrier_mask
      #log_to_file(self, ofdm_blocks, "data/vec_mask.compl")
       ## Least Squares estimator for channel transfer function (CTF)
      log_to_file( self, subcarrier_mask, "data/OFDM_Blocks.compl" )
    
          
    ## post-FFT processing
      
    
    
    ## extract channel estimation preamble from frame
    ##chest_pre_trigger = blocks.delay( gr.sizeof_char, 
                                  ##1 )
    ##sampled_chest_preamble = \
     ## ofdm.vector_sampler( gr.sizeof_gr_complex * total_subc, 1 )
    ##self.connect( frame_start,       chest_pre_trigger )
    ##self.connect( chest_pre_trigger, ( sampled_chest_preamble, 1 ) )
    ##self.connect( ofdm_blocks,       ( sampled_chest_preamble, 0 ) )
    

    
    ## Least Squares estimator for channel transfer function (CTF)
    inv_preamble_fd = numpy.array( block_header.pilotsym_fd[ 
        block_header.channel_estimation_pilot[0] ] )
    #print "Channel estimation pilot: ", inv_preamble_fd
    inv_preamble_fd = 1. / inv_preamble_fd
    
    LS_channel_estimator = ofdm.multiply_const_vcc( list( inv_preamble_fd ) )
    self.connect( ofdm_blocks_est, LS_channel_estimator )
    estimated_CTF = LS_channel_estimator
    terminate_stream(self,estimated_CTF)
    """
    if options.ideal is False and options.ideal2 is False:
        if options.logcir:
         log_to_file( self, sampled_chest_preamble, "data/PREAM.compl" )
     
    
        if not options.disable_ctf_enhancer:
      
      
            if options.logcir:
                ifft1 = fft_blocks.fft_vcc(total_subc,False,[],True)
                self.connect( estimated_CTF, ifft1,gr.null_sink(gr.sizeof_gr_complex*total_subc))
                summ1 = ofdm.vector_sum_vcc(total_subc)
                c2m =gr.complex_to_mag(total_subc)
                self.connect( estimated_CTF,summ1 ,gr.null_sink(gr.sizeof_gr_complex))
                self.connect( estimated_CTF, c2m,gr.null_sink(gr.sizeof_float*total_subc))
                log_to_file( self, ifft1, "data/CIR1.compl" )
                log_to_file( self, summ1, "data/CTFsumm1.compl" )
                log_to_file( self, estimated_CTF, "data/CTF1.compl" )
                log_to_file( self, c2m, "data/CTFmag1.float" )
        
            ## MSE enhancer
            ctf_mse_enhancer = ofdm.CTF_MSE_enhancer( total_subc, cp_length + cp_length)
            self.connect( estimated_CTF, ctf_mse_enhancer )
#      log_to_file( self, ctf_mse_enhancer, "data/ctf_mse_enhancer_original.compl")
      #ifft3 = fft_blocks.fft_vcc(total_subc,False,[],True)
      #null_noise = ofdm.noise_nulling(total_subc, cp_length + cp_length)
      #ctf_mse_enhancer = fft_blocks.fft_vcc(total_subc,True,[],True)
      #ctf_mse_enhancer = ofdm.vector_mask( fft_length, virtual_subc/2,
                                          # total_subc, [] )
      #self.connect( estimated_CTF, ifft3,null_noise,ctf_mse_enhancer )
        
            estimated_CTF = ctf_mse_enhancer 
            print "Disabled CTF MSE enhancer"

        if options.logcir:
         ifft2 = fft_blocks.fft_vcc(total_subc,False,[],True)
         self.connect( estimated_CTF, ifft2,gr.null_sink(gr.sizeof_gr_complex*total_subc))
         summ2 = ofdm.vector_sum_vcc(total_subc)
         c2m2 =gr.complex_to_mag(total_subc)
         self.connect( estimated_CTF,summ2 ,gr.null_sink(gr.sizeof_gr_complex))
         self.connect( estimated_CTF, c2m2,gr.null_sink(gr.sizeof_float*total_subc))
         log_to_file( self, ifft2, "data/CIR2.compl" )
         log_to_file( self, summ2, "data/CTFsumm2.compl" )
         log_to_file( self, estimated_CTF, "data/CTF2.compl" )
         log_to_file( self, c2m2, "data/CTFmag2.float" )
         
        ## Postprocess the CTF estimate
        ## CTF -> inverse CTF (for equalizer)
        ## CTF -> norm |.|^2 (for CTF display)
        ctf_postprocess = ofdm.fbmc_postprocess_CTF_estimate( total_subc )
        
        self.connect( help2, ctf_postprocess )
        #estimated_SNR = ( ctf_postprocess, 0 )
        disp_CTF = ( ctf_postprocess, 0 )
        #self.connect(estimated_SNR,out_snr_pream)
        #log_to_file( self, estimated_SNR, "data/fbmc_SNR.float" )
        
        #Disable measured SNR output
        #terminate_stream(self, estimated_SNR)
        #self.connect(blocks.vector_source_f([10.0],True) ,out_snr_pream)
    
#     if options.disable_equalization or options.ideal:
#       terminate_stream(self, inv_estimated_CTF)
#       inv_estimated_CTF_vec = blocks.vector_source_c([1.0/fft_length*math.sqrt(total_subc)]*total_subc,True,total_subc)
#       inv_estimated_CTF_str = blocks.vector_to_stream(gr.sizeof_gr_complex, total_subc)
#       self.inv_estimated_CTF_mul = ofdm.multiply_const_ccf( 1.0/config.rms_amplitude )
#       #inv_estimated_CTF_mul.set_k(1.0/config.rms_amplitude)
#       inv_estimated_CTF = blocks.stream_to_vector(gr.sizeof_gr_complex, total_subc)
#       self.connect( inv_estimated_CTF_vec, inv_estimated_CTF_str, self.inv_estimated_CTF_mul, inv_estimated_CTF)
#       print "Disabled equalization stage"
    '''
    ## LMS Phase tracking
    ## Track residual frequency offset and sampling clock frequency offset

    nondata_blocks = []
    for i in range(config.frame_length):
      if i in config.training_data.pilotsym_pos:
        nondata_blocks.append(i)
        
    print"\t\t\t\t\tnondata_blocks=",nondata_blocks
    pilot_subc = block_header.pilot_tones
    pilot_subcarriers = block_header.pilot_subc_sym
    print "PILOT SUBCARRIERS: ", pilot_subcarriers
        
    phase_tracking = ofdm.lms_phase_tracking_03( total_subc, pilot_subc,
                                               nondata_blocks, pilot_subcarriers,0 )
    self.connect( ofdm_blocks, ( phase_tracking, 0 ) )
    self.connect( inv_estimated_CTF, ( phase_tracking, 1 ) )
    self.connect( frame_start, ( phase_tracking, 2 ) ) ##
    
    if options.scatter_plot_before_phase_tracking:
      self.before_phase_tracking = equalizer
      
    
    if options.disable_phase_tracking or options.ideal:
      terminate_stream(self, phase_tracking)
      print "Disabled phase tracking stage"
    else:
      ofdm_blocks = phase_tracking
    '''
    ## Channel Equalizer
    ##equalizer = ofdm.channel_equalizer( total_subc )
    ##self.connect( ofdm_blocks,       ( equalizer, 0 ) )
    ##self.connect( inv_estimated_CTF, ( equalizer, 1 ) )
    ##self.connect( frame_start,       ( equalizer, 2 ) )
    ##ofdm_blocks = equalizer
    #log_to_file(self, equalizer,"data/equalizer_siso.compl")
    
    
    #log_to_file(self, ofdm_blocks, "data/equalizer.compl")

    ## LMS Phase tracking
    ## Track residual frequency offset and sampling clock frequency offset

    nondata_blocks = []
    for i in range(config.frame_length):
      if i in config.training_data.pilotsym_pos:
        nondata_blocks.append(i)
        
    print"\t\t\t\t\tnondata_blocks=",nondata_blocks
    pilot_subc = block_header.pilot_tones
    pilot_subcarriers = block_header.pilot_subc_sym
    print "PILOT SUBCARRIERS: ", pilot_subcarriers
    
    if options.scatter_plot_before_phase_tracking:
      self.before_phase_tracking = equalizer
        

    ## Output connections

    self.connect( ofdm_blocks, out_ofdm_blocks )
    self.connect( frame_start, out_frame_start )
    if options.ideal is False and options.ideal2 is False:
        self.connect( disp_CTF, out_disp_ctf )
    else:
        self.connect( blocks.vector_source_f([1.0]*total_subc),blocks.stream_to_vector(gr.sizeof_float,total_subc), out_disp_ctf )
    
    

    if log:
      log_to_file( self, sc_metric, "data/sc_metric.float" )
      log_to_file( self, gi_metric, "data/gi_metric.float" )
      log_to_file( self, morelli_foe, "data/morelli_foe.float" )
      log_to_file( self, lms_fir, "data/lms_fir.float" )
      log_to_file( self, sampler_preamble, "data/preamble.compl" )
      log_to_file( self, sync, "data/sync.compl" )
      log_to_file( self, frequency_shift, "data/frequency_shift.compl" )
      log_to_file( self, fft, "data/fft.compl")
      log_to_file( self, fft, "data/fft.float", mag=True )
      
      if vars().has_key( 'subcarrier_mask' ):
        log_to_file( self, subcarrier_mask, "data/subcarrier_mask.compl" )
      
      log_to_file( self, ofdm_blocks, "data/ofdm_blocks_out.compl" )
      log_to_file( self, frame_start, "data/frame_start.float", 
                   char_to_float=True )
      
      log_to_file( self, sampled_chest_preamble, 
                   "data/sampled_chest_preamble.compl" )
      log_to_file( self, LS_channel_estimator, 
                   "data/ls_channel_estimator.compl" )
      log_to_file( self, LS_channel_estimator, 
                   "data/ls_channel_estimator.float", mag=True )
      
      if "ctf_mse_enhancer" in locals(): 
        log_to_file( self, ctf_mse_enhancer, "data/ctf_mse_enhancer.compl" )
        log_to_file( self, ctf_mse_enhancer, "data/ctf_mse_enhancer.float", 
                     mag=True )
      
      log_to_file( self, (ctf_postprocess,0), "data/inc_estimated_ctf.compl" )
      log_to_file( self, (ctf_postprocess,1), "data/disp_ctf.float" )
      
      log_to_file( self, equalizer, "data/equalizer.compl" )
      log_to_file( self, equalizer, "data/equalizer.float", mag=True )
      
      log_to_file( self, phase_tracking, "data/phase_tracking.compl" )
    def __init__(self):
        gr.top_block.__init__(self, "Calibration Example")
        Qt.QWidget.__init__(self)
        self.setWindowTitle("Calibration Example")
        try:
             self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc'))
        except:
             pass
        self.top_scroll_layout = Qt.QVBoxLayout()
        self.setLayout(self.top_scroll_layout)
        self.top_scroll = Qt.QScrollArea()
        self.top_scroll.setFrameStyle(Qt.QFrame.NoFrame)
        self.top_scroll_layout.addWidget(self.top_scroll)
        self.top_scroll.setWidgetResizable(True)
        self.top_widget = Qt.QWidget()
        self.top_scroll.setWidget(self.top_widget)
        self.top_layout = Qt.QVBoxLayout(self.top_widget)
        self.top_grid_layout = Qt.QGridLayout()
        self.top_layout.addLayout(self.top_grid_layout)

        self.settings = Qt.QSettings("GNU Radio", "calibration_example_gui_2x_measure")
        self.restoreGeometry(self.settings.value("geometry").toByteArray())

        ##################################################
        # Variables
        ##################################################
        self.speed_of_light = speed_of_light = 299792458
        self.antenna_spacing = antenna_spacing = 0.1
        self.variable_qtgui_chooser_0_1_0 = variable_qtgui_chooser_0_1_0 = 0
        self.variable_qtgui_chooser_0_0 = variable_qtgui_chooser_0_0 = 1
        self.samp_rate = samp_rate = 100000000/64
        self.gain_rx = gain_rx = 0
        self.center_freq = center_freq = speed_of_light/(2*antenna_spacing)
        self.cal_freq = cal_freq = 1024

        ##################################################
        # Blocks
        ##################################################
        self._variable_qtgui_chooser_0_1_0_options = (1, 0, )
        self._variable_qtgui_chooser_0_1_0_labels = ("Stop", "Running", )
        self._variable_qtgui_chooser_0_1_0_group_box = Qt.QGroupBox("Sync System")
        self._variable_qtgui_chooser_0_1_0_box = Qt.QHBoxLayout()
        class variable_chooser_button_group(Qt.QButtonGroup):
            def __init__(self, parent=None):
                Qt.QButtonGroup.__init__(self, parent)
            @pyqtSlot(int)
            def updateButtonChecked(self, button_id):
                self.button(button_id).setChecked(True)
        self._variable_qtgui_chooser_0_1_0_button_group = variable_chooser_button_group()
        self._variable_qtgui_chooser_0_1_0_group_box.setLayout(self._variable_qtgui_chooser_0_1_0_box)
        for i, label in enumerate(self._variable_qtgui_chooser_0_1_0_labels):
        	radio_button = Qt.QRadioButton(label)
        	self._variable_qtgui_chooser_0_1_0_box.addWidget(radio_button)
        	self._variable_qtgui_chooser_0_1_0_button_group.addButton(radio_button, i)
        self._variable_qtgui_chooser_0_1_0_callback = lambda i: Qt.QMetaObject.invokeMethod(self._variable_qtgui_chooser_0_1_0_button_group, "updateButtonChecked", Qt.Q_ARG("int", self._variable_qtgui_chooser_0_1_0_options.index(i)))
        self._variable_qtgui_chooser_0_1_0_callback(self.variable_qtgui_chooser_0_1_0)
        self._variable_qtgui_chooser_0_1_0_button_group.buttonClicked[int].connect(
        	lambda i: self.set_variable_qtgui_chooser_0_1_0(self._variable_qtgui_chooser_0_1_0_options[i]))
        self.top_layout.addWidget(self._variable_qtgui_chooser_0_1_0_group_box)
        self._variable_qtgui_chooser_0_0_options = (0, 1, )
        self._variable_qtgui_chooser_0_0_labels = ("Enable", "Disable", )
        self._variable_qtgui_chooser_0_0_group_box = Qt.QGroupBox("Source Enable")
        self._variable_qtgui_chooser_0_0_box = Qt.QVBoxLayout()
        class variable_chooser_button_group(Qt.QButtonGroup):
            def __init__(self, parent=None):
                Qt.QButtonGroup.__init__(self, parent)
            @pyqtSlot(int)
            def updateButtonChecked(self, button_id):
                self.button(button_id).setChecked(True)
        self._variable_qtgui_chooser_0_0_button_group = variable_chooser_button_group()
        self._variable_qtgui_chooser_0_0_group_box.setLayout(self._variable_qtgui_chooser_0_0_box)
        for i, label in enumerate(self._variable_qtgui_chooser_0_0_labels):
        	radio_button = Qt.QRadioButton(label)
        	self._variable_qtgui_chooser_0_0_box.addWidget(radio_button)
        	self._variable_qtgui_chooser_0_0_button_group.addButton(radio_button, i)
        self._variable_qtgui_chooser_0_0_callback = lambda i: Qt.QMetaObject.invokeMethod(self._variable_qtgui_chooser_0_0_button_group, "updateButtonChecked", Qt.Q_ARG("int", self._variable_qtgui_chooser_0_0_options.index(i)))
        self._variable_qtgui_chooser_0_0_callback(self.variable_qtgui_chooser_0_0)
        self._variable_qtgui_chooser_0_0_button_group.buttonClicked[int].connect(
        	lambda i: self.set_variable_qtgui_chooser_0_0(self._variable_qtgui_chooser_0_0_options[i]))
        self.top_layout.addWidget(self._variable_qtgui_chooser_0_0_group_box)
        self.uhd_usrp_source_0_0_0 = uhd.usrp_source(
        	",".join(("addr0=192.168.70.2,addr1=192.168.20.2,addr2=192.168.30.2,addr3=192.168.50.2", "")),
        	uhd.stream_args(
        		cpu_format="fc32",
        		channels=range(4),
        	),
        )
        self.uhd_usrp_source_0_0_0.set_clock_source("external", 0)
        self.uhd_usrp_source_0_0_0.set_time_source("external", 0)
        self.uhd_usrp_source_0_0_0.set_clock_source("external", 1)
        self.uhd_usrp_source_0_0_0.set_time_source("external", 1)
        self.uhd_usrp_source_0_0_0.set_clock_source("external", 2)
        self.uhd_usrp_source_0_0_0.set_time_source("external", 2)
        self.uhd_usrp_source_0_0_0.set_clock_source("external", 3)
        self.uhd_usrp_source_0_0_0.set_time_source("external", 3)
        self.uhd_usrp_source_0_0_0.set_time_unknown_pps(uhd.time_spec())
        self.uhd_usrp_source_0_0_0.set_samp_rate(samp_rate)

        # Tell boards to run these commands at this specific time in the future
        cmd_time = self.uhd_usrp_source_0_0_0.get_time_now() + uhd.time_spec_t(1.0)
        self.uhd_usrp_source_0_0_0.set_command_time(cmd_time,0)
        self.uhd_usrp_source_0_0_0.set_command_time(cmd_time,1)
        self.uhd_usrp_source_0_0_0.set_command_time(cmd_time,2)
        self.uhd_usrp_source_0_0_0.set_command_time(cmd_time,3)

        self.uhd_usrp_source_0_0_0.set_center_freq(center_freq, 0)
        self.uhd_usrp_source_0_0_0.set_gain(gain_rx, 0)
        self.uhd_usrp_source_0_0_0.set_center_freq(center_freq, 1)
        self.uhd_usrp_source_0_0_0.set_gain(gain_rx, 1)
        self.uhd_usrp_source_0_0_0.set_center_freq(center_freq, 2)
        self.uhd_usrp_source_0_0_0.set_gain(gain_rx, 2)
        self.uhd_usrp_source_0_0_0.set_center_freq(center_freq, 3)
        self.uhd_usrp_source_0_0_0.set_gain(gain_rx, 3)

        self.uhd_usrp_source_0_0_0.clear_command_time()
        time.sleep(1.5)

        self.uhd_usrp_sink_0_0 = uhd.usrp_sink(
        	",".join(("addr=192.168.40.2", "")),
        	uhd.stream_args(
        		cpu_format="fc32",
        		channels=range(1),
        	),
        )
        self.uhd_usrp_sink_0_0.set_clock_source("mimo", 0)
        self.uhd_usrp_sink_0_0.set_time_source("mimo", 0)
        self.uhd_usrp_sink_0_0.set_samp_rate(samp_rate)
        self.uhd_usrp_sink_0_0.set_center_freq(center_freq, 0)
        self.uhd_usrp_sink_0_0.set_gain(10, 0)
        self.qtgui_time_sink_x_0_0 = qtgui.time_sink_f(
        	100, #size
        	samp_rate, #samp_rate
        	"", #name
        	3 #number of inputs
        )
        self.qtgui_time_sink_x_0_0.set_update_time(0.10)
        self.qtgui_time_sink_x_0_0.set_y_axis(-1, 1)

        self.qtgui_time_sink_x_0_0.set_y_label("Amplitude", "")

        self.qtgui_time_sink_x_0_0.enable_tags(-1, True)
        self.qtgui_time_sink_x_0_0.set_trigger_mode(qtgui.TRIG_MODE_AUTO, qtgui.TRIG_SLOPE_POS, 0.0, 0, 0, "")
        self.qtgui_time_sink_x_0_0.enable_autoscale(True)
        self.qtgui_time_sink_x_0_0.enable_grid(False)
        self.qtgui_time_sink_x_0_0.enable_control_panel(True)

        if not True:
          self.qtgui_time_sink_x_0_0.disable_legend()

        labels = ["", "", "", "", "",
                  "", "", "", "", ""]
        widths = [1, 1, 1, 1, 1,
                  1, 1, 1, 1, 1]
        colors = ["blue", "red", "green", "black", "cyan",
                  "magenta", "yellow", "dark red", "dark green", "blue"]
        styles = [1, 1, 1, 1, 1,
                  1, 1, 1, 1, 1]
        markers = [-1, -1, -1, -1, -1,
                   -1, -1, -1, -1, -1]
        alphas = [1.0, 1.0, 1.0, 1.0, 1.0,
                  1.0, 1.0, 1.0, 1.0, 1.0]

        for i in xrange(3):
            if len(labels[i]) == 0:
                self.qtgui_time_sink_x_0_0.set_line_label(i, "Data {0}".format(i))
            else:
                self.qtgui_time_sink_x_0_0.set_line_label(i, labels[i])
            self.qtgui_time_sink_x_0_0.set_line_width(i, widths[i])
            self.qtgui_time_sink_x_0_0.set_line_color(i, colors[i])
            self.qtgui_time_sink_x_0_0.set_line_style(i, styles[i])
            self.qtgui_time_sink_x_0_0.set_line_marker(i, markers[i])
            self.qtgui_time_sink_x_0_0.set_line_alpha(i, alphas[i])

        self._qtgui_time_sink_x_0_0_win = sip.wrapinstance(self.qtgui_time_sink_x_0_0.pyqwidget(), Qt.QWidget)
        self.top_layout.addWidget(self._qtgui_time_sink_x_0_0_win)
        self.qtgui_time_sink_x_0 = qtgui.time_sink_f(
        	1526*2, #size
        	samp_rate, #samp_rate
        	"", #name
        	4 #number of inputs
        )
        self.qtgui_time_sink_x_0.set_update_time(0.10)
        self.qtgui_time_sink_x_0.set_y_axis(-1, 1)

        self.qtgui_time_sink_x_0.set_y_label("Amplitude", "")

        self.qtgui_time_sink_x_0.enable_tags(-1, True)
        self.qtgui_time_sink_x_0.set_trigger_mode(qtgui.TRIG_MODE_AUTO, qtgui.TRIG_SLOPE_POS, 0.0, 0, 0, "")
        self.qtgui_time_sink_x_0.enable_autoscale(True)
        self.qtgui_time_sink_x_0.enable_grid(False)
        self.qtgui_time_sink_x_0.enable_control_panel(True)

        if not True:
          self.qtgui_time_sink_x_0.disable_legend()

        labels = ["", "", "", "", "",
                  "", "", "", "", ""]
        widths = [1, 1, 1, 1, 1,
                  1, 1, 1, 1, 1]
        colors = ["blue", "red", "green", "black", "cyan",
                  "magenta", "yellow", "dark red", "dark green", "blue"]
        styles = [1, 1, 1, 1, 1,
                  1, 1, 1, 1, 1]
        markers = [-1, -1, -1, -1, -1,
                   -1, -1, -1, -1, -1]
        alphas = [1.0, 1.0, 1.0, 1.0, 1.0,
                  1.0, 1.0, 1.0, 1.0, 1.0]

        for i in xrange(4):
            if len(labels[i]) == 0:
                self.qtgui_time_sink_x_0.set_line_label(i, "Data {0}".format(i))
            else:
                self.qtgui_time_sink_x_0.set_line_label(i, labels[i])
            self.qtgui_time_sink_x_0.set_line_width(i, widths[i])
            self.qtgui_time_sink_x_0.set_line_color(i, colors[i])
            self.qtgui_time_sink_x_0.set_line_style(i, styles[i])
            self.qtgui_time_sink_x_0.set_line_marker(i, markers[i])
            self.qtgui_time_sink_x_0.set_line_alpha(i, alphas[i])

        self._qtgui_time_sink_x_0_win = sip.wrapinstance(self.qtgui_time_sink_x_0.pyqwidget(), Qt.QWidget)
        self.top_layout.addWidget(self._qtgui_time_sink_x_0_win)
        self.measure_offset_0 = measure_offset(
            cal_freq=cal_freq,
            mu=0.0001,
            samp_rate=samp_rate,
        )
        self.blocks_skiphead_0_1 = blocks.skiphead(gr.sizeof_int*1, 1024*4)
        self.blocks_skiphead_0_0 = blocks.skiphead(gr.sizeof_int*1, 1024*4)
        self.blocks_skiphead_0 = blocks.skiphead(gr.sizeof_int*1, 1024*4)
        self.blocks_message_strobe_0 = blocks.message_strobe(pmt.from_double(variable_qtgui_chooser_0_1_0), 1000)
        self.blocks_int_to_float_0_1 = blocks.int_to_float(1, 1)
        self.blocks_int_to_float_0_0 = blocks.int_to_float(1, 1)
        self.blocks_int_to_float_0 = blocks.int_to_float(1, 1)
        self.blocks_head_0 = blocks.head(gr.sizeof_int*1, 100)
        self.blocks_file_sink_0_1 = blocks.file_sink(gr.sizeof_int*1, "/home/travis/Dropbox/PHD/WiFiUS/doa/gnuradio/gr-wifius/data/offsets_chan3_ints.bin", False)
        self.blocks_file_sink_0_1.set_unbuffered(False)
        self.blocks_file_sink_0_0 = blocks.file_sink(gr.sizeof_int*1, "/home/travis/Dropbox/PHD/WiFiUS/doa/gnuradio/gr-wifius/data/offsets_chan2_ints.bin", False)
        self.blocks_file_sink_0_0.set_unbuffered(False)
        self.blocks_file_sink_0 = blocks.file_sink(gr.sizeof_int*1, "/home/travis/Dropbox/PHD/WiFiUS/doa/gnuradio/gr-wifius/data/offsets_chan1_ints.bin", False)
        self.blocks_file_sink_0.set_unbuffered(False)
        self.blocks_complex_to_real_1_0 = blocks.complex_to_real(1)
        self.blocks_complex_to_real_1 = blocks.complex_to_real(1)
        self.blocks_complex_to_real_0_0 = blocks.complex_to_real(1)
        self.blocks_complex_to_real_0 = blocks.complex_to_real(1)
        self.analog_sig_source_x_0 = analog.sig_source_c(samp_rate, analog.GR_COS_WAVE, cal_freq, 1, 0)

        ##################################################
        # Connections
        ##################################################
        self.msg_connect((self.blocks_message_strobe_0, 'strobe'), (self.measure_offset_0, 'in'))
        self.connect((self.analog_sig_source_x_0, 0), (self.uhd_usrp_sink_0_0, 0))
        self.connect((self.blocks_complex_to_real_0, 0), (self.qtgui_time_sink_x_0, 0))
        self.connect((self.blocks_complex_to_real_0_0, 0), (self.qtgui_time_sink_x_0, 2))
        self.connect((self.blocks_complex_to_real_1, 0), (self.qtgui_time_sink_x_0, 1))
        self.connect((self.blocks_complex_to_real_1_0, 0), (self.qtgui_time_sink_x_0, 3))
        self.connect((self.blocks_head_0, 0), (self.blocks_file_sink_0, 0))
        self.connect((self.blocks_int_to_float_0, 0), (self.qtgui_time_sink_x_0_0, 0))
        self.connect((self.blocks_int_to_float_0_0, 0), (self.qtgui_time_sink_x_0_0, 2))
        self.connect((self.blocks_int_to_float_0_1, 0), (self.qtgui_time_sink_x_0_0, 1))
        self.connect((self.blocks_skiphead_0, 0), (self.blocks_head_0, 0))
        self.connect((self.blocks_skiphead_0_0, 0), (self.blocks_file_sink_0_0, 0))
        self.connect((self.blocks_skiphead_0_1, 0), (self.blocks_file_sink_0_1, 0))
        self.connect((self.measure_offset_0, 0), (self.blocks_int_to_float_0, 0))
        self.connect((self.measure_offset_0, 2), (self.blocks_int_to_float_0_0, 0))
        self.connect((self.measure_offset_0, 1), (self.blocks_int_to_float_0_1, 0))
        self.connect((self.measure_offset_0, 0), (self.blocks_skiphead_0, 0))
        self.connect((self.measure_offset_0, 1), (self.blocks_skiphead_0_0, 0))
        self.connect((self.measure_offset_0, 2), (self.blocks_skiphead_0_1, 0))
        self.connect((self.uhd_usrp_source_0_0_0, 0), (self.blocks_complex_to_real_0, 0))
        self.connect((self.uhd_usrp_source_0_0_0, 2), (self.blocks_complex_to_real_0_0, 0))
        self.connect((self.uhd_usrp_source_0_0_0, 1), (self.blocks_complex_to_real_1, 0))
        self.connect((self.uhd_usrp_source_0_0_0, 3), (self.blocks_complex_to_real_1_0, 0))
        self.connect((self.uhd_usrp_source_0_0_0, 0), (self.measure_offset_0, 0))
        self.connect((self.uhd_usrp_source_0_0_0, 1), (self.measure_offset_0, 1))
        self.connect((self.uhd_usrp_source_0_0_0, 2), (self.measure_offset_0, 2))
        self.connect((self.uhd_usrp_source_0_0_0, 3), (self.measure_offset_0, 3))
Пример #55
0
    def __init__(self, channel_noise, img_path):
        gr.top_block.__init__(self, "Top Block")

        ##################################################
        # Variables
        ##################################################
        self.taps = taps = [1]
        self.size_packed_file = size_packed_file = os.path.getsize(
            "/home/rcampello/Main/FixedPath/OOT Gnuradio/Material/GnuRadio/Scripts/BPSK/{}"
            .format(str(img_path)))
        self.samp_rate = samp_rate = 32000 * 20
        self.rrc_taps = rrc_taps = firdes.root_raised_cosine(
            32, 32, 1.0 / float(2), 0.35, 11 * 2 * 32)
        self.noise = noise = channel_noise
        self.eq_gain = eq_gain = 0
        self.delay2 = delay2 = int(8)
        self.delay = delay = int(2)

        self.BPSK = BPSK = digital.constellation_bpsk().base()

        ##################################################
        # Blocks
        ##################################################
        self.digital_pfb_clock_sync_xxx_0 = digital.pfb_clock_sync_ccf(
            4, 62.8e-3, (rrc_taps), 32, 16, 1.5, 2)
        self.digital_costas_loop_cc_0 = digital.costas_loop_cc(
            62.8e-3, 2, False)
        self.digital_constellation_modulator_0 = digital.generic_mod(
            constellation=BPSK,
            differential=False,
            samples_per_symbol=4,
            pre_diff_code=True,
            excess_bw=0.35,
            verbose=False,
            log=False,
        )
        self.digital_constellation_decoder_cb_0 = digital.constellation_decoder_cb(
            BPSK)
        self.digital_cma_equalizer_cc_0 = digital.cma_equalizer_cc(
            15, 1, eq_gain, 2)
        self.channels_channel_model_0 = channels.channel_model(
            noise_voltage=noise,
            frequency_offset=0.0,
            epsilon=1.0,
            taps=(taps),
            noise_seed=0,
            block_tags=False)
        self.blocks_throttle_0 = blocks.throttle(gr.sizeof_char * 1, samp_rate,
                                                 True)
        self.blocks_skiphead_0_0 = blocks.skiphead(gr.sizeof_char * 1,
                                                   int(size_packed_file * 0.1))
        self.blocks_pack_k_bits_bb_1 = blocks.pack_k_bits_bb(8)
        self.blocks_null_sink_0 = blocks.null_sink(gr.sizeof_char * 1)
        self.blocks_head_0_0 = blocks.head(gr.sizeof_char * 1,
                                           int(size_packed_file * 2))
        self.blocks_file_source_0 = blocks.file_source(
            gr.sizeof_char * 1,
            '/home/rcampello/Main/FixedPath/OOT Gnuradio/Material/GnuRadio/Scripts/BPSK/{}'
            .format(str(img_path)), True)
        self.sink = blocks.vector_sink_b()

        ##################################################
        # Connections
        ##################################################
        self.connect((self.blocks_file_source_0, 0),
                     (self.blocks_throttle_0, 0))
        self.connect((self.blocks_head_0_0, 0),
                     (self.digital_constellation_modulator_0, 0))
        self.connect((self.blocks_pack_k_bits_bb_1, 0), (self.sink, 0))
        self.connect((self.blocks_pack_k_bits_bb_1, 0),
                     (self.blocks_null_sink_0, 0))
        self.connect((self.blocks_skiphead_0_0, 0), (self.blocks_head_0_0, 0))
        self.connect((self.blocks_throttle_0, 0),
                     (self.blocks_skiphead_0_0, 0))
        self.connect((self.channels_channel_model_0, 0),
                     (self.digital_pfb_clock_sync_xxx_0, 0))
        self.connect((self.digital_cma_equalizer_cc_0, 0),
                     (self.digital_costas_loop_cc_0, 0))
        self.connect((self.digital_constellation_decoder_cb_0, 0),
                     (self.blocks_pack_k_bits_bb_1, 0))
        self.connect((self.digital_constellation_modulator_0, 0),
                     (self.channels_channel_model_0, 0))
        self.connect((self.digital_costas_loop_cc_0, 0),
                     (self.digital_constellation_decoder_cb_0, 0))
        self.connect((self.digital_pfb_clock_sync_xxx_0, 0),
                     (self.digital_cma_equalizer_cc_0, 0))
def main():
    args = get_arguments()
    constellation = {
            1:digital.constellation_bpsk(),
            2:digital.constellation_qpsk(),
            3:digital.constellation_8psk(),
    }
    
    fft_len = 64
    cp_len = 16
    
    occupied_carriers=(range(-26, -21) + range(-20, -7) +
                       range(-6, 0) + range(1, 7) +
                       range(8, 21) + range(22, 27),)
    pilot_carriers=((-21, -7, 7, 21),)
    pilot_symbols=tuple([(1, -1, 1, -1),])

    tb1 = gr.top_block()
    tb2 = gr.top_block()
    
    if args.freq == None:
        data_source = mimoots.file_source2(
                itemsize=(gr.sizeof_gr_complex, gr.sizeof_gr_complex),
                filename=(
                        '1.'.join(args.from_file.rsplit('.',1)),
                        '2.'.join(args.from_file.rsplit('.',1))
                )
        )
    else:
        data_source = mimoots.uhd_source2(freq=args.freq, gain=args.gain)

    skip1 = blocks.skiphead(
            itemsize=gr.sizeof_gr_complex,
            nitems_to_skip=args.skiphead
    )
    
    skip2 = blocks.skiphead(
            itemsize=gr.sizeof_gr_complex,
            nitems_to_skip=args.skiphead
    )
    
    ofdm_frames1 = mimoots.ofdm_basebandsignal_to_frames_cvc(
            fft_len=fft_len,
            cp_len=cp_len,
            nofdm_symbols=args.nsymbols
    )
    
    ofdm_frames2 = mimoots.ofdm_basebandsignal_to_frames_cvc(
            fft_len=fft_len,
            cp_len=cp_len,
            nofdm_symbols=args.nsymbols
    )
    
    buffer1 = blocks.vector_sink_c(vlen=fft_len)
    buffer2 = blocks.vector_sink_c(vlen=fft_len)
    
    tb1.connect((data_source,0), skip1, ofdm_frames1, buffer1)
    tb1.connect((data_source,1), skip2, ofdm_frames2, buffer2)

    tb1.connect(ofdm_frames1, blocks.file_sink(gr.sizeof_gr_complex*fft_len, 'd1.gr'))
    tb1.connect(ofdm_frames2, blocks.file_sink(gr.sizeof_gr_complex*fft_len, 'd2.gr'))

    tb1.run()
    
    data1 = buffer1.data()
    data2 = buffer2.data()
    
    data1 = extract_channeldata(data1, 0, fft_len)
    data2 = extract_channeldata(data2, 1, fft_len)
    
    buf_source1 = blocks.vector_source_c(data1)
    buf_source2 = blocks.vector_source_c(data2)
    
    data_sink = mimoots.file_sink2(
            itemsize=(gr.sizeof_gr_complex, gr.sizeof_gr_complex),
            filename=('s1r1.gr', 's2r2.gr')
    )
    
    tb2.connect(buf_source1, (data_sink, 0))
    tb2.connect(buf_source2, (data_sink, 1))
    
    tb2.run()