예제 #1
0
def send_data(modulated_data, snr, verbose=True):
    if verbose:
        print("Sending data over AWGN-Channel")
    channel = komm.AWGNChannel(snr=snr,
                               signal_power=1)  # creating new AWGNChannel
    received_data = channel(modulated_data)  # sending data over channel
    return received_data
예제 #2
0
def ARQ_simulation(tx_bin, modulator, snr):
    parity = Parity('odd')
    awgn = komm.AWGNChannel(snr=10**(snr / 10.))

    # make the data a multiple of 7
    if (len(tx_bin) % 7 != 0):
        tx_bin = np.int8(np.append(tx_bin, np.zeros(7 - len(tx_bin) % 7)))

    # transmission
    rx_bin = []
    ARQ_counter = 0
    for i in range(0, len(tx_bin), 7):
        temp = tx_bin[i:i + 7]
        temp = np.append(temp, parity.parity_cal(temp))
        tx_data = modulator.modulate(temp)

        rx_data = awgn(tx_data)
        rx_byte = modulator.demodulate(rx_data)

        while (parity.parity_cal(rx_byte[0:7]) != rx_byte[7]):
            # parity check fail, need resend
            rx_data = awgn(tx_data)
            rx_byte = modulator.demodulate(rx_data)
            ARQ_counter += 1

        rx_bin = np.int8(np.append(rx_bin, rx_byte[0:7]))

    return BER_cal(tx_bin, rx_bin)
예제 #3
0
def modulations():
    while 1:
        print("-----------MODULATION-PROJECT-----------")
        print("1. ASK modulation")
        print("2. PSK modulation")
        print("3. APSK modulation")
        print("4. Exit")
        action = input()
        input_len = 10000 * 3
        inputs = [random.choice([0, 1]) for _ in range(input_len)]
        if action == '1':
            modulation = komm.ASKModulation(4)
            print("ASK modulation")
        elif action == '2':
            modulation = komm.PSKModulation(4)
            print("PSK modulation")
        elif action == '3':
            modulation = komm.APSKModulation((4, 4), (1.0, 2.0))
            print("APSK modulation")
        elif action == '4':
            sys.exit(0)
        channel = komm.AWGNChannel(1.0)
        modulated = modulation.modulate(inputs)
        transmitted = channel(modulated)
        demodulated = modulation.demodulate(transmitted)
        errors = 0
        for d, i in zip(demodulated, inputs):
            if d != i:
                errors += 1
        error_rate = errors / input_len * 100
        print(f"Input size: {input_len}")
        print(f"Error rate: {error_rate}%")
def CON_snr_ber_simulation(tx_bin, snr, modulate, BCH_encoder, C_encoder, C_decoder, tblen, method):
    # BCH encode
    tx_bin_rearrange =  np.reshape(tx_bin, (int(len(tx_bin) / BCH_encoder.dimension), BCH_encoder.dimension))
    pool = ThreadPool(8) 
    tx_encoded_data = pool.map(BCH_encoder.encode, tx_bin_rearrange)
    tx_encoded_data = np.array(tx_encoded_data).flatten()
    pool.close()
    pool.join()
    
    # convolution encode
    tx_enc_c = np.uint8(C_encoder(np.append(tx_encoded_data,np.zeros(tblen))))

    # modulate
    tx_data = modulate.modulate(tx_enc_c)

    # transaction
    awgn = komm.AWGNChannel(snr=10**(snr/10.))
    rx_data = awgn(tx_data)

    # demodulate
    rx_enc_c = modulate.demodulate(rx_data, decision_method = method)


    # Convolution decode
    rx_encoded_data = C_decoder(rx_enc_c)[tblen:]

    # BCH decode
    rx_encoded_data = np.reshape(rx_encoded_data, (int(len(rx_encoded_data) / BCH_encoder.length), BCH_encoder.length))
    pool = ThreadPool(8)
    rx_bin = pool.map(BCH_encoder.decode, rx_encoded_data)
    pool.close()
    pool.join()
    rx_bin = np.array(rx_bin).flatten()
    
    return BER_cal(tx_bin, rx_bin)
