---
title: "Project: an oscillator in Python"
heading: Simulate an oscillator and measure what it does
eyebrow: A8 · Lesson 53 · Project
xp: 80
---

::: hook
Lesson 42 claimed that the van der Pol oscillator settles at an amplitude of about 2, whatever it starts from, and that its period stretches as the nonlinearity grows. In this project you'll check those claims the way an engineer checks a circuit design: simulate it, then measure the result. You'll write an RK4 integrator for a system of equations, run the oscillator from a tiny starting kick, and write code that measures the settled amplitude and period from the simulated waveform, the same measurements a scope would make.
:::

::: predict
## Starting the van der Pol oscillator with $\mu = 1$ from $x = 0.1$, what amplitude do you expect it to settle at?

- [ ] 0.1, where it started
- [x] About 2
- [ ] About 1
- [ ] It keeps growing

::: reveal
About 2. The tiny start grows, because the origin is an unstable spiral, until it reaches the limit cycle. For small $\mu$ the amplitude is very close to 2; at $\mu = 1$ it's slightly above, which your measurement should show.
:::
:::

::: nameit
## RK4 for systems

Write the system as $\dot{\mathbf{x}} = \mathbf{f}(t, \mathbf{x})$ with $\mathbf{x}$ a NumPy array. One RK4 step of size $h$:

$$\mathbf{k}_1 = \mathbf{f}(t, \mathbf{x}) \quad \mathbf{k}_2 = \mathbf{f}(t + \tfrac{h}{2}, \mathbf{x} + \tfrac{h}{2}\mathbf{k}_1) \quad \mathbf{k}_3 = \mathbf{f}(t + \tfrac{h}{2}, \mathbf{x} + \tfrac{h}{2}\mathbf{k}_2) \quad \mathbf{k}_4 = \mathbf{f}(t + h, \mathbf{x} + h\mathbf{k}_3)$$

$$\mathbf{x}_\text{new} = \mathbf{x} + \frac{h}{6}(\mathbf{k}_1 + 2\mathbf{k}_2 + 2\mathbf{k}_3 + \mathbf{k}_4)$$

It's exactly the scalar method from lesson 45, with arrays in place of numbers.

## The oscillator

With $x$ and $y = \dot x$:

$$\dot x = y \qquad \dot y = \mu(1 - x^2)y - x$$

## Measuring from a waveform

To measure a settled oscillation, ignore the start-up (use only the second half of the run), then:

- **amplitude:** the largest $|x|$;
- **period:** the average spacing of upward zero crossings, each located between two samples by linear interpolation: if $x_i < 0 \le x_{i+1}$, the crossing is at $t_i + h\frac{-x_i}{x_{i+1} - x_i}$.

Interpolating matters: without it, the period is only known to the nearest step.
:::

::: example
## What step size is reasonable for $\mu = 1$?

::: solution
1. **Steps per cycle.** The period is about 6.7 time units, so $h = 0.02$ gives over 300 steps per cycle.
2. **Accuracy.** RK4's error goes as $h^4$, so with that many steps per cycle the waveform is accurate to far better than the 0.01 the measurements need.
3. **Cost.** Simulating 100 time units takes 5000 steps, about 15 cycles.

**Answer:** $h = 0.02$ is reasonable: over 300 steps per cycle, and 5000 steps for 100 time units.
:::
:::

::: example
## What should the measurements show as $\mu$ grows?

::: solution
1. **Simulate carefully.** Careful simulation gives:

| $\mu$ | Amplitude | Period |
|---|---|---|
| 0.1 | 2.000 | 6.287 (close to $2\pi$) |
| 1 | 2.009 | 6.663 |
| 3 | 2.023 | 8.86 |

2. **The amplitude.** The amplitude barely changes.
3. **The period.** The period grows as the waveform turns into slow climbs and fast jumps.

**Answer:** the amplitude stays near 2 while the period grows, from 6.287 at $\mu = 0.1$ to 8.86 at $\mu = 3$.
:::
:::

::: check
kind: python

## Step 1. Write `rk4_step(f, t, x, h)` for a NumPy state `x`, returning the new state.

```python starter
import numpy as np

def rk4_step(f, t, x, h):
    # k1 ... k4, then the weighted average
    return x

f = lambda t, x: np.array([x[1], -x[0]])
print(rk4_step(f, 0.0, np.array([1.0, 0.0]), 0.1))
```

