Case study: a pendulum, from physics to PINN

One simple machine, every idea in this book: a differential equation from Newton's law, a numerical solver, a neural network trained on measurements, and a physics-informed network that needs far fewer of them.

⏱ 35 minNeeds: Chapters 5, 6, 12–161 lab · 4 animations
In plain words

Hang a weight on a string and let it swing. Physics gives us a rule for how the angle changes. A computer can follow that rule step by step. A neural network can instead learn the swing from measurements — but only where it has measurements. A PINN learns from a few measurements and the rule, so it keeps swinging correctly long after the data stop.

Level 1 · basicThe physics, the period, and the vocabulary of machine learning Level 2 · standardThe lab: data-only network vs PINN, training vs test error Level 3 · advancedInverse problem: learn $g/L$ from data, with PyTorch code

1. The physics: Newton's law becomes an ODE

Animation: a swinging pendulum and its angle drawn against time as a wave.
Watch: the swing on the left draws the curve $\theta(t)$ on the right — the solution of the differential equation.

A bob of mass $m$ hangs on a light rod of length $L$. Let $\theta(t)$ be the angle from the vertical. Gravity pulls with force $mg$; its component along the path of the bob is $-mg\sin\theta$. The bob moves along a circle, so its acceleration along the path is $L\theta''$. Newton's second law (mass × acceleration = force) gives $$mL\,\theta'' = -mg\sin\theta \quad\Longrightarrow\quad \boxed{\;\theta''(t) + \frac{g}{L}\sin\theta(t) = 0,\qquad \theta(0) = \theta_0,\ \ \theta'(0) = 0.\;}$$ The mass cancels: a heavy and a light bob swing the same way. This is a second-order, nonlinear ODE with two initial conditions.

Simplest example first · small swings

For small angles, $\sin\theta \approx \theta$ (at $10^\circ = 0.1745$ rad, $\sin\theta = 0.1736$ — a 0.5 % difference). The equation becomes $\theta'' + \omega^2\theta = 0$ with $\omega = \sqrt{g/L}$, whose solution is $\theta(t) = \theta_0\cos(\omega t)$. One full swing takes $$T_0 = \frac{2\pi}{\omega} = 2\pi\sqrt{\frac{L}{g}}.$$ For $L = 1$ m and $g = 9.81$ m/s²: $T_0 = 2\pi\sqrt{1/9.81} \approx 2.006$ s. A one-metre pendulum ticks almost exactly once per second each way — which is why grandfather clocks are about a metre long.

For large swings the period grows: at $\theta_0 = 30^\circ$ it is 1.7 % longer than $T_0$, at $60^\circ$ 7.3 % longer, and at $80^\circ$ about 14 % longer (the exact value involves an elliptic integral). That is where the small-angle model fails, and where solving the full nonlinear equation matters.

2. The classical way: step through time

Animation: Euler's method spirals outwards and gains energy while Runge–Kutta 4 stays on the exact circle.
Watch: with the same step size, Euler's method (red) gains energy every swing — a pendulum that swings higher and higher, which is impossible. RK4 (green) stays on the true orbit.

Write the equation as a first-order system for angle and angular velocity, $\theta' = v$, $v' = -\frac{g}{L}\sin\theta$, then step with Runge–Kutta 4 or SciPy's solve_ivp. With a small step this is extremely accurate and fast — this is the reference ("ground truth") against which we will judge every neural network.

import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt

g, L = 9.81, 1.0
def rhs(t, y):                      # y = [theta, v]
    return [y[1], -g / L * np.sin(y[0])]

t = np.linspace(0, 6, 600)
for deg in [10, 60, 120]:
    sol = solve_ivp(rhs, [0, 6], [np.radians(deg), 0], t_eval=t, rtol=1e-9)
    plt.plot(t, sol.y[0], label=f"start at {deg}°")
plt.xlabel("time t (s)"); plt.ylabel("angle θ (rad)"); plt.legend(); plt.title("Larger swings take longer")
plt.show()

3. The vocabulary of machine learning, on one pendulum

WordMeaningOn the pendulum
Input / outputwhat the model reads / predictstime $t$ → angle $\theta(t)$
Training dataexamples used to fit the weightsangles measured during the first second (blue dots in the lab)
Test dataexamples never shown during training, used to judge the modeltrue angles at other times, including later times (hollow violet dots)
Collocation pointspoints where a PINN checks the equation; no measurement neededorange ticks along the time axis
Initial-condition pointswhere the PINN is told the starting state$\theta(0) = \theta_0$, $\theta'(0) = 0$
Lossone number measuring how wrong the model isdata misfit + equation residual + initial-condition misfit
Iteration / epochone update of the weights / one pass through all datathe counter in the lab
Training errorerror on the training datahow well the curve passes through the blue dots
Test errorerror on unseen data — the honest scorehow well the curve matches the truth at the violet dots
Interpolation / extrapolationpredicting inside / outside the range of the data$t < 1$ s / $t > 1$ s
Accuracyfor numbers we usually report an error (root-mean-square, maximum, or relative %); "accuracy" in % is mainly used for classificatione.g. test error 0.02 rad ≈ 1°

4. The lab: data-only network vs PINN

Animation: a data-only network fits ten early measurements then wanders off; the PINN follows the exact pendulum swing.
Watch first: both networks see the same 10 measurements from the first 1.3 s. The data-only network (left) has no reason to keep swinging. The PINN (right) is also told the equation at the violet collocation ticks, and swings on.