예제 #5
0
    def _simulate(self):
        order = 2**self._parameters['log_order']
        amplitude = self._parameters['amplitude']
        phase_offset = self._parameters['phase_offset']
        labeling = self._parameters['labeling']
        noise_power_db = self._parameters['noise_power_db']

        modulation = komm.PSKModulation(order, amplitude, phase_offset, labeling)
        modulation._constellation = np.round(modulation._constellation, 12)  # Only for pedagogical reasons
        awgn = komm.AWGNChannel()
        num_symbols = 200*order
        noise_power = 10**(noise_power_db / 10)
        awgn.signal_power = modulation.energy_per_symbol
        awgn.snr = awgn.signal_power / noise_power
        num_bits = modulation.bits_per_symbol * num_symbols
        bits = np.random.randint(2, size=num_bits)
        sentword = modulation.modulate(bits)
        recvword = awgn(sentword)

        self.output = {
            'title': str(modulation),
            'constellation': modulation.constellation,
            'labels': [''.join(str(b) for b in komm.int2binlist(modulation.labeling[i], width=modulation.bits_per_symbol)) for i in range(order)],
            'gaussian_clouds': recvword,
        }
예제 #6
0
def single_test(amplitudes, phase_offsets, orders, snr, signal_power,
                signal_len, sygnal_wejsciowy):
    channel = komm.AWGNChannel(snr=snr, signal_power=signal_power)
    modulation = komm.APSKModulation(orders=orders,
                                     amplitudes=amplitudes,
                                     phase_offsets=phase_offsets)
    sygnal_zakodowany = modulation.modulate(sygnal_wejsciowy)
    sygnal_zaklocony = channel(sygnal_zakodowany)
    sygnal_wyjsciowy = modulation.demodulate(sygnal_zaklocony)
    ber = get_ber(sygnal_wejsciowy, sygnal_wyjsciowy)
    return round(ber / signal_len, 3), modulation.bits_per_symbol
예제 #7
0
def snr_ber_simulation(tx_bin, snr, modulate):

    BER = []
    tx_data = modulate.modulate(tx_bin)

    for i in range (0, len(snr)):
        
        awgn = komm.AWGNChannel(snr=10**(snr[i]/10.))
        rx_data = awgn(tx_data)
        rx_bin = modulate.demodulate(rx_data)
        BER.append(BER_cal(tx_bin, rx_bin))
        # plt.figure()
        # plt.title("constellation diagram")
        # plt.scatter(rx_data.real,rx_data.imag,s=1,marker=".")
        # plt.axes().set_aspect('equal')
    return BER
예제 #8
0
def generate_data():
    global amplitudes, phase_offsets, orders, snr, signal_power, number_of_tests, signal_len  #, digits
    sheet_name = input(">> Nazwa arkusza: ")
    # Kanal i modulacja
    channel = komm.AWGNChannel(snr=snr, signal_power=signal_power)
    modulation = komm.APSKModulation(orders=orders,
                                     amplitudes=amplitudes,
                                     phase_offsets=phase_offsets)
    # Wypisanie wynikow od excela
    wb = openpyxl.load_workbook(filename="Wyniki.xlsx")
    ws = wb.create_sheet(sheet_name)  # Utworzenie arkusza
    # Ustalenie naglowkow
    ws['A1'] = "Numer"
    ws['B1'] = "BER"
    ws['C1'] = "Szybkosc transmisji"
    # Wypisanie danych symulacji
    ws['M1'] = "Amplituda"
    ws['M2'] = "Przesuniecie fazowe"
    ws['M3'] = "Rzad"
    ws['M4'] = "SNR"
    ws['M5'] = "Moc sygnalu"
    ws['M6'] = "Liczba testow"
    ws['M7'] = "Dlugosc sygnalu"
    ws['N1'] = str(amplitudes)
    ws['N2'] = str(phase_offsets)
    ws['N3'] = str(orders)
    ws['N4'] = str(snr)
    ws['N5'] = str(signal_power)
    ws['N6'] = str(number_of_tests)
    ws['N7'] = str(signal_len)
    #Petla
    for i in range(1, number_of_tests + 1):
        # Sygnaly
        sygnal_wejsciowy = generate_random_signal()
        sygnal_zakodowany = modulation.modulate(sygnal_wejsciowy)
        sygnal_zaklocony = channel(sygnal_zakodowany)
        sygnal_wyjsciowy = modulation.demodulate(sygnal_zaklocony)
        #BER
        ber = get_ber(sygnal_wejsciowy, sygnal_wyjsciowy)
        ws.cell(row=i + 1, column=1).value = i  # Numer
        ws.cell(row=i + 1, column=2).value = ber  # BER
        ws.cell(row=i + 1, column=3).value = modulation.bits_per_symbol
    wb.save("Wyniki.xlsx")
    print(
        f"Zakonczono testy - wyniki znajduja sie w pliku Wyniki.xlsx w arkuszu {sheet_name}"
    )
    input("Wcisnij ENTER, aby kontynuowac ...")
