B11. Introduction to Numpy and Scipy
[1]:
import numpy as np
import scipy.special
Here you will learn about NumPy, 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.
A very brief introduction to NumPy arrays
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.
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
np.array()
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.
[2]:
# Create a NumPy array from a list
my_ar = np.array([1, 2, 3, 4])
# Look at it
my_ar
[2]:
array([1, 2, 3, 4])
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.
[3]:
# The data type of stored entries
my_ar.dtype
[3]:
dtype('int64')
[4]:
# The shape of the array
my_ar.shape
[4]:
(4,)
There are also lots of methods. The one we use most often is astype()
, which converts the data type of the array.
[5]:
my_ar.astype(float)
[5]:
array([1., 2., 3., 4.])
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.
[6]:
print(my_ar.max())
print(my_ar.min())
print(my_ar.sum())
print(my_ar.mean())
print(my_ar.std())
4
1
10
2.5
1.118033988749895
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.
[7]:
print(np.max(my_ar))
print(np.min(my_ar))
print(np.sum(my_ar))
print(np.mean(my_ar))
print(np.std(my_ar))
4
1
10
2.5
1.118033988749895
Other ways to make NumPy arrays
There are many other ways to make NumPy arrays besides just converting lists or tuples. Below are some examples.
[8]:
# How long our arrays will be
n = 10
# Make a NumPy array of length n filled with zeros
np.zeros(n)
[8]:
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
[9]:
# Make a NumPy array of length n filled with ones
np.ones(n)
[9]:
array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
[10]:
# Make an empty NumPy array of length n without initializing entries
# (while it initially holds whatever values were previously in the memory
# locations assigned, ones will be displayed)
np.empty(n)
[10]:
array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
[11]:
# Make a NumPy array filled with zeros the same shape as another NumPy array
my_ar = np.array([[1, 2], [3, 4]])
np.zeros_like(my_ar)
[11]:
array([[0, 0],
[0, 0]])
As we work through the rest of this exercise, we will use more interesting arrays (not just zeroes, ones, and counting).
[12]:
x = np.array(
[1683, 2061, 1792, 1852, 2091, 1781, 1912, 1802, 1751, 1731, 1892,
1951, 1809, 1683, 1787, 1840, 1821, 1910, 1930, 1800, 1833, 1683,
1671, 1680, 1692, 1800, 1821, 1882, 1642, 1749, 1712, 1661, 1701,
2141, 1863, 1752, 1740, 1721, 1660, 1930, 2030, 1851, 2131, 1828])
y = np.array(
[1840, 2090, 2169, 1988, 2212, 2339, 1989, 2144, 2290, 1920, 2280,
1809, 2158, 1800, 2133, 2060, 2160, 2001, 2030, 2088, 1951, 2460])
Slicing NumPy arrays
We can slice NumPy arrays like lists and tuples. Here are a few examples.
[13]:
# Reversed array
x[::-1]
[13]:
array([1828, 2131, 1851, 2030, 1930, 1660, 1721, 1740, 1752, 1863, 2141,
1701, 1661, 1712, 1749, 1642, 1882, 1821, 1800, 1692, 1680, 1671,
1683, 1833, 1800, 1930, 1910, 1821, 1840, 1787, 1683, 1809, 1951,
1892, 1731, 1751, 1802, 1912, 1781, 2091, 1852, 1792, 2061, 1683])
[14]:
# Every 5th element, starting at index 3
x[3::5]
[14]:
array([1852, 1751, 1683, 1930, 1680, 1642, 2141, 1660, 1828])
[15]:
# Entries 10 to 20
x[10:21]
[15]:
array([1892, 1951, 1809, 1683, 1787, 1840, 1821, 1910, 1930, 1800, 1833])
Fancy indexing
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.
[16]:
x[[1, 19, 6]]
[16]:
array([2061, 1800, 1912])
Instead of a list, we could also use a NumPy array.
[17]:
x[np.array([1, 19, 6])]
[17]:
array([2061, 1800, 1912])
As a very nice feature, we can use Boolean indexing with Numpy arrays. Say we only want entries greater than 2000.
[18]:
# Just slice out the big ones
x[x > 2000]
[18]:
array([2061, 2091, 2141, 2030, 2131])
If we want to know the indices where the values are high, we can use the np.where()
function.
[19]:
np.where(x > 2000)
[19]:
(array([ 1, 4, 33, 40, 42]),)
NumPy arrays are mutable
Yes, NumPy arrays are mutable. Let’s look at some consequences.
[20]:
# Make an array
my_ar = np.array([1, 2, 3, 4])
# Change an element
my_ar[2] = 6
# See the result
my_ar
[20]:
array([1, 2, 6, 4])
Now, let’s try attaching another variable to the NumPy array.
[21]:
# Attach a new variable
my_ar2 = my_ar
# Set an entry using the new variable
my_ar2[3] = 9
# Does the original change? (yes.)
my_ar
[21]:
array([1, 2, 6, 9])
Let’s see how messing with NumPy in functions affects things.
[22]:
# Re-instantiate my_ar
my_ar = np.array([1, 2, 3, 4]).astype(float)
# Function to normalize x (note that /= works with mutable objects)
def normalize(x):
x /= np.sum(x)
# Pass it through a function
normalize(my_ar)
# Is it normalized even though we didn't return anything? (Yes.)
my_ar
[22]:
array([0.1, 0.2, 0.3, 0.4])
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:
NumPy arrays are mutable.
Slices of NumPy arrays are views, not copies
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.
[23]:
# Make list and array
my_list = [1, 2, 3, 4]
my_ar = np.array(my_list)
# Slice out of each
my_list_slice = my_list[1:-1]
my_ar_slice = my_ar[1:-1]
# Mess with the slices
my_list_slice[0] = 9
my_ar_slice[0] = 9
# Look at originals
print(my_list)
print(my_ar)
[1, 2, 3, 4]
[1 9 3 4]
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.
Slices of NumPy arrays are views, not copies.
Fortunately, you can make a copy of an array using the np.copy()
function.
[24]:
# Make a copy
x_copy = np.copy(x)
# Mess with an entry
x_copy[10] = 2000
# Check equality
np.allclose(x, x_copy)
[24]:
False
So, messing with an entry in the copy did not affect the original.
Mathematical operations with arrays
Mathematical operations on arrays are done elementwise to all elements.
[25]:
# Divide one array be another
np.array([5, 6, 7, 8]) / np.array([1, 2, 3, 4])
[25]:
array([5. , 3. , 2.33333333, 2. ])
[26]:
# Multiply by scalar
-4 * x
[26]:
array([-6732, -8244, -7168, -7408, -8364, -7124, -7648, -7208, -7004,
-6924, -7568, -7804, -7236, -6732, -7148, -7360, -7284, -7640,
-7720, -7200, -7332, -6732, -6684, -6720, -6768, -7200, -7284,
-7528, -6568, -6996, -6848, -6644, -6804, -8564, -7452, -7008,
-6960, -6884, -6640, -7720, -8120, -7404, -8524, -7312])
[27]:
# Raise to power
x**2
[27]:
array([2832489, 4247721, 3211264, 3429904, 4372281, 3171961, 3655744,
3247204, 3066001, 2996361, 3579664, 3806401, 3272481, 2832489,
3193369, 3385600, 3316041, 3648100, 3724900, 3240000, 3359889,
2832489, 2792241, 2822400, 2862864, 3240000, 3316041, 3541924,
2696164, 3059001, 2930944, 2758921, 2893401, 4583881, 3470769,
3069504, 3027600, 2961841, 2755600, 3724900, 4120900, 3426201,
4541161, 3341584])
Indexing 2D NumPy arrays
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.)
[28]:
# New 2D array using the reshape() method
my_ar = x.reshape((11, 4))
# Look at it
my_ar
[28]:
array([[1683, 2061, 1792, 1852],
[2091, 1781, 1912, 1802],
[1751, 1731, 1892, 1951],
[1809, 1683, 1787, 1840],
[1821, 1910, 1930, 1800],
[1833, 1683, 1671, 1680],
[1692, 1800, 1821, 1882],
[1642, 1749, 1712, 1661],
[1701, 2141, 1863, 1752],
[1740, 1721, 1660, 1930],
[2030, 1851, 2131, 1828]])
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:
list_of_lists[i][j]
[29]:
# Make list of lists
list_of_lists = [[1, 2], [3, 4]]
# Pull out value in first row, second column
list_of_lists[0][1]
[29]:
2
Though this will work with NumPy arrays, this is not how NumPy arrays are indexed. They are indexed much more conveniently.
[30]:
my_ar[0, 1]
[30]:
2061
We essentially have a tuple in the indexing brackets. Now, say we wanted the second row (indexing starting at 0).
[31]:
my_ar[2, :]
[31]:
array([1751, 1731, 1892, 1951])
We can use Boolean indexing as before.
[32]:
my_ar[my_ar > 2000]
[32]:
array([2061, 2091, 2141, 2030, 2131])
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()
.
[33]:
np.where(my_ar > 2000)
[33]:
(array([ 0, 1, 8, 10, 10]), array([1, 0, 1, 0, 2]))
This tuple of NumPy arrays is how we would index using fancy indexing to pull those values out using fancy indexing.
[34]:
my_ar[(np.array([ 0, 1, 8, 10, 10]), np.array([1, 0, 1, 0, 2]))]
[34]:
array([2061, 2091, 2141, 2030, 2131])
NumPy arrays can be of arbitrary integer dimension, and these principles extrapolate to 3D, 4D, etc., arrays.
Concatenating arrays
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.
[35]:
combined = np.concatenate((x, y))
# Look at it
combined
[35]:
array([1683, 2061, 1792, 1852, 2091, 1781, 1912, 1802, 1751, 1731, 1892,
1951, 1809, 1683, 1787, 1840, 1821, 1910, 1930, 1800, 1833, 1683,
1671, 1680, 1692, 1800, 1821, 1882, 1642, 1749, 1712, 1661, 1701,
2141, 1863, 1752, 1740, 1721, 1660, 1930, 2030, 1851, 2131, 1828,
1840, 2090, 2169, 1988, 2212, 2339, 1989, 2144, 2290, 1920, 2280,
1809, 2158, 1800, 2133, 2060, 2160, 2001, 2030, 2088, 1951, 2460])
NumPy has useful mathematical functions
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.
[36]:
# Exponential
np.exp(x / 1000)
[36]:
array([5.38167681, 7.8538197 , 6.00144336, 6.37255189, 8.09300412,
5.93578924, 6.76660849, 6.06175887, 5.76036016, 5.64629738,
6.63262067, 7.03571978, 6.10434004, 5.38167681, 5.97151103,
6.29653826, 6.1780334 , 6.7530888 , 6.88951024, 6.04964746,
6.2526164 , 5.38167681, 5.31748262, 5.36555597, 5.43033051,
6.04964746, 6.1780334 , 6.56662499, 5.16549017, 5.74885095,
5.54003047, 5.26457279, 5.47942408, 8.50794132, 6.44303692,
5.7661234 , 5.69734342, 5.59011579, 5.25931084, 6.88951024,
7.61408636, 6.36618252, 8.42328589, 6.22143134])
[37]:
# Cosine
np.cos(x)
[37]:
array([ 0.62656192, 0.9933696 , 0.27501843, 0.03112568, 0.26681725,
-0.96021239, -0.33430744, 0.29228295, -0.42404251, -0.99984597,
0.72399324, -0.99748325, 0.84865001, 0.62656192, -0.84393482,
0.56257847, 0.43231386, 0.99610114, 0.48702972, -0.99122275,
-0.11903049, 0.62656192, 0.94691648, -0.73027654, -0.24968607,
-0.99122275, 0.43231386, -0.98275172, -0.49500319, -0.64703425,
-0.98592179, -0.61963892, -0.17156886, 0.00460656, -0.99936794,
0.53296056, 0.90375673, 0.82939405, 0.3256673 , 0.48702972,
0.86222727, -0.824246 , 0.5401501 , 0.91834245])
[38]:
# Square root
np.sqrt(x)
[38]:
array([41.02438299, 45.39823785, 42.33202098, 43.03486958, 45.72745346,
42.20189569, 43.72642222, 42.44997055, 41.84495191, 41.60528813,
43.49712634, 44.17012565, 42.53234064, 41.02438299, 42.27292278,
42.89522118, 42.67317659, 43.70354677, 43.93176527, 42.42640687,
42.81354926, 41.02438299, 40.87786687, 40.98780306, 41.1339276 ,
42.42640687, 42.67317659, 43.38202393, 40.52159918, 41.82104733,
41.37632173, 40.75536774, 41.24318125, 46.27094121, 43.16248371,
41.85689907, 41.71330723, 41.48493703, 40.74309757, 43.93176527,
45.0555213 , 43.02324953, 46.16275555, 42.75511665])
We can even do some matrix operations (which are obviously not done elementwise), like dot products.
[39]:
np.dot(x, x)
[39]:
146360195
NumPy also has useful attributes, like np.pi
.
[40]:
np.pi
[40]:
3.141592653589793
SciPy has even more useful functions (in modules)
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
import scipy.special
[41]:
scipy.special.erf(x / 2000)
[41]:
array([0.76597747, 0.8549794 , 0.7948931 , 0.80965587, 0.86074212,
0.79209865, 0.8236209 , 0.79740973, 0.78433732, 0.77904847,
0.81905337, 0.83227948, 0.79915793, 0.76597747, 0.7936263 ,
0.80676772, 0.8021292 , 0.82316805, 0.8276577 , 0.79690821,
0.80506817, 0.76597747, 0.76262579, 0.76514271, 0.76846912,
0.79690821, 0.8021292 , 0.81673693, 0.7543863 , 0.78381257,
0.77393853, 0.75980693, 0.77094188, 0.86995276, 0.81227529,
0.78459935, 0.78143985, 0.77636944, 0.75952376, 0.8276577 ,
0.84883448, 0.80941641, 0.86814949, 0.80384751])
There are many SciPy submodules which give plenty or rich functionality for scientific computing. You can check out the SciPy docs to learn about all of the functionality. Particularly useful modules that have come up in our work in systems biology include:
scipy.special
: Special functions.scipy.stats
: Functions for statistical analysis.scipy.optimize
: Numerical optimization.scipy.integrate
: Numerical solutions to differential equations.scipy.interpolate
: Smooth interpolation of functions.
NumPy and SciPy are highly optimized
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.
Interpreted and compiled languages
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, 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.
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, so the function below works for multiple data types, but the C function works only for double precision floating point numbers.
[42]:
# Python code to sum an array and print the result to the screen
print(sum(my_ar))
[19793 20111 20171 19978]
/* C code to sum an array and print the result to the screen */
#include <stdio.h>
void sum_array(double a[], int n);
void sum_array(double a[], int n) {
int i;
double sum=0;
for (i = 0; i < n; i++){
sum += a[i];
}
printf("%g\n", sum);
}
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!
NumPy and SciPy use compiled code!
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.
[43]:
# Make array of 10,000 random numbers
rng = np.random.default_rng()
x = rng.random(10000)
# Sum with Python for loop
def python_sum(x):
x_sum = 0.0
for y in x:
x_sum += y
return x_sum
# Test speed
%timeit python_sum(x)
877 µs ± 9.01 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
Now we’ll do the same test with the NumPy implementation.
[44]:
%timeit np.sum(x)
7.84 µs ± 99.1 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
Wow! We went from a millisecond to microseconds!
Word of advice: use NumPy and SciPy
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.
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.
Computing environment
[45]:
%load_ext watermark
%watermark -v -p numpy,scipy,jupyterlab
Python implementation: CPython
Python version : 3.10.9
IPython version : 8.10.0
numpy : 1.23.5
scipy : 1.10.0
jupyterlab: 3.5.3