(c) 2019 Justin Bois. With the exception of pasted graphics, where the source is noted, this work is licensed under a Creative Commons Attribution License CC-BY 4.0. All code contained herein is licensed under an MIT license.

This document was prepared at Caltech with financial support from the Donna and Benjamin M. Rosen Bioengineering Center.

*This tutorial was generated from a Jupyter notebook. You can download the notebook here.*

In [1]:

```
import numpy as np
import pandas as pd
# We'll demo a bit of Scipy
import scipy.special
import bokeh_catplot
import bokeh.io
import bokeh.plotting
bokeh.io.output_notebook()
```

In this lesson, 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.

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 "`as`

`np`

". 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.

In [2]:

```
# Create a NumPy array from a list
my_ar = np.array([1, 2, 3, 4])
# Look at it
my_ar
```

Out[2]:

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.

In [3]:

```
# The data type of stored entries
my_ar.dtype
```

Out[3]:

In [4]:

```
# The shape of the array
my_ar.shape
```

Out[4]:

There are also lots of methods. The one I use most often is `astype()`

, which converts the data type of the array.

In [5]:

```
my_ar.astype(float)
```

Out[5]:

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.

In [6]:

```
print(my_ar.max())
print(my_ar.min())
print(my_ar.sum())
print(my_ar.mean())
print(my_ar.std())
```

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.

In [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))
```

There are many other ways to make NumPy arrays besides just converting lists or tuples. Below are some examples.

In [8]:

```
# How long our arrays will be
n = 10
# Make a NumPy array of length n filled with zeros
np.zeros(n)
```

Out[8]:

In [9]:

```
# Make a NumPy array of length n filled with ones
np.ones(n)
```

Out[9]:

In [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)
```

Out[10]:

In [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)
```

Out[11]:

NumPy has a primitive function for loading in data from text files, `np.loadtxt()`

, but with Pandas's `read_csv()`

, there is really no reason to ever use it. Instead, we may sometimes wish to extract NumPy arrays out of Pandas data frames. Thi is almost always for speed reasons, which we will see when we do hacker stats. NumPy arrays are highly optimized for computing speed.

As it is always more fun to work with a real biological application, we will populate our NumPy arrays with data. In their 2011 paper in PLoS ONE, Harvey and Orbidans measured the cross-sectional area of *C. elegans* eggs that came from mothers who had a high concentration of food and from mothers of a low concentration of food. I digitized the data from their plots, and they are available in the file `~/git/bootcamp/data/c_elegans_egg_xa.csv`

in the bootcamp repository.

In [12]:

```
df = pd.read_csv('data/c_elegans_egg_xa.csv', comment='#')
# Take a look
df.head()
```

Out[12]:

It's always a good idea to do a quick look at a data set by making a plot.

In [13]:

```
p = bokeh_catplot.strip(
data=df,
cats='food',
val='area (sq. um)',
order=['low', 'high'],
jitter=True,
x_axis_label='amount of food',
width=200,
)
bokeh.io.show(p)
```

It looks like worms that eat more food have smaller eggs.

If we wanted to extract the measurements for worms with high food, we can do so using Boolean indexing in Pandas.

In [14]:

```
xa_high = df.loc[df['food']=='high', 'area (sq. um)']
# Take a look at the data type
type(xa_high)
```

Out[14]:

The result is a Pandas `Series`

, which is kind of like a single-column `DataFrame`

. If we want to convert this to a Numpy array, we use the `.values`

attribute.

In [15]:

```
xa_high = df.loc[df['food']=='high', 'area (sq. um)'].values
type(xa_high)
```

Out[15]:

Now we have a Numpy array! Let's pull out the low food cross sectional areas as well.

In [16]:

```
xa_low = df.loc[df['food']=='low', 'area (sq. um)'].values
```

And now let's take a look at these arrays.

In [17]:

```
xa_high
```

Out[17]:

In [18]:

```
xa_low
```

Out[18]:

We will use these arrays as examples to learn about NumPy arrays.

We can slice NumPy arrays like lists and tuples. Here are a few examples.

In [19]:

```
# Reversed array
xa_high[::-1]
```

Out[19]:

In [20]:

```
# Every 5th element, starting at index 3
xa_high[3::5]
```

Out[20]:

In [21]:

```
# Entries 10 to 20
xa_high[10:21]
```

Out[21]:

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 `xa_high`

. We just index with a list of the indices we want.

In [22]:

```
xa_high[[1, 19, 6]]
```

Out[22]:

Instead of a list, we could also use a NumPy array.

In [23]:

```
xa_high[np.array([1, 19, 6])]
```

Out[23]:

As a very nice feature, we can use Boolean indexing with Numpy arrays, just like with Pandas using `.loc`

. Say we only want the egg cross sectional areas that are greater than 2000 µm².

In [24]:

```
# Just slice out the big ones
xa_high[xa_high > 2000]
```

Out[24]:

If we want to know the indices where the values are high, we can use the `np.where()`

function.

In [25]:

```
np.where(xa_high > 2000)
```

Out[25]:

Yes, NumPy arrays are mutable. Let's look at some consequences.

In [26]:

```
# Make an array
my_ar = np.array([1, 2, 3, 4])
# Change an element
my_ar[2] = 6
# See the result
my_ar
```

Out[26]:

Now, let's try working attaching another variable to the NumPy array.

In [27]:

```
# 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
```

Out[27]:

Let's see how messing with NumPy in functions affects things.

In [28]:

```
# 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
```

Out[28]:

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:

A very important distinction between NumPy arrays and lists is that slices of NumPy arrays are **views** into the original NumPy array, NOT copies.

In [29]:

```
# 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)
```

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.

Fortunately, you can make a copy of an array using the `np.copy()`

function.

In [30]:

```
# Make a copy
xa_high_copy = np.copy(xa_high)
# Mess with an entry
xa_high_copy[10] = 2000
# Check equality
np.allclose(xa_high, xa_high_copy)
```

Out[30]:

So, messing with an entry in the copy did not affect the original.

Mathematical operations on arrays are done elementwise to all elements, as we saw with Pandas data frames.

In [31]:

```
# Divide one array be another
np.array([5, 6, 7, 8]) / np.array([1, 2, 3, 4])
```

Out[31]:

In [32]:

```
# Multiply by scalar
-4 * xa_high
```

Out[32]:

In [33]:

```
# Raise to power
xa_high**2
```

Out[33]:

NumPy arrays need not be one-dimensional. We'll create a two-dimensional NumPy array by reshaping our `xa_high`

array from having shape `(44,)`

to having shape `(11, 4)`

. That is, it will become an array with 11 rows and 4 columns.

In [34]:

```
# New 2D array using the reshape() method
my_ar = xa_high.reshape((11, 4))
# Look at it
my_ar
```

Out[34]:

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]`

