NanoPy #4

NumPy

NumPy, along with its ancestors Numeric and numarray, are cornerstones of scientific computing in the world of Python, providing - most importantly - efficient array objects with a high-level array syntax.

A few examples for NumPy are shown here; many more examples are provided online as part of a larger set of documentation on NumPy and SciPy The SciPy package (see NanoPy #5) supplements the core NumPy package, using NumPy arrays as the centerpiece of more complex numerical algorithms. For many modules, it will be easiest to work with arrays as presented by scipy, since you'll be using other pieces of scipy. For other purposes, you may find it easier to use either NumPy directly. The same underlying array package is imported in either case.

Arrays

NumPy supports, at their core, array objects are arbitrary dimension. NumPy arrays are: NumPy arrays support array syntax, that is, the ability to execute operations across entire arrays without the need for explicit indexing into the array. (This is similar to the manipulation of arrays in Matlab.) Arrays are implemented in C, but are callable from Python, and offer significant performance enhancements if manipulated with array-level operations (as opposed to explicit looping with either arrays or Python lists).

Some examples of array operations:

import numpy 
x = numpy.array([0.5, 1.0, 1.5])   # make a numpy array from the list [0.5, 1.0, 1.5]
y = numpy.arange(0., 10., 2.)      # make array stepping from 0. to 8. by 2. (stops short of 
                                     # upper bound 10., as with built-in Python function range)
z = numpy.zeros((N,M), int)  # make NxM array of integer zeros; array's shape is (N,M)

a = b + c            # add arrays b and c element-by-element; b & c must be of the same shape
y = 0.1 * x          # multiply every element of x by 0.1 
y = numpy.sin(x)   # return sin of every element in x; sin is a Ufunc
y = x > 1.0          # return an array y of the same shape as x, containing 0 (False) 
                     # wherever x is <= 1.0, and 1 (True) wherever x > 1.0
y = z[0]             # y is zeroth row of z (indexing an array)
y = z[:,1]           # y is 1th column of z ("slicing" an array)
y = z[3:8, 2:5]      # slicing z along multiple dimensions

x = 10.**numpy.arange(-3.0, 0.01, 0.5)    # raise 10. to the power of each element 
                                            # in the array [-3.0, -2.5, -2.0, -1.5, -1.0, -0.5, 0.0] 
y = numpy.reshape(x, (10, 2))             # reshape array x into a new array of shape 10 x 2; 
                                            # x must be of compatible shape, i.e., 
                                            # have 20 elements to begin with 
y = x.tolist()                              # convert array x to ordinary Python list
import scipy                                # if you want the scipy package
x = scipy.array([0.5, 1.0, 1.5])            # create a scipy array
y = scipy.linspace(0.0, 10.0, 20.)          # similar to arange, but returns a specified 
                                            # number of linearly spaced samples within 
                                            # a defined range, e.g., 20 samples between 
                                            # 0.0 and 10.0, inclusive

Random arrays

NumPy provides support for construction of arrays composed of random numbers drawn from various distributions, as part of a submodule (numpy.random).
import numpy   # numpy.random imported along with rest of numpy
x = numpy.random.random((L,L))             # create LxL array of random numbers drawn 
                                          # uniformly on the interval [0,1.)
y = numpy.random.randint(0, 5, (10, 10))   # create 10x10 array of random integers 
                                          # drawn uniformly from [0,5), i.e., [0,4]

Linear algebra

As in Matlab, array objects are useful both as multidimensional arrays and as tensors, matrices, and vectors whose behavior is defined by the operations of linear algebra. NumPy provides interfaces to compiled linear algebra routines (from a subset of lapack), as part of the submodule numpy.linalg:
import numpy    # numpy.linalg imported along with rest of numpy
e = numpy.linalg.eigvals(x)                     # compute eigenvalues of square matrix x
s = numpy.linalg.svd(y)                         # compute SVD of matrix y
inv = numpy.linalg.inv(m)                       # compute inverse of matrix m
x = numpy.linalg.solve(a, b)       # solve for x such that dot(a,x) = b
If you have experience using Matlab, you might want to take a look at the documentation on NumPy for Matlab users.