0% found this document useful (0 votes)
23 views1 page

See SPP Lab Final

Uploaded by

prajwal shivaiah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views1 page

See SPP Lab Final

Uploaded by

prajwal shivaiah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

In [6]: #1.

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

# Original continuous-time signal (sine wave)


x = np.sin(2 * np.pi * f * t)

# Ideal sampling (sampling frequency matches signal requirements)


ideal_fs = 2 * f # Nyquist rate (twice the signal frequency)
ideal_t = np.arange(0, 1, 1/ideal_fs)
ideal_sampled_signal = np.sin(2 * np.pi * f * ideal_t)

# Under-sampling (sampling frequency is less than Nyquist rate)


under_fs = f # Sampling frequency equal to signal frequency (f)
under_t = np.arange(0, 1, 1/under_fs)
under_sampled_signal = np.sin(2 * np.pi * f * under_t)

# Over-sampling (sampling frequency is much greater than Nyquist rate)


over_fs = 10 * f # Sampling frequency ten times the signal frequency
over_t = np.arange(0, 1, 1/over_fs)
over_sampled_signal = np.sin(2 * np.pi * f * over_t)

# Plotting
plt.figure(figsize=(12, 8))

# Plot original continuous-time signal


plt.subplot(3, 1, 1)
plt.plot(t, x, label="Continuous Signal")
plt.stem(ideal_t, ideal_sampled_signal, linefmt='r-', markerfmt='ro', basefmt='r-', use_line_collection=True)
plt.title("Ideal Sampling (Nyquist Rate)")
plt.xlabel("Time [s]")
plt.ylabel("Amplitude")
plt.legend()

# Plot under-sampled signal


plt.subplot(3, 1, 2)
plt.plot(t, x, label="Continuous Signal")
plt.stem(under_t, under_sampled_signal, linefmt='g-', markerfmt='go', basefmt='g-', use_line_collection=True)
plt.title("Under-Sampling (Aliasing)")
plt.xlabel("Time [s]")
plt.ylabel("Amplitude")
plt.legend()

# Plot over-sampled signal


plt.subplot(3, 1, 3)
plt.plot(t, x, label="Continuous Signal")
plt.stem(over_t, over_sampled_signal, linefmt='b-', markerfmt='bo', basefmt='b-', use_line_collection=True)
plt.title("Over-Sampling")
plt.xlabel("Time [s]")
plt.ylabel("Amplitude")
plt.legend()
plt.tight_layout()
plt.show()

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

import matplotlib.pyplot as plt


import numpy as np
from scipy.fftpack import fft,ifft

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\AppData\Local\Temp\ipykernel_11620\2807628304.py:27: MatplotlibDeprecationWarning: Passing the linefmt parameter positionally is deprecated si


nce Matplotlib 3.5; the parameter will become keyword-only two minor releases later.
plt.stem(freq,abs(X),'b',markerfmt=" ",basefmt="-b")

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

import matplotlib.pyplot as plt


import numpy as np
from scipy.fftpack import fft,ifft

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.stem(f, abs(X), 'b')


plt.title('Frequency Spectrum of a Sine Wave Signal')
plt.xlabel('Frequency (Hz)')
plt.ylabel('|x(f)|')
plt.show()

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\AppData\Local\Temp\ipykernel_11620\3352328074.py:18: MatplotlibDeprecationWarning: Passing the linefmt parameter positionally is deprecated si


nce Matplotlib 3.5; the parameter will become keyword-only two minor releases later.
plt.stem(f, abs(X), 'b')

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

# Generate signal x(n) for N=64 and N=256


N1 = 64
n1 = np.arange(N1)

# Example signal: sum of two sinusoidal signals


x1 = np.sin(2 * np.pi * 5 * n1 / N1) + 0.5 * np.sin(2 * np.pi * 10 * n1 / N1)

# Compute DFT using FFT


X1_dft = fft(x1)

# Compute DCT
X1_dct = dct(x1, type=2)

# Plot results
plt.figure(figsize=(12, 10))

# Original signal for N=64


