{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## EE 123 iPython Notebook Tutorial Spring 2016
modified from Berkeley Python Bootcamp 2013 https://github.com/profjsb/python-bootcamp
and Python for Signal Processing http://link.springer.com/book/10.1007%2F978-3-319-01342-8
- Frank Ong
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Installing iPython Notebook" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Follow the instructions on the class website to install python:\n", "\n", "http://inst.eecs.berkeley.edu/~ee123/sp16/python_install.html" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# iPython Notebook Navigation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Run iPython notebook cell" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The ipython notebook is divided into cells. Each cell can contain texts, codes or html scripts. Running a non-code cell simply advances to the next cell. To run a code cell using Shift-Enter or pressing the play button in the toolbar above:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "1+2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Interupting the kernel" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For debugging, often we would like to interupt the current running process. This can be done by pressing the stop button. \n", "\n", "When a processing is running, the circle on the right upper corner is filled. When idle, the circle is empty." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import time\n", "\n", "while(1):\n", " print \"error\"\n", " time.sleep(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Restarting the kernels" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Interupting sometimes does not work. You can reset the state by restarting the kernel. This is done by clicking Kernel/Restart or the Refresh button in the toolbar above." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Saving the notebook" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To save your notebook, either select `\"File->Save and Checkpoint\"` or hit `Command-s` for Mac and `Ctrl-s` for Windows" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Undoing" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To undo changes in each cell, hit `Command-z` for Mac and `Ctrl-z` for Windows\n", "\n", "To undo `Delete Cell`, select `Edit->Undo Delete Cell`" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Tab Completion" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "One useful feature of iPython is tab completion " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "one_plus_one = 1+1\n", "\n", "# type `one_` then hit TAB will auto-complete the variable\n", "print one_\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Help menu for functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Another useful feature is the help command. Type any function followed by `?` returns a help window. Hit the `x` button to close it." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "abs?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Other iPython Notebook navigation tips" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- To add a new cell, either select `\"Insert->Insert New Cell Below\"` or click the white plus button\n", "- You can change the cell mode from code to text in the pulldown menu. I use `Markdown` for text\n", "- You can change the texts in the `Markdown` cells by double-clicking them.\n", "- `Help->Keyboard Shortcuts` has a list of keyboard shortcuts" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Libraries" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These are the libraries that we will be using in this class:\n", " \n", "__Numpy__\n", "\n", "NumPy is the fundamental package for scientific computing with Python.\n", "\n", "__Scipy__\n", "\n", "The SciPy library is a collection of numerical algorithms and domain-specific toolboxes, including signal processing, optimization, statistics and much more.\n", "\n", "__matplotlib__\n", "\n", "matplotlib is a python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.\n", "\n", "__bokeh__\n", "\n", "Bokeh is a Python interactive visualization library that targets modern web browsers for presentation. Allows real-time plotting\n", "\n", "__PyAudio__\n", "\n", "PyAudio provides Python bindings for PortAudio, the cross-platform audio I/O library. With PyAudio, you can easily use Python to play and record audio on a variety of platforms.\n", "\n", "__pyrtlsdr__\n", "\n", "pyrtlsdr is a simple Python interface to devices supported by the RTL-SDR project, which turns certain USB DVB-T dongles employing the Realtek RTL2832U chipset into low-cost, general purpose software-defined radio receivers. It wraps all the functions in the librtlsdr library (including asynchronous read support), and also provides a more Pythonic API." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Importing" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To import a specific library `x`, simply type `import x`\n", "\n", "To access the library function `f`, type `x.f`\n", "\n", "If you want to change the library name to `y`, type `import x as y`\n", "\n", "\n", " " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "\n", "np.ones((3,1))\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Data Types" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Floats and Integers" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Unlike MATLAB, there is a difference between `int` and `float` in Python. Mainly, integer division returns the floor. Always check this when debugging!" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "1 / 4" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "1 / 4.0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "However, this will change in the future (Python 3.0)... If you import division from the future, then everything works fine" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from __future__ import division\n", "1 / 4" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Strings" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Unlike MATLAB/C, doubles quotes and single quotes are the same thing. Both represent strings. `'+'` concatenates strings" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# This is a comment\n", "\"123 \" + 'DSP'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Lists" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A list is a mutable array of data. That is we can change it after we create it. They can be created using square brackets []\n", "\n", "\n", "Important functions: \n", "\n", "- `'+'` appends lists. \n", "\n", "- `len(x)` to get length" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "x = [1, 2, 3] + [\"DSP\"]\n", "\n", "print x" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print len(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Tuples" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A tuple is an unmutable list. They can be created using round brackets (). \n", "\n", "They are usually used as inputs and outputs to functions" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "t = (\"D\", \"S\", \"P\") + (1, 2, 3)\n", "print t" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# cannot do assignment\n", "t[0] = 10\n", "\n", "# errors in ipython notebook appear inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Numpy Array" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Numpy array is like a list with multidimensional support and more functions. This will be the primary data structure in our class." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Creating a numpy array" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "x = np.array( [ [1, 2], [3 , 4] ] )\n", "\n", "print x" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Getting the shape of array" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "x.shape" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Elementwise operation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "One major advantage of using numpy arrays is that arithmetic operations on numpy arrays correspond to elementwise operations. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print x + 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Matrix multiplication" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can use np.matrix to do matrix multiplication" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "np.matrix(x) * np.matrix(x)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Slicing numpy arrays" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Numpy uses pass-by-reference semantics so it creates views into the existing array, without implicit copying. This is particularly helpful with very large arrays because copying can be slow." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "x = np.array([1,2,3,4,5,6])\n", "print x" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We slice an array from a to b-1 with `[a:b]`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "y = x[0:4]\n", "print y" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Because slicing does not copy the array, changing `y` changes `x`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "y[0] = 7\n", "print x\n", "print y" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To actually copy x, we should use .copy()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "x = np.array([1,2,3,4,5,6])\n", "y = x.copy()\n", "y[0] = 7\n", "print x\n", "print y" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Useful Numpy function: r_" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We use `r_` to create integer sequences in numpy arrays\n", "\n", "`r_[0:N]` creates an array listing every integer from 0 to N-1\n", "\n", "`r_[0:N:m]` creates an array listing every `m` th integer from 0 to N-1 " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np # by convention, import numpy as np\n", "from numpy import r_ # import r_ function from numpy directly, so that we can call r_ directly instead of np.r_\n", "\n", "print np.r_[-5:5] # every integer from -5 ... 4\n", "\n", "print np.r_[0:5:2] # every other integer from 0 ... 4" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Plotting" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this class, we will use `matplotlib.pyplot` to plot signals and images. \n", "\n", "By convention, we import `matplotlib.pyplot` as `plt`.\n", "\n", "To display the plots inside the browser, we use the command `%matplotlib inline`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "\n", "import matplotlib.pyplot as plt # by convention, we import pyplot as plt\n", "\n", "# plot in browser instead of opening new windows\n", "%matplotlib inline\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Generate signals\n", "x = np.r_[:1:0.01] # if you don't specify a number before the colon, the starting index defaults to 0\n", "y1 = np.exp( -x )\n", "y2 = np.sin( x*10.0 )/4.0 + 0.5" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Plotting one signal" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "plt.figure()\n", "plt.plot( x, y1 )" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Plotting multiple signals in one figure" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "plt.figure()\n", "plt.plot( x, y1 )\n", "plt.plot( x, y2 )" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Plotting multiple signals in different figures" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "plt.figure()\n", "plt.plot( x, y1 )\n", "plt.figure()\n", "plt.plot( x, y2 )" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### You can also add title and legends using `plt.title()` and `plt.legend()`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "plt.figure()\n", "plt.plot( x, y1 )\n", "plt.plot( x, y2 )\n", "plt.xlabel( \"x axis\" )\n", "plt.ylabel( \"y axis\" )\n", "\n", "plt.title( \"Title\" )\n", "\n", "plt.legend( (\"blue\", \"red\") )" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# xkcd style\n", "with plt.xkcd() :\n", " plt.figure()\n", " plt.plot( x, y1 )\n", " plt.plot( x, y2 )\n", " plt.xlabel( \"x axis\" )\n", " plt.ylabel( \"y axis\" )\n", "\n", " plt.title( \"Title\" )\n", "\n", " plt.legend( (\"blue\", \"red\") )" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Showing images" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`imshow` will be our default function to plot images" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# image\n", "\n", "image = np.outer( y1, y2 ) # plotting the outer product of y1 and y2\n", "\n", "plt.figure()\n", "plt.imshow(image)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## That's all!" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "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.11" } }, "nbformat": 4, "nbformat_minor": 0 }