{ "metadata": { "name": "", "signature": "sha256:d7d8a4c49f7e6af297d631a6678cee291f011a2ff9638e389e299f7c0bf855d3" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "EE 123 Basic Python Tutorial Spring 2015\n", "\n", "\n", " \n", "
January 21st, 2014 \n", "
\n", " modified from Berkeley Python Bootcamp 2013 https://github.com/profjsb/python-bootcamp\n", "
and Python for Signal Processing http://link.springer.com/book/10.1007%2F978-3-319-01342-8\n", " \n", "
- Frank Ong \n", "
" ] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "General iPython Notebook usage instructions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Click the `Play` button to run and advance a cell. The short-cut for it is `shift-enter`\n", "- To add a new cell, either select `\"Insert->Insert New Cell Below\"` or click the white down arrow 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", "- To save your notebook, either select `\"File->Save and Checkpoint\"` or hit `Command-s` for Mac and `Ctrl-s` for Windows\n", "- To undo in each cell, hit `Command-z` for Mac and `Ctrl-z` for Windows\n", "- To undo `Delete Cell`, select `Edit->Undo Delete Cell`\n", "- `Help->Keyboard Shortcuts` has a list of keyboard shortcuts" ] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Installing Python" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Follow the instructions on the class website to install python:\n", "\n", "http://inst.eecs.berkeley.edu/~ee123/sp15/python_install.html" ] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Tab Completion" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "One useful feature of iPython is tab completion " ] }, { "cell_type": "code", "collapsed": false, "input": [ "x = 1\n", "y = 2\n", "x_plus_y = x+y\n", "\n", "# type `x_` then hit TAB will auto-complete the variable\n", "print x_\n" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Help" ] }, { "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", "collapsed": false, "input": [ "abs?" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Hit `Tab` after a left parenthesis also brings up a help window" ] }, { "cell_type": "code", "collapsed": false, "input": [ "abs(" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Floats and Integers" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Doing math in python is easy, but note that there are `int` and `float` in Python. Integer division returns the floor. Always check this when debugging!" ] }, { "cell_type": "code", "collapsed": true, "input": [ "1 / 4" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "1 / 4.0" ], "language": "python", "metadata": {}, "outputs": [] }, { "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", "collapsed": false, "input": [ "from __future__ import division\n", "1 / 4" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Strings" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Doubles quotes and single quotes are the same thing. `'+'` concatenates strings" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# This is a comment\n", "\"Hi \" + 'Bye'" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Lists" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A list is a mutable array of data, ie can change stuff. 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", "collapsed": false, "input": [ "x = [1, 2, \"asdf\"] + [4, 5, 6]\n", "\n", "print x" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "print len(x)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "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", "collapsed": false, "input": [ "t = (1, 2, \"asdf\") + (3, 4, 5)\n", "print t" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "# cannot do assignment\n", "t[0] = 10\n", "\n", "# errors in ipython notebook appear inline" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Arrays (Numpy)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Numpy array is like a list with multidimensional support and more functions. We will be using it a lot.\n", "\n", "Arithmetic operations on numpy arrays correspond to elementwise operations. \n", "\n", "Important functions:\n", "\n", "- `.shape` returns the dimensions of the array\n", "\n", "- `.ndim` returns the number of dimensions. \n", "\n", "- `.size` returns the number of entries in the array\n", "\n", "- `len()` returns the first dimension\n", "\n", "\n", "To use functions in numpy, we have to import numpy to our workspace. This is done by the command `import numpy`. By convention, we rename `numpy` as `np` for convenience" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import numpy as np # by convention, import numpy as np\n", "\n", "x = np.array( [ [1, 2, 3], [4, 5, 6] ] )\n", "\n", "print x" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "print \"Number of dimensions:\", x.ndim" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "print \"Dimensions:\", x.shape" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "print \"Size:\", x.size" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "print \"Length:\", len(x)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "a = np.array([1, 2, 3])\n", "\n", "print \"a=\", a\n", "\n", "print \"a*a=\", a * a #elementwise" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "b = np.array(np.ones((3,3)))*2\n", "print \"b=\", b\n", "c = np.array(np.ones((3,3)))\n", "print \"c=\", c" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "multiply elementwise" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print \"b*c = \", b*c " ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now multiply as matrices" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print \"b*c = \", np.matrix(b)*np.matrix(c)\n", "print \"b*c = \", dot(b,c)\n" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Alternatively, array can be created as a matrix" ] }, { "cell_type": "code", "collapsed": false, "input": [ "d = np.matrix([[1,1j,0],[1,2,3]])\n", "e = np.matrix([[1],[1j],[0]])\n", "\n", "print d*e" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Slicing for 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", "collapsed": false, "input": [ "x = np.array([1,2,3,4,5,6])\n", "print x" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We slice an array from a to b-1 with `[a:b]`" ] }, { "cell_type": "code", "collapsed": false, "input": [ "y = x[0:4]\n", "print y" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Since slicing does not copy the array, changing `y` changes `x`" ] }, { "cell_type": "code", "collapsed": false, "input": [ "y[0] = 7\n", "print x\n", "print y" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To actually copy x, we should use .copy()" ] }, { "cell_type": "code", "collapsed": false, "input": [ "x = np.array([1,2,3,4,5,6])\n", "y = x.copy()\n", "y[0] = 7\n", "print x\n", "print y" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Commonly used Numpy function: r_" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We use `r_` to create integer sequences\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", "collapsed": false, "input": [ "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 r_[-5:5] # every integer from -5 ... 4\n", "\n", "print r_[0:5:2] # every other integer from 0 ... 4\n", "\n", "print abs( r_[-5:5] )\n" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Plotting" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this class, we will use `matplotlib.pyplot` to plot signals and images. \n", "\n", "To begin with, we import `matplotlib.pyplot` as `plt`" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import numpy as np\n", "import matplotlib.pyplot as plt # by convention, we import pyplot as plt\n", "from numpy import r_ # import r_ function from numpy\n", "\n", "\n", "x = r_[:1:0.01] # if you don't specify a number before the colon, the starting index defaults to 0\n", "a = np.exp( -x )\n", "b = np.sin( x*10.0 )/4.0 + 0.5\n", "\n", "# plot in browser instead of opening new windows\n", "%matplotlib inline" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`plt.plot(x, a)` plots `a` against `x`" ] }, { "cell_type": "code", "collapsed": false, "input": [ "plt.figure()\n", "plt.plot( x, a )" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Once you started a figure, you can keep plotting to the same figure" ] }, { "cell_type": "code", "collapsed": false, "input": [ "plt.figure()\n", "plt.plot( x, a )\n", "plt.plot( x, b )" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To plot different plots, you can create a second figure" ] }, { "cell_type": "code", "collapsed": false, "input": [ "plt.figure()\n", "plt.plot( x, a )\n", "plt.figure()\n", "plt.plot( x, b )" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To label the axes, use `plt.xlabel()` and `plt.ylabel()`" ] }, { "cell_type": "code", "collapsed": false, "input": [ "plt.figure()\n", "plt.plot( x, a )\n", "plt.plot( x, b )\n", "\n", "plt.xlabel( \"time\" )\n", "plt.ylabel( \"space\" )" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can also add title and legends using `plt.title()` and `plt.legend()`" ] }, { "cell_type": "code", "collapsed": false, "input": [ "plt.figure()\n", "plt.plot( x, a )\n", "plt.plot( x, b )\n", "plt.xlabel( \"time\" )\n", "plt.ylabel( \"space\" )\n", "\n", "plt.title( \"Graph\" )\n", "\n", "plt.legend( (\"blue\", \"red\") )" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are many options you can specify in `plot()`, such as color and linewidth. You can also change the axis using `plt.axis`" ] }, { "cell_type": "code", "collapsed": false, "input": [ "plt.figure()\n", "plt.plot( x, a ,':r',linewidth=20)\n", "plt.plot( x, b ,'--k')\n", "plt.xlabel( \"time\" )\n", "plt.ylabel( \"space\" )\n", "\n", "plt.title( \"Graph\" )\n", "\n", "plt.legend( (\"blue\", \"red\") )\n", "\n" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are many other plotting functions. For example, we will use `plt.imshow()` for showing images and `plt.stem()` for plotting discretized signal" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# image\n", "plt.figure()\n", "\n", "data = np.outer( a, b ) # plotting the outer product of a and b\n", "\n", "plt.imshow(data)\n" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "# stem plot\n", "plt.figure()\n", "plt.stem(a[::5]) # subsample by 5" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "# xkcd style\n", "plt.xkcd() \n", "plt.plot( x, a )\n", "plt.plot( x, b )\n", "plt.xlabel( \"time\" )\n", "plt.ylabel( \"space\" )\n", "\n", "plt.title( \"Graph\" )\n", "\n", "plt.legend( (\"blue\", \"red\") )" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "For loop" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Indent matters in python. Everything indented belongs to the loop" ] }, { "cell_type": "code", "collapsed": false, "input": [ "for i in [4, 6, \"asdf\", \"jkl\"]:\n", " print i\n" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "for i in r_[0:10]:\n", " print i" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "If Else statement" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Same goes to If Else" ] }, { "cell_type": "code", "collapsed": false, "input": [ "if 1 != 0:\n", " print \"1 != 0\"\n", "else:\n", " print \"1 = 0\"" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Printing" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here are some fancy ways of printing:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print \"There are currently %d students enrolled in EE123.\\n\" % 59" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "print \"%d out of %d is %f percent\" % ( 1 , 59 , 1.0/59.0 * 100 )" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] } ], "metadata": {} } ] }