{ "metadata": { "name": "Central Limit Theroem" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "code", "collapsed": false, "input": [ "from pandas import *\n", "from matplotlib import animation\n", "import numpy as np " ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 1 }, { "cell_type": "code", "collapsed": false, "input": [ "import sys\n", "sys.path.append('C:\\Python27\\Lib\\site-packages\\JSAnimation')\n", "from JSAnimation.IPython_display import display_animation" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Histogram animation" ] }, { "cell_type": "code", "collapsed": false, "input": [ "\"\"\"\n", "This example shows how to use a path patch to draw a bunch of\n", "rectangles for an animated histogram\n", "\"\"\"\n", "from JSAnimation import IPython_display\n", "import numpy as np\n", "\n", "import matplotlib.pyplot as plt\n", "import matplotlib.patches as patches\n", "import matplotlib.path as path\n", "import matplotlib.animation as animation\n", "\n", "fig = plt.figure()\n", "ax = fig.add_subplot(111)\n", "\n", "# histogram our data with numpy\n", "data = np.random.randn(1000)\n", "n, bins = np.histogram(data, 100)\n", "\n", "# get the corners of the rectangles for the histogram\n", "left = np.array(bins[:-1])\n", "right = np.array(bins[1:])\n", "bottom = np.zeros(len(left))\n", "top = bottom + n\n", "nrects = len(left)\n", "\n", "# here comes the tricky part -- we have to set up the vertex and path\n", "# codes arrays using moveto, lineto and closepoly\n", "\n", "# for each rect: 1 for the MOVETO, 3 for the LINETO, 1 for the\n", "# CLOSEPOLY; the vert for the closepoly is ignored but we still need\n", "# it to keep the codes aligned with the vertices\n", "nverts = nrects*(1+3+1)\n", "verts = np.zeros((nverts, 2))\n", "codes = np.ones(nverts, int) * path.Path.LINETO\n", "codes[0::5] = path.Path.MOVETO\n", "codes[4::5] = path.Path.CLOSEPOLY\n", "verts[0::5,0] = left\n", "verts[0::5,1] = bottom\n", "verts[1::5,0] = left\n", "verts[1::5,1] = top\n", "verts[2::5,0] = right\n", "verts[2::5,1] = top\n", "verts[3::5,0] = right\n", "verts[3::5,1] = bottom\n", "\n", "barpath = path.Path(verts, codes)\n", "patch = patches.PathPatch(barpath, facecolor='green', edgecolor='yellow', alpha=0.5)\n", "ax.add_patch(patch)\n", "\n", "ax.set_xlim(left[0], right[-1])\n", "ax.set_ylim(bottom.min(), top.max())\n", "\n", "def animate(i):\n", " # simulate new data coming in\n", " data = np.random.randn(1000)\n", " n, bins = np.histogram(data, 100)\n", " top = bottom + n\n", " verts[1::5,1] = top\n", " verts[2::5,1] = top\n", "\n", "ani = animation.FuncAnimation(fig, animate, 100, repeat=False)\n", "display_animation(ani, default_mode='once')" ], "language": "python", "metadata": {}, "outputs": [ { "html": [ "\n", "\n", "\n", "
\n", " \n", "
\n", " \n", "
\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
\n", " Once \n", " Loop \n", " Reflect \n", "
\n", "
\n", "\n", "\n", "\n" ], "metadata": {}, "output_type": "pyout", "prompt_number": 3, "text": [ "" ] } ], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Jakes examples" ] }, { "cell_type": "code", "collapsed": false, "input": [ "\"\"\"\n", "Matplotlib Animation Example\n", "\n", "author: Jake Vanderplas\n", "email: vanderplas@astro.washington.edu\n", "website: http://jakevdp.github.com\n", "license: BSD\n", "Please feel free to use and modify this, but keep the above information. Thanks!\n", "\"\"\"\n", "\n", "# First set up the figure, the axis, and the plot element we want to animate\n", "fig = plt.figure()\n", "ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))\n", "line, = ax.plot([], [], lw=2)\n", "\n", "# initialization function: plot the background of each frame\n", "def init():\n", " line.set_data([], [])\n", " return line,\n", "\n", "# animation function. This is called sequentially\n", "def animate(i):\n", " x = np.linspace(0, 2, 1000)\n", " y = np.sin(2 * np.pi * (x - 0.01 * i))\n", " line.set_data(x, y)\n", " return line,\n", "\n", "# call the animator. blit=True means only re-draw the parts that have changed.\n", "anim = animation.FuncAnimation(fig, animate, init_func=init,\n", " frames=200, interval=20, blit=True)\n", "\n", "# save the animation as an mp4. This requires ffmpeg or mencoder to be\n", "# installed. The extra_args ensure that the x264 codec is used, so that\n", "# the video can be embedded in html5. You may need to adjust this for\n", "# your system: for more information, see\n", "# http://matplotlib.sourceforge.net/api/animation_api.html\n", "#anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])\n", "\n", "display_animation(anim)" ], "language": "python", "metadata": {}, "outputs": [ { "html": [ "\n", "\n", "\n", "
\n", " \n", "
\n", " \n", "
\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
\n", " Once \n", " Loop \n", " Reflect \n", "
\n", "
\n", "\n", "\n", "\n" ], "metadata": {}, "output_type": "pyout", "prompt_number": 8, "text": [ "" ] } ], "prompt_number": 8 }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Jake Ball Animation" ] }, { "cell_type": "code", "collapsed": false, "input": [ "\"\"\"\n", "Animation of Elastic collisions with Gravity\n", "\n", "author: Jake Vanderplas\n", "email: vanderplas@astro.washington.edu\n", "website: http://jakevdp.github.com\n", "license: BSD\n", "Please feel free to use and modify this, but keep the above information. Thanks!\n", "\"\"\"\n", "import numpy as np\n", "from scipy.spatial.distance import pdist, squareform\n", "\n", "import matplotlib.pyplot as plt\n", "import scipy.integrate as integrate\n", "import matplotlib.animation as animation\n", "\n", "class ParticleBox:\n", " \"\"\"Orbits class\n", " \n", " init_state is an [N x 4] array, where N is the number of particles:\n", " [[x1, y1, vx1, vy1],\n", " [x2, y2, vx2, vy2],\n", " ... ]\n", "\n", " bounds is the size of the box: [xmin, xmax, ymin, ymax]\n", " \"\"\"\n", " def __init__(self,\n", " init_state = [[1, 0, 0, -1],\n", " [-0.5, 0.5, 0.5, 0.5],\n", " [-0.5, -0.5, -0.5, 0.5]],\n", " bounds = [-2, 2, -2, 2],\n", " size = 0.04,\n", " M = 0.05,\n", " G = 9.8):\n", " self.init_state = np.asarray(init_state, dtype=float)\n", " self.M = M * np.ones(self.init_state.shape[0])\n", " self.size = size\n", " self.state = self.init_state.copy()\n", " self.time_elapsed = 0\n", " self.bounds = bounds\n", " self.G = G\n", "\n", " def step(self, dt):\n", " \"\"\"step once by dt seconds\"\"\"\n", " self.time_elapsed += dt\n", " \n", " # update positions\n", " self.state[:, :2] += dt * self.state[:, 2:]\n", "\n", " # find pairs of particles undergoing a collision\n", " D = squareform(pdist(self.state[:, :2]))\n", " ind1, ind2 = np.where(D < 2 * self.size)\n", " unique = (ind1 < ind2)\n", " ind1 = ind1[unique]\n", " ind2 = ind2[unique]\n", "\n", " # update velocities of colliding pairs\n", " for i1, i2 in zip(ind1, ind2):\n", " # mass\n", " m1 = self.M[i1]\n", " m2 = self.M[i2]\n", "\n", " # location vector\n", " r1 = self.state[i1, :2]\n", " r2 = self.state[i2, :2]\n", "\n", " # velocity vector\n", " v1 = self.state[i1, 2:]\n", " v2 = self.state[i2, 2:]\n", "\n", " # relative location & velocity vectors\n", " r_rel = r1 - r2\n", " v_rel = v1 - v2\n", "\n", " # momentum vector of the center of mass\n", " v_cm = (m1 * v1 + m2 * v2) / (m1 + m2)\n", "\n", " # collisions of spheres reflect v_rel over r_rel\n", " rr_rel = np.dot(r_rel, r_rel)\n", " vr_rel = np.dot(v_rel, r_rel)\n", " v_rel = 2 * r_rel * vr_rel / rr_rel - v_rel\n", "\n", " # assign new velocities\n", " self.state[i1, 2:] = v_cm + v_rel * m2 / (m1 + m2)\n", " self.state[i2, 2:] = v_cm - v_rel * m1 / (m1 + m2) \n", "\n", " # check for crossing boundary\n", " crossed_x1 = (self.state[:, 0] < self.bounds[0] + self.size)\n", " crossed_x2 = (self.state[:, 0] > self.bounds[1] - self.size)\n", " crossed_y1 = (self.state[:, 1] < self.bounds[2] + self.size)\n", " crossed_y2 = (self.state[:, 1] > self.bounds[3] - self.size)\n", "\n", " self.state[crossed_x1, 0] = self.bounds[0] + self.size\n", " self.state[crossed_x2, 0] = self.bounds[1] - self.size\n", "\n", " self.state[crossed_y1, 1] = self.bounds[2] + self.size\n", " self.state[crossed_y2, 1] = self.bounds[3] - self.size\n", "\n", " self.state[crossed_x1 | crossed_x2, 2] *= -1\n", " self.state[crossed_y1 | crossed_y2, 3] *= -1\n", "\n", " # add gravity\n", " self.state[:, 3] -= self.M * self.G * dt\n", "\n", "\n", "#------------------------------------------------------------\n", "# set up initial state\n", "np.random.seed(0)\n", "init_state = -0.5 + np.random.random((50, 4))\n", "init_state[:, :2] *= 3.9\n", "\n", "box = ParticleBox(init_state, size=0.04)\n", "dt = 1. / 30 # 30fps\n", "\n", "\n", "#------------------------------------------------------------\n", "# set up figure and animation\n", "fig = plt.figure()\n", "fig.subplots_adjust(left=0, right=1, bottom=0, top=1)\n", "ax = fig.add_subplot(111, aspect='equal', autoscale_on=False,\n", " xlim=(-3.2, 3.2), ylim=(-2.4, 2.4))\n", "\n", "# particles holds the locations of the particles\n", "particles, = ax.plot([], [], 'bo', ms=6)\n", "\n", "# rect is the box edge\n", "rect = plt.Rectangle(box.bounds[::2],\n", " box.bounds[1] - box.bounds[0],\n", " box.bounds[3] - box.bounds[2],\n", " ec='none', lw=2, fc='none')\n", "ax.add_patch(rect)\n", "\n", "def init():\n", " \"\"\"initialize animation\"\"\"\n", " global box, rect\n", " particles.set_data([], [])\n", " rect.set_edgecolor('none')\n", " return particles, rect\n", "\n", "def animate(i):\n", " \"\"\"perform animation step\"\"\"\n", " global box, rect, dt, ax, fig\n", " box.step(dt)\n", "\n", " ms = int(fig.dpi * 2 * box.size * fig.get_figwidth()\n", " / np.diff(ax.get_xbound())[0])\n", " \n", " # update pieces of the animation\n", " rect.set_edgecolor('k')\n", " particles.set_data(box.state[:, 0], box.state[:, 1])\n", " particles.set_markersize(ms)\n", " return particles, rect\n", "\n", "ani = animation.FuncAnimation(fig, animate, frames=600,\n", " interval=10, blit=True, init_func=init)\n", "\n", "\n", "# save the animation as an mp4. This requires ffmpeg or mencoder to be\n", "# installed. The extra_args ensure that the x264 codec is used, so that\n", "# the video can be embedded in html5. You may need to adjust this for\n", "# your system: for more information, see\n", "# http://matplotlib.sourceforge.net/api/animation_api.html\n", "#ani.save('particle_box.mp4', fps=30, extra_args=['-vcodec', 'libx264'])\n", "\n", "display_animation(ani)" ], "language": "python", "metadata": {}, "outputs": [ { "html": [ "\n", "\n", "\n", "
\n", " \n", "
\n", " \n", "
\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
\n", " Once \n", " Loop \n", " Reflect \n", "
\n", "
\n", "\n", "\n", "\n" ], "metadata": {}, "output_type": "pyout", "prompt_number": 5, "text": [ "" ] } ], "prompt_number": 5 }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Version Control" ] }, { "cell_type": "code", "collapsed": false, "input": [ "!git add \"Central Limit Theroem.ipynb\"" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 9 }, { "cell_type": "code", "collapsed": false, "input": [ "!git commit " ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "# On branch master\n", "# Untracked files:\n", "# (use \"git add ...\" to include in what will be committed)\n", "#\n", "#\t.ipynb_checkpoints/\n", "#\tMagicTriangle.ipynb\n", "#\tOlympicAthletes.csv\n", "#\tcentral_lim.js\n", "#\ttmp_output_fdsahkrkdkskrt.html\n", "nothing added to commit but untracked files present (use \"git add\" to track)\n" ] } ], "prompt_number": 10 }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] } ], "metadata": {} } ] }