def __init__(self, noise_amp, ndata):
        gr.top_block.__init__(self, "Top Block")

        ##################################################
        # Variables
        ##################################################
        self.signal_gain = signal_gain = 0.01
        self.samp_rate = samp_rate = 32000
        self.noise_amplitude = noise_amplitude = noise_amp  #noise_amplitude = noise_amp
        self.ndata = ndata

        ##################################################
        # Blocks
        ##################################################
        self.digital_psk_mod_0 = digital.psk.psk_mod(
            constellation_points=4,
            mod_code="gray",
            differential=True,
            samples_per_symbol=2,
            excess_bw=0.35,
            verbose=False,
            log=False,
        )

        self.blocks_throttle_0 = blocks.throttle(gr.sizeof_char * 1, samp_rate,
                                                 True)
        self.s2v_signal = blocks.stream_to_vector(gr.sizeof_gr_complex,
                                                  self.ndata)
        self.s2v_noise = blocks.stream_to_vector(gr.sizeof_gr_complex,
                                                 self.ndata)
        self.s2v_sn = blocks.stream_to_vector(gr.sizeof_gr_complex, self.ndata)
        self.blocks_probe_signal_and_noise = blocks.probe_signal_vc(self.ndata)
        self.blocks_probe_noise_only = blocks.probe_signal_vc(self.ndata)
        self.blocks_probe_signal_only = blocks.probe_signal_vc(self.ndata)
        self.blocks_multiply_const_vxx_3 = blocks.multiply_const_vcc(
            (signal_gain, ))
        self.blocks_add_xx_0 = blocks.add_vcc(1)
        self.analog_random_source_x_0 = blocks.vector_source_b(
            map(int, numpy.random.randint(0, 2, 1000)), True)
        self.analog_noise_source_x_0 = analog.noise_source_c(
            analog.GR_GAUSSIAN, noise_amplitude, 0)

        ##################################################
        # Connections
        ##################################################
        self.connect((self.analog_noise_source_x_0, 0),
                     (self.blocks_add_xx_0, 1))
        self.connect((self.analog_noise_source_x_0, 0), (self.s2v_noise, 0),
                     (self.blocks_probe_noise_only, 0))
        self.connect((self.analog_random_source_x_0, 0),
                     (self.blocks_throttle_0, 0))
        self.connect((self.blocks_add_xx_0, 0), (self.s2v_sn, 0),
                     (self.blocks_probe_signal_and_noise, 0))
        self.connect((self.blocks_multiply_const_vxx_3, 0),
                     (self.blocks_add_xx_0, 0))
        self.connect((self.blocks_multiply_const_vxx_3, 0),
                     (self.s2v_signal, 0), (self.blocks_probe_signal_only, 0))
        self.connect((self.blocks_throttle_0, 0), (self.digital_psk_mod_0, 0))
        self.connect((self.digital_psk_mod_0, 0),
                     (self.blocks_multiply_const_vxx_3, 0))
Example #2
0
    def test_000(self):
        """
        Generates nfilts sets of random complex data.
        Generates two sets of random taps for each filter.
        Applies one set of the random taps, gets some output,
        applies the second set of random taps, gets some more output,
        The output is then compared with a python-implemented
        convolution.
        """
        myrand = random.Random(123).random
        nfilts = 10
        ntaps = 5
        # Sets some of the taps to be all zeros.
        zero_filts1 = (3, 7)
        zero_filts2 = (1, 6, 9)
        ndatapoints = 100
        # Generate some random sets of data
        data_sets = []
        for i in range(0, nfilts):
            data_sets.append([(myrand() - 0.5) + (myrand() - 0.5) * (0 + 1j)
                              for k in range(0, ndatapoints)])
        # Join them together to pass to vector_source block
        data = []
        for dp in zip(*data_sets):
            data += dp
        # Generate some random taps.
        taps1 = []
        taps2 = []
        for i in range(0, nfilts):
            if i in zero_filts1:
                taps1.append([0] * ntaps)
            else:
                taps1.append([myrand() - 0.5 for k in range(0, ntaps)])
            if i in zero_filts2:
                taps2.append([0] * ntaps)
            else:
                taps2.append([myrand() - 0.5 for k in range(0, ntaps)])

        # Calculate results with a python-implemented convolution.
        results = []
        results2 = []
        for ds, ts, ts2 in zip(data_sets, taps1, taps2):
            results.append(convolution(ds[-len(ts):] + ds[:-1], ts))
            results2.append(convolution(ds[-len(ts):] + ds[:-1], ts2))
        # Convert results from 2D arrays to 1D arrays for ease of comparison.
        comb_results = []
        for rs in zip(*results):
            comb_results += rs
        comb_results2 = []
        for rs in zip(*results2):
            comb_results2 += rs
        # Construct the signal-processing chain.
        src = blocks.vector_source_c(data, True, nfilts)
        fb = filter.filterbank_vcvcf(taps1)
        v2s = blocks.vector_to_stream(gr.sizeof_gr_complex, nfilts)
        s2v = blocks.stream_to_vector(gr.sizeof_gr_complex,
                                      nfilts * ndatapoints)
        snk = blocks.probe_signal_vc(nfilts * ndatapoints)
        self.tb.connect(src, fb, v2s, s2v, snk)
        # Run the signal-processing chain.
        self.tb.start()
        all_zero = True
        outdata = None
        waittime = 0.001
        # Wait until we have some data.
        while (not outdata) or outdata[0] == 0:
            time.sleep(waittime)
            outdata = snk.level()
        # Apply the second set of taps.
        fb.set_taps(taps2)
        outdata2 = None
        # Wait until we have new data.
        while (not outdata2) or outdata[0] == outdata2[0]:
            time.sleep(waittime)
            outdata2 = snk.level()
        self.tb.stop()
        # Compare the datasets.
        self.assertComplexTuplesAlmostEqual(comb_results, outdata, 6)
        self.assertComplexTuplesAlmostEqual(comb_results2, outdata2, 6)
