NumPy
J/K or →/← jump between sections
Arrays: numbers that do arithmetic
An array holds numbers of one type. An operation applies to every element. Click an operation.
$ conda install -c conda-forge numpy
import numpy as np py_list = [1, 2, 3] np_array = np.array(py_list)
Every array knows its shape and type
np_array.shape, np_array.dtype, len(np_array)
np.sqrt(np_array), np.exp, np.sin… also work element by element.
Creating arrays
arange takes a step and stops before the end, like range. linspace takes a number of points and includes the end.
Filled arrays: the shape is one argument, a tuple
Shape: the same numbers, arranged differently
reshape fills rows left to right, top to bottom. -1 means "work it out". Colour follows the value.
vec = np.arange(12) mat = vec.reshape(3, 4)
mat.flatten() gives back the 12 numbers in one row.
A third axis: a stack of matrices
np.arange(24).reshape(2, 3, 4)
Indexing: mat[row, column]
One index or slice per axis, separated by a comma. : alone means "all".
A comparison gives a boolean array; a boolean array selects
The same on a matrix. The selected elements always come out as a 1-D array.
Reductions along an axis
axis=0 collapses the rows: one result per column. axis=1 collapses the columns: one per row. Hover a result.
mat.std(axis=1), mat.min() work the same way.
Distance between two atoms
atom1 = np.array([0.0, 0.0, 0.0]) atom2 = np.array([1.0, 1.0, 0.0]) np.sqrt(np.sum((atom1 - atom2) ** 2)), np.linalg.norm(atom1 - atom2)
Exercise 1: Arrays
Calculate the average of all integers below 100 that are divisible by 8, in three ways:
np.arangewith a step, andmeannp.arange(1, 97).reshape(12, 8)and one column of it- a boolean mask with
%onnp.arange(1, 100)
52.0 52.0 52.0
* is element by element, @ is the matrix product
Hover a result element of mat @ vec: a row of the matrix times the vector, summed.
a = np.array([1, 2, 3]) a * a, a @ a
mat = np.arange(6).reshape(2, 3) vec = np.array([1, 0, 1]) mat @ vec
The inner sizes must agree
mat @ np.array([1, 0])
Inverse and identity
m = np.array([[1, 2], [3, 4]]) m_inv = np.linalg.inv(m) m @ m_inv
np.allclose(m @ m_inv, np.identity(2))
allclose: equal up to a tiny tolerance.
Reading and writing files
array.dat holds the pyridine coordinates, one atom per line, x y z in Å.
xyz = np.loadtxt('array.dat')
xyz.shape
xyz[:3]
np.savetxt('xyz_copy.dat', xyz, fmt='%10.4f', header='x y z')
fmt='%10.4f': width 10, 4 decimals, as {x:10.4f} in an f-string.
Exercise 2: Reading data
Load array.dat with np.loadtxt. Print its shape, the geometric centre (mean along the right axis) and the distance between atoms 0 and 1 (np.linalg.norm).
(11, 3) [-0.18022684 0.36094512 0.03922925] 1.3941348519942394
Broadcasting: arrays of different shapes
Shapes are compared from the right. Two sizes fit if they are equal or one of them is 1; a size 1 is stretched by copying.
None in an index adds an axis of length 1
d = np.arange(4) d[:, None].shape
Three axes: the same rule
tensor = np.arange(24).reshape(2, 4, 3) (tensor + vec).shape
The distance matrix in one line
Every atom minus every atom. Row i repeats atom i, column j repeats atom j. Hover a cell.
(xyz[:, None, :] - xyz).shape distances = np.linalg.norm(xyz[:, None, :] - xyz, axis=-1)
Exercises 3–5: Distances
3. Distance matrix
Build the 11 × 11 matrix of all interatomic distances with two nested for loops (enumerate) filling np.zeros((11, 11)). Check with np.allclose that it agrees with the broadcasting one-liner.
True
4. Counting bonds
Two atoms are bonded if their distance is below 1.6 Å. How many bonds does pyridine have? Count each pair once and ignore the diagonal: np.triu with k=1.
11
5. Writing data
Save the distance matrix to distances.dat with two decimals (np.savetxt, fmt), load it back and print the shape.
(11, 11)
Speed
A Python loop handles one number at a time. An array operation runs the whole loop in compiled C.
%timeit sum([x**2 for x in range(1_000_000)]) %timeit (np.arange(1_000_000)**2).sum()
%timeit is a Jupyter command: it runs the line many times and reports the average.
Text columns: reading an xyz file
dtype=str reads everything as text. Take the columns apart, then convert the numbers. Hover the code.
raw = np.loadtxt('pyridine.xyz', skiprows=2, dtype=str)
elements = raw[:, 0]
coordinates = raw[:, 1:].astype(float)
elements, coordinates.mean(axis=0)
The same reader works for any xyz file: the homework and the plotting class use it.