In [35]:

```
# Make list of lists
list_of_lists = [[1, 2], [3, 4]]
# Pull out value in first row, second column
list_of_lists[0][1]
```

Out[35]:

Though this will work with NumPy arrays, this is *not* how NumPy arrays are indexed. They are indexed much more conveniently.

In [36]:

```
my_ar[0,1]
```

Out[36]:

We essentially have a tuple in the indexing brackets. Now, say we wanted the second row (indexing starting at 0).

In [37]:

```
my_ar[2,:]
```

Out[37]:

We can use Boolean indexing as before.

In [38]:

```
my_ar[my_ar > 2000]
```

Out[38]:

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()`

.

In [39]:

```
np.where(my_ar > 2000)
```

Out[39]:

This tuple of NumPy arrays is how we would index using fancy indexing to pull those values out using fancy indexing.

In [40]:

```
my_ar[(np.array([ 0, 1, 8, 10, 10]), np.array([1, 0, 1, 0, 2]))]
```

Out[40]:

NumPy arrays can be of arbitrary integer dimension, and these principles extrapolate to 3D, 4D, etc., 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.

In [41]:

```
combined = np.concatenate((xa_high, xa_low))
# Look at it
combined
```

Out[41]:

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 (just like we have seen in Pandas `DataFrame`

s). That is, they apply the function to each entry in the array. Check it out (even though exponentiating cross sectional areas is nonsensical).

In [42]:

```
# Exponential
np.exp(xa_high / 1000)
```

Out[42]:

In [43]:

```
# Cosine
np.cos(xa_high)
```

Out[43]:

In [44]:

```
# Square root
np.sqrt(xa_high)
```

Out[44]:

We can even do some matrix operations (which are obviously not done elementwise), like dot products.

In [45]:

```
np.dot(xa_high/1000, xa_high/1000)
```

Out[45]:

NumPy also has useful attributes, like `np.pi`

.

In [46]:

```
np.pi
```

Out[46]:

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
```

In [47]:

```
scipy.special.erf(xa_high/2000)
```

Out[47]:

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. In my own work, I use the following extensively.

`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.

Like operations on Pandas `Series`

that we have already seen, operations on Numpy arrays are also vectorized and binary operations typically work elementwise.

In [48]:

```
xa_high + xa_high
```

Out[48]:

Numpy arrays are ordered strictly indexed by integers. There are therefore sliced just like lists, tuples and strings we have seen before. Conveniently we can also use Boolean indexing on Numpy arrays, just like with Pandas.

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.

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.

In [49]:

```
# Python code to sum an array and print the result to the screen
print(sum(my_ar))
```

```
/* 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!

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 lesson). We then use the `%timeit`

magic function of IPython to time the execution of the sum of the elements of the array.In [50]:

```
# Make array of 10,000 random numbers
x = np.random.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)
```

Now we'll do the same test with the NumPy implementation.

In [51]:

```
%timeit np.sum(x)
```

Wow! We went from milliseconds to *micro*seconds!

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 (and we learned the importance of that in the test-driven development lessons). 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.

In [52]:

```
%load_ext watermark
%watermark -v -p numpy,scipy,pandas,bokeh,bokeh_catplot,jupyterlab
```