# -*- coding: utf-8 -*-
"""RisetSiskom.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1AaHJHVsp1D5IcVYTwnoThoYGOW89bHmd
"""

import numpy as np
import matplotlib.pyplot as plt
import math
from scipy.signal import hilbert
 
def bpsk(bit): #modulasi
  return 2*bit-1 
 
def awgn(x,SNR):
  snr = 10**(SNR/10) #numerik
  sigma = np.matrix(np.sqrt(1/(2*snr)))
  n = sigma*(np.random.randn(len(x))+np.random.randn(len(x))*1j)
  return x+n
 
#inisiasi
snr = np.arange(0,15,1)
ber = np.zeros((len(snr)))
nbit = int(1e4)
bit = np.random.randint(0,2,nbit)
modulasi = bpsk(bit)
 
for i in range (0,len(snr)):
  noise = awgn(modulasi,snr[i]).A1
  demod = (noise.real>0)*1
  ber[i] = sum((demod!=bit)*1)/nbit
print(bit)
print(len(snr))
print('noise= ', noise)
print('demod= ', demod)
plt.semilogy(snr,ber)
plt.xlabel('SNR')
plt.ylabel('BER')
print(modulasi)

"""Bawah sini"""

def qpsk(bit): #modulasi
  ban = int(len(bit)/2)
  sym = np.zeros(ban).astype('complex128')
  for to in range(0,ban):
   sym[to] = (1-2*bit[2*to])+(1-2*bit[2*to+1])*1j
  return sym

def awgn(x,SNR):
  snr = 10**(SNR/10)
  sigma = np.matrix(np.sqrt(1/(2*snr)))
  n = sigma*(np.random.randn(len(x))+np.random.randn(len(x))*1j)
  return x+n

snr = np.arange(0,15,1)
ber = np.zeros((len(snr)))
nbit = int(1e4)
bit = np.random.randint(0,2,nbit)   #GENERATE BIT
modulasi = qpsk(bit)                #MODULASI
demodqpsk = np.zeros(0)


for i in range (0,len(snr)):
  noise = awgn(modulasi,snr[i]).A1
  for j in range(0,len(noise)):
    demod[2*j] = (noise[j].real<0)*1 #demod
    demod[2*j+1] = (noise[j].imag<0)*1 #demod
    a = np.array(demod[2*j])
    b = np.array(demod[2*j+1])
    demodd = np.array((a,b)) #gabung
    demodqpsk = np.append(demodqpsk, demodd) #selangseling
  ber[i] = sum((demodqpsk!=bit)*1)/nbit
  demodqpsk = np.zeros(0)

print('bit= ', bit)
print('modulasi= ', modulasi)
print('noise = ', noise)
print('print a = ', a)
print('print b = ', b)
print('demodd= ', demodd)
print('demodulasi= ', demodqpsk)  
plt.semilogy(snr,ber)
plt.xlabel('SNR')
plt.ylabel('BER')

print(ber.shape)
print(noise.shape)

print(bit)
print(modulasi)





"""#FM MODULASI-DEMODULASI"""

sampling_freq = 1000
  T = 1/sampling_freq
  fm = 5
  fc = 40
  fdev=0.2*fc
  ts = np.arange(0,1-T,T)
  ts2 = np.arange(0,998)
  xm = np.cos(2*np.pi*fm*ts) #info
  xc = np.cos(2*np.pi*fc*ts) #carrier
  xmint= np.sin(2*np.pi*fm*ts) #integral Xm
  mf=100 # Modulation factor
  xt = np.cos((2*np.pi*fc*ts+mf*xmint)) #Modulated carrier



def fm_demod(x, df=1.0, fc=0.0):

    # Making complex signal from real values input
    z = hilbert(x)

    # Remove carrier.
    n = np.arange(0,len(z))
    rx = z*np.exp(-1j*2*np.pi*fc*n)

    # Extract phase of carrier.
    phi = np.arctan2(np.imag(rx), np.real(rx))

    # Calculate frequency from phase.
    y = np.diff(np.unwrap(phi)/(2*np.pi*df))
    
    return y

xd = fm_demod(xc,10,fc) # Demodulated signal
data = np.fft.rfft(xd) # Demodulated signal spectrum
plt.plot(ts,xm,'y-',label="Modulating signal")
plt.xlabel("waktu")
plt.ylabel("amplitudo")
plt.title("information signal")
plt.grid()
plt.show()

plt.plot(ts,xc,'r',label="Modulated signal")
plt.xlabel("Jarak (km)")
plt.ylabel("Daya Terima (dBm)")
plt.title("carrier signal")
plt.grid()
plt.show()

plt.plot(ts,xt,'y-',label="Modulating signal")
plt.xlabel("waktu")
plt.ylabel("amplitudo")
plt.title("Modulated signal")
plt.grid()
plt.show()

plt.plot(ts2,xd,'b-',label="Modulated signal")
plt.xlabel("frekuensi")
plt.ylabel("amplitudo")
plt.title("demodulated signal")
plt.grid()
plt.show()

"""#AM MODULATION"""

A_c = float(input('masukkan carrier amplitude: '))
f_c = float(input('masukkan  carrier frquency: '))
A_m = float(input('masukkan  message amplitude: '))
f_m = float(input('masukkan  message frquency: '))
t = np.linspace(0, 1, 1000)
def am_carrier(ac, fc, t):
  return A_c*np.cos(2*np.pi*f_c*t)

def am_info(am, fm, t):
  return A_m*np.cos(2*np.pi*f_m*t)

def AM_Modulation(am, ac, fc, fm, t): 
  return ((A_c*A_m)/2)*np.cos((2*np.pi)*(f_c+f_m)*t)

product = AM_Modulation(A_m, A_c, f_c, f_m, t) #ammodulation
sinyalinfo = am_info(A_m, f_m, t)
sinyalcarrier = am_carrier(A_c, f_c, t)

plt.subplot(3,1,1)
plt.title('Amplitude Modulation')
plt.plot(t, sinyalinfo, 'g')
plt.ylabel('Message signal')
plt.xlabel('waktu')

plt.subplot(3,1,2)
plt.plot(t, sinyalcarrier, 'r')
plt.ylabel('Carrier signal')
plt.xlabel('waktu')

plt.subplot(3,1,3)
plt.plot(t, product, color="purple")
plt.ylabel('AM signal')
plt.xlabel('waktu')

plt.subplots_adjust(hspace=1)
plt.rc('font', size=15)
fig = plt.gcf()
fig.set_size_inches(16, 9)

fig.savefig('Amplitude Modulation.png', dpi=100)

from scipy.signal import butter, lfilter, freqz
t = np.linspace(0, 1, 1000, endpoint=False)
# Filter requirements.
order = 6
fs = 1000      # sample rate, Hz
cutoff = 3.667  # desired cutoff frequency of the filter, Hz

def butter_lowpass_filter(data, cutoff, fs, order=5):
    b, a = butter_lowpass(cutoff, fs, order=order)
    y = lfilter(b, a, data)
    return y

b, a = butter_lowpass(cutoff, fs, order)

# "Noisy" data.  We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)

# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)

plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()

plt.subplots_adjust(hspace=0.35)
plt.show()