Post

Solving ODEs using odeint

A tutorial on solving a system of nonlinear ordinary differential equations and plotting phase portraits using Python.

Solving ODEs using odeint

Most differential equations that we meet in physics have no solution in closed form, so we have to solve them numerically, and the pendulum is a good place to learn how. Its equation is simple, and its motion shows two features of nonlinear dynamics, a period that depends on the amplitude and a separatrix between two kinds of motion. We also know exact results for it, such as the conserved energy and the period, so we can test a numerical solution against them. In this post, we write the pendulum as a system of first-order equations, sketch its phase portrait, and solve it with odeint from SciPy.

We all know the simple pendulum, a bob on a light rod of length $\ell$. It swings according to

\[\begin{align} \dfrac{d^2 x}{d t^2} + \dfrac{g}{\ell} x = 0 , \end{align}\]

where $x$ is the angle that the rod makes with the vertical. Its solutions oscillate with the period $2\pi \sqrt{\ell / g}$, whatever their amplitude, but this equation is an approximation. The component of gravity along the path of the bob is $-mg \sin x$, so Newton’s second law gives

\[\begin{align} m \ell \dfrac{d^2 x}{d t^2} = -m g \sin x , \end{align}\]

and the simple pendulum follows only for small angles, where $\sin x \approx x$. If we keep the $\sin x$ and choose units of time in which $g / \ell = 1$, the motion of a nonlinear pendulum is governed by the well-known equation [1],

\[\begin{align} \dfrac{d^2 x}{d t^2} + \sin x = 0 . \label{eq:pendulum} \end{align}\]

At larger angles, the $\sin x$ term changes the motion. The period grows with the amplitude, and a pendulum that moves fast enough swings over the top. The exact solution involves elliptic functions, so in practice we solve the equation numerically. By the end of this post, we will have drawn the phase portrait of the pendulum in Fig. 1.

Phase portrait of the nonlinear pendulum: streamlines with rotations and librations Phase portrait of the nonlinear pendulum: streamlines with rotations and librations

Fig. 1. Phase portrait of the nonlinear pendulum, Eq. $\eqref{eq:pendulum}$. The thin curves are streamlines of the vector field. The thick curves are trajectories, with arrowheads in the direction of motion. The rotations, above and below, whirl over the top, and the librations about the origin swing back and forth.

A system of first-order ODEs

Equation $\eqref{eq:pendulum}$ is an example of a second-order, nonlinear ordinary differential equation (ODE). We can now introduce the angular velocity,

\[\begin{align} y & = \dfrac{d x}{d t}, \end{align}\]

and convert the second-order ODE into a system of two first-order ODEs, viz.,

\[\begin{align} \dot{x} & = y, \\ \dot{y} & = - \sin x. \end{align}\]

Here, the dot denotes a derivative with respect to time. Numerical ODE solvers such as odeint work with systems of first-order equations, so we always rewrite a higher-order equation in this form first.

We can now introduce the state vector $\boldsymbol{S} = (x, y)$ and write our two-dimensional system as

\[\begin{align} \dfrac{d \boldsymbol{S}}{d t} = \begin{pmatrix} S_2 \\ -\sin S_1 \end{pmatrix} = \begin{pmatrix} y \\ -\sin x \end{pmatrix} , \end{align}\]

where $S_i$ is the $i$th component of $\boldsymbol{S}$.

Our task is to analyse the behaviour of this system, and we do that by

  • drawing the phase portrait of the system,
  • solving the system of ODEs numerically.

We shall use Python for both tasks, and we begin by importing suitable Python libraries,

  • numpy to perform manipulations over numeric arrays
  • scipy.integrate.odeint to numerically solve our ODEs
  • matplotlib to plot the results.

If you do not have a Python environment with these packages yet, see the guide to setting one up. For books and tutorials on scientific Python, see Python Resources.

1
2
3
import numpy as np  # arrays and vectorised maths
from scipy.integrate import odeint  # the ODE solver
import matplotlib.pyplot as plt  # plotting

The code in this post uses plain matplotlib. I drew the figures with my matplotlib stylesheet amore, in a light and a dark version to match the theme of this site. The section Final code gives the script for them. You do not need the stylesheet, since the code below makes the same plots in the default matplotlib style.

Our first task is to code up a function that returns the right-hand side (RHS) of the system.

1
2
3
def f(S, t=0):
    x, y = S  # unpack the state into the angle and the angular velocity
    return [y, -np.sin(x)]  # the RHS of the system, [x', y']

The function takes two arguments, the state S and the time t. The line x, y = S unpacks the state into its two components. Our system is autonomous, that is, its RHS does not depend on time, but we still include t, because ODE solvers expect a function of both the dependent and the independent variables. The order of the arguments matters, and odeint expects the dependent variables first. We also give t the default value 0, so that we can call f without it when we plot the vector field. The same function then serves to solve the ODEs and to plot the phase portrait.

The phase portrait

Each point $(x, y)$ of the plane gives a state of the pendulum, its angle and its angular velocity. As time runs, the state moves along a curve in this plane, called a trajectory. The vector field $\dot{\boldsymbol{S}}$ gives the direction and the speed of the motion at every point. We call this plane the phase plane, and a sketch of the vector field with a few trajectories is a phase portrait.

Our first order of business is to generate the phase portrait, which means sketching the vector field

\[\begin{align} \dot{\boldsymbol{S}} = (\dot{x}, \dot{y}) = (y, -\sin x) . \end{align}\]

To plot a vector field, we need two functions:

  • numpy.meshgrid to generate a grid of points (over the $xy$ plane) where we must calculate the value of the components of the vector field.
  • matplotlib.pyplot.streamplot to visualize a vector field by plotting the streamlines of the vector flow.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# a wide figure with one set of axes
fig, ax = plt.subplots(figsize=(40, 10))

xmin, xmax = -4.0 * np.pi, 4.0 * np.pi  # range of the angle x
ymin, ymax = -3.0, 3.0  # range of the angular velocity y

x = np.linspace(xmin, xmax, 30)  # 30 points along each axis
y = np.linspace(ymin, ymax, 30)

XX, YY = np.meshgrid(x, y)  # coordinates of every point of the grid

xdot, ydot = f([XX, YY])  # the vector field at every point of the grid

ax.streamplot(XX, YY, xdot, ydot, density=2)  # draw the streamlines

plt.show()

Streamlines of the vector field of the pendulum Streamlines of the vector field of the pendulum

