See SPP Lab Final
See SPP Lab Final
Write a python code for demonstrating ideal sampling with under sampling and oversampling condition
import numpy as np
import matplotlib.pyplot as plt
# Parameters
fs = 8000 # Sampling frequency
f = 5 # Signal frequency
t = np.arange(0, 1, 1/fs) # Time vector for 1 second
# Plotting
plt.figure(figsize=(12, 8))
In [7]: #2. Write a python code for demonstrating, for a given data x(n) to compute DFT by defining a function call and plot the spectrum. Also reconstruct x(n) from
N=64
fs=1000.0
f0=100.0
t=np.arange(N)/fs
x=np.sin(2*np.pi*f0*t)
def DFT(x):
N=len(x)
n=np.arange(N)
k=n.reshape((N,1))
e=np.exp(-2j*np.pi*k*n/N)
X=np.dot(e,x)
return X
X=DFT(x)
N=len(X)
n=np.arange(N)
T=N/fs
freq=n/T
plt.figure(figsize=(8,6))
plt.stem(freq,abs(X),'b',markerfmt=" ",basefmt="-b")
plt.xlabel('Freq(Hz)')
plt.ylabel('DFT Amplitude|X(freq)|')
plt.show()
def IDFT(X):
N=len(X)
n=np.arange(N)
k=n.reshape((N,1))
e=np.exp(2j*np.pi*k*n/N)
x=1/N*(np.dot(e,X))
return x
x=IDFT(X)
plt.plot(t,x,'r')
plt.xlabel('Time(s)')
plt.ylabel('Amplitude')
plt.tight_layout()
C:\Users\SWARNA\anaconda3\lib\site-packages\matplotlib\cbook\__init__.py:1298: ComplexWarning: Casting complex values to real discards the imaginary part
return np.asarray(x, float)
In [8]: #3.Write a python code for demonstrating, for a given data x(n) to compute DFT by using FFT from numpy package and plot the spectrum. Also reconstruct x(n) fr
N=64
fs=1000.0
f0=100.0
t=np.arange(N)/fs
x=np.sin(2*np.pi*f0*t)
X=fft(x)
df=fs/N
f=np.arange(N)*df
plt.subplot(2,2,1)
plt.plot(t,ifft(X),color='r',label='reconstructed')
plt.subplot(2,2,2)
plt.plot(t,x,color='g',label='original')
plt.xlabel('Time(s)')
plt.ylabel('Amplitude')
plt.tight_layout()
plt.legend()
plt.show()
C:\Users\SWARNA\anaconda3\lib\site-packages\matplotlib\cbook\__init__.py:1298: ComplexWarning: Casting complex values to real discards the imaginary part
return np.asarray(x, float)
In [13]: #4.Write a python code for demonstrating for a given signal x(n) to compute DFT and DCT. compare the results and comment Illustrate for N=64,256
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft, dct
# Compute DCT
X1_dct = dct(x1, type=2)
# Plot results
plt.figure(figsize=(12, 10))
plt.tight_layout()
plt.show()
In [112… #5.Write a python code for demonstrating, for a given data x(n) to compute DFT by using FFT from numpy package and plot the spectrum with zero padding with N=
import numpy as np
from numpy import pi, cos, log10
from numpy.fft import fft
import matplotlib.pyplot as plt
In [22]: #6. Write a python code for demonstrating for an given data/image to extract its approximation and detailed coefficients using Daubechies - 2 WT. Plot them
import matplotlib.pyplot as plt
import numpy as np
import pywt
import pywt.data
# Perform a 2D Discrete Wavelet Transform (DWT) using the Daubechies wavelet (db2)
coeffs2 = pywt.dwt2(original, 'db2')
LL, (LH, HL, HH) = coeffs2
# Loop through and plot each set of coefficients (approximation and details)
for i, a in enumerate([LL, LH, HL, HH]):
ax = fig.add_subplot(1, 4, i + 1)
ax.imshow(a, interpolation="nearest", cmap=plt.cm.gray)
ax.set_title(titles[i], fontsize=10)
ax.set_xticks([]) # Remove x-axis ticks
ax.set_yticks([]) # Remove y-axis ticks
In [24]: #7. Write a python code for demonstrating for an given data/image to extract its approximation and detailed coefficients using Haar - 2 WT. Plot them
import matplotlib.pyplot as plt
import numpy as np
import pywt
import pywt.data
# Perform a 2D Discrete Wavelet Transform (DWT) using the Haar wavelet ('haar')
coeffs2 = pywt.dwt2(original, 'haar')
LL, (LH, HL, HH) = coeffs2
# Loop through and plot each set of coefficients (approximation and details)
for i, a in enumerate([LL, LH, HL, HH]):
ax = fig.add_subplot(1, 4, i + 1)
ax.imshow(a, interpolation="nearest", cmap=plt.cm.gray)
ax.set_title(titles[i], fontsize=10)
ax.set_xticks([]) # Remove x-axis ticks
ax.set_yticks([]) # Remove y-axis ticks
In [37]: #8.Write a python code for generating a signal x= np.sin(2*pi*f*n), f=5, Fs= 200 andt=4. Add noise and filter it using Butterworth (LP )filter . plot the nois
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
from scipy.fftpack import fft as fft
order = 6
fs = 100.0 # sample rate, Hz
cutoff = 20 # desired cutoff frequency of the filter, Hz
In [45]: #9.Write a python code for generating a signal x= np.sin(2*pi*f*n), f=5, Fs= 200 andt=4. Add noise and filter it using Butterworth (HP)filter . plot the noisy
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
from scipy.fftpack import fft as fft
order = 6
fs = 100.0 # sample rate, Hz
cutoff = 20 # desired cutoff frequency of the filter, Hz
In [46]: #10.Write a python code to generate a signal x= np.sin(2*pi*f1*n)+np.sin(2*pi*f2*n) and use the Bandpass Butterworth filter to pass (f1, f2). f1= , f2 = . Plo
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
# Frequency response
w, h = signal.freqs(b, a, worN=1000)
In [49]: #11.Write a python code to generate a signal x= np.sin(2*pi*f1*n)+np.sin(2*pi*f2*n) and use Band stop Butterworth filter remove (f1, f2). f1= , f2 = . Plot th
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
# Frequency response
w, h = signal.freqs(b, a, worN=1000)
In [77]: #12.Write a python code to generate signal with (1000Hz + 1500 Hz) and filter 1000 Hz using FIR HP filter with Hanning window.
from pylab import *
import scipy.signal as signal
import matplotlib.pyplot as plt
plt.subplot(2, 1, 2)
plt.magnitude_spectrum(filtered_signal, Fs=sample_rate, label='Filtered')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Magnitude')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
In [71]: #13.Write a python code to generate signal with (1000Hz + 1500 Hz) and filter 1500 Hz using FIR LP filter with Hanning window
from pylab import *
import scipy.signal as signal
import matplotlib.pyplot as plt
plt.subplot(2, 1, 2)
plt.magnitude_spectrum(filtered_signal, Fs=sample_rate, label='Filtered')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Magnitude')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
In [79]: #14.Write a python code to generate signal with (1000Hz + 3000 Hz) and filter 3000 Hz using FIR HP filter with Hamming window.
from pylab import *
import scipy.signal as signal
import matplotlib.pyplot as plt
plt.subplot(2, 1, 2)
plt.magnitude_spectrum(filtered_signal, Fs=sample_rate, label='Filtered')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Magnitude')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
In [84]: #15.Write a python code to generate signal with (1000Hz + 3000 Hz) and filter 3000 Hz using FIR LP filter with Hamming window.
from pylab import *
import scipy.signal as signal
import matplotlib.pyplot as plt
plt.subplot(2, 1, 2)
plt.magnitude_spectrum(filtered_signal, Fs=sample_rate, label='Filtered')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Magnitude')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
In [92]: #16.Write a python code to generate signal with (f1+ f2 Hz) and pass both the frequency components using FIR BP filter with Hann / OR Hamming window. F1=1000H
from pylab import *
import scipy.signal as signal
from scipy.signal import firwin, freqz, lfilter
Fs=40000
nyq_rate = Fs/2
#The cutoff frequency of the filter: GKHz
lowcut = 2000.0
fl = lowcut/nyq_rate
highcut = 7000
fh=highcut/nyq_rate
#Length of the filter (number of coefficients, l.e. the filter order + 1)
n=61
fir_coeff = firwin(n, [fl, fh], pass_zero=False, window="hamming",)
#Frequency and phase response
w,h = signal.freqz (fir_coeff, worN=8000)
h_dB = 20*log10 (abs(h))
plot(w/max(w),h_dB)
ylim(-150, 5)
ylabel('Magnitude (db)')
xlabel('Normalized Frequency (x$\pi$rad/sample)')
title('Frequency response')
plt.figure(figsize=(10, 6))
plt.subplot(2, 1, 2)
plt.magnitude_spectrum (signal, Fs=sample_rate, label='filtered')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Magnitude')
plt.legend()
In [96]: #17 Write a python code to generate signal with (f1+ f2 Hz) and pass both the frequency components using FIR BS filter with Hann / OR Hamming window. F1=1000H
from pylab import *
import scipy.signal as signal
from scipy.signal import firwin, freqz, lfilter
Fs=40000
nyq_rate = Fs/2
#The cutoff frequency of the filter: GKHz
lowcut = 2000.0
fl = lowcut/nyq_rate
highcut = 7000
fh=highcut/nyq_rate
#Length of the filter (number of coefficients, l.e. the filter order + 1)
n=61
fir_coeff = firwin(n, [fl, fh], pass_zero=True, window="hamming",)
#Frequency and phase response
w,h = signal.freqz (fir_coeff, worN=8000)
h_dB = 20*log10 (abs(h))
plot(w/max(w),h_dB)
ylim(-150, 5)
ylabel('Magnitude (db)')
xlabel('Normalized Frequency (x$\pi$rad/sample)')
title('Frequency response')
plt.figure(figsize=(16, 6))
plt.subplot(2, 1, 2)
plt.magnitude_spectrum(filtered_signal, Fs = sample_rate, label='Filtered')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Magnitude')
plt.legend()
plt.show()
In [98]: #18.Write a python code to generate signal x =[1,2,3,4,5,6,7,8,9,10,11,12] and illustrate down sampling ,up sampling by factor 3./ OR 2
import numpy as np
# Original sequence
original_sequence = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
# Upsampling by a factor of 2
upsampling_factor = 2
upsampled_sequence = np.zeros(len(original_sequence) * upsampling_factor)
upsampled_sequence[::upsampling_factor] = original_sequence
# Downsampling by a factor of 2
downsampling_factor = 2
downsampled_sequence = original_sequence[::downsampling_factor]
# Output results
print("Original Sequence:", original_sequence)
print("Upsampled Sequence:", upsampled_sequence)
print("Downsampled Sequence:", downsampled_sequence)
In [99]: #19.Write a python code to filter a random noise added to image using Weiner filter and plot the filtered image.
from scipy.signal import wiener
import matplotlib.pyplot as plt
import numpy as np
plt.show()
plt.close('all')
# AM Modulation
Fs = 1500
n = np.arange(0, 2, 1/Fs)
Fc = 50
Ac = 1
c = Ac * np.sin(2 * pi * Fc * n)
Fm = 2
Am = 0.5
m = Am * np.sin(2 * pi * Fm * n)
s = c * (1 + m / Ac)
plt.subplot(3, 1, 1)
plt.plot(n, s)
plt.title("Unmodulated case, Am = 0.5")
plt.xlabel('Time(s)')
plt.ylabel('Amplitude')
plt.grid(True)
Am = 1
m = Am * np.sin(2 * pi * Fm * n)
s = c * (1 + m / Ac)
plt.subplot(3, 1, 2)
plt.plot(n, s)
plt.title("Full modulation case, Am = 1")
plt.xlabel('Time(s)')
plt.ylabel('Amplitude')
plt.grid(True)
Am = 1.5
m = Am * np.sin(2 * pi * Fm * n)
s = c * (1 + m / Ac)
plt.subplot(3, 1, 3)
plt.plot(n, s)
plt.title("Over modulation case, Am = 1.5")
plt.xlabel('Time(s)')
plt.ylabel('Amplitude')
plt.grid(True)
plt.tight_layout()
plt.show()
# FM Modulation
Fs = 2000
n = np.arange(0, 0.2, 1/Fs)
fc = 100
fm1 = 30
fm2 = 45
b = 1
m_signal = np.sin(2 * pi * fm1 * n) + np.sin(2 * pi * fm2 * n)
carrier_signal = np.sin(2 * pi * fc * n)
fmd = np.sin(2 * pi * fc * n + b * m_signal)
plt.subplot(3, 1, 1)
plt.plot(n, m_signal)
plt.title("Analog Message signal")
plt.subplot(3, 1, 2)
plt.plot(n, carrier_signal)
plt.title("RF carrier signal")
plt.subplot(3, 1, 3)
plt.plot(n, fmd)
plt.title("Frequency Modulated Signal")
plt.tight_layout()
plt.show()
In [101… #21 Write a python code for generating Amplitude Modulated wave with modulation index m=75%. Change the index m to 50% and plot the waveform
import numpy as np
import matplotlib.pyplot as plt
from math import pi
plt.close('all')
Fs = 1500
n = np.arange(0, 2, 1/Fs)
Fc = 50
Ac = 1
c = Ac * np.sin(2 * pi * Fc * n)
Fm = 2
mod_index = 0.75
Am = mod_index * Ac
m = Am * np.sin(2 * pi * Fm * n)
s = c * (1 + m / Ac)
plt.subplot(2, 1, 1)
plt.plot(n, s)
plt.title("Amplitude Modulated Wave, Modulation Index = 75%")
plt.xlabel('Time(s)')
plt.ylabel('Amplitude')
plt.grid(True)
mod_index = 0.5
Am = mod_index * Ac
m = Am * np.sin(2 * pi * Fm * n)
s = c * (1 + m / Ac)
plt.subplot(2, 1, 2)
plt.plot(n, s)
plt.title("Amplitude Modulated Wave, Modulation Index = 50%")
plt.xlabel('Time(s)')
plt.ylabel('Amplitude')
plt.grid(True)
plt.tight_layout()
plt.show()
#ASK
import numpy as np
import matplotlib.pyplot as plt
# Parameters for the ASK modulation
fs = 1000 # Sampling frequency
f_carrier = 50 # Carrier frequency
t = np.arange(0, 1, 1/fs) # Time vector
# Binary message signal (0 and 1)
message = np.array([0, 1, 0, 1, 1, 0, 1, 0])
# Repeat each bit for the duration of 100 samples to match the carrier
message_signal = np.repeat(message, fs // len(message))
# Carrier signal (for logic 1)
carrier_signal = np.sin(2 * np.pi * f_carrier * t)
# Amplitude shift keying (ASK) signal
amplitude_high = 1 # Amplitude for logic 1
amplitude_low = 0 # Amplitude for logic 0
ask_signal = message_signal * carrier_signal * amplitude_high
# Plotting the signals
plt.figure(figsize=(12, 8))
# Plot the message signal
plt.subplot(3, 1, 1)
plt.plot(t, message_signal)
plt.title('Message Signal (Binary Data)')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.ylim([-0.1, 1.1])
# Plot the carrier signal
plt.subplot(3, 1, 2)
plt.plot(t, carrier_signal)
plt.title('Carrier Signal')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
# Plot the ASK modulated signal
plt.subplot(3, 1, 3)
plt.plot(t, ask_signal)
plt.title('Amplitude Shift Keying (ASK) Modulated Signal')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.tight_layout()
plt.show()
In [105… #FSK
import numpy as np
import matplotlib.pyplot as plt
# Parameters for the FSK modulation
fs = 1000 # Sampling frequency
f_carrier_1 = 50 # Frequency for logic 1
f_carrier_0 = 25 # Frequency for logic 0
t = np.arange(0, 1, 1/fs) # Time vector
# Binary message signal (0 and 1)
message = np.array([0, 1, 0, 1, 1, 0, 1, 0])
# Repeat each bit for the duration of 100 samples to match the carrier
message_signal = np.repeat(message, fs // len(message))
# Carrier signals for FSK (based on binary logic)
carrier_signal_0 = np.sin(2 * np.pi * f_carrier_0 * t)
carrier_signal_1 = np.sin(2 * np.pi * f_carrier_1 * t)
# Frequency Shift Keying (FSK) signal
fsk_signal = np.where(message_signal == 1, carrier_signal_1, carrier_signal_0)
# Plotting the signals
plt.figure(figsize=(12, 8))
# Plot the message signal
plt.subplot(3, 1, 1)
plt.plot(t, message_signal)
plt.title('Message Signal (Binary Data)')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.ylim([-0.1, 1.1])
# Plot the carrier signals
plt.subplot(3, 1, 2)
plt.plot(t, carrier_signal_0, label='Carrier 0 (25Hz)')
plt.plot(t, carrier_signal_1, label='Carrier 1 (50Hz)')
plt.title('Carrier Signals for FSK')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.legend()
# Plot the FSK modulated signal
plt.subplot(3, 1, 3)
plt.plot(t, fsk_signal)
plt.title('Frequency Shift Keying (FSK) Modulated Signal')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.tight_layout()
plt.show()
In [106… #PSK
import numpy as np
import matplotlib.pyplot as plt
# Parameters for the PSK modulation
fs = 1000 # Sampling frequency
f_carrier = 50 # Carrier frequency
t = np.arange(0, 1, 1/fs) # Time vector
# Binary message signal (0 and 1)
message = np.array([0, 1, 0, 1, 1, 0, 1, 0])
# Repeat each bit for the duration of 100 samples to match the carrier
message_signal = np.repeat(message, fs // len(message))
# Carrier signal
carrier_signal = np.sin(2 * np.pi * f_carrier * t)
# Phase Shift Keying (PSK) modulation
# Logic 1: 180-degree phase shift (pi radians), Logic 0: 0-degree phase shift
psk_signal = np.sin(2 * np.pi * f_carrier * t + np.pi * message_signal)
# Plotting the signals
plt.figure(figsize=(12, 8))
# Plot the message signal
plt.subplot(3, 1, 1)
plt.plot(t, message_signal)
plt.title('Message Signal (Binary Data)')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.ylim([-0.1, 1.1])
# Plot the carrier signal
plt.subplot(3, 1, 2)
plt.plot(t, carrier_signal)
plt.title('Carrier Signal')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
# Plot the PSK modulated signal
plt.subplot(3, 1, 3)
plt.plot(t, psk_signal)
plt.title('Phase Shift Keying (PSK) Modulated Signal')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.tight_layout()
plt.show()