Example #3
0
    def test_000(self):
        """
        Generates nfilts sets of random complex data.
        Generates two sets of random taps for each filter.
        Applies one set of the random taps, gets some output,
        applies the second set of random taps, gets some more output,
        The output is then compared with a python-implemented
        convolution.
        """
        myrand = random.Random(123).random
        nfilts = 10
        ntaps = 5
        # Sets some of the taps to be all zeros.
        zero_filts1 = (3, 7)
        zero_filts2 = (1, 6, 9)
        ndatapoints = 100
        # Generate some random sets of data
        data_sets = []
        for i in range(0, nfilts):
            data_sets.append([(myrand()-0.5) + (myrand()-0.5)*(0+1j)
                              for k in range(0, ndatapoints)])
        # Join them together to pass to vector_source block
        data = []
        for dp in zip(*data_sets):
            data += dp
        # Generate some random taps.
        taps1 = []
        taps2 = []
        for i in range(0, nfilts):
            if i in zero_filts1:
                taps1.append([0]*ntaps)
            else:
                taps1.append([myrand()-0.5 for k in range(0, ntaps)])
            if i in zero_filts2:
                taps2.append([0]*ntaps)
            else:
                taps2.append([myrand()-0.5 for k in range(0, ntaps)])

        # Calculate results with a python-implemented convolution.
        results = []
        results2 = []
        for ds, ts, ts2 in zip(data_sets, taps1, taps2):
            results.append(convolution(ds[-len(ts):]+ds[:-1], ts))
            results2.append(convolution(ds[-len(ts):]+ds[:-1], ts2))
        # Convert results from 2D arrays to 1D arrays for ease of comparison.
        comb_results = []
        for rs in zip(*results):
            comb_results += rs
        comb_results2 = []
        for rs in zip(*results2):
            comb_results2 += rs
        # Construct the signal-processing chain.
        src = blocks.vector_source_c(data, True, nfilts)
        fb = filter.filterbank_vcvcf(taps1)
        v2s = blocks.vector_to_stream(gr.sizeof_gr_complex, nfilts)
        s2v = blocks.stream_to_vector(gr.sizeof_gr_complex, nfilts*ndatapoints)
        snk = blocks.probe_signal_vc(nfilts*ndatapoints)
        self.tb.connect(src, fb, v2s, s2v, snk)
        # Run the signal-processing chain.
        self.tb.start()
        all_zero = True
        outdata = None
        waittime = 0.001
        # Wait until we have some data.
        while (not outdata) or outdata[0]==0:
            time.sleep(waittime)
            outdata = snk.level()
        # Apply the second set of taps.
        fb.set_taps(taps2)
        outdata2 = None
        # Wait until we have new data.
        while (not outdata2) or outdata[0] == outdata2[0]:
            time.sleep(waittime)
            outdata2 = snk.level()
        self.tb.stop()
        # Compare the datasets.
        self.assertComplexTuplesAlmostEqual(comb_results, outdata, 6)
        self.assertComplexTuplesAlmostEqual(comb_results2, outdata2, 6)
    def __init__(self):
        gr.top_block.__init__(self, "Top Block")

        gr.top_block.__init__(self, "Top Block")

        parser = OptionParser(option_class=eng_option)
        parser.add_option("-N",
                          "--name",
                          type="string",
                          default="test",
                          help="Experiment name (to include in file name).")
        parser.add_option("-n",
                          "--ndata",
                          type="int",
                          default=128,
                          help="Number of data samples to collect at a time.")
        parser.add_option("-t",
                          "--ntrials",
                          type="int",
                          default=128,
                          help="Number of trials to run.")
        parser.add_option("-a",
                          "--args",
                          type="string",
                          default="",
                          help="UHD device address args [default=%default]")
        parser.add_option("",
                          "--spec",
                          type="string",
                          default="A:0 A:0",
                          help="Subdevice of UHD device where appropriate")
        parser.add_option("-A",
                          "--antenna",
                          type="string",
                          default=None,
                          help="select Rx Antenna where appropriate")
        parser.add_option(
            "-s",
            "--samp-rate",
            type="eng_float",
            default=1e6,
            help="set sample rate (bandwidth) [default=%default]")
        parser.add_option("-f",
                          "--freq",
                          type="eng_float",
                          default=2e9,
                          help="set frequency to FREQ [default=%default]",
                          metavar="FREQ")
        parser.add_option("-g",
                          "--rx-gain",
                          type="eng_float",
                          default=0,
                          help="set gain in dB (default is zero)")

        (options, args) = parser.parse_args()

        ##################################################
        # Variables
        ##################################################
        self.name = options.name
        self.ndata = options.ndata
        self.ntrials = options.ntrials
        self.samp_rate = options.samp_rate
        self.rx_gain = options.rx_gain
        self.freq = options.freq

        ##################################################
        # Blocks
        ##################################################
        self.uhd_usrp_source_0 = uhd.usrp_source(
            device_addr=options.args, stream_args=uhd.stream_args('fc32'))

        self.uhd_usrp_source_0.set_samp_rate(self.samp_rate)
        self.uhd_usrp_source_0.set_center_freq(self.freq, 0)
        self.uhd_usrp_source_0.set_gain(self.rx_gain, 0)
        self.s2v = blocks.stream_to_vector(gr.sizeof_gr_complex, self.ndata)
        self.blocks_probe_signal_vx_0 = blocks.probe_signal_vc(self.ndata)

        ##################################################
        # Connections
        ##################################################
        self.connect((self.uhd_usrp_source_0, 0), (self.s2v, 0),
                     (self.blocks_probe_signal_vx_0, 0))
    def __init__(self):
        gr.top_block.__init__(self, "Top Block")

        ##################################################
        # Variables
        ##################################################
        self.samp_rate = samp_rate = 1e6
        self.noise_level = noise_level = 1e-6

        ##################################################
        # Blocks
        ##################################################
        self.random_source = blocks.vector_source_b(
            map(int, np.random.randint(0, 255, 10000)), False)
        # self.modulator = digital.gfsk_mod(
        #     samples_per_symbol=2,
        #     sensitivity=1.0,
        #     bt=0.5,
        #     verbose=False,
        #     log=False,
        # )
        # self.modulator = digital.gmsk_mod(
        #     samples_per_symbol=2,
        #     bt=0.5,
        #     verbose=False,
        #     log=False,
        # )
        # self.modulator = digital.psk.psk_mod(
        #     constellation_points=8, # 2, 4, 8
        #     mod_code="gray",
        #     differential=True,
        #     samples_per_symbol=2,
        #     excess_bw=0.5,
        #     verbose=False,
        #     log=False,
        # )
        self.modulator = digital.qam.qam_mod(
            constellation_points=4,  # 4, 16, 64
            mod_code="gray",
            differential=True,
            samples_per_symbol=2,
            excess_bw=0.5,
            verbose=False,
            log=False,
        )
        self.channel_model = channels.channel_model(noise_voltage=noise_level,
                                                    frequency_offset=0.0,
                                                    epsilon=1.0,
                                                    taps=(1.0 + 1.0j, ),
                                                    noise_seed=0,
                                                    block_tags=False)
        num_samps = 2048
        self.stream_to_vector = blocks.stream_to_vector(
            gr.sizeof_gr_complex * 1, num_samps)
        self.probe_signal = blocks.probe_signal_vc(num_samps)

        ##################################################
        # Connections
        ##################################################
        self.connect(self.random_source, self.modulator, self.channel_model,
                     self.stream_to_vector, self.probe_signal)
