{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# B11. Introduction to Numpy and Scipy\n",
"\n",
"
"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import scipy.special"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"Here you will learn about [NumPy](http://www.numpy.org), arguably *the* most important package for scientific computing, and SciPy, a package containing lots of goodies for scientific computing, like special functions and numerical integrators. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## A very brief introduction to NumPy arrays\n",
"\n",
"The central object for NumPy and SciPy is the `ndarray`, commonly referred to as a \"NumPy array.\" This is an array object that is convenient for scientific computing. We will go over it in depth in the next lesson, but for now, let's just create some NumPy arrays and see how operators work on them.\n",
"\n",
"Just like with type conversions with lists, tuples, and other data types we've looked at, we can convert a list to a NumPy array using\n",
"\n",
" np.array()\n",
" \n",
"Note that above we imported the NumPy package with the `np` alias. This is for convenience; it allow us to use `np` as a prefix instead of `numpy`. NumPy is in *very* widespread use, and the convention is to use the `np` abbreviation."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([1, 2, 3, 4])"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Create a NumPy array from a list\n",
"my_ar = np.array([1, 2, 3, 4])\n",
"\n",
"# Look at it\n",
"my_ar"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We see that the list has been converted, and it is explicitly shown as an array. It has several attributes and lots of methods. The most important attributes are probably the data type of its elements and the shape of the array."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"dtype('int64')"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# The data type of stored entries\n",
"my_ar.dtype"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(4,)"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# The shape of the array\n",
"my_ar.shape"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There are also lots of methods. The one we use most often is `astype()`, which converts the data type of the array."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([1., 2., 3., 4.])"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"my_ar.astype(float)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There are many others. For example, we can compute summary statistics about the entries in the array, very similar to what we have see with Pandas."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4\n",
"1\n",
"10\n",
"2.5\n",
"1.118033988749895\n"
]
}
],
"source": [
"print(my_ar.max())\n",
"print(my_ar.min())\n",
"print(my_ar.sum())\n",
"print(my_ar.mean())\n",
"print(my_ar.std())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Importantly, NumPy arrays can be arguments to NumPy functions. In this case, these functions do the same operations as the methods we just looked at."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4\n",
"1\n",
"10\n",
"2.5\n",
"1.118033988749895\n"
]
}
],
"source": [
"print(np.max(my_ar))\n",
"print(np.min(my_ar))\n",
"print(np.sum(my_ar))\n",
"print(np.mean(my_ar))\n",
"print(np.std(my_ar))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Other ways to make NumPy arrays\n",
"\n",
"There are many other ways to make NumPy arrays besides just converting lists or tuples. Below are some examples."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# How long our arrays will be\n",
"n = 10\n",
"\n",
"# Make a NumPy array of length n filled with zeros\n",
"np.zeros(n)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Make a NumPy array of length n filled with ones\n",
"np.ones(n)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Make an empty NumPy array of length n without initializing entries\n",
"# (while it initially holds whatever values were previously in the memory\n",
"# locations assigned, ones will be displayed)\n",
"np.empty(n)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[0, 0],\n",
" [0, 0]])"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Make a NumPy array filled with zeros the same shape as another NumPy array\n",
"my_ar = np.array([[1, 2], [3, 4]])\n",
"np.zeros_like(my_ar)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As we work through the rest of this exercise, we will use more interesting arrays (not just zeroes, ones, and counting)."
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"x = np.array(\n",
" [1683, 2061, 1792, 1852, 2091, 1781, 1912, 1802, 1751, 1731, 1892,\n",
" 1951, 1809, 1683, 1787, 1840, 1821, 1910, 1930, 1800, 1833, 1683,\n",
" 1671, 1680, 1692, 1800, 1821, 1882, 1642, 1749, 1712, 1661, 1701,\n",
" 2141, 1863, 1752, 1740, 1721, 1660, 1930, 2030, 1851, 2131, 1828])\n",
"\n",
"y = np.array(\n",
" [1840, 2090, 2169, 1988, 2212, 2339, 1989, 2144, 2290, 1920, 2280,\n",
" 1809, 2158, 1800, 2133, 2060, 2160, 2001, 2030, 2088, 1951, 2460])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Slicing NumPy arrays\n",
"\n",
"We can slice NumPy arrays like lists and tuples. Here are a few examples."
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([1828, 2131, 1851, 2030, 1930, 1660, 1721, 1740, 1752, 1863, 2141,\n",
" 1701, 1661, 1712, 1749, 1642, 1882, 1821, 1800, 1692, 1680, 1671,\n",
" 1683, 1833, 1800, 1930, 1910, 1821, 1840, 1787, 1683, 1809, 1951,\n",
" 1892, 1731, 1751, 1802, 1912, 1781, 2091, 1852, 1792, 2061, 1683])"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Reversed array\n",
"x[::-1]"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([1852, 1751, 1683, 1930, 1680, 1642, 2141, 1660, 1828])"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Every 5th element, starting at index 3\n",
"x[3::5]"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([1892, 1951, 1809, 1683, 1787, 1840, 1821, 1910, 1930, 1800, 1833])"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Entries 10 to 20\n",
"x[10:21]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Fancy indexing\n",
"\n",
"NumPy arrays also allow **fancy indexing**, where we can slice out specific values. For example, say we wanted indices 1, 19, and 6 (in that order) from `x`. We just index with a list of the indices we want."
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([2061, 1800, 1912])"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x[[1, 19, 6]]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Instead of a list, we could also use a NumPy array."
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([2061, 1800, 1912])"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x[np.array([1, 19, 6])]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As a very nice feature, we can use **Boolean indexing** with Numpy arrays. Say we only want entries greater than 2000."
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([2061, 2091, 2141, 2030, 2131])"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Just slice out the big ones\n",
"x[x > 2000]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we want to know the indices where the values are high, we can use the `np.where()` function."
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(array([ 1, 4, 33, 40, 42]),)"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.where(x > 2000)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## NumPy arrays are mutable\n",
"\n",
"Yes, NumPy arrays are mutable. Let's look at some consequences."
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([1, 2, 6, 4])"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Make an array\n",
"my_ar = np.array([1, 2, 3, 4])\n",
"\n",
"# Change an element\n",
"my_ar[2] = 6\n",
"\n",
"# See the result\n",
"my_ar"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, let's try attaching another variable to the NumPy array."
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([1, 2, 6, 9])"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Attach a new variable\n",
"my_ar2 = my_ar\n",
"\n",
"# Set an entry using the new variable\n",
"my_ar2[3] = 9\n",
"\n",
"# Does the original change? (yes.)\n",
"my_ar"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's see how messing with NumPy in functions affects things."
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([0.1, 0.2, 0.3, 0.4])"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Re-instantiate my_ar\n",
"my_ar = np.array([1, 2, 3, 4]).astype(float)\n",
"\n",
"# Function to normalize x (note that /= works with mutable objects)\n",
"def normalize(x):\n",
" x /= np.sum(x)\n",
"\n",
"# Pass it through a function\n",
"normalize(my_ar)\n",
"\n",
"# Is it normalized even though we didn't return anything? (Yes.)\n",
"my_ar"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"So, be careful when writing functions. What you do to your NumPy array inside the function will happen outside of the function as well. Always remember that:\n",
"\n",
"
\n",
" \n",
"NumPy arrays are mutable.\n",
" \n",
"
\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Slices of NumPy arrays are **views**, not copies\n",
"\n",
"A very important distinction between NumPy arrays and lists is that slices of NumPy arrays are **views** into the original NumPy array, NOT copies. To illustrate this, we will again use out 1, 2, 3, 4 array for simplicity and clarity."
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3, 4]\n",
"[1 9 3 4]\n"
]
}
],
"source": [
"# Make list and array\n",
"my_list = [1, 2, 3, 4]\n",
"my_ar = np.array(my_list)\n",
"\n",
"# Slice out of each\n",
"my_list_slice = my_list[1:-1]\n",
"my_ar_slice = my_ar[1:-1]\n",
"\n",
"# Mess with the slices\n",
"my_list_slice[0] = 9\n",
"my_ar_slice[0] = 9\n",
"\n",
"# Look at originals\n",
"print(my_list)\n",
"print(my_ar)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Messing with an element of a slice of a NumPy array messes with that element in the original! This is not the case with lists. Let's issue a warning.\n",
"\n",
"
\n",
" \n",
"Slices of NumPy arrays are views, not copies.\n",
" \n",
"
\n",
"\n",
"Fortunately, you can make a copy of an array using the `np.copy()` function."
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Make a copy\n",
"x_copy = np.copy(x)\n",
"\n",
"# Mess with an entry\n",
"x_copy[10] = 2000\n",
"\n",
"# Check equality\n",
"np.allclose(x, x_copy)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"So, messing with an entry in the copy did not affect the original."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Mathematical operations with arrays\n",
"\n",
"Mathematical operations on arrays are done elementwise to all elements."
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([5. , 3. , 2.33333333, 2. ])"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Divide one array be another\n",
"np.array([5, 6, 7, 8]) / np.array([1, 2, 3, 4])"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([-6732, -8244, -7168, -7408, -8364, -7124, -7648, -7208, -7004,\n",
" -6924, -7568, -7804, -7236, -6732, -7148, -7360, -7284, -7640,\n",
" -7720, -7200, -7332, -6732, -6684, -6720, -6768, -7200, -7284,\n",
" -7528, -6568, -6996, -6848, -6644, -6804, -8564, -7452, -7008,\n",
" -6960, -6884, -6640, -7720, -8120, -7404, -8524, -7312])"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Multiply by scalar\n",
"-4 * x"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([2832489, 4247721, 3211264, 3429904, 4372281, 3171961, 3655744,\n",
" 3247204, 3066001, 2996361, 3579664, 3806401, 3272481, 2832489,\n",
" 3193369, 3385600, 3316041, 3648100, 3724900, 3240000, 3359889,\n",
" 2832489, 2792241, 2822400, 2862864, 3240000, 3316041, 3541924,\n",
" 2696164, 3059001, 2930944, 2758921, 2893401, 4583881, 3470769,\n",
" 3069504, 3027600, 2961841, 2755600, 3724900, 4120900, 3426201,\n",
" 4541161, 3341584])"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Raise to power\n",
"x**2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Indexing 2D NumPy arrays\n",
"\n",
"NumPy arrays need not be one-dimensional. We'll create a two-dimensional NumPy array by reshaping our `x` array from having shape `(44,)` to having shape `(11, 4)`. That is, it will become an array with 11 rows and 4 columns. (The 2D nature of this array has no meaning in this case; it's just meant for demonstration.)"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[1683, 2061, 1792, 1852],\n",
" [2091, 1781, 1912, 1802],\n",
" [1751, 1731, 1892, 1951],\n",
" [1809, 1683, 1787, 1840],\n",
" [1821, 1910, 1930, 1800],\n",
" [1833, 1683, 1671, 1680],\n",
" [1692, 1800, 1821, 1882],\n",
" [1642, 1749, 1712, 1661],\n",
" [1701, 2141, 1863, 1752],\n",
" [1740, 1721, 1660, 1930],\n",
" [2030, 1851, 2131, 1828]])"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# New 2D array using the reshape() method\n",
"my_ar = x.reshape((11, 4))\n",
"\n",
"# Look at it\n",
"my_ar"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notice that it is represented as an array made out of a list of lists. If we had a list of lists, we would index it like this:\n",
"\n",
" list_of_lists[i][j]"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Make list of lists\n",
"list_of_lists = [[1, 2], [3, 4]]\n",
"\n",
"# Pull out value in first row, second column\n",
"list_of_lists[0][1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Though this will work with NumPy arrays, this is *not* how NumPy arrays are indexed. They are indexed much more conveniently."
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2061"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"my_ar[0, 1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We essentially have a tuple in the indexing brackets. Now, say we wanted the second row (indexing starting at 0)."
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([1751, 1731, 1892, 1951])"
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"my_ar[2, :]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can use Boolean indexing as before."
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([2061, 2091, 2141, 2030, 2131])"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"my_ar[my_ar > 2000]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that this gives a one-dimensional array of the entries greater than 2000. If we wanted indices where this is the case, we can again use `np.where()`."
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(array([ 0, 1, 8, 10, 10]), array([1, 0, 1, 0, 2]))"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.where(my_ar > 2000)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This tuple of NumPy arrays is how we would index using fancy indexing to pull those values out using fancy indexing."
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([2061, 2091, 2141, 2030, 2131])"
]
},
"execution_count": 34,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"my_ar[(np.array([ 0, 1, 8, 10, 10]), np.array([1, 0, 1, 0, 2]))]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"NumPy arrays can be of arbitrary integer dimension, and these principles extrapolate to 3D, 4D, etc., arrays."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Concatenating arrays\n",
"\n",
"Let's say we want to study all cross sectional areas and don't care if the mother was well-fed or not. We would want to concatenate our arrays. The `np.concatenate()` function accomplishes this. We simply have to pass it a tuple containing the NumPy arrays we want to concatenate."
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([1683, 2061, 1792, 1852, 2091, 1781, 1912, 1802, 1751, 1731, 1892,\n",
" 1951, 1809, 1683, 1787, 1840, 1821, 1910, 1930, 1800, 1833, 1683,\n",
" 1671, 1680, 1692, 1800, 1821, 1882, 1642, 1749, 1712, 1661, 1701,\n",
" 2141, 1863, 1752, 1740, 1721, 1660, 1930, 2030, 1851, 2131, 1828,\n",
" 1840, 2090, 2169, 1988, 2212, 2339, 1989, 2144, 2290, 1920, 2280,\n",
" 1809, 2158, 1800, 2133, 2060, 2160, 2001, 2030, 2088, 1951, 2460])"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"combined = np.concatenate((x, y))\n",
"\n",
"# Look at it\n",
"combined"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## NumPy has useful mathematical functions\n",
"\n",
"So far, we have not done much mathematics with Python. We have done some adding and division, but nothing like computing a logarithm or cosine. The NumPy functions also work elementwise on the arrays when it is intuitive to do so. That is, they apply the function to each entry in the array. Check it out."
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([5.38167681, 7.8538197 , 6.00144336, 6.37255189, 8.09300412,\n",
" 5.93578924, 6.76660849, 6.06175887, 5.76036016, 5.64629738,\n",
" 6.63262067, 7.03571978, 6.10434004, 5.38167681, 5.97151103,\n",
" 6.29653826, 6.1780334 , 6.7530888 , 6.88951024, 6.04964746,\n",
" 6.2526164 , 5.38167681, 5.31748262, 5.36555597, 5.43033051,\n",
" 6.04964746, 6.1780334 , 6.56662499, 5.16549017, 5.74885095,\n",
" 5.54003047, 5.26457279, 5.47942408, 8.50794132, 6.44303692,\n",
" 5.7661234 , 5.69734342, 5.59011579, 5.25931084, 6.88951024,\n",
" 7.61408636, 6.36618252, 8.42328589, 6.22143134])"
]
},
"execution_count": 36,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Exponential\n",
"np.exp(x / 1000)"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 0.62656192, 0.9933696 , 0.27501843, 0.03112568, 0.26681725,\n",
" -0.96021239, -0.33430744, 0.29228295, -0.42404251, -0.99984597,\n",
" 0.72399324, -0.99748325, 0.84865001, 0.62656192, -0.84393482,\n",
" 0.56257847, 0.43231386, 0.99610114, 0.48702972, -0.99122275,\n",
" -0.11903049, 0.62656192, 0.94691648, -0.73027654, -0.24968607,\n",
" -0.99122275, 0.43231386, -0.98275172, -0.49500319, -0.64703425,\n",
" -0.98592179, -0.61963892, -0.17156886, 0.00460656, -0.99936794,\n",
" 0.53296056, 0.90375673, 0.82939405, 0.3256673 , 0.48702972,\n",
" 0.86222727, -0.824246 , 0.5401501 , 0.91834245])"
]
},
"execution_count": 37,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Cosine\n",
"np.cos(x)"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([41.02438299, 45.39823785, 42.33202098, 43.03486958, 45.72745346,\n",
" 42.20189569, 43.72642222, 42.44997055, 41.84495191, 41.60528813,\n",
" 43.49712634, 44.17012565, 42.53234064, 41.02438299, 42.27292278,\n",
" 42.89522118, 42.67317659, 43.70354677, 43.93176527, 42.42640687,\n",
" 42.81354926, 41.02438299, 40.87786687, 40.98780306, 41.1339276 ,\n",
" 42.42640687, 42.67317659, 43.38202393, 40.52159918, 41.82104733,\n",
" 41.37632173, 40.75536774, 41.24318125, 46.27094121, 43.16248371,\n",
" 41.85689907, 41.71330723, 41.48493703, 40.74309757, 43.93176527,\n",
" 45.0555213 , 43.02324953, 46.16275555, 42.75511665])"
]
},
"execution_count": 38,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Square root\n",
"np.sqrt(x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can even do some matrix operations (which are obviously not done elementwise), like dot products."
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"146360195"
]
},
"execution_count": 39,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.dot(x, x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"NumPy also has useful attributes, like `np.pi`."
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3.141592653589793"
]
},
"execution_count": 40,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.pi"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## SciPy has even more useful functions (in modules)\n",
"\n",
"SciPy actually began life as a library of special functions that operate on NumPy arrays. For example, we can compute an error function using the `scipy.special` module, which contains lots of special functions. Note that you often have to individually import the SciPy module you want to use, for example with\n",
" \n",
"```python\n",
"import scipy.special\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([0.76597747, 0.8549794 , 0.7948931 , 0.80965587, 0.86074212,\n",
" 0.79209865, 0.8236209 , 0.79740973, 0.78433732, 0.77904847,\n",
" 0.81905337, 0.83227948, 0.79915793, 0.76597747, 0.7936263 ,\n",
" 0.80676772, 0.8021292 , 0.82316805, 0.8276577 , 0.79690821,\n",
" 0.80506817, 0.76597747, 0.76262579, 0.76514271, 0.76846912,\n",
" 0.79690821, 0.8021292 , 0.81673693, 0.7543863 , 0.78381257,\n",
" 0.77393853, 0.75980693, 0.77094188, 0.86995276, 0.81227529,\n",
" 0.78459935, 0.78143985, 0.77636944, 0.75952376, 0.8276577 ,\n",
" 0.84883448, 0.80941641, 0.86814949, 0.80384751])"
]
},
"execution_count": 41,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"scipy.special.erf(x / 2000)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There are many SciPy submodules which give plenty or rich functionality for scientific computing. You can check out the [SciPy docs](https://docs.scipy.org/doc/scipy/reference/) to learn about all of the functionality. Particularly useful modules that have come up in our work in systems biology include:\n",
"\n",
"- `scipy.special`: Special functions.\n",
"- `scipy.stats`: Functions for statistical analysis.\n",
"- `scipy.optimize`: Numerical optimization.\n",
"- `scipy.integrate`: Numerical solutions to differential equations.\n",
"- `scipy.interpolate`: Smooth interpolation of functions."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## NumPy and SciPy are highly optimized\n",
"\n",
"Importantly, NumPy and SciPy routines are often *fast*. To understand why, we need to think a bit about how your computer actually runs code you write."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Interpreted and compiled languages\n",
"\n",
"We have touched on the fact that Python is an **interpreted language**. This means that the Python interpreter reads through your code, line by line, translates the commands into instructions that your computer's processor can execute, and then these are executed. It also does [**garbage collection**](https://en.wikipedia.org/wiki/Garbage_collection_(computer_science)), which manages memory usage in your programs for you. As an interpreted language, code is often much easier to write, and development time is much shorter. It is often easier to debug. By contrast, with **compiled languages** (the dominant ones being Fortran, C, and C++), your entire source code is translated into machine code before you ever run it. When you execute your program, it is already in machine code. As a result, compiled code is often much faster than interpreted code. The speed difference depends largely on the task at hand, but there is often over a 100-fold difference.\n",
"\n",
"First, we'll demonstrate the difference between compiled and interpreted languages by looking at a function to sum the elements of an array. Note that Python is [dynamically typed](http://stackoverflow.com/a/34004445/2320823), so the function below works for multiple data types, but the C function works only for [double precision floating point](https://en.wikipedia.org/wiki/Double-precision_floating-point_format) numbers."
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[19793 20111 20171 19978]\n"
]
}
],
"source": [
"# Python code to sum an array and print the result to the screen\n",
"print(sum(my_ar))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"```C\n",
"/* C code to sum an array and print the result to the screen */\n",
"\n",
"#include \n",
"\n",
"void sum_array(double a[], int n);\n",
"\n",
"void sum_array(double a[], int n) {\n",
" int i; \n",
" double sum=0;\n",
" for (i = 0; i < n; i++){\n",
" sum += a[i];\n",
" }\n",
" printf(\"%g\\n\", sum);\n",
"}\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The C code won't even execute without another function called `main` to call it. You should notice the difference in complexity of the code. Interpreted code is very often much easier to write!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### NumPy and SciPy use compiled code!\n",
"\n",
"Under the hood, when you call a NumPy or SciPy function, or use one of the methods, the Python interpreter passes the arrays into pre-compiled functions. (They are usually C or Fortran functions.) That means that you get to use an interpreted language with near-compiled speed! We can demonstrate the speed by comparing an explicit sum of elements of an array using a Python `for` loop versus NumPy. We will use the `np.random` module to generate a large array of random numbers (we will visit random number generation in a coming section). We then use the `%timeit` magic function of IPython to time the execution of the sum of the elements of the array."
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"877 µs ± 9.01 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n"
]
}
],
"source": [
"# Make array of 10,000 random numbers\n",
"rng = np.random.default_rng()\n",
"x = rng.random(10000)\n",
"\n",
"# Sum with Python for loop\n",
"def python_sum(x):\n",
" x_sum = 0.0\n",
" for y in x:\n",
" x_sum += y\n",
" return x_sum\n",
"\n",
"# Test speed\n",
"%timeit python_sum(x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we'll do the same test with the NumPy implementation."
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"7.84 µs ± 99.1 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)\n"
]
}
],
"source": [
"%timeit np.sum(x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Wow! We went from a millisecond to *micro*seconds!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Word of advice: use NumPy and SciPy\n",
"\n",
"If you are writing code and you think to yourself, \"This seems like a pretty common things to do,\" there is a good chance the someone really smart has written code to do it. If it's something numerical, there is a good chance it is in NumPy or SciPy. **Use these packages.** Do not reinvent the wheel. It is very rare you can beat them for performance, error checking, etc.\n",
"\n",
"Furthermore, NumPy and SciPy are very well tested. In general, you do not need to write unit tests for well-established packages. Obviously, if you use NumPy or SciPy within your own functions, you still need to test what you wrote."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Computing environment"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {
"tags": [
"hide-input"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Python implementation: CPython\n",
"Python version : 3.10.9\n",
"IPython version : 8.10.0\n",
"\n",
"numpy : 1.23.5\n",
"scipy : 1.10.0\n",
"jupyterlab: 3.5.3\n",
"\n"
]
}
],
"source": [
"%load_ext watermark\n",
"%watermark -v -p numpy,scipy,jupyterlab"
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"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.9.16"
}
},
"nbformat": 4,
"nbformat_minor": 4
}