Fig. 2. Streamlines of the vector field of the pendulum. The streamlines circle the centres at $x = 0$, $\pm 2\pi$ and $\pm 4\pi$, and cross at the saddles at $x = \pm \pi$ and $\pm 3\pi$.

Figure 2 shows the streamlines that the code above draws. We first set up the figure and the axes and choose the ranges of $x$ and $y$. numpy.linspace then generates 30 equally spaced points along each axis. numpy.meshgrid turns these into two 2D arrays, XX and YY, which hold the $x$ and $y$ coordinates of every point of the grid. Since f works on whole arrays, a single call, f([XX, YY]), gives the components of the vector field at all the grid points, and we store them in xdot and ydot. Finally, matplotlib.pyplot.streamplot sketches the vector field.

Figures and axes in matplotlib

plt.subplots() returns two objects. The figure, fig, is the whole canvas. It sets the size of the image, here figsize=(40, 10) in inches, and holds everything we draw. The axes, ax, is one plot inside the figure, with its own coordinates, ticks and labels. We draw on it with methods such as ax.plot and ax.streamplot. A figure can hold several axes. For example, fig, axes = plt.subplots(1, 2) gives two plots side by side. When we call the methods of fig and ax directly, instead of plt.plot, we always know which plot a command acts on.

We use meshgrid mainly to avoid slow Python loops.

How numpy.meshgrid works

numpy.meshgrid takes the points along each axis and returns the coordinates of every point of the grid they span. For three points along $x$ and two along $y$,

1
2
3
x = np.linspace(0, 2, 3)  # [0, 1, 2]
y = np.linspace(0, 1, 2)  # [0, 1]
XX, YY = np.meshgrid(x, y)

gives

1
2
XX = [[0, 1, 2],     YY = [[0, 0, 0],
      [0, 1, 2]]           [1, 1, 1]]

Each array has one row for each value of $y$ and one column for each value of $x$. The pair (XX[i, j], YY[i, j]) is one point of the grid. NumPy applies arithmetic and functions such as np.sin element by element, so f([XX, YY]) evaluates the vector field at every point of the grid in one call. Without meshgrid, we would need two nested loops over $x$ and $y$, and loops in Python run much more slowly.

Notice the line where streamplot is invoked. The basic syntax is:

ax.streamplot(x_grid, y_grid, x_vec, y_vec, density=spacing)

Here x_grid and y_grid are arrays of x, y points. The arrays x_vec and y_vec hold the stream velocity at each point of the grid, and the keyword argument density=spacing sets how close together the streamlines are drawn.

The fixed points of the system, where $\dot{\boldsymbol{S}} = 0$, lie at $y = 0$ and $\sin x = 0$, that is, at $x = n\pi$ for integer $n$. We find the type of each by linearising the equation about it. Near $x = 0$, $\sin x \approx x$ and $\ddot{x} = -x$. Here the pendulum hangs straight down and makes small oscillations about a stable equilibrium, and the streamlines circle the point. We call such a point a centre. Near $x = \pi$, we write $x = \pi + \xi$, so that $\sin x \approx -\xi$ and $\ddot{\xi} = \xi$, whose solutions grow or decay exponentially. Here the pendulum stands upright, balanced at an unstable equilibrium. The streamlines come in along one direction and leave along another, and we call such a point a saddle. Since $\sin x$ has period $2\pi$, every even multiple of $\pi$ is a centre and every odd multiple a saddle, as Fig. 2 shows.

Solving the ODEs with odeint

We shall now use odeint to numerically solve the two-dimensional system.

Since we have two differential equations, we have to provide two initial conditions. First, we shall try to simulate the case where the bob of the pendulum starts at its lowest point and we set it into motion with some initial velocity, that is,

\(x(0) = 0 , \quad y(0) = c ,\) where $c$ is a constant.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
fig, ax = plt.subplots(figsize=(40, 10))

t0, tf = 0.0, 45.0  # start and end of the time interval
# times at which odeint returns the solution
tspan = np.linspace(t0, tf, 1000)

x0 = 0.0  # every pendulum starts at the bottom

c = np.linspace(-2.05, 2.05, 10)  # initial angular velocities

for y0 in c:
    S0 = [x0, y0]  # initial state
    # one row for each time, with columns x and y
    ys = odeint(f, S0, tspan)
    # the trajectory in the phase plane
    ax.plot(ys[:, 0], ys[:, 1], 'r-')

plt.show()

Trajectories of the pendulum started at x = 0 Trajectories of the pendulum started at x = 0

Fig. 3. Trajectories started at $x = 0$ with $y = c$, for ten values of $c$ from $-2.05$ to $2.05$. The closed curves are librations. The two open curves, for $c = \pm 2.05$, are rotations, to the right for $c > 0$ and to the left for $c < 0$.

Figure 3 shows the trajectories that the code above computes. We first set up the figure and the axes, and the time interval over which we solve our ODEs. The array tspan holds 1000 equally spaced times between t0 and tf, and odeint returns the solution at these times. We then fix the first initial condition, $x(0) = 0$, and construct an array of suitable values of $c$ for the second. The loop takes one value of $c$ at a time, calls the ODE solver with the initial conditions $[0, c]$, stores the solution in ys and plots it. The first column, ys[:, 0], holds $x(t)$, and the second, ys[:, 1], holds $y(t)$.

The value $\lvert c \rvert = 2$ comes from the energy of the pendulum. Multiplying Eq. $\eqref{eq:pendulum}$ by $\dot{x}$, we find

\[\begin{align} \dot{x}\ddot{x} + \dot{x} \sin x = \dfrac{d}{dt} \left( \frac{1}{2} \dot{x}^2 - \cos x \right) = 0 , \end{align}\]

so the energy

\[\begin{align} E = \frac{1}{2} y^2 - \cos x \end{align}\]

stays constant along every trajectory. The trajectories in the phase portrait are therefore the level curves of $E$. A pendulum started at $x = 0$ with $y = c$ has ${E = c^2/2 - 1}$. It reaches the top, $x = \pm \pi$, only if $E \geq 1$, that is, if $\lvert c \rvert \geq 2$.

For $\lvert c \rvert < 2$ the bob swings back and forth, and the trajectories are closed curves around the origin. For $\lvert c \rvert > 2$ the bob has enough energy to swing over the top, and the trajectory runs off to the right if $c > 0$ and to the left if $c < 0$. The two ends of our array, $c = \pm 2.05$, belong to this second class, and we avoid $c = \pm 2$ itself, since a pendulum started there lies on the separatrix, the level curve $E = 1$, or $y = \pm 2 \cos(x/2)$. The separatrix passes through the saddles and divides the two kinds of motion, and a numerical solution cannot stay on it.

