---
title: "Lab: the phase plane in code"
heading: Classifying, linearizing and simulating two-state systems
eyebrow: A8 · Lesson 43 · Lab: the phase plane
xp: 60
---

::: hook
Lessons 40 to 42 read a two-state system's behavior from its equilibria, its Jacobians and its phase portrait. In this lab you'll automate that: a function that classifies any 2 × 2 linear system, a numerical Jacobian for any nonlinear one, a measurement of the van der Pol oscillator's limit cycle, and a search for the exact launch speed that sends a damped pendulum over the top.
:::

::: play
- The flow is a double-well system, $\ddot x = x - x^3 - c\dot x$: a ball in a landscape with two valleys at $x = \pm1$ and a hump at 0.
- Each trajectory settles into one valley or the other. Which one depends on where it starts, and the boundary between the basins runs through the saddle at the origin.
- With $c = 0$ nothing settles: trajectories circle one valley, or both, forever.
:::

```sim plot
view: flow
x: x = -2..2
y: y = -1.5..1.5
slider: c = 0..1 step 0.05 = 0.3
dx: y
dy: x - x^3 - c*y
start: 0.05, 0 | forward
start: -0.05, 0 | forward
start: 1.8, 0 | forward
start: -1.5, 1.2 | forward
grid: 16
readout: ringing frequency in a valley = sqrt(2 - c^2/4) | digits: 4
readout: escape rate from the hump = (-c + sqrt(c^2 + 4))/2 | digits: 4
```

::: predict
## How many stable equilibria does $\ddot x = x - x^3 - c\dot x$ have, for $c > 0$?

- [ ] One
- [x] Two
- [ ] Three
- [ ] None

::: reveal
Two, at $x = \pm1$. There are three equilibria, $x = -1, 0, 1$, but the Jacobian $\begin{bmatrix}0 & 1\\1 - 3x^2 & -c\end{bmatrix}$ has determinant $-1$ at the origin, a saddle, and $+2$ at $\pm1$, with negative trace: stable. A system with two stable states is bistable, the basis of every memory cell.
:::
:::

::: nameit
## Classifying in code

From the trace $T$ and determinant $D$ of a 2 × 2 matrix:
- $D < 0$: saddle;
- $D > 0$ and $T^2 < 4D$: spiral (center if $T = 0$), stable if $T < 0$;
- $D > 0$ and $T^2 \ge 4D$: node, stable if $T < 0$.

Floating-point values are rarely exactly zero, so code should treat $|T|$ below a small tolerance as zero.

## Numerical Jacobians

Each column of the Jacobian is the derivative of $\mathbf f$ along one coordinate. Central differences estimate it:

$$J_{:,k} \approx \frac{\mathbf f(\mathbf x + h\mathbf e_k) - \mathbf f(\mathbf x - h\mathbf e_k)}{2h}$$

with an error proportional to $h^2$; $h \approx 10^{-5}$ balances that against rounding. Circuit simulators linearize their device models this way when no analytic derivative is available.

## Measuring with simulation

A limit cycle's amplitude is a property of the whole orbit, not of any equilibrium, so it has to be measured: simulate past the transient, then record the largest $|x|$. A threshold, like the smallest launch speed that clears the top, is a root-finding problem whose function evaluation is a simulation; bisection on yes/no outcomes finds it reliably.
:::

::: example
## Linearize the double well $\ddot x = x - x^3 - 0.3\dot x$ at $x = 1$.

::: solution
1. **State form.** $f = y$ and $g = x - x^3 - 0.3y$.
2. **Jacobian at $x = 1$.**
   $$\begin{aligned} J &= \begin{bmatrix}0 & 1\\1 - 3x^2 & -0.3\end{bmatrix}_{x = 1} \\ &= \begin{bmatrix}0 & 1\\-2 & -0.3\end{bmatrix} \end{aligned}$$