Example #6
0
    def __init__(self, base_freq, samp_rate, num_output, use_fixed_freq,
                 freq_1, freq_2, freq_3):

        freq_1 = base_freq if freq_1 == -1 else freq_1
        freq_2 = base_freq if freq_2 == -1 else freq_2
        freq_3 = base_freq if freq_3 == -1 else freq_3

        if use_fixed_freq:
            if num_output == 1:
                if freq_2 != base_freq and freq_3 != base_freq:
                    gr.log.info(
                        'num_output(%d)<given freq, freq_2, freq_3 will be overlooked'
                        % num_output)
                if freq_1 > base_freq + samp_rate / 2 or freq_1 < base_freq - samp_rate / 2:
                    gr.log.info(
                        'given freq(%d), exceed freq_range(%d->%d), use auto_freq instead'
                        % (freq_1, base_freq - samp_rate / 2,
                           base_freq + samp_rate / 2))
                    freq_1 = base_freq
            if num_output == 2:
                if freq_3 != base_freq:
                    gr.log.info(
                        'num_output(%d)<given freq, freq_2, freq_3 will be overlooked'
                        % num_output)
                if freq_1 > base_freq + samp_rate / 2 or freq_1 < base_freq - samp_rate / 2:
                    gr.log.info(
                        'given freq(%d), exceed freq_range(%d->%d), use auto_freq instead'
                        % (freq_1, base_freq - samp_rate / 2,
                           base_freq + samp_rate / 2))
                    freq_1 = base_freq
                if freq_2 > base_freq + samp_rate / 2 or freq_2 < base_freq - samp_rate / 2:
                    gr.log.info(
                        'given freq(%d), exceed freq_range(%d->%d), use auto_freq instead'
                        % (freq_2, base_freq - samp_rate / 2,
                           base_freq + samp_rate / 2))
                    freq_2 = base_freq
            if num_output == 3:
                if freq_1 > base_freq + samp_rate / 2 or freq_1 < base_freq - samp_rate / 2:
                    gr.log.info(
                        'given freq(%d), exceed freq_range(%d->%d), use auto_freq instead'
                        % (freq_1, base_freq - samp_rate / 2,
                           base_freq + samp_rate / 2))
                    freq_1 = base_freq
                if freq_2 > base_freq + samp_rate / 2 or freq_2 < base_freq - samp_rate / 2:
                    gr.log.info(
                        'given freq(%d), exceed freq_range(%d->%d), use auto_freq instead'
                        % (freq_2, base_freq - samp_rate / 2,
                           base_freq + samp_rate / 2))
                    freq2 = base_freq
                if freq_3 > base_freq + samp_rate / 2 or freq_3 < base_freq - samp_rate / 2:
                    gr.log.info(
                        'given freq(%d), exceed freq_range(%d->%d), use auto_freq instead'
                        % (freq_3, base_freq - samp_rate / 2,
                           base_freq + samp_rate / 2))
                    freq_3 = base_freq
        ##################################################
        # Variables
        ##################################################
        self.base_freq = base_freq
        self.samp_rate = samp_rate
        self.num_output = num_output
        self.use_fixed_freq = use_fixed_freq
        self.freq_1 = freq_1
        self.freq_2 = freq_2
        self.freq_3 = freq_3
        self.fft_val = None

        ##################################################
        # Submodule
        ##################################################
        self.signal_sources = [
            analog.sig_source_c(
                self.samp_rate, analog.GR_COS_WAVE,
                getattr(self, 'freq_%d' % (i + 1)) - self.base_freq, 1, 0)
            for i in range(self.num_output)
        ]
        self.multiplies = [
            blocks.multiply_vcc(1) for i in range(self.num_output)
        ]
        # freq selector
        self.stream_to_vector = blocks.stream_to_vector(
            gr.sizeof_gr_complex * 1, 1024)
        self.fft = fft.fft_vcc(1024, True, (window.blackmanharris(1024)), True,
                               1)
        # self.vec_sink =  blocks.vector_sink_c(1024)
        self.samp_prob = blocks.probe_signal_vc(1024)

        gr.hier_block2.__init__(
            self,
            "freq_selector",
            gr.io_signature(1, 1, gr.sizeof_gr_complex),  # Input signature
            gr.io_signature(1, 1, gr.sizeof_gr_complex),
        )  # Output signature

        def _auto_freq_topk():
            while True:
                try:
                    # gr.log.info('0 set new max_freq:%d'%self.freq_1)
                    val = self.samp_prob.level()
                    # gr.log.info('1 set new max_freq:%d'%self.freq_1)
                    val = np.abs(np.array(val))
                    if self.fft_val is None:
                        self.fft_val = val
                    else:
                        self.fft_val = self.fft_val * 0.9 + val * 0.1
                    amp_idx = np.argmax(self.fft_val)
                    freq_1 = self.base_freq - self.samp_rate / 2 + (
                        amp_idx) / 1024 * self.samp_rate
                    if freq_1 != self.freq_1:
                        pass
                        # self.set_taps(self.base_freq, self.samp_rate, freq_1)
                        # gr.log.info('set new max_freq as %d for the %dth num of fft'%(self.freq_1, amp_idx))
                except AttributeError:
                    pass
                time.sleep(1.0 / (10000))

        _auto_freq_topk_thread = threading.Thread(target=_auto_freq_topk)
        _auto_freq_topk_thread.daemon = True
        _auto_freq_topk_thread.start()

        for i in range(self.num_output):
            self.connect((self, 0), (self.multiplies[i], 0))
            self.connect((self.signal_sources[i], 0), (self.multiplies[i], 1))
            self.connect((self.multiplies[i], 0), (self, i))
        self.connect((self, 0), (self.stream_to_vector, 0))
        self.connect((self.stream_to_vector, 0), (self.fft, 0))
        self.connect((self.fft, 0), (self.samp_prob, 0))
    def __init__(self, fliter_base, intep_deci, auto_gain, samp_rate,
                 cutoff_freq, trans_width, window, beta, dtype):
        """
        Args:
            [TODO]: complete args docstring.
        """

        self.gain_ratio = auto_gain
        self.lp_gain = np.float64(1)
        self.samp_rate = samp_rate
        self.cutoff_freq = cutoff_freq
        self.trans_width = trans_width
        self.window = window
        self.beta = beta
        self.amp_gain = None

        self.filter = fliter_base(
            intep_deci,
            firdes.low_pass(self.lp_gain, samp_rate, cutoff_freq, trans_width,
                            window, beta))

        if str(dtype) == "<type 'complex'>":
            gr.log.info("init auto gain low pass filter with complex type")
            self.samp_vector = blocks.stream_to_vector(gr.sizeof_gr_complex,
                                                       1024)
            self.samp_prob = blocks.probe_signal_vc(1024)
        else:
            gr.log.info("init auto gain low pass filter with float type")
            self.samp_vector = blocks.stream_to_vector(gr.sizeof_float, 1024)
            self.samp_prob = blocks.probe_signal_vf(1024)

        gr.hier_block2.__init__(
            self, "rational_resampler",
            gr.io_signature(
                1, 1,
                self.filter.input_signature().sizeof_stream_item(0)),
            gr.io_signature(
                1, 1,
                self.filter.output_signature().sizeof_stream_item(0)))

        def _auto_gain_function_probe():
            while True:
                try:
                    val = self.samp_prob.level()
                    val = np.abs(np.array(val))
                    amp_pp = max(val)
                    if amp_pp > 0:
                        if self.amp_gain is None:
                            self.amp_gain = (self.gain_ratio / amp_pp)
                        if abs(self.gain_ratio / amp_pp - 1) > 0.2:
                            self.amp_gain += (self.gain_ratio / amp_pp -
                                              1) * self.amp_gain
                            # gr.log.info('current gain:%f, target: %f.'%(self.get_lp_gain(), self.amp_gain))
                            self.set_lp_gain(self.amp_gain)
                    # print(amp_pp)
                    # print(amp_pp/0.5)
                except AttributeError:
                    pass
                time.sleep(1.0 / (100))

        _auto_gain_function_thread = threading.Thread(
            target=_auto_gain_function_probe)
        _auto_gain_function_thread.daemon = True
        _auto_gain_function_thread.start()

        # connections
        self.connect((self.filter, 0), (self.samp_vector, 0))
        self.connect((self.samp_vector, 0), (self.samp_prob, 0))
        self.connect(self, self.filter, self)
