The following function outlines are included with this notebook. In order to complete ths assignment some parts of the code are provided to you. You will be filling in some parts
import os, h5py
from PIL import Image
from scipy.fftpack import fft
from scipy.io import loadmat
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# This function computes the DFT of the input vector
def f_dft(data,M):
'''
Computes DFT of length M of the data vector "data"
'''
dft_data = fft(data,M)
dft_data = np.abs(dft_data)/np.max(np.abs(dft_data))
# prevent zero argument for log10 - setting to -80db
#dft_data[np.where(dft_data==0)] = 10**(-4)
return(dft_data)
###############################################################################
# function to generate gaussian distributed value
def f_gaussian(n, mu, var):
'''
Generate Gaussian data with mean mu and variance var.
'''
sigma = np.sqrt(var)
#xg = (1/np.sqrt(2*np.pi*var))*np.exp(-0.5*(n-mu)*(n-mu)/var)
xg = np.random.normal(mu,sigma,n)
count, bins, ignored = plt.hist(xg, 30, density=True)
#plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) * np.exp( - (bins - mu)**2 / (2 * sigma**2) ), linewidth=2, color='r')
#plt.show()
return(xg)
###############################################################################
# function to generate uniform distributed value
def f_uniform(n,min,max):
'''
Generate uniform data with mean mu and variance var.
'''
xu = np.random.uniform(min, max,n)
count, bins, ignored = plt.hist(xu, 1, density=True)
# plt.plot(bins, 1/(max*2)*np.ones_like(bins), linewidth=2, color='r')
# plt.show()
return(xu)
#
def f_plotspectrum(data,M):
'''
Plot specturm of dft_data and compute SNR - this assumes even length DFT
'''
#dftlen = np.len(data)
dft_data = fft(data,M)
# pick the first half of DFT samples - this corresponds to the region (0,pi)
Nv = np.int(M/2);
#print(Nv)
dft_data = dft_data[0:Nv]
dft_data = np.abs(dft_data)/np.max(abs(dft_data)) + 1e-16
plt.plot(20*np.log10(dft_data),'#1f77b4')
In the class we discussed the implications of windowing a signal. Windowing of data is necessary since we cannot have an infinite length signal. The sectral characteristics of a signal are altered by the window function, hence it is essential to know the spectral characterisics of different windows. Some properties of the commonly used window types in circuit applications are summarized below. The
| Window Type |
Functional form |
Non-zero FFT bins |
|---|---|---|
| Rectangular |
$w[n] = 1 $ |
1 |
| Hann |
$ w[n] = \dfrac{1-cos\left(\frac{2\pi n}{N}\right)}{2}$ |
3 |
| $\mbox{Hann}^2$ |
$ w[n] = \left(\dfrac{1-cos\left(\frac{2\pi n}{N}\right)}{2}\right)^2$ |
5 |
#set up all the windows and call f_data function to plot the spectrum of windows discussed in class
#window length
N = 51
#DFT length
M = 1023
#set the font weight to bold, fontwidth to 12 and linewidth to 1.5
plt.rcParams['font.size'] = 12
plt.rcParams['lines.linewidth'] = 2
plt.rc('font', weight='bold')
#generate rect, Hann, and Hann2 windows
rect_data = np.ones(N)
#hann window.
x = np.arange(0,N-1,1)
#generate Hann window
hann_data = (1 - (np.cos(2*np.pi*(x)/N)))/2
#hann2 window
hann_data2 = np.square(hann_data)
line, = plt.plot(rect_data,label='Rectangular')
line.set_label('Rect')
plt.legend()
line, = plt.plot(hann_data)
line.set_label('Hann')
plt.legend()
line, = plt.plot(hann_data2)
line.set_label('Hann2')
plt.legend()
plt.title('Commonly used windows in ADC data processing')
plt.xlabel('n')
plt.ylabel('W[n]')
plt.grid('True')
plt.show()
# compute normalized frequency
#f = ((np.arange(0,511,1)*10000))/M
f = ((np.arange(0,511,1)))/M
# compute DFT of rectangular window
dft_data = f_dft(rect_data,M)
line, = plt.plot(f,20*np.log10(dft_data[0 : 511]))
line.set_label('Rect')
plt.legend()
#plt.show()
#compute DFT of Hann window
dft_data = f_dft(hann_data,M)
line, = plt.plot(f,20*np.log10(dft_data[0:511]))
line.set_label('Hann')
plt.legend()
#compute DFT of Hann2 window
dft_data = f_dft(hann_data2,M)
line, = plt.plot(f,20*np.log10(dft_data[0:511]))
line.set_label('Hann2')
plt.legend()
plt.xlabel('Normalized frequency')
plt.ylabel('$|W_{Hann}(\omega)|$ in dB')
plt.title('Frequency response of Windows')
plt.grid('True')
The CT signal $x_a(t) = 0.9sin(2000\pi t)$ is sampled with a sampling period $T = \dfrac{1}{16000} s$.
nsamples = 256
N = int(nsamples/2)
#sampling frequency
Fs = 16000
xsig = np.sin(2*np.pi*np.arange(0,nsamples,1)/16)
# compute DFT and plot the spectrum
plt.plot(xsig,'#1f77b4')
plt.xlabel('n')
plt.title('Signal x[n]')
plt.ylabel('x[n]')
plt.show()
dft_data = f_dft(xsig,nsamples)
f = ((np.arange(0,nsamples/2,1)*Fs))/nsamples
line, = plt.plot(f,20*np.log10(dft_data[0 : N]),'#1f77b4')
#plt.plot((dft_data[0:N]))
plt.xlabel('Frequency Hz')
plt.ylabel('$|X{[k]=|$ in dB')
plt.title('Spectrum of x[n]')
plt.grid('True')
In this problem we will look at the implications of computing DFT of a sinusoidal signal. Analog to Digital Converters (ADCs) are tested using a sinusoidal signal of certain frequency. It is essential during ADC testing that we distinguish between non-idealities of an ADC and non-idealities introduced due to DFT. As discussed in class, one of the non-idealities introduced by an ADC is quantization noise and it's impact is measured by Signal to Quantization noise ratio (SQNR). In this problem we will model quantization noise using additive white noise of certain variance. We will compute the SQNR of two sinusoidal signals and see the importance of picking sinusoidal signals of the correct frequency.
The CT signal ${x_a(t) = 0.9 sin(2\pi 47t)}$ is sampled with sampling period ${T}=\dfrac{1}{1024}s$.
%%capture
# generate samples of input signal
nsamples = 1024
#x=np.linspace(0,1/(10000),nsamples)
noise_var = 10**(-4) # noise for noise floor
xg = f_gaussian(nsamples,0,noise_var) # generate gaussian data
# compute the limits in case using uniform white noise
del2 = (np.sqrt(12*noise_var))/2
#xsig = np.cos(2*np.pi*np.arange(0,nsamples-1,1)/6)
xsig = np.sin(2*np.pi*np.arange(0,nsamples,1)/6) + xg
#plt.plot(xsig)
dft_data = f_plotspectrum(xsig,nsamples)
plt.xlabel('DFT sample index, k')
plt.ylabel('$|X[k]|$ in dB')
plt.title('Magnitude $X[k]$')
plt.grid('True')
plt.ylim([-100,5])
#xu = f_uniform(nsamples,-del2,del2)
#plt.plot(xg)
#dft_data = np.abs(dft_data)/np.max(abs(dft_data))
#plt.plot(20*np.log10(dft_data))
# generate samples of input signal
nsamples = 1024
M = int(nsamples/2)
P = 47 # prime number to generate a sin frequency
x=np.linspace(0,1/(10000),nsamples)
noise_var = 10**(-6) # noise for noise floor
xg = f_gaussian(nsamples,0,noise_var) #generate Gaussian data
# compute the limits in case using uniform white noise
del2 = (np.sqrt(12*noise_var))/2
#xsig = np.cos(2*np.pi*np.arange(0,nsamples-1,1)/6)
xsig = 0.9*np.sin(2*np.pi*P*np.arange(0,nsamples,1)/nsamples) + xg
#plt.plot(xsig)
dft_data = f_dft(xsig,nsamples)
#xu = f_uniform(nsamples,-del2,del2)
#plt.plot(xg)
dft_data = np.abs(dft_data)/np.max(abs(dft_data))
dft_data = dft_data + 1e-16
plt.plot(20*np.log10(dft_data[0:M-1]),'#1f77b4')
plt.xlabel('DFT sample index')
plt.ylabel('$|X[k]|$ in dB')
plt.title('Magnitude $X[k]$')
plt.grid('True')
plt.ylim([-120,5])
In this problem we will look at the effect of windowing on computed SQNR. Download the file $\textbf{noisy_sine.mat}$ from the course website. The data in the file contains a signal length ${N=16384}$ signal, ${x_{in}}[n]$, which is a sinusoid embedded in noise. Assume that data in the file is sampled at ${T} = \dfrac{1}{10^4}$ s. It is known in advance that the sinusoid could be present anywhere in the frequency range ${0<f < 500 Hz}$ and the noise component steadly increases beyond this range.
#investigation of the effect of windows on spectrum of a signal
P = 521
N = 16384
wlen = 4096
M = int(wlen/2)
T = 1/(10**4)
# load noisy sine wave
inp = loadmat('noisy_sine.mat')['xin']
inp = inp[0,:]
# apply a rectangular window of length 4096 to the signal and compute SQNR
inpR = inp[0:wlen-1]
dft_data = f_dft(inpR,wlen)
line, = plt.plot(20*np.log10(dft_data[0:M-1]))
line.set_label('Rect')
plt.legend()
# compute SQNR
#apply a Hann window of length 4096 to the signal and compute SQNR
#hann window.
x = np.arange(0,wlen,1)
#generate Hann window
hann_data = (1 - (np.cos(2*np.pi*(x)/wlen)))/2
#plt.show()
#plt.plot(hann_data)
# apply the window
inpH = inp[0:wlen] * hann_data
dft_data = f_dft(inpH,wlen)
plt.plot(20*np.log10(dft_data[0:M-1]),'#1f7f0e')
line, = plt.plot(20*np.log10(dft_data[0:M-1]))
line.set_label('Hann')
plt.legend()
plt.xlabel('DFT sample index, k')
plt.ylabel('$|X[k]|$ in dB')
plt.title('Magnitude $X[k]$')
plt.grid('True')
plt.ylim([-140,5])