In this notebook we will look at the following concepts:

  • Gain familiarity with python
  • Spectrum of a sine wave
  • Spectral characteristics of windows and their implications in DFT of a signal
  • Compute SQNR
  • Observe the implications of spectral leakage on SQNR.

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

  1. f_dft: Compute and plot DFT of a vector.
  2. f_gaussian: Generate samples of a Gaussian distribution and plot.
  3. f_uniform: Generate samples of uniform distribution and plot.
  4. f_plotspectrum: Plot the magnitude (in dB) of DFT samples.
In [16]:
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)
In [17]:
###############################################################################
# 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)
In [18]:
###############################################################################
# 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)
In [58]:
#
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')
    
    

Problem 1. Time and spectral characteristics of windows.

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
  1. Generate and plot length $M=51$ Rectangular, Hann, and $\mbox{Hann}^2$ windows.
  2. Compute $N=1024$ length DFT of the three windows and plot the magnitude spectrum in dB. Ensure that computed DFT is normalized.
  3. Determine the width of the main lobe, height of the first side lobe, and the slope of the line joining the peaks of high frequency side lobes for each of the windows from your plots.
In [59]:
#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')
C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:53: RuntimeWarning: divide by zero encountered in log10

Problem 2. DFT of a sine under "ideal" conditions.

The CT signal $x_a(t) = 0.9sin(2000\pi t)$ is sampled with a sampling period $T = \dfrac{1}{16000} s$.

  1. Generate $N = 256$ samples of the signal $x[n] = x_a(nT), n=0,1,\dots, N-1$. Compute the DFT, $X[k], k=0,1,2,\dots, N-1$ of $x[n]$. Plot $x[n[$ and the magnitude of DFT $X[k]$.
  2. Do you observe the effects of frequency leakage in your plot? Why not?
  3. Compute the "SQNR" of the signal. What is the SQNR limited by in this case?
In [61]:
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')

Problem 3. Spectral analysis of Sinusoidal signals.

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$.

  1. Generate $N= 1024$ samples of the signal given signal, $x[n] = x_a(nT), n=0,1,\dots,N-1$. Compute the DFT, $X[k], k=0,1,2,\dots, N-1$ of $x[n]$. Plot $x[n[$ and the magnitude of DFT $X[k]$.
  2. Compute the SNR of $x[n]$ using the samples of $X[k]$.
  3. Generate $N=1024$ samples of Gaussian noise, $x_g[n]$, of variance $\sigma^2 = 10^{-6}$. Form a new new signal, $\hat{x}[n] = x[n] + x_g[n]$.
    • Compute the $N=1024$ point DFT, $\hat{X}[k],k=0,1,\dots, N-1$, of $\hat{x}[n]$.
    • Plot $\hat{x}[n]$ and magnitude $|\hat{X}[k]$.
  4. Repeat parts (1) - (3) for the signal $x_a(t) = 0.9 sin(2\pi 47.5 t)$.
  5. Qualititatively explain the difference in SQNR you observe.
In [65]:
%%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))
In [63]:
# 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])
Out[63]:
(-120, 5)

Problem 4. Effect of windowing on data.

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.

  1. Plot the signal ${x_{in}}[n],n=0,1,\dots,N-1$ and $|X[k]|$, where ${X[k]}$ is the $N$ length DFT of ${xin}[n]$.
  2. Find the frequency of the sinusoid in ${x_{in}}[n]$ from your plots. Compute the SNR of the given signal in the frequency band ${0<f < 500 Hz}$.
  3. Generate the signal ${\hat{x}[n] =x_{in}[n]W[n] }$, where ${W[n]}$ is a rectangular window of length $M=4096$. Plot the signal ${\hat{x}[n]}$. Compute $M=4096$ length DFT, $\hat{X}[k]$ of $\hat{x}[n]$ and plot $|\hat{X}[k]|$. Compute the SNR of the signal $\hat{x}[n]$ in the frequency band ${0<f < 500 Hz}$.
  4. Repeat part (3) using a Hann window of length $M=4096$.
  5. Explain why there is a difference in the plotted spectrum and the computed SNR.
In [64]:
#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])
Out[64]:
(-140, 5)
In [ ]: