Beispiel #1
0
def main():
    mod_type = 'QPSK'
    SNR = 1
    max_SNR = 15
    sym_num = 10000  # Символов в одной генерации ПСП
    snr_step = 1
    num_iter = int(max_SNR / snr_step)  # Количество генераций ПСП
    prsGen = PrsGenerate(prs_type='Default')
    demode = Demodulator(psk_type=mod_type)
    tester = BerTester(prs_type='Default')
    plotBER = np.zeros(num_iter, dtype=np.float)
    plotSNR = np.zeros(num_iter, dtype=np.float)

    k = 0
    while True:

        if k >= num_iter:
            break
        elif k < num_iter:
            demode_buf = ''
            prs_data = ''
            tester.reset()

            # Генерация ПСП
            for j in range(sym_num):
                prs_data += prsGen.generate()
            # Модулирование -> + абгш -> демодулирование
            noise_sigma = sigma_calc(SNR, 0.5, mod_type)
            for j in range(len(prs_data) // 2):
                I, Q = modulator(prs_data[2 * j:2 * j + 2])
                x, y = awgn_generate()
                noisy_I = I + x * noise_sigma
                noisy_Q = Q + y * noise_sigma
                demode_buf += demode.hard_decision(noisy_I, noisy_Q)
            # ber tester
            for j in range(len(demode_buf)):
                bit, err = tester.check(demode_buf[j])
            print('Prs data =', prs_data)
            print('HD data  =', demode_buf)
            a = hamming_distance(prs_data, demode_buf)
            print('Err after decode =', a)
            print('Bit cntr =', bit)
            print('Err cntr =', err)
            if bit != 0:
                print('BER = ' + str(err / bit))
            plotBER[k] = err / bit
            plotSNR[k] = SNR
        print('SNR =', SNR)
        SNR += snr_step
        k += 1

    # plot create
    plt.semilogy(plotSNR, plotBER)
    plt.xlabel('SNR(db)')
    plt.ylabel('BER')
    plt.grid()
    plt.xticks([i for i in range(0, max_SNR)])
    plt.show()
Beispiel #2
0
def test_qpsk(noise_strength):
    lista = [1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1]
    modulator = Modulator()
    demodulator = Demodulator()
    channel = Channel()

    signal = modulator.make_qpsk_mod(lista)
    signal.show_signal()
    signal = channel.send_signal(signal, noise_strength)
    signal.show_signal()
    bits = demodulator.make_qpsk_demod(signal, channel)
    print(bits)
Beispiel #3
0
def qpsk_img_compute_distorsion(noise_strength):
    bit_list = FileIO("computerA\\cloud.png").read_from_file()
    modulator = Modulator()
    demodulator = Demodulator()
    channel = Channel()
    signal = modulator.make_qpsk_mod(bit_list)

    # With noise=0.1 the image is completely shattered, with noise=0.01 the image is fine
    signal = channel.send_signal(signal, noise_strength)

    result_bits = demodulator.make_qpsk_demod(signal, channel)
    print("Number of distorted bits: ",
          utils.compute_distorted_bits(bit_list, result_bits))
Beispiel #4
0
def qpsk_send_png(noise_strength):
    bit_list = FileIO("computerA\\cloud.png").read_from_file()
    modulator = Modulator()
    demodulator = Demodulator()
    channel = Channel()
    signal = modulator.make_qpsk_mod(bit_list)
    signal.show_signal()

    # With noise=0.1 the image is completely shattered, with noise=0.01 the image is fine
    signal = channel.send_signal(signal, noise_strength)

    result_bits = demodulator.make_qpsk_demod(signal, channel)

    FileIO("computerB\\cloud.png").write_to_file(result_bits)
Beispiel #5
0
def test_8psk(noise_strength):
    lista = [
        0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1
    ]
    modulator = Modulator()
    demodulator = Demodulator()
    channel = Channel()

    signal = modulator.make_8psk_mod(lista)
    signal.show_signal()
    signal = channel.send_signal(signal, noise_strength)
    signal.show_signal()
    bits = demodulator.make_8psk_demod(signal, channel)
    print("Komputer A: ", lista)
    print("Komputer B: ", bits)
Beispiel #6
0
def test_bpsk(noise_strength):
    in_bits = [1, 0, 1, 0, 1, 0, 0]
    modulator = Modulator()
    demodulator = Demodulator()
    channel = Channel()

    signal: WirelessSignal
    # make modulation
    signal = modulator.make_bpsk_mod(in_bits)
    signal.show_signal()
    # send signal over the channel
    signal = channel.send_signal(signal, noise_strength)
    signal.show_signal()
    # demodulate the signal
    out_bits = demodulator.make_bpsk_demod(signal, channel)

    print(out_bits)
Beispiel #7
0
def test_bpsk_picture(noise_strength):
    # tests sending picture from computerA to computerB with bpsk
    modulator = Modulator()
    demodulator = Demodulator()
    channel = Channel()

    # send signal to modulator
    bits = FileIO("computerA\\cloud.png").read_from_file()
    print(bits)
    signal = modulator.make_bpsk_mod(bits)
    signal.show_signal()

    # send signal to channel
    signal = channel.send_signal(signal, noise_strength)

    # demodulator receives signal
    result_bits = demodulator.make_bpsk_demod(signal, channel)

    FileIO("computerB\\cloud_bpsk.png").write_to_file(result_bits)
Beispiel #8
0
def test_16psk_picture(noise_strength):
    # tests sending png from computerA to computerB with 16psk
    modulator = Modulator()
    demodulator = Demodulator()
    channel = Channel()

    # send signal to modulator
    bits = FileIO("computerA\\cloud.png").read_from_file()
    signal = modulator.make_16psk_mod(bits)
    signal.show_signal()

    # send signal to channel
    signal = channel.send_signal(signal, noise_strength)

    # demodulator receives signal
    result_bits = demodulator.make_16psk_demod(signal, channel)

    picture_pbm_result = PbmClass()
    picture_pbm_result.read_wireless_signal_from_bits(result_bits)
    FileIO("computerB\\recieved_16psk_cloud.png").write_to_file(result_bits)
    def qpsk(input_bits, noise):
        """
        Perform simple qpsk modulation-demodulation and return received bits.
        Parameters
        ----------
        input_bits Bits to be trensfered.
        noise Noise strength.

        Returns
        -------
        bits Received bits.
        """
        modulator = Modulator()
        demodulator = Demodulator()
        channel = Channel()
        signal = modulator.make_qpsk_mod(input_bits)

        signal = channel.send_signal(signal, noise)

        result_bits = demodulator.make_qpsk_demod(signal, channel)
        return result_bits
Beispiel #10
0
def wrong_bits_test():
    noise_strength = [0.001, 0.009, 0.01, 0.03, 0.05, 0.1, 0.2, 0.5]
    bpsk = {}
    qpsk = {}
    psk8 = {}
    psk16 = {}

    # tests sending png from computerA to computerB with 16psk
    modulator = Modulator()
    demodulator = Demodulator()
    channel = Channel()

    # send signal to modulator
    bits = FileIO("computerA\\cloud.png").read_from_file()

    for noise in noise_strength:
        # bpsk
        signal1 = modulator.make_bpsk_mod(bits)
        # send signal to channel
        signal1 = channel.send_signal(signal1, noise)
        result_bits1 = demodulator.make_bpsk_demod(signal1, channel)

        # qpsk
        signal2 = modulator.make_qpsk_mod(bits)
        # send signal to channel
        signal2 = channel.send_signal(signal2, noise)
        result_bits2 = demodulator.make_qpsk_demod(signal2, channel)

        # 8psk
        signal3 = modulator.make_8psk_mod(bits)
        # send signal to channel
        signal3 = channel.send_signal(signal3, noise)
        result_bits3 = demodulator.make_8psk_demod(signal3, channel)

        # 16psk
        signal4 = modulator.make_16psk_mod(bits)
        # send signal to channel
        signal4 = channel.send_signal(signal4, noise)
        result_bits4 = demodulator.make_16psk_demod(signal4, channel)

        # wrong bits counters
        wrong_bpsk = 0
        wrong_qpsk = 0
        wrong_8psk = 0
        wrong_16psk = 0

        for i in range(len(result_bits1)):
            # check how many wrong bits
            if bits[i] != result_bits1[i]:
                wrong_bpsk += 1
            if bits[i] != result_bits2[i]:
                wrong_qpsk += 1
            if bits[i] != result_bits3[i]:
                wrong_8psk += 1
            if bits[i] != result_bits4[i]:
                wrong_16psk += 1

        bpsk[noise] = wrong_bpsk
        qpsk[noise] = wrong_qpsk
        psk8[noise] = wrong_8psk
        psk16[noise] = wrong_16psk

    out_file = open('wrong_bits.csv', 'w', newline='')
    headers = ['noise', 'bpsk', 'qpsk', 'psk8', 'psk16', 'oryginal_size']
    writer = csv.DictWriter(out_file,
                            delimiter=';',
                            lineterminator='\n',
                            fieldnames=headers)

    writer.writeheader()

    for i in range(0, 8):
        writer.writerow({
            'noise': noise_strength[i],
            'bpsk': str(list(bpsk.values())[i]).replace('.', ','),
            'qpsk': str(list(qpsk.values())[i]).replace('.', ','),
            'psk8': str(list(psk8.values())[i]).replace('.', ','),
            'psk16': str(list(psk16.values())[i]).replace('.', ','),
            'oryginal_size': len(bits)
        })

    out_file.close()
Beispiel #11
0
def code1_2():
    mod_type = 'QPSK'
    code_type = 'Intelsat 3/4'
    mod_order = {'BPSK': 1, 'QPSK': 2, '8PSK': 3}
    sym_rate = {'Intelsat 1/2': 2, 'Intelsat 3/4': 4, 'Intelsat 7/8': 8}
    SNR = 6
    max_SNR = 15
    SNR_step = 1
    sym_num = 20000  # Символов в одной генерации ПСП
    max_back_step = 180  # Макс. количество шагов назад для декодера
    cur_back_step = 180  # Текущее количество шагов назад для декодера
    encoder_len = 63  # Длина регистра кодера: 1/2 = 36, 3/4 = 63
    del_sym = encoder_len + max_back_step  # Количесво 0, которое надо удалить вначале декод-й последовательно
    num_iter = int((max_SNR - SNR) / SNR_step)  # Количество генераций ПСП
    prsGen = PrsGenerate(prs_type='Default')
    demode = Demodulator(psk_type=mod_type)
    encoder = ConvolutionEncoder(code_type=code_type)
    decoder = FanoDecoder(delta_T=5, max_back_step=max_back_step, code_type=code_type)
    tester = BerTester(prs_type='Default')
    plotBER = np.zeros(num_iter, dtype=np.float)
    plotSNR = np.zeros(num_iter, dtype=np.float)

    k = 0
    while True:

        if k >= num_iter:
            break
        elif k < num_iter:
            demode_buf = ''
            prs_data = ''
            encode_seq = ''
            decode_seq = ''
            tester.reset()
            encoder.reset()
            decoder.reset()
            prsGen.reset()

            # Генерация ПСП -> кодирование ->
            for j in range(sym_num):
                prs_sym = prsGen.generate()
                prs_data += prs_sym
                encode_word = encoder.encode(prs_sym)
                encode_seq += encode_word

            # -> Модулирование -> + абгш -> демодулирование ->
            noise_sigma = sigma_calc(SNR, 0.5, mod_type)
            for j in range(len(encode_seq) // mod_order[mod_type]):
                I, Q = modulator(encode_seq[mod_order[mod_type] * j:mod_order[mod_type] * j + mod_order[mod_type]])
                x, y = awgn_generate()
                noisy_I = I + x * noise_sigma
                noisy_Q = Q + y * noise_sigma
                demode_buf += demode.hard_decision(noisy_I, noisy_Q)

            # -> Декодирование
            for j in range(len(demode_buf) // sym_rate[code_type]):
                decode_seq += decoder.decode(demode_buf[sym_rate[code_type] * j:sym_rate[code_type] * j + sym_rate[code_type]], cur_back_step)

            # ber tester
            decode_seq = decode_seq[del_sym:-200]
            for j in range(len(decode_seq)):
                bit, err = tester.check(decode_seq[j])

            noise_sigma = sigma_calc(SNR, 0.5, mod_type)
            for j in range(sym_num):
                # Генерация ПСП -> кодирование ->
                prs_sym = prsGen.generate()
                prs_data += prs_sym
                encode_word = encoder.encode(prs_sym)
                encode_seq += encode_word

                # -> Модулирование -> + абгш -> демодулирование ->
                I, Q = modulator(encode_word)
                x, y = awgn_generate()
                noisy_I = I + x * noise_sigma
                noisy_Q = Q + y * noise_sigma
                demode_sym = demode.hard_decision(noisy_I, noisy_Q)
                demode_buf += demode_sym

                # -> Декодирование
                decode_seq += decoder.decode(demode_sym, cur_back_step)

            print('Encode seq =', encode_seq)
            print('Demode seq =', demode_buf)
            a = hamming_distance(encode_seq, demode_buf)
            print('Err after demode =', a)

            print('Prs data   =', prs_data[:-del_sym])
            print('Decode seq =', decode_seq)
            a = hamming_distance(prs_data[:-(del_sym+200)], decode_seq)
            print('Err after decode =', a)
            print('Bit cntr =', bit)
            print('Err cntr =', err)

            # b = ''
            # for j in range(len(encode_seq)):
            #     if encode_seq[j] != demode_buf[j]:
            #         b += str(j) + ', '
            # print(b)
            if bit != 0:
                print('BER = ' + str(err / bit))
            plotBER[k] = err / bit
            plotSNR[k] = SNR
        print('SNR =', SNR)
        SNR += SNR_step
        k += 1

    # plot create
    plt.semilogy(plotSNR, plotBER)
    plt.xlabel('SNR(db)')
    plt.ylabel('BER')
    plt.grid()
    plt.xticks([i for i in range(0, max_SNR)])
    plt.show()
Beispiel #12
0
    def make_16psk_mod(self, bits):
        """ Generates WirelessSignal object from given list of bits in 16-phase-shift keying.
            WirelessSignal objects contains linspace and sinwave.

           Parameters
           ----------
           bits : list
               List of bits to generate sinwave from it

           Returns
           -------
           signal : WirelessSignal
               Signal generated from bits
        """

        signalBits = bits.copy()

        # We need to check if signal's number of bits can be defined as 4n
        one_number_of_bits = False
        two_number_of_bits = False
        three_number_of_bits = False
        # Deal with rest equal 3
        if len(signalBits) % 4 == 3:
            signalBits.append(0)
            three_number_of_bits = True
        # Deal with rest equal 2
        if len(signalBits) % 4 == 2:
            signalBits.append(0)
            signalBits.append(0)
            two_number_of_bits = True
        # Deal with rest equal 1
        if len(signalBits) % 4 == 1:
            signalBits.append(0)
            signalBits.append(0)
            signalBits.append(0)
            one_number_of_bits = True

        start_time = 0
        end_time = self.__period * len(signalBits) / 4
        timeline = np.arange(start_time, end_time, 1 / self.__sample_rate)

        theta1 = np.pi / 16  # coding 0000
        theta2 = 3 * np.pi / 16  # coding 0001
        theta3 = 5 * np.pi / 16  # coding 0010
        theta4 = 7 * np.pi / 16  # coding 0011
        theta5 = 9 * np.pi / 16  # coding 0100
        theta6 = 11 * np.pi / 16  # coding 0101
        theta7 = 13 * np.pi / 16  # coding 0110
        theta8 = 15 * np.pi / 16  # coding 0111
        theta9 = 17 * np.pi / 16  # coding 1000
        theta10 = 19 * np.pi / 16  # coding 1001
        theta11 = 21 * np.pi / 16  # coding 1010
        theta12 = 23 * np.pi / 16  # coding 1011
        theta13 = 25 * np.pi / 16  # coding 1100
        theta14 = 27 * np.pi / 16  # coding 1101
        theta15 = 29 * np.pi / 16  # coding 1110
        theta16 = 31 * np.pi / 16  # coding 1111
        # Generate corresponding sinwaves with length of period
        linspace = np.arange(0, self.__period, 1 / self.__sample_rate)
        sinwave1 = self.__amplitude * np.sin(2 * np.pi * self.__frequency *
                                             linspace + theta1)
        sinwave2 = self.__amplitude * np.sin(2 * np.pi * self.__frequency *
                                             linspace + theta2)
        sinwave3 = self.__amplitude * np.sin(2 * np.pi * self.__frequency *
                                             linspace + theta3)
        sinwave4 = self.__amplitude * np.sin(2 * np.pi * self.__frequency *
                                             linspace + theta4)
        sinwave5 = self.__amplitude * np.sin(2 * np.pi * self.__frequency *
                                             linspace + theta5)
        sinwave6 = self.__amplitude * np.sin(2 * np.pi * self.__frequency *
                                             linspace + theta6)
        sinwave7 = self.__amplitude * np.sin(2 * np.pi * self.__frequency *
                                             linspace + theta7)
        sinwave8 = self.__amplitude * np.sin(2 * np.pi * self.__frequency *
                                             linspace + theta8)
        sinwave9 = self.__amplitude * np.sin(2 * np.pi * self.__frequency *
                                             linspace + theta9)
        sinwave10 = self.__amplitude * np.sin(2 * np.pi * self.__frequency *
                                              linspace + theta10)
        sinwave11 = self.__amplitude * np.sin(2 * np.pi * self.__frequency *
                                              linspace + theta11)
        sinwave12 = self.__amplitude * np.sin(2 * np.pi * self.__frequency *
                                              linspace + theta12)
        sinwave13 = self.__amplitude * np.sin(2 * np.pi * self.__frequency *
                                              linspace + theta13)
        sinwave14 = self.__amplitude * np.sin(2 * np.pi * self.__frequency *
                                              linspace + theta14)
        sinwave15 = self.__amplitude * np.sin(2 * np.pi * self.__frequency *
                                              linspace + theta15)
        sinwave16 = self.__amplitude * np.sin(2 * np.pi * self.__frequency *
                                              linspace + theta16)

        sinwave = []

        for i in range(0, len(signalBits) - 1, 4):
            if signalBits[i] == 0 and signalBits[i + 1] == 0 and signalBits[
                    i + 2] == 0 and signalBits[i + 3] == 0:  # theta1 case
                sinwave.extend(sinwave1)
            elif signalBits[i] == 0 and signalBits[i + 1] == 0 and signalBits[
                    i + 2] == 0 and signalBits[i + 3] == 1:  # theta2 case
                sinwave.extend(sinwave2)
            elif signalBits[i] == 0 and signalBits[i + 1] == 0 and signalBits[
                    i + 2] == 1 and signalBits[i + 3] == 0:  # theta3 case
                sinwave.extend(sinwave3)
            elif signalBits[i] == 0 and signalBits[i + 1] == 0 and signalBits[
                    i + 2] == 1 and signalBits[i + 3] == 1:  # theta4 case
                sinwave.extend(sinwave4)
            elif signalBits[i] == 0 and signalBits[i + 1] == 1 and signalBits[
                    i + 2] == 0 and signalBits[i + 3] == 0:  # theta5 case
                sinwave.extend(sinwave5)
            elif signalBits[i] == 0 and signalBits[i + 1] == 1 and signalBits[
                    i + 2] == 0 and signalBits[i + 3] == 1:  # theta6 case
                sinwave.extend(sinwave6)
            elif signalBits[i] == 0 and signalBits[i + 1] == 1 and signalBits[
                    i + 2] == 1 and signalBits[i + 3] == 0:  # theta7 case
                sinwave.extend(sinwave7)
            elif signalBits[i] == 0 and signalBits[i + 1] == 1 and signalBits[
                    i + 2] == 1 and signalBits[i + 3] == 1:  # theta8 case
                sinwave.extend(sinwave8)
            elif signalBits[i] == 1 and signalBits[i + 1] == 0 and signalBits[
                    i + 2] == 0 and signalBits[i + 3] == 0:  # theta9 case
                sinwave.extend(sinwave9)
            elif signalBits[i] == 1 and signalBits[i + 1] == 0 and signalBits[
                    i + 2] == 0 and signalBits[i + 3] == 1:  # theta10 case
                sinwave.extend(sinwave10)
            elif signalBits[i] == 1 and signalBits[i + 1] == 0 and signalBits[
                    i + 2] == 1 and signalBits[i + 3] == 0:  # theta11 case
                sinwave.extend(sinwave11)
            elif signalBits[i] == 1 and signalBits[i + 1] == 0 and signalBits[
                    i + 2] == 1 and signalBits[i + 3] == 1:  # theta12 case
                sinwave.extend(sinwave12)
            elif signalBits[i] == 1 and signalBits[i + 1] == 1 and signalBits[
                    i + 2] == 0 and signalBits[i + 3] == 0:  # theta13 case
                sinwave.extend(sinwave13)
            elif signalBits[i] == 1 and signalBits[i + 1] == 1 and signalBits[
                    i + 2] == 0 and signalBits[i + 3] == 1:  # theta14 case
                sinwave.extend(sinwave14)
            elif signalBits[i] == 1 and signalBits[i + 1] == 1 and signalBits[
                    i + 2] == 1 and signalBits[i + 3] == 0:  # theta15 case
                sinwave.extend(sinwave15)
            elif signalBits[i] == 1 and signalBits[i + 1] == 1 and signalBits[
                    i + 2] == 1 and signalBits[i + 3] == 1:  # theta16 case
                sinwave.extend(sinwave16)
        signal = WirelessSignal(timeline, sinwave)

        # save information about rest of bits
        if one_number_of_bits:
            signal.was_one = True
        if two_number_of_bits:
            signal.was_two = True
        if three_number_of_bits:
            signal.was_three = True

        demodulator = Demodulator()
        return signal
	for r in src:
		for s in r:
			if abs(s) > temp[i]:
				temp[i] = s
		i += 1
	return temp

# Examples
input = '21'
sig = Signal(2)#, True)
# Need to compare QAM with excel spreadsheet... YAY!
res, src = sig.generate(input, True)

temp = get_max(src)

print "Source"
for i in temp:
	print i

print "Demodulate"
dem = Demodulator()
dem.build(4)#, True)

out = dem.generate(temp)

#print "Result"
#for i in res:
#	print i

print "Res:"
print out
    def OnRun(self, event):
        print "Running..."
    	error = False #flag for if any invalid input is detected
    	message = "" #holds the error message if any invalid input is detected
        global pos

        # take in generated string and noise string
        global seq, seqNoise
        seq = self.seq_length.GetValue()
        
        print ""
        print "input"
        print seq
        print ""

        mod = self.mod_type.GetValue()

        noise = self.noise_type.GetValue()

        speed = self.speed_up.GetValue()
        try:
            int(speed)
        except ValueError:
	    message = message + 'Invalid input on speed up\r\n'
            print "invalid input on speed_up"
	    error = True

        code = self.coding.GetValue()

        res = self.resolution.GetValue()
        try: 
            int(res)
        except ValueError:
	    message = message + 'Invalid input on resolution\r\n'
            print "invalid input on resolution"
	    error = True

        levels = 2
        qam_on = False
    	if(error):
    	    wx.MessageBox(message, 'Error in input', wx.OK | wx.ICON_ERROR)
    	else:
            if int(mod) is 4:
                levels = 16
                qam_on = True
                sig = Signal((levels), True)
            if int(mod) is 3:
                levels = 16
                sig = Signal(levels)
            if int(mod) is 2:
                levels = 8
                sig = Signal(levels)
            if int(mod) is 1:
                levels = 4
                sig = Signal(levels)
            if int(mod) is 0:
                levels = 2
                sig = Signal(levels)
            else:
                levels = 2
                sig = Signal(levels)

            res, src, amplitude, phase = sig.generate(str(seq), True)

            temp = self.get_max(src)
            maxSource = res[pos]

            print "signal"
            print temp
            print ""
            print "noise signal"
            print maxSource
            print ""

            amp = amplitude[pos]
            pha = phase[pos]

            noise_ratio = []
            phase_y = []

            for x in range(0, 10):
                noise_ratio.append(temp[x]/maxSource[x])
                phase_y.append(amp[x]*math.sin((pha[x])*(57.2957795)))

            #demodulate
            dem = Demodulator()
            if qam_on is True:
                dem.build((levels), True)
            else:
                dem.build(4, False)
            
            #result
            out = dem.generate(temp)
            print "output"
            print out
            print ""

            global const_x, const_y
            const_x = np.append(const_x,0.0)
            const_y = np.append(const_y,0.0)
            for i in range(0,10):
                const_x = np.append(const_x,amplitude[pos][i])
                const_y = np.append(const_y,phase_y[i])

            global ber_x, ber_y
            for c in range(0,10):
                ber_y = np.append(ber_y,calculateBER(temp[c], maxSource[c]))

            global con
            con.drawConsPlot(const_x,const_y)

            for i in range(0,len(noise_ratio)):
                ber_x = np.append(ber_x,abs(noise_ratio[i]))
            
            global ber
            ber.drawBerPlot(ber_x,ber_y)
        
        print "calculated"
Beispiel #15
0
from demodulator import Demodulator
from modulator import Modulator

start = 0
end = 56 #
ifDoubleTrack=0 # 是否按照双声道文件解析
sampling_rate = 8000 # 采样频率
fft_size = (end-start)*100 # 分析多长的时域信号
path="singleTrack.wav"
flt=700



if __name__ == "__main__":
    dm=Demodulator(path, sampling_rate,fft_size)
    dm.get_time_track(ifDoubleTrack)
    dm.to_frequency(dm.raw_sig,1) # 0不画图 1画图

    lp=dm.lowpass(8,flt)
    hp=dm.highpass(8,flt)
    dm.to_frequency(lp,0)


    m=Modulator()

    # # 根据3DB带宽滤波 但并没有成功
    # bands = dm.find3DB()
    # for band in bands:
    #     bp=dm.bandpass(8,band[0],band[1])
    #     print(len(bp))
Beispiel #16
0
    def make_qpsk_mod(self, bits):
        """ Generates WirelessSignal object from given list of bits in quadrature phase-shift keying.
            WirelessSignal objects contains linspace and sinwave.

           Parameters
           ----------
           bits : list
               List of bits to generate sinwave from it

           Returns
           -------
           signal : WirelessSignal
               Signal generated from bits
        """

        signalBits = bits.copy()

        # We need to check if signal has odd number of bits
        odd_number_of_bits = False

        # Deal with odd-sized signal
        if len(signalBits) % 2 != 0:
            signalBits.append(0)
            odd_number_of_bits = True

        start_time = 0
        end_time = self.__period * len(signalBits) / 2
        timeline = np.arange(start_time, end_time, 1 / self.__sample_rate)

        theta1 = np.pi / 4  # coding 11
        theta2 = 3 * np.pi / 4  # coding 01
        theta3 = 5 * np.pi / 4  # coding 00
        theta4 = 7 * np.pi / 4  # coding 10

        # Generate corresponding sinwaves with length of period
        linspace = np.arange(0, self.__period, 1 / self.__sample_rate)
        sinwave1 = self.__amplitude * np.sin(2 * np.pi * self.__frequency *
                                             linspace + theta1)
        sinwave2 = self.__amplitude * np.sin(2 * np.pi * self.__frequency *
                                             linspace + theta2)
        sinwave3 = self.__amplitude * np.sin(2 * np.pi * self.__frequency *
                                             linspace + theta3)
        sinwave4 = self.__amplitude * np.sin(2 * np.pi * self.__frequency *
                                             linspace + theta4)

        sinwave = []

        for i in range(0, len(signalBits) - 1, 2):
            if signalBits[i] == 1 and signalBits[i + 1] == 1:  # theta1 case
                sinwave.extend(sinwave1)
            elif signalBits[i] == 0 and signalBits[i + 1] == 1:  # theta2 case
                sinwave.extend(sinwave2)
            elif signalBits[i] == 0 and signalBits[i + 1] == 0:  # theta3 case
                sinwave.extend(sinwave3)
            elif signalBits[i] == 1 and signalBits[i + 1] == 0:  # theta4 case
                sinwave.extend(sinwave4)
        signal = WirelessSignal(timeline, sinwave)

        # save information about odd number of bits
        if odd_number_of_bits:
            signal.was_odd = True

        demodulator = Demodulator()
        return signal
Beispiel #17
0
        for s in r:
            if abs(s) > temp[i]:
                temp[i] = s
        i += 1
    return temp


# Examples
input = '21'
sig = Signal(2)  #, True)
# Need to compare QAM with excel spreadsheet... YAY!
res, src = sig.generate(input, True)

temp = get_max(src)

print "Source"
for i in temp:
    print i

print "Demodulate"
dem = Demodulator()
dem.build(4)  #, True)

out = dem.generate(temp)

#print "Result"
#for i in res:
#	print i

print "Res:"
print out