Ejemplo n.º 1
0
def test_psk_modulation():
    bpsk = komm.PSKModulation(2)
    qpsk = komm.PSKModulation(4)
    psk8 = komm.PSKModulation(8)
    r4 = (1.0 + 1.0j) / np.sqrt(2)
    assert np.allclose(bpsk.constellation, [1.0, -1.0])
    assert np.allclose(qpsk.constellation, [1.0, 1.0j, -1.0, -1.0j])
    assert np.allclose(
        psk8.constellation,
        [1.0, r4, 1.0j, -r4.conjugate(), -1.0, -r4, -1.0j,
         r4.conjugate()])
Ejemplo n.º 2
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,
        }
Ejemplo n.º 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}%")
Ejemplo n.º 4
0
def main():

    tx_im = Image.open("DC4_150x100.pgm")
    tx_bin = np.unpackbits(np.array(tx_im))

    # make sure every modulation has the same energy per symbol
    bpsk = komm.PSKModulation(2)
    qam_16 = komm.QAModulation(16, base_amplitudes=1/np.sqrt(10))
    qam_256 = komm.QAModulation(256, base_amplitudes=1/np.sqrt(170))

    snr = np.arange(0,40,2)
    ber_bpsk = snr_ber_simulation(tx_bin, snr, bpsk)
    ber_qam_16 = snr_ber_simulation(tx_bin, snr, qam_16)
    ber_qam_256 = snr_ber_simulation(tx_bin, snr, qam_256)

    # plot all snr vs ber curves
    plt.figure()    
    plt.scatter(snr, ber_bpsk)
    plt.plot(snr, ber_bpsk, label = 'BPSK')
    plt.scatter(snr, ber_qam_16)
    plt.plot(snr, ber_qam_16, label = '16QAM')
    plt.scatter(snr, ber_qam_256)
    plt.plot(snr, ber_qam_256, label = '256QAM')

    plt.xlabel('SNR dB')
    plt.ylabel('BER percentage')
    plt.title('SNR vs BER')
    plt.legend()
    plt.yscale('log')

    # image recovery
    # plt.figure()
    # rx_im = np.packbits(rx_bin).reshape(tx_im.size[1],tx_im.size[0])

    plt.show()
Ejemplo n.º 5
0
def psk_constellation_demo(order, amplitude, phase_offset, labeling,
                           noise_power_db):
    psk_modulation = komm.PSKModulation(order, amplitude, phase_offset,
                                        labeling)
    constellation_demo(psk_modulation,
                       noise_power_db,
                       xlim=[-3.0, 3.0],
                       ylim=[-3.0, 3.0])
Ejemplo n.º 6
0
    def create_object(self, x):
        """

        Creates an instance of the corresponding modulation scheme
        Parameters
        ----------
        x : string containing the name of the modulation scheme
        
        Returns
        -------
        instance of the corresponding modulation scheme 
        k : bits per symbol
        """
        if x == 'BPSK':
            k = 1
            obj = komm.PSKModulation(2)

        if x == 'QPSK':
            k = 2
            obj = komm.PSKModulation(4, phase_offset=np.pi / 4)

        if x == '4-QAM':
            k = 2
            obj = komm.QAModulation(
                4, base_amplitudes=1 / np.sqrt(2.)
            )  # base_amplitudes is set to a value such that obj.energy_per_symbol becomes unity.

        if x == '16-QAM':
            k = 4
            obj = komm.QAModulation(
                16, base_amplitudes=1 / np.sqrt(10.)
            )  # base_amplitudes is set to a value such that obj.energy_per_symbol becomes unity.

        if x == '256-QAM':
            k = 8
            obj = komm.QAModulation(
                256, base_amplitudes=1 / np.sqrt(170.)
            )  # base_amplitudes is set to a value such that obj.energy_per_symbol becomes unity.
        return obj, k
Ejemplo n.º 7
0
def test_pipeline(image_path, show=True, verbose=True):
    psk = komm.PSKModulation(4, phase_offset=np.pi /
                             4)  # defining QPSK modulation

    modulated_data = modulate(
        psk, image_path=image_path,
        verbose=verbose)  # loads image from file and uses QPSK on it
    received_data = send_data(
        modulated_data, snr=0.99,
        verbose=verbose)  # simulates data transfer with loss
    demodulated_data = demodulate(psk, received_data,
                                  verbose=verbose)  # demodulates the data
    save_image(demodulated_data, "transmission.png",
               verbose=verbose)  # saves the transmitted image to a file

    if show:
        show_image(demodulated_data, verbose=verbose)