def CCODE_snr_ber_simulation(tx_bin, snr, modulation, encoder, decoder, tblen,
                             method):
    # encode
    tx_enc = np.uint8(encoder(np.append(tx_bin, np.zeros(tblen))))
    # modulate
    tx_data = modulation.modulate(tx_enc)

    # transaction
    awgn = komm.AWGNChannel(snr=10**(snr / 10.))
    rx_data = awgn(tx_data)

    # demodulate
    rx_enc = modulation.demodulate(rx_data, decision_method=method)

    # decode
    rx_bin = np.uint8(decoder(rx_enc))[tblen:]

    return BER_cal(tx_bin, rx_bin)
예제 #10
0
def BCH_snr_ber_simulation(tx_bin, snr, modulate, encoder):

    if (encoder != -1):
        # encode
        tx_bin_rearrange = np.reshape(
            tx_bin, (int(len(tx_bin) / encoder.dimension), encoder.dimension))
        pool = ThreadPool(8)
        tx_encoded_data = pool.map(encoder.encode, tx_bin_rearrange)
        pool.close()
        pool.join()
        # for i in range (0, len(tx_bin_rearrange)):
        #     tx_encoded_data.append(encoder.encode(tx_bin_rearrange[i]))
    else:
        tx_encoded_data = tx_bin

    # modulate
    tx_data = modulate.modulate(np.array(tx_encoded_data).flatten())

    # transaction
    awgn = komm.AWGNChannel(snr=10**(snr / 10.))
    rx_data = awgn(tx_data)

    # demodulate
    rx_encoded_data = modulate.demodulate(rx_data)

    # decode
    if (encoder != -1):
        rx_encoded_data = np.reshape(
            rx_encoded_data,
            (int(len(rx_encoded_data) / encoder.length), encoder.length))
        pool = ThreadPool(8)
        rx_bin = pool.map(encoder.decode, rx_encoded_data)
        pool.close()
        pool.join()
        # for j in range(0, len(rx_encoded_data)):
        #     rx_bit_stream.append(encoder.decode(rx_encoded_data[j]))
    else:
        rx_bin = rx_encoded_data

    rx_bin = np.array(rx_bin).flatten()

    BER = BER_cal(tx_bin, rx_bin)

    return BER
예제 #11
0
def constellation_demo(modulation, noise_power_db, xlim, ylim):
    awgn = komm.AWGNChannel()

    num_symbols = 10000
    noise_power = 10**(noise_power_db / 10)
    awgn.signal_power = modulation.energy_per_symbol
    awgn.snr = awgn.signal_power / noise_power
    num_bits = modulation.bits_per_symbol * num_symbols
    bits = np.random.randint(2, size=num_bits)
    sentword = modulation.modulate(bits)
    recvword = awgn(sentword)

    _, ax = plt.subplots(figsize=(16, 10))
    ax.scatter(recvword.real, recvword.imag, color='xkcd:light blue', s=1)
    ax.scatter(modulation.constellation.real,
               modulation.constellation.imag,
               color='xkcd:blue',
               s=8**2)
    for (i, point) in enumerate(modulation.constellation):
        binary_label = ''.join(
            str(b) for b in komm.int2binlist(modulation.labeling[i],
                                             width=modulation.bits_per_symbol))
        ax.text(point.real,
                point.imag + 0.075 * xlim[0],
                binary_label,
                horizontalalignment='center')
    ax.set_title(repr(modulation))
    ax.set_xlabel('Re')
    ax.set_ylabel('Im')
    ax.axis('square')
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)
    ax.grid()
    info_text = 'SNR = {:.1f} dB\n'.format(10 * np.log10(awgn.snr))
    info_text += 'Eb/N0 = {:.1f} dB'.format(
        10 * np.log10(awgn.snr / modulation.bits_per_symbol))
    ax.text(1.125 * xlim[1],
            0.0,
            info_text,
            horizontalalignment='left',
            verticalalignment='center')
    plt.show()
