{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Populating the interactive namespace from numpy and matplotlib\n" ] } ], "source": [ "%pylab inline\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from scipy import io\n", "\n", "import warnings\n", "warnings.filterwarnings('ignore')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Problem 1(b): On-Off Keying" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "#Initialize signal to be all zeros\n", "A = np.zeros(50000)\n", "\n", "#Set Tbit and assign 1s to A accordingly\n", "#BEGIN ANSWER HERE\n", "\n", "#Assign an integer value that corresponds to Tbit (in ns) to the variable Tbit. If Tbit = 8ns, Tbit = 8\n", "Tbit = \n", "\n", "#Assign first Tbit elements of A to 1. Syntactically, A[a:b]=1 sets elements a through b to 1\n", "A[] = \n", "\n", "#END ANSWER HERE\n", "\n", "#Plot A(t)\n", "figure(figsize=(15,6))\n", "subplot(1,2,1)\n", "plot(A); xlim(0, 300); ylim(0,2)\n", "title('A(t) for Tbit = ' + str(Tbit) + 'ns'); xlabel('t (ns)');\n", "\n", "#Calculate the Spectrum of A(t)\n", "#BEGIN ANSWER HERE\n", "\n", "#To calculate Fourier Transform of an array x, use np.fft.fftshift(np.fft.fft(x))\n", "A_spectrum = \n", "\n", "#END ANSWER HERE\n", "\n", "\n", "#Plot Spectrum \n", "subplot(1,2,2)\n", "w = np.linspace(0,2*pi,len(A_spectrum)/2)\n", "\n", "#Taking the magnitude of the spectrum so it is easy to identify 3dB bandwidth\n", "mag = 20*log10(abs(A_spectrum[len(A_spectrum)/2:len(A_spectrum)]/A_spectrum[len(A_spectrum)/2]*1.0))\n", "\n", "plot(w,mag); xlim(0,pi);ylim(-50,1.2*max(mag))\n", "title('Spectrum of A(t)'); xlabel('$\\omega$', fontsize=14); ylabel('Magnitude (dB)'); \n", "\n", "#Mark -3dB magnitude and frequency\n", "plot(w, -3*np.ones(len(w)), 'r')\n", "idx = min(range(len(mag)), key=lambda i: abs(abs(mag[i])-3))\n", "plot(w[idx]*np.ones(2), [-50, 1.2*max(mag)], 'g')\n", "print('3dB Bandwidth is = ' + str(w[idx]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Problem 1(c): On-Off Keying" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "#BEGIN ANSWER HERE\n", "#Create array for Tbit values\n", "Tbit_array = \n", "\n", "#Create array for 3dB bandwidth values\n", "w_array = \n", "\n", "#END ANSWER HERE\n", "\n", "#Plot Tbit (on x-axis) and w (on y-axis)\n", "plot(Tbit_array, w_array)\n", "xlabel('Tbits'); ylabel('3dB Bandwidth')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Problem 3(b): Audio Compression\n", "Run the helper functions below before continuing!" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import pyaudio\n", "import wave\n", "\n", "# function that reads wav file to array\n", "def read_wav( wavname ):\n", " \n", " wf = wave.open(wavname, 'rb')\n", " \n", " CHUNK = 1024\n", " frames = []\n", " data_str = wf.readframes(CHUNK) #read a chunk\n", " \n", " while data_str != '':\n", " data_int = np.fromstring( data_str, 'int16') # convert from string to int (assumes .wav in int16)\n", " data_flt = data_int.astype( np.float32 ) / 32767.0 # convert from int to float32\n", " frames.append( data_flt ) #append to list\n", " data_str = wf.readframes(CHUNK) #read a chunk\n", "\n", " return np.concatenate( frames )\n", "\n", "\n", "def play_audio( data, p, fs):\n", " # data - audio data array\n", " # p - pyAudio object\n", " # fs - sampling rate\n", " \n", " # open output stream\n", " ostream = p.open(format=pyaudio.paFloat32, channels=1, rate=fs,output=True)\n", " # play audio\n", " ostream.write( data.astype(np.float32).tostring() )\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Problem begins here!" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [], "source": [ "#Instantiate PyAudio and Load Song (~10sec)\n", "p = pyaudio.PyAudio()\n", "fs = 44100\n", "data = io.loadmat('pharrell.mat')\n", "pharrell = double(data['pharrell'])[0]\n", "\n", "#Play Audio from .wav file (needs to finish playing before you can move on)\n", "play_audio(pharrell, p, fs )\n", "p.terminate()" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [], "source": [ "#BEGIN ANSWER HERE\n", "\n", "#To calculate Fourier Transform of an array x, use np.fft.fftshift(np.fft.fft(x))\n", "pharrell_fft = \n", "\n", "#END ANSWER HERE\n", "\n", "#Set thresh% of the highest frequencies to 0\n", "\n", "#Set threshold value \n", "thresh = 0.80\n", "\n", "#Calculate number of frequencies to set to 0\n", "freq_zero_len = thresh*len(pharrell_fft)/2.0\n", "\n", "#Set appropriate frequency components in pharrell_fft to 0\n", "pharrell_fft[0:freq_zero_len] = pharrell_fft[len(pharrell_fft)-freq_zero_len:len(pharrell_fft)] = 0" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [], "source": [ "#Take Inverse Fourier Transform\n", "pharrell_new = (np.fft.ifft(np.fft.ifftshift(pharrell_fft)))\n", "\n", "#Instantiate PyAudio and Compressed Song\n", "p = pyaudio.PyAudio()\n", "fs = 44100\n", "play_audio(real(pharrell_new), p, fs) #Taking real part\n", "p.terminate()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Problem 3(c): Image Compression" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "#Load and display campanile image\n", "campanile = np.load('campanile.npy')\n", "plt.imshow(campanile, cmap='gray')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The following block of code calculates the Fourier Transform of each column of the image, thresholds it, and displays the resulting image\n" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": false }, "outputs": [], "source": [ "#Create matrices for the Fourier Transform and new campanile image\n", "campanile_fft = np.zeros((329,329) , dtype=numpy.complex)\n", "campanile_new = np.zeros((329,329) , dtype=numpy.complex)\n", "\n", "#Iterate through each column\n", "for i in range(329):\n", " #Take Fourier Transform of a row of the image\n", " campanile_fft[:,i] = np.fft.fftshift(np.fft.fft(campanile[:,i]))\n", " \n", " #Set thresh% of the highest frequencies to 0 (look at audio problem code!)\n", " #BEGIN ANSWER HERE\n", " \n", " #Set threshold value \n", " \n", " \n", " #Calculate number of frequencies to set to 0\n", " \n", " \n", " #Set appropriate frequency components in camanile_fft to 0\n", " \n", " \n", " #END ANSWER HERE\n", " \n", " #Take Inverse Fourier Transform\n", " campanile_new[:,i] = ((np.fft.ifft(np.fft.ifftshift(campanile_fft[:,i]))))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "#Show Compressed Image\n", "figure(figsize=(8,8))\n", "imshow(abs(campanile_new), cmap='gray')" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "Now, repeat the exercise by iterating through each *row* of the image, taking the Fourier Tranform, setting high frequencies to 0, and displaying the result.\n", "Hint: You should be able to just copy the code from above and change the indexing!" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.5" } }, "nbformat": 4, "nbformat_minor": 0 }