plt.subplot(4, 2, 1)
plt.stem(n1, x1, use_line_collection=True)
plt.title('Original Signal x(n) for N=64')
plt.xlabel('n')
plt.ylabel('Amplitude')

# DFT Magnitude for N=64


plt.subplot(4, 2, 3)
plt.stem(np.arange(N1), np.abs(X1_dft), use_line_collection=True)
plt.title('DFT Magnitude for N=64')
plt.xlabel('Frequency Bin')
plt.ylabel('Magnitude')

# DCT Magnitude for N=64


plt.subplot(4, 2, 5)
plt.stem(np.arange(N1), np.abs(X1_dct), use_line_collection=True)
plt.title('DCT Magnitude for N=64')
plt.xlabel('Frequency Bin')
plt.ylabel('Magnitude')

# Comparison of DFT and DCT for N=64


plt.subplot(4, 2, 7)
plt.plot(np.arange(N1), np.abs(X1_dft), label='DFT')
plt.plot(np.arange(N1), np.abs(X1_dct), label='DCT', linestyle='--')
plt.title('Comparison of DFT and DCT for N=64')
plt.xlabel('Frequency Bin')
plt.ylabel('Magnitude')
plt.legend()

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

# Parameters for the original signal


N1 = 16 # Length of the original signal for the first case
N2 = 256 # Length of the original signal for the second case
T = 1 # Sampling period
A = 1 # Amplitude
phi = 0 # Phase
f = 0.25 # Frequency (cycles per sample)

# Generate original signal for N1


n1 = np.arange(N1)
x1 = A * cos(2 * pi * n1 * f * T + phi)

# Compute FFT for the original signal (N1)


X1 = fft(x1)
magX1 = abs(X1)

# Frequency bins for N1


fn1 = np.linspace(0, 1, len(magX1))
spec1 = 20 * log10(magX1)

# Plotting original signal and spectrum for N1


plt.figure(figsize=(10, 10))

# Subplot for original signal


plt.subplot(2, 1, 1)
plt.plot(n1, x1, '*k', label='Sampled Signal')
ni1 = np.arange(0, N1, 0.1)
plt.plot(ni1, A * cos(2 * pi * ni1 * f * T + phi), '-k', label='Continuous Signal')
plt.xlim(0, N1)
plt.title('Sinusoid at 1/4 the Sampling Rate (N=16)')
plt.xlabel('Time (samples)')
plt.ylabel('Amplitude')
plt.text(-0.11 * N1, 1, 'a)')
plt.legend()

# Subplot for frequency spectrum


plt.subplot(2, 1, 2)
plt.plot(fn1, spec1, '--ok')
plt.grid()
plt.xlim(0, 1)
plt.ylim(-350, 50)
plt.xlabel('Normalized Frequency (cycles per sample)')
plt.ylabel('Magnitude (dB)')
plt.text(-0.11, 0, 'b)')
plt.title('Spectrum (N=16)')
plt.tight_layout()
plt.show()

# Generate original signal for N2


n2 = np.arange(N2)
x2 = A * cos(2 * pi * n2 * f * T + phi)

# FFT for the original signal (N2)


X2 = fft(x2)
magX2 = abs(X2)

# Zero padding for N2


zpf = 8
n3 = np.arange(zpf * N2)
x2_zp = np.concatenate([cos(2 * pi * n3[:N2] * f * T + phi), np.zeros((zpf - 1) * N2)])
X2_zp = fft(x2_zp)
magX2_zp = abs(X2_zp)

# Frequency bins for the zero-padded FFT


nfft = zpf * N2
fni = np.arange(0, 1, 1.0/nfft)

# Plotting for zero-padded signal


plt.figure(figsize=(10, 10))

# Subplot for zero-padded signal


plt.subplot(3, 1, 1)
plt.plot(n3, x2_zp, '-k')
plt.xlim(0, N2 * zpf)
plt.title('Zero-Padded Sampled Sinusoid (N=256)')
plt.xlabel('Time (samples)')
plt.ylabel('Amplitude')
plt.text(-0.11 * N2 * zpf, 1, 'a)')

# Magnitude plot (linear scale)


plt.subplot(3, 1, 2)
plt.plot(fni, magX2_zp, '-k')
plt.grid()
plt.xlim(0, 1)
plt.ylim(0, 40)
plt.xlabel('Normalized Frequency (cycles per sample)')
plt.ylabel('Magnitude (Linear)')
plt.text(-0.11, 40, 'b)')

# Spectrum plot (dB scale)


spec2 = 20 * log10(magX2_zp) # Spectrum magnitude in dB
plt.subplot(3, 1, 3)
plt.plot(fni, spec2, '-k')
plt.grid()
plt.xlim(0, 1)
plt.ylim(-40, 40)
plt.xlabel('Normalized Frequency (cycles per sample)')
plt.ylabel('Magnitude (dB)')
plt.text(-0.11, 0, 'c)')
plt.title('Spectrum (N=256 with Zero Padding)')
plt.tight_layout()
plt.show()

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

# Load an example image


original = pywt.data.camera()

# Perform a 2D Discrete Wavelet Transform (DWT) using the Daubechies wavelet (db2)
coeffs2 = pywt.dwt2(original, 'db2')
LL, (LH, HL, HH) = coeffs2

# Set the titles for each sub-plot


titles = ['Approximation', 'Horizontal detail', 'Vertical detail', 'Diagonal detail']

# Create a figure with 4 sub-plots


fig = plt.figure(figsize=(12, 3))

# 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

# Adjust layout to avoid overlap


fig.tight_layout()

# Show the plot


plt.show()

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

# Load an example image


original = pywt.data.camera()

# Perform a 2D Discrete Wavelet Transform (DWT) using the Haar wavelet ('haar')
coeffs2 = pywt.dwt2(original, 'haar')
LL, (LH, HL, HH) = coeffs2

# Set the titles for each sub-plot


titles = ['Approximation', 'Horizontal detail', 'Vertical detail', 'Diagonal detail']

# Create a figure with 4 sub-plots


fig = plt.figure(figsize=(12, 3))

# 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

# Adjust layout to avoid overlap


fig.tight_layout()

# Show the plot


plt.show()

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

b, a = signal.butter(4, 100, 'low', analog=True)


w, h = signal.freqs(b, a)
plt.semilogx(w, 20 * np.log10(abs(h)))
plt.title('Butterworth filter frequency response')
plt.xlabel('Frequency [radians / second]')
plt.ylabel('Amplitude [dB]')
t = np.linspace(0, 1, 1000, False) # 1 second
sig = np.sin(2 * np.pi * 10 * t) + np.sin(2 * np.pi * 20 * t)
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
ax1.plot(t, sig)
ax1.set_title('10 Hz and 20 Hz sinusoids')
ax1.axis([0, 1, -2, 2])

sos = signal.butter(10, 15, 'lp', fs=1000, output='sos')


filtered = signal.sosfilt(sos, sig)
ax2.plot(t, filtered)
ax2.set_title('After filter')
ax2.axis([0, 1, -2, 2])
ax2.set_xlabel('Time [seconds]')
plt.tight_layout()
plt.show()

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

b, a = signal.butter(4, 100, 'high', analog=True)


w, h = signal.freqs(b, a)
plt.semilogx(w, 20 * np.log10(abs(h)))
plt.title('Butterworth filter frequency response')
plt.xlabel('Frequency [radians / second]')
plt.ylabel('Amplitude [dB]')
t = np.linspace(0, 1, 1000, False) # 1 second
sig = np.sin(2 * np.pi * 10 * t) + np.sin(2 * np.pi * 20 * t)
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
ax1.plot(t, sig)
ax1.set_title('10 Hz and 20 Hz sinusoids')
ax1.axis([0, 1, -2, 2])

sos = signal.butter(10, 15, 'hp', fs=1000, output='sos')


filtered = signal.sosfilt(sos, sig)
ax2.plot(t, filtered)
ax2.set_title('After filter')
ax2.axis([0, 1, -2, 2])
ax2.set_xlabel('Time [seconds]')
plt.tight_layout()
plt.show()

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

