{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Advanced IPython breakout session\n", "===\n", "Created for the Berkeley Python Bootcamp August 2012 by Henrik Brink <brink@berkeley.edu>.\n", "\n", "![XKCD Python comic](http://imgs.xkcd.com/comics/python.png)\n", "\n", "Comic from !\n", "\n", "Introduction\n", "---\n", "In this breakout session we're going to try some of the more advanced features of IPython, mostly serving to optimize your code by using other languages (such as R and C/Cython) inline as well as seamless parallelization.\n", "\n", "Throughout this we'll assume that you have started the IPython Notebook server with Pylab enabled for inline plotting:" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ ipython notebook --pylab=\"inline\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Version 0.13 of IPython is highly recommended, as some of the features used in this session are newly introduced. Unfortunately, EPD currently ships with IPython 0.12, so you will have to either download the new version of IPython or make due with the 0.12 features (welcome to life on the edge!).\n", "\n", "### The problem\n", "\n", "We are going to define a simple problem that some of you might have run into during your work. Given some function that is complicated to calculate, you might want to use some sampling technique to trace out the function more efficiently than the brute force approach.\n", "\n", "Let's first define some function that is supposed to be complicated. And pretty. Sorry if it's neither." ] }, { "cell_type": "code", "execution_count": 3, "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\n", "\"\"\"\n", "A complicated function consisting of 3 2D gaussians.\n", "\"\"\"\n", "c_x1 = 0.5; c_y1 = 0.2; w_x1 = 0.15; w_y1 = 0.04\n", "c_x2 = 0.7; c_y2 = 0.7; w_x2 = 0.05; w_y2 = 0.05\n", "c_x3 = 0.3; c_y3 = 0.7; w_x3 = 0.05; w_y3 = 0.07\n", "def gaussian(x, y):\n", " return \\\n", " exp( -( ((c_x1 - x)/w_x1)**2. + ((c_y1 - y)/w_y1)**2. )/2 ) + \\\n", " exp( -( ((c_x2 - x)/w_x2)**2. + ((c_y2 - y)/w_y2)**2. )/2 ) + \\\n", " exp( -( ((c_x3 - x)/w_x3)**2. + ((c_y3 - y)/w_y3)**2. )/2 )" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's see how it looks (and pretend this is computationally intractable)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAQcAAAEACAYAAAC+rrMfAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAFuVJREFUeJzt3X+MXXWZx/H3Y0UqCtTatWbbYe9KG+go8kNtWQSp0WQr\nycqKRqy/4q+Im9QY3USIf8iSXd0lcZE1bLAisrqb2GxA3S7hRyRagRW620D5sW1NB5hsWwQpPxTd\nDmmXZ/+4V73nOQ9zv3N75t47nc8raTLfM88957ln7jxzztPvOcfcHRGR6EXDTkBERpOKg4ikVBxE\nJKXiICIpFQcRSak4iEiqZ3Ews2+Z2eNm9sA0MV8zs91mdp+Znd5siiIyDCVHDtcB617om2Z2HrDC\n3VcCnwSubig3ERminsXB3e8Anp4m5J3AtzuxW4FFZra0mfREZFia6DksA/Z0jfcCyxtYr4gMUVMN\nSQtjzckWmeNe3MA69gFjXePlnWUVZqaCITIk7h7/gPfURHHYDGwANpnZmcAz7v54HnppA5sbpC3A\n2iHnMBNbmFv5gnIehMv6elXP4mBm3wXOBZaY2R7av+FHAbj7Rne/yczOM7MJ4DfAR/vKRERGSs/i\n4O7rC2I2NJOOiIwKzZCcVmvYCcxQa9gJ9KE17AT60Bp2AgOh4jCt1rATmKHWsBPoQ2vYCfShNewE\nBkLFQURSKg4iklJxEJGUioOIpFQcRCSl4iAiqSamT0vFUbO47oOzuG6RKh05iEhKxUFEUioOIpJS\ncRCRlBqSM5I1G+MuLGlIZrv9UB+vy16jpqU0Q0cOIpJScRCRlIqDiKTUc5hW7B9ku+ulPcbZsqwv\nEXsFB5KYuCyL6bVekTI6chCRlIqDiKRUHEQkpeIgIik1JH+nZILTcUnM4h7jbFlJQ/KpJ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l53hVoY/h6NkHwN8GrgeeGKQySVK8n0/cIO77wVw9/0D\nzjEqyfnnwHGdr48DnnT3ph7qOWPufgfw9DQhM/69a7o4zLVJUyX5dvs4cNOsZtRbz5zNbBntD/Nv\np7IPs7FUso9XAovN7Mdmts3MPjSw7HIlOV8DvNbMHgXuAz4zoNz6NePfu6afeDXXJk0Vb9fM3gp8\nDHjz7KVTpCTnK4FL3N3NzKjv70Eqyfco4AzgbcAxwF1mdre7757VzF5YSc5fALa7+1ozOxH4oZmd\n6u7PznJuh2NGv3dNF4eGJ03NupJ86TQhrwHWuft0h26DUJLzG2jPO4H2+fA7zOygu28eTIoVJfnu\nAfa7+wHggJndDpwKDKs4lOR8FvAlAHd/yMweAU6iPTdoFM38967hpsiLgYdoN3JeQu+G5JkMtyFZ\nku8JtJtTZw4rz5nmHOKvAy4Y5XyBk4HbaDcCjwEeAMZHPOcrgEs7Xy+lXTwWD/mz0aKsIVn0e9fo\nkYPPsUlTJfkCXwReAVzd+Ut80N1Xj3jOI6PwM7HLzG4B7geeB65x9x2jnDPwZeA6M7uPdu/u8+7+\n1LByNrPvAucCS8xsD3Ap7dO1vn/vNAlKRFK6TZyIpFQcRCSl4iAiKRUHEUmpOIhISsVBRFIqDiKS\nUnEQkdT/A8gg8wOiisaEAAAAAElFTkSuQmCC\n", "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "resolution = 50.\n", "inds = indices((resolution,resolution))/resolution\n", "imshow( gaussian(*inds).T, origin=\"lower\", interpolation=\"nearest\", extent=(0,1,0,1) );" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Wait, who is that?\n", "\n", "### Metropolis-Hastings sampler\n", "\n", "Anyways, let's look at a way to sample arbitrary functions: The [Metropolis-Hastings algorithm](http://en.wikipedia.org/wiki/Metropolis%E2%80%93Hastings_algorithm).\n", "\n", "A very simple Metropolis-Hastings 2D random walker is defined below, along with a function for plotting the points returned by the walker:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [], "source": [ "\"\"\"\n", "A very simple Metropolis-Hastings random walker in 2D\n", "\"\"\"\n", "def random_walker(func, n_steps=1000, start=[0,0], burn_in=100):\n", " points = []\n", " point = start\n", " for i in arange(n_steps):\n", " # Our jumping distribution is the [-0.1,0.1] Uniform distribution around the current point\n", " new_point = point + (rand(2)-0.5)/5.\n", " accept = func(*new_point) / func(*point)\n", " if accept >= 1 or rand() <= accept:\n", " point = new_point\n", " if i > burn_in: points.append(point)\n", " return asarray(points)\n", "\n", "\"\"\"\n", "A function to plot the points\n", "\"\"\"\n", "def plot_points(points):\n", " h2,_,_ = histogram2d(points[:,0], points[:,1], [resolution,resolution], range=[[0,1],[0,1]])\n", " imshow(h2.T, origin=\"lower\", extent=(0,1,0,1), interpolation='nearest')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise 1\n", "\n", "In the cell below, sample the function defined above using the Metropolis-Hastings sampler and plot the result." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Yes, you're up!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Try different walker parameters and see what happens.\n", "\n", "What's wrong with that image?\n", "\n", "### [Optional] Exercise 2\n", "\n", "Time the random walker with n_steps=1e5 steps." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Time it" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise 3\n", "\n", "In the cell below, finish the code to start several random walkers at different locations and combine the output to show a more complete picture. We're creating 10 random starting positions, so you can go an order of magnitude down in sample size. Remember that this will take 10 times whatever you got in Exercise 2." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Fill out the missing pieces\n", "starts = rand(10,2)\n", "points = []\n", "for start in starts:\n", " #points.append( ... )\n", "plot_points( concatenate(points) )" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Hopefully, you were able to sample a larger part of the function. But this comes at the cost of far more computing time...\n", "\n", "Parallelization\n", "----\n", "\n", "At this point it would be very obvious to cut down on computation time by parallelizing the independent random walkers. But who wants to go through all the hastleof parallization?\n", "\n", "Luckily, IPython makes it much easier to start parallel computing clusters and use those from IPython. If you're using version 0.13 of IPython, you can go to the Notebook Dashboard that appeared when you started the notebook server (you can get there again by hitting File -> Open above). Select the Clusters tab, insert the number of cores on your computer (usually 2 or 4) and hit Start.\n", "\n", "I you're using 0.12, I would recommend you to update. If you're still using 0.12, you can start the cluster manually by issuing in the console:" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ ipcluster start -n 4" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The only thing you have to do now is enable parallel support in your running notebook:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from IPython.parallel import Client\n", "c = Client()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We now have all of the cores in the cluster available, and we can execute code on all of them by prefixing with a %px. We will use this to load the pylab interface on all engines:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%px %pylab" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You should see some startup output from all the engines in the cluster.\n", "\n", "### Exercise 4\n", "\n", "To run all the code in a notebook shell, you can start the whole cell with %%px. In fact, you are now going to use this to parallelize the code from above. It's almost easier than making the loop. \n", "\n", "The only thing that we need to do is define the functions that we use on all of the external cores. Simply head to the cells where the gaussian and the random_walker functions are defined, put %%px as the only thing on the first line and evaluate the cell again. This is a powerful feature of the notebook, that you can go back and forth between cells when your system changes, but it can also be dangerous. For example, if you close this notebook server and reopen, the %%px cells won't work until you've defined the cluster. Usually you want to do this at the beginning anyway.\n", "\n", "When you come back here, fill out the cell below and enjoy the speedup:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%%px\n", "# ..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Interacting with the engines\n", "\n", "But how to get the results? We need to use the parallel Client object to get the variables defined on each machine. Below we do this and plot the result:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "plot_points(concatenate( c[:][\"points\"] ))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This hints to a pretty nice feature. With our cluster defined, we can get a single engine with c[id], and we can extract their variables using a standard Dict syntax. By using the --targets argument with %%px, we can control exactly what code is run on which engines. See more in the [IPython manual](http://ipython.org/ipython-doc/rel-0.13/parallel/magics.html).\n", "\n", "It's out of the scope of this session, but the very cool thing about these engines is that they need not run on the local machine. In fact, they can run on any supercomputer in the world and still be used in exactly the same way from the Notebook or other IPython clients.\n", "\n", "Other languages in the Notebook\n", "----\n", "\n", "But what if we're still not satisfied with the performance? In the IPython Notebook we can turn any cell into C code using the excellent Cython language and %cythonmagic feature. Note that running this requires Cython and a C compiler. You most likely have a C compiler, and Cython can easily be installed with easy_install (or pip):" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ sudo easy_install Cython" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We now load Cython functionality into the Notebook:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%load_ext cythonmagic" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise 5\n", "\n", "Now we can transform any cell into a Cython cell by starting if off with %%cython. We will now use this to optimize our code even further, by reimplementing the 2D gaussian function in Cython code and hopefully gain some efficiency. Remember that this function is called at least twice pr. step by a random walker. Fill out the missing parts below. Hint: Cython is often just copy-pastable from regular Python. Hint 2: Use the imported pow instead of \"**\" for exponentiation." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%%px\n", "%%cython\n", "cimport cython\n", "from math import pow, exp\n", "\"\"\"\n", "A complicated function consisting of 3 2D gaussians, now in C with Cython.\n", "\"\"\"\n", "cdef double c_x1 = 0.5, c_y1 = 0.2, w_x1 = 0.15, w_y1 = 0.04\n", "cdef double c_x2 = 0.7, c_y2 = 0.7, w_x2 = 0.05, w_y2 = 0.05\n", "cdef double c_x3 = 0.3, c_y3 = 0.7, w_x3 = 0.05, w_y3 = 0.07\n", "def gaussian_cython(x, y):\n", " return \\\n", " #...\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### [Optional] Exercise 6\n", "\n", "Now run the random walker using the cython function as a replacement and time it. Any difference?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Your timing code here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Putting everything together\n", "\n", "We can now do something very cool: dispath the Cython'ized version of our code to our cluster of engines. Before this works, go back and load the cythonmagic and define the Cython function on all the cores (just place a %%px at the top, remember?).\n", "\n", "### Exercise 7\n", "\n", "Once again, fill out the missing parts below." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%%px\n", "# ..." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Plot it" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Fast eh?\n", "\n", "### More magic\n", "\n", "You can run many other languages in the Notebook, some of the must useful (depending on your background) might be the %%R magic (in the rmagic extension), the %%octave magic (in the octavemagic extension) and the built-in %%! magic for running things in the underlying command line shell.\n", "\n", "### [Optional] Exercise 8\n", "\n", "Load and use the R or Octave magics to plot the points from the random walker run, if you know how to use those." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Go for it!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Taking your code to the cloud\n", "\n", "You can go even further in the parallelization of your code by using a public cloud such as Amazon. PiCloud has made this very easy with Python, and you get a pretty substantial amount of free computing time every month.\n", "\n", "Go to [PiCloud](https://www.picloud.com/) to read more, sign up and follow the instructions for installing their client package. After that, the steps below should just work! " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import cloud" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def start_walker(start):\n", " return random_walker(gaussian, 1e5, start=start)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "starts = rand(10,2)\n", "jids = cloud.map( start_walker, starts )" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "plot_points(concatenate(cloud.result(jids)))" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.4.3" } }, "nbformat": 4, "nbformat_minor": 0 }