We have used odeint to solve our ODEs; the syntax is ys = odeint(model, initial_values, t), where model is the RHS of the two-dimensional system, initial_values is an array of initial conditions, and t is an array of the times at which we want the solution.

odeint returns a matrix which has $k$ columns, one for each of the $k$ variables, and a row for each time point specified in t. odeint is SciPy’s [2] interface to LSODA, a solver from the FORTRAN library ODEPACK [3] that switches automatically between methods for stiff and non-stiff equations.

How odeint works

ODEPACK is a collection of FORTRAN solvers for initial value problems, written by Alan Hindmarsh and colleagues at the Lawrence Livermore National Laboratory in the early 1980s [3]. Its solvers grew out of Gear’s work on stiff equations in the 1970s. They are still in use more than four decades later, and R’s deSolve package and GNU Octave’s lsode call them too. Linda Petzold and Hindmarsh added LSODA, the Livermore Solver for Ordinary Differential equations with Automatic method switching, to this family in 1983 [4].

LSODA uses two families of linear multistep methods. For non-stiff problems it uses the Adams–Moulton methods, of orders 1 to 12, which predict the next value from a polynomial through the previous steps and then correct it. For stiff problems it uses the backward differentiation formulas (BDF), of orders 1 to 5. These are implicit, so each step solves a nonlinear system by Newton’s method. odeint estimates the Jacobian for this by finite differences, unless we pass a function for it through the argument Dfun. In both cases, the solver changes the step size and the order as it goes, to keep the estimated error of each step within the tolerances rtol and atol.

A system is stiff when it contains time scales that differ by many orders of magnitude. An Adams method then needs steps as small as the fastest time scale to stay stable, even where the solution itself changes slowly. A BDF method can take steps set by the accuracy alone. LSODA starts with the Adams methods and estimates, as it goes, the step size that each family could take. It switches to BDF when the problem turns stiff, and back to Adams when it stops being stiff.

We can ask LSODA which method it uses. With full_output=True, odeint also returns a dictionary of diagnostics. Its entry mused gives the method in use at each output time, 1 for Adams and 2 for BDF, nqu gives the order, and tsw gives the time of the last switch between the two. For the pendulum, with the output of each line in a comment,

1
2
3
4
5
6
7
8
9
S0 = [0.0, 1.5]
ys, info = odeint(f, S0, tspan, full_output=True)

# methods in use, 1 for Adams and 2 for BDF
print(np.unique(info['mused']))  # [1]
# highest order used
print(info['nqu'].max())  # 9
# time of the last switch between methods
print(info['tsw'][-1])  # 0.0

LSODA never leaves the Adams methods and reaches order 9, as we expect for a system that is not stiff. To see why the pendulum is not stiff, we linearise it about a point $(x, y)$ of a trajectory. The Jacobian of the RHS, the matrix of its partial derivatives, is

\[\begin{align} J = \begin{pmatrix} \partial \dot{x} / \partial x & \partial \dot{x} / \partial y \\ \partial \dot{y} / \partial x & \partial \dot{y} / \partial y \end{pmatrix} = \begin{pmatrix} 0 & 1 \\ -\cos x & 0 \end{pmatrix} . \end{align}\]

Its eigenvalues solve ${\det(J - \lambda I) = \lambda^2 + \cos x = 0}$, so ${\lambda = \pm \sqrt{-\cos x}}$. Each eigenvalue sets a local time scale of the motion, $1 / \lvert \lambda \rvert$. Near the bottom, $\cos x \approx 1$ and $\lambda = \pm i$, an oscillation with the period $2\pi$. Near the top, $\cos x \approx -1$ and $\lambda = \pm 1$, a growth or decay at the rate 1. Since $\lvert \cos x \rvert \leq 1$, no eigenvalue exceeds 1 in size anywhere in the phase plane. The pendulum has no time scale much shorter than 1, so it is not stiff.

The switch is a heuristic, though. For the rotation started at $x = 5\pi$ with $y = -1$, solved at the 4001 output times of the final script, LSODA uses BDF from $t \approx 40.2$ to $41.8$ and then returns to Adams. For contrast, consider the van der Pol oscillator, $\ddot{x} - \mu (1 - x^2) \dot{x} + x = 0$, with $\mu = 1000$, a standard stiff test problem. Its solution creeps slowly for long stretches and then jumps quickly, twice in each period of about ${(3 - 2 \ln 2) \mu \approx 1614}$ [1].

1
2
3
4
5
6
7
8
9
10
def vdp(S, t, mu=1000.0):
    x, y = S
    return [y, mu * (1 - x**2) * y - x]


t = np.linspace(0.0, 3000.0, 300001)
ys, info = odeint(vdp, [2.0, 0.0], t, full_output=True)

print(np.unique(info['tsw']).round(3).tolist())  # times of the switches
# [0.005, 807.077, 807.095, 1614.276, 1614.294, 2421.476, 2421.493]

LSODA switches to BDF almost at once, at $t = 0.005$. At each jump, near $t = 807$, $1614$ and $2421$, the problem stops being stiff for a moment. LSODA then switches to Adams for about $0.02$ units of time, and back to BDF when the slow motion resumes.

odeint and solve_ivp

SciPy also provides solve_ivp, a newer function for initial value problems, and the documentation of odeint recommends it for new code. The two functions differ as follows:

  • solve_ivp expects the right-hand side as f(t, S), with the time first. odeint expects f(S, t), unless we pass tfirst=True.
  • solve_ivp takes the time interval (t0, tf), and we pass the times at which we want the solution in t_eval.
  • solve_ivp lets us choose the method, among them RK45 (the default), DOP853, Radau, BDF and LSODA. odeint always uses LSODA.
  • solve_ivp has much looser default tolerances (rtol=1e-3) than odeint (about 1.5e-8), so we pass rtol and atol to get the same accuracy.
  • solve_ivp returns an object that holds the solution in sol.y, with one row for each variable. odeint returns the transpose of this matrix.

With solve_ivp, we would compute the trajectories above as

1
2
3
4
5
6
7
8
9
10
11
from scipy.integrate import solve_ivp

sol = solve_ivp(
    lambda t, S: f(S, t),
    (t0, tf),
    S0,
    t_eval=tspan,
    rtol=1e-8,
    atol=1e-8,
)
x, y = sol.y

