{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"\n",
"# Monte Carlo Integration in 1 Dimension #\n",
"\n",
"### Modules - Numerical Integration\n",
"\n",
"By Tor Nordam\n",
"\n",
"___\n",
"This notebook will give a brief introduction to $D$-dimensional numerical integration, comparing two naïve methods:\n",
" * Riemann Sum\n",
" * Monte Carlo integration with uniform sampling\n",
" \n",
"## Riemann sum ##\n",
"The Riemann sum is perhaps the simplest and most intuitive numerical integration scheme. You want to integrate \n",
"a function on an interval of length $x$. Divide your interval into $N$ sub-intervals of equal length $\\Delta x = L/N$.\n",
"Evaluate the function in the middle of each sub-interval. The contribution to the total area from a sub-inteval \n",
"with midpoint $x_i$ is then $f(x_i) \\Delta x$, and the total value of the integral is\n",
"$$\n",
"\\Delta x\\sum_{i=1}^{N} f(x_i).\n",
"$$\n",
"The generalisation to $D$ dimensions is straightforward. Instead of having N equally spaced points along a line, you create an $D$-dimensional grid of points, with equal spacing, $\\Delta x$, in all dimensions. The contribution to the total integral from a volume with center $\\mathbf{x}_i$ is $f(\\mathbf{x}_i) \\cdot \\Delta x^D$.\n",
"\n",
"## Monte Carlo integration with uniform sampling ##\n",
"The simplest Monte Carlo integration scheme is essentially very similar to the Riemann sum method, except that the points where the function is to be evaluated are selected at random, instead of being equally spaced. Uniform sampling means that each point has the same probability of being selected. More advanced versions of Monte Carlo integration can for example use denser sampling in areas where the function value changes rapidly (*i.e.*, where the derivative of the function is large).\n",
"\n",
"For a large number of random points, the integral obtained by the Monte Carlo method will approach the true value of the integral.\n",
"\n",
"The generalisation to $D$ dimensions follows naturally in this case as well. Instead of selecting a random point along the line, we select a random point in $D$ dimensions, which amounts to generating $D$ random numbers in the right ranges and taking them as the coordinates of the point."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"# These lines import the numpy library, set up matplotlib\n",
"# to be used directly in the notebook and makes division work\n",
"# like it does in Python 3, so that 1/2 = 0.5 instead of 1/2 = 0\n",
"import numpy as np\n",
"%matplotlib inline\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We will need the gamma function for the analytical solution. See http://en.wikipedia.org/wiki/Gamma_function for details."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"from math import gamma"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The volume of the unit sphere in $D$ dimensions ##\n",
"\n",
"The problem we will use as an example is to determine the volume of the unit sphere, i.e., the sphere with radius 1, in $D$ dimensions. The answer is known analytically, and is\n",
"$$\n",
"V(r, D) = \\frac{\\pi^{D/2}}{\\Gamma(D/2+1)}r^{D},\n",
"$$\n",
"or, with $r=1$,\n",
"$$\n",
"V(r, D) = \\frac{\\pi^{D/2}}{\\Gamma(D/2+1)},\n",
"$$\n",
"(see http://en.wikipedia.org/wiki/Volume_of_an_n-ball for details)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"# This function returns 1 if a point is inside the unit sphere, 0 otherwise.\n",
"# The notation *X allows the function to take a variable number of arguments,\n",
"# which are available as a tuple inside the function. By converting the tuple\n",
"# to a numpy array, we can treat it as a D-dimensional vector, and find its \n",
"# length by taking the root of the sum of the squares.\n",
"def unitSphere(*X):\n",
" R = 1\n",
" r = 0\n",
" X = np.array(X)\n",
" r = np.sqrt(np.sum(X**2))\n",
" if r < R:\n",
" return 1\n",
" else:\n",
" return 0\n",
"\n",
"# This line performs some numpy magic on the function, allowing it to operate\n",
"# elementwise when called with an array as its argument. In this way, we can\n",
"# for example call this function with a rank 3 array, and have it interpreted\n",
"# as a rank 2 array of vectors.\n",
"unitSphere = np.vectorize(unitSphere)\n",
"\n",
"# This function returns the volume of the unit sphere (r=1) in d dimensions\n",
"def v(D):\n",
" return np.pi**(D/2.0) / gamma(1+D/2.0)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/pl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prZT8zs7DzHGBozO2Fml83sx2b2VTN705DtGma2\nY2bfN7PvznuceTfOZ87MPtP9/vNmdve8xxiSo95PM7vfzJrdz+P3zewTWYwzRlndZo8ToNL3cUmX\n3f0OSV/vPh7EJd3v7ne7+71zG10AxvnMmdkDkt7q7rdL+qikJ+c+0EBM8P/wN7ufx7vd/VNzHWTE\nMom7u1919x8fsdneCVDu/pqk3glQGOy9kp7qfv2UpPeP2JbJ68HG+cztvc/u/h1JbzKzk/MdZjDG\n/X+Yz+MM5PkG2YNOgLo1o7GE4KS7v9z9+mVJw4Ljkr5mZlfM7CPzGVowxvnMDdrmthmPK1TjvJ8u\n6R3dQ1zPmdmdcxtd5GZ2hionQKVvxHu67wwed/cR5w28091/bmaLki6b2VV3/3baYw3UuJ+5g3ua\nfFYHG+d9+Z6k0+7+azN7j6QvSrpjtsMqhpnF3d3flfBX/EzS6b7Hp9X5k7+wRr2nZvaymb3Z3X9h\nZm+R9N9DfsfPu/++bmb/qs5fnYl7xzifuYPb3NZ9Docd+X66+6/6vv6ymX3WzE64+ytzGmO08nBY\n5sgToMysrM4JUM/Ob1jBeVbSh7tff1idPaB9zOwNZvab3a/fKOnd6kxuo2Ocz9yzkv5U2jsD+5d9\nh8Ow35Hvp5mdtO7VB83sXnWWZxP2FGS1FJIToNL3d5LeZWY/lvQH3cf73lN1Dul828x+IOk7kv7d\n3b+ayWhzaNhnzsweMrOHuts8J+m/zOxFSZ+X9BeZDTjnxnk/JS1J+mH3M/m4pD/JZrTx4SQmAIhQ\nHg7LAABSRtwBIELEHQAiRNwBIELEHQAiRNwBIELEHQAiRNwBIEL/D8gCG2gbZ4GkAAAAAElFTkSu\nQmCC\n",
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# This piece of code plots the unit sphere in 2 dimensions.\n",
"# It is of course also possible to plot in 3 dimensions, but the \n",
"# matplotlib code gets a bit more involved.\n",
"X = np.arange(-1, 1, 0.01)\n",
"Y = np.arange(-1, 1, 0.01)\n",
"X, Y = np.meshgrid(X, Y)\n",
"plt.clf();\n",
"plt.figure(figsize = (6,6));\n",
"plt.contourf(X, Y, unitSphere(X, Y));"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Number of points ##\n",
"\n",
"With the Monte Carlo method, it's easy to use any number of points you like, but with the Riemann sum you are limited by the regular grid. For simplicity, let's stick to the same spacing in each direction. Say we want to integrate from -1 to 1 along the $x$ direction, and split this interval into $N_x$ subintervals. Doing the same along the other dimensions give a total of $N=N_x^D$ points. To keep things nice and comparable, we will use the same number of points with both methods, and write both functions so they take $N_x$ as an argument and figure out the total from that."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Riemann sum integrator ##"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"# This function takes as its arguments\n",
"# f - a function to be integrated\n",
"# Nx - number of points along each dimension of the regular grid\n",
"# D - number of dimensions\n",
"# start - start of integration interval (same for all dimensions)\n",
"# stop - end of integration interval (same for all dimensions)\n",
"def riemannSum(f, Nx, D, start, stop):\n",
" # Calculate the spacing\n",
" dx = (stop - start)/float(Nx)\n",
" # Calculate the coordinates of the gridpoints along one dimension\n",
" # The coordinates for the other dimensions will be the same\n",
" x = np.linspace(start+dx/2, stop-dx/2, Nx)\n",
" # Calculate the volume surrounding each grid point\n",
" vol = dx**D\n",
" # The one-dimensional case is handled specially, because np.meshgrid\n",
" # doesn't work with only one argument\n",
" if D == 1:\n",
" points = [x]\n",
" else:\n",
" # This bit may not be intuitively obvious, as there is quite a lot\n",
" # going on at once. See explanation in the Appendix. Essentially, \n",
" # this line assigns a rank 2 array with shape (D, N) to the variable\n",
" # points. Each of the N columns represents a D vector which holds the\n",
" # the coordinates of a point in the grid.\n",
" points = np.array(np.meshgrid(*[x]*D)).reshape(D, -1)\n",
" # Here, f is called on each point in the grid, and the sum times the volume\n",
" # of each cell is returned\n",
" return np.sum(f(*points))*vol\n"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"# This function takes as its arguments\n",
"# f - a function to be integrated\n",
"# Nx - number of points along each dimension of the regular grid\n",
"# D - number of dimensions\n",
"# start - start of integration interval (same for all dimensions)\n",
"# stop - end of integration interval (same for all dimensions)\n",
"def monteCarloIntegrator(f, Nx, D, start, stop):\n",
" # Calculate the total number of points\n",
" N = Nx**D\n",
" # Calculate the volume represented by each point as the total\n",
" # integration volume divided by the number of points. You can\n",
" # easily confirm that this is the same as the volume used in the\n",
" # Riemann sum function.\n",
" vol = (float(stop - start)**D) / N\n",
" # Generate a rank 2 array of shape(D, N) filled with uniformly distributed\n",
" # random numbers between start and stop. Each of the N columns represents a\n",
" # D vector which holds the coordinates of one of the random points.\n",
" points = np.random.random((D, N))*(stop - start) + start\n",
" # Here, f is called on each point in the grid, and the sum times the volume\n",
" # of each cell is returned\n",
" return np.sum(f(*points))*vol"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Application ##\n",
"\n",
"It's hard to have an intuitive feeling for things in many dimensions. We therefore select a maximum number of points that we want to use, and calculate the highest possible $N_x$ that fits."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Nx: 5\n",
"N: 390625\n",
"Analytic: 4.05871212642\n",
"Monte Carlo: 4.11959296\n",
"Riemann Sum: 4.4990464\n"
]
}
],
"source": [
"Nmax = 500000 # Upper limit on number of points\n",
"D = 8 # Number of dimensions\n",
"start = -1 # Start of integration interval (same for all dimensions)\n",
"stop = 1 # End of integration interval (same for all dimensions)\n",
"Nx = int(Nmax**(1.0/D)) # Calculate max number of points along each dimension\n",
"N = Nx**D # Calculate the total number of points used\n",
"print 'Nx: ', Nx\n",
"print 'N: ', N\n",
"print 'Analytic: ', v(D)\n",
"print 'Monte Carlo: ', monteCarloIntegrator(unitSphere, Nx, D, start, stop)\n",
"print 'Riemann Sum: ', riemannSum(unitSphere, Nx, D, start, stop)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Results ##\n",
"By experimenting a bit with different numbers, you should realise a couple of things\n",
" * If the number of dimensions is small, both these methods perform ok\n",
" * If the number of dimensions is large, the total number of points grows extremely fast with $N_x$\n",
" * If the number of dimensions is large (8 or 10, for example), the Monte Carlo method works better\n",
"\n",
"So why does the Monte Carlo method work better? In this particular case (integrating a function which only depends on $r$), I think it is due to the fact that with a regular grid, there will be a large number of points that have the same distance from the origin. Adjusting the resolution will thus move a lot of points inside or outside the unit sphere at the same time, causing the Riemann sum to over- or underestimate the answer in most cases. With the Monte Carlo method, the points will have a better distribution in terms of distance from the origin.\n",
"\n",
"Again, this example was chosen specifically to show that the Monte Carlo method can perform better than the Riemann sum, but the general point that Monte Carlo methods tend to perform better in higher dimensions hold."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Appendix ##"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"points = np.array(np.meshgrid(*[x]*D)).reshape(D, -1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What does this line of code actually do? Let's have a look at it piece by piece.\n",
"\n",
"``np.meshgrid`` takes $n$ arrays as arguments (where $n > 1$), and returns $n$ rank $n$ arrays, which only change along one direction.\n",
"It is easiest to grasp with an example. Say you have two vectors, $X$ and $Y$:"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"X = [0 1 2 3 4]\n",
"Y = [5 6 7 8 9]\n"
]
}
],
"source": [
"X = np.arange(0, 5)\n",
"Y = np.arange(5, 10)\n",
"print 'X = ', X\n",
"print 'Y = ', Y"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Then, say you want to create a grid of points, for example for plotting,\n",
"where the $x$ coordinates are given by $X$, and the $y$ coordinates by $Y$, \n",
"such that the first point would be $(0, 5)$, the second point $(1,5)$, ...\n",
"the sixth point $(0, 6)$, etc.\n",
"This is facilitated by ``np.meshgrid``:"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Xs = [[0 1 2 3 4]\n",
" [0 1 2 3 4]\n",
" [0 1 2 3 4]\n",
" [0 1 2 3 4]\n",
" [0 1 2 3 4]]\n",
"Ys = [[5 5 5 5 5]\n",
" [6 6 6 6 6]\n",
" [7 7 7 7 7]\n",
" [8 8 8 8 8]\n",
" [9 9 9 9 9]]\n"
]
}
],
"source": [
"Xs, Ys = np.meshgrid(X, Y)\n",
"print 'Xs = ', Xs\n",
"print 'Ys = ', Ys"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"When combining one element from the array $Xs$, with the corresponding\n",
"element from the array $Ys$, we get the coordinates of each point.\n",
"Although perhaps not immediately obvious, this generalises to more than\n",
"two dimensions as well. In our case, we create an array, $x$, of points in\n",
"the $x$-direction, which we want to use in all directions. In $D$ dimensions, \n",
"we can achieve this by calling meshgrid on $D$ copies of the array $x$.\n",
"In Python a list multiplied with a number $n$ is a list containing the elements\n",
"of the original list repeated $n$ times:"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3, 1, 2, 3, 1, 2, 3]\n"
]
}
],
"source": [
"print [1,2,3] * 3"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that this is very different from multiplying a numpy array by a number:"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[3 6 9]\n"
]
}
],
"source": [
"print np.array([1,2,3]) * 3"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Thus, the code ``[x]*D`` makes a list of $D$ elements, where each element is\n",
"the array $x$:"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[array([1, 2]), array([1, 2])]\n"
]
}
],
"source": [
"x = np.array([1,2])\n",
"print [x]*2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The code ``np.meshgrid(*[x]*D)`` uses the ``*`` to \"unpack\" the list created by ``[x]*D``\n",
"thus effectively calling the function meshgrid with $D$ arguments,\n",
"each of which is a copy of the array $x$\n",
"``np.meshgrid(*[x]*3)``\n",
"is exactly the same as \n",
"``np.meshgrid(x, x, x)``.\n",
"\n",
"Meshgrid returns a tuple of $D$ arrays. This can be turned into an array\n",
"of arrays, which is the same as an array of one higher rank. Again, an\n",
"example is probably easiest:"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"(array([1, 2]), array([1, 2]))\n",
"[[1 2]\n",
" [1 2]]\n"
]
}
],
"source": [
"# Creating a rank 1 array\n",
"a = np.array([1,2])\n",
"# Creating a tuple of two rank 1 arrays\n",
"b = (a, a)\n",
"print b\n",
"# Turning the tuple into a rank 2 array\n",
"print np.array(b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"So, finally, the line in question produces an array of rank $D+1$, which\n",
"is reshaped into a rank 2 array with shape $(D, N)$ where $D$ is the number of dimensions\n",
"and $N$ is the number of points, and where each column is a $D$-vector which gives \n",
"the coordinates of one point.\n",
"\n",
"For small numbers, it can be verified by inspection that each column does\n",
"indeed give the coordinates of a unique point:"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[0 0 0 1 1 1 2 2 2 0 0 0 1 1 1 2 2 2 0 0 0 1 1 1 2 2 2]\n",
" [0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2]\n",
" [0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2]]\n"
]
}
],
"source": [
"D = 3\n",
"x = np.array([0,1,2])\n",
"points = np.array(np.meshgrid(*[x]*D)).reshape(D, -1)\n",
"print points"
]
}
],
"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.5.4"
}
},
"nbformat": 4,
"nbformat_minor": 1
}