예제 #12
0
def main():
    parity = Parity('odd')

    tx_im = Image.open("DC4_150x100.pgm")
    tx_bin = np.unpackbits(np.array(tx_im))
    modulator = komm.QAModulation(4, base_amplitudes=1 / np.sqrt(2))
    # modulator = komm.PSKModulation(2)

    snr = 4
    awgn = komm.AWGNChannel(snr=10**(snr / 10.))

    # make the data a multiple of 7
    if (len(tx_bin) % 7 != 0):
        tx_bin = np.int8(np.append(tx_bin, np.zeros(7 - len(tx_bin) % 7)))

    # transmission
    rx_bin = []
    ARQ_counter = 0
    for i in range(0, len(tx_bin), 7):
        temp = tx_bin[i:i + 7]
        temp = np.append(temp, parity.parity_cal(temp))
        tx_data = modulator.modulate(temp)

        rx_data = awgn(tx_data)
        rx_byte = modulator.demodulate(rx_data)

        while (parity.parity_cal(rx_byte[0:7]) != rx_byte[7]):
            # parity check fail, need resend
            rx_data = awgn(tx_data)
            rx_byte = modulator.demodulate(rx_data)
            ARQ_counter += 1

        rx_bin = np.int8(np.append(rx_bin, rx_byte[0:7]))

    print("ARQ counter = " + str(ARQ_counter))
    print("BER = " + str(BER_cal(tx_bin, rx_bin)))
import numpy as np
import komm

# ---- Parameters
feedforward_polynomials = [[0o117, 0o155]]
L = 1000
snr = 2.0
decoding_method = 'viterbi_soft'
# ----

convolutional_code = komm.ConvolutionalCode(feedforward_polynomials)
code = komm.TerminatedConvolutionalCode(convolutional_code, num_blocks=L)
awgn = komm.AWGNChannel(snr=snr)
bpsk = komm.PAModulation(2)
soft_or_hard = getattr(code, '_decode_' + decoding_method).input_type

message = np.random.randint(2, size=L)
codeword = code.encode(message)
sentword = bpsk.modulate(codeword)
recvword = awgn(sentword)
demodulated = bpsk.demodulate(recvword, decision_method=soft_or_hard)
message_hat = code.decode(demodulated, method=decoding_method)

print(f'{np.count_nonzero(message != message_hat)} / {len(message)}')
예제 #14
0
    Npixels = tx_im.size[1] * tx_im.size[0]

    # # plot input image
    # plt.figure(1)
    # plt.title('Input Image')
    # plt.imshow(np.array(tx_im),cmap="gray",vmin=0,vmax=255)

    # create an instance of the qpsk modulation scheme
    qpsk = komm.PSKModulation(4, phase_offset=np.pi / 4)

    # maximim SNR[dB] value
    max_snr = 10
    num_bits = 8 * Npixels

    # list of additive white gaussian noise sources with SNR in range 0 to max_snr
    awgn = [komm.AWGNChannel(snr=10**(x / 10.)) for x in range(max_snr)]

    # array to store simulated bit error ratio
    ber = np.zeros(max_snr)
    # array to store signal-to-noise[dB] ratio for the channel
    snr = np.zeros(max_snr)

    # rate 1/2 code with [0o7, 0o5] as the feedforward polynomial
    code, tblen = FEC.ConvCode.create_conv_codes()

    # flatten the image into a 1D array and
    # append tblen zeros to compensate for the decoder delay
    tx_bin = np.append(np.unpackbits(np.array(tx_im)), np.zeros(tblen))

    # simulate channel encoding
    encoder = komm.ConvolutionalStreamEncoder(code)