Putting it all together

Lastly, I will define a helper function that plots arrows along the trajectories in the phase space. Its detailed working is not important; it draws small arrowheads at regular intervals along a trajectory, each pointing in the direction of motion.

Show plotarrows
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def plotarrows(xs, ys):
    # split the trajectory into 100 groups of s points
    s = int((xs.size) / 100)
    # drop the first point of each group
    xs = xs.reshape(-1, s)[:, 1:].flatten()
    ys = ys.reshape(-1, s)[:, 1:].flatten()

    for i in range(0, xs.size, 2):  # take the remaining points in pairs
        dx = xs[i + 1] - xs[i]  # the step from one point to the next
        dy = ys[i + 1] - ys[i]
        ax.arrow(  # an arrowhead pointing along this step
            xs[i],
            ys[i],
            dx,
            dy,
            shape='full',
            lw=0,
            length_includes_head=True,
            head_width=0.06,
            color='#ee5f5b',
        )

We now sketch the vector field, solve the ODEs with the three sets of initial conditions in Table I, and plot everything in one figure, Fig. 1. Sets (a) and (b) give rotations, in which the pendulum whirls over the top, and set (c) gives librations, in which it swings back and forth.

Table I. Initial conditions of the trajectories in the phase portrait. All the trajectories run from $t = 0$ to $t = 45$.

Set $x(0)$ ${y(0) = c}$ Trajectories Motion
(a) $5\pi$ ${-2 \leq c \leq -1}$ 4 rotation to the left
(b) ${-5\pi}$ ${1 \leq c \leq 2}$ 4 rotation to the right
(c) $0$ ${-1.95 \leq c \leq 1.95}$ 10 libration

The code below repeats the steps of the previous sections and draws the phase portrait of Fig. 1.

Show the code for the full phase portrait
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
fig, ax = plt.subplots(figsize=(40, 10))

xmin, xmax = -4.0 * np.pi, 4.0 * np.pi
ymin, ymax = -3.0, 3.0

x = np.linspace(xmin, xmax, 30)
y = np.linspace(ymin, ymax, 30)

XX, YY = np.meshgrid(x, y)

xdot, ydot = f([XX, YY])

# streamlines, in blue
ax.streamplot(XX, YY, xdot, ydot, density=2, color='#52adc8')

t0, tf = 0.0, 45.0
tspan = np.linspace(t0, tf, 1000)

# rotations that start on the right and move to the left
x0 = 5.0 * np.pi
c = np.linspace(-2.0, -1.0, 4)

for y0 in c:
    S0 = [x0, y0]
    ys = odeint(f, S0, tspan)
    # the trajectory, in red
    ax.plot(ys[:, 0], ys[:, 1], color='#ee5f5b')
    plotarrows(ys[:, 0], ys[:, 1])  # arrowheads along it

# rotations that start on the left and move to the right
x0 = -5.0 * np.pi
c = np.linspace(1.0, 2.0, 4)

for y0 in c:
    S0 = [x0, y0]
    ys = odeint(f, S0, tspan)
    ax.plot(ys[:, 0], ys[:, 1], color='#ee5f5b')
    plotarrows(ys[:, 0], ys[:, 1])

x0 = 0  # librations about the bottom
c = np.linspace(-1.95, 1.95, 10)

# fewer points for the librations, which retrace closed curves
tspan = np.linspace(t0, tf, 300)

for y0 in c:
    S0 = [x0, y0]
    ys = odeint(f, S0, tspan)
    ax.plot(ys[:, 0], ys[:, 1], color='#ee5f5b')
    plotarrows(ys[:, 0], ys[:, 1])

ax.set_xlim(xmin, xmax)  # keep the window of the vector field
ax.set_ylim(ymin, ymax)

# uncomment for grid lines but no labels
# ax.set(yticklabels=[]) # hide y labels
# ax.set(xticklabels=[]) # hide x labels

plt.axis('off')  # hide the axes, ticks and labels

plt.show()

Checking energy conservation

The exact solution conserves the energy $E$, so any change in $E$ along a computed trajectory is numerical error, and $E$ gives us a direct check on the numerical solution. The code below computes $E$ along three trajectories that start at $x = 0$, and plots $\lvert E(t) - E(0) \rvert$ on a logarithmic scale.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
fig, ax = plt.subplots(figsize=(10, 4))

t0, tf = 0.0, 45.0
tspan = np.linspace(t0, tf, 1000)

x0 = 0.0

for y0 in [0.5, 1.5, 1.95]:  # three swings of increasing size
    S0 = [x0, y0]
    ys = odeint(f, S0, tspan)
    # the energy at each time
    E = 0.5 * ys[:, 1] ** 2 - np.cos(ys[:, 0])
    # its change, without t = 0
    ax.semilogy(tspan[1:], np.abs(E[1:] - E[0]), label=f'c = {y0}')

ax.set_xlabel('t')
ax.set_ylabel('|E(t) - E(0)|')
ax.legend()

plt.show()

Energy error along three trajectories of the pendulum Energy error along three trajectories of the pendulum

Fig. 4. Change in the energy, $\lvert E(t) - E(0) \rvert$, along three trajectories started at $x = 0$ with $c = 0.5$, $1.5$ and $1.95$, computed with odeint at its default tolerances.

Figure 4 shows the result, where we skip $t = 0$ because the error vanishes there and its logarithm does not exist. With the default tolerances, the error stays below $3 \times 10^{-7}$ over the whole run. The error does not die away, since LSODA keeps the error of each step small and these errors add up over many steps. For $c = 0.5$ and $c = 1.5$, the typical error grows by a factor of three to five over the run. The sharp dips mark the moments when $E(t) - E(0)$ changes sign. With rtol=1e-12 and atol=1e-12, the error falls below $2 \times 10^{-10}$. Symplectic integrators, such as the leapfrog method, keep the energy error bounded for all time, but they need a fixed step size.

Things to try

The two exercises below extend the code of this post. Try to reproduce each figure before you look at the solutions at the end of the post.

Friction

A real pendulum loses energy to friction. The simplest model adds a damping term proportional to the angular velocity,

\[\begin{align} \ddot{x} + \gamma \dot{x} + \sin x = 0 , \label{eq:damped} \end{align}\]

with $\gamma > 0$, so that the second equation of our system becomes $\dot{y} = -\sin x - \gamma y$. Multiplying by $\dot{x}$ as before, we now find $dE/dt = -\gamma y^2 \leq 0$, so friction drains the energy whenever the pendulum moves. Near the bottom, the linearised equation $\ddot{x} + \gamma \dot{x} + x = 0$ has solutions that oscillate with the frequency $\sqrt{1 - \gamma^2/4}$ inside the envelope $e^{-\gamma t / 2}$, so the centres turn into stable spirals. A pendulum that starts with enough energy to whirl over the top loses some of it on every turn. When it can no longer pass the top, one of the wells captures it, and it spirals to rest at $x = 2\pi n$.

Add the damping term to f, with $\gamma = 0.25$, and reproduce Fig. 5.

Phase portrait of the damped pendulum: trajectories spiral into the stable equilibria Phase portrait of the damped pendulum: trajectories spiral into the stable equilibria

Fig. 5. Phase portrait of the damped pendulum, Eq. $\eqref{eq:damped}$, with $\gamma = 0.25$. The trajectories spiral into the stable equilibria. Those that start by whirling over the top lose energy on every turn until a well captures them.

The period of the pendulum

The period of the linear pendulum, $2\pi$, does not depend on the amplitude. The period of the nonlinear pendulum does. A pendulum started at $x = 0$ with $y = c$ swings up to the amplitude $x_{\mathrm{max}} = 2 \arcsin(c/2)$, and the conservation of energy gives its period in closed form,

\[\begin{align} T = 4 K(k) , \quad k = \frac{c}{2} , \end{align}\]

where

\[\begin{align} K(k) = \int_0^{\pi/2} \frac{d\varphi}{\sqrt{1 - k^2 \sin^2 \varphi}} \end{align}\]

is the complete elliptic integral of the first kind. For small swings, $K \to \pi/2$ and $T \to 2\pi$. As $c \to 2$, $K$ grows like $\ln \left( 4 / \sqrt{1 - k^2} \right)$, and the period becomes infinite on the separatrix, where the pendulum takes infinitely long to creep up to the top.

Plot $x(t)$ for a small and a large value of $c$. Then measure the period from the numerical solution for many values of $c$, and compare it with $4K(c/2)$. SciPy provides $K$ as scipy.special.ellipk, which takes the parameter $m = k^2$. Reproduce Fig. 6.

The swing of the pendulum for c = 0.5 and c = 1.95, and its period against c compared with 4K(c/2) The swing of the pendulum for c = 0.5 and c = 1.95, and its period against c compared with 4K(c/2)

Fig. 6. Left: the angle $x(t)$ for $c = 0.5$ and $c = 1.95$. The larger swing has the longer period. Right: the period $T$ measured from the numerical solution (points) and the exact result $4K(c/2)$ (curve). The dashed line marks $2\pi$.

Final code

The script below draws Figs. 1–4 of this post with my matplotlib stylesheet amore, solving the same system with the same f and odeint. It takes more points along each trajectory, so that the curves come out smooth, and draws every figure twice, for the light and the dark theme of this site. The tutorial does not need any of this, and the code above makes the same plots in the default matplotlib style.

amore typesets the text with LaTeX, so the script needs a LaTeX installation. If you set USETEX = False in the script, matplotlib uses its own Computer Modern fonts instead. Without amore, the script still runs and draws the figures in the default matplotlib style, with the same colours. To run the script, use uv:

1
uv run pendulum_phase_portrait.py

The comment block at the top of the script lists the packages it needs, amore among them. On the first run, uv reads this list and installs the packages in a separate environment. The script saves the figures in a folder called figures, in the directory where you run it.

I recommend uv over pip for this. It installs Python and the packages in an environment of their own, and it is much faster than pip. You can install uv with curl -LsSf https://astral.sh/uv/install.sh | sh.

The script is also on GitHub as a gist.

Show the script, pendulum_phase_portrait.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
#!/usr/bin/env python3
#
# Author(s): Subhodeep Sarkar
# Affiliation: IIT Gandhinagar and IIIT Allahabad
# Contact: subhodeep.sarkar1@gmail.com
# Date: 2021
# Last updated: October 2026
# Github: https://github.com/subhodeeps/quasinormal-notes
#
# /// script
# requires-python = ">=3.10"
# dependencies = [
#     "numpy",
#     "scipy",
#     "matplotlib",
#     "amore @ git+https://github.com/subhodeeps/amore.mplstyle",
# ]
# ///

"""Solve the pendulum with `odeint` and plot its phase portrait.

The script writes the pendulum, x'' + sin x = 0, as the first-order
system x' = y, y' = -sin x, and solves it for several initial
conditions. It plots the vector field and the trajectories with the
amore matplotlib stylesheet and saves each figure twice, as
<name>-light.png and <name>-dark.png, for the light and dark themes of
the site. These are the figures of the post "Solving ODEs using
`odeint`".

The script has three parts: the simulation, the drawing, and the
aesthetics (colours, sizes and the axes), which the drawing uses.

The amore MPL stylesheet (https://github.com/subhodeeps/amore.mplstyle)
is optional. Without it, the figures use the default matplotlib style
with the same colours. amore typesets text with LaTeX; set USETEX =
False below if LaTeX is not installed.

Usage
-----
    uv run pendulum_phase_portrait.py [folder]

On the first run, uv reads the dependencies from the comment block at
the top of this file and installs them in a separate environment. The
script saves the figures in ./figures, or in `folder` if given.
"""

import sys
from pathlib import Path

import matplotlib

matplotlib.use("Agg")

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import FancyArrowPatch
from scipy.integrate import odeint

try:
    import amore
except ImportError:
    amore = None


# --- Simulation -------------------------------------------------------

# Window of the phase plane
XMIN, XMAX, YMIN, YMAX = -4.0 * np.pi, 4.0 * np.pi, -3.0, 3.0

# More time steps than in the post, for smooth curves
TSPAN = np.linspace(0.0, 45.0, 4001)


def f(S, t=0):
    """Return the right-hand side of the pendulum.

    Parameters
    ----------
    S : sequence
        State [x, y]. The components may be arrays, e.g. a grid.
    t : float, optional
        Time. Unused, since the system is autonomous, but required by
        `odeint`.

    Returns
    -------
    list
        The derivatives [x', y'] = [y, -sin x].
    """
    x, y = S
    return [y, -np.sin(x)]