# Butterworth filter design parameters


order = 17
lowcut = 50.0 # Low cutoff frequency in Hz
highcut = 200.0 # High cutoff frequency in Hz

# Design Butterworth bandpass filter


b, a = signal.iirfilter(order, [2*np.pi*lowcut, 2*np.pi*highcut],
btype='band', analog=True, ftype='butter')

# Frequency response
w, h = signal.freqs(b, a, worN=1000)

# Plotting the frequency response


fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.semilogx(w / (2*np.pi), 20 * np.log10(np.maximum(abs(h), 1e-5)))
ax.set_title('Butterworth bandpass filter frequency response')
ax.set_xlabel('Frequency [Hz]')
ax.set_ylabel('Amplitude [dB]')
ax.axis((10, 1000, -100, 10))
ax.grid(which='both', axis='both')
plt.show()

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

# Butterworth filter design parameters


order = 17
lowcut = 50.0 # Low cutoff frequency in Hz
highcut = 200.0 # High cutoff frequency in Hz

# Design Butterworth bandpass filter


b, a = signal.iirfilter(order, [2*np.pi*lowcut, 2*np.pi*highcut],
btype='bandstop', analog=True, ftype='butter')

# Frequency response
w, h = signal.freqs(b, a, worN=1000)

# Plotting the frequency response


fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.semilogx(w / (2*np.pi), 20 * np.log10(np.maximum(abs(h), 1e-5)))
ax.set_title('Butterworth bandstop filter frequency response')
ax.set_xlabel('Frequency [Hz]')
ax.set_ylabel('Amplitude [dB]')
ax.axis((10, 1000, -100, 10))
ax.grid(which='both', axis='both')
plt.show()

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

# Sampling frequency and Nyquist rate


fs = 48000
nyq_rate = fs / 2

# Adjusted cutoff frequency to filter out 3000 Hz component


cutoff_hz = 2500.0 # Reduced from 3000 to 2500 Hz for better filtering
cut = cutoff_hz / nyq_rate

# Increased filter order for sharper attenuation


n = 101

# FIR filter coefficients using a Hann window


fir_coeff = signal.firwin(n, cutoff=cut, window="hamming", pass_zero=True) # Low-pass filter

# Frequency and phase response


w, h = signal.freqz(fir_coeff, worN=8000)
h_dB = 20 * log10(abs(h))

# Plot the frequency response of the filter


plt.figure(figsize=(10, 6))
plt.plot(w / max(w), h_dB)
plt.ylim(-150, 5)
plt.ylabel('Magnitude (dB)')
plt.xlabel('Normalized Frequency (x$\pi$ rad/sample)')
plt.title('Frequency Response of Low-pass FIR Filter')
plt.grid(True)

# Signal generation: 320 samples of 1000 Hz and 3000 Hz at 48kHz


sample_rate = 48000
nsamples = 320
F_1KHz = 1000
A_1KHz = 1.0
F_3KHz = 3000
A_3KHz = 1.0
t = arange(nsamples) / sample_rate
signal_input = A_1KHz * sin(2 * pi * F_1KHz * t) + A_3KHz * sin(2 * pi * F_3KHz * t)

# Apply FIR filter to the signal


filtered_signal = signal.lfilter(fir_coeff, 1.0, signal_input) # Correctly use lfilter

# Plot the spectrum before and after filtering


plt.figure(figsize=(10, 6))
plt.subplot(2, 1, 1)
plt.magnitude_spectrum(signal_input, Fs=sample_rate, label='Unfiltered')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Magnitude')
plt.legend()
plt.grid(True)

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

# Sampling frequency and Nyquist rate


fs = 48000
nyq_rate = fs / 2

# Adjusted cutoff frequency to filter out 3000 Hz component


cutoff_hz = 2500.0 # Reduced from 3000 to 2500 Hz for better filtering
cut = cutoff_hz / nyq_rate

# Increased filter order for sharper attenuation


n = 101

# FIR filter coefficients using a Hann window