3. **Classify.** $T = -0.3$ and $D = 2$, with $T^2 < 4D$: a stable spiral.
4. **Eigenvalues.**
   $$\begin{aligned} \lambda &= -0.15 \pm j\sqrt{2 - 0.0225} \\ &= -0.15 \pm 1.406j \end{aligned}$$
   so it rings at 1.41 rad/s and settles with time constant 6.7 s.

**Answer:** a stable spiral with eigenvalues $-0.15 \pm 1.406j$: it rings at 1.41 rad/s and settles with a 6.7 s time constant.
:::
:::

::: example
## How large does the van der Pol oscillator $\ddot x - \mu(1 - x^2)\dot x + x = 0$ swing?

::: solution
1. **Energy balance.** Its amplitude is set by an energy balance over one cycle: the $(1 - x^2)$ term adds energy while $|x| < 1$ and removes it beyond.
2. **Small $\mu$.** For small $\mu$ the balance comes out at amplitude 2 exactly.
3. **At $\mu = 1$.** Simulating with $\mu = 1$ and measuring after the start-up gives 2.009: still close to 2, although the waveform is no longer a pure sine.
4. **Large $\mu$.** At large $\mu$ it becomes a relaxation oscillation, slow ramps and fast jumps, with an amplitude near 2 still.

**Answer:** it swings to an amplitude of about 2: exactly 2 for small $\mu$, 2.009 at $\mu = 1$, and still near 2 at large $\mu$.
:::
:::

::: check
given: c = 0.5 | 1 | 1.5
answer: sqrt(2 - c^2/4)
unit: rad/s
tolerance: 0.5%

## In the double well $\ddot x = x - x^3 - \given{c}\dot x$, at what frequency do small oscillations in a valley ring?

::: right
Right. $J$ has $D = 2$ and $T = -c$, so $\omega_d = \sqrt{2 - c^2/4}$ = {answer}.
:::

::: misses
- [sqrt(2)] That's without damping; $\zeta$ lowers it slightly.
- [1] The valley's stiffness is $3x^2 - 1 = 2$, not 1.
- [any] Not yet. Linearize at $x = 1$.
:::
:::

::: check
given: c = 0.2 | 0.5 | 1
answer: (-c + sqrt(c^2 + 4))/2
unit: s⁻¹
tolerance: 0.5%

## At what rate does a small displacement grow away from the hump at $x = 0$ in $\ddot x = x - x^3 - \given{c}\dot x$?

::: right
Right. $J = \begin{bmatrix}0 & 1\\1 & -c\end{bmatrix}$ has the positive eigenvalue {answer}.
:::

::: misses
- [1] Damping slows the escape.
- [any] Not yet. The eigenvalues solve $\lambda^2 + c\lambda - 1 = 0$.
:::
:::

::: check
kind: python

## Write `classify(A)` returning one of `"saddle"`, `"center"`, `"stable spiral"`, `"unstable spiral"`, `"stable node"` or `"unstable node"` for a 2 × 2 NumPy array, treating $|T| < 10^{-12}$ as zero.

```python starter
import numpy as np

def classify(A):
    return "saddle"

print(classify(np.array([[1, 2], [3, 0]])))
```

```python solution
import numpy as np

def classify(A):
    T = np.trace(A)
    D = np.linalg.det(A)
    if D < 0:
        return "saddle"
    if abs(T) < 1e-12:
        return "center"
    kind = "spiral" if T * T < 4 * D else "node"
    return ("stable " if T < 0 else "unstable ") + kind

print(classify(np.array([[1, 2], [3, 0]])))
```

```python tests
import numpy as np
cases = {((1, 2), (3, 0)): "saddle", ((0, 1), (-4, 0)): "center", ((-1, -2), (2, -1)): "stable spiral",
         ((1, -2), (2, 1)): "unstable spiral", ((-3, 1), (1, -3)): "stable node", ((2, 0), (0, 3)): "unstable node"}
for m, want in cases.items():
    got = classify(np.array(m, dtype=float))
    assert got == want, f"{m} should be a {want}; got {got}."
```