Now do it yourself. Both networks below have the same architecture (one hidden layer of 32 tanh neurons), the same starting weights and the same optimiser (Adam). The data-only network minimises only the misfit to the measurements. The PINN minimises $$\mathcal L(\theta_{\text{net}}) = \underbrace{\frac{1}{N_c}\sum_{j}\Big(u''(t_j) + \tfrac{g}{L}\sin u(t_j)\Big)^2}_{\text{physics, at collocation points}} + \underbrace{\lambda\Big[(u(0)-\theta_0)^2 + u'(0)^2\Big]}_{\text{initial conditions}} + \underbrace{\frac{\lambda_d}{N_d}\sum_k \big(u(t_k) - y_k\big)^2}_{\text{data}},$$ with the derivatives $u'$, $u''$ of the network computed exactly. Here $g/L = \pi^2$, so a small swing takes 2 s.

Lab · pendulum: data-only network vs PINNpress ▶ Train both
exact (dashed)training datatest pointscollocation pointsdata-only networkPINN
Training runs in your browser (6 000 iterations, a few seconds). The table compares training error (on the measurements) with test error (on unseen times). Lower-left: loss curves. Lower-right: three pendulums driven by the truth and by the two networks.
Experiments to try
  1. Default settings. Both networks fit the blue dots (small training error). Only the PINN has a small test error. That is the difference between memorising and learning.
  2. Measurements = 2. The data-only network is hopeless; the PINN still works, because the initial conditions and the equation carry almost all the information.
  3. Data window = 3 s. Now the data cover the whole range: the data-only network improves a lot. Data can replace physics — if you have enough of it, everywhere you need it.
  4. Noise = 0.15. The data-only network bends to follow the noisy dots (overfitting). The PINN is held close to the law.
  5. Collocation points = 10. Too few checks of the equation: the PINN can cheat between them. Raise to 60 again.
  6. Time span = 5 s. PINN training gets much harder over long times — errors at early times propagate. This is a real, known difficulty (see Chapter 16, section 4); remedies include training on growing time windows.
  7. Starting angle = 120°. Strongly nonlinear motion. The PINN uses the full $\sin\theta$, so it still follows the truth.

5. Underfitting and overfitting, seen on the pendulum

The general ideas are in Chapter 15. On the pendulum:

In the lab, the data-only network has training error 0.004 and test error 0.9. Which statement is best?

Right. A tiny training error with a large test error means the model learned the training set, not the law. Here the main cause is extrapolation beyond the data window.

6. The inverse problem: learn $g/L$ from measurements

Suppose you do not know the length of the string. Make $k = g/L$ a trainable number next to the network weights, and minimise the same loss with the residual $u'' + k\sin u$. If the measurements are informative, $k$ converges to the true value — from which $L = g/k$. This is a PINN doing what classical solvers cannot do directly: solving the equation and identifying its coefficient in one optimisation (see Chapter 16, section 3).

import math, torch
torch.manual_seed(0)

# --- synthetic measurements from the true pendulum (g/L = pi^2, start at 60 degrees)
k_true, th0 = math.pi**2, math.radians(60)
def rk4(k, T=3.0, n=3000):
    h, y, out = T / n, torch.tensor([th0, 0.0]), []
    f = lambda y: torch.stack([y[1], -k * torch.sin(y[0])])
    for i in range(n + 1):
        out.append(y[0].item())
        k1 = f(y); k2 = f(y + h/2*k1); k3 = f(y + h/2*k2); k4 = f(y + h*k3)
        y = y + h/6*(k1 + 2*k2 + 2*k3 + k4)
    return torch.tensor(out)
truth = rk4(k_true)
t_data = torch.linspace(0.1, 1.5, 12).reshape(-1, 1)
y_data = truth[(t_data[:, 0] / 3.0 * 3000).round().long()].reshape(-1, 1)
y_data += 0.01 * torch.randn_like(y_data)                 # measurement noise

# --- network u(t) and the unknown coefficient k (log-parametrised to stay positive)
net = torch.nn.Sequential(torch.nn.Linear(1, 32), torch.nn.Tanh(),
                          torch.nn.Linear(32, 32), torch.nn.Tanh(),
                          torch.nn.Linear(32, 1))
log_k = torch.nn.Parameter(torch.tensor(math.log(5.0)))   # deliberately wrong guess
opt = torch.optim.Adam(list(net.parameters()) + [log_k], lr=1e-3)

t_col = torch.linspace(0, 3.0, 200).reshape(-1, 1).requires_grad_(True)
t0 = torch.zeros(1, 1, requires_grad=True)
for it in range(15000):
    u = net(t_col)
    u_t = torch.autograd.grad(u, t_col, torch.ones_like(u), create_graph=True)[0]
    u_tt = torch.autograd.grad(u_t, t_col, torch.ones_like(u_t), create_graph=True)[0]
    res = u_tt + torch.exp(log_k) * torch.sin(u)            # the pendulum equation
    u0 = net(t0)
    u0_t = torch.autograd.grad(u0, t0, torch.ones_like(u0), create_graph=True)[0]
    loss = (res**2).mean() + 10*((u0 - th0)**2 + u0_t**2).sum() + 10*((net(t_data) - y_data)**2).mean()
    opt.zero_grad(); loss.backward(); opt.step()
    if it % 3000 == 0:
        print(f"iter {it:5d}  loss {loss.item():.2e}  k = {torch.exp(log_k).item():.3f}")

print(f"learned g/L = {torch.exp(log_k).item():.3f}   (true {k_true:.3f})")
print(f"=> string length L = {9.81 / torch.exp(log_k).item():.3f} m  (true {9.81 / k_true:.3f} m)")
The same story, everywhere in SciML

Replace the pendulum by heat in a rod, flow in an oil reservoir, or a chemical reaction in a catalyst pellet, and the story is the same: a few expensive measurements, a trusted law with unknown coefficients, and a network that combines the two. When you need the answer for thousands of different starting angles or coefficients, train an operator network instead of one PINN per case.

Key takeaways

Further reading