def modulatedinchannel(modulated):
    awgn = komm.AWGNChannel(snr=100.0, signal_power=1.0)
    sentsignal = awgn(modulated)
    return sentsignal[0]  #einfach ganz lollig
예제 #16
0
import numpy as np
import komm

mod = komm.PAModulation(order=2)
#mod = komm.ASKModulation(order=4)
#mod = komm.PSKModulation(order=2)
#mod = komm.PSKModulation(order=4)
#mod = komm.PSKModulation(order=8)
#mod = komm.QAModulation(order=16, labeling='reflected_2d')
#mod = komm.ComplexModulation(constellation=[0, 1, 1j, -1])

M = mod.order
snr = 100.0
awgn = komm.AWGNChannel(snr=snr, signal_power=mod.energy_per_symbol)
mod.channel_snr = snr
num_symbols = 100_000
bits = np.random.randint(2, size=num_symbols * mod.bits_per_symbol)
sent = mod.modulate(bits)
recv = awgn(sent)
recv = [0.5 + 0.707j, -0.9 - 0.4j]
if isinstance(mod, komm.RealModulation):
    recv = np.real(recv)
demodulated_hard = mod.demodulate(recv, 'hard')
demodulated_soft = mod.demodulate(recv, 'soft')

print(f'mod = {mod}')
print(f'mod.constellation = {mod.constellation.tolist()}')
print(f'mod.order = {mod.order}')
print(f'mod.bits_per_symbol = {mod.bits_per_symbol}')
print(f'mod.labeling = {mod.labeling}')
print(f'mod._mapping = {mod._inverse_mapping}')
예제 #17
0
파일: ex2.py 프로젝트: schaiana/COM2
import numpy as np
import sindrome
import komm

param = {}
param['n'] = 7
param['k'] = 4

b = np.random.randint(2, size=param['n'])
#code = komm.HammingCode(param['n']-param['k'])
#param['c'] = code.encode(u)
mod = komm.PAModulation(2)
s = mod.modulate(b)

awgn = komm.AWGNChannel(snr=1.0, signal_power=1.0)
r = awgn(s)
u_hat = sindrome.decode_SDD(r, param)
print('b = {}\n û = {}'.format(b, u_hat))
'''
% Codigo de Hamming
codigo.n = 7;
codigo.k = 4;
% Taxa do codigo
R = codigo.k/codigo.n;
% Matriz geradora
Ik = eye(k,k);
p = [1 1 0;1 0 1;0 1 1;1 1 1];
codigo.G = [Ik,p];
% Palavras codigo
u_decimal = [0:2^codigo.k-1];
예제 #18
0
파일: biterr.py 프로젝트: krogk/Pytsdr
def SimulateBER(snrArray, txBin, Npixels, modulatioInfo):
    nSNR = len(snrArray)
    rxDataArray = np.empty(len(txBin))
    BitErrorArray = np.empty(2)
    berArray = np.empty(0)
    mod = 0

    # Create Modulation Scheme Object
    if (modulatioInfo.get("mod") == "PSK"):
        mod = komm.PSKModulation(modulatioInfo.get("order"))

    if (modulatioInfo.get("mod") == 'QAM'):
        mod = komm.QAModulation(modulatioInfo.get("order"))
        # Normalize energy per symbol
        baseAmplitude = 1 / (np.sqrt(mod.energy_per_symbol))
        mod = komm.QAModulation(modulatioInfo.get("order"), baseAmplitude)

    print("Modulation to be used:")
    print(
        str(modulatioInfo.get("order")) + " " + str(modulatioInfo.get("mod")))
    print("Bits Per Symbol: " + str(mod.bits_per_symbol))
    print("Energy Per Symbol: " + str(mod.energy_per_symbol))
    print("\n")

    # Modulate Data
    txData = mod.modulate(txBin)

    # For each transmision
    for i in range(nSNR):
        # Calculate based on db
        awgn = komm.AWGNChannel(snr=10**(snrArray[i] / 10.))
        # Simulate noise in channel
        rxData = awgn(txData)
        # Demodulate Data
        rxBin = mod.demodulate(rxData)
        # Append demodulated data as a new row
        rxDataArray = np.vstack([rxDataArray, rxBin])

    awgn = komm.AWGNChannel(snr=10**(snrArray[10] / 10.))
    rx_data = awgn(txData)
    rx_bin = mod.demodulate(rx_data)

    # Plot few rx bits
    plt.figure()
    plt.axes().set_aspect("equal")
    plt.scatter(rx_data[:10000].real, rx_data[:10000].imag, s=1, marker=".")
    plt.show()
    rx_im = np.packbits(rx_bin).reshape(tx_im.size[1], tx_im.size[0])

    plt.figure()
    plt.imshow(np.array(rx_im), cmap="gray", vmin=0, vmax=255)
    plt.show()

    # Measuring Bit Error Ratio
    # For each transmision
    for j in range(1, nSNR + 1):
        # Reset number of bit errors
        BitErrorCount = 0

        # Compute bit errors
        # i.e For each pixel
        for i in range(Npixels * 8):
            # If pixel value does not match
            if (rxDataArray[j][i] != txBin[i]):
                # Increment error count
                BitErrorCount += 1
        # Calculate bit error rate for transmision
        ber = BitErrorCount / (Npixels * 8)
        berArray = np.append(berArray, ber)
        # Append new dimension containing bit count and bit error rate
        BitErrorArray = np.vstack([BitErrorArray, [BitErrorCount, ber]])

    print("Bit Error Array:")
    print(BitErrorArray)
    print("\n")
    plt.figure()
    plt.scatter(snrArray, berArray)  #plot points
    plt.plot(snrArray, berArray)  #plot lines
    plt.yscale("log")
    plt.ylabel('$BER$')
    plt.xlabel('$SNR$')
    plt.title((str(modulatioInfo.get("order")) + " " +
               str(modulatioInfo.get("mod"))))
    plt.grid(True)
    #plt.show()

    # Calculate theoretical BER
    # Modify k parameter i.e. bits per symbol
    k = mod.bits_per_symbol

    errfcDataSet = np.empty(0)
    # For Each SNR
    for i in range(nSNR):
        # Calculate Theorethical BER
        errfc = 0.5 * scipy.special.erfc(
            math.sqrt((10**(snrArray[i] / 10)) / k))
        errfcDataSet = np.append(errfcDataSet, errfc)
    plt.plot(snrArray, errfcDataSet, color='r')
    plt.show()

    print("Errfc Data Set:")
    print(errfcDataSet)
    print("\n")
    return berArray, errfcDataSet
예제 #19
0
import numpy as np
import komm

awgn = komm.AWGNChannel(snr=12.0, signal_power='measured')

power = lambda v: np.real(np.vdot(v, v)) / len(v)

#s = 2.0 * (-1.0)**np.random.randint(2, size=100000)
s = 2.0 * (-1.0)**np.random.randint(
    2, size=100000) + 2.0j * (-1.0)**np.random.randint(2, size=100000)
r = awgn(s)
print(s)
print(r)
print(power(s))
print(power(r))
print(power(r - s))
print(power(s) / power(r - s))
예제 #20
0
import numpy as np
import komm

code = komm.BCHCode(4, 2)
bpsk = komm.PAModulation(2)
awgn = komm.AWGNChannel(2.0)

print(code)
print((code.length, code.dimension, code.minimum_distance))
print(code._available_decoding_methods())
print(code._default_encoder())
print(code._default_decoder(np.float))
print(code.generator_polynomial)
#print(code.generator_matrix)
print(code.parity_polynomial)
#print(code.parity_check_matrix)

n_words = 1_000

message = np.random.randint(2, size=n_words * code.dimension)
codeword = code.encode(message)

sentword = bpsk.modulate(codeword)
recvword = awgn(sentword)
demodulated_hard = bpsk.demodulate(recvword)
message_hat = code.decode(demodulated_hard)

#print(message)
#print(codeword)
#print(demodulated_hard)
#print((codeword != recvword_hard).astype(np.int))
예제 #21
0
파일: biterr.py 프로젝트: krogk/Pytsdr
def SimulateParityBits(snrArray, txBin, Npixels, modulatioInfo):
    nSNR = len(snrArray)
    rxBinDecoded = np.empty(0)
    rxIncorrect = True

    mod = 0
    if (modulatioInfo.get("mod") == "PSK"):
        mod = komm.PSKModulation(modulatioInfo.get("order"))

    if (modulatioInfo.get("mod") == 'QAM'):
        mod = komm.QAModulation(
            modulatioInfo.get("order"))  # add baseAmplitude
        print("Base Amplitude is: " + str(mod.energy_per_symbol))
        # Normalize Enerhy per symbol
        baseAmplitude = 1 / (np.sqrt(mod.energy_per_symbol))
        print("New Base Amplitude is: " + str(baseAmplitude))
        mod = komm.QAModulation(modulatioInfo.get("order"), baseAmplitude)

    print("Modulation to be used:")
    print(
        str(modulatioInfo.get("order")) + " " + str(modulatioInfo.get("mod")))
    print("Bits Per Symbol: " + str(mod.bits_per_symbol))
    print("Energy Per Symbol: " + str(mod.energy_per_symbol))
    print("\n")
    print("Simulating ARQ based on parity bit check!")

    print("Adding Parity Bits!")
    # Add parity bits
    # For each pixel
    for i in range(Npixels):
        startIndex = i * 8
        # If the sum of on bits is not even
        if (((np.sum(txBin[startIndex:startIndex + 7])) % 2) != 0):
            # Change parity bit to 1
            txBin[(startIndex + 7)] = 1
        # The sum of on bits is even
        else:
            # Change parity bit to 0
            txBin[(startIndex + 7)] = 0

    # Modulate data
    txDataParity = mod.modulate(txBin)
    print("Simulating Transmision!")
    indexFactor = int(8 / mod.bits_per_symbol)
    berArray = np.empty(0)
    arqArray = np.empty(0)

    for c in range(nSNR):
        print("Simulating SNR: " + str(snrArray[c]))
        # Set Average Gausian Noise to reflect new SNR
        awgn = komm.AWGNChannel(snr=10**(snrArray[c] / 10.))
        ARQ = 0
        # For Each Symbol
        for i in range(Npixels):
            # Compute Index of the codeword
            startIndex = i * indexFactor
            # Until the Parity bit check is not passed
            while (rxIncorrect):
                # Simulate noise in the channel during transmision only
                rxData = awgn(txDataParity[startIndex:startIndex +
                                           indexFactor])
                # Demodulate Data
                rxBin = mod.demodulate(rxData)
                # Check if parity = 0
                if ((np.sum(rxBin) % 2) != 0):
                    # Error During Transmision
                    # Increment Request Counter
                    ARQ += 1
                else:
                    # Passed parity check, assume data is correct
                    # Append Data Bits to final binary array
                    rxBinDecoded = np.append(rxBinDecoded, rxBin)
                    # Set while loop flag to false indicating this codeword has been rx without error
                    rxIncorrect = False

            #Set while loop flag to true to process next codeword
            rxIncorrect = True

        # Convert to real int
        rxBinDecoded = np.real(rxBinDecoded)
        rxBinDecoded = rxBinDecoded.astype(int)
        # For SNR 10 Plot graphs
        if (c == 0):
            # Plot few rx bits
            # plt.figure()
            # plt.axes().set_aspect("equal")
            # plt.scatter(rxBinDecoded[:10000].real,rxBinDecoded[:10000].imag,s=1,marker=".")
            # plt.show()
            rx_im = np.packbits(rxBinDecoded).reshape(tx_im.size[1],
                                                      tx_im.size[0])

            plt.figure()
            plt.imshow(np.array(rx_im), cmap="gray", vmin=0, vmax=255)
            plt.show()

        # Count Bit errors
        print("Computing BER: " + str(snrArray[c]))
        BitErrorCount = 0
        # For each bit in the rx data
        for i in range(Npixels * 8):
            # If bit value does not match
            if (rxBinDecoded[i] != txBin[i]):
                # Increment error count
                BitErrorCount += 1
            # Calculate bit error rate for the transmision
        berArray = np.append(berArray, (BitErrorCount / (Npixels * 8)))
        arqArray = np.append(arqArray, (ARQ / (Npixels * 8)))

    print("BER Array:")
    print(berArray)
    print("\n")

    print("ARQ Array:")
    print(arqArray)
    print("\n")

    plt.figure()
    plt.scatter(snrArray, berArray)  #plot points
    plt.plot(snrArray, berArray)  #plot lines
    plt.yscale("log")
    plt.ylabel('$BER$')
    plt.xlabel('$SNR$')
    plt.title((str(modulatioInfo.get("order")) + " " +
               str(modulatioInfo.get("mod")) + " BER"))
    plt.grid(True)

    # Calculate theoretical BER
    # Modify k parameter i.e. bits per symbol
    k = mod.bits_per_symbol

    errfcDataSet = np.empty(0)
    # For Each SNR
    for i in range(nSNR):
        # Calculate Theorethical BER
        errfc = 0.5 * scipy.special.erfc(
            math.sqrt((10**(snrArray[i] / 10)) / k))
        errfcDataSet = np.append(errfcDataSet, errfc)
    plt.plot(snrArray, errfcDataSet, color='r')
    plt.show()

    plt.figure()
    plt.scatter(snrArray, arqArray)  #plot points
    plt.plot(snrArray, arqArray)  #plot lines
    plt.yscale("log")
    plt.ylabel('$ARQ Rate$')
    plt.xlabel('$SNR$')
    plt.title((str(modulatioInfo.get("order")) + " " +
               str(modulatioInfo.get("mod")) + " ARQ/nBits"))
    plt.grid(True)

    return berArray, arqArray, rxBinDecoded
예제 #22
0
파일: sim_mod.py 프로젝트: pdadial/pyComm
    ber_th = np.empty(max_snr)
    # array to store signal-to-noise[dB] ratio for the channel
    snr = np.empty(max_snr)
    # array to store automatic-repeat-request ratio
    arq_ratio = np.empty(max_snr)

    string = ' '.join([
        "Performing", args.scheme, "for signal-to-noise ratio in range 0 to",
        str(max_snr - 1), "dB..."
    ])
    print(string)

    # loop to to simulate the transmission with SNR[dB] up to the maximum value
    while n < max_snr:
        # additive white gaussian noise source with SNR=n[dB]
        awgn = komm.AWGNChannel(snr=10**(n / 10.))
        # reset the counter which adds the total number of ARQs
        arq = 0
        # array to store received binary sequence
        rx_bin = np.empty(num_bits, dtype=int)
        # list to store received complex-valued data
        rx_data = []

        # loop to simulate the transmission of an 8-bit word at a time
        for j in range(0, num_bits, 8):
            # replace the LSB of each 8-bit word with even parity bit
            temp = tx_bin[j:j + 8]
            temp[-1] = np.sum(temp[:-1]) % 2
            tx_bin[j:j + 8] = temp

            # simulate modulation
예제 #23
0
import numpy as np
import komm

#code = komm.CyclicCode(length=7, generator_polynomial=0o13)  # Hamming(3)
code = komm.CyclicCode(length=23, generator_polynomial=0o5343)  # Golay()
#code = komm.CyclicCode(length=127, generator_polynomial=0o3447023271); code._minimum_distance = 9
awgn = komm.AWGNChannel(snr=4.0)
bpsk = komm.PAModulation(2)

print(code)
print((code.length, code.dimension, code.minimum_distance))
print(code._available_decoding_methods())
print(code._default_encoder())
print(code._default_decoder(np.float))
print(code.generator_polynomial)
#print(code.generator_matrix)
print(code.parity_polynomial)
#print(code.parity_check_matrix)

n_words = 10_000

message = np.random.randint(2, size=n_words * code.dimension)
codeword = code.encode(message)

sentword = bpsk.modulate(codeword)
recvword = awgn(sentword)
demodulated_hard = bpsk.demodulate(recvword)
message_hat = code.decode(demodulated_hard, method='meggitt')

#print(message)
#print(codeword)