::: right
Right. Two numbers, the trace and the determinant, sort every linear system in the plane.
:::
:::

::: check
kind: python

## Write `jacobian(f, x, h=1e-5)` by central differences, where `f` maps a NumPy array to a NumPy array. Set `J` to the Jacobian of the damped pendulum $f(\theta, \omega) = (\omega, -\sin\theta - 0.5\omega)$ at $(\pi, 0)$.

```python starter
import numpy as np

def jacobian(f, x, h=1e-5):
    return np.eye(len(x))

f = lambda s: np.array([s[1], -np.sin(s[0]) - 0.5 * s[1]])
J = jacobian(f, np.array([np.pi, 0.0]))
print(J)
```

```python solution
import numpy as np

def jacobian(f, x, h=1e-5):
    n = len(x)
    J = np.zeros((n, n))
    for k in range(n):
        e = np.zeros(n)
        e[k] = h
        J[:, k] = (f(x + e) - f(x - e)) / (2 * h)
    return J

f = lambda s: np.array([s[1], -np.sin(s[0]) - 0.5 * s[1]])
J = jacobian(f, np.array([np.pi, 0.0]))
print(J)
```

```python tests
import numpy as np
assert np.allclose(J, [[0, 1], [1, -0.5]], atol=1e-9), f"At the top the Jacobian is [[0, 1], [1, -0.5]]; got {J}."
g = lambda s: np.array([s[0] * (2 - s[1]), s[1] * (s[0] - 1)])
assert np.allclose(jacobian(g, np.array([1.0, 2.0])), [[0, -1], [2, 0]], atol=1e-8), "Predator and prey at (1, 2): [[0, -1], [2, 0]]."
```

::: right
Right. Central differences are accurate to about $h^2$, here $10^{-10}$, which is plenty for classifying.
:::
:::

::: check
kind: python

## Simulate van der Pol with $\mu$ = 1, $\ddot x = \mu(1 - x^2)\dot x - x$, from $(0.1, 0)$ with RK4 ($h$ = 0.001) to $t$ = 100. Set `amp` to the largest $|x|$ over $t > 50$.

```python starter
amp = 0.0
print(amp)
```

```python solution
def f(x, v):
    return v, (1 - x * x) * v - x

x, v, h, amp = 0.1, 0.0, 0.001, 0.0
for n in range(100000):
    k1 = f(x, v)
    k2 = f(x + h / 2 * k1[0], v + h / 2 * k1[1])
    k3 = f(x + h / 2 * k2[0], v + h / 2 * k2[1])
    k4 = f(x + h * k3[0], v + h * k3[1])
    x += h / 6 * (k1[0] + 2 * k2[0] + 2 * k3[0] + k4[0])
    v += h / 6 * (k1[1] + 2 * k2[1] + 2 * k3[1] + k4[1])
    if n * h > 50:
        amp = max(amp, abs(x))
print(amp)
```

```python tests
assert 2.0 < amp < 2.02, f"The limit cycle's amplitude at mu = 1 is about 2.009; got {amp}."
```

::: right
Right. Starting from 0.1, the oscillation grows until the energy balance holds, at an amplitude just over 2.
:::
:::

::: check
kind: python

## A pendulum with damping $c$ = 0.3, $\ddot\theta = -\sin\theta - 0.3\dot\theta$, starts at the bottom with speed $\omega_0$. Write `over(w0)` that simulates with RK4 ($h$ = 0.005) for 40 s and returns whether $\theta$ ever exceeds $\pi$. Then bisect between 1.5 and 3 (40 steps) for the smallest launch speed that goes over, and set `w_crit`.

```python starter
import math

def over(w0):
    return w0 > 2

w_crit = 2.0
print(w_crit)
```