fir_coeff = signal.firwin(n, cutoff=cut, window="hann", pass_zero=True) # Low-pass filter

# Frequency and phase response


w, h = signal.freqz(fir_coeff, worN=8000)
h_dB = 20 * log10(abs(h))

# Plot the frequency response of the filter


plt.figure(figsize=(10, 6))
plt.plot(w / max(w), h_dB)
plt.ylim(-150, 5)
plt.ylabel('Magnitude (dB)')
plt.xlabel('Normalized Frequency (x$\pi$ rad/sample)')
plt.title('Frequency Response of Low-pass FIR Filter')
plt.grid(True)

# Signal generation: 320 samples of 1000 Hz and 3000 Hz at 48kHz


sample_rate = 48000
nsamples = 320
F_1KHz = 1000
A_1KHz = 1.0
F_3KHz = 3000
A_3KHz = 1.0
t = arange(nsamples) / sample_rate
signal_input = A_1KHz * sin(2 * pi * F_1KHz * t) + A_3KHz * sin(2 * pi * F_3KHz * t)

# Apply FIR filter to the signal


filtered_signal = signal.lfilter(fir_coeff, 1.0, signal_input) # Correctly use lfilter

# Plot the spectrum before and after filtering


plt.figure(figsize=(10, 6))
plt.subplot(2, 1, 1)
plt.magnitude_spectrum(signal_input, Fs=sample_rate, label='Unfiltered')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Magnitude')
plt.legend()
plt.grid(True)

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

# Sampling frequency and Nyquist rate


fs = 48000
nyq_rate = fs / 2

# Adjusted cutoff frequency to filter out 3000 Hz component


cutoff_hz = 2500.0 # Reduced from 3000 to 2500 Hz for better filtering
cut = cutoff_hz / nyq_rate

# Increased filter order for sharper attenuation


n = 101

# FIR filter coefficients using a Hann window


fir_coeff = signal.firwin(n, cutoff=cut, window="hamming", pass_zero=False) # Low-pass filter

# Frequency and phase response


w, h = signal.freqz(fir_coeff, worN=8000)
h_dB = 20 * log10(abs(h))

# Plot the frequency response of the filter


plt.figure(figsize=(10, 6))
plt.plot(w / max(w), h_dB)
plt.ylim(-150, 5)
plt.ylabel('Magnitude (dB)')
plt.xlabel('Normalized Frequency (x$\pi$ rad/sample)')
plt.title('Frequency Response of Low-pass FIR Filter')
plt.grid(True)

# Signal generation: 320 samples of 1000 Hz and 3000 Hz at 48kHz


sample_rate = 48000
nsamples = 320
F_1KHz = 1000
A_1KHz = 1.0
F_3KHz = 3000
A_3KHz = 1.0
t = arange(nsamples) / sample_rate
signal_input = A_1KHz * sin(2 * pi * F_1KHz * t) + A_3KHz * sin(2 * pi * F_3KHz * t)

# Apply FIR filter to the signal


filtered_signal = signal.lfilter(fir_coeff, 1.0, signal_input) # Correctly use lfilter

# Plot the spectrum before and after filtering


plt.figure(figsize=(10, 6))
plt.subplot(2, 1, 1)
plt.magnitude_spectrum(signal_input, Fs=sample_rate, label='Unfiltered')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Magnitude')
plt.legend()
plt.grid(True)

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

# Sampling frequency and Nyquist rate


fs = 48000
nyq_rate = fs / 2

# Adjusted cutoff frequency to filter out 3000 Hz component


cutoff_hz = 2500.0 # Reduced from 3000 to 2500 Hz for better filtering
cut = cutoff_hz / nyq_rate

# Increased filter order for sharper attenuation


n = 101

# FIR filter coefficients using a Hann window


fir_coeff = signal.firwin(n, cutoff=cut, window="hamming", pass_zero=True) # Low-pass filter

# Frequency and phase response


w, h = signal.freqz(fir_coeff, worN=8000)
h_dB = 20 * log10(abs(h))

# Plot the frequency response of the filter