def vector_field(n=30):
    """Evaluate the vector field on an n x n grid over the window.

    Parameters
    ----------
    n : int, optional
        Number of grid points along each axis.

    Returns
    -------
    XX, YY : ndarray
        Coordinates of the grid points.
    xdot, ydot : ndarray
        Components of the vector field at the grid points.
    """
    x = np.linspace(XMIN, XMAX, n)
    y = np.linspace(YMIN, YMAX, n)
    XX, YY = np.meshgrid(x, y)
    xdot, ydot = f([XX, YY])
    return XX, YY, xdot, ydot


def trajectory(x0, y0, tspan=TSPAN):
    """Solve the pendulum from the initial condition (x0, y0).

    Parameters
    ----------
    x0, y0 : float
        Initial angle and angular velocity.
    tspan : ndarray, optional
        Times at which the solution is returned.

    Returns
    -------
    dict
        The initial condition, under "x0" and "y0", the solution, under
        "x" and "y", and the methods and the highest order that LSODA
        used, under "methods" and "order".
    """
    S0 = [x0, y0]
    ys, info = odeint(f, S0, tspan, full_output=True)
    return dict(
        x0=x0,
        y0=y0,
        x=ys[:, 0],
        y=ys[:, 1],
        methods=set(info["mused"].tolist()),
        order=int(info["nqu"].max()),
    )


METHODS = {
    1: "Adams",
    2: "BDF",
}  # the methods of LSODA, as `odeint` numbers them


def methods_used(orbits):
    """Summarise the methods that LSODA used for a set of trajectories.

    Parameters
    ----------
    orbits : list of dict
        Trajectories, as returned by `trajectory`.

    Returns
    -------
    str
        How many trajectories used each method, and the highest order
        used.
    """
    counts = {
        name: sum(m in orbit["methods"] for orbit in orbits)
        for m, name in METHODS.items()
    }
    order = max(orbit["order"] for orbit in orbits)
    used = ", ".join(
        f"{name} for {n} of them" for name, n in counts.items() if n
    )
    return (
        f"LSODA solved {len(orbits)} trajectories, using {used}, "
        f"up to order {order}."
    )


def first_lap(x):
    """Return the index at which a libration completes one period.

    The libration starts at x = 0, and the period ends at the second
    crossing of x = 0.

    Parameters
    ----------
    x : ndarray
        Angle along the trajectory.

    Returns
    -------
    int
        Index one past the end of the first period.
    """
    crossings = np.flatnonzero(np.sign(x[1:]) != np.sign(x[:-1]))
    return crossings[1] + 2


def energy(orbit):
    """Return the energy E = y^2 / 2 - cos x along a trajectory.

    Parameters
    ----------
    orbit : dict
        Trajectory, as returned by `trajectory`.

    Returns
    -------
    ndarray
        Energy at each time of the trajectory.
    """
    return 0.5 * orbit["y"] ** 2 - np.cos(orbit["x"])


def energy_errors():
    """Return the change in energy along three trajectories.

    The trajectories start at x = 0 and use the same 1000 times and the
    default tolerances of `odeint` as the code in the post, since the
    plot shows the error of that code.

    Returns
    -------
    list of dict
        For each trajectory, the initial velocity under "y0", and the
        times and |E(t) - E(0)| under "t" and "error", without t = 0.
    """
    tspan = np.linspace(0.0, 45.0, 1000)
    errors = []
    for y0 in [0.5, 1.5, 1.95]:
        E = energy(trajectory(0.0, y0, tspan))
        errors.append(
            dict(y0=y0, t=tspan[1:], error=np.abs(E[1:] - E[0]))
        )
    return errors


def librations():
    """Return the trajectories of the second figure, started at x = 0.

    The eight with |y0| < 2 are librations. The two with y0 = +2.05 and
    -2.05 are rotations, which go over the top to the right and to the
    left.

    Returns
    -------
    list of dict
        Trajectories, as returned by `trajectory`.
    """
    x0 = 0.0
    c = np.linspace(-2.05, 2.05, 10)
    return [trajectory(x0, y0) for y0 in c]


def portrait():
    """Return the trajectories of the last figure.

    These are four rotations started from each side and ten librations
    about the origin.

    Returns
    -------
    list of dict
        Trajectories, as returned by `trajectory`.
    """
    orbits = []
    for x0, c in [
        (5.0 * np.pi, np.linspace(-2.0, -1.0, 4)),
        (-5.0 * np.pi, np.linspace(1.0, 2.0, 4)),
        (0.0, np.linspace(-1.95, 1.95, 10)),
    ]:
        orbits += [trajectory(x0, y0) for y0 in c]
    return orbits


# --- Drawing ----------------------------------------------------------


def draw_flow(ax, field, colours):
    """Draw the streamlines of the vector field.

    Parameters
    ----------
    ax : matplotlib.axes.Axes
        Axes to draw on.
    field : tuple of ndarray
        Grid and vector field, as returned by `vector_field`.
    colours : dict
        Colours of the theme, from `THEMES`.
    """
    ax.streamplot(
        *field,
        density=LOOK["flow_density"],
        color=colours["flow"],
        linewidth=LOOK["flow_width"],
        arrowsize=LOOK["flow_arrows"],
    )


def draw_arrowheads(ax, x, y, colour):
    """Draw arrowheads along a curve at even intervals.

    LOOK["head_spacing"] sets the spacing in inches on the figure, which
    keeps the arrowheads evenly spaced whatever the scales of the two
    axes.

    Parameters
    ----------
    ax : matplotlib.axes.Axes
        Axes to draw on.
    x, y : ndarray
        Points of the curve.
    colour : str
        Colour of the arrowheads.
    """
    box = ax.get_position()
    fig_w, fig_h = ax.figure.get_size_inches()
    sx = box.width * fig_w / (XMAX - XMIN)  # inches per unit of x
    sy = box.height * fig_h / (YMAX - YMIN)  # inches per unit of y
    length = np.concatenate(
        [[0], np.cumsum(np.hypot(np.diff(x) * sx, np.diff(y) * sy))]
    )
    spacing = LOOK["head_spacing"]
    for at in np.arange(spacing / 2, length[-1], spacing):
        i = np.searchsorted(length, at)
        if i + 1 < len(x) and XMIN < x[i] < XMAX and YMIN < y[i] < YMAX:
            ax.add_patch(
                FancyArrowPatch(
                    (x[i], y[i]),
                    (x[i + 1], y[i + 1]),
                    arrowstyle="-|>",
                    mutation_scale=LOOK["head_size"],
                    lw=0,
                    color=colour,
                    zorder=4,
                )
            )


def draw_orbit(ax, orbit, colours, arrows=True):
    """Draw a trajectory, with arrowheads for the direction of motion.

    A libration (x0 = 0) is a closed curve, so it gets arrowheads on its
    first period only. Librations with y0 < 0 get none, since they trace
    the same curves as those with -y0.

    Parameters
    ----------
    ax : matplotlib.axes.Axes
        Axes to draw on.
    orbit : dict
        Trajectory, as returned by `trajectory`.
    colours : dict
        Colours of the theme, from `THEMES`.
    arrows : bool, optional
        Whether to draw arrowheads.
    """
    x, y = orbit["x"], orbit["y"]
    ax.plot(
        x, y, color=colours["orbit"], lw=LOOK["orbit_width"], zorder=3
    )
    closed = orbit["x0"] == 0.0 and abs(orbit["y0"]) < 2.0
    if not arrows or (closed and orbit["y0"] < 0):
        return
    end = first_lap(x) if closed else len(x)
    draw_arrowheads(ax, x[:end], y[:end], colours["head"])


def figure_vector_field(data, colours):
    """Draw the streamlines of the vector field."""
    fig, ax = phase_plane()
    draw_flow(ax, data["field"], colours)
    return fig


def figure_librations(data, colours):
    """Draw the trajectories started at x = 0, without arrowheads."""
    fig, ax = phase_plane()
    for orbit in data["librations"]:
        draw_orbit(ax, orbit, colours, arrows=False)
    return fig


def figure_phase_portrait(data, colours):
    """Draw the streamlines with rotations and librations."""
    fig, ax = phase_plane()
    draw_flow(ax, data["field"], colours)
    for orbit in data["portrait"]:
        draw_orbit(ax, orbit, colours)
    return fig


def figure_energy(data, colours):
    """Draw the energy error on a logarithmic scale."""
    fig, ax = energy_axes()
    lines = zip(data["energy"], colours["lines"], strict=True)
    for line, colour in lines:
        label = rf"$c = {line['y0']}$"
        ax.plot(
            line["t"],
            line["error"],
            color=colour,
            lw=LOOK["orbit_width"],
            label=label,
        )
    ax.legend(loc="lower right")
    return fig


FIGURES = {
    "vector-field": figure_vector_field,
    "librations": figure_librations,
    "phase-portrait": figure_phase_portrait,
    "energy": figure_energy,
}


# --- Aesthetics -------------------------------------------------------

USETEX = True

if amore is not None:
    TEAL, RED, AMBER, SLATE = (
        amore.palette("teal"),
        amore.palette("red"),
        amore.palette("amber"),
        amore.palette("slate"),
    )
else:
    # The same colours as the amore palettes
    TEAL = dict(main="#4e9e9f")
    RED = dict(ink="#6b1d2a", main="#d2737f", light="#efc0c4")
    AMBER = dict(main="#d39b3c")
    SLATE = dict(ink="#28313d", light="#c2c9d1")

LINES = [
    TEAL["main"],
    RED["main"],
    AMBER["main"],
]  # one colour per curve of the energy plot

THEMES = {
    "light": dict(
        text=SLATE["ink"],
        flow=TEAL["main"],
        orbit=RED["main"],
        head=RED["ink"],
        lines=LINES,
    ),
    "dark": dict(
        text=SLATE["light"],
        flow=TEAL["main"],
        orbit=RED["main"],
        head=RED["light"],
        lines=LINES,
    ),
}

LOOK = dict(
    size=(8.0, 2.6),  # figure size in inches
    dpi=200,
    flow_width=0.5,  # streamlines: thin, in the background
    flow_arrows=0.6,
    flow_density=2,
    orbit_width=1.3,  # trajectories: thicker, in front
    head_size=7,
    head_spacing=1.6,  # inches between arrowheads
)


def use_theme(theme):
    """Set the style and colours for one theme of the site.

    Uses amore if it is installed and the default matplotlib style
    otherwise, with a transparent background in both cases.

    Parameters
    ----------
    theme : {"light", "dark"}
        Theme of the site.

    Returns
    -------
    dict
        Colours of the theme, from `THEMES`.
    """
    if amore is not None:
        amore.use()
    else:
        plt.style.use("default")
    colours = THEMES[theme]
    plt.rcParams.update(
        {
            "text.usetex": USETEX,
            "mathtext.fontset": "cm",  # used when USETEX is False
            "text.color": colours["text"],
            "axes.labelcolor": colours["text"],
            "axes.edgecolor": colours["text"],
            "xtick.color": colours["text"],
            "ytick.color": colours["text"],
            "axes.facecolor": "none",
            "figure.facecolor": "none",
            "savefig.transparent": True,
            "axes.grid": False,
        }
    )
    return colours


def phase_plane():
    """Create a figure with the axes of the phase plane.

    Returns
    -------
    fig : matplotlib.figure.Figure
    ax : matplotlib.axes.Axes
    """
    fig, ax = plt.subplots(figsize=LOOK["size"], layout="constrained")
    ax.set_xlim(XMIN, XMAX)
    ax.set_ylim(YMIN, YMAX)
    ax.set_xticks(
        np.pi * np.arange(-4, 5, 2),
        [r"$-4\pi$", r"$-2\pi$", r"$0$", r"$2\pi$", r"$4\pi$"],
    )
    ax.set_yticks([-2, 0, 2])
    ax.set_xlabel(r"$x$")
    ax.set_ylabel(r"$y = \dot{x}$")
    # fix the layout, so that the size of the axes is known
    fig.canvas.draw()
    return fig, ax


def energy_axes():
    """Create a figure with the logarithmic axes of the energy plot.

    Returns
    -------
    fig : matplotlib.figure.Figure
    ax : matplotlib.axes.Axes
    """
    fig, ax = plt.subplots(figsize=LOOK["size"], layout="constrained")
    ax.set_yscale("log")
    ax.set_xlim(0.0, 45.0)
    ax.set_xlabel(r"$t$")
    ax.set_ylabel(r"$|E(t) - E(0)|$")
    return fig, ax


def main(out=Path("figures")):
    """Solve the system, then save every figure in both themes.

    Parameters
    ----------
    out : pathlib.Path, optional
        Folder for the figures.
    """
    data = dict(
        field=vector_field(),
        librations=librations(),
        portrait=portrait(),
        energy=energy_errors(),
    )
    orbits = data["librations"] + data["portrait"]
    print(methods_used(orbits))
    out.mkdir(parents=True, exist_ok=True)
    for theme in THEMES:
        colours = use_theme(theme)
        for name, draw in FIGURES.items():
            fig = draw(data, colours)
            path = out / f"{name}-{theme}.png"
            fig.savefig(path, dpi=LOOK["dpi"])
            plt.close(fig)
            print(path)


if __name__ == "__main__":
    main(Path(sys.argv[1]) if len(sys.argv) > 1 else Path("figures"))

Further reading

Dynamical systems

The books below run roughly from introductory to advanced.

  • S. H. Strogatz, Nonlinear Dynamics and Chaos, 2nd ed. (Westview Press, Boulder, CO, 2015). Secs. 6.3 and 6.5 cover fixed points, linearisation and conservative systems. Sec. 6.7 treats the pendulum, with and without damping, along the same lines as this post, and Sec. 7.5 treats the relaxation oscillations of the van der Pol oscillator.
  • R. C. Hilborn, Chaos and Nonlinear Dynamics: An Introduction for Scientists and Engineers, 2nd ed. (Oxford University Press, Oxford, 2000). Chapter 3 treats dynamics in a state space of one and two dimensions, the setting of this post, and Chapter 8 treats Hamiltonian systems. The other chapters go on to iterated maps, quasi-periodicity and the measures that quantify chaos.
  • D. D. Nolte, Introduction to Modern Dynamics: Chaos, Networks, Space, and Time, 2nd ed. (Oxford University Press, Oxford, 2019). Nolte builds dynamics on the geometry of phase space. Chapter 3 treats Hamiltonian dynamics and phase space, Chapter 4 nonlinear dynamics and chaos, and Chapter 5 Hamiltonian chaos. Later chapters apply the same ideas to synchronization, networks and relativity.
  • E. Ott, Chaos in Dynamical Systems, 2nd ed. (Cambridge University Press, Cambridge, 2002). Ott writes for physicists and goes further than Strogatz. Chapter 3 treats strange attractors and fractal dimension, and Chapter 7 treats chaos in Hamiltonian systems, the class to which the pendulum without friction belongs.
  • M. Brin and G. Stuck, Introduction to Dynamical Systems (Cambridge University Press, Cambridge, 2002). Brin and Stuck write for mathematicians and prove what they state. The book covers topological and symbolic dynamics, ergodic theory and hyperbolic dynamics, the theory behind the chaos in the books above.

Classical mechanics

The books below run roughly from introductory to advanced.

  • D. Morin, Introduction to Classical Mechanics: With Problems and Solutions (Cambridge University Press, 2008). Sec. 5.1 uses the conservation of energy to treat motion in one dimension, the method behind the energy and the period of the pendulum in this post, and Sec. 5.2 treats small oscillations about an equilibrium. Secs. 4.3 and 4.4 treat damped and driven oscillators.
  • S. T. Thornton and J. B. Marion, Classical Dynamics of Particles and Systems, 5th ed. (Brooks/Cole, 2004). Chapter 4, on nonlinear oscillations and chaos, discusses the plane pendulum and its phase diagram at an introductory level.
  • T. W. B. Kibble and F. H. Berkshire, Classical Mechanics, 5th ed. (Imperial College Press, 2004). The book takes a geometric view of dynamics. Secs. 13.1 and 13.3 introduce phase space and the phase plane, Sec. 13.5 treats limit cycles, and Chapter 14 goes on to order and chaos in Hamiltonian systems.
  • W. Greiner, Classical Mechanics: Systems of Particles and Hamiltonian Dynamics, 2nd ed. (Springer, 2010). Its chapters on dynamical systems and on bifurcations, in the part on nonlinear dynamics, take the ideas of this post to general flows in phase space.
  • H. Goldstein, C. Poole, and J. Safko, Classical Mechanics, 3rd ed. (Addison-Wesley, 2002). Chapter 11, on classical chaos, goes from periodic motion and the Kolmogorov–Arnold–Moser theorem (Secs. 11.1 and 11.2) to attractors and Liapunov exponents (Secs. 11.3 and 11.4).
  • J. V. José and E. J. Saletan, Classical Dynamics: A Contemporary Approach (Cambridge University Press, 1998). Chapter 7 treats nonlinear dynamics, and its Sec. 7.1, on nonlinear oscillators, includes the van der Pol oscillator.
  • L. D. Landau and E. M. Lifshitz, Mechanics, 3rd ed. (Pergamon, Oxford, 1976). Sec. 11 integrates motion in one dimension with the conservation of energy, and its first problem derives the period of the pendulum in terms of the elliptic integral $K$.
  • K. S. Thorne and R. D. Blandford, Modern Classical Physics: Optics, Fluids, Plasmas, Elasticity, Relativity, and Statistical Physics (Princeton University Press, 2017). Sec. 15.6 follows the route from regular flow to chaos in fluids, through Feigenbaum’s period-doubling sequence, and Sec. 15.6.4 discusses the extreme sensitivity to initial conditions. These sections show where the ideas of this post lead in continuum physics.

Numerical methods

References

Show the references
  1. [1]S.H. Strogatz, Nonlinear Dynamics and Chaos: With Applications to Physics, Biology, Chemistry, and Engineering, Westview Press, Boulder, CO, 2nd ed. (2015).S.H. Strogatz, Nonlinear Dynamics and Chaos: With Applications to Physics, Biology, Chemistry, and Engineering, Westview Press, 2015.
  2. [2]P. Virtanen et al., SciPy 1.0–Fundamental Algorithms for Scientific Computing in Python, Nature Meth. 17 (2020) 261 [1907.10121].P. Virtanen et al., SciPy 1.0–Fundamental Algorithms for Scientific Computing in Python, Nature Meth. 17 (2020) 261 [1907.10121].
  3. [3]A.C. Hindmarsh, ODEPACK, a systematized collection of ODE solvers, in Scientific Computing, R.S. Stepleman et al., eds., (Amsterdam), pp. 55–64, North-Holland (1983).A.C. Hindmarsh, ODEPACK, a systematized collection of ODE solvers, in Scientific Computing (1983).
  4. [4]L. Petzold, Automatic selection of methods for solving stiff and nonstiff systems of ordinary differential equations, SIAM J. Sci. Stat. Comput. 4 (1983) 136.L. Petzold, Automatic selection of methods for solving stiff and nonstiff systems of ordinary differential equations, SIAM J. Sci. Stat. Comput. 4 (1983) 136.

Solutions

Show the solutions

The solution to each exercise is a script like pendulum_phase_portrait.py in Final code, and you run it with uv run in the same way.

This post is licensed under CC BY 4.0 by the author.