```python solution
import math

def over(w0):
    def f(th, w):
        return w, -math.sin(th) - 0.3 * w
    th, w, h = 0.0, w0, 0.005
    for _ in range(8000):
        k1 = f(th, w)
        k2 = f(th + h / 2 * k1[0], w + h / 2 * k1[1])
        k3 = f(th + h / 2 * k2[0], w + h / 2 * k2[1])
        k4 = f(th + h * k3[0], w + h * k3[1])
        th += h / 6 * (k1[0] + 2 * k2[0] + 2 * k3[0] + k4[0])
        w += h / 6 * (k1[1] + 2 * k2[1] + 2 * k3[1] + k4[1])
        if th > math.pi:
            return True
    return False

lo, hi = 1.5, 3.0
for _ in range(40):
    mid = (lo + hi) / 2
    if over(mid):
        hi = mid
    else:
        lo = mid
w_crit = hi
print(w_crit)
```

```python tests
assert abs(w_crit - 2.633) < 0.005, f"The threshold launch speed is about 2.633 rad/s; got {w_crit}."
assert not over(2.6) and over(2.7), "2.6 rad/s falls short and 2.7 goes over."
```

::: right
Right. Without friction it would be exactly 2 rad/s (enough energy to reach the top); friction costs about 32% more.
:::
:::

::: check
kind: python

## Simulate predator and prey, $\dot x = x(2 - y)$, $\dot y = y(x - 1)$, from $(1.05, 2)$ with RK4 ($h$ = 0.001) for 30 time units. Set `period` to the time between the first two upward crossings of $x = 1$ and `linear` to the linearization's $2\pi/\sqrt2$.

```python starter
import math

period = linear = 0.0
print(period, linear)
```

```python solution
import math

def f(x, y):
    return x * (2 - y), y * (x - 1)

x, y, h, t = 1.05, 2.0, 0.001, 0.0
ups = []
for _ in range(30000):
    k1 = f(x, y)
    k2 = f(x + h / 2 * k1[0], y + h / 2 * k1[1])
    k3 = f(x + h / 2 * k2[0], y + h / 2 * k2[1])
    k4 = f(x + h * k3[0], y + h * k3[1])
    xn = x + h / 6 * (k1[0] + 2 * k2[0] + 2 * k3[0] + k4[0])
    yn = y + h / 6 * (k1[1] + 2 * k2[1] + 2 * k3[1] + k4[1])
    if x < 1 <= xn:
        ups.append(t + (1 - x) / (xn - x) * h)
    x, y, t = xn, yn, t + h
period = ups[1] - ups[0]
linear = 2 * math.pi / math.sqrt(2)
print(period, linear)
```

```python tests
import math
assert abs(linear - 2 * math.pi / math.sqrt(2)) < 1e-12, "linear should be 2 pi / sqrt(2)."
assert abs(period - linear) / linear < 0.005, f"A small cycle's period should be within 0.5% of 4.443; got {period}."
```

::: right
Right. A small cycle keeps the linear period almost exactly; larger cycles in this system take noticeably longer.
:::
:::

::: explain
## Why does a bistable system need a saddle between its two stable states?

::: model
Two stable equilibria each attract the trajectories near them, so the plane divides into two basins, and the basins must meet along a boundary. Trajectories on the boundary can't go to either stable state, so they must go somewhere else: to an equilibrium that attracts along the boundary and repels across it. That's a saddle, with its stable direction lying along the basin boundary and its unstable directions pointing into the two basins. In a latch, the saddle is the balanced point between 0 and 1, and a state that starts almost exactly on the boundary lingers near it before falling one way: metastability.
:::
:::

::: practice

::: check
given: c = 0..2
answer: sqrt(2 - c^2/4)
tolerance: 0.5%

## Valley ringing frequency of the double well with damping {c}?

::: misses
- [any] $\sqrt{2 - c^2/4}$.
:::
:::

::: check
given: c = 0..3
answer: (-c + sqrt(c^2 + 4))/2
tolerance: 0.5%

## Escape rate from the hump with damping {c}?

::: misses
- [any] $\frac{-c + \sqrt{c^2 + 4}}{2}$.
:::
:::
:::
