Python intro

Topics for today

  • NumPy arrays and vectorization
  • Styleguides
  • Plots

Use numpy arrays, not lists!

  • Available all necessary math operations with vectors, matrices and tensors
  • Optimized implementation: more details in the next week lectures
  • Easy to use!
In [ ]:
import numpy as np

n = 3
A = np.random.randn(n, n)
x = np.random.randn(n)
print(A)
print(A @ x)
print(A.dot(x))
print(np.dot(A, x))
In [ ]:
print("Trace of the matrix =", np.trace(A))
print("Diagonal of the matrix =", np.diag(A))
print("Different sums")
print("Sum all elements in the matrix", np.sum(A))
print("Sum all evelements over rows \n {} \n and columns \n {}".format(np.sum(A, 1), np.sum(A, 0)))
print("Inverse matrix =", np.linalg.inv(A))

Broadcasting

  • Is it possible to compute $A + x$ for the matrix $A$ and vector $x$?
In [ ]:
print(A)
print(x)
print(A + x)
print(A * x)

And what about columns?

In [ ]:
print(A)
print(x)
print(A + x[:, np.newaxis])

One more example

In [ ]:
i = np.arange(4)
j = np.arange(4)
mat = i[:, None] - j[None, :]

No loops!

  • Avoid loops wherever its possible!
  • Loops in Python are very slow
  • Use initializers from NumPy
In [ ]:
%%timeit
a = []
n = 100000
for i in range(n):
    a.append(1)
In [ ]:
%timeit np.ones(n)
%timeit [1 for i in range(n)]
In [ ]:
print(np.zeros(3))
print(np.ones(3))
print(np.eye(3))
print(np.arange(3))

Styleguides

Plotting

  • Use matplotlib library
  • Check the following parts of plots
    • Scale (log vs. linear)
    • Fontsize in axis labels
    • Fontsize in ticks
    • Fontsize in legend
    • Clear difference between lines colours and/or markers
    • Grid if necessary
In [ ]:
import matplotlib.pyplot as plt
%matplotlib inline
In [ ]:
c = 1.
num_points = 100
method_1 = [c / k**5 for k in range(1, num_points)]
method_2 = [c * 0.5**k for k in range(1, num_points)]
In [ ]:
plt.plot(method_1, label="Method A")
plt.plot(method_2, label="Method B")
plt.legend()
plt.ylabel("Convergence")
plt.xlabel("Number of iterations")

If you leave this plot as it is, you will get penalty!

In [ ]:
plt.plot(method_1, label="Method A", linewidth=4)
plt.plot(method_2, label="Method B", linewidth=4)
plt.legend(fontsize=18)
plt.ylabel("Convergence", fontsize=18)
plt.xlabel("Number of iterations", fontsize=18)
plt.yscale("log")
plt.grid(True)
plt.xticks(fontsize=18)
plt.yticks(fontsize=18)
In [ ]:
plt.rc("text", usetex=True)
plt.plot(method_1, label="Method A", linewidth=4)
plt.plot(method_2, label="Method B", linewidth=4)
plt.legend(fontsize=18)
plt.ylabel("Convergence", fontsize=18)
plt.xlabel("Number of iterations", fontsize=18)
plt.yscale("log")
plt.grid(True)
plt.xticks(fontsize=18)
plt.yticks(fontsize=18)
In [ ]:
plt.figure(figsize=(8, 6))
plt.plot(method_1, label="Method A", linewidth=4)
plt.plot(method_2, label="Method B", linewidth=4)
plt.legend(fontsize=18)
plt.ylabel("Convergence", fontsize=18)
plt.xlabel("Number of iterations", fontsize=18)
plt.yscale("log")
plt.grid(True)
plt.xticks(fontsize=18)
_ = plt.yticks(fontsize=18)

Summary

  • Use NumPy objects
  • Check styleguides to write readable code!
  • Make nice plots with clear desciptions and conclusions