```python solution
import numpy as np

def rk4_step(f, t, x, h):
    k1 = f(t, x)
    k2 = f(t + h / 2, x + h / 2 * k1)
    k3 = f(t + h / 2, x + h / 2 * k2)
    k4 = f(t + h, x + h * k3)
    return x + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)

f = lambda t, x: np.array([x[1], -x[0]])
print(rk4_step(f, 0.0, np.array([1.0, 0.0]), 0.1))
```

```python tests
import numpy as np
f = lambda t, x: np.array([x[1], -x[0]])
x = np.array([1.0, 0.0])
for i in range(63):
    x = rk4_step(f, i * 0.1, x, 0.1)
assert np.allclose(x, [np.cos(6.3), -np.sin(6.3)], atol=1e-5), "Integrating x'' = -x for 6.3 time units should give (cos 6.3, -sin 6.3) closely."
g = lambda t, x: np.array([t])
assert np.isclose(rk4_step(g, 1.0, np.array([0.0]), 0.5)[0], 0.625), "RK4 must pass t + h/2 and t + h to f: ∫ t dt from 1 to 1.5 is 0.625."
```

::: right
Right. RK4 on an oscillator keeps the amplitude to about $10^{-6}$ over a full cycle with $h = 0.1$, where Euler would have spiraled visibly.
:::
:::

::: check
kind: python

## Step 2. Write `simulate(mu, x0, h, n)` returning an `(n + 1) × 2` array of states for the van der Pol oscillator, starting at `x0`. `rk4_step` is included.

```python starter
import numpy as np

def rk4_step(f, t, x, h):
    k1 = f(t, x)
    k2 = f(t + h / 2, x + h / 2 * k1)
    k3 = f(t + h / 2, x + h / 2 * k2)
    k4 = f(t + h, x + h * k3)
    return x + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)

def simulate(mu, x0, h, n):
    xs = np.zeros((n + 1, 2))
    # define f for van der Pol, then step n times
    return xs

xs = simulate(1.0, np.array([0.1, 0.0]), 0.02, 5000)
print(xs[-1])
```

```python solution
import numpy as np

def rk4_step(f, t, x, h):
    k1 = f(t, x)
    k2 = f(t + h / 2, x + h / 2 * k1)
    k3 = f(t + h / 2, x + h / 2 * k2)
    k4 = f(t + h, x + h * k3)
    return x + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)

def simulate(mu, x0, h, n):
    f = lambda t, x: np.array([x[1], mu * (1 - x[0] ** 2) * x[1] - x[0]])
    xs = np.zeros((n + 1, 2))
    xs[0] = x0
    for i in range(n):
        xs[i + 1] = rk4_step(f, i * h, xs[i], h)
    return xs

xs = simulate(1.0, np.array([0.1, 0.0]), 0.02, 5000)
print(xs[-1])
```

```python tests
import numpy as np
xs = simulate(1.0, np.array([0.1, 0.0]), 0.02, 5000)
assert xs.shape == (5001, 2), "Return n + 1 states, including the start."
assert np.allclose(xs[0], [0.1, 0.0]), "The first row should be the starting state."
assert 1.95 < np.max(np.abs(xs[2500:, 0])) < 2.05, "After start-up the swing should be close to 2."
lin = simulate(0.0, np.array([1.0, 0.0]), 0.01, 628)
assert np.isclose(lin[-1, 0], np.cos(6.28), atol=1e-6), "With mu = 0 it's a plain oscillator: x = cos t."
```

::: right
Right. From a kick of 0.1 the oscillation grows for a few cycles and then locks onto the limit cycle.
:::
:::

::: check
kind: python

## Step 3. Write `measure(xs, h)` returning `(amplitude, period)` from the second half of a run: the largest $|x|$, and the mean spacing of upward zero crossings found by linear interpolation. `simulate` is included.

```python starter
import numpy as np

def rk4_step(f, t, x, h):
    k1 = f(t, x)
    k2 = f(t + h / 2, x + h / 2 * k1)
    k3 = f(t + h / 2, x + h / 2 * k2)
    k4 = f(t + h, x + h * k3)
    return x + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)

def simulate(mu, x0, h, n):
    f = lambda t, x: np.array([x[1], mu * (1 - x[0] ** 2) * x[1] - x[0]])
    xs = np.zeros((n + 1, 2))
    xs[0] = x0
    for i in range(n):
        xs[i + 1] = rk4_step(f, i * h, xs[i], h)
    return xs

def measure(xs, h):
    return 0.0, 0.0

print(measure(simulate(1.0, np.array([0.1, 0.0]), 0.02, 5000), 0.02))
```

