Esempio n. 1
0
 def pulso(self, K=10, alfa=0.3, num=4, tipo='square'):
     if (tipo == 'square'):
         lo = np.ceil(K / 2) - 1
         return np.ones(K), lo
     if (tipo == 'sinc'):
         n = np.arange(-K * num, K * num + 1, 1)
         n[n == 0] = -1000
         tmp = np.sin(np.pi * n / K) / (np.pi * n / K)
         lo = np.ceil(len(tmp) / 2) - 1
         n[n == -1000] = 0
         tmp[n == 0] = 1
         return tmp, lo
     if (tipo == 'squareRZ'):
         lo = np.ceil(K / 2) - 1
         n = np.linspace(0, K - 1, K)
         x = np.ones_like(n)
         x[n >= K / 2] = 0
         return x, lo
     if (tipo == 'Manchester'):
         lo = np.ceil(K / 2) - 1
         n = np.linspace(0, K - 1, K)
         x = np.ones_like(n)
         x[n >= K / 2] = -1
         return x, lo
     if (tipo == 'RC'):
         n, v = rcosfilter(num * K, alfa, 1, K)
         lo = np.ceil(len(v) / 2)
         return v, lo
     if (tipo == 'rootRC'):
         n, v = rrcosfilter(num * K, alfa, 1, K)
         lo = np.ceil(len(v) / 2)
         return v, lo
Esempio n. 2
0
def main():
    #generacion random
    x_re = np.random.randint(0, 2, LEN_SIGNALX) * 2 - 1
    x_im = np.random.randint(0, 2, LEN_SIGNALX) * 2 - 1
    x_signal = zip(x_re, x_im)

    #upsample
    len_upsampled = UPSAMPLE * LEN_SIGNALX
    up_x_re = np.zeros(len_upsampled)
    up_x_re[np.array(range(LEN_SIGNALX)) * UPSAMPLE] = x_re
    up_x_im = np.zeros(len_upsampled)
    up_x_im[np.array(range(LEN_SIGNALX)) * UPSAMPLE] = x_im

    #rrcos filter
    rrcos = rrcosfilter(NBAUDS * UPSAMPLE, ROLL_OFF, 1. / BAUD_RATE,
                        SAMPLE_RATE)[1]
    rrcos = rrcos / np.sqrt(UPSAMPLE)
    H, A, F = resp_freq(rrcos, 1. / BAUD_RATE, 256)
    plt.figure()
    plt.grid()
    plt.title('root raised cosine')
    plt.plot(rrcos)
    plt.figure()
    plt.grid()
    plt.semilogx(F, 20 * np.log(H))

    #senial enviada
    tx_re = np.convolve(up_x_re, rrcos, 'same')
    tx_im = np.convolve(up_x_im, rrcos, 'same')
    plt.figure()
    plt.grid()
    plt.title('tx signal real')
    plt.plot(tx_re[:LEN_PLOT])

    #senial recibida
    rx_re = np.convolve(tx_re, rrcos, 'same')
    rx_im = np.convolve(tx_im, rrcos, 'same')
    plt.figure()
    plt.grid()
    plt.title('rx signal real')
    plt.plot(rx_re[:LEN_PLOT])
    eyediagram(rx_re, 4, 2, UPSAMPLE)

    #downsample
    offset = 2
    sample_indexs = range(offset, len(rx_re), UPSAMPLE)
    down_rx_re = rx_re[sample_indexs]
    down_rx_im = rx_im[sample_indexs]
    plt.figure()
    plt.title('recibed symbols')
    plt.grid()
    plt.plot(down_rx_re, down_rx_im, '.')

    #slicer
    detection_re = (down_rx_re > 0) * 2 - 1
    detection_im = (down_rx_im > 0) * 2 - 1
    detection = zip(detection_re, detection_im)
    plt.show(block=False)
    raw_input("Aprete cualquier tecla")
    plt.close()