Ejemplo n.º 8
0
def main():

    tx_im = Image.open("DC4_300x200.pgm")
    tx_bin = np.unpackbits(np.array(tx_im))

    modulation = komm.PSKModulation(2)
    # modulation = komm.QAModulation(256, base_amplitudes= 1/np.sqrt(170))

    SNR = np.arange(0, 20, 1)
    BER = snr_ber_simulation(tx_bin, SNR, modulation)

    plt.figure()
    plt.scatter(SNR, BER)
    plt.plot(SNR, BER, label='simulation')

    # theoraticall curve
    BER_theoratical = 1 / 2 * scipy.special.erfc(
        np.sqrt(10**(SNR / 10) / modulation.bits_per_symbol))
    plt.plot(SNR, BER_theoratical, label='theoratical')

    plt.title('SNR vs BER')
    plt.yscale('log')
    plt.legend()
    plt.show()
Ejemplo n.º 9
0
def main():
    Result = []
    SNR = 3
    modulation = komm.PSKModulation(4)
    tx_bin = np.random.randint(2, size = 1200)

    # convolutional code
    Ccode = komm.ConvolutionalCode(feedforward_polynomials=[[0o7, 0o5]])
    tblen = 18
    method = "soft"
    Cparam = convolution_simulation.sim_param(tx_bin, SNR, modulation, Ccode, tblen, method)
    BER = format(convolution_simulation.CCODE_simulation(Cparam), '.4f')
    Result.append([BER,'1/2'])

    Ccode = komm.ConvolutionalCode(feedforward_polynomials=[[0o155, 0o117]])
    tblen = 36
    method = "soft"
    Cparam = convolution_simulation.sim_param(tx_bin, SNR, modulation, Ccode, tblen, method)
    BER = format(convolution_simulation.CCODE_simulation(Cparam), '.4f')
    Result.append([BER,'1/2'])

    Ccode = komm.ConvolutionalCode(feedforward_polynomials=[[0o155, 0o117, 0o127]])
    tblen = 36
    method = "soft"
    Cparam = convolution_simulation.sim_param(tx_bin, SNR, modulation, Ccode, tblen, method)
    BER = format(convolution_simulation.CCODE_simulation(Cparam), '.4f')
    Result.append([BER,'1/3'])

    # BCH code
    BCH_encoder = komm.BCHCode(3, 1)
    BCH_param = BCH_simulation.sim_param(tx_bin, SNR, modulation, BCH_encoder)
    BER = format(BCH_simulation.sim_BCH(BCH_param), '.4f')
    Result.append([BER,'4/7'])

    BCH_encoder = komm.BCHCode(4, 3)
    BCH_param = BCH_simulation.sim_param(tx_bin, SNR, modulation, BCH_encoder)
    BER = format(BCH_simulation.sim_BCH(BCH_param), '.4f')
    Result.append([BER,'5/15'])

    BCH_encoder = komm.BCHCode(5, 7)
    BCH_param = BCH_simulation.sim_param(tx_bin, SNR, modulation, BCH_encoder)
    BER = format(BCH_simulation.sim_BCH(BCH_param), '.4f')
    Result.append([BER,'6/31'])

    BCH_encoder = komm.BCHCode(6, 13)
    BCH_param = BCH_simulation.sim_param(tx_bin, SNR, modulation, BCH_encoder)
    BER = format(BCH_simulation.sim_BCH(BCH_param), '.4f')
    Result.append([BER,'10/63'])

    # ARQ
    BER = format(ARQ_simulation.ARQ_simulation(tx_bin, modulation, SNR), '.4f')
    Result.append([BER, '7/8'])


    columns = ['BER','Code rate']
    rows = ['(0o7,0o5)','(0o155,0o117)','(0o155,0o117,0o127)','(7,4)BCH','(15,5)BCH','(31,6)BCH','(63,10)BCH','ARQ']

    plt.table(cellText = Result, rowLabels = rows, colLabels = columns, loc='center')
    plt.axis('tight')
    plt.axis('off')
    plt.title("Comparison among different FEC code")
    plt.show()