```python solution
import numpy as np

def rk4_step(f, t, x, h):
    k1 = f(t, x)
    k2 = f(t + h / 2, x + h / 2 * k1)
    k3 = f(t + h / 2, x + h / 2 * k2)
    k4 = f(t + h, x + h * k3)
    return x + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)

def simulate(mu, x0, h, n):
    f = lambda t, x: np.array([x[1], mu * (1 - x[0] ** 2) * x[1] - x[0]])
    xs = np.zeros((n + 1, 2))
    xs[0] = x0
    for i in range(n):
        xs[i + 1] = rk4_step(f, i * h, xs[i], h)
    return xs

def measure(xs, h):
    x = xs[:, 0]
    half = len(x) // 2
    amp = np.max(np.abs(x[half:]))
    crossings = []
    for i in range(half, len(x) - 1):
        if x[i] < 0 <= x[i + 1]:
            crossings.append((i + (-x[i]) / (x[i + 1] - x[i])) * h)
    return amp, float(np.mean(np.diff(crossings)))

print(measure(simulate(1.0, np.array([0.1, 0.0]), 0.02, 5000), 0.02))
```

```python tests
import numpy as np
amp, period = measure(simulate(1.0, np.array([0.1, 0.0]), 0.02, 5000), 0.02)
assert abs(amp - 2.0086) < 0.01, f"For mu = 1 the amplitude should be about 2.009; got {amp:.4f}."
assert abs(period - 6.6633) < 0.01, f"For mu = 1 the period should be about 6.663; got {period:.4f}. Did you interpolate the crossings?"
t = np.arange(0, 50, 0.1)
fake = np.column_stack([1.5 * np.sin(2 * np.pi * t / 3.7), np.zeros_like(t)])
a2, p2 = measure(fake, 0.1)
assert abs(a2 - 1.5) < 0.01 and abs(p2 - 3.7) < 0.005, "On a pure sine of amplitude 1.5 and period 3.7 the measurements should match."
```

::: right
Right. The measured amplitude, 2.009, sits just above the small-$\mu$ value of 2, and the period, 6.663, is 6% longer than $2\pi$.
:::
:::

::: check
given: mu = 0.01 | 0.02 | 0.05 | 0.1 | 0.2
answer: 2*pi
tolerance: 1%

## Step 4. Use your code (or the lesson's table) to find the period for small $\mu$ = {mu}. What value does it approach as $\mu \to 0$?

::: right
Right. $2\pi$ = {answer}: for small $\mu$ the oscillator is nearly the linear one, $\ddot x + x = 0$, with only enough nonlinearity to fix the amplitude.
:::

::: misses
- [2] That's the amplitude.
- [1] That's the angular frequency in rad per time unit; the period is $2\pi$ over it.
- [any] Not yet. What is the period of $\ddot x + x = 0$?
:::
:::

::: explain
## Why does the measurement use only the second half of the simulation?

::: model
The simulation starts from a tiny kick far inside the limit cycle, and for the first few cycles the oscillation is still growing toward it. Measuring the amplitude or period during that start-up would mix in the transient. By the second half of a long run, the trajectory has converged onto the limit cycle, so the waveform repeats and the measurements describe the settled oscillation. A real bench measurement does the same thing by waiting for the circuit to settle before reading the scope.
:::
:::

::: practice

::: check
given: mu = 0.5 | 1 | 1.5 | 2 | 3 | 5
answer: mu/2
tolerance: 0.5%

## For the van der Pol oscillator with $\mu$ = {mu}, what is the growth rate at the origin that starts the oscillation?

::: misses
- [mu] Half the trace of the Jacobian.
- [any] $\mu/2$.
:::
:::

::: check
given: T = 6.663 | 8.859; h = 0.02 | 0.01
answer: T/h
tolerance: 0.5%

## A period of {T} time units is simulated with step {h}. How many steps per cycle is that?

::: misses
- [any] $T/h$.
:::
:::

::: check
given: x1 = -0.3 | -0.05; x2 = 0.1 | 0.2; h = 0.02 | 0.1
answer: h*(-x1)/(x2 - x1)
tolerance: 0.5%

## A waveform is {x1} at one sample and {x2} at the next, {h} apart. By linear interpolation, how far after the first sample does it cross zero?

::: misses
- [h/2] Interpolate in proportion to the values, not halfway.
- [any] $h\frac{-x_1}{x_2 - x_1}$.
:::
:::
:::
