{ "metadata": { "name": "numpy" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Scientific Python: Part 1\n", "## Numpy and Scipy\n", "\n", "__Software Carpentry Bootcamp \n", "eResearch NZ 2013__ \n", "\n", "Prepared by: Ariel Rokem\n", " \n", "Thanks to: Matt Davis, Justin Kitzes, Katy Huff, Matthew Terry" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Introducing Numpy\n", "\n", "NumPy is a Python package implementing efficient collections of specific types of data (generally numerical), similar to the standard array\n", "module (but with many more features). NumPy arrays differ from lists and tuples in that the data is contiguous in memory. A Python **list**, \n", "```[0, 1, 2]```, in contrast, is actually an array of pointers to Python objects representing each number. This allows NumPy arrays to be\n", "considerably faster for numerical operations than Python lists/tuples." ] }, { "cell_type": "code", "collapsed": true, "input": [ "# Many useful functions are in external packages\n", "# Let's meet numpy\n", "import numpy as np" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 1 }, { "cell_type": "code", "collapsed": true, "input": [ "# To see what's in a package, type the name, a period, then hit tab\n", "#np?\n", "#np." ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 2 }, { "cell_type": "code", "collapsed": false, "input": [ "# Some examples of numpy functions and \"things\":\n", "print(np.sqrt(4))\n", "print(np.pi) # Not a function, just a variable\n", "print(np.sin(np.pi)) # A function on a variable :) " ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "2.0\n", "3.14159265359\n", "1.22464679915e-16\n" ] } ], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Numpy arrays (ndarrays)\n", "\n", "Creating a NumPy array is as simple as passing a sequence to numpy.array:\n", " \n", "Numpy arrays are collections of things, all of which must be the same type, that work\n", "similarly to lists (as we've described them so far). The most important are:\n", "\n", "1. You can easily perform elementwise operations (and matrix algebra) on arrays\n", "1. Arrays can be n-dimensional\n", "1. Arrays must be pre-allocated (ie, there is no equivalent to append)\n", "\n", "Arrays can be created from existing collections such as lists, or instantiated \"from scratch\" in a \n", "few useful ways." ] }, { "cell_type": "code", "collapsed": false, "input": [ "arr1 = np.array([1, 2.3, 4]) \n", "print(type(arr1))\n", "print(arr1.dtype)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "\n", "float64\n" ] } ], "prompt_number": 4 }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can also explicitly specify the data-type if the automatically-chosen one would be unsuitable." ] }, { "cell_type": "code", "collapsed": false, "input": [ "arr2 = np.array([1, 2.3, 4], dtype=int) \n", "print(type(arr2))\n", "print(arr2.dtype)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "\n", "int64\n" ] } ], "prompt_number": 5 }, { "cell_type": "markdown", "metadata": {}, "source": [ "As you might expect, creating a NumPy array this way can be slow, since it must manually convert each element of a list into its equivalent C type (int objects become C ints, etc). There are many other ways to create NumPy arrays, such as `np.identity`, `np.zeros`, `np.zeros_like`, or by manually specifying the dimensions and type of the array with the low-level creation function:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "arr3 = np.ndarray((2, 3, 4), dtype=complex) # Notice : `ndarray`, not `array`!\n", "print(type(arr3))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "\n" ] } ], "prompt_number": 6 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Arrays have a `.shape` attribute, which stores the dimensions of the array as a tuple:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print(arr3.shape)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "(2, 3, 4)\n" ] } ], "prompt_number": 7 }, { "cell_type": "markdown", "metadata": {}, "source": [ "For many of the examples below, we will be using `np.arange` which, similar to the Python built-in function `range`, returns a NumPy array\n", "of integers from 0 to N-1, inclusive. Like `range`, you can also specify a starting value and a step:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "arr4 = np.arange(2, 5)\n", "print(arr4)\n", "arr5 = np.arange(1, 5, 2)\n", "print(arr5)\n", "arr6 = np.arange(1, 10, 2)\n", "print arr6" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[2 3 4]\n", "[1 3]\n", "[1 3 5 7 9]\n" ] } ], "prompt_number": 8 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise : Create an Array\n", "\n", "Create an array with values ranging from 0 to 10, in increments of 0.5. \n", "\n", "Reminder: get help by typing `np.arange?`, `np.ndarray?`, `np.array?`, etc. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Arithmetic with arrays\n", "\n", "Since numpy exists to perform efficient numerical operations in Python, arrays have all the usual arithmetic operations available to them. These operations are performed element-wise (i.e. the same operation is performed independently on each element of the array)." ] }, { "cell_type": "code", "collapsed": false, "input": [ "A = np.arange(5)\n", "B = np.arange(5, 10)\n", "\n", "print (A+B)\n", "\n", "print(B-A)\n", "\n", "print(A*B)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[ 5 7 9 11 13]\n", "[5 5 5 5 5]\n", "[ 0 6 14 24 36]\n" ] } ], "prompt_number": 9 }, { "cell_type": "markdown", "metadata": {}, "source": [ "## What would happen if A and B did not have the same `shape`?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Arithmetic with scalars:\n", "In addition, if one of the arguments is a scalar, that value will be applied to all the elements of the array." ] }, { "cell_type": "code", "collapsed": false, "input": [ "A = np.arange(5)\n", "print(A+10)\n", "print(2*A)\n", "print(A**2)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[10 11 12 13 14]\n", "[0 2 4 6 8]\n", "[ 0 1 4 9 16]\n" ] } ], "prompt_number": 10 }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Linear algebra with arrays\n", "You can use arrays as vectors and matrices in linear algebra operations\n", "\n", "Specifically, you can perform matrix/vector multiplication between arrays, by using the `.dot` method, or the `np.dot` function:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print A.dot(B)\n", "print np.dot(A, B)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "80\n", "80\n" ] } ], "prompt_number": 11 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note: *This is like the '`*`' operator in Matlab*" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise : \n", " \n", "1. Given two vectors in 3-space:\n", " \n", " `a = [1,2]`\n", " \n", " `b = [4,5]`\n", "\n", " Find the angle between these vectors. \n", "1. The rotation matrix of $\\theta$ angle is a matrix with elements: \n", " \n", " [[cos($\\theta$), -sin($\\theta$], \n", " \n", " [sin($\\theta$, cos($\\theta$)]]\n", " \n", " Create a function that takes two 3-vectors and creates the rotation matrix between them.\n", "1. For the vector `c=[7,8]`, find a vector `d` that has the same rotation as `b` has relative to `a`" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Boolean operators work on arrays too, and they return boolean arrays\n", "Much like the basic arithmetic operations we discussed above, comparison operations are perfomed element-wise. That is, rather than returning a\n", "single boolean, comparison operators compare each element in both arrays pairwise, and return an `array` of booleans (if the sizes of the input\n", "arrays are incompatible, the comparison will simply return False). For example:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "arr1 = np.array([1, 2, 3, 4, 5])\n", "arr2 = np.array([1, 1, 3, 3, 5])\n", "print(arr1 == arr2)\n", "c = (arr1 == arr2)\n", "print c.dtype" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[ True False True False True]\n", "bool\n" ] } ], "prompt_number": 12 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note: You can use the methods `.any()` and `.all()` or the functions `np.any` and `np.all` to return a single boolean indicating whether any or all values in the array are `True`, respectively.\n" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print(np.all(c))\n", "print(c.all())\n", "print(c.any())" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "False\n", "False\n", "True\n" ] } ], "prompt_number": 13 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Indexing arrays\n", "\n", "In addition to the usual methods of indexing lists with an integer (or with a series of colon-separated integers for a slice), numpy allows you\n", "to index arrays in a wide variety of different ways for more advanced operations.\n", "\n", "First, the simple way:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "a = np.array([1,2,3])\n", "print a[0:2]" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[1 2]\n" ] } ], "prompt_number": 14 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### What happens if the array has more than one dimension? " ] }, { "cell_type": "code", "collapsed": false, "input": [ "c = np.random.rand(3,3)\n", "print(c)\n", "print(c[1:3,0:2])\n", "c[0,:] = a\n", "print(c)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[[ 0.67732547 0.92040098 0.78127807]\n", " [ 0.17040251 0.45105409 0.53734387]\n", " [ 0.01613388 0.86307387 0.01468406]]\n", "[[ 0.17040251 0.45105409]\n", " [ 0.01613388 0.86307387]]\n", "[[ 1. 2. 3. ]\n", " [ 0.17040251 0.45105409 0.53734387]\n", " [ 0.01613388 0.86307387 0.01468406]]\n" ] } ], "prompt_number": 15 }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise\n", "We can manipulate the shape of an array as follows: \n", " `A = np.arange(16).reshape(4, 4)`\n", "Or even:\n", " `A = np.reshape(numpy.arange(16), (4, 4))`\n", " \n", "Using what we've learned about slicing and indexing, create a function that takes an integer as input, creates a square n-by-n array with integers from `0` to `n**2-1` (like `A`) and prints just the upper-left quarter of the array\n", "\n", "For example, for A, the desired output would be: \n", " \n", " array([[2, 3],\n", " [6, 7]])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Arrays can also be indexed with other arrays\n", "\n", "Arrays can be indexed with other arrays, using either an array of indices, or an array of booleans of the same length. In the former case, numpy returns a view of the data in the specified indices as a new array. In the latter, numpy returns a view of the array with only the elements where the index array is True. (We'll discuss the difference between views and copies in a moment.) This makes normally-tedious operations like clamping extremely simple.\n", "\n", "Indexing with an array of indices:\n" ] }, { "cell_type": "code", "collapsed": false, "input": [ "A = np.arange(5, 10)\n", "print(A)\n", "print(A[[0, 2, 3]])\n", "A[[0, 2, 3]] = 0\n", "print(A)\n" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[5 6 7 8 9]\n", "[5 7 8]\n", "[0 6 0 0 9]\n" ] } ], "prompt_number": 16 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Indexing with a boolean array:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "random = np.random\n", "A = np.array([random.randint(0, 10) for i in range(10)]) # Check out the list comprehension!\n", "print(A)\n", "A[A>5] = 5\n", "print(A)\n" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[0 2 9 1 9 5 6 1 3 1]\n", "[0 2 5 1 5 5 5 1 3 1]\n" ] } ], "prompt_number": 17 }, { "cell_type": "markdown", "metadata": {}, "source": [ "A few more examples:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "b = np.array([4,5,6])\n", "print (a)\n", "print (b)\n", "print (a > 2)\n", "print (a[a > 2])\n", "print (b[a > 2])\n", "b[a == 3] = 77\n", "print(b)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[1 2 3]\n", "[4 5 6]\n", "[False False True]\n", "[3]\n", "[6]\n", "[ 4 5 77]\n" ] } ], "prompt_number": 18 }, { "cell_type": "code", "collapsed": false, "input": [ "# There are handy ways to make arrays full of ones and zeros\n", "print(np.zeros(5))\n", "print np.ones(5)\n", "print np.identity(5), '\\n'" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[ 0. 0. 0. 0. 0.]\n", "[ 1. 1. 1. 1. 1.]\n", "[[ 1. 0. 0. 0. 0.]\n", " [ 0. 1. 0. 0. 0.]\n", " [ 0. 0. 1. 0. 0.]\n", " [ 0. 0. 0. 1. 0.]\n", " [ 0. 0. 0. 0. 1.]] \n", "\n" ] } ], "prompt_number": 19 }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Numpy 'gotchas'\n", "\n", "### Multiplication and Addition\n", "\n", "As you may have noticed above, since NumPy arrays are modeled more closely after vectors and matrices, multiplying by a scalar will multiply each element of the array, whereas multiplying a list by a scalar will repeat that list N times." ] }, { "cell_type": "code", "collapsed": false, "input": [ "A = np.arange(5)*2\n", "print(A) \n", "B = range(5)*2\n", "print(B)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[0 2 4 6 8]\n", "[0, 1, 2, 3, 4, 0, 1, 2, 3, 4]\n" ] } ], "prompt_number": 20 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Similarly, when adding two numpy arrays together, we get the vector sum back, whereas when adding two lists together, we get the concatenation back." ] }, { "cell_type": "code", "collapsed": false, "input": [ "A = np.arange(5) + np.arange(5)\n", "print(A)\n", "B =range(5) + range(5)\n", "print(B)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[0 2 4 6 8]\n", "[0, 1, 2, 3, 4, 0, 1, 2, 3, 4]\n" ] } ], "prompt_number": 21 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Views vs. Copies\n", "\n", "In order to be as efficient as possible, numpy uses \"views\" instead of copies wherever possible. That is, numpy arrays derived from another base array generally refer to the ''exact same data'' as the base array. The consequence of this is that modification of these derived arrays will also modify the base array. The result of an array indexed by an array of indices is a ''copy'', but an array indexed by an array of booleans is a ''view''. \n", "\n", "Specifically, slices of arrays are always views, unlike slices of lists or tuples, which are always copies." ] }, { "cell_type": "code", "collapsed": false, "input": [ "A = np.arange(5)\n", "B = A[0:1]\n", "B[0] = 42\n", "print(A)\n", "\n", "A = range(5)\n", "B = A[0:1]\n", "B[0] = 42\n", "print(A)\n", "\n", " \n", " " ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[42 1 2 3 4]\n", "[0, 1, 2, 3, 4]\n" ] } ], "prompt_number": 22 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise : Copy a numpy array\n", "\n", "Figure out how to create a copy of a numpy array. Remember: since numpy slices are views, you can't use the trick you'd use for Python lists,\n", "i.e. copy = list[:]." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Mathematics with numpy\n", "\n", "Being designed for scientific computing, numpy also contains a host of common mathematical functions, including linear algebra functions, fast\n", "Fourier transforms, and probability/statistics functions. While there isn't space to go over ''all'' of these in detail, we will provide an overview of the most common/essential of these." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For >2-dimensional arrays, there are some other common matrix operations that can be conducted:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "A = np.arange(16).reshape(4, 4)\n", "print(A)\n", "print(A.T) # transpose\n", "print(A.trace())" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[[ 0 1 2 3]\n", " [ 4 5 6 7]\n", " [ 8 9 10 11]\n", " [12 13 14 15]]\n", "[[ 0 4 8 12]\n", " [ 1 5 9 13]\n", " [ 2 6 10 14]\n", " [ 3 7 11 15]]\n", "30\n" ] } ], "prompt_number": 23 }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are many more methods like these available with NumPy arrays. Be sure to consult the numpy documentation before writing your own versions!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### The `matrix` class \n", "\n", "So far, we've used two-dimensional arrays to represent matrix-like objects. However, numpy provides a specialized class for this. The `matrix` class is almost identical to a two-dimensional numpy array, but has a few changes to the interface to simplify common linear algebraic tasks. These are: \\* The `*` operator is performs matrix multiplication \\* The `**` operator performs matrix exponentiation \\* The property `.I` (or the method `.getI()`) returns the matrix inverse \\* The property `.H` (or the method `.getH()`) returns the conjugate transpose\n", "\n", "### Example: Solving a System of Linear Equations" ] }, { "cell_type": "code", "collapsed": false, "input": [ "la = np.linalg\n", "A = np.matrix([[3, 2, -1], [2, -2, 4], [-1, .5, -1]])\n", "B = np.array([1, -2, 0])\n", "print(la.solve(A, B))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[ 1. -2. -2.]\n" ] } ], "prompt_number": 24 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Universal functions \n", "\n", "Universal functions (also called ufuncs) are high-speed, element-wise operations on NumPy arrays. They are, in essence, what allows you to operate on NumPy arrays efficiently. There are a large number of universal functions available covering most of the basic operations that get performed on data, like addition, subtraction, logarithms, and so on. Calling a ufunc is a simple matter:\n", "\n", " " ] }, { "cell_type": "code", "collapsed": false, "input": [ "A = np.arange(1,10)\n", "print(np.log10(A))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[ 0. 0.30103 0.47712125 0.60205999 0.69897 0.77815125\n", " 0.84509804 0.90308999 0.95424251]\n" ] } ], "prompt_number": 25 }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 25 }, { "cell_type": "markdown", "metadata": {}, "source": [ "In addition to basic operation like above, ufuncs that take two input arrays and return an output array can be used in more advanced ways.\n", "\n", "### Exercise : Elementwise Operations\n", "\n", "Using ufuncs, calculate the reciprocals of each element in the following array:\n", " \n", " [8.1, 1.6, 0.9, 4.3, 7.0, 7.3, 4.7, 8.2, 7.2, 3.0,\n", " 1.4, 9.8, 5.7, 0.7, 8.7, 4.6, 8.8, 0.9, 4.4, 4.4]\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Scipy\n", "\n", "Scipy is a huge library of scientific software. It includes many useful things, such as functions for statistics, for signal processing, image processing, etc. \n", "\n", "Because it's very large, importing it doesn't actually bring in all of its modules and those need to be imported individually. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "import scipy\n", "# scipy?" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 26 }, { "cell_type": "markdown", "metadata": {}, "source": [ "For example, if you want to look at physical constants, you need to specifically import the `constants` module." ] }, { "cell_type": "code", "collapsed": false, "input": [ "import scipy.constants as const" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 27 }, { "cell_type": "code", "collapsed": false, "input": [ "print(const.c)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "299792458.0\n" ] } ], "prompt_number": 28 }, { "cell_type": "code", "collapsed": false, "input": [ "print(const.find(\"alpha\"))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "['alpha particle mass', 'alpha particle mass energy equivalent', 'alpha particle mass energy equivalent in MeV', 'alpha particle mass in u', 'alpha particle molar mass', 'alpha particle-electron mass ratio', 'alpha particle-proton mass ratio', 'electron to alpha particle mass ratio']\n" ] } ], "prompt_number": 29 }, { "cell_type": "code", "collapsed": false, "input": [ "print(const.physical_constants['alpha particle mass'])" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "(6.64465675e-27, 'kg', 2.9e-34)\n" ] } ], "prompt_number": 30 }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are a lot of gems hidden in the `special` and `misc` modules" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import scipy.special as sps\n", "\n", "# We'll talk about matplotlib later today:\n", "import matplotlib.pylab as pylab\n", "x = np.arange(0.0, 10.1, 0.1)\n", "\n", "for n in range(4): \n", " j = sps.jn(n, x) \n", " pylab.plot(x, j, label='Bessel order=%s'%n)\n", "\n", "pylab.legend()\n", "pylab.show()\n", "\n" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 31 }, { "cell_type": "code", "collapsed": false, "input": [ "import scipy.misc as misc" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 32 }, { "cell_type": "code", "collapsed": false, "input": [ "import matplotlib.pylab as pylab\n", "pylab.matshow(misc.lena())\n", "pylab.show()" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 33 }, { "cell_type": "markdown", "metadata": {}, "source": [ "As a short-cut, you can import many useful things using the following command:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%pylab inline" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "\n", "Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.kernel.zmq.pylab.backend_inline].\n", "For more information, type 'help(pylab)'.\n" ] } ], "prompt_number": 34 }, { "cell_type": "markdown", "metadata": {}, "source": [ "This pulls into your namespace numpy (as `np`), as well as everything that is in numpy:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "array([1,2,3]) # Notice - I am calling this 'bare' without the preceding 'np'!" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 35, "text": [ "array([1, 2, 3])" ] } ], "prompt_number": 35 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Also - plots will from now on appear 'inline', as part of the cell output" ] }, { "cell_type": "code", "collapsed": false, "input": [ "plot(array([1,2,3]))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 36, "text": [ "[]" ] }, { "output_type": "display_data", "png": "iVBORw0KGgoAAAANSUhEUgAAAXYAAAD9CAYAAACoXlzKAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAETNJREFUeJzt3V9ok+cCx/FfZoUZ63S9sIW0h8HqRqM2rRuEc9AZGUPq\nsBQUnJyOor0ocvx3cW6GwuwmMlAQZUP0piJeOKiDFdYKuzAOla4MszHmwAor/aOUFumwnA2jvufC\nrSRtmr/vm/ff9wMFk/dZ8vDy7vG7J2+zgGEYhgAAnvGS3RMAAJiLhR0APIaFHQA8hoUdADyGhR0A\nPIaFHQA8JuvC/ueffyoajaqpqUnhcFgfffRRxnEHDx7UmjVrFIlElEgkLJkoACA/FdkOvvzyy7p+\n/bqCwaC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Gh4c1\nMjKiJ0+e6Msvv1Rra2vaGO55z18+53NycnLub/GhoSEZhqGqqio7put6XJvm4trMn2EY6uzsVDgc\n1uHDhzOOKfT6NG0rpqKiQp9//rm2bt2qZ8+eqbOzUw0NDTp//rwk7nkvVD7ns7e3V+fOnVNFRYWC\nwaCuXLli86ydi9/HMFeu88m1mb9bt27p8uXLamxsVHNzsyTpxIkTGh0dlVTc9Rkw+OgaADzF9v81\nHgDAXCzsAOAxLOwA4DEs7ADgMSzsAOAxLOwA4DH/BwsvGgE+K4eBAAAAAElFTkSuQmCC\n", "text": [ "" ] } ], "prompt_number": 36 }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] } ], "metadata": {} } ] }