Ejemplo n.º 10
0
def main():
    # param specification
    SNR = 0
    modulation = komm.PSKModulation(4)
    tx_bin = np.random.randint(2, size=1200)
    decision_method = "soft"
    param = []

    # Convolution param (0o7,0o5)
    tblen = 18
    C_code = komm.ConvolutionalCode(feedforward_polynomials=[[0o7, 0o5]])
    BCH_code = komm.BCHCode(3, 1)
    param.append(
        con_param(tx_bin, SNR, modulation, BCH_code, C_code, tblen,
                  decision_method))
    BCH_code = komm.BCHCode(4, 3)
    param.append(
        con_param(tx_bin, SNR, modulation, BCH_code, C_code, tblen,
                  decision_method))
    BCH_code = komm.BCHCode(5, 7)
    param.append(
        con_param(tx_bin, SNR, modulation, BCH_code, C_code, tblen,
                  decision_method))
    BCH_code = komm.BCHCode(6, 13)
    param.append(
        con_param(tx_bin, SNR, modulation, BCH_code, C_code, tblen,
                  decision_method))

    # Convolution param (0o155,0o117)
    tblen = 36
    C_code = komm.ConvolutionalCode(feedforward_polynomials=[[0o155, 0o117]])
    BCH_code = komm.BCHCode(3, 1)
    param.append(
        con_param(tx_bin, SNR, modulation, BCH_code, C_code, tblen,
                  decision_method))
    BCH_code = komm.BCHCode(4, 3)
    param.append(
        con_param(tx_bin, SNR, modulation, BCH_code, C_code, tblen,
                  decision_method))
    BCH_code = komm.BCHCode(5, 7)
    param.append(
        con_param(tx_bin, SNR, modulation, BCH_code, C_code, tblen,
                  decision_method))
    BCH_code = komm.BCHCode(6, 13)
    param.append(
        con_param(tx_bin, SNR, modulation, BCH_code, C_code, tblen,
                  decision_method))

    # Convolution param (0o155,0o117,0o127)
    tblen = 36
    C_code = komm.ConvolutionalCode(
        feedforward_polynomials=[[0o155, 0o117, 0o127]])
    BCH_code = komm.BCHCode(3, 1)
    param.append(
        con_param(tx_bin, SNR, modulation, BCH_code, C_code, tblen,
                  decision_method))
    BCH_code = komm.BCHCode(4, 3)
    param.append(
        con_param(tx_bin, SNR, modulation, BCH_code, C_code, tblen,
                  decision_method))
    BCH_code = komm.BCHCode(5, 7)
    param.append(
        con_param(tx_bin, SNR, modulation, BCH_code, C_code, tblen,
                  decision_method))
    BCH_code = komm.BCHCode(6, 13)
    param.append(
        con_param(tx_bin, SNR, modulation, BCH_code, C_code, tblen,
                  decision_method))

    BER = []
    for i in range(0, len(param), 4):
        temp = [
            format(sim_CON(param[i]), '.4f'),
            format(sim_CON(param[i + 1]), '.4f'),
            format(sim_CON(param[i + 2]), '.4f'),
            format(sim_CON(param[i + 3]), '.4f')
        ]
        BER.append(temp)

    columns = ['(7,4)BCH', '(15,5)BCH', '(31,6)BCH', '(63,10)BCH']
    rows = ['(0o7,0o5)', '(0o155,0o117)', '(0o155,0o117,0o127)']

    plt.table(cellText=BER, rowLabels=rows, colLabels=columns, loc='center')
    plt.axis('tight')
    plt.axis('off')
    plt.title(
        "Comparison among different combination of BCH code and Conv code")
    plt.show()
Ejemplo n.º 11
0
    args = parser.parse_args()

    script_dir = os.path.abspath(os.path.dirname(__file__))
    image_path = os.path.join(script_dir, 'data/DC4_150x100.pgm')
    # input image
    tx_im = Image.open(image_path)
    # number of pixels
    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()
Ejemplo n.º 12
0
 def demodulate(self, bods):
     symbols = self.getSymbolsFromSignal(bods)
     psk = komm.PSKModulation(self.orders[0], self.amplitudes[0],
                              self.phaseOffsets[0])
     return psk.demodulate(symbols)
Ejemplo n.º 13
0
 def modulate(self, bits):
     psk = komm.PSKModulation(self.orders[0], self.amplitudes[0],
                              self.phaseOffsets[0])
     return psk.modulate(bits)
