Python toolkit for SciML
Everything in this book, in code. Every cell marked Run executes in your browser — edit it, break it, run it again.
Python is the common language of scientific machine learning. You need four libraries: NumPy (Numerical Python) for arrays, Matplotlib for plots, SciPy (Scientific Python) for classical solvers, and PyTorch (or JAX) for neural networks and automatic differentiation. The cells below cover what you will use in the workshop's hands-on sessions.
- Work through cells 1–6 here (they run in the browser; the first run downloads Python once, about 10–20 MB).
- Create a free Google account and open Google Colab (colab.research.google.com) — PyTorch is pre-installed there. Copy cell 7 into Colab and run it.
- Optional, for your own laptop: install Python 3.10+ (e.g. via Anaconda or python.org), then
pip install numpy scipy matplotlib torch.
Three lines compute the area under the constant function $f(x) = 2$ on $[1, 4]$ — the rectangle of Chapter 3 — first by the formula, then by adding up thin strips exactly as a computer integrates. Press Run.
height, a, b = 2, 1, 4
print("rectangle area =", height * (b - a)) # 2 x 3 = 6
n = 1000 # now add up 1000 thin strips
h = (b - a) / n
print("sum of strips =", round(sum(height * h for k in range(n)), 10))
Change height, a or b and run again — then the rest of this chapter.
1. Python in ten minutes
# numbers, strings, lists, dictionaries
x = 3.5; n = 10; name = "RACM-SciML"
print(name, "has", len(name), "characters;", "x * n =", x * n)
squares = [k**2 for k in range(1, 6)] # list comprehension
print("squares:", squares, " sum:", sum(squares))
params = {"alpha": 0.1, "L": 1.0} # dictionary: name -> value
print("diffusivity:", params["alpha"])
def euler_step(y, h, f): # a function
"""One forward Euler step for y' = f(y)."""
return y + h * f(y)
y = 1.0
for step in range(10): # a loop: y' = -y, h = 0.1
y = euler_step(y, 0.1, lambda y: -y)
print("Euler y(1) =", round(y, 5), " exact e^-1 =", round(2.718281828**-1, 5))
if y < 0.5:
print("decayed below one half")
Indentation (4 spaces) defines blocks — there are no braces. Indexing starts at 0. range(1, 6) gives 1, 2, 3, 4, 5.
2. NumPy: arrays and vectorisation
A NumPy array holds many numbers of one type. Operations act on all entries at once ("vectorised"), which is 10–100× faster than Python loops.
import numpy as np
x = np.linspace(0, 1, 11) # 11 equally spaced points
print("x =", x)
print("shape:", x.shape, " dtype:", x.dtype)
u = np.sin(np.pi * x) # applied to every entry
print("u at the midpoint:", u[5], " last entry:", u[-1].round(12))
# slicing: interior points, every second point, reversed
print(u[1:-1].round(3)); print(u[::2].round(3)); print(u[::-1][:3].round(3))
# central second difference on the whole grid at once (Chapter 8)
h = x[1] - x[0]
uxx = (u[:-2] - 2 * u[1:-1] + u[2:]) / h**2
print("max |u_xx + pi^2 u| =", np.abs(uxx + np.pi**2 * u[1:-1]).max().round(4))
# matrices
A = np.array([[4., 1.], [1., 3.]]); b = np.array([1., 2.])
print("A @ b =", A @ b, " solve A x = b:", np.linalg.solve(A, b))
print("eigenvalues:", np.linalg.eigvalsh(A))
# broadcasting: a (3,1) column with a (4,) row gives a (3,4) table
print(np.arange(3)[:, None] * 10 + np.arange(4))
stop is excluded; negative indices count from the end ($-1$ is the last). The finite-difference formula (u[:-2] - 2*u[1:-1] + u[2:]) / h**2 lines up the left neighbour, the centre and the right neighbour of every interior point — try the three slices in turn.3. Matplotlib: plotting
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 1, 200); t = np.linspace(0, 0.3, 120)
X, T = np.meshgrid(x, t) # 2D grids
U = np.exp(-np.pi**2 * T) * np.sin(np.pi * X) # heat equation solution
fig, ax = plt.subplots(1, 2, figsize=(10, 3.6))
for tk in [0, 0.05, 0.1, 0.2]:
ax[0].plot(x, np.exp(-np.pi**2 * tk) * np.sin(np.pi * x), label=f"t = {tk}")
ax[0].set_xlabel("x"); ax[0].set_ylabel("u"); ax[0].legend(); ax[0].grid(alpha=.3)
im = ax[1].pcolormesh(X, T, U, shading="auto", cmap="inferno")
ax[1].set_xlabel("x"); ax[1].set_ylabel("t"); fig.colorbar(im, ax=ax[1], label="u(x, t)")
plt.tight_layout(); plt.show()
4. SciPy: classical solvers
scipy.integrate.solve_ivp solves ODE systems with adaptive Runge–Kutta (and implicit methods for stiff problems, Chapter 6). scipy.sparse handles the large sparse matrices of Chapter 4.
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp, quad
from scipy.sparse import diags
from scipy.sparse.linalg import spsolve
# (a) an ODE system: damped pendulum theta'' + 0.3 theta' + sin(theta) = 0
sol = solve_ivp(lambda t, y: [y[1], -0.3 * y[1] - np.sin(y[0])], [0, 30], [2.5, 0.0],
method="RK45", rtol=1e-8, dense_output=True)
t = np.linspace(0, 30, 600)
plt.plot(t, sol.sol(t)[0], label="angle")
plt.xlabel("t"); plt.legend(); plt.grid(alpha=.3); plt.title("Damped pendulum (solve_ivp)"); plt.show()
print("steps taken by RK45:", sol.t.size)
# (b) numerical integration (Chapter 3)
val, err = quad(lambda x: np.exp(-x**2), 0, np.inf)
print("integral of exp(-x^2) on [0, inf):", val, " exact sqrt(pi)/2 =", np.sqrt(np.pi) / 2)
# (c) a sparse Poisson solve with 100,000 unknowns (Chapter 8)
n = 100_000; h = 1 / (n + 1); x = np.linspace(h, 1 - h, n)
K = diags([-1, 2, -1], [-1, 0, 1], shape=(n, n), format="csc") / h**2
u = spsolve(K, np.pi**2 * np.sin(np.pi * x))
print("max error with 1e5 unknowns:", np.abs(u - np.sin(np.pi * x)).max())
5. A complete finite-difference heat solver
import numpy as np
import matplotlib.pyplot as plt
alpha, L, T = 0.01, 1.0, 10.0
N = 50; dx = L / N; x = np.linspace(0, L, N + 1)
dt = 0.4 * dx**2 / alpha # r = 0.4 <= 1/2: stable (Chapter 8)
u = np.where(np.abs(x - 0.5) < 0.15, 1.0, 0.0) # hot middle section
snapshots = {0.0: u.copy()}
t, r = 0.0, alpha * dt / dx**2
while t < T - 1e-12:
u[1:-1] = u[1:-1] + r * (u[:-2] - 2 * u[1:-1] + u[2:])
u[0] = u[-1] = 0.0 # Dirichlet ends
t += dt
for ts in [1.0, 3.0, 10.0]:
if abs(t - ts) < dt / 2: snapshots[ts] = u.copy()
for ts, us in snapshots.items():
plt.plot(x, us, label=f"t = {ts:g}")
plt.xlabel("x"); plt.ylabel("temperature"); plt.legend(); plt.grid(alpha=.3)
plt.title(f"Explicit heat solver, r = {r:.2f}, {int(round(T/dt))} steps"); plt.show()
6. Training by hand: gradient descent with NumPy
import numpy as np
import matplotlib.pyplot as plt
# noisy measurements of a cooling object; fit T(t) = T_room + (T0 - T_room) exp(-k t)
rng = np.random.default_rng(2)
t = np.linspace(0, 10, 25); T_room, T0, k_true = 25.0, 90.0, 0.35
data = T_room + (T0 - T_room) * np.exp(-k_true * t) + rng.normal(0, 1.0, t.size)
k, lr = 0.05, 2e-4 # initial guess and learning rate
for it in range(4000):
model = T_room + (T0 - T_room) * np.exp(-k * t)
dmodel_dk = -(T0 - T_room) * t * np.exp(-k * t) # derivative by the chain rule
grad = np.mean(2 * (model - data) * dmodel_dk) # d(MSE)/dk
k -= lr * grad
print(f"estimated k = {k:.4f} (true {k_true})")
plt.plot(t, data, "o", label="measurements")
plt.plot(t, T_room + (T0 - T_room) * np.exp(-k * t), label=f"fitted, k = {k:.3f}")
plt.xlabel("time (min)"); plt.ylabel("temperature (°C)"); plt.legend(); plt.grid(alpha=.3); plt.show()
This is a tiny inverse problem: we used a physical model (Newton's law of cooling, Chapter 5) and data to find an unknown parameter. PINNs do the same when the model is a PDE without a formula solution.
7. PyTorch: tensors and automatic differentiation
PyTorch arrays (tensors) look like NumPy arrays but remember how they were computed, so torch.autograd.grad can differentiate anything — including derivatives with respect to inputs, the core of PINNs (Chapter 16).
import torch
x = torch.linspace(0, 1, 5, requires_grad=True) # track operations on x
u = torch.sin(torch.pi * x) * torch.exp(x)
# du/dx and d2u/dx2 at all points, exactly
du = torch.autograd.grad(u, x, torch.ones_like(u), create_graph=True)[0]
d2u = torch.autograd.grad(du, x, torch.ones_like(du))[0]
exact_du = (torch.pi * torch.cos(torch.pi * x) + torch.sin(torch.pi * x)) * torch.exp(x)
print("autograd du/dx:", du.detach())
print("exact du/dx:", exact_du.detach())
print("d2u/dx2:", d2u)
# a small network and its gradient with respect to the parameters
net = torch.nn.Sequential(torch.nn.Linear(1, 16), torch.nn.Tanh(), torch.nn.Linear(16, 1))
loss = net(x.reshape(-1, 1)).pow(2).mean()
loss.backward() # backpropagation
print("number of parameters:", sum(p.numel() for p in net.parameters()))
print("gradient of the first weight matrix has shape", net[0].weight.grad.shape)
8. Where to go next
- The complete PINN code is in Chapter 16, and a DeepONet in Chapter 18.
- Official tutorials: numpy.org/learn, matplotlib.org/stable/tutorials, docs.scipy.org, pytorch.org/tutorials ("Learn the Basics").
- For SciML specifically: DeepXDE examples (deepxde.readthedocs.io) and the book by Brunton & Kutz below, which has Python code for every chapter.
| Task | NumPy / SciPy | PyTorch |
|---|---|---|
| array of zeros | np.zeros((3, 4)) | torch.zeros(3, 4) |
| grid of points | np.linspace(0, 1, 101) | torch.linspace(0, 1, 101) |
| matrix product | A @ B | A @ B |
| solve $A\mathbf x = \mathbf b$ | np.linalg.solve(A, b) | torch.linalg.solve(A, b) |
| derivative | finite differences by hand | torch.autograd.grad |
| convert | t.detach().numpy() | torch.from_numpy(a) |
What does u[1:-1] select from a NumPy array u of length 11?
Right — indices 1, 2, …, 9. This is how finite-difference codes update interior grid points while leaving boundary values fixed.
Why can't we use NumPy alone to build a PINN as easily as with PyTorch?
Right. Chapter 16 does it by hand for a one-layer network; for deeper networks and PDEs in several variables automatic differentiation is essential.
- NumPy arrays + slicing = fast, readable numerical code; avoid Python loops over grid points.
- Matplotlib for every result: always look at your solution.
- SciPy gives reliable classical solvers to compare against.
- PyTorch adds automatic differentiation and GPUs — the basis of PINNs and neural operators.
Further reading
- J. VanderPlas, Python Data Science Handbook, 2nd ed., O'Reilly, 2023 — free online.
- C. R. Harris et al., "Array programming with NumPy", Nature 585 (2020) 357–362.
- P. Virtanen et al., "SciPy 1.0: fundamental algorithms for scientific computing in Python", Nature Methods 17 (2020) 261–272.
- A. Paszke et al., "PyTorch: an imperative style, high-performance deep learning library", NeurIPS 2019.
- S. L. Brunton & J. N. Kutz, Data-Driven Science and Engineering, 2nd ed., Cambridge University Press, 2022.