plt.figure(figsize=(10, 6))
plt.plot(w / max(w), h_dB)
plt.ylim(-150, 5)
plt.ylabel('Magnitude (dB)')
plt.xlabel('Normalized Frequency (x$\pi$ rad/sample)')
plt.title('Frequency Response of Low-pass FIR Filter')
plt.grid(True)

# Signal generation: 320 samples of 1000 Hz and 3000 Hz at 48kHz


sample_rate = 48000
nsamples = 320
F_1KHz = 1000
A_1KHz = 1.0
F_3KHz = 3000
A_3KHz = 1.0
t = arange(nsamples) / sample_rate
signal_input = A_1KHz * sin(2 * pi * F_1KHz * t) + A_3KHz * sin(2 * pi * F_3KHz * t)

# Apply FIR filter to the signal


filtered_signal = signal.lfilter(fir_coeff, 1.0, signal_input) # Correctly use lfilter

# Plot the spectrum before and after filtering


plt.figure(figsize=(10, 6))
plt.subplot(2, 1, 1)
plt.magnitude_spectrum(signal_input, Fs=sample_rate, label='Unfiltered')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Magnitude')
plt.legend()
plt.grid(True)

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')

from scipy.signal import firwin, freqz, lfilter


import matplotlib.pyplot as plt
#320 samples of (1000Hz + 1500Hz)at 48KHz
sample_rate = 48000
F_1KHz = 3000
A_1KHz = 1.0
F_7KHz = 7000
A_7KHz = 1.0
t = arange(nsamples) / sample_rate
signal = A_1KHz * sin(2*pi*F_1KHz*t) + A_7KHz*sin(2*pi*F_7KHz*t)
filtered_signal = lfilter(fir_coeff, 1.0, signal)
plt.figure(figsize = (10, 6))
plt.subplot(2, 1, 1)
plt.magnitude_spectrum (signal, Fs = sample_rate, label='Unfiltered')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Magnitude')
plt.legend()

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()

Out[92]: <matplotlib.legend.Legend at 0x1085db9e400>

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')

from scipy.signal import firwin, freqz, lfilter


import matplotlib.pyplot as plt
#320 samples of (1000Hz + 15000 Hz) at 48 kHz
sample_rate=48000
nsamples = 320
F_1KHz = 5000
A_1KHz = 1.0
F_7KHz = 7000
A_7KHz = 1.0
t = arange(nsamples) / sample_rate
signal = A_1KHz * sin(2*pi*F_1KHz*t) + A_7KHz*sin(2*pi*F_7KHz*t)
#Use Ifilter to filter the signal with the FIR filter
filtered_signal = lfilter(fir_coeff, 1.0, signal)
plt.figure(figsize=(10, 6))
plt.subplot(2, 1, 1)
plt.magnitude_spectrum (signal, Fs = sample_rate, label='Unfiltered')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Magnitude')
plt.legend()

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)

Original Sequence: [ 1 2 3 4 5 6 7 8 9 10 11 12]


Upsampled Sequence: [ 1. 0. 2. 0. 3. 0. 4. 0. 5. 0. 6. 0. 7. 0. 8. 0. 9. 0.
10. 0. 11. 0. 12. 0.]
Downsampled Sequence: [ 1 3 5 7 9 11]

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

# Use NumPy's random number generator to create a random image


rng = np.random.default_rng()
img = rng.random((40, 40)) # Create a random 40x40 image

# Apply Wiener filter to the random image


filtered_img = wiener(img, (5, 5)) # Apply Wiener filter with a 5x5 window

# Plot the original and filtered image side by side


f, (plot1, plot2) = plt.subplots(1, 2)

# Display the original image


plot1.imshow(img)
plot1.set_title("Original Image")

# Display the filtered image


plot2.imshow(filtered_img)
plot2.set_title("Filtered Image")

plt.show()

In [100… #20 Write a python code for generating AM wave / FM wave


import numpy as np
import matplotlib.pyplot as plt
from math import pi

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()

In [104… #22 Write a python code for ASK, FSK, PSK.

#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()

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy