Friday, January 17, 2020

qpsk

from numpy import ones,arange,cos,sin,pi
from matplotlib.pyplot import plot,subplot,title,xlabel,ylabel,show
M =4#
i = range(0,M)
t = arange(0,0.001+1,0.001)
s1=ones([len(i),len(t)])
s2=ones([len(i),len(t)])
for i in range(0,M):
  s1[i,:] = [cos(2*pi*2*tt)*cos((2*i-1)*pi/4) for tt in t]
  s2[i,:] = [-sin(2*pi*2*tt)*sin((2*i-1)*pi/4) for tt in t]
S1 =[]#
S2 = []#
S = []#
m =[0,1,0,1,1,0,1,1]
for i in range(0,len(m)):
  S1 = s1[m[i],:]
  S2 = s2[m[i],:]
  S = S+[S1*S2]
subplot(3,1,1)
plot(S1)
title('Binary PSK wave of Odd-numbered bits of input sequence')
subplot(3,1,2)
plot(S2)
title('Binary PSK wave of Even-numbered bits of input sequence')
subplot(3,1,3)
plot(S)
title('QPSK waveform')
show()

rayleigh

from numpy import ones,arange,cos,sin,pi
from math import log10,sqrt,exp
import random
import matplotlib.pyplot as plt
N = 10000
EbNodB_range = range(0, 11)
itr = len(EbNodB_range)
ber = [None]*itr
tx_symbol = 0
noise = 0
ch_coeff = 0
rx_symbol = 0
det_symbol = 0
for n in range (0, itr):
     EbNodB = EbNodB_range[n] 
     EbNo=10**(EbNodB/10.0)
     noise_std = 1/sqrt(2*EbNo)
     noise_mean = 0
     no_errors = 0
     for m in range (0, N):
      tx_symbol = 2*random.randint(0,1)-1
      noise = random.gauss(noise_mean, noise_std)
      ch_coeff = sqrt(random.gauss(0,1)**2+random.gauss(0,1)**2)/sqrt(2)
      rx_symbol = tx_symbol*ch_coeff + noise
      det_symbol = 2 * (rx_symbol >= 0) - 1
      no_errors += 1*(tx_symbol != det_symbol) 
      ber[n] = no_errors / N
print("EbNodB:", EbNodB)
print ("Numbder of errors:", no_errors)
print ("Error probability:", ber[n])
plt.plot(EbNodB_range, ber, 'bo-')
plt.axis([0, 10, 0, 0.1])
#plt.xscale('linear')
#plt.yscale('log')
plt.xlabel('EbNo(dB)')
plt.ylabel('BER')
#plt.grid(True)
plt.title('BPSK Modulation')
plt.show()

block codes

#Program to generate parity check matrix
from numpy import ones,zeros,identity,transpose,hstack,mat
n=5
k=1
m=1
I=identity(n-k)
P=ones(n-k)
I=mat(I)
P=mat(P)
H=hstack([I,transpose(P)])
print('\n parity check matrix\n',H)
print('\n identity matrix\n',I)

#Program to generate code vectors
from numpy import ones,zeros,identity,multiply,mat,concatenate,hstack,transpose
from pylab import show
k=4
n=7
d=n-k
I=identity(k)
I=mat(I)
print('identity matrix Ik\n',I)
p=[[1,1,0],[0,1,1],[1,1,1],[1,0,1]]
p=mat(p)
print('\n coefficient matrix p\n',p)
G=hstack([p,I])
print('generator matrix G\n',G)
H=hstack([identity(k-1),transpose(p)])
print('parity check matrix H\n',H)
d=[[0,0,0,0],[0,0,0,1],[0,0,1,0],[0,0,1,1],
   [0,1,0,0],[0,1,0,1],[0,1,1,0],[0,1,1,1],
   [1,0,0,0],[1,0,0,1],[1,0,1,0],[1,0,1,1],
   [1,1,0,0],[1,1,0,1],[1,1,1,0],[1,1,1,1]]
c=d*G
c=(c%2)
print('codes block of(7,4)hamming code\n',c)

sampling

from matplotlib.pyplot import plot,axis,show
from numpy import linspace,cos,pi,ceil,floor,arange
f=40
tmin=-0.3
tmax=0.3
t=linspace(tmin,tmax,800)
x=cos(2*pi*f*t)
plot(t,x)
T=1/80
nmin=ceil(tmin/T)
nmax=floor(tmax/T)
n=arange(nmin,nmax)
x1=cos(2*pi*n*T*f)
plot(n*T,x1)
T=1/35
nmin=ceil(tmin/T)
nmax=floor(tmax/T)
n=arange(nmin,nmax)
x2=cos(2*pi*n*T*f)
plot(n*T,x2)
T=1/100
nmin=ceil(tmin/T)
nmax=floor(tmax/T)
n=arange(nmin,nmax)
x3=cos(2*pi*n*T*f)
plot(n*T,x3)
show()

Wednesday, January 1, 2020

dpsk

from __future__ import division
from numpy import ones,arange,cos,sin,pi
import numpy as np
from matplotlib.pyplot import plot,subplot,title,xlabel,ylabel,show,legend,grid,subplot
Fs =150.0;  # sampling rate
Ts = 1.0/Fs; # sampling interval
freq=10
t = np.arange(0,2,Ts)
bk = [1,0,0,1,0,0,1,1]##input digital sequence
bk_not=[]
for i in range(0,len(bk)):
  if(bk[i]==1):
   bk_not.append(0)
  else:
    bk_not.append(1)
dk_1 = [ 1 and bk[0]]#  #initial value of differential encoded sequence
dk_1_not =[ 0 and bk_not[0]]
dk = [dk_1[0]^dk_1_not[0]] #first bit of dpsk encoder
for i in range(1,len(bk)):
  dk_1.append(dk[(i-1)])
  if dk[(i-1)]==1:
     x=0
  else:
    x=1
  dk_1_not.append(x)
  dk.append(((dk_1[i] and bk[i])^(dk_1_not[i] and bk_not[i])))
dk_radians=[]
for i in range(0,len(dk)):
  if(dk[i]==1):
    dk_radians.append(0)
  elif(dk[i]==0):
    dk_radians.append(180)
print ('Table 7.3 Illustrating the Generation of DPSK Signal')
print ('_____________________________________________________')
print ('\n(bk)',bk)
print ('\n(bk_not)',bk_not)
print ('\nDifferentially encoded sequence (dk)')
for dd in dk:
    print (dd,'\t')
print ('\n\nTransmitted phase in radians')
for ddd in dk_radians:
    print (ddd,'\t')
print ('\n\n_____________________________________________________')
bit_arr =np.array([0,180,0,0,180])
samples_per_bit = 2*Fs/bit_arr.size
dd = np.repeat(bit_arr, samples_per_bit)
y= np.sin(2 * np.pi * (freq) * t+(np.pi*dd/180))
plot(t,y)
show()

fft

FFT of two sine waves together
from scipy.fftpack import fft
import matplotlib.pyplot as plt
import numpy as np
# Number of sample points
N = 600
# sample spacing
T = 1.0 / 800.0
x = np.linspace(0.0, N*T, N)
y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)
yf = fft(y)
xf = np.linspace(0.0, 1.0/(2.0*T), N//2)
plt.plot(xf, 2.0/N * np.abs(yf[0:N//2]))
plt.grid()
plt.show()

QPSK
 from numpy import ones,arange,cos,sin,pi
from matplotlib.pyplot import plot,subplot,title,xlabel,ylabel,show
M =4#
i = range(0,M)
t = arange(0,0.001+1,0.001)
s1=ones([len(i),len(t)])
s2=ones([len(i),len(t)])
for i in range(0,M):
  s1[i,:] = [cos(2*pi*2*tt)*cos((2*i-1)*pi/4) for tt in t]
  s2[i,:] = [-sin(2*pi*2*tt)*sin((2*i-1)*pi/4) for tt in t]
S1 =[]#
S2 = []#
S = []#
m =[0,1,0,1,1,0,1,1]
for i in range(0,len(m)):
  S1 = s1[m[i],:]
  S2 = s2[m[i],:]
  S = S+[S1*S2]
subplot(3,1,1)
plot(S1)
title('Binary PSK wave of Odd-numbered bits of input sequence')
subplot(3,1,2)
plot(S2)
title('Binary PSK wave of Even-numbered bits of input sequence')
subplot(3,1,3)
plot(S)
title('QPSK waveform')
show()

probability error

Probability Error

from __future__ import division
from numpy import ones,arange,cos,sin,pi
##matplotlib inline
from matplotlib.pyplot import plot,subplot,title,xlabel,ylabel,show,legend,grid
from scipy.special import erfc
from math import log10,sqrt,exp
#Comparison of Symbol Error Probability
#of Different Digital Transmission System
#Eb =  Energy of the bit  No = Noise Spectral Density
Eb_No =[18,0.3162278]
x = arange(Eb_No[1],1/100+Eb_No[0],1./100)
x_dB = [10*log10(xx) for xx in x]
Pe_BPSK=ones(len(x))
Pe_BFSK=ones(len(x))
Pe_DPSK=ones(len(x))
Pe_NFSK=ones(len(x))
Pe_QPSK=ones(len(x))
for i in range(0,len(x)):
  #Error Probability of Coherent BPSK
  Pe_BPSK[i]= (1/2)*erfc(sqrt(x[i]))#
  #Error Probability of Coherent BFSK
  Pe_BFSK[i]= (1/2)*erfc(sqrt(x[i]/2))#
  #Error Probability Non-Coherent PSK = DPSK
  Pe_DPSK[i]= (1/2)*exp(-x[i])#
  #Error Probability Non-Coherent FSK
  Pe_NFSK[i]= (1/2)*exp(-(x[i]/2))#
  #Error Probability of QPSK
  Pe_QPSK[i]= erfc(sqrt(x[i]))-((1/4)*(erfc(sqrt(x[i]))**2))
plot(x_dB,Pe_BPSK)
plot(x_dB,Pe_BFSK)
plot(x_dB,Pe_NFSK)
plot(x_dB,Pe_QPSK)
xlabel('Eb/No in dB ---->')
ylabel('Probability of Error Pe--->')
title('Comparison of Noise Performance of different PSK & FSK Scheme')
legend(['BPSK','BFSK','DPSK','Non-Coherent FSK','QPSK'])
grid()
show()


Rayleigh Fading channel


from numpy import ones,arange,cos,sin,pi
from math import log10,sqrt,exp
import random
import matplotlib.pyplot as plt
N = 10000
EbNodB_range = range(0, 11)
itr = len(EbNodB_range)
ber = [None]*itr
tx_symbol = 0
noise = 0
ch_coeff = 0
rx_symbol = 0
det_symbol = 0
for n in range (0, itr):
     EbNodB = EbNodB_range[n] 
     EbNo=10**(EbNodB/10.0)
     noise_std = 1/sqrt(2*EbNo)
     noise_mean = 0
     no_errors = 0
     for m in range (0, N):
      tx_symbol = 2*random.randint(0,1)-1
      noise = random.gauss(noise_mean, noise_std)
      ch_coeff = sqrt(random.gauss(0,1)**2+random.gauss(0,1)**2)/sqrt(2)
      rx_symbol = tx_symbol*ch_coeff + noise
      det_symbol = 2 * (rx_symbol >= 0) - 1
      no_errors += 1*(tx_symbol != det_symbol) 
      ber[n] = no_errors / N
print("EbNodB:", EbNodB)
print ("Numbder of errors:", no_errors)
print ("Error probability:", ber[n])
plt.plot(EbNodB_range, ber, 'bo-')
plt.axis([0, 10, 0, 0.1])
#plt.xscale('linear')
#plt.yscale('log')
plt.xlabel('EbNo(dB)')
plt.ylabel('BER')
#plt.grid(True)
plt.title('BPSK Modulation')
plt.show()

Tuesday, November 26, 2019

ask fsk psk

import matplotlib.pyplot as plt
import numpy as np
import sys
from scipy import signal
type='fsk'
freq=10
Fs = 150.0;  # sampling rate
Ts = 1.0/Fs; # sampling interval
t = np.arange(0,2,Ts)
if (type=='fsk'):
    bit_arr = np.array([5,5,-5,5,-5])
    samples_per_bit = 2*Fs/bit_arr.size 
    dd = np.repeat(bit_arr, samples_per_bit)
    y= np.sin(2 * np.pi * (freq + dd) * t)
elif (type=='psk'):
    bit_arr = np.array([180,180,0,180,0])
    samples_per_bit = 2*Fs/bit_arr.size 
    dd = np.repeat(bit_arr, samples_per_bit)
    y= np.sin(2 * np.pi * (freq) * t+(np.pi*dd/180))
else:
    bit_arr = np.array([1, 0, 1, 1, 0])
    samples_per_bit = 2*Fs/bit_arr.size 
    dd = np.repeat(bit_arr, samples_per_bit)
    y= dd*np.sin(2 * np.pi * freq * t)
plt.plot(t,y)
plt.show()

dpsk

from __future__ import division
from numpy import ones,arange,cos,sin,pi
import numpy as np
from matplotlib.pyplot import plot,subplot,title,xlabel,ylabel,show,legend,grid,subplot
Fs =150.0;  # sampling rate
Ts = 1.0/Fs; # sampling interval
freq=10
t = np.arange(0,2,Ts)
bk = [1,0,0,1,0,0,1,1]##input digital sequence
bk_not=[]
for i in range(0,len(bk)):
  if(bk[i]==1):
   bk_not.append(0)
  else:
    bk_not.append(1)
dk_1 = [ 1 and bk[0]]#  #initial value of differential encoded sequence
dk_1_not =[ 0 and bk_not[0]]
dk = [dk_1[0]^dk_1_not[0]] #first bit of dpsk encoder
for i in range(1,len(bk)):
  dk_1.append(dk[(i-1)])
  if dk[(i-1)]==1:
     x=0
  else:
    x=1
  dk_1_not.append(x)
  dk.append(((dk_1[i] and bk[i])^(dk_1_not[i] and bk_not[i])))
dk_radians=[]
for i in range(0,len(dk)):
  if(dk[i]==1):
    dk_radians.append(0)
  elif(dk[i]==0):
    dk_radians.append(180)
print ('Table 7.3 Illustrating the Generation of DPSK Signal')
print ('_____________________________________________________')
print ('\n(bk)',bk)
print ('\n(bk_not)',bk_not)
print ('\nDifferentially encoded sequence (dk)')
for dd in dk:
    print (dd,'\t')
print ('\n\nTransmitted phase in radians')
for ddd in dk_radians:
    print (ddd,'\t')
print ('\n\n_____________________________________________________')
bit_arr =np.array([0,180,0,0,180])
samples_per_bit = 2*Fs/bit_arr.size
dd = np.repeat(bit_arr, samples_per_bit)
y= np.sin(2 * np.pi * (freq) * t+(np.pi*dd/180))
plot(t,y)
show()

Dss

## PN sequence generation with Max length
x0= 1
x1= 0
x2 =0
x3 =0
N = 7 
for i in range(1,N+1):
  x3 =x2
  x2 =x1
  x1 = x0
  x0 =(x1^x3)
  print ('The PN sequence at step:',i)
  x = [x1, x2, x3]
  print ('x=',x)
m = [7,8,9,10,11,12,13,17,19]#
N = [2**mm-1 for mm in m]
print ('Table 9.1 Range of PN Sequence lengths')
print ('_________________________________________________________')
print ('Length of shift register (m) =',m)
print ('PN sequence Length (N) =',N)
print ('_________________________________________________________')








##Properties of PNsequence
from numpy import corrcoef as corr
from matplotlib.pyplot import plot,xlabel,ylabel,title,show

#Period of PN Sequence N = 7
#Properites of maximum-length sequence

#Assign Initial value for PN generator
x0= 1
x1= 0
x2 =0
x3 =0
N = 7 
one_count = 0
zero_count = 0
C=[]
C_level=[]
t=[]
for i in range(1,N+1):
  x3 =x2#
  x2 =x1#
  x1 = x0#
  x0 =(x1^x3)
  print ('The PN sequence at step :',i)
  x = [x1 ,x2 ,x3]
  print ('x=',x)
  C.append(x3)
  if(C[i-1]==1):
    C_level.append(1)
    one_count = one_count+1
  elif(C[i-1]==0):
    C_level.append(-1)
    zero_count = zero_count+1  
print ('Output Sequence : ',C) 
print ('Output Sequence levels :',C_level)
if(zero_count < one_count):
  print ('Number of 1s in the given PN sequence : ',one_count)
  print ('Number of 0s in the given PN sequence :',zero_count)
  print ('Property 1 (Balance property) is satisified')
Rc_tuo = corr(C_level,rowvar=N)
t = range(1,2*len(C_level)+1)
plot(t,C_level+C_level)
xlabel('                                        t')
title('Waveform of maximum-length sequence ')
show()













## Generation of waveforms in DSSS/BPSK spread spectrum transmitter
from numpy import ones ,sin , arange , hstack ,nditer , pi 
import numpy as np
from matplotlib.pyplot import plot , subplot , xlabel , ylabel , title , show
t =range(0,13+1)
N =7#
m=[7,8,9,5]
l=[2**n-1 for n in m]
print('/n Values of length',l)
wt=arange(0,0.01+1,0.01)
bt=hstack([[1*xx for xx in ones(N)],[-1*yy for yy in ones(N)]])
ct= [0,0,1,1,1,0,1,0,0,1,1,1,0,1]
ct_polar= [-1,-1,1,1,1,-1,1,-1,-1,1,1,1,-1,1]
mt= [a*b for a,b in nditer([bt,ct_polar])]
Carrier = [2*sin(wtt*2*pi) for wtt in wt]
st= []#
for i in range(0,len(mt)):
    st=st+[mt[i]*Cr for Cr in Carrier]
subplot(3,1,1)
plot(t,mt)
xlabel('                                                                t')
title('Product Signal m(t)')
subplot(3,1,2)
plot(Carrier)
xlabel('                                                               t')
title('Carrier Signal')
subplot(3,1,3)
plot(st)
xlabel('                                                               t')
title('DS/BPSK signal s(t)')
show()

Matched filter

Signal corrupted with AWGN
from pylab import show
import numpy as np
import matplotlib.pyplot as plt
fs = 4096           # sampling rate [Hz]  
T = 4               # duration [s]
amp = 0.1           # amplitude of the sinusoid 
ome = 13            # frequency of the signal 
N = T*fs            # total number of points 
# time interval spaced with 1/fs 
t = np.arange(0, T, 1./fs)
# white noise 
noise = np.random.normal(size=t.shape)
# sinusoidal signal with amplitude amp
template = amp*np.sin(ome*2*np.pi*t)
# data: signal (template) with added noise 
data = template + noise
plt.figure()
plt.plot(t, data, '-', color="grey")
plt.plot(t, template, '-', color="white", linewidth=2)
plt.xlim(0, T)
plt.xlabel('time')
plt.ylabel('data = signal + noise')
show()





Matched Filter
from numpy import ones,convolve as convol
from matplotlib.pyplot import plot,xlabel,ylabel,title,show
#Matched Filter Output
T =4#
a =2#
t = range(0,T+1)
g = [2*xx for xx in ones([1,T+1])][0]
h  =[abs(x) for x in (convol(g,g))]
for i in range(0,len(h)):
  if(h[i]<0.01):
    h[i]=0
h = [hh-T for hh in h]
t1 = range(0,len(h))
plot(t,g)
xlabel('t--->')
ylabel('g(t)---->')
title('Rectangular pulse duration T = 4, a =2')
show()
plot(t1,h)
xlabel('t--->')
ylabel('Matched Filter output')
title('Output of filter matched to rectangular pulse g(t)')
show()

qpsk

from numpy import ones,arange,cos,sin,pi from matplotlib.pyplot import plot,subplot,title,xlabel,ylabel,show M =4# i = range(0,M) t = a...