Esempio n. 3
0
def send(input_string, m=2, modem=PSKModem, Ts=1e-3, Fs=int(6e4), fc=int(3e3)):
    # convert string to bitsarray
    # pylint: disable=too-many-format-args
    bits_string = text_to_bits(input_string)
    input_bits = np.array([int(b) for b in bits_string])
    # instantiate modem
    modem = modem(m)
    # FIX: rounding error in CommPy
    modem.constellation = _round_complex(np.array(modem.constellation))
    # modulate input bits
    dk = modem.modulate(input_bits)
    N = len(dk)
    # weight baseband symbols with Dirac comb function
    ups = int(Ts * Fs)
    x = np.zeros(ups * N, dtype='complex')
    x[::ups] = dk
    # set pulse shaping filter
    t0 = 3 * Ts
    _, rrc = rrcosfilter(N=int(2 * t0 * Fs), alpha=1, Ts=Ts, Fs=Fs)
    # convolve pulse shaping filter with Dirac comb
    u = np.convolve(x, rrc)
    time_sample = np.arange(len(u)) / Fs
    # define up-converted I and Q components
    i = u.real
    q = u.imag
    iup = i * np.cos(2 * np.pi * time_sample * fc)
    qup = q * -np.sin(2 * np.pi * time_sample * fc)
    # define transmitted signal
    s = iup + qup
    # TODO: apply channel effects
    # .....
    # define down-converted I and Q components
    idown = s * np.cos(2 * np.pi * -fc * time_sample)
    qdown = s * -np.sin(2 * np.pi * fc * time_sample)
    # set lowpass filter for image rejection
    BN = 1 / (2 * Ts)
    cutoff = 5 * BN
    lowpass_order = 51
    lowpass_delay = (lowpass_order // 2) / Fs
    lowpass = firwin(lowpass_order, cutoff / (Fs / 2))
    # lowpass filter down-converted I and Q components
    idown_lp = lfilter(lowpass, 1, idown)
    qdown_lp = lfilter(lowpass, 1, qdown)
    # define sample
    sample = np.empty((2, len(time_sample)))
    sample[0, :] = idown_lp
    sample[1, :] = qdown_lp
    # define labels
    label_ids = list(
        map(lambda s: np.where(modem.constellation == s)[0][0], dk))
    labels = np.zeros(ups * N)
    bins = np.zeros(N + 1)
    for (i, y) in enumerate(label_ids):
        labels[i * ups:(i + 1) * ups] = y
        bins[i + 1] = (i + 1) * Ts
    delay = t0 + lowpass_delay
    time_labels = np.arange(len(labels)) / Fs + delay - Ts / 2
    bins += delay - Ts / 2
    return time_sample, sample, time_labels, labels, bins
Esempio n. 4
0
    def _construct_rrc_filter(self):
        # filter parameters
        rrc_len_factor = 6
        rrc_alpha_coefficient = 0.4

        from commpy.filters import rrcosfilter
        filter_len_sec = rrc_len_factor * self._symbol_period
        filter_len_samples = int(filter_len_sec * self._f_sample)
        _, rrc = rrcosfilter(N=filter_len_samples,
                             alpha=rrc_alpha_coefficient,
                             Ts=self._symbol_period,
                             Fs=self._f_sample)

        delay = filter_len_sec / 2
        return delay, rrc
Esempio n. 5
0
I_samples = (I_data_raw-127.5)/127.5
Q_samples = (Q_data_raw-127.5)/127.5
complex_data = I_samples + 1j*Q_samples

# plt.figure(1)
# plt.plot(abs(complex_data))
# plt.grid()



data = complex_data[14397:39130]
 

N = 1024  # output size

rrcos = rrcosfilter(N*4, 0.8, 1, 24)[1]



new_data = np.convolve(rrcos, data) # Waveform with PSF

mag = np.abs(new_data)
data_x = -1*(20*np.log10((abs(np.fft.fft(mag)))))





# plt.plot(np.angle(new_data))
# plt.plot(rrcos)
# plt.plot(new_data,'r')
Esempio n. 6
0
for idx in range(len(bits)):
    scrambled[idx] = bits[idx] ^ scrambled[idx - 23] ^ scrambled[idx - 18]

# Upsample
x = np.zeros(num_symbols * samples_per_symbol, dtype=complex)
for idx, bitss in enumerate(scrambled.reshape((num_symbols, 2))):
    x[idx * samples_per_symbol] = (bitss[0]*2-1) + 1j*(bitss[1]*2-1)

print(bits)
print(scrambled)
print(x)

# Generate root raised cosine filter 
num_taps = 50 * samples_per_symbol + int (samples_per_symbol / 2)
alpha = 0.35
t, h = filters.rrcosfilter(num_taps, alpha, 1, samples_per_symbol)

# Interpolate with RRC
tx = np.convolve(x, h)

#FFT of tx signal
#s = tx * np.hamming(len(tx))
#S = np.fft.fftshift(np.fft.fft(s))
#S_mag = np.abs(S)
#f = np.linspace(-0.5,0.5,len(tx))
#plt.figure(0)
#plt.plot(f, S_mag,'.-')
#plt.show()

#Channel
rx = tx
def main():

    ## Inicializacion de simbolos a transmitir
    symbolsI = 0x1AA
    symbolsQ = 0x1FE

    ## Filtro Tx y Rx
    #Filtro Root Raised Cosine
    rc = rrcosfilter(int(Nbauds * os), beta, T, 1. / Ts)[1]
    #Normalizacion
    rc = rc[:24]
    #rc=rc/np.linalg.norm(rc) #lialg.norm ----> Raiz de la suma de los cuadrados de los coeficientes
    rc = rc / np.sqrt(float(os))
    rc_fp = VectorCuantizacion(8, 7, rc, 'trunc')

    # ### FIR para Canal
    # #Filtro Root Raised Cosine
    rch = rcosfilter(int(Nbauds_ch * os), beta, T_ch, 1. / Ts_ch)[1]
    # # #Normalizacion fir del canal
    rch = rch[:28]
    # rch=rch/np.linalg.norm(rch)
    #rch=rch/np.linalg.norm(rch) #lialg.norm ----> Raiz de la suma de los cuadrados de los coeficientes
    #rch=rch/np.sqrt(float(os))
    #rch_fp= VectorCuantizacion(8,7,rch,'trunc')
    #canal=np.convolve(rc,rc)  ## filtro equivalente, resultado de la convolucion de filtro Tx y FIR canal
    #canal_fp=VectorCuantizacion(8,7,canal,'trunc')

    ###---------------------------------------------------
    ####Calculos de energia de filtros
    #Tx
    energia_tx = 0
    for p in range(len(rc)):
        energia_tx = energia_tx + (rc[p]**2)
    print "Energia Tx = ", energia_tx

    # ##FIR canal
    # energia_rch=0
    # for q in range(len(rch)):
    #     energia_rch=energia_rch+(rch[q]**2)
    # print "Energia rch = ",energia_rch

    # ##Filtro equivalente de Tx y FIR , canal equivalente
    # energia_fir_equiv=0
    # for w in range(len(canal)):
    #     energia_fir_equiv=energia_fir_equiv+(canal[w]**2)

    # print "Energia canal equivalente: ", energia_fir_equiv

    ###---------------------------------------------------
    #Grafica de respuesta al impulso del filtro
    # graf_respImpulso(rc_fp,"Filtro Transmisor Tx")
    # graf_respImpulso(rch_fp,"Filtro Canal")
    # graf_respImpulso(canal,"Rc Rch")

    plt.figure()
    plt.title("Filtro RRC")
    plt.plot(rc, 'k-', linewidth=2.0)
    plt.plot(rc_fp, 'b-', linewidth=2.0)
    plt.legend()
    plt.grid(True)
    plt.xlim(0, len(rc) - 1)
    plt.xlabel('Muestras')
    plt.ylabel('Magnitud')

    # plt.figure()
    # plt.title("Convolucion TxRx")
    # plt.plot(canal,'k-',linewidth=2.0)
    # plt.plot(canal_fp,'b-', linewidth =2.0)
    # plt.legend()
    # plt.grid(True)
    # plt.xlim(0,len(canal)-1)
    # plt.xlabel('Muestras')
    # plt.ylabel('Magnitud')

    # plt.figure()
    # plt.title("Canal")
    # plt.plot(canal,'k-',linewidth=2.0)
    # plt.plot(canal_fp,'b-', linewidth =2.0)
    # plt.legend()
    # plt.grid(True)
    # plt.xlim(0,len(canal)-1)
    # plt.xlabel('Muestras')
    # plt.ylabel('Magnitud')

    #Respuesta en frecuencia
    [H0, A0, F0] = resp_freq(rc, Ts, Nfreqs)
    [H1, A1, F1] = resp_freq(rc_fp, Ts, Nfreqs)

    #Grafica de respuesta en frecuencia del filtro
    #graf_respFrecuencia(H0,A0,F0,"Filtro Transmisor")

    plt.figure()
    plt.title(
        'Respuesta en frecuencia convolucion filtro transmisor y receptor')
    plt.semilogx(F0,
                 20 * np.log10(H0),
                 'r',
                 linewidth=2.0,
                 label=r'$\beta=0.5$')
    plt.semilogx(F1,
                 20 * np.log10(H1),
                 'b',
                 linewidth=2.0,
                 label=r'$\beta=0.5$')
    #plt.axvline(x=(1./Ts)/2.,color='k',linewidth=2.0)
    #plt.axvline(x=(1./T)/2.,color='k',linewidth=2.0)
    plt.axhline(y=20 * np.log10(0.5), color='k', linewidth=2.0)
    plt.legend(loc=3)
    plt.grid(True)
    #plt.xlim(F0[1],F0[len(F0)-1])
    plt.xlabel('Frequencia [Hz]')
    plt.ylabel('Magnitud [dB]')

    #Grafica de respuesta al impulso del filtro
    # graf_respImpulso(rcoseno,"convolucion filtro transmisor y receptor")

    #Respuesta en frecuencia
    # [H1,A1,F1]=resp_freq(rcoseno, Ts, Nfreqs)

    #Grafica de respuesta en frecuencia del filtro
    # graf_respFrecuencia(H1,A1,F1,"convolucion filtro transmisor y receptor")

    #Shift register del transmisor y receptor
    shift_tx_I = np.zeros(24)
    shift_tx_Q = np.zeros(24)
    shift_rx_I = np.zeros(24)
    shift_rx_Q = np.zeros(24)

    #Bit transmitidos para comparar en la BER
    trans_berI = np.zeros(1024)
    trans_berQ = np.zeros(1024)

    #Bit recibios para comprar en la BER
    recib_berI = np.zeros(511)
    recib_berQ = np.zeros(511)

    #Salida del filtro transmisor
    out_tx_I = 0
    out_tx_Q = 0
    out_tx_I_fp = DeFixedInt(7, 6, 'S', 'trunc')  #Punto Fijo
    out_tx_Q_fp = DeFixedInt(7, 6, 'S', 'trunc')

    #Salida de del canal mas el ruido
    # out_ch_I=0
    # out_ch_Q=0
    # out_ch_I= DeFixedInt(8,7) #Punto Fijo
    # out_ch_Q= DeFixedInt(8,7)

    #Salida del filtro receptor
    rx_I = 0
    rx_Q = 0
    rx_I_fp = DeFixedInt(7, 6, 'S', 'trunc')  #Punto Fijo
    rx_Q_fp = DeFixedInt(7, 6, 'S', 'trunc')

    #Valor obtenido del Slicer (detector)
    ak_I = 0
    ak_Q = 0

    #Salida del FIR del Equalizador
    y_I = 0
    y_Q = 0
    y_I_fp = DeFixedInt(9, 7, 'S', 'trunc')
    y_Q_fp = DeFixedInt(9, 7, 'S', 'trunc')

    #Error realimentacion Equalizador
    error_adap_I = 0
    error_adap_Q = 0
    error_adap_I_fp = DeFixedInt(7, 6, 'S', 'trunc')
    error_adap_Q_fp = DeFixedInt(7, 6, 'S', 'trunc')

    offset = 1

    phase_I = np.zeros(4)
    phase_Q = np.zeros(4)

    #Variables utilizadas en la sincronizacion
    error_actual = 0
    error_minimo = 99999
    pos_trans = 0
    pos_aux = 0
    cont_ber = 0

    #Variables utilizadas post sincronizacion
    error_final = 0
    cant_muestras = 0

    #Habilitacion Prbs, Ber
    value = 0

    delta = 0.0115
    # delta=0.005

    #Cantidad de coeficientes FIR del ecualizador
    Ntap = 31

    #Memoria del filtro FIR Ecualizador
    mem_fir_adap_I = np.zeros(Ntap)
    mem_fir_adap_Q = np.zeros(Ntap)

    #Coeficientes del filtro FIR del ecualizador adaptativo
    coef_fir_adap_I = np.zeros(Ntap)
    coef_fir_adap_Q = np.zeros(Ntap)
    #Pos 15 = 1 inicializacion
    coef_fir_adap_I[(Ntap - 1) / 2] = 1
    coef_fir_adap_Q[(Ntap - 1) / 2] = 1

    coef_fir_adap_I_fp = DeFixedInt(10, 8, 'S', 'sature')
    coef_fir_adap_Q_fp = DeFixedInt(10, 8, 'S', 'sature')

    diezmado = 2

    end_sync = 0  #Bandera indica fin etapa de sincronizacion (1)

    graficar = 0  #Cuando esta en 1 almacena valores para luego graficar

    # #Memoria del canal
    mem_canal_I = np.zeros(len(rch))
    mem_canal_Q = np.zeros(len(rch))

    #Usados para graficar
    senial_transmitir_I = []
    senial_transmitir_Q = []

    senial_recibida_I = []
    senial_recibida_Q = []

    senial_recibida_diezmada_I = []
    senial_recibida_diezmada_Q = []

    coeficientes = []

    error_tiempo = []

    input_equ = []
    var_tx = []
    var_rx = []
    var_ch = []
    #CURVA BER SIMULADA
    snr = [100.]  #,20.]#,100.,16.,14.,12.,10.,8.,6.,4.,2.]
    ber = []
    snr_iteraciones = [
        100000
    ]  #+ 2097153,100000+100000]#,100000,100000,100000,100000,100000,100000,100000]
    for t in range(len(snr_iteraciones)):
        error_final = 0
        # noise_vector_I=noise(snr[t],snr_iteraciones[t],energia_tx/4) #genero senial de ruido
        # noise_vector_Q=noise(snr[t],snr_iteraciones[t],energia_tx/4)
        print "snr_iter: ", snr_iteraciones[t]
        print "t: ", t

        for i in range(0, snr_iteraciones[t]):
            value = i % os
            if (i == 0):
                sym_t_I = 0
                sym_t_Q = 0
            else:
                sym_t_I = out_tx_I_fp.fValue
                sym_t_Q = out_tx_Q_fp.fValue

            shift_tx_I = ShiftReg(shift_tx_I)
            shift_tx_Q = ShiftReg(shift_tx_Q)

            if (value == 0):  #es multiplo de 4?
                symbolsI = PRBS9(symbolsI)  #Generacion de simbolos
                symbolsQ = PRBS9(symbolsQ)
                if ((symbolsI >> 8) & 0x001 == 0):
                    shift_tx_I[0] = 1
                else:
                    shift_tx_I[0] = -1

                if ((symbolsQ >> 8) & 0x001 == 0):
                    shift_tx_Q[0] = 1
                else:
                    shift_tx_Q[0] = -1

                trans_berI = ShiftReg(trans_berI)
                trans_berQ = ShiftReg(trans_berQ)

                trans_berI[0] = shift_tx_I[
                    0]  #Agrego nuevo valor transmitido a arreglo bits transmitidos
                trans_berQ[0] = shift_tx_Q[0]

            else:  #Oversampling
                shift_tx_I[0] = 0
                shift_tx_Q[0] = 0

            ## Convolucion transmisor, senial transmitida
            out_tx_I = np.sum(rc * shift_tx_I)
            out_tx_Q = np.sum(rc * shift_tx_Q)

            # if(i%4):
            #     var_tx.append(out_tx_I)

            out_tx_I_fp.value = out_tx_I  #+noise_vector_I[i]
            out_tx_Q_fp.value = out_tx_Q  #+noise_vector_Q[i]

            # ###
            # Canal
            # ###
            # mem_canal_I = ShiftReg(mem_canal_I) #corrimiento de memoria del canal
            # mem_canal_Q = ShiftReg(mem_canal_Q)

            # mem_canal_I[0]=out_tx_I #agregamos nuevo valor de salida de Tx a la memoria
            # mem_canal_Q[0]=out_tx_Q

            # out_ch_I=np.sum(mem_canal_I*(rch)) #salida Tx pasa por canal
            # out_ch_Q=np.sum(mem_canal_Q*(rch))

            # if(i%4):
            #     var_ch.append(out_ch_I)

            shift_rx_I = ShiftReg(shift_rx_I)
            shift_rx_Q = ShiftReg(shift_rx_Q)

            shift_rx_I[0] = sym_t_I
            shift_rx_Q[0] = sym_t_Q

            ##Convolucion receptor, senial recibida
            rx_I = np.sum(rc * shift_rx_I)
            rx_Q = np.sum(rc * shift_rx_Q)

            rx_I_fp.value = rx_I
            rx_Q_fp.value = rx_Q

            # if(i%4 and t==0):
            #     input_equ.append(abs(rx_I))
            # rx_I = rx_I *vect_pond[t]
            # rx_Q = rx_Q *vect_pond[t]

            # rx_I=rx_I*pond
            # rx_Q=rx_Q*pond

            # if(max_rx[t] < abs(rx_I)):
            #     max_rx[t] = abs(rx_I)

            # print "Salida Rx: ",rx_I

            ####
            ###FIR ECUALIZADOR
            #####
            if ((i % 2 != 0) and (i != 0)):  #nos quedamos con muestras 1 y 3

                mem_fir_adap_I = ShiftReg(mem_fir_adap_I)
                mem_fir_adap_Q = ShiftReg(mem_fir_adap_Q)

                mem_fir_adap_I[0] = rx_I_fp.fValue
                mem_fir_adap_Q[0] = rx_Q_fp.fValue

            if ((value == 0) and i != 0):

                #for r in range(0,Ntap-1):
                y_I = np.sum(coef_fir_adap_I * mem_fir_adap_I)  #FIR
                y_Q = np.sum(coef_fir_adap_Q * mem_fir_adap_Q)  #FIR

                y_I_fp.value = y_I
                y_Q_fp.value = y_Q

                #Slicer
                ak_I = (2 * (y_I_fp.fValue >= 0) - 1)
                ak_Q = (2 * (y_Q_fp.fValue >= 0) - 1)

                #------------------------------------------Algoritmo de adaptacion
                error_adap_I = ak_I - y_I_fp.fValue
                error_adap_Q = ak_Q - y_Q_fp.fValue

                error_adap_I_fp.value = error_adap_I
                error_adap_Q_fp.value = error_adap_Q

                if (i % 4 == 0):
                    coeficientes.append(coef_fir_adap_I.copy())

                for b in range(0, Ntap):
                    coef_fir_adap_I[b] = coef_fir_adap_I[
                        b] + delta * error_adap_I_fp.fValue * mem_fir_adap_I[b]
                    coef_fir_adap_Q[b] = coef_fir_adap_Q[
                        b] + delta * error_adap_Q_fp.fValue * mem_fir_adap_Q[b]

                # print("COEF I SIN FIX")
                # print ("sin fix",coef_fir_adap_I)
                # print("NOSE",coef_fir_adap_I_fp)
                # for b in range(0,Ntap):
                #     coef_fir_adap_I_fp.value=coef_fir_adap_I[b]
                #     coef_fir_adap_I[b]=coef_fir_adap_I_fp.fValue

                # print("FIX",coef_fir_adap_I)

                for b in range(0, Ntap):
                    coef_fir_adap_I_fp.value = coef_fir_adap_I[b]
                    coef_fir_adap_I[b] = coef_fir_adap_I_fp.fValue
                    coef_fir_adap_Q_fp.value = coef_fir_adap_Q[b]
                    coef_fir_adap_Q[b] = coef_fir_adap_Q_fp.fValue
                # # raw_input('Press Enter to Continue')
                # print("COEF I CON FIX")
                # for b in range(0,Ntap):
                #     print (coef_fir_adap_I[b])
            ##Ber
            # if(i>1000):
            #     if((value==0) and i!=0):
            #         recib_berI = ShiftReg(recib_berI)
            #         recib_berQ = ShiftReg(recib_berQ)

            #         recib_berI[0]=ak_I #Bits recibidos
            #         recib_berQ[0]=ak_Q #Bits recibidos

            #         if(end_sync==0): ##Etapa de sincronizacion
            #             if(cont_ber<511):
            #                 cont_ber=cont_ber+1
            #             else: #cont_ber==511
            #                 cont_ber=0
            #                 if(error_actual<error_minimo):
            #                     print "Error minimo actual: ",error_actual
            #                     print "Pos error minimo actual: ",pos_trans
            #                     error_minimo=error_actual
            #                     error_actual=0
            #                     pos_aux=pos_trans
            #                 else:
            #                     error_actual=0

            #                 if(pos_trans!=1023):
            #                     pos_trans=pos_trans+1
            #                 else:   #finalizo etapa de sincronizacion
            #                     pos_trans=pos_aux
            #                     end_sync=1
            #                     # print "end_sync",end_sync
            #                     #graficar=1
            #             if(recib_berI[0]!=trans_berI[pos_trans]):
            #                 error_actual=error_actual+1
            #             if(recib_berQ[0]!=trans_berQ[pos_trans]):
            #                 error_actual=error_actual+1

            #         else: #end_sync==1 pos sincronizacion
            #             cant_muestras=cant_muestras+1
            #             # print "end_sync"
            #             # if(end_sync==1):
            #                 # print "Bit recibido en BER: ", ak_I
            #                 # raw_input('Press Enter to Continue')
            #                 # plt.close()

            #             if(recib_berI[0]!=trans_berI[pos_trans]):
            #                 error_final=error_final+1
            #             if(recib_berQ[0]!=trans_berQ[pos_trans]):
            #                 error_final=error_final+1

            #             if(i==(snr_iteraciones[t]-4)):
            #                 print "snr",snr[t]
            #                 print "error_final", error_final
            #                 ber.append(float(error_final)/(((snr_iteraciones[t]/os)*2)))
            #                 print ber

    # print "VAR_TX", np.var(var_tx)
    # print "VAR_RX", np.var(var_rx)
    # print "VAR_CH", np.var(var_ch)

    # print "SNR = ", snr[t], " Maximo = ", max_rx[t]
    # print "SNR = %d - Maximo = %d" %(snr[t],max_rx[t])
    # suma=0
    # for w in range (len(input_equ)):
    #     suma=suma + input_equ[w]

    # plt.figure()
    # plt.title("Entrada Ecualizador")
    # plt.plot(input_equ,".")
    # print "Cantidad de muestras para la media ", len(input_equ)
    # print "MEDIA:", suma/len(input_equ)
    # print "Vector de Maximos", max_rx
    #print "BER: ", ber

    #print error_minimo
    #print pos_aux

    ##Grafico de simbolos transmitidos
    #graf_simbTransmitidos(shift_tx_I,shift_tx_Q)

    ### Convolucion transmisor, senial transmitida
    #graf_Convolucion(senial_transmitir_I, "transmitida")

    ##Grafico diagrama ojo transmisor
    #eyediagram(senial_transmitir_I[100:len(senial_transmitir_I)-100],os,0,Nbauds)
    #eyediagram(senial_transmitir_Q[100:len(senial_transmitir_Q)-100],os,0,Nbauds)

    ##Convolucion receptor, senial recibida
    #graf_Convolucion(var_rx,"recibida")

    ##Grafica curvas Ber-teorica y simulada
    #graf_BER(snr,ber)

    ##Grafico diagrama ojo receptor
    #eyediagram(senial_recibida_I[100:len(senial_recibida_I)-100],os,0,Nbauds)
    #eyediagram(senial_recibida_Q[100:len(senial_recibida_Q)-100],os,0,Nbauds)

    ##Constelaciones
    # plt.figure()
    # plt.title("Constelaciones")
    # plt.plot(senial_recibida_diezmada_I[(offset):len(senial_recibida_diezmada_I)-((offset)):int(os)],
    #      senial_recibida_diezmada_Q[(offset):len(senial_recibida_diezmada_Q)-((offset)):int(os)],
    #          'r.',linewidth=2.0)
    # plt.axis('equal')
    # plt.grid(True)
    # plt.xlabel('Real')
    # plt.ylabel('Imag')

    # plt.figure()
    # plt.title("Error en la adaptacion")
    # plt.plot(error_tiempo)

    plt.figure()
    plt.title("Coeficientes en el tiempo")
    plt.plot(coeficientes)

    # print len(coeficientes)
    plt.figure()
    plt.title("Ultimos coeficientes del filtro FIR")
    plt.stem(coeficientes[len(coeficientes) - 1])

    #equa=np.convolve(rcoseno,np.transpose(coeficientes[len(coeficientes)-1]))

    # ## Grafica de respuesta al impulso del filtro
    # graf_respImpulso(equa,"a la salida del equalizador")

    # ## Respuesta en frecuencia
    # [H2,A2,F2]=resp_freq(equa, Ts, Nfreqs)
    # ## Grafica de respuesta en frecuencia del filtro
    # graf_respFrecuencia(H2,A2,F2,"a la salida del ecualizador")

    plt.show(block=False)
    raw_input('Press Enter to Continue')
    plt.close()
Esempio n. 8
0
mag = np.abs(m_filter)

d=int(len(m_filter))


magnitude = np.abs(m_filter)
plt.figure(1)
plt.plot((m_filter))
plt.grid()

data_x = (20*np.log10((abs(np.fft.fft(mag)))))


#Scipy Website Commpy Library root raised Cosines

rrcos = rrcosfilter(1*2, 0.5, 1, 2400000)[1] 
f_sample_factor=11
sinc_func=np.sin(np.arange(0,f_sample_factor,1)*np.pi/f_sample_factor)



rollof=10
rrcos_2=3*np.sinc(np.arange(-rollof,rollof,0.5)*np.pi/rollof)
filterout_t=np.correlate((m_filter),sinc_func)
mag = np.abs(filterout_t)
angle = np.angle(filterout_t)
unwrap = np.unwrap(angle)

fft_1  = 20*np.log10(np.abs(np.fft.fft(np.abs(filterout_t ),sample_rate)))

import numpy as np
import matplotlib.pyplot as plt
import commpy.filters as matlab

filename_out = 'yeet.txt'
file_out = open(filename_out,'w+')

L = 5
beta = .12

#length rolloff ts fs
[filt,bad] = matlab.rrcosfilter(L,beta,5,1)
print(filt)
plt.stem(filt)
plt.show()


Esempio n. 10
0
# PYTHONPATH=./tutorial-env/lib/python3.5/site-packages/commpy python rrc-coeffs.py

import numpy as np
import matplotlib.pyplot as plt
from commpy import filters

Fs = 1000 # Sampling rate of 1kHz
Ts = 0.01 # Symbol length of 10ms (i.e. 10 samples per symbol)

# the RRC filter should span 3 baseband samples to the left and to the right.
# Hence, it introduces a delay of 3Ts seconds.
t0 = 3*Ts

_, rrc = filters.rrcosfilter(N=int(2*t0*Fs), alpha=1,Ts=Ts, Fs=Fs)
t_rrc = np.arange(len(rrc)) / Fs
plt.plot(t_rrc/Ts, rrc)
plt.show()

# Now give us coefficients in A(2,13) format
for coeff in rrc:
    fp_coeff = int((2**13)*coeff);
    print(format(fp_coeff & 0xffff, '04x'))

Esempio n. 11
0
    l = 0
    for line in fileobject:
        reading = line[0:line.find(",")]
        raw_samples.append(complex(reading))
        l = +1
fileobject.close()
# print(raw_samples)

#################Read From Textfile##################

# set carrier frequency
fsy = 100000
samplefreq = 2.4e6
fsymrate = 1.3e9  # + fsy

time, h_t = rrcosfilter(30000, 0.5, 8 / fsy, fsy)
# h_t = h_t/np.max(h_t)
# raw_samples = raw_samples/np.max(raw_samples)
jaaaa = signal.fftconvolve((raw_samples), h_t, mode='full')
# rawsquare = np.square(raw_samples)
# mag = np.sqrt(jaaaa.real()**2 + jaaaa.imag()**2)
jaaaa = jaaaa[15000:45000]  # /np.max(jaaaa)

t = np.arange(0, 30000 / samplefreq, 1 / samplefreq)
clock = 0.5 * np.cos(fsy * 2 * np.pi * t + 22 * np.pi / 10) + .5  # vir DBPSK

print(t[0:10])
print(time[0:10])

plt.figure()
plt.plot(np.real(jaaaa), label='filter')
Esempio n. 12
0
def main():

    ## Inicializacion de simbolos a transmitir
    symbolsI = 0x1AA
    symbolsQ = 0x1FE

    ## Filtro Tx y Rx
    #Filtro Root Raised Cosine
    rc = rrcosfilter(int(Nbauds * os), beta, T, 1. / Ts)[1]
    #Normalizacion
    #(t,rc)=rrcosine(beta, T, os, Nbauds)
    rc = rc[:24]
    #rc=rc/np.linalg.norm(rc) #lialg.norm ----> Raiz de la suma de los cuadrados de los coeficientes
    rc = rc / np.sqrt(float(os))

    # ### FIR para Canal
    # #Filtro Root Raised Cosine
    #rch=rcosfilter(int(Nbauds_ch*os),beta,T_ch,1./Ts_ch)[1]
    #(t,rch)=rcosine(beta, T_ch, os_ch, Nbauds_ch,0)
    # # #Normalizacion fir del canal
    #rch=rch[:28]

    rch = np.zeros(28)
    rch[13] = 1
    #rch=rch/np.linalg.norm(rch) #lialg.norm ----> Raiz de la suma de los cuadrados de los coeficientes
    #rch=rch/np.sqrt(float(os))
    canal = np.convolve(
        rc, rch
    )  ## filtro equivalente, resultado de la convolucion de filtro Tx y FIR canal

    ###---------------------------------------------------
    ####Calculos de energia de filtros
    #Tx
    energia_tx = 0
    for p in range(len(rc)):
        energia_tx = energia_tx + (rc[p]**2)
    print "Energia Tx = ", energia_tx

    ##FIR canal
    energia_rch = 0
    for q in range(len(rch)):
        energia_rch = energia_rch + (rch[q]**2)
    print "Energia rch = ", energia_rch

    ##Filtro equivalente de Tx y FIR , canal equivalente
    energia_fir_equiv = 0
    for w in range(len(canal)):
        energia_fir_equiv = energia_fir_equiv + (canal[w]**2)

    print "Energia canal equivalente: ", energia_fir_equiv

    ###---------------------------------------------------
    #Grafica de respuesta al impulso del filtro
    graf_respImpulso(rc, "Filtro Transmisor Tx")
    graf_respImpulso(rch, "Filtro Canal")
    graf_respImpulso(canal, "Rc Rch")
    # plt.show(block=False)
    # raw_input('Press Enter to Continue')
    # plt.close()

    # exit(0)
    # plt.show(block=False)
    # raw_input('Press Enter to Continue')
    # plt.close()

    # exit()

    #Respuesta en frecuencia
    # [H0,A0,F0]=resp_freq(rc, Ts, Nfreqs)

    #Grafica de respuesta en frecuencia del filtro
    # graf_respFrecuencia(H0,A0,F0,"Filtro Transmisor")

    # rcoseno=np.convolve(rc,rc)

    #Grafica de respuesta al impulso del filtro
    # graf_respImpulso(rcoseno,"convolucion filtro transmisor y receptor")

    #Respuesta en frecuencia
    # [H1,A1,F1]=resp_freq(rcoseno, Ts, Nfreqs)

    #Grafica de respuesta en frecuencia del filtro
    # graf_respFrecuencia(H1,A1,F1,"convolucion filtro transmisor y receptor")

    #Shift register del transmisor y receptor
    shift_tx_I = np.zeros(24)
    shift_tx_Q = np.zeros(24)
    shift_rx_I = np.zeros(24)
    shift_rx_Q = np.zeros(24)

    #Bit transmitidos para comparar en la BER
    trans_berI = np.zeros(1024)
    trans_berQ = np.zeros(1024)

    #Bit recibios para comprar en la BER
    recib_berI = np.zeros(511)
    recib_berQ = np.zeros(511)

    #Salida del filtro transmisor
    out_tx_I = 0
    out_tx_Q = 0

    #Salida de del canal mas el ruido
    # out_ch_I=0
    # out_ch_Q=0

    #Valor obtenido del Slicer (detector)
    ak_I = 0
    ak_Q = 0

    y_I = 0
    y_Q = 0

    offset = 1

    phase_I = np.zeros(4)
    phase_Q = np.zeros(4)

    #Variables utilizadas en la sincronizacion
    error_actual = 0
    error_minimo = 99999
    pos_trans = 0
    pos_aux = 0
    cont_ber = 0

    #Variables utilizadas post sincronizacion
    error_final = 0
    cant_muestras = 0

    #Habilitacion Prbs, Ber
    value = 0

    delta = 0.0115
    # delta=0.005

    #Cantidad de coeficientes FIR del ecualizador
    Ntap = 31

    #Memoria del filtro FIR Ecualizador
    mem_fir_adap_I = np.zeros(Ntap)
    mem_fir_adap_Q = np.zeros(Ntap)

    #Coeficientes del filtro FIR del ecualizador adaptativo
    coef_fir_adap_I = np.zeros(Ntap)
    coef_fir_adap_Q = np.zeros(Ntap)

    #Pos 15 = 1 inicializacion
    coef_fir_adap_I[(Ntap - 1) / 2] = 1
    coef_fir_adap_Q[(Ntap - 1) / 2] = 1

    diezmado = 2

    end_sync = 0  #Bandera indica fin etapa de sincronizacion (1)

    graficar = 0  #Cuando esta en 1 almacena valores para luego graficar

    # #Memoria del canal
    mem_canal_I = np.zeros(len(rch))
    mem_canal_Q = np.zeros(len(rch))

    #Maximos y minimos
    max_rx = np.zeros(9)
    #Ponderacion
    #vect_pond=[0.93,0.74,0.70,0.64,0.56,0.52,0.48,0.44,0.4] impulso con /2
    #vect_pond=[0.93,0.65,0.62,0.53,0.47,0.42,0.38,0.33,0.28] impulso

    #vect_pond=[0.49,0.42,0.40,0.37,0.36,0.33,0.30,0.27,0.25] dividio 2
    vect_pond = [0.5, 0.36, 0.33, 0.31, 0.28, 0.25, 0.22, 0.19, 0.17]
    #Usados para graficar
    senial_transmitir_I = []
    senial_transmitir_Q = []

    senial_recibida_I = []
    senial_recibida_Q = []

    senial_recibida_diezmada_I = []
    senial_recibida_diezmada_Q = []

    coeficientes = []

    error_tiempo = []

    input_equ = []
    input_equ_m = []
    input_equ_2 = []
    output_tx = []
    var_tx = []
    var_rx = []
    var_ch = []
    #CURVA BER SIMULADA
    snr = [100., 16., 14., 12., 10., 8., 6., 4., 2.]
    ber = []
    #2097153

    snr_iteraciones = [
        100000 + 2097153, 100000 + 1000000, 100000 + 1000000, 100000 + 1000000,
        100000 + 1000000, 100000 + 1000000, 100000 + 1000000, 100000 + 1000000,
        100000 + 1000000
    ]
    # snr_iteraciones=[100000,100000,100000,100000,100000,100000,100000,100000,100000]

    for t in range(len(snr_iteraciones)):
        error_final = 0
        noise_vector_I = noise(snr[t], snr_iteraciones[t], energia_fir_equiv /
                               1.2)  #genero senial de ruido
        noise_vector_Q = noise(snr[t], snr_iteraciones[t],
                               energia_fir_equiv / 1.2)
        print "snr_iter: ", snr_iteraciones[t]
        print "snr", snr[t]

        for i in range(0, snr_iteraciones[t]):
            value = i % os
            if (i == 0):
                sym_t_I = 0
                sym_t_Q = 0
            else:
                sym_t_I = out_ch_I + noise_vector_I[i]
                sym_t_Q = out_ch_Q + noise_vector_Q[i]

            shift_tx_I = ShiftReg(shift_tx_I)
            shift_tx_Q = ShiftReg(shift_tx_Q)

            if (value == 0):  #es multiplo de 4?
                symbolsI = PRBS9(symbolsI)  #Generacion de simbolos
                symbolsQ = PRBS9(symbolsQ)
                if ((symbolsI >> 8) & 0x001 == 0):
                    shift_tx_I[0] = 1
                else:
                    shift_tx_I[0] = -1

                if ((symbolsQ >> 8) & 0x001 == 0):
                    shift_tx_Q[0] = 1
                else:
                    shift_tx_Q[0] = -1

                trans_berI = ShiftReg(trans_berI)
                trans_berQ = ShiftReg(trans_berQ)

                trans_berI[0] = shift_tx_I[
                    0]  #Agrego nuevo valor transmitido a arreglo bits transmitidos
                trans_berQ[0] = shift_tx_Q[0]

            else:  #Oversampling
                shift_tx_I[0] = 0
                shift_tx_Q[0] = 0

            ## Convolucion transmisor, senial transmitida
            out_tx_I = np.sum(rc * shift_tx_I)
            out_tx_Q = np.sum(rc * shift_tx_Q)

            # if(i%4):
            #     var_tx.append(out_tx_I)

            # ###
            # Canal
            # ###
            mem_canal_I = ShiftReg(
                mem_canal_I)  #corrimiento de memoria del canal
            mem_canal_Q = ShiftReg(mem_canal_Q)

            mem_canal_I[
                0] = out_tx_I  #agregamos nuevo valor de salida de Tx a la memoria
            mem_canal_Q[0] = out_tx_Q

            out_ch_I = np.sum(mem_canal_I * (rch))  #salida Tx pasa por canal
            out_ch_Q = np.sum(mem_canal_Q * (rch))

            # if(i%4):
            #     var_ch.append(out_ch_I)

            shift_rx_I = ShiftReg(shift_rx_I)
            shift_rx_Q = ShiftReg(shift_rx_Q)

            shift_rx_I[0] = sym_t_I
            shift_rx_Q[0] = sym_t_Q

            ##Convolucion receptor, senial recibida
            rx_I = np.sum(rc * shift_rx_I)
            rx_Q = np.sum(rc * shift_rx_Q)

            # if(max_rx[t]<rx_I):
            #     max_rx[t]=rx_I

            rx_I = rx_I * vect_pond[t]
            rx_Q = rx_Q * vect_pond[t]

            input_equ.append(rx_I)
            # if(rx_I>1.0):
            #     input_equ_m.append(abs(rx_I))

            ####
            ###FIR ECUALIZADOR
            #####
            if ((i % 2 != 0) and (i != 0)):  #nos quedamos con muestras 1 y 3

                mem_fir_adap_I = ShiftReg(mem_fir_adap_I)
                mem_fir_adap_Q = ShiftReg(mem_fir_adap_Q)

                mem_fir_adap_I[0] = rx_I
                mem_fir_adap_Q[0] = rx_Q

            if ((value == 0) and i != 0):

                #for r in range(0,Ntap-1):
                y_I = np.sum(coef_fir_adap_I * mem_fir_adap_I)  #FIR
                y_Q = np.sum(coef_fir_adap_Q * mem_fir_adap_Q)  #FIR

                #Slicer
                ak_I = (2 * (y_I >= 0) - 1)
                ak_Q = (2 * (y_Q >= 0) - 1)

                #------------------------------------------Algoritmo de adaptacion
                error_adap_I = ak_I - y_I
                error_adap_Q = ak_Q - y_Q

                if (i % 8 == 0):
                    coeficientes.append(coef_fir_adap_I.copy())

                for b in range(0, Ntap):
                    coef_fir_adap_I[b] = coef_fir_adap_I[
                        b] + delta * error_adap_I * mem_fir_adap_I[b]
                    coef_fir_adap_Q[b] = coef_fir_adap_Q[
                        b] + delta * error_adap_Q * mem_fir_adap_Q[b]

            ##Ber
            if (i > 100000):
                if ((value == 0) and i != 0):
                    recib_berI = ShiftReg(recib_berI)
                    recib_berQ = ShiftReg(recib_berQ)

                    recib_berI[0] = ak_I  #Bits recibidos
                    recib_berQ[0] = ak_Q  #Bits recibidos

                    if (end_sync == 0):  ##Etapa de sincronizacion
                        if (cont_ber < 511):
                            cont_ber = cont_ber + 1
                        else:  #cont_ber==511
                            cont_ber = 0
                            if (error_actual < error_minimo):
                                print "Error minimo actual: ", error_actual
                                print "Pos error minimo actual: ", pos_trans
                                error_minimo = error_actual
                                error_actual = 0
                                pos_aux = pos_trans
                            else:
                                error_actual = 0

                            if (pos_trans != 1023):
                                pos_trans = pos_trans + 1
                            else:  #finalizo etapa de sincronizacion
                                pos_trans = pos_aux
                                end_sync = 1

                        if (recib_berI[0] != trans_berI[pos_trans]):
                            error_actual = error_actual + 1
                        if (recib_berQ[0] != trans_berQ[pos_trans]):
                            error_actual = error_actual + 1

                    else:  #end_sync==1 pos sincronizacion
                        cant_muestras = cant_muestras + 1
                        if (recib_berI[0] != trans_berI[pos_trans]):
                            error_final = error_final + 1
                        if (recib_berQ[0] != trans_berQ[pos_trans]):
                            error_final = error_final + 1

                        if (i == (snr_iteraciones[t] - 4)):
                            print "snr", snr[t]
                            print "error_final", error_final
                            ber.append(
                                float(error_final) /
                                ((((snr_iteraciones[t] - 100000) / os) * 2)))
                            print ber

    # print "Media Tx",np.mean(output_tx)
    # print "Media", np.mean(input_equ)
    # print "Media", np.mean(input_equ_m)
    # print "VAR_TX", np.var(var_tx)
    # print "VAR_RX", np.var(var_rx)
    # print "VAR_CH", np.var(var_ch)
    # for k in range (0,len(max_rx)):
    #     print "SNR = ", snr[k], " Maximo = ", max_rx[k]

#  print "SNR = %d - Maximo = %d" %(snr[t],max_rx[t])
# suma=0
# for w in range (len(input_equ)):
#     suma=suma + input_equ[w]

    plt.figure()
    plt.title("Entrada Ecualizador")
    plt.plot(input_equ)
    # print "Cantidad de muestras para la media ", len(input_equ)
    # print "MEDIA:", suma/len(input_equ)
    # print "Vector de Maximos", max_rx
    print "BER: ", ber

    #print error_minimo
    #print pos_aux

    ##Grafico de simbolos transmitidos
    #graf_simbTransmitidos(shift_tx_I,shift_tx_Q)

    ### Convolucion transmisor, senial transmitida
    #graf_Convolucion(senial_transmitir_I, "transmitida")

    ##Grafico diagrama ojo transmisor
    #eyediagram(senial_transmitir_I[100:len(senial_transmitir_I)-100],os,0,Nbauds)
    #eyediagram(senial_transmitir_Q[100:len(senial_transmitir_Q)-100],os,0,Nbauds)

    ##Convolucion receptor, senial recibida
    #graf_Convolucion(var_rx,"recibida")

    ##Grafica curvas Ber-teorica y simulada
    #graf_BER(snr,ber)

    ##Grafico diagrama ojo receptor
    #   eyediagram(senial_recibida_I[100:len(senial_recibida_I)-100],os,0,Nbauds)
    #    eyediagram(senial_recibida_Q[100:len(senial_recibida_Q)-100],os,0,Nbauds)
    # plt.figure()
    # plt.plot(senial_recibida_I)
    ##Constelaciones
    # plt.figure()
    # plt.title("Constelaciones")
    # plt.plot(senial_recibida_diezmada_I[(offset):len(senial_recibida_diezmada_I)-((offset)):int(os)],
    #      senial_recibida_diezmada_Q[(offset):len(senial_recibida_diezmada_Q)-((offset)):int(os)],
    #          'r.',linewidth=2.0)
    # plt.axis('equal')
    # plt.grid(True)
    # plt.xlabel('Real')
    # plt.ylabel('Imag')

    # plt.figure()
    # plt.title("Error en la adaptacion")
    # plt.plot(error_tiempo)

    plt.figure()
    plt.title("Coeficientes en el tiempo")
    plt.plot(coeficientes)

    # print len(coeficientes)
    plt.figure()
    plt.title("Ultimos coeficientes del filtro FIR")
    plt.stem(coeficientes[len(coeficientes) - 1])

    #equa=np.convolve(rcoseno,np.transpose(coeficientes[len(coeficientes)-1]))

    # ## Grafica de respuesta al impulso del filtro
    # graf_respImpulso(equa,"a la salida del equalizador")

    # ## Respuesta en frecuencia
    # [H2,A2,F2]=resp_freq(equa, Ts, Nfreqs)
    # ## Grafica de respuesta en frecuencia del filtro
    # graf_respFrecuencia(H2,A2,F2,"a la salida del ecualizador")

    plt.show(block=False)
    raw_input('Press Enter to Continue')
    plt.close()
Esempio n. 13
0
def evmMeter(signalIn, symbolsIn, fs, freqMix, debugMode=False):
    # Generating reference signal
    ts = 1e-6
    osr = int(fs * ts)
    numberSamples = int(8 * osr)
    time, pulseShape = com.rrcosfilter(numberSamples, 0.5, ts, fs)
    symbolsUp = np.zeros(
        symbolsIn.size * osr) + 1j * np.zeros(symbolsIn.size * osr)
    symbolsUp[0::osr] = symbolsIn
    phaseInc = 2 * np.pi * freqMix / fs * np.ones(symbolsUp.size +
                                                  pulseShape.size - 1)
    signalRef = np.convolve(symbolsUp, pulseShape) * np.exp(
        1j * phaseInc.cumsum())

    #timeMix = np.arange(0, symbolsUp.size + pulseShape.size - 1) * (1 / fs)
    #signalRef = np.convolve(symbolsUp, pulseShape) * np.exp(2j * np.pi * freqMix * timeMix)

    signalRefLevel = np.sqrt(np.abs(np.mean(signalRef * signalRef.conj())))
    if (debugMode):
        signalPlotting(signalRef, fs, 'Signal Ref')
        signalPlotting(signalIn, fs, 'Signal Ref')

    if (debugMode):
        fig1, (ax1, ax12) = plt.subplots(figsize=(10, 8),
                                         dpi=80,
                                         facecolor='w',
                                         edgecolor='k',
                                         ncols=1,
                                         nrows=2,
                                         sharex=False)
        ax1.plot(signalRef.real, 'b', label='real')
        ax1.plot(signalRef.imag, 'r', label='imag')
        ax1.set_title(
            f'Signal Ref Level = {signalRefLevel} with length {signalRef.size}'
        )
        ax1.legend()
        ax12.plot(signalIn.real, 'b', label='real')
        ax12.plot(signalIn.imag, 'r', label='imag')
        ax12.set_title(f'Signal In with length {signalIn.size}')
        ax12.legend()

    # Calculate EVM

    # Check lenghts are ok
    if signalIn.size < signalRef.size:
        raise SyntaxError(
            'ERROR: DSPFunctions::evmMeter - Signal is shorter than reference.'
        )

    crossCorrelSignal = np.correlate(signalIn, signalRef, 'full')
    index = np.arange(-np.max([signalIn.size, signalRef.size]) + 1,
                      np.max([signalIn.size, signalRef.size]), 1)
    indexAligned = index[-crossCorrelSignal.size:]
    indexAligned = indexAligned[int(indexAligned.size / 2):]
    crossCorrelSignal = crossCorrelSignal[int(crossCorrelSignal.size / 2):]
    lag = indexAligned[np.abs(crossCorrelSignal).argmax()]
    if (lag < 0):
        raise SyntaxError(
            'ERROR: DSPFunction::evmMeter - index of correlation is negative.')

    if (debugMode):
        fig2, ax2 = plt.subplots(figsize=(10, 8))
        ax2.plot(signalIn.real, 'b', label='Signal In Real')
        ax2.plot(signalRef.real, 'g', label='Signal Ref Real')
        ax2.plot(indexAligned,
                 np.abs(crossCorrelSignal) / np.abs(crossCorrelSignal).max(),
                 'r',
                 label='CrossCorrelation')
        ax2.set_title(f'Cross-correlation lag = {lag}')
        ax2.legend()

    # chopping signals
    signalInChop = signalIn[lag:]
    if (debugMode):
        print('Lag = ', lag, 'signalInChop = ', signalInChop.size,
              'signalIn = ', signalIn.size)
        print(signalIn[:10].real * 1e3)
        print(signalInChop[:10].real * 1e3)
    signalLen = np.min([signalInChop.size, signalRef.size])
    if (debugMode):
        print('signalInChop = ', signalInChop.size)
        print('signalLen = ', signalLen)
    signalInChop = signalInChop[:signalLen]
    signalRefChop = signalRef[:signalLen]
    if (debugMode):
        print('signalLen = ', signalLen)
        print(signalIn[:10].real * 1e3)
        print(signalInChop[:10].real * 1e3)

    if (debugMode):
        print('signalInChop = ', signalInChop.size, ' signalRefChop = ',
              signalRefChop.size)

    if (debugMode):
        fig3, (ax3, ax4) = plt.subplots(figsize=(10, 8),
                                        dpi=80,
                                        facecolor='w',
                                        edgecolor='k',
                                        ncols=1,
                                        nrows=2,
                                        sharex=False)
        signalInChopLevel = np.sqrt(
            np.abs(np.mean(signalInChop * signalInChop.conj())))
        gain = signalRefLevel / signalInChopLevel
        ax3.plot(signalRefChop.real, 'b', label='Ref real')
        ax3.plot(gain * signalInChop.real, 'r--', label='Signal In real')
        ax3.legend()
        ax3.set_title(f'Signal ref Chopped - length = {signalRefChop.size}')
        ax4.plot(signalRefChop.imag, 'b', label='Ref imag')
        ax4.plot(gain * signalInChop.imag, 'r--', label='Signal In imag')
        ax4.legend()
        ax4.set_title(f'Signal In Chopped - length = {signalInChop.size}')

    # Input Signal level and rotation
    signalInLevel = np.sqrt(np.abs(np.mean(signalInChop *
                                           signalInChop.conj())))
    signalInRot = (signalRefLevel / signalInLevel) * np.exp(
        -1j * np.angle(crossCorrelSignal.max())) * signalInChop
    if (debugMode):
        fig5, ax5 = plt.subplots(figsize=(10, 8))
        ax5.plot(signalInRot.real, 'b', label='Rot Real')
        ax5.plot(signalInRot.imag, 'r', label='Rot Imag')
        ax5.plot(gain * signalInChop.real, 'b--', label='Org Real')
        ax5.plot(gain * signalInChop.imag, 'r--', label='Org Imag')
        ax5.set_title(
            f'Rot Signal angle {np.angle(crossCorrelSignal.max())}, signalRefLevel = {signalRefLevel}, signalInLevel = {signalInLevel}'
        )
        ax5.legend()

    # Error Vector
    errorVector = signalInRot - signalRefChop
    rmsRef = np.sqrt(np.mean(np.abs(signalRefChop)**2))
    evmValue = 20 * np.log10(
        np.sqrt(np.mean(np.abs(np.abs(errorVector)**2))) / rmsRef)
    if (debugMode):
        print('rmsRef = ', rmsRef)
        fig6, (ax6a, ax6b) = plt.subplots(figsize=(10, 8),
                                          dpi=80,
                                          facecolor='w',
                                          edgecolor='k',
                                          ncols=1,
                                          nrows=2,
                                          sharex=False)
        ax6aa = ax6a.twinx()
        ax6a.plot(signalInRot.real, 'r', label='Rot Real')
        ax6a.plot(signalRef.real, 'b--', label='Ref Real')
        ax6aa.plot(20 * np.log10(errorVector.real / rmsRef),
                   'k',
                   label='Error')
        ax6aa.legend()
        ax6bb = ax6b.twinx()
        ax6b.plot(signalInRot.imag, 'r', label='Rot Imag')
        ax6b.plot(signalRef.imag, 'b--', label='Ref Imag')
        ax6bb.plot(20 * np.log10(errorVector.imag / rmsRef),
                   'k',
                   label='Error')
        ax6bb.legend()
        ax6a.set_title(f'EVM = {evmValue}')

    plt.show()

    return (evmValue)
Esempio n. 14
0
def main():

    rrcos = rrcosfilter(NBAUDS * UPSAMPLE, ROLL_OFF, 1. / BAUD_RATE,
                        SAMPLE_RATE)[1]
    rrcos = rrcos / np.sqrt(UPSAMPLE)
    rrcos_fixed = arrayFixedInt(COEF_NBITS, COEF_FBITS, rrcos)

    prbs_r = prbs(SEED_R)
    tx_r = tx(rrcos_fixed, UPSAMPLE, COEF_NBITS, COEF_FBITS, TX_NBITS,
              TX_FBITS)
    rx_r = rx(rrcos_fixed, UPSAMPLE, COEF_NBITS, COEF_FBITS, TX_NBITS,
              TX_FBITS)
    ber_r = ber(SEQ_LEN)

    rrcos_float = [i.fValue for i in rrcos_fixed]

    prbs_r_v = []
    tx_r_v = []
    rx_r_v = []
    rx_full_v = []

    prbs_r.reset()
    tx_r.reset()
    rx_r.reset()
    ber_r.reset()

    phase = DX_SWITCH_SEL
    prbs_r_s = prbs_r.prbs_out
    tx_r_s = tx_r.tx_out
    rx_r_s = rx_r.rx_out

    enable_prbs = 0
    enable_tx = 1
    enable_rx = 1
    enable_ber = 0

    counter = 0

    for i in range(NCLK):

        prbs_r_s = prbs_r.prbs_out
        tx_r_s = tx_r.tx_out
        rx_r_s = rx_r.rx_out
        rx_full_out = rx_r.rx_full_out

        prbs_r_v.append(prbs_r_s)
        tx_r_v.append(tx_r_s.fValue)
        rx_r_v.append(rx_r_s)
        rx_full_v.append(rx_full_out.fValue)

        prbs_r.run(enable_prbs)
        ber_r.run(prbs_r_s, rx_r_s, enable_ber)
        rx_r.run(tx_r_s, phase, enable_rx)
        tx_r.run(prbs_r_s, enable_tx)

        if counter == 0:
            enable_prbs = 1
            enable_ber = 1
        else:
            enable_prbs = 0
            enable_ber = 0
        counter = (counter + 1) % 4

    vector = zip(range(NCLK), prbs_r_v, tx_r_v, rx_full_v, rx_r_v)
    """
    for i in vector[0:20]:
        print i
    exit()
    """

    plt.figure()
    plt.grid()
    plt.plot(tx_r_v[:200])

    plt.figure()
    plt.grid()
    plt.plot(rx_full_v[:200])
    rx_a = arrayFixedInt(8, 7, rx_full_v[:200])
    rx_a = [i.fValue for i in rx_a]
    plt.figure()
    plt.grid()
    plt.plot(rx_a)
    """
    eyediagram(rx_full_v[12:], 4, 1, UPSAMPLE)

    rrcos_float = [i.fValue for i in rrcos_fixed]
    H,A,F = resp_freq(rrcos_float, 1./BAUD_RATE, 512)
    plt.figure()
    plt.grid()
    plt.semilogx(F, 20*np.log(H))

    plt.figure()
    plt.grid()
    plt.plot([i.fValue for i in rrcos_fixed])
    """

    plt.show()
Esempio n. 15
0
    l = 0
    for line in fileobject:
        reading = line[0:line.find(",")]
        raw_samples.append(complex(reading))
        l = +1
fileobject.close()
# print(raw_samples)

#################Read From Textfile##################

# set carrier frequency
fsy = 100000
samplefreq = 2.4e6
fsymrate = 1.3e9  #+ fsy

time, h_t = rrcosfilter(300000, 0.5, 1 / fsy, samplefreq)
#h_t = h_t/np.max(h_t)
#raw_samples = raw_samples/np.max(raw_samples)
jaaaa = signal.fftconvolve((raw_samples), h_t, mode='full')
#rawsquare = np.square(raw_samples)
#mag = np.sqrt(jaaaa.real()**2 + jaaaa.imag()**2)
jaaaa = jaaaa[15000:45000]  #/np.max(jaaaa)

t = np.arange(0, 30000 / samplefreq, 1 / samplefreq)
clock = 0.5 * np.cos(fsy * 2 * np.pi * t + 25 * np.pi / 5) + .5  #vir DBPSK
clock2 = 0.5 * np.cos(samplefreq * 2 * np.pi * time +
                      5 * np.pi / 5) + .5  #vir DBPSK

no_zerosH = []
ons_sample_hier_jaH = np.zeros([300000], dtype=complex)
flaggie = 0  ##################################################################Die issue is dalk hier
Esempio n. 16
0
import numpy as np
from random import randint
from commpy.modulation import QAMModem
from commpy.filters import rrcosfilter
from commpy.utilities import bitarray2dec, dec2bitarray

np.set_printoptions(threshold=np.nan)
N = 1024  # output size
M = 16
mod1 = QAMModem(M)  # QAM16
sB = dec2bitarray(randint(0, 2**(mod1.num_bits_symbol * N * M / 4)),
                  (mod1.num_bits_symbol * N * M / 4))  # Random bit stream
# print np.array2string(sB)
sQ = mod1.modulate(sB)  # Modulated baud points
print np.array2string(np.abs(sQ))
sPSF = rrcosfilter(N * 4, 0.2, 1, 4000)[1]
qW = np.convolve(sPSF, sQ)  # Waveform with PSF
#print np.array2string(qW)