Example #8
0
    def __init__(self,
                 modulation,
                 code_rate,
                 num_samples,
                 code_type="convolutional"):
        gr.top_block.__init__(self, "Modulation and Coding Scheme")

        ##################################################
        # Variables
        ##################################################
        self.modulation = modulation
        self.code_rate = code_rate
        self.num_samples = num_samples
        self.code_type = code_type
        self.enc_cc = fec.dummy_encoder_make(2048)
        if code_rate != '1':
            self.enc_cc = fec.cc_encoder_make(2048, 7, 2, ([79, 109]), 0,
                                              fec.CC_STREAMING, False)
        self.const = digital.constellation_bpsk().base()
        self.puncpat = '11'
        self.snr_db = 10

        self.get_constellation_from_string(modulation)
        self.get_puncpat_from_string(code_rate)

        ##################################################
        # Blocks
        ##################################################
        self.fec_extended_encoder_0 = fec.extended_encoder(
            encoder_obj_list=self.enc_cc,
            threading='capillary',
            puncpat=self.puncpat)
        self.digital_chunks_to_symbols_xx_0 = digital.chunks_to_symbols_bc(
            (self.const.points()), 1)
        self.blocks_probe_signal_vx_0 = blocks.probe_signal_vc(
            self.num_samples)
        self.blocks_stream_to_vector_0 = blocks.stream_to_vector(
            gr.sizeof_gr_complex * 1, self.num_samples)
        self.analog_random_source_x_0 = blocks.vector_source_b(
            map(int, np.random.randint(0, 256, 100000)), True)
        self.channels_channel_model_0 = channels.channel_model(
            noise_voltage=np.sqrt(10.0**(-self.snr_db / 10.0) / 2.0),
            frequency_offset=0.0,
            epsilon=1.0,
            taps=(1.0, ),
            noise_seed=0,
            block_tags=False)

        ##################################################
        # Connections
        ##################################################
        self.connect((self.analog_random_source_x_0, 0),
                     (self.fec_extended_encoder_0, 0))
        self.connect((self.fec_extended_encoder_0, 0),
                     (self.digital_chunks_to_symbols_xx_0, 0))
        self.connect((self.digital_chunks_to_symbols_xx_0, 0),
                     (self.channels_channel_model_0, 0))
        self.connect((self.channels_channel_model_0, 0),
                     (self.blocks_stream_to_vector_0, 0))
        self.connect((self.blocks_stream_to_vector_0, 0),
                     (self.blocks_probe_signal_vx_0, 0))