NumPy

NumPy adds arrays and linear algebra to Python, with special functions, transformations, the ability to operate on all elements of an array in one stroke. Remember that in addition to the web resources, in interactive Python try help() for more information on a function:

help("numpy.arange")

will tell you that arange takes one required argument but has several optional ones:

Notice that the array is created with np.zeros(), and the argument is (3,4,5). This means an array of 3x4x5 elements, all zero (float64, by default), grouped as 3 elements, each of 4 elements, each of 5 elements.

An array can be reshaped after it is made. The array stays the same way in memory, but the grouping changes.

myarray = np.array( [1,3,5,7,11,13] )

makes a linear array of 6 elements, and

myarray.reshape(2,3)

changes its shape, so it will be

array([[ 1, 3, 5],
[ 7, 11, 13]])

To create an array of 1000 elements from 0 to 999, the function

my_1d_array = np.arange(1000)

It is reshaped into an array 10x10x10 with

my_3d_array = my_1d_array.reshape((10,10,10))

or an multi-dimensional array may be flattened

my_new_array = my_3d_array.ravel()

The original data remain unchanged, but they are sliced and indexed in different ways depending on the shape of the array and the choices for indexing it.

In summary, NumPy arrays may be created with

np.array()
np.arange()
np.zeros()
np.empty()

reshaped with

myarray.reshape()
myarray.ravel()

written to files in a binary format, and read back with

np.save('myfile.npy', myarray)
newarray = np.load('myfile.npy')

In the following we will see how to index within arrays, operate on arrays, and have arrays functionally combine with one another.

Indexing

Once an array is created, you can refer to it as a whole, or to its elements one-by-one. Create a list, turn it into an array, reshape it, and print it with something like this

NumPy math has the usual trigonometric functions, and others. A full list is in the documentation, and some useful ones are for element-by-element

add(x1,x2)

sub(x1,x2)

multiply(x1,x2)

divide(x1,x2)

power(x1,x2)

square(x)

sqrt(x)

exp(x)

log(x)

log10(x)

absolute(x)

negative(x)

sin(x), cos(x), tan(x)

arcsin(x), arccos(x), arctan(x)

arctan2(x,y) returns the angle whose tangent is the ratio of x and y

sinh(x), cosh(x), tanh(x)

arcsinh(x), arccosh(x), arctanh(x)

degrees(x) or rad2deg(x) convert from radians

radians(x) or deg2rad(x) convert from degrees

rint(x) round to the nearest integer

fix(x) round to the nearest integer toward zero

The broadcast feature of NumPy arrays can be combined with selective indexing in an interesting way. Consider this program to make an array of random numbers in a Gaussian distribution with mean 0, and sigma 1

a = np.random.randn(100)

Print this will show 100 values, some negative, some positive. We can select only those larger than a cutoff, work with them, and put them back in the array

index = a > 0.75
b = a[index]
b= b ** 3 - 100.
a[index] = b

Printing index will show an array of True and False that mask the original array. The array b will only have those elements that satisified the condition used to make the index. The index is used again, to put modified elements back into the original array.

Matrix and vector math in NumPy

We have seen that NumPy has its own set of math functions that broadcast over arrays. If you define an array

a = np.arange(0,1,0.01)*np.pi

you will have an array from 0 to Pi in steps of 0.01*Pi. You can operate on this array, element by element, with np.cos

b = np.cos(a)

and have a new array that contains the cosine of each element of the first one.

Before we move on to SciPy, which builds on NumPy to add a number of useful features, there are two things we should note.

First, NumPy includes matrix math, either by mapping its native arrives to conventional matrices, or by invoking matrix math operations on its arrays. We will only look at this second way, which handles most applications and creates very clear code.

The product of two matrices is done with the "dot" operation between two NumPy arrays.

a = np.array(([1,2],[3,4]))
b = np.array(([0,1],[1,0]))

makes two arrays that may be thought of as 2x2 matrices. To multiply them in the usual sense of matrix multiplication,

c = a.dot(b)

gives

array([[2, 1],
[4, 3]])

and

d = b.dot(a)

gives

array([[3, 4],
[1, 2]])

A matrix inverse is found in the linalg package of NumPy

e = np.linalg.inv(a)

With this we can solve linear equations. Suppose that you have the system of 3 equations in 3 unknowns:

Fourier Transforms in NumPy

NumPy provides Fourier Transforms in several functions, including the one-dimension discrete Fast Fourier Transform or FFT with the function fft(a), and the one-dimensional FFT of real data with rfft(a). It also has n-dimensional Fourier Transforms as well.

As a very simple example, let's consider an exponential decay modulating a sine wave adapted from our dampled cosine plotting example to use NumPy arrays:

SciPy and SciKits

NumPy adds numerical support to Python that enables a broad range of applications in science in engineering. SciPy and SciKits use NumPy to provide features that are targeted at scientific computing. These packages are dynamic, with community support that is adding new contributions and updating older ones. As we continue our short course on Python for Physics and Astronomy we will explore a few of these to see how we can use Python for interpolating data, numerical integration, and image processing. A reference guide to SciPy is available on line from the their website, or in this reference pdf if that site is not available.

Interpolation

Frequently we will have data that are not as finely spaced as we would like, but which are smooth enough to reliably interpolate between the known points. An example might be a resource-intensive computation of a wavefunction for a complex system, a model of the opacity of stellar atmosphere, or a calculation of of a planetary atmosphere on a coarse spatial grid. You can also interpolate noisy data and recover an acceptable estimate of the values between the sampled points.

For example, this program will create a set of test data of a sparsely sampled cosine curve, and then fit it with a linear and a quadratic approximation.

The result, zoomed in to see a few points in detail, looks like this on an interactive screen:

For 1-dimensional interpolation we have tried "linear" and "quadratic" which have clear meanings. The linear interpolation does a linear fit between two adjacent points and uses that to find the value at an x between those points. As you can see in the graph, the values follow a straight line connecting the sample points. The quadratic interpolator takes points bracketing the x of interest and fits a quadratic polynomial to them. This allows the interpolation to have non-zero second derivative, and visually the new data will "curve" between the original sample points.

The choices available for "kind" include

linear

quadratic

cubic

1,2,3, or higher indicating order of spline

When the data support it, cubic interpolation introduces a third derivative, and gives a better representation of the original. You would not use linear interpolation of position to find velocity, and if you wanted to know the rate of change of acceleration you might use cubic interpolation.

For more functions where the shape is not well represented by a polynomial, a spline fit will adapt to the available points and give a representation of the data better than fixed polynomials. The cubic spline is the most often used. Another implementation of spline fitting comes is incorporated into SciPy's UnivariateSpline function.

Similar to the fitting above, the program to use spline fitting would have lines such as these

# Values of x for sampling inside the boundaries of the original data
x_interpolated = np.linspace(x.min(),x.max(), 1000)

# New values of y for these sample points
y_interpolated_spline = f_spline(x_interpolated)

The function call to UnivariateSpline uses an optional smoothing factor argument "s=40". If "s=0" the spline will interpolate through all the points.
The larger this value, the more the spline filters short interval changes. Another optional argument is the order of the smoothing spline which is specified with "k=3". It must be less than or equal to 5.

The complete program is in the Examples section. It will create a new data and a different fit on each run because it calls a random number generator.

which we will plot in a moment. As is, it will print the integral from -50 to 50 under the Lorentzian curve (generated with the "f" definition) and a=10. As given, this Lorentzian has a peak of 1, and it falls to 0.5 of the peak at x=a. The area is exactly a x Pi.

You can iterate this by hand and see that as the limits are extended to infinity the integral slowly converges to the exactly value it would have at infinite limits. You can also generate a numerical infinity by using

Differentiation

SciPy provides differentiation of functions, much in the same fashion as it offers integration.

derivative(func, x0, dx=1.0, n=1, args=(), order=3)

where the "func" is the function being differentiated at "x0", "dx" is the interval on x used to find the derivative, "n" is order for the differentiation (by default 1 for first derivative), and "order" is the number of points to use in finding the derivative, not to be confused with the order of the differentiation. The "args" argument allows a function to call other arguments, rather than have them globally defined as we do in these examples.

The result can be very sensitive to the choice of dx, which must be small enough to see the representative incremental changes.

Differentiation of NumPy arrays can be done without additional programming, since it is only the difference between uniformly spaced values. However, for noisy data it would be best to interpolate the data first, and then take differences between adjacent points to calculate the derivative. Given the arrays, the derivative might be found with

np.diff(y) / np.diff(x)

with suitable tests for pathological behavior.

In some cases it is possible to use symbolic analytic differentiation with the SymPy package that has evolved into a robust full-featured symbolic mathematics tool.

Statistics

As expected, SciPy provides statistical functions to Python in the form of various conventional statistical discrete and continuous distributions. The normal distribution is first one we would usually encounter:

where sigma is the standard deviation, sigma^2 is the variance, and mu is the mean.
The factor in front normalizes the distribution to unit area integrated to infinity on x. A Gaussian distribution centered at the origin has mu=0 and a width such that at x=sqr(2)sigma the distribution is 1/e of its maximum at x=0.

Numpy would also allow creating a normal random array of values with mean 0 and variance 1, such as

y = np.random.randn(1000)

The mean, standard deviation, and variance could be assessed by evaluating the array

mean = y.mean()
std = y.std()
var = y.var()

SciKits Packages

We mention SciKits in the context of SciPy because it is a collection of SciPy applications that extend into many different domains of physics, astronomy, and engineering. The best introduction is to browse the SciKits website and explore the variety there. In addition to image processing, you'll find speech processing, light scattering from non-spherical particles, sparse matrices, machine learning, vector field plotting, and more. Some are fully developed, others are works in progress. One of the most promising is the scikits.cuda package, which interfaces Python to CUDA, NVidia's parallel processing through graphical processing units (GPU). The most recent hardware at this date (February 2013), is
the GeForce GTX Titan, a supercomputer on a card with 2668 GPU cores, 4.5 Teraflops of single precision and 1.3 Teraflops of double precision processing power, and 6 GB graphic DDR5 memory.

We will return to use the SciPy image processing routines later.

Examples

For examples of NumPy, see the examples section. The program numpy_fft contains the damped oscillator discussed above.

Assignments

For the assigned homework to use these ideas, see the assignments section.