diff options
Diffstat (limited to 'gr-digital/examples')
-rw-r--r-- | gr-digital/examples/berawgn.py | 34 | ||||
-rw-r--r-- | gr-digital/examples/example_costas.py | 42 | ||||
-rw-r--r-- | gr-digital/examples/example_fll.py | 48 | ||||
-rw-r--r-- | gr-digital/examples/example_timing.py | 84 | ||||
-rw-r--r-- | gr-digital/examples/gen_whitener.py | 11 | ||||
-rw-r--r-- | gr-digital/examples/narrowband/benchmark_add_channel.py | 17 | ||||
-rw-r--r-- | gr-digital/examples/narrowband/digital_bert_rx.py | 34 | ||||
-rw-r--r-- | gr-digital/examples/narrowband/digital_bert_tx.py | 27 | ||||
-rw-r--r-- | gr-digital/examples/narrowband/uhd_interface.py | 62 | ||||
-rw-r--r-- | gr-digital/examples/ofdm/benchmark_add_channel.py | 17 | ||||
-rw-r--r-- | gr-digital/examples/ofdm/receive_path.py | 19 | ||||
-rw-r--r-- | gr-digital/examples/ofdm/transmit_path.py | 9 | ||||
-rw-r--r-- | gr-digital/examples/ofdm/uhd_interface.py | 61 | ||||
-rw-r--r-- | gr-digital/examples/run_length.py | 18 | ||||
-rw-r--r-- | gr-digital/examples/snr_estimators.py | 57 |
15 files changed, 302 insertions, 238 deletions
diff --git a/gr-digital/examples/berawgn.py b/gr-digital/examples/berawgn.py index 082b73d83f..31ea8403b0 100644 --- a/gr-digital/examples/berawgn.py +++ b/gr-digital/examples/berawgn.py @@ -21,7 +21,6 @@ magnitude below what you chose for N_BITS. """ - import math import numpy from gnuradio import gr, digital @@ -45,20 +44,23 @@ except ImportError: N_BITS = 1e7 RAND_SEED = 42 + def berawgn(EbN0): """ Calculates theoretical bit error rate in AWGN (for BPSK and given Eb/N0) """ return 0.5 * erfc(math.sqrt(10**(float(EbN0) / 10))) + class BitErrors(gr.hier_block2): """ Two inputs: true and received bits. We compare them and add up the number of incorrect bits. Because integrate_ff() can only add up a certain number of values, the output is not a scalar, but a sequence of values, the sum of which is the BER. """ + def __init__(self, bits_per_byte): gr.hier_block2.__init__(self, "BitErrors", - gr.io_signature(2, 2, gr.sizeof_char), - gr.io_signature(1, 1, gr.sizeof_int)) + gr.io_signature(2, 2, gr.sizeof_char), + gr.io_signature(1, 1, gr.sizeof_int)) # Bit comparison comp = blocks.xor_bb() @@ -74,29 +76,32 @@ class BitErrors(gr.hier_block2): self) self.connect((self, 1), (comp, 1)) + class BERAWGNSimu(gr.top_block): " This contains the simulation flow graph " + def __init__(self, EbN0): gr.top_block.__init__(self) self.const = digital.qpsk_constellation() # Source is N_BITS bits, non-repeated - data = list(map(int, numpy.random.randint(0, self.const.arity(), N_BITS / self.const.bits_per_symbol()))) - src = blocks.vector_source_b(data, False) - mod = digital.chunks_to_symbols_bc((self.const.points()), 1) - add = blocks.add_vcc() + data = list(map(int, numpy.random.randint( + 0, self.const.arity(), N_BITS / self.const.bits_per_symbol()))) + src = blocks.vector_source_b(data, False) + mod = digital.chunks_to_symbols_bc((self.const.points()), 1) + add = blocks.add_vcc() noise = analog.noise_source_c(analog.GR_GAUSSIAN, self.EbN0_to_noise_voltage(EbN0), RAND_SEED) demod = digital.constellation_decoder_cb(self.const.base()) - ber = BitErrors(self.const.bits_per_symbol()) - self.sink = blocks.vector_sink_f() + ber = BitErrors(self.const.bits_per_symbol()) + self.sink = blocks.vector_sink_f() self.connect(src, mod, add, demod, ber, self.sink) self.connect(noise, (add, 1)) self.connect(src, (ber, 1)) def EbN0_to_noise_voltage(self, EbN0): """ Converts Eb/N0 to a complex noise voltage (assuming unit symbol power) """ - return 1.0 / math.sqrt(self.const.bits_per_symbol( * 10**(float(EbN0) / 10))) + return 1.0 / math.sqrt(self.const.bits_per_symbol(* 10**(float(EbN0) / 10))) def simulate_ber(EbN0): @@ -106,16 +111,17 @@ def simulate_ber(EbN0): fg.run() return numpy.sum(fg.sink.data()) + if __name__ == "__main__": EbN0_min = 0 EbN0_max = 15 - EbN0_range = list(range(EbN0_min, EbN0_max+1)) - ber_theory = [berawgn(x) for x in EbN0_range] + EbN0_range = list(range(EbN0_min, EbN0_max + 1)) + ber_theory = [berawgn(x) for x in EbN0_range] print("Simulating...") - ber_simu = [simulate_ber(x) for x in EbN0_range] + ber_simu = [simulate_ber(x) for x in EbN0_range] f = pyplot.figure() - s = f.add_subplot(1,1,1) + s = f.add_subplot(1, 1, 1) s.semilogy(EbN0_range, ber_theory, 'g-.', label="Theoretical") s.semilogy(EbN0_range, ber_simu, 'b-o', label="Simulated") s.set_title('BER Simulation') diff --git a/gr-digital/examples/example_costas.py b/gr-digital/examples/example_costas.py index 1db3287578..b7185ba974 100644 --- a/gr-digital/examples/example_costas.py +++ b/gr-digital/examples/example_costas.py @@ -24,6 +24,7 @@ except ImportError: print("Error: could not import pyplot (http://matplotlib.sourceforge.net/)") sys.exit(1) + class example_costas(gr.top_block): def __init__(self, N, sps, rolloff, ntaps, bw, noise, foffset, toffset, poffset): gr.top_block.__init__(self) @@ -31,8 +32,8 @@ class example_costas(gr.top_block): rrc_taps = filter.firdes.root_raised_cosine( sps, sps, 1.0, rolloff, ntaps) - data = 2.0*numpy.random.randint(0, 2, N) - 1.0 - data = numpy.exp(1j*poffset) * data + data = 2.0 * numpy.random.randint(0, 2, N) - 1.0 + data = numpy.exp(1j * poffset) * data self.src = blocks.vector_source_c(data.tolist(), False) self.rrc = filter.interp_fir_filter_ccf(sps, rrc_taps) @@ -45,28 +46,29 @@ class example_costas(gr.top_block): self.connect(self.src, self.rrc, self.chn, self.cst, self.vsnk_cst) self.connect(self.rrc, self.vsnk_src) - self.connect((self.cst,1), self.vsnk_frq) + self.connect((self.cst, 1), self.vsnk_frq) + def main(): parser = ArgumentParser(conflict_handler="resolve") parser.add_argument("-N", "--nsamples", type=int, default=2000, - help="Set the number of samples to process [default=%(default)r]") + help="Set the number of samples to process [default=%(default)r]") parser.add_argument("-S", "--sps", type=int, default=4, - help="Set the samples per symbol [default=%(default)r]") + help="Set the samples per symbol [default=%(default)r]") parser.add_argument("-r", "--rolloff", type=eng_float, default=0.35, - help="Set the rolloff factor [default=%(default)r]") - parser.add_argument("-W", "--bandwidth", type=eng_float, default=2*numpy.pi/100.0, - help="Set the loop bandwidth [default=%(default)r]") + help="Set the rolloff factor [default=%(default)r]") + parser.add_argument("-W", "--bandwidth", type=eng_float, default=2 * numpy.pi / 100.0, + help="Set the loop bandwidth [default=%(default)r]") parser.add_argument("-n", "--ntaps", type=int, default=45, - help="Set the number of taps in the filters [default=%(default)r]") + help="Set the number of taps in the filters [default=%(default)r]") parser.add_argument("--noise", type=eng_float, default=0.0, - help="Set the simulation noise voltage [default=%(default)r]") + help="Set the simulation noise voltage [default=%(default)r]") parser.add_argument("-f", "--foffset", type=eng_float, default=0.0, - help="Set the simulation's normalized frequency offset (in Hz) [default=%(default)r]") + help="Set the simulation's normalized frequency offset (in Hz) [default=%(default)r]") parser.add_argument("-t", "--toffset", type=eng_float, default=1.0, - help="Set the simulation's timing offset [default=%(default)r]") + help="Set the simulation's timing offset [default=%(default)r]") parser.add_argument("-p", "--poffset", type=eng_float, default=0.707, - help="Set the simulation's phase offset [default=%(default)r]") + help="Set the simulation's phase offset [default=%(default)r]") args = parser.parse_args() # Adjust N for the interpolation by sps @@ -81,21 +83,21 @@ def main(): data_src = numpy.array(put.vsnk_src.data()) # Convert the FLL's LO frequency from rads/sec to Hz - data_frq = numpy.array(put.vsnk_frq.data()) / (2.0*numpy.pi) + data_frq = numpy.array(put.vsnk_frq.data()) / (2.0 * numpy.pi) # adjust this to align with the data. - data_cst = numpy.array(3*[0,]+list(put.vsnk_cst.data())) + data_cst = numpy.array(3 * [0, ] + list(put.vsnk_cst.data())) # Plot the Costas loop's LO frequency - f1 = pyplot.figure(1, figsize=(12,10), facecolor='w') - s1 = f1.add_subplot(2,2,1) + f1 = pyplot.figure(1, figsize=(12, 10), facecolor='w') + s1 = f1.add_subplot(2, 2, 1) s1.plot(data_frq) s1.set_title("Costas LO") s1.set_xlabel("Samples") s1.set_ylabel("Frequency (normalized Hz)") # Plot the IQ symbols - s3 = f1.add_subplot(2,2,2) + s3 = f1.add_subplot(2, 2, 2) s3.plot(data_src.real, data_src.imag, "o") s3.plot(data_cst.real, data_cst.imag, "rx") s3.set_title("IQ") @@ -105,7 +107,7 @@ def main(): s3.set_ylim([-2, 2]) # Plot the symbols in time - s4 = f1.add_subplot(2,2,3) + s4 = f1.add_subplot(2, 2, 3) s4.set_position([0.125, 0.05, 0.775, 0.4]) s4.plot(data_src.real, "o-") s4.plot(data_cst.real, "rx-") @@ -115,9 +117,9 @@ def main(): pyplot.show() + if __name__ == "__main__": try: main() except KeyboardInterrupt: pass - diff --git a/gr-digital/examples/example_fll.py b/gr-digital/examples/example_fll.py index 021a3c1f6f..70b5bbd749 100644 --- a/gr-digital/examples/example_fll.py +++ b/gr-digital/examples/example_fll.py @@ -24,6 +24,7 @@ except ImportError: print("Error: could not from matplotlib import pyplot (http://matplotlib.sourceforge.net/)") sys.exit(1) + class example_fll(gr.top_block): def __init__(self, N, sps, rolloff, ntaps, bw, noise, foffset, toffset, poffset): gr.top_block.__init__(self) @@ -31,8 +32,8 @@ class example_fll(gr.top_block): rrc_taps = filter.firdes.root_raised_cosine( sps, sps, 1.0, rolloff, ntaps) - data = 2.0*numpy.random.randint(0, 2, N) - 1.0 - data = numpy.exp(1j*poffset) * data + data = 2.0 * numpy.random.randint(0, 2, N) - 1.0 + data = numpy.exp(1j * poffset) * data self.src = blocks.vector_source_c(data.tolist(), False) self.rrc = filter.interp_fir_filter_ccf(sps, rrc_taps) @@ -47,30 +48,31 @@ class example_fll(gr.top_block): self.connect(self.src, self.rrc, self.chn, self.fll, self.vsnk_fll) self.connect(self.rrc, self.vsnk_src) - self.connect((self.fll,1), self.vsnk_frq) - self.connect((self.fll,2), self.vsnk_phs) - self.connect((self.fll,3), self.vsnk_err) + self.connect((self.fll, 1), self.vsnk_frq) + self.connect((self.fll, 2), self.vsnk_phs) + self.connect((self.fll, 3), self.vsnk_err) + def main(): parser = ArgumentParser(conflict_handler="resolve") parser.add_argument("-N", "--nsamples", type=int, default=2000, - help="Set the number of samples to process [default=%(default)r]") + help="Set the number of samples to process [default=%(default)r]") parser.add_argument("-S", "--sps", type=int, default=4, - help="Set the samples per symbol [default=%(default)r]") + help="Set the samples per symbol [default=%(default)r]") parser.add_argument("-r", "--rolloff", type=eng_float, default=0.35, - help="Set the rolloff factor [default=%(default)r]") - parser.add_argument("-W", "--bandwidth", type=eng_float, default=2*numpy.pi/100.0, - help="Set the loop bandwidth [default=%(default)r]") + help="Set the rolloff factor [default=%(default)r]") + parser.add_argument("-W", "--bandwidth", type=eng_float, default=2 * numpy.pi / 100.0, + help="Set the loop bandwidth [default=%(default)r]") parser.add_argument("-n", "--ntaps", type=int, default=45, - help="Set the number of taps in the filters [default=%(default)r]") + help="Set the number of taps in the filters [default=%(default)r]") parser.add_argument("--noise", type=eng_float, default=0.0, - help="Set the simulation noise voltage [default=%(default)r]") + help="Set the simulation noise voltage [default=%(default)r]") parser.add_argument("-f", "--foffset", type=eng_float, default=0.2, - help="Set the simulation's normalized frequency offset (in Hz) [default=%(default)r]") + help="Set the simulation's normalized frequency offset (in Hz) [default=%(default)r]") parser.add_argument("-t", "--toffset", type=eng_float, default=1.0, - help="Set the simulation's timing offset [default=%(default)r]") + help="Set the simulation's timing offset [default=%(default)r]") parser.add_argument("-p", "--poffset", type=eng_float, default=0.0, - help="Set the simulation's phase offset [default=%(default)r]") + help="Set the simulation's phase offset [default=%(default)r]") args = parser.parse_args() # Adjust N for the interpolation by sps @@ -86,29 +88,29 @@ def main(): data_err = numpy.array(put.vsnk_err.data()) # Convert the FLL's LO frequency from rads/sec to Hz - data_frq = numpy.array(put.vsnk_frq.data()) / (2.0*numpy.pi) + data_frq = numpy.array(put.vsnk_frq.data()) / (2.0 * numpy.pi) # adjust this to align with the data. There are 2 filters of # ntaps long and the channel introduces another 4 sample delay. - data_fll = numpy.array(put.vsnk_fll.data()[2*args.ntaps-4:]) + data_fll = numpy.array(put.vsnk_fll.data()[2 * args.ntaps - 4:]) # Plot the FLL's LO frequency - f1 = pyplot.figure(1, figsize=(12,10)) - s1 = f1.add_subplot(2,2,1) + f1 = pyplot.figure(1, figsize=(12, 10)) + s1 = f1.add_subplot(2, 2, 1) s1.plot(data_frq) s1.set_title("FLL LO") s1.set_xlabel("Samples") s1.set_ylabel("Frequency (normalized Hz)") # Plot the FLL's error - s2 = f1.add_subplot(2,2,2) + s2 = f1.add_subplot(2, 2, 2) s2.plot(data_err) s2.set_title("FLL Error") s2.set_xlabel("Samples") s2.set_ylabel("FLL Loop error") # Plot the IQ symbols - s3 = f1.add_subplot(2,2,3) + s3 = f1.add_subplot(2, 2, 3) s3.plot(data_src.real, data_src.imag, "o") s3.plot(data_fll.real, data_fll.imag, "rx") s3.set_title("IQ") @@ -116,7 +118,7 @@ def main(): s3.set_ylabel("Imag part") # Plot the symbols in time - s4 = f1.add_subplot(2,2,4) + s4 = f1.add_subplot(2, 2, 4) s4.plot(data_src.real, "o-") s4.plot(data_fll.real, "rx-") s4.set_title("Symbols") @@ -125,9 +127,9 @@ def main(): pyplot.show() + if __name__ == "__main__": try: main() except KeyboardInterrupt: pass - diff --git a/gr-digital/examples/example_timing.py b/gr-digital/examples/example_timing.py index e2ff4a5649..f49576b2aa 100644 --- a/gr-digital/examples/example_timing.py +++ b/gr-digital/examples/example_timing.py @@ -24,6 +24,7 @@ except ImportError: print("Error: could not from matplotlib import pyplot (http://matplotlib.sourceforge.net/)") sys.exit(1) + class example_timing(gr.top_block): def __init__(self, N, sps, rolloff, ntaps, bw, noise, foffset, toffset, poffset, mode=0): @@ -35,10 +36,10 @@ class example_timing(gr.top_block): gain = bw nfilts = 32 rrc_taps_rx = filter.firdes.root_raised_cosine( - nfilts, sps*nfilts, 1.0, rolloff, ntaps*nfilts) + nfilts, sps * nfilts, 1.0, rolloff, ntaps * nfilts) - data = 2.0*numpy.random.randint(0, 2, N) - 1.0 - data = numpy.exp(1j*poffset) * data + data = 2.0 * numpy.random.randint(0, 2, N) - 1.0 + data = numpy.exp(1j * poffset) * data self.src = blocks.vector_source_c(data.tolist(), False) self.rrc = filter.interp_fir_filter_ccf(sps, rrc_taps) @@ -47,25 +48,25 @@ class example_timing(gr.top_block): if mode == 0: self.clk = digital.pfb_clock_sync_ccf(sps, gain, rrc_taps_rx, - nfilts, nfilts//2, 1) + nfilts, nfilts // 2, 1) self.taps = self.clk.taps() self.dtaps = self.clk.diff_taps() - self.delay = int(numpy.ceil(((len(rrc_taps)-1)//2 + - (len(self.taps[0])-1)//2 )//float(sps))) + 1 + self.delay = int(numpy.ceil(((len(rrc_taps) - 1) // 2 + + (len(self.taps[0]) - 1) // 2) // float(sps))) + 1 self.vsnk_err = blocks.vector_sink_f() self.vsnk_rat = blocks.vector_sink_f() self.vsnk_phs = blocks.vector_sink_f() - self.connect((self.clk,1), self.vsnk_err) - self.connect((self.clk,2), self.vsnk_rat) - self.connect((self.clk,3), self.vsnk_phs) + self.connect((self.clk, 1), self.vsnk_err) + self.connect((self.clk, 2), self.vsnk_rat) + self.connect((self.clk, 3), self.vsnk_phs) - else: # mode == 1 + else: # mode == 1 mu = 0.5 gain_mu = bw - gain_omega = 0.25*gain_mu*gain_mu + gain_omega = 0.25 * gain_mu * gain_mu omega_rel_lim = 0.02 self.clk = digital.clock_recovery_mm_cc(sps, gain_omega, mu, gain_mu, @@ -73,37 +74,38 @@ class example_timing(gr.top_block): self.vsnk_err = blocks.vector_sink_f() - self.connect((self.clk,1), self.vsnk_err) + self.connect((self.clk, 1), self.vsnk_err) self.vsnk_src = blocks.vector_sink_c() self.vsnk_clk = blocks.vector_sink_c() - self.connect(self.src, self.rrc, self.chn, self.off, self.clk, self.vsnk_clk) + self.connect(self.src, self.rrc, self.chn, + self.off, self.clk, self.vsnk_clk) self.connect(self.src, self.vsnk_src) def main(): parser = ArgumentParser(conflict_handler="resolve") parser.add_argument("-N", "--nsamples", type=int, default=2000, - help="Set the number of samples to process [default=%(default)r]") + help="Set the number of samples to process [default=%(default)r]") parser.add_argument("-S", "--sps", type=int, default=4, - help="Set the samples per symbol [default=%(default)r]") + help="Set the samples per symbol [default=%(default)r]") parser.add_argument("-r", "--rolloff", type=eng_float, default=0.35, - help="Set the rolloff factor [default=%(default)r]") - parser.add_argument("-W", "--bandwidth", type=eng_float, default=2*numpy.pi/100.0, - help="Set the loop bandwidth (PFB) or gain (M&M) [default=%(default)r]") + help="Set the rolloff factor [default=%(default)r]") + parser.add_argument("-W", "--bandwidth", type=eng_float, default=2 * numpy.pi / 100.0, + help="Set the loop bandwidth (PFB) or gain (M&M) [default=%(default)r]") parser.add_argument("-n", "--ntaps", type=int, default=45, - help="Set the number of taps in the filters [default=%(default)r]") + help="Set the number of taps in the filters [default=%(default)r]") parser.add_argument("--noise", type=eng_float, default=0.0, - help="Set the simulation noise voltage [default=%(default)r]") + help="Set the simulation noise voltage [default=%(default)r]") parser.add_argument("-f", "--foffset", type=eng_float, default=0.0, - help="Set the simulation's normalized frequency offset (in Hz) [default=%(default)r]") + help="Set the simulation's normalized frequency offset (in Hz) [default=%(default)r]") parser.add_argument("-t", "--toffset", type=eng_float, default=1.0, - help="Set the simulation's timing offset [default=%(default)r]") + help="Set the simulation's timing offset [default=%(default)r]") parser.add_argument("-p", "--poffset", type=eng_float, default=0.0, - help="Set the simulation's phase offset [default=%(default)r]") + help="Set the simulation's phase offset [default=%(default)r]") parser.add_argument("-M", "--mode", type=int, default=0, - help="Set the recovery mode (0: polyphase, 1: M&M) [default=%(default)r]") + help="Set the recovery mode (0: polyphase, 1: M&M) [default=%(default)r]") args = parser.parse_args() # Adjust N for the interpolation by sps @@ -124,10 +126,10 @@ def main(): data_rat = numpy.array(put.vsnk_rat.data()[20:]) data_phs = numpy.array(put.vsnk_phs.data()[20:]) - f1 = pyplot.figure(1, figsize=(12,10), facecolor='w') + f1 = pyplot.figure(1, figsize=(12, 10), facecolor='w') # Plot the IQ symbols - s1 = f1.add_subplot(2,2,1) + s1 = f1.add_subplot(2, 2, 1) s1.plot(data_src.real, data_src.imag, "bo") s1.plot(data_clk.real, data_clk.imag, "ro") s1.set_title("IQ") @@ -139,7 +141,7 @@ def main(): # Plot the symbols in time delay = put.delay m = len(data_clk.real) - s2 = f1.add_subplot(2,2,2) + s2 = f1.add_subplot(2, 2, 2) s2.plot(data_src.real, "bs", markersize=10, label="Input") s2.plot(data_clk.real[delay:], "ro", label="Recovered") s2.set_title("Symbols") @@ -148,7 +150,7 @@ def main(): s2.legend() # Plot the clock recovery loop's error - s3 = f1.add_subplot(2,2,3) + s3 = f1.add_subplot(2, 2, 3) s3.plot(data_err, label="Error") s3.plot(data_rat, 'r', label="Update rate") s3.set_title("Clock Recovery Loop Error") @@ -158,26 +160,27 @@ def main(): s3.legend() # Plot the clock recovery loop's error - s4 = f1.add_subplot(2,2,4) + s4 = f1.add_subplot(2, 2, 4) s4.plot(data_phs) s4.set_title("Clock Recovery Loop Filter Phase") s4.set_xlabel("Samples") s4.set_ylabel("Filter Phase") - diff_taps = put.dtaps ntaps = len(diff_taps[0]) nfilts = len(diff_taps) - t = numpy.arange(0, ntaps*nfilts) + t = numpy.arange(0, ntaps * nfilts) - f3 = pyplot.figure(3, figsize=(12,10), facecolor='w') - s31 = f3.add_subplot(2,1,1) - s32 = f3.add_subplot(2,1,2) + f3 = pyplot.figure(3, figsize=(12, 10), facecolor='w') + s31 = f3.add_subplot(2, 1, 1) + s32 = f3.add_subplot(2, 1, 2) s31.set_title("Differential Filters") s32.set_title("FFT of Differential Filters") - for i,d in enumerate(diff_taps): - D = 20.0*numpy.log10(1e-20+abs(numpy.fft.fftshift(numpy.fft.fft(d, 10000)))) + for i, d in enumerate(diff_taps): + D = 20.0 * \ + numpy.log10( + 1e-20 + abs(numpy.fft.fftshift(numpy.fft.fft(d, 10000)))) s31.plot(t[i::nfilts].real, d, "-o") s32.plot(D) s32.set_ylim([-120, 10]) @@ -189,10 +192,10 @@ def main(): data_err = numpy.array(put.vsnk_err.data()[20:]) - f1 = pyplot.figure(1, figsize=(12,10), facecolor='w') + f1 = pyplot.figure(1, figsize=(12, 10), facecolor='w') # Plot the IQ symbols - s1 = f1.add_subplot(2,2,1) + s1 = f1.add_subplot(2, 2, 1) s1.plot(data_src.real, data_src.imag, "o") s1.plot(data_clk.real, data_clk.imag, "ro") s1.set_title("IQ") @@ -202,7 +205,7 @@ def main(): s1.set_ylim([-2, 2]) # Plot the symbols in time - s2 = f1.add_subplot(2,2,2) + s2 = f1.add_subplot(2, 2, 2) s2.plot(data_src.real, "bs", markersize=10, label="Input") s2.plot(data_clk.real, "ro", label="Recovered") s2.set_title("Symbols") @@ -211,7 +214,7 @@ def main(): s2.legend() # Plot the clock recovery loop's error - s3 = f1.add_subplot(2,2,3) + s3 = f1.add_subplot(2, 2, 3) s3.plot(data_err) s3.set_title("Clock Recovery Loop Error") s3.set_xlabel("Samples") @@ -219,6 +222,7 @@ def main(): pyplot.show() + if __name__ == "__main__": try: main() diff --git a/gr-digital/examples/gen_whitener.py b/gr-digital/examples/gen_whitener.py index a6261d021b..6798597131 100644 --- a/gr-digital/examples/gen_whitener.py +++ b/gr-digital/examples/gen_whitener.py @@ -1,18 +1,19 @@ #!/usr/bin/env python # # Copyright 2011,2013 Free Software Foundation, Inc. -# +# # This file is part of GNU Radio -# +# # SPDX-License-Identifier: GPL-3.0-or-later # -# +# from gnuradio import gr from gnuradio import blocks from argparse import ArgumentParser import sys + class my_graph(gr.top_block): def __init__(self): @@ -25,6 +26,7 @@ class my_graph(gr.top_block): self.dst = blocks.vector_sink_s() self.connect(src, head, self.dst) + if __name__ == '__main__': try: tb = my_graph() @@ -34,10 +36,9 @@ if __name__ == '__main__': for s in tb.dst.data(): f.write("%3d, " % (s & 0xff,)) f.write("%3d, " % ((s >> 8) & 0xff,)) - i = i+2 + i = i + 2 if i % 16 == 0: f.write('\n') except KeyboardInterrupt: pass - diff --git a/gr-digital/examples/narrowband/benchmark_add_channel.py b/gr-digital/examples/narrowband/benchmark_add_channel.py index 351aae29cd..725138f85d 100644 --- a/gr-digital/examples/narrowband/benchmark_add_channel.py +++ b/gr-digital/examples/narrowband/benchmark_add_channel.py @@ -15,7 +15,10 @@ from gnuradio import eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser -import random, math, sys +import random +import math +import sys + class my_top_block(gr.top_block): def __init__(self, ifile, ofile, options): @@ -24,7 +27,7 @@ class my_top_block(gr.top_block): SNR = 10.0**(options.snr / 10.0) frequency_offset = options.frequency_offset time_offset = options.time_offset - phase_offset = options.phase_offset*(math.pi / 180.0) + phase_offset = options.phase_offset * (math.pi / 180.0) # calculate noise voltage from SNR power_in_signal = abs(options.tx_amplitude)**2 @@ -35,9 +38,9 @@ class my_top_block(gr.top_block): #self.throttle = blocks.throttle(gr.sizeof_gr_complex, options.sample_rate) self.channel = channels.channel_model(noise_voltage, frequency_offset, - time_offset, noise_seed=-random.randint(0,100000)) + time_offset, noise_seed=-random.randint(0, 100000)) self.phase = blocks.multiply_const_cc(complex(math.cos(phase_offset), - math.sin(phase_offset))) + math.sin(phase_offset))) self.snk = blocks.file_sink(gr.sizeof_gr_complex, ofile) self.connect(self.src, self.channel, self.phase, self.snk) @@ -50,7 +53,8 @@ class my_top_block(gr.top_block): def main(): # Create Options Parser: usage = "benchmack_add_channel.py [options] <input file> <output file>" - parser = OptionParser (usage=usage, option_class=eng_option, conflict_handler="resolve") + parser = OptionParser( + usage=usage, option_class=eng_option, conflict_handler="resolve") parser.add_option("-n", "--snr", type="eng_float", default=30, help="set the SNR of the channel in dB [default=%default]") parser.add_option("", "--seed", action="store_true", default=False, @@ -67,7 +71,7 @@ def main(): default=1.0, help="tell the simulator the signal amplitude [default=%default]") - (options, args) = parser.parse_args () + (options, args) = parser.parse_args() if len(args) != 2: parser.print_help(sys.stderr) @@ -86,6 +90,7 @@ def main(): tb.start() # start flow graph tb.wait() # wait for it to finish + if __name__ == '__main__': try: main() diff --git a/gr-digital/examples/narrowband/digital_bert_rx.py b/gr-digital/examples/narrowband/digital_bert_rx.py index e20b798ee2..7b951c4569 100644 --- a/gr-digital/examples/narrowband/digital_bert_rx.py +++ b/gr-digital/examples/narrowband/digital_bert_rx.py @@ -13,7 +13,9 @@ from gnuradio import gr, eng_notation from optparse import OptionParser from gnuradio.eng_option import eng_option import threading -import sys, time, math +import sys +import time +import math from gnuradio import digital from gnuradio import blocks @@ -23,6 +25,7 @@ from uhd_interface import uhd_receiver n2s = eng_notation.num_to_str + class status_thread(threading.Thread): def __init__(self, tb): threading.Thread.__init__(self) @@ -34,14 +37,13 @@ class status_thread(threading.Thread): def run(self): while not self.done: print("Freq. Offset: {0:5.0f} Hz Timing Offset: {1:10.1f} ppm Estimated SNR: {2:4.1f} dB BER: {3:g}".format( - tb.frequency_offset(), tb.timing_offset()*1e6, tb.snr(), tb.ber())) + tb.frequency_offset(), tb.timing_offset() * 1e6, tb.snr(), tb.ber())) try: time.sleep(1.0) except KeyboardInterrupt: self.done = True - class bert_receiver(gr.hier_block2): def __init__(self, bitrate, constellation, samples_per_symbol, @@ -50,7 +52,8 @@ class bert_receiver(gr.hier_block2): verbose, log): gr.hier_block2.__init__(self, "bert_receive", - gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature + # Input signature + gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(0, 0, 0)) # Output signature self._bitrate = bitrate @@ -70,7 +73,8 @@ class bert_receiver(gr.hier_block2): self.connect(self._demod.time_recov, self._snr_probe) # Descramble BERT sequence. A channel error will create 3 incorrect bits - self._descrambler = digital.descrambler_bb(0x8A, 0x7F, 7) # CCSDS 7-bit descrambler + self._descrambler = digital.descrambler_bb( + 0x8A, 0x7F, 7) # CCSDS 7-bit descrambler # Measure BER by the density of 0s in the stream self._ber = digital.probe_density_b(1.0 / self._symbol_rate) @@ -78,7 +82,7 @@ class bert_receiver(gr.hier_block2): self.connect(self, self._demod, self._descrambler, self._ber) def frequency_offset(self): - return self._demod.freq_recov.get_frequency()*self._sample_rate/(2*math.pi) + return self._demod.freq_recov.get_frequency() * self._sample_rate / (2 * math.pi) def timing_offset(self): return self._demod.time_recov.clock_rate() @@ -87,8 +91,7 @@ class bert_receiver(gr.hier_block2): return self._snr_probe.snr() def ber(self): - return (1.0-self._ber.density()) / 3.0 - + return (1.0 - self._ber.density()) / 3.0 class rx_psk_block(gr.top_block): @@ -99,7 +102,8 @@ class rx_psk_block(gr.top_block): self._demodulator_class = demod # Get demod_kwargs - demod_kwargs = self._demodulator_class.extract_kwargs_from_options(options) + demod_kwargs = self._demodulator_class.extract_kwargs_from_options( + options) # demodulator self._demodulator = self._demodulator_class(**demod_kwargs) @@ -114,7 +118,8 @@ class rx_psk_block(gr.top_block): options.samples_per_symbol = self._source._sps elif(options.from_file is not None): - self._source = blocks.file_source(gr.sizeof_gr_complex, options.from_file) + self._source = blocks.file_source( + gr.sizeof_gr_complex, options.from_file) else: self._source = blocks.null_source(gr.sizeof_gr_complex) @@ -154,7 +159,7 @@ class rx_psk_block(gr.top_block): def get_options(demods): parser = OptionParser(option_class=eng_option, conflict_handler="resolve") - parser.add_option("","--from-file", default=None, + parser.add_option("", "--from-file", default=None, help="input file of samples to demod") parser.add_option("-m", "--modulation", type="choice", choices=list(demods.keys()), default='psk', @@ -165,10 +170,11 @@ def get_options(demods): parser.add_option("-S", "--samples-per-symbol", type="float", default=2, help="set samples/symbol [default=%default]") if not parser.has_option("--verbose"): - parser.add_option("-v", "--verbose", action="store_true", default=False) + parser.add_option("-v", "--verbose", + action="store_true", default=False) if not parser.has_option("--log"): parser.add_option("", "--log", action="store_true", default=False, - help="Log all parts of flow graph to files (CAUTION: lots of data)") + help="Log all parts of flow graph to files (CAUTION: lots of data)") uhd_receiver.add_options(parser) @@ -185,7 +191,7 @@ def get_options(demods): if __name__ == "__main__": - print ("""Warning: this example in its current shape is deprecated and + print("""Warning: this example in its current shape is deprecated and will be removed or fundamentally reworked in a coming GNU Radio release.""") demods = digital.modulation_utils.type_1_demods() diff --git a/gr-digital/examples/narrowband/digital_bert_tx.py b/gr-digital/examples/narrowband/digital_bert_tx.py index fe8ad0671f..d609534271 100644 --- a/gr-digital/examples/narrowband/digital_bert_tx.py +++ b/gr-digital/examples/narrowband/digital_bert_tx.py @@ -21,25 +21,30 @@ from uhd_interface import uhd_transmitter n2s = eng_notation.num_to_str + class bert_transmit(gr.hier_block2): def __init__(self, constellation, samples_per_symbol, differential, excess_bw, gray_coded, verbose, log): gr.hier_block2.__init__(self, "bert_transmit", - gr.io_signature(0, 0, 0), # Output signature - gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Input signature + # Output signature + gr.io_signature(0, 0, 0), + gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Input signature # Create BERT data bit stream - self._bits = blocks.vector_source_b([1,], True) # Infinite stream of ones - self._scrambler = digital.scrambler_bb(0x8A, 0x7F, 7) # CCSDS 7-bit scrambler + self._bits = blocks.vector_source_b( + [1, ], True) # Infinite stream of ones + self._scrambler = digital.scrambler_bb( + 0x8A, 0x7F, 7) # CCSDS 7-bit scrambler self._mod = digital.generic_mod(constellation, differential, samples_per_symbol, gray_coded, excess_bw, verbose, log) - self._pack = blocks.unpacked_to_packed_bb(self._mod.bits_per_symbol(), gr.GR_MSB_FIRST) + self._pack = blocks.unpacked_to_packed_bb( + self._mod.bits_per_symbol(), gr.GR_MSB_FIRST) self.connect(self._bits, self._scrambler, self._pack, self._mod, self) @@ -66,11 +71,11 @@ class tx_psk_block(gr.top_block): options.samples_per_symbol = self._sink._sps elif(options.to_file is not None): - self._sink = blocks.file_sink(gr.sizeof_gr_complex, options.to_file) + self._sink = blocks.file_sink( + gr.sizeof_gr_complex, options.to_file) else: self._sink = blocks.null_sink(gr.sizeof_gr_complex) - self._transmitter = bert_transmit(self._modulator._constellation, options.samples_per_symbol, options.differential, @@ -95,10 +100,11 @@ def get_options(mods): help="Select modulation bit rate (default=%default)") parser.add_option("-S", "--samples-per-symbol", type="float", default=2, help="set samples/symbol [default=%default]") - parser.add_option("","--to-file", default=None, + parser.add_option("", "--to-file", default=None, help="Output file for modulated samples") if not parser.has_option("--verbose"): - parser.add_option("-v", "--verbose", action="store_true", default=False) + parser.add_option("-v", "--verbose", + action="store_true", default=False) if not parser.has_option("--log"): parser.add_option("", "--log", action="store_true", default=False) @@ -114,8 +120,9 @@ def get_options(mods): return (options, args) + if __name__ == "__main__": - print ("""Warning: this example in its current shape is deprecated and + print("""Warning: this example in its current shape is deprecated and will be removed or fundamentally reworked in a coming GNU Radio release.""") mods = digital.modulation_utils.type_1_mods() diff --git a/gr-digital/examples/narrowband/uhd_interface.py b/gr-digital/examples/narrowband/uhd_interface.py index 54d152cd7c..7a541296ee 100644 --- a/gr-digital/examples/narrowband/uhd_interface.py +++ b/gr-digital/examples/narrowband/uhd_interface.py @@ -16,6 +16,7 @@ from optparse import OptionParser import sys + def add_freq_option(parser): """ Hackery that has the -f / --freq option set both tx_freq and rx_freq @@ -30,14 +31,17 @@ def add_freq_option(parser): help="set Tx and/or Rx frequency to FREQ [default=%default]", metavar="FREQ") + class uhd_interface(object): def __init__(self, istx, args, sym_rate, sps, freq=None, lo_offset=None, gain=None, spec=None, antenna=None, clock_source=None): if(istx): - self.u = uhd.usrp_sink(device_addr=args, stream_args=uhd.stream_args('fc32')) + self.u = uhd.usrp_sink( + device_addr=args, stream_args=uhd.stream_args('fc32')) else: - self.u = uhd.usrp_source(device_addr=args, stream_args=uhd.stream_args('fc32')) + self.u = uhd.usrp_source( + device_addr=args, stream_args=uhd.stream_args('fc32')) # Set clock source if(clock_source): @@ -52,7 +56,7 @@ class uhd_interface(object): self.u.set_antenna(antenna, 0) self._args = args - self._ant = antenna + self._ant = antenna self._spec = spec self._gain = self.set_gain(gain) self._lo_offset = lo_offset @@ -69,7 +73,7 @@ class uhd_interface(object): sps = actual_samp_rate / sym_rate if(sps < 2): - req_sps +=1 + req_sps += 1 else: actual_sps = sps break @@ -93,10 +97,10 @@ class uhd_interface(object): if gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() - gain = float(g.start()+g.stop()) / 2 + gain = float(g.start() + g.stop()) / 2 print("\nNo gain specified.") print("Setting gain to %f (from [%f, %f])" % - (gain, g.start(), g.stop())) + (gain, g.start(), g.stop())) self.u.set_gain(gain, 0) return gain @@ -111,20 +115,21 @@ class uhd_interface(object): return freq else: frange = self.u.get_freq_range() - sys.stderr.write(("\nRequested frequency (%f) out or range [%f, %f]\n") % \ - (freq, frange.start(), frange.stop())) + sys.stderr.write(("\nRequested frequency (%f) out or range [%f, %f]\n") % + (freq, frange.start(), frange.stop())) sys.exit(1) #-------------------------------------------------------------------# # TRANSMITTER #-------------------------------------------------------------------# + class uhd_transmitter(uhd_interface, gr.hier_block2): def __init__(self, args, sym_rate, sps, freq=None, lo_offset=None, gain=None, spec=None, antenna=None, clock_source=None, verbose=False): gr.hier_block2.__init__(self, "uhd_transmitter", - gr.io_signature(1,1,gr.sizeof_gr_complex), - gr.io_signature(0,0,0)) + gr.io_signature(1, 1, gr.sizeof_gr_complex), + gr.io_signature(0, 0, 0)) # Set up the UHD interface as a transmitter uhd_interface.__init__(self, True, args, sym_rate, sps, @@ -153,21 +158,23 @@ class uhd_transmitter(uhd_interface, gr.hier_block2): help="set transmit gain in dB (default is midpoint)") parser.add_option("-C", "--clock-source", type="string", default=None, help="select clock source (e.g. 'external') [default=%default]") - parser.add_option("-v", "--verbose", action="store_true", default=False) + parser.add_option("-v", "--verbose", + action="store_true", default=False) def _print_verbage(self): """ Prints information about the UHD transmitter """ print("\nUHD Transmitter:") - print("Args: %s" % (self._args)) - print("Freq: %sHz" % (eng_notation.num_to_str(self._freq))) - print("LO Offset: %sHz" % (eng_notation.num_to_str(self._lo_offset)) ) + print("Args: %s" % (self._args)) + print("Freq: %sHz" % (eng_notation.num_to_str(self._freq))) + print("LO Offset: %sHz" % + (eng_notation.num_to_str(self._lo_offset))) print("Gain: %f dB" % (self._gain)) print("Sample Rate: %ssps" % (eng_notation.num_to_str(self._rate))) - print("Antenna: %s" % (self._ant)) - print("Subdev Spec: %s" % (self._spec)) - print("Clock Source: %s" % (self._clock_source)) + print("Antenna: %s" % (self._ant)) + print("Subdev Spec: %s" % (self._spec)) + print("Clock Source: %s" % (self._clock_source)) #-------------------------------------------------------------------# # RECEIVER @@ -178,8 +185,8 @@ class uhd_receiver(uhd_interface, gr.hier_block2): def __init__(self, args, sym_rate, sps, freq=None, lo_offset=None, gain=None, spec=None, antenna=None, clock_source=None, verbose=False): gr.hier_block2.__init__(self, "uhd_receiver", - gr.io_signature(0,0,0), - gr.io_signature(1,1,gr.sizeof_gr_complex)) + gr.io_signature(0, 0, 0), + gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Set up the UHD interface as a receiver uhd_interface.__init__(self, False, args, sym_rate, sps, @@ -209,19 +216,20 @@ class uhd_receiver(uhd_interface, gr.hier_block2): parser.add_option("-C", "--clock-source", type="string", default=None, help="select clock source (e.g. 'external') [default=%default]") if not parser.has_option("--verbose"): - parser.add_option("-v", "--verbose", action="store_true", default=False) + parser.add_option("-v", "--verbose", + action="store_true", default=False) def _print_verbage(self): """ Prints information about the UHD transmitter """ print("\nUHD Receiver:") - print("UHD Args: %s" % (self._args)) - print("Freq: %sHz" % (eng_notation.num_to_str(self._freq))) - print("LO Offset: %sHz" % (eng_notation.num_to_str(self._lo_offset)) ) + print("UHD Args: %s" % (self._args)) + print("Freq: %sHz" % (eng_notation.num_to_str(self._freq))) + print("LO Offset: %sHz" % + (eng_notation.num_to_str(self._lo_offset))) print("Gain: %f dB" % (self._gain)) print("Sample Rate: %ssps" % (eng_notation.num_to_str(self._rate))) - print("Antenna: %s" % (self._ant)) - print("Spec: %s" % (self._spec)) - print("Clock Source: %s" % (self._clock_source)) - + print("Antenna: %s" % (self._ant)) + print("Spec: %s" % (self._spec)) + print("Clock Source: %s" % (self._clock_source)) diff --git a/gr-digital/examples/ofdm/benchmark_add_channel.py b/gr-digital/examples/ofdm/benchmark_add_channel.py index 6355bcc828..fec315e8d7 100644 --- a/gr-digital/examples/ofdm/benchmark_add_channel.py +++ b/gr-digital/examples/ofdm/benchmark_add_channel.py @@ -15,7 +15,10 @@ from gnuradio import eng_notation from gnuradio.eng_option import eng_option from optparse import OptionParser -import random, math, sys +import random +import math +import sys + class my_top_block(gr.top_block): def __init__(self, ifile, ofile, options): @@ -23,7 +26,7 @@ class my_top_block(gr.top_block): SNR = 10.0**(options.snr / 10.0) time_offset = options.time_offset - phase_offset = options.phase_offset*(math.pi / 180.0) + phase_offset = options.phase_offset * (math.pi / 180.0) # calculate noise voltage from SNR power_in_signal = abs(options.tx_amplitude)**2 @@ -37,9 +40,9 @@ class my_top_block(gr.top_block): #self.throttle = blocks.throttle(gr.sizeof_gr_complex, options.sample_rate) self.channel = channels.channel_model(noise_voltage, frequency_offset, - time_offset, noise_seed=-random.randint(0,100000)) + time_offset, noise_seed=-random.randint(0, 100000)) self.phase = blocks.multiply_const_cc(complex(math.cos(phase_offset), - math.sin(phase_offset))) + math.sin(phase_offset))) self.snk = blocks.file_sink(gr.sizeof_gr_complex, ofile) self.connect(self.src, self.channel, self.phase, self.snk) @@ -52,7 +55,8 @@ class my_top_block(gr.top_block): def main(): # Create Options Parser: usage = "benchmack_add_channel.py [options] <input file> <output file>" - parser = OptionParser (usage=usage, option_class=eng_option, conflict_handler="resolve") + parser = OptionParser( + usage=usage, option_class=eng_option, conflict_handler="resolve") parser.add_option("-n", "--snr", type="eng_float", default=30, help="set the SNR of the channel in dB [default=%default]") parser.add_option("", "--seed", action="store_true", default=False, @@ -71,7 +75,7 @@ def main(): default=1.0, help="tell the simulator the signal amplitude [default=%default]") - (options, args) = parser.parse_args () + (options, args) = parser.parse_args() if len(args) != 2: parser.print_help(sys.stderr) @@ -94,6 +98,7 @@ def main(): tb.start() # start flow graph tb.wait() # wait for it to finish + if __name__ == '__main__': try: main() diff --git a/gr-digital/examples/ofdm/receive_path.py b/gr-digital/examples/ofdm/receive_path.py index 90b572a08f..e46056c245 100644 --- a/gr-digital/examples/ofdm/receive_path.py +++ b/gr-digital/examples/ofdm/receive_path.py @@ -19,6 +19,7 @@ import sys # receive path # ///////////////////////////////////////////////////////////////////////////// + class receive_path(gr.hier_block2): def __init__(self, rx_callback, options): @@ -26,12 +27,13 @@ class receive_path(gr.hier_block2): gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(0, 0, 0)) + # make a copy so we can destructively modify + options = copy.copy(options) - options = copy.copy(options) # make a copy so we can destructively modify - - self._verbose = options.verbose - self._log = options.log - self._rx_callback = rx_callback # this callback is fired when there's a packet available + self._verbose = options.verbose + self._log = options.log + # this callback is fired when there's a packet available + self._rx_callback = rx_callback # receiver self.ofdm_rx = digital.ofdm_demod(options, @@ -40,7 +42,7 @@ class receive_path(gr.hier_block2): # Carrier Sensing Blocks alpha = 0.001 thresh = 30 # in dB, will have to adjust - self.probe = analog.probe_avg_mag_sqrd_c(thresh,alpha) + self.probe = analog.probe_avg_mag_sqrd_c(thresh, alpha) self.connect(self, self.ofdm_rx) self.connect(self.ofdm_rx, self.probe) @@ -53,7 +55,7 @@ class receive_path(gr.hier_block2): """ Return True if we think carrier is present. """ - #return self.probe.level() > X + # return self.probe.level() > X return self.probe.unmuted() def carrier_threshold(self): @@ -79,7 +81,8 @@ class receive_path(gr.hier_block2): normal.add_option("-W", "--bandwidth", type="eng_float", default=500e3, help="set symbol bandwidth [default=%default]") - normal.add_option("-v", "--verbose", action="store_true", default=False) + normal.add_option("-v", "--verbose", + action="store_true", default=False) expert.add_option("", "--log", action="store_true", default=False, help="Log all parts of flow graph to files (CAUTION: lots of data)") diff --git a/gr-digital/examples/ofdm/transmit_path.py b/gr-digital/examples/ofdm/transmit_path.py index 0982bb688c..83ac6a19a4 100644 --- a/gr-digital/examples/ofdm/transmit_path.py +++ b/gr-digital/examples/ofdm/transmit_path.py @@ -20,6 +20,7 @@ import sys # transmit path # ///////////////////////////////////////////////////////////////////////////// + class transmit_path(gr.hier_block2): def __init__(self, options): ''' @@ -30,10 +31,11 @@ class transmit_path(gr.hier_block2): gr.io_signature(0, 0, 0), gr.io_signature(1, 1, gr.sizeof_gr_complex)) - options = copy.copy(options) # make a copy so we can destructively modify + # make a copy so we can destructively modify + options = copy.copy(options) - self._verbose = options.verbose # turn verbose mode on/off - self._tx_amplitude = options.tx_amplitude # digital amp sent to radio + self._verbose = options.verbose # turn verbose mode on/off + self._tx_amplitude = options.tx_amplitude # digital amp sent to radio self.ofdm_tx = digital.ofdm_mod(options, msgq_limit=4, @@ -87,4 +89,3 @@ class transmit_path(gr.hier_block2): Prints information about the transmit path """ print("Tx amplitude %s" % (self._tx_amplitude)) - diff --git a/gr-digital/examples/ofdm/uhd_interface.py b/gr-digital/examples/ofdm/uhd_interface.py index c354473267..ca0f0e2598 100644 --- a/gr-digital/examples/ofdm/uhd_interface.py +++ b/gr-digital/examples/ofdm/uhd_interface.py @@ -16,6 +16,7 @@ from optparse import OptionParser import sys + def add_freq_option(parser): """ Hackery that has the -f / --freq option set both tx_freq and rx_freq @@ -30,14 +31,17 @@ def add_freq_option(parser): help="set Tx and/or Rx frequency to FREQ [default=%default]", metavar="FREQ") + class uhd_interface(object): def __init__(self, istx, args, bandwidth, freq=None, lo_offset=None, gain=None, spec=None, antenna=None, clock_source=None): if(istx): - self.u = uhd.usrp_sink(device_addr=args, stream_args=uhd.stream_args('fc32')) + self.u = uhd.usrp_sink( + device_addr=args, stream_args=uhd.stream_args('fc32')) else: - self.u = uhd.usrp_source(device_addr=args, stream_args=uhd.stream_args('fc32')) + self.u = uhd.usrp_source( + device_addr=args, stream_args=uhd.stream_args('fc32')) # Set clock source to external. if(clock_source): @@ -52,7 +56,7 @@ class uhd_interface(object): self.u.set_antenna(antenna, 0) self._args = args - self._ant = antenna + self._ant = antenna self._spec = spec self._gain = self.set_gain(gain) self._lo_offset = lo_offset @@ -73,10 +77,10 @@ class uhd_interface(object): if gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() - gain = float(g.start()+g.stop()) / 2 + gain = float(g.start() + g.stop()) / 2 print("\nNo gain specified.") print("Setting gain to %f (from [%f, %f])" % - (gain, g.start(), g.stop())) + (gain, g.start(), g.stop())) self.u.set_gain(gain, 0) return gain @@ -92,20 +96,21 @@ class uhd_interface(object): return freq else: frange = self.u.get_freq_range() - sys.stderr.write(("\nRequested frequency (%f) out or range [%f, %f]\n") % \ - (freq, frange.start(), frange.stop())) + sys.stderr.write(("\nRequested frequency (%f) out or range [%f, %f]\n") % + (freq, frange.start(), frange.stop())) sys.exit(1) #-------------------------------------------------------------------# # TRANSMITTER #-------------------------------------------------------------------# + class uhd_transmitter(uhd_interface, gr.hier_block2): def __init__(self, args, bandwidth, freq=None, lo_offset=None, gain=None, spec=None, antenna=None, clock_source=None, verbose=False): gr.hier_block2.__init__(self, "uhd_transmitter", - gr.io_signature(1,1,gr.sizeof_gr_complex), - gr.io_signature(0,0,0)) + gr.io_signature(1, 1, gr.sizeof_gr_complex), + gr.io_signature(0, 0, 0)) # Set up the UHD interface as a transmitter uhd_interface.__init__(self, True, args, bandwidth, @@ -134,22 +139,23 @@ class uhd_transmitter(uhd_interface, gr.hier_block2): help="set transmit gain in dB (default is midpoint)") parser.add_option("-C", "--clock-source", type="string", default=None, help="select clock source (e.g. 'external') [default=%default]") - parser.add_option("-v", "--verbose", action="store_true", default=False) + parser.add_option("-v", "--verbose", + action="store_true", default=False) def _print_verbage(self): """ Prints information about the UHD transmitter """ print("\nUHD Transmitter:") - print("UHD Args: %s" % (self._args)) - print("Freq: %sHz" % (eng_notation.num_to_str(self._freq))) - print("LO Offset: %sHz" % (eng_notation.num_to_str(self._lo_offset))) + print("UHD Args: %s" % (self._args)) + print("Freq: %sHz" % (eng_notation.num_to_str(self._freq))) + print("LO Offset: %sHz" % + (eng_notation.num_to_str(self._lo_offset))) print("Gain: %f dB" % (self._gain)) print("Sample Rate: %ssps" % (eng_notation.num_to_str(self._rate))) - print("Antenna: %s" % (self._ant)) - print("Subdev Sec: %s" % (self._spec)) - print("Clock Source: %s" % (self._clock_source)) - + print("Antenna: %s" % (self._ant)) + print("Subdev Sec: %s" % (self._spec)) + print("Clock Source: %s" % (self._clock_source)) #-------------------------------------------------------------------# @@ -161,8 +167,8 @@ class uhd_receiver(uhd_interface, gr.hier_block2): def __init__(self, args, bandwidth, freq=None, lo_offset=None, gain=None, spec=None, antenna=None, clock_source=None, verbose=False): gr.hier_block2.__init__(self, "uhd_receiver", - gr.io_signature(0,0,0), - gr.io_signature(1,1,gr.sizeof_gr_complex)) + gr.io_signature(0, 0, 0), + gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Set up the UHD interface as a receiver uhd_interface.__init__(self, False, args, bandwidth, @@ -192,19 +198,20 @@ class uhd_receiver(uhd_interface, gr.hier_block2): parser.add_option("-C", "--clock-source", type="string", default=None, help="select clock source (e.g. 'external') [default=%default]") if not parser.has_option("--verbose"): - parser.add_option("-v", "--verbose", action="store_true", default=False) + parser.add_option("-v", "--verbose", + action="store_true", default=False) def _print_verbage(self): """ Prints information about the UHD transmitter """ print("\nUHD Receiver:") - print("UHD Args: %s" % (self._args)) - print("Freq: %sHz" % (eng_notation.num_to_str(self._freq))) - print("LO Offset: %sHz" % (eng_notation.num_to_str(self._lo_offset))) + print("UHD Args: %s" % (self._args)) + print("Freq: %sHz" % (eng_notation.num_to_str(self._freq))) + print("LO Offset: %sHz" % + (eng_notation.num_to_str(self._lo_offset))) print("Gain: %f dB" % (self._gain)) print("Sample Rate: %ssps" % (eng_notation.num_to_str(self._rate))) - print("Antenna: %s" % (self._ant)) - print("Subdev Sec: %s" % (self._spec)) - print("Clock Source: %s" % (self._clock_source)) - + print("Antenna: %s" % (self._ant)) + print("Subdev Sec: %s" % (self._spec)) + print("Clock Source: %s" % (self._clock_source)) diff --git a/gr-digital/examples/run_length.py b/gr-digital/examples/run_length.py index 0d9477012c..8d84b60533 100644 --- a/gr-digital/examples/run_length.py +++ b/gr-digital/examples/run_length.py @@ -12,6 +12,7 @@ from optparse import OptionParser import sys + def main(): parser = OptionParser() parser.add_option("-f", "--file", default=None, @@ -33,7 +34,7 @@ def main(): for ch in f.read(): x = ord(ch) bytes = bytes + 1 - for i in range(7,-1,-1): + for i in range(7, -1, -1): bits = bits + 1 t = (x >> i) & 0x1 if t == current: @@ -42,29 +43,30 @@ def main(): if count > 0: if len(runs) < count: for j in range(count - len(runs)): - runs.append(0); - runs[count-1] = runs[count-1] + 1 + runs.append(0) + runs[count - 1] = runs[count - 1] + 1 - current = 1-current; + current = 1 - current count = 1 # Deal with last run at EOF if len(runs) < count and count > 0: for j in range(count - len(runs)): - runs.append(0); - runs[count-1] = runs[count-1] + 1 + runs.append(0) + runs[count - 1] = runs[count - 1] + 1 chk = 0 print("Bytes read: ", bytes) print("Bits read: ", bits) print() for i in range(len(runs)): - chk = chk + runs[i]*(i+1) - print("Runs of length", i+1, ":", runs[i]) + chk = chk + runs[i] * (i + 1) + print("Runs of length", i + 1, ":", runs[i]) print() print("Sum of runs:", chk, "bits") print() print("Maximum run length is", len(runs), "bits") + if __name__ == "__main__": main() diff --git a/gr-digital/examples/snr_estimators.py b/gr-digital/examples/snr_estimators.py index fbaf06a5ab..bc622bfd31 100644 --- a/gr-digital/examples/snr_estimators.py +++ b/gr-digital/examples/snr_estimators.py @@ -38,6 +38,7 @@ For an explination of the online algorithms, see: http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Higher-order_statistics ''' + def online_skewness(data): n = 0 mean = 0 @@ -46,52 +47,57 @@ def online_skewness(data): for n in range(len(data)): delta = data[n] - mean - delta_n = delta / (n+1) + delta_n = delta / (n + 1) term1 = delta * delta_n * n mean = mean + delta_n M3 = M3 + term1 * delta_n * (n - 1) - 3 * delta_n * M2 M2 = M2 + term1 - return scipy.sqrt(len(data))*M3 / scipy.power(M2, 3.0 / 2.0); + return scipy.sqrt(len(data)) * M3 / scipy.power(M2, 3.0 / 2.0) + def snr_est_simple(signal): s = scipy.mean(abs(signal)**2) - n = 2*scipy.var(abs(signal)) + n = 2 * scipy.var(abs(signal)) snr_rat = s / n - return 10.0*scipy.log10(snr_rat), snr_rat + return 10.0 * scipy.log10(snr_rat), snr_rat + def snr_est_skew(signal): y1 = scipy.mean(abs(signal)) y2 = scipy.mean(scipy.real(signal**2)) - y3 = (y1*y1 - y2) + y3 = (y1 * y1 - y2) y4 = online_skewness(signal.real) #y4 = stats.skew(abs(signal.real)) - skw = y4*y4 / (y2*y2*y2); - s = y1*y1 - n = 2*(y3 + skw*s) + skw = y4 * y4 / (y2 * y2 * y2) + s = y1 * y1 + n = 2 * (y3 + skw * s) snr_rat = s / n - return 10.0*scipy.log10(snr_rat), snr_rat + return 10.0 * scipy.log10(snr_rat), snr_rat + def snr_est_m2m4(signal): M2 = scipy.mean(abs(signal)**2) M4 = scipy.mean(abs(signal)**4) - snr_rat = scipy.sqrt(2*M2*M2 - M4) / (M2 - scipy.sqrt(2*M2*M2 - M4)) - return 10.0*scipy.log10(snr_rat), snr_rat + snr_rat = scipy.sqrt(2 * M2 * M2 - M4) / \ + (M2 - scipy.sqrt(2 * M2 * M2 - M4)) + return 10.0 * scipy.log10(snr_rat), snr_rat + def snr_est_svr(signal): N = len(signal) ssum = 0 msum = 0 for i in range(1, N): - ssum += (abs(signal[i])**2)*(abs(signal[i-1])**2) + ssum += (abs(signal[i])**2) * (abs(signal[i - 1])**2) msum += (abs(signal[i])**4) - savg = (1.0 / (float(N-1.0)))*ssum - mavg = (1.0 / (float(N-1.0)))*msum + savg = (1.0 / (float(N - 1.0))) * ssum + mavg = (1.0 / (float(N - 1.0))) * msum beta = savg / (mavg - savg) - snr_rat = ((beta - 1) + scipy.sqrt(beta*(beta-1))) - return 10.0*scipy.log10(snr_rat), snr_rat + snr_rat = ((beta - 1) + scipy.sqrt(beta * (beta - 1))) + return 10.0 * scipy.log10(snr_rat), snr_rat def main(): @@ -104,7 +110,6 @@ def main(): "m2m4": snr_est_m2m4, "svr": snr_est_svr} - parser = OptionParser(option_class=eng_option, conflict_handler="resolve") parser.add_option("-N", "--nsamples", type="int", default=10000, help="Set the number of samples to process [default=%default]") @@ -118,13 +123,13 @@ def main(): choices=list(gr_estimators.keys()), default="simple", help="Estimator type {0} [default=%default]".format( list(gr_estimators.keys()))) - (options, args) = parser.parse_args () + (options, args) = parser.parse_args() N = options.nsamples xx = scipy.random.randn(N) xy = scipy.random.randn(N) - bits =2*scipy.complex64(scipy.random.randint(0, 2, N)) - 1 - #bits =(2*scipy.complex64(scipy.random.randint(0, 2, N)) - 1) + \ + bits = 2 * scipy.complex64(scipy.random.randint(0, 2, N)) - 1 + # bits =(2*scipy.complex64(scipy.random.randint(0, 2, N)) - 1) + \ # 1j*(2*scipy.complex64(scipy.random.randint(0, 2, N)) - 1) snr_known = list() @@ -134,7 +139,7 @@ def main(): # when to issue an SNR tag; can be ignored in this example. ntag = 10000 - n_cpx = xx + 1j*xy + n_cpx = xx + 1j * xy py_est = py_estimators[options.type] gr_est = gr_estimators[options.type] @@ -142,17 +147,17 @@ def main(): SNR_min = options.snr_min SNR_max = options.snr_max SNR_step = options.snr_step - SNR_dB = scipy.arange(SNR_min, SNR_max+SNR_step, SNR_step) + SNR_dB = scipy.arange(SNR_min, SNR_max + SNR_step, SNR_step) for snr in SNR_dB: SNR = 10.0**(snr / 10.0) - scale = scipy.sqrt(2*SNR) + scale = scipy.sqrt(2 * SNR) yy = bits + n_cpx / scale print("SNR: ", snr) Sknown = scipy.mean(yy**2) Nknown = scipy.var(n_cpx / scale) snr0 = Sknown / Nknown - snr0dB = 10.0*scipy.log10(snr0) + snr0dB = 10.0 * scipy.log10(snr0) snr_known.append(float(snr0dB)) snrdB, snr = py_est(yy) @@ -169,7 +174,7 @@ def main(): snr_gr.append(gr_snr.snr()) f1 = pyplot.figure(1) - s1 = f1.add_subplot(1,1,1) + s1 = f1.add_subplot(1, 1, 1) s1.plot(SNR_dB, snr_known, "k-o", linewidth=2, label="Known") s1.plot(SNR_dB, snr_python, "b-o", linewidth=2, label="Python") s1.plot(SNR_dB, snr_gr, "g-o", linewidth=2, label="GNU Radio") @@ -180,7 +185,7 @@ def main(): s1.legend() f2 = pyplot.figure(2) - s2 = f2.add_subplot(1,1,1) + s2 = f2.add_subplot(1, 1, 1) s2.plot(yy.real, yy.imag, 'o') pyplot.show() |