Ejemplo n.º 14
0
def main():

    SNR = np.arange(-5, 10, 1)
    modulation = komm.PSKModulation(4)
    tx_bin = np.random.randint(2, size = 1200)
    # new figure
    plt.figure()

    P = multiprocessing.Pool(len(SNR))
    encoder = komm.BCHCode(3, 1)   # (7,4) BCH
    param = []
    for i in range(0,len(SNR)):
        param.append(sim_param(tx_bin, SNR[i], modulation, encoder))
    BER = P.map(sim_BCH, param)
    plt.plot(SNR, BER, label = '(7,4) BCH code')
    P.close()
    P.join()

    P = multiprocessing.Pool(len(SNR))
    encoder = komm.BCHCode(4, 3)   # (15,5) BCH
    param = []
    for i in range(0,len(SNR)):
        param.append(sim_param(tx_bin, SNR[i], modulation, encoder))
    BER = P.map(sim_BCH, param)
    plt.plot(SNR, BER, label = '(15,5) BCH code')
    P.close()
    P.join()

    P = multiprocessing.Pool(len(SNR))
    encoder = komm.BCHCode(5, 7)   # (31,6) BCH
    param = []
    for i in range(0,len(SNR)):
        param.append(sim_param(tx_bin, SNR[i], modulation, encoder))
    BER = P.map(sim_BCH, param)
    plt.plot(SNR, BER, label = '(31,6) BCH code')
    P.close()
    P.join()

    P = multiprocessing.Pool(len(SNR))
    encoder = komm.BCHCode(6, 13)   # (63,10) BCH
    param = []
    for i in range(0,len(SNR)):
        param.append(sim_param(tx_bin, SNR[i], modulation, encoder))
    BER = P.map(sim_BCH, param)
    plt.plot(SNR, BER, label = '(63,10) BCH code')
    P.close()
    P.join()

    P = multiprocessing.Pool(len(SNR))
    encoder = -1
    param = []
    for i in range(0,len(SNR)):
        param.append(sim_param(tx_bin, SNR[i], modulation, encoder))
    BER = P.map(sim_BCH, param)
    plt.plot(SNR, BER, label = 'QPSK without FEC')
    P.close()
    P.join()
    
    plt.xlabel("SNR")
    plt.ylabel("BER")
    plt.yscale('log')
    plt.legend()
    plt.title("Comparison among different BCH codes")
    plt.show()
Ejemplo n.º 15
0
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
Ejemplo n.º 16
0
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
Ejemplo n.º 17
0
def main():
    # param specification
    SNR = np.arange(-5, 10, 1)
    modulation = komm.PSKModulation(4)
    tx_bin = np.random.randint(2, size=1200)
    tblen = 36

    # hard decision simulation
    decision_method = "hard"
    code = komm.ConvolutionalCode(feedforward_polynomials=[[0o7, 0o5]])
    BER = []
    param = []
    p = multiprocessing.dummy.Pool(len(SNR))
    for i in range(0, len(SNR)):
        temp = sim_param(tx_bin, SNR[i], modulation, code, tblen,
                         decision_method)
        param.append(temp)
    BER = p.map(CCODE_simulation, param)
    p.close()
    p.join()
    plt.figure()
    plt.title("Comparison between Ccode with soft and hard decision")
    plt.yscale('log')
    plt.plot(SNR, BER, label='(0o7,0o5) ccode with hard decision')

    # soft decision simulation
    decision_method = "soft"
    code = komm.ConvolutionalCode(feedforward_polynomials=[[0o7, 0o5]])
    BER = []
    param = []
    p = multiprocessing.dummy.Pool(len(SNR))
    for i in range(0, len(SNR)):
        temp = sim_param(tx_bin, SNR[i], modulation, code, tblen,
                         decision_method)
        param.append(temp)
    BER = p.map(CCODE_simulation, param)
    p.close()
    p.join()
    plt.plot(SNR, BER, label='(0o7,0o5) ccode with soft decision')
    plt.legend()
    plt.xlabel("SNR")
    plt.ylabel("BER")

    plt.figure()
    plt.yscale('log')
    plt.title("Comparison among different Ccode with soft decision")
    plt.plot(SNR, BER, label='(0o7,0o5) ccode')
    # (0o155,0o117) simulation
    decision_method = "soft"
    code = komm.ConvolutionalCode(feedforward_polynomials=[[0o155, 0o117]])
    BER = []
    param = []
    p = multiprocessing.dummy.Pool(len(SNR))
    for i in range(0, len(SNR)):
        temp = sim_param(tx_bin, SNR[i], modulation, code, tblen,
                         decision_method)
        param.append(temp)
    BER = p.map(CCODE_simulation, param)
    p.close()
    p.join()
    plt.plot(SNR, BER, label='(0o155,0o117) ccode')

    # (0o155,0o117,0o127) simulation
    decision_method = "soft"
    code = komm.ConvolutionalCode(
        feedforward_polynomials=[[0o155, 0o117, 0o127]])
    BER = []
    param = []
    p = multiprocessing.dummy.Pool(len(SNR))
    for i in range(0, len(SNR)):
        temp = sim_param(tx_bin, SNR[i], modulation, code, tblen,
                         decision_method)
        param.append(temp)
    BER = p.map(CCODE_simulation, param)
    p.close()
    p.join()
    plt.plot(SNR, BER, label='(0o155,0o117,0o127) ccode')
    plt.xlabel("SNR")
    plt.ylabel("BER")